Google Analytics API reporting value other than real - google-analytics

I was doing a test here, I do not know if I used the wrong method, I do not think so, but the ga:timeOnPage reported by the Google Analytics API is different from the one reported on Google's own panel.
There it shows a mean time of 00:01:35, while the one reported by the API is 160588.0. I converted the value obtained from seconds (it's in the documentation) to minutes and got a result totally out of the reality.
...
query({
'ids': 'ga:<?php echo $items[0]->id; ?>',
'dimensions': 'ga:date,ga:nthDay',
'metrics': 'ga:pageviews,ga:uniquePageviews,ga:timeOnPage',
'start-date': '<?php echo $data_ini; ?>',
'end-date': '<?php echo $data_fim; ?>'
})
...
document.getElementById('total-grafico-3').innerHTML = results[0].totalsForAllResults["ga:timeOnPage"];

ga:timeOnPage - total time on page for chosen period.
You need to use other dimension - ga:avgTimeOnPage.
https://developers.google.com/analytics/devguides/reporting/core/dimsmets

Related

Can I use "dataLayer" code to capture "purchase" events from backend of website when batch processing orders / membership fees?

Is it possible to use dataLayer code on my website to capture monthly membership plan fees? My website processes this automatically and charges my customers credit card, so would I be able to have my developer add this code so when each customer's credit card is charged this dataLayer will execute?
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: "purchase",
ecommerce: {
transaction_id: "{invoice_id}",
value: {billable_amount},
currency: "USD",
items: [
{
item_id: "{invoice_id}",
item_name: "Membership Plan Fee",
price: {billable_amount}
}]
}
});
</script>
Would this also work if I batch process orders on the backend of my website, where a similar dataLayer would fire for each order that is processed?
Would I need to add GTM tracking code to the admin/backend of my website for this to work?
Thank you!
I ended up finding what I need to use to accomplish this; I guess Google calls it Measurement Protocols for sending events server-to-server.
Measurement Protocols - Sending Events Server to Server

Google Analytics User-ID report Dimensions and Metrics

I need to populate my database with the User-ID report data for each user (The report I am referring to can be found in Google Analytics > Reports > User Explorer (> click on the user id)).
I am looking at the documentation, but cannot seem to find any dimensions or metrics that I can use to accomplish this: https://ga-dev-tools.appspot.com/dimensions-metrics-explorer/?authuser=1
I wish I had some code examples, however the alternative method would be to run this script (with all the other functions that I will not include in here for simplicity):
def get_user_Activity(analytics, VIEW_ID, user_id, start_date, end_date):
# Use the Analytics Service Object to query the Analytics Reporting API V4.
return analytics.userActivity().search(
body={
"viewId": VIEW_ID,
"user": {
"type": "USER_ID",
"userId": user_id
},
"dateRange": {
"startDate": start_date,
"endDate": end_date
},
"activityTypes": [
"PAGEVIEW", "EVENT"
]
}
).execute()
Which will yield this dictionary for each user-id:
{'sessions': [{'sessionId': '1579xxxx',
'deviceCategory': 'desktop',
'platform': 'Windows',
'dataSource': 'web',
'activiti es': [{'activityTime': '2020-01-22T12:48:20.971410Z',
source': '(direct)',
'medium': '(none)',
'channelGrouping': 'Direct',
'campaign': '(not set)',
'keyword': '(not set)',
'hostname': 'example.com',
'landingPagePath': '/somelandingpage',
'activityType': 'PAGEVIEW',
'customDimension': [{'index': 1}],
'pageview': {'pagePath': '/some/page', 'pageTitle': 'SOME Title'}},
{'activityTime': '2020-01-22T12:48:20.970754Z',
'source': '(direct)',
'medium': '(none)',
'channelGrouping': 'Direct',
'campaign': '(not set)',
'keyword': '(not set)',
'hostname': 'example.com',
'landingPagePath': '/somelandingpage',
'activityType': 'PAGEVIEW',
'customDimension': [{'index': 1}],
'pageview': {'pagePath': '/some/other/path', 'pageTitle': 'SomeTitle'}},...
..................
etc ..............
The trouble of this method is that I would have to go calculate most of the metrics that I am interested in, instead, I would prefer to merely collect the metrics and populate the DB.
If the needed "ga:dimension(s)" and "ga:metric(s)" could please be provided, it would be highly appreciated.
There's no built-in support for userId-level reporting in Google Core Reporting API, so you'll have to calculate all the necessary metrics on your side based on what's available in the Activity API responses.
The only alternative is having a user-level custom dimension with the same value as user ID. However, this only works if you have this tracking implemented in advance.

Wordpress REST RESPONSE API Float value is Big

I am working wordpress rest endpoint, returning float value when it's showing response it is taking maximum decimal values. before sending it i rounded but it's not working.
ini_set( 'precision', '6' );
echo floatval($data['float_value']);
if i echo the value that is giving 45.45.but in my rest response,
"float_value": 45.4500000000000028421709430404007434844970703125,
"created_at": "2020-06-18T11:58:06",
"updated_at": "2020-06-19T10:50:46"
Maybe ini_set is overriden somewhere in middle of script.
you can do like this
$new_num=number_format((float)$num, 2);

Google Analytics - Access api without login

I had successfully configured google analytics api and get successful data.
I want to access analytics api without gmail login.
i.e. I will hard code credentials to for login, but how to do it with PHP?
Is there any api function to achive this task (for PHP)
Thanks!
The Hello Analytics API: PHP Quickstart Guide for Service Accounts will walk you through the steps necessary to create and add a service account to your existing Google Analytics Account/Property/View.
Once you download have the php client libs and the p12 file downloaded from developer console you can create an authorized analytics service object as follows:
// Creates and returns the Analytics service object.
// Load the Google API PHP Client Library.
require_once 'google-api-php-client/src/Google/autoload.php';
// Use the developers console and replace the values with your
// service account email, and relative location of your key file.
$service_account_email = '<Replace with your service account email address.>';
$key_file_location = '<Replace with /path/to/generated/client_secrets.p12>';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("HelloAnalytics");
$analytics = new Google_Service_Analytics($client);
// Read the generated client_secrets.p12 key.
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_email,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
return $analytics;
With the returned service object you can now make calls to the Google Analytics APIs:
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
$analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
The Google Analytics API is not fit for what you want for several reasons.
Security. If the end user has your credentials he can log into your google account and have access to all your data.
Latency. The API is not intended to be used on page load. If your page loads depend on it it may take a long time to load for your users.
Quota. The API has a limited quota that will extinguish fast if you query it every time a user enters your website.
Design. Ultimately, the API was designed to be used by yourself extracting data offline not in real time by others.
With these things in mind if you want to show your users the data you should build some kind of system that downloads the right data you want to show offline, store it in a database and display on the page. This way you can query the data once and show multiple times and not expose your credentials.
Google even published an AppEngine Application that does just that. It queries data and store in a database so it can be viewed by any unathenticated users and with minimum latency since at the view time it's just retrieved from the datastore. It's called Google Analytics superProxy.
UPDATE 09/02
When doing the request on your application you still need to complete oAuth and as you want it to be automated you want to avoid the login screen. There are 2 options
Use oAuth for Installed Apps. Manually complete the login screen and store refresh tokens. Daily you can use the refresh token to get an access token and query data with no manual intervention.
Use Service Accounts. These don't require manually approving the login screen but you need to grant access to the service account email in your Google Analytics Account. Service Accounts use crypto to authenticate so you might need a crypto module for php in order to use this.
Use Service Account:
https://developers.google.com/api-client-library/php/auth/service-accounts
https://developers.google.com/analytics/solutions/articles/hello-analytics-api#authorize_access
It needs google-api-php-client library, you can create a service account in your google developer console, then add the email if this account into your Google analytics profile 'User Management' for the profile that your want to access.
The follow the code in the links above, you should be able to access your Google analytics data without Goolge login (because your already provide serive account email and p12 key for authorization)
Hi Kiran,
Service Account
Using server side authorization with the Google Python Client API you can use this demo to get access in google analytics data and charts for every user without login.
oAuth for Google APP
The other way is to use oAuth. But in this case you need a payable Google Apps for work Account Google Apps You can read here how to combine Apps and oAuth for access without login.
I have added here the working code for the new (2016) Google Client PHP API Beta for anonymous access using json - including an amChart.
Additionally the renewing process for the json credential files can be automated - this is not done in this code example.
A ClientLogin token can last for 2 weeks from the issue date, but this limit is service-specific and can be shorter. You can change lifetime in Google_AssertionCredentials.php(24) though this is a security risk (for your money - if someone calls the site automatically you run out of the allowed duty free volume)
class Google_AssertionCredentials {
const MAX_TOKEN_LIFETIME_SECS = 360000;
To make the autoload.php work correctly, you have to install the Client PHP API ressources by composer.phar into htdocs(Apache) or wwwroot(IIS) and place this code in the folder "vendor".
I did not use dataLoader and commented it out, for amChart stucks in my environment on load. Therefore I used the dataprovider, which works reliable.
/*
"dataLoader": {
"url": "data.php",
"format": "json"
},
*/
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<title>Gimba - Google Analytics - GimbaChartAll</title>
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"></script>
<style>
body, html {
font-family: Verdana;
font-size: 10px;
}
#chartdiv {
width: 1100px;
height: 700px;
margin-left:auto;
margin-right:auto;
}
</style>
<script>
var dataJS = <?php echo dataGA(); ?>;
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
/*
"dataLoader": {
"url": "data.php",
"format": "json"
},
*/
"dataProvider": dataJS ,
"categoryField": "country",
"categoryAxis": {
"gridColor": "#0000FF",
"gridAlpha": 0.07,
"title": "Country"
},
"creditsPosition": "top-right",
"categoryField": "country",
"categoryAxis": {
"gridAlpha": 0.07,
"gridPosition": "start",
"tickPosition": "start",
"title": "Country"
},
"valueAxes": [ {
"id": "v1",
"gridAlpha": 0.1,
"axisColor": "#0000ff",
"title": "Users/Sessions"
}, {
"id": "v2",
"gridAlpha": 0,
"axisColor": "#0000ff",
"position": "right",
"title": "Page views"
} ],
"graphs": [ {
"startDuration": 3,
"type": "column",
"title": "Sessions",
"valueField": "sessions",
"fillColors": "#0000ff" ,
"lineAlpha": 0,
"fillAlphas": 0.6
}, {
"type": "column",
"title": "Users",
"valueField": "users",
"fillColors": "#0000ff" ,
"lineAlpha": 0,
"fillAlphas": 0.2
}, {
"type": "line",
"valueAxis": "v2",
"title": "Page views",
"valueField": "pageviews",
"lineColor": "#0000ff" ,
"lineThickness": 1,
"bullet": "round"
} ],
"legend": {}
} );
</script>
</head>
<body>
<div id="chartdiv"></div>
</body>
</html>
<?php
//dataGA();
function dataGA()
{
require_once 'autoload.php';
$google_account = array(
'email' => 'xxxxxxxxxxxxxxxxxxxxxx#xxxxxxxxxxxxxxxx.iam.gserviceaccount.com',
'key' => file_get_contents(__DIR__ . '/OAuthClientServiceAccount1.json'),
'profile' => 'xxxxxxxxx'
);
// Creates and returns the Analytics service object.
// Load the Google API PHP Client Library.
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName( 'Gimba3' );
$analytics = new Google_Service_Analytics($client);
$scopes = array('https://www.googleapis.com/auth/analytics.readonly');
$client->setScopes($scopes);
try{
$client->setAuthConfigFile(__DIR__ . '/OAuthClientServiceAccount1.json');
}
catch(Exception $e){
echo "Key NOT OK<br>";
echo $e->getMessage()."<br>";
}
try{
if( $client->isAccessTokenExpired() ) {
$client->refreshTokenWithAssertion($client->setAuthConfigFile(__DIR__ . '/OAuthClientServiceAccount2.json'));
}
}
catch(Exception $e){
echo "RefreshKey NOT OK<br>";
echo $e->getMessage()."<br>";
}
$projectId = '123464155';
$results = $analytics->data_ga->get(
'ga:'.$projectId,
'30daysAgo',
'today',
'ga:sessions,ga:users,ga:pageviews',
array(
'dimensions' => 'ga:country',
'sort' => '-ga:sessions',
'max-results' => 10
));
$rows = $results->getRows();
//var_dump($rows);
$dataGA = array();
foreach( $rows as $row ) {
$dataGA[] = array(
'country' => $row[0],
'sessions' => $row[1],
'users' => $row[2],
'pageviews' => $row[3]
);
}
$res = json_encode($dataGA);
return $res;
}
?>
Best regards
Axel Arnold Bangert - Herzogenrath 2016

Does the Universal Analytics' Ecommerce plugin have to be required multiple times when using multiple trackers?

When using the multiple tracker support in analytics.js Ecommerce tracking...
https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#multitracker
Does ecommerce.js have to be required for each tracker?
Like this... ?
ga('require', 'ecommerce', 'ecommerce.js'); // default tracker object
ga('myTracker.require', 'ecommerce', 'ecommerce.js'); // tracker for another web property
Yes, be sure to follow the trackerName.pluginName:method method for the transaction objects.
Here's a bit more information on this from the Google documentation
You can also use the ecommerce plugin if you have implemented multiple
(named) trackers on your page. The plugin works exactly the same as
the default tracker, except that the format is:
trackerName.pluginName:method. For example if you created a tracker
named myTracker:
ga('create', 'UA-XXXX-Y', 'auto', {'name': 'myTracker'}); You would
then load the ecommerce plugin for that named tracker using:
ga('myTracker.require', 'ecommerce', 'ecommerce.js'); The to send a
transaction, you can create a transaction object and pass it to the
named tracker as follows:
var transaction = { 'id': '1234', // Transaction
ID. 'affiliation': 'Acme Clothing', // Affiliation or store name.
'revenue': '11.99', // Grand Total. 'shipping': '5' ,
// Shipping. 'tax': '1.29' // Tax. };
ga('myTracker.ecommerce:addTransaction', transaction); Using this
syntax, the transaction object can be used on multiple trackers.
Finally you would send the transaction data as follows:
ga('myTracker.ecommerce:send');
Here's the link to the documentation https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#multitracker

Resources