Google Analytics API - Average Session time doesn't fit with Analytics Dashboard - google-analytics

I am using the Google Analytics API and want to know the average session duration of a spezific content site.
To get the metrics I am using this PHP Code:
$result = $analytics->data_ga->get(
'ga:XXXXXXX',
'2012-01-01',
date("Y-m-d"),
'ga:visits',
array(
'filters' => 'ga:pagePath==MY_URL',
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews,ga:sessions,ga:uniquePageviews,ga:avgSessionDuration,ga:bounces',
'sort' => '-ga:uniquePageviews',
'max-results' => '25'
)
);
I get the following result:
[0] => Array
(
[0] => MY_URL
[1] => 8966
[2] => 7434
[3] => 7434
[4] => 17.15496368038741
[5] => 6245
)
Numbers 0-3 and 5 are exactly the same like Google Analytics Dashboard numbers (when I am logged in with my browser in google analytics)
But average duration time on site doesn't fit. API shows me 17.15 seconds and Google Analytics dashboard shows me 1 minute and 23 seconds.
Are these the same metrics? I want to have the "average duration time on site" (like standard Analytics Dashboard shows me).
Thanks!

There is no average duration time on site dimension. There is Avg. Time on Page and Avg. Session Duration. The confusion might be that you are looking at Time on Page in your dashboard, rather then session duration.
You might want to try ga:avgTimeOnPage instead of ga:avgSessionDuration.

Related

Google Analytics Custom Metrics not showing up

I want to push the products profit of a transaction to Google Analytics.
With this i want to generate a report where i can see the total Product revenue and it's profit for each product that has been ordered.
i'm using this api to push custom metrics to analytics (Measurement protocol api)
I have made several custom metrics in analytics, for example:
Productsprofit (Scope hit, decimal)
Productsprofit2 (Scope Product, decimal)
I've googled several times and i think i need to use the Scope Hit for this type of tracking, am i right?
I've used the api to push the metric with the right indexes to Analytics
$analytics->setTransactionId('test'.$orderId)
->setAffiliation('Testshop')
->setRevenue(number_format($orderTotalPrice,2,'.',''))
->setTax(number_format($taxTotal,2,'.',''))
->setShipping(number_format($shippingTotal,2,'.',''))
->setCouponCode('');
foreach($orderInfo['orderDetails'] as $orderDetail) {
// Include a product, only required fields are SKU and Name
$productData1 = [
'sku' => $orderDetail['model'],
'name' => $orderDetail['name'],
'brand' => '',
'category' => '',
'variant' => '',
'price' => number_format($orderDetail['price'], 2, '.', ''),
'quantity' => $orderDetail['aantal'],
'coupon_code' => '',
'position' => 0,
'custom_metric_3'=>50.45, //<-- test data (Hit)
'custom_metric_4'=>15.50 //<-- test data (Product)
];
$analytics->addProduct($productData1);
}
// Don't forget to set the product action, in this case to PURCHASE
$analytics->setProductActionToPurchase();
// Finally, you must send a hit, in this case we send an Event
$analytics->setEventCategory('Checkout')
->setEventAction('Purchase')
->sendEvent();
I've created a custom report and added these metric to my report. But both metrics stay empty in my report.
Does anyone know what i'm doing wrong ? or what might solve my problem?
Thanks in advance!
In the PHP library that you are using, custom metrics and dimensions are set in a different manner depending on the scope, for Product scope you use the product array like you did, for Hit scope you use the setCustomMetric method. In your code this would look like:
$analytics->setTransactionId('test'.$orderId)
->setAffiliation('Testshop')
->setRevenue(number_format($orderTotalPrice,2,'.',''))
->setTax(number_format($taxTotal,2,'.',''))
->setShipping(number_format($shippingTotal,2,'.',''));
foreach($orderInfo['orderDetails'] as $orderDetail) {
$productData1 = [
'sku' => $orderDetail['model'],
'name' => $orderDetail['name'],
'brand' => 'the brand',
'category' => 'test category',
'variant' => 'variant x',
'price' => number_format($orderDetail['price'], 2, '.', ''),
'quantity' => $orderDetail['qty'],
'coupon_code' => 'coupon used',
'custom_metric_4' => 15.50,
];
$analytics->addProduct($productData1);
}
$analytics->setProductActionToPurchase();
$analytics->setCustomMetric(50.45, 3);
$analytics->setEventCategory('Checkout')
->setEventAction('Purchase')
->sendEvent();
Notice the call to $analytics->setCustomMetric(50.45, 3); before sending the hit. This should send the right data, the rest is creating or looking at the right report in Google Analytics.

Google Analytics Tracking Events With Dimensions Incorrect Relations

Im trying to track an event that has 3 dimensions (user id, widget id,post id). Every click event must have its own row with a unique post id, user id and widget id so i can track the number of clicks per post. Extra: All the dimensions are set to have a scope of 'user'.
ga('send', 'event', 'widget', 'click', 'uwp',
{
'dimension1': $user_id,
'dimension2': $widget_id,
'dimension3': $post_id
}
);
I later query using the reporting api.
$result = Analytics::query(
$start_date,
$end_date,
'ga:totalEvents',
array(
'dimensions' => 'ga:dimension3,ga:pagePath,ga:date,ga:eventAction',
'sort' => '-ga:date',
'filters' => 'ga:eventAction==click;ga:eventLabel==uwp;ga:dimension1=='.$user->id,
'max-results'=> '100'
));
The result is incorrect all the clicks are being bundled up into 1 dimension, being dimension3 the post id.
Ex) If i click on a post of id 30 (dimension3 is set to 30) and a post of id 10 it will report that post of id 30 has 2 clicks or some older id has 2 clicks.
Google Analytics Dashbaord Picks:
As you can see from the pick i have 1 row with post id of 2 and 7 clicks, yet i sent events with many different post ids. (dimension3 == post id).
The problem here is that you are setting all of these dimensions to have a scope of user. Because of this, each dimension can only have one value per user. This is fine for the user id dimension, but for a dimension like post id, this is likely incorrect. Presumably, a user can view many post ids. Setting post id to user scope will cause the post id value to be overwritten with the latest post each time a new post is seen (which is why only one value is appearing in your report). You'll instead want to set post id to have a scope of hit, which will allow a different value to be sent on each event hit.
You can change the scope via the interface.
Read more about custom dimension scope.

How to get custom variable info from Google Analytics via API

I have data stored in the Second Dimension Google Analytics Events. The field is called Custom Variable (Value 01).
How can I use the GA api to get the values from Custom Variable (Value 01).
I'm using the GA explorer http://ga-dev-tools.appspot.com/explorer/ and can't figure out how to get the Custom Variable.
I see these options:
ga:dimensionXX
ga:customVarNameXX
ga:customVarValueXX
I tried replacing the xx with 01 but I had no luck. Anyone know how I can get the info for GA via API?
Thanks to #Blexy. This was my code at the end:
$params = array(
'metrics' => 'ga:visitors',
'dimensions' => 'ga:customVarValue1,ga:eventLabel,ga:deviceCategory,ga:operatingSystem',
'max-results' => 1000,
'start-date' => $start_date,
'end-date' => $end_date,
);
Try removing the 0.
For example, I have a query like this:
ga:customVarName4=~Previous-Purchases;ga:customVarValue4==1
This gets my custom variable name that matches regex Previous-Purchases AND the custom variable value is equal to 1.

GA Measurement Protocol: All events showing as unique

I'm using the new Google Analytics Measurement Protocol and running into a problem where all my events are coming is as "new visitor" even though I'm sending the same client ID for all of the requests.
I assume Google is using the client ID to determine if a visitor is new or not, but it appears to be ignoring this value.
Here's the variables I'm sending in the POST request:
Array
(
[v] => 1
[tid] => *OBFUSCATED*
[cid] => E19A0922-ABDF-D704-E4D4-620FB7AD7885
[t] => event
[sr] => 1280x720
[ec] => Video%20Plays
[ea] => Sample
[el] => Roku%20App
[ev] => 1
)
Other events are similar, where the cid remains the same but the event category and values change.
It looks like after waiting a full day and sending some events again, they are showing as returning visits.
Your cid is wrong I guess. it should be a 32bit id separated from a dot. Find a actual case study in my blog post http://www.niroshan-samuel.com/google-universal-analytics-isnt-linking-offline-and-online-user-properly/

Restrictions for app tab pages?

is there a way to install the app to the page with restrictions to the visitors country or age?
I am programming an app which will be only available for Users of distinct coutries.
However, I am planning to install the app as a tab on a Facebook page that is international with no restrictions. And I don't want users from other countries seeing my app.
Is this possible?
Regards,
Flashbaer
It should be possible according to https://developers.facebook.com/docs/reference/fbml/restricted-to/
Whatever settings I use result in that the tab isn't available for non-signed in users and is always available for signed in users. I don't think I'm doing anything wrong.
This is the code I use:
self::$facebookClient = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
));
$restrictions = array(
'location' => 'AR,AT',
// 'type' => 'alcohol',
// 'age' => '50+',
);
var_dump($fb->api('/'.$appId.'?restrictions='.urlencode(json_encode($restrictions)), 'POST'));
var_dump($fb->api('/'.$appId.'?fields=restrictions'));

Resources