Google Analytics API deviceCategory - google-analytics

I am trying to use the Google Analytics API (v3) in Google Scripts to pull Device Category information from Google Analytics.
Within Analytics under Audience -> Mobile -> Overview there is a Device Category section listing 'tablet', 'mobile' and 'desktop'. I wish to pull these numbers into a Google Sheet that my script is attached to.
The code I believe I should be using is:
ga:deviceCategory==mobile (to pull mobile traffic) and ga:deviceCategory==tablet to pull tablet traffic.
However, I receive the error:
Invalid dimension or metric: ga:deviceCategory==desktop
I'm somewhat confused by this as Google's own documentation says that deviceCategory is a valid dimension
(https://developers.google.com/analytics/devguides/reporting/core/dimsmets#view=detail&group=platform_or_device&jump=ga_devicecategory)
If I remove the device type from the end ('ga:deviceCategory') I get the error:
Unknown metric(s): ga:deviceCategory (line 43, file "Code")
This leads me to believe that I need to include the metric (which I believe is 'pageviews') beforehand. If this is the case, can someone show me how I pull in the figures for mobile/tablet traffic?
I am having no other issues pulling other aspects of my data. For example:
var impressions = Analytics.Data.Ga.get(tableId, startDate, endDate, 'ga:visits').rows.toString();
works fine.
For reference, this is the full code I am using for device Category:
// Get Mobile Visits, this is the number of visits from mobile devices
var mvisits = Analytics.Data.Ga.get(tableId, startDate, endDate, 'ga:deviceCategory==mobile').rows.toString();
mvisits = mvisits;
I would be grateful for any assistance and please let me know if you require any more code from my script.
Thanks in advance.

My app script is a bit rusty but your problem is your == the dimension field is just a column you want to select.
var tableId = 'ga:' + profileId;
var metric = 'ga:visits';
var options = {
'dimensions': 'ga:deviceCategory',
'filters': 'ga:deviceCategory==mobile'
};
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
What you need to do is add some filters instead. If you think of this like a relational database this would be like saying
select deviceCategory, visits
from tableId
where devicecategory == mobile
Remember you need to add a metric.
Example: shamelessly ripped from Analytics service page.

Related

Google Analytics UserID API extraction

Trying to extract a userID from GoogleAnalytics. This is to view which user is the using the website most and least.
I would to retrieve the top 5 user IDs and bottom 5 user IDs that were passed using either:
gtag('config', 'GA_TRACKING_ID', {
'user_id': 'USER_ID'
});
OR
using a custom dimension... ( https://support.google.com/analytics/answer/2709828?hl=en )
I'm (vaguely) aware of policies and TOS to keep 'non identifying' information on Google BUT there are posts online indicating you can link back to CMS data.
Steps so far
Google Analytics with UserID and view setup - Working in Google dashboard and showing filtered userID and All website data using the idea.
Requirements:
Extract page view and session data for each userId between a date
range (or all by default)
UserID via standard GA method
UserID via Custom dimension method
Any help, pointers or examples how someone has completed something like this are appreciated.
NOTE: This is to PULL data out of GA and manipulate/display it on an external system/dashboard.
Seen this which states it's not possible: Google analytics userID tracking
and this which states it (kind of) is google analytics API implementation for tracking a specific user activities in php
The solution I used:
Tracking
Create Google Analytics account
Create a new view by activating the UserID tracking (labeled NewView1)
Use https://developers.google.com/analytics/devguides/collection/gtagjs/custom-dims-mets
i.e. Define your custom dimension
Get Analytics tracking code + Add custom definition code
Create a Custom report using the 'metrics' you want to see and filtering by the 'custom dimension' I created earlier.
(note: data took ~ 12 hours to be visible so don't expect to work instantly)
Front end tracking additions
gtag('config', 'GA_TRACKING_ID', {
'custom_map': {'dimension<Index>': 'dimension_name'}
});
// Sends the custom dimension to Google Analytics.
gtag('event', 'any_event_name', {'dimension_name': dimension_value});
Extraction
Create New Google Developer Console Project (API)
Use a Service Account to connect the API with Analytics ( https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php ) -- API -> credentials -> Create Credentials (Service Account key)
(assign role [mine was set to Project => View])
Save the Text file to your filesystem and rename to json as per examples
Add permissions to your Analytics project by copy/pasting the 'Email' from the Service account details into Analytics User Management.
Get the view ID of the data you wish to extract (Analtyics created in step 2 in tracking)
Use the sample Code (HelloAnalytics.php) to connect and extract data
Use your custom dimension to filter results
The dimension filter I used was $dimensions (see below)
...
$dimensions = new \Google_Service_AnalyticsReporting_Dimension();
$dimensions->setName('ga:dimension1'); // as per docs
// Create the ReportRequest object.
$request = new \Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions, $pageviews));
$request->setDimensions($dimensions);
From there I was able to see the same data via API that I could see in the custom report on analytics web.
NOTE: be careful of which Google project and view you're in while setting up
permissions and dimensions.
NOTE: using gtag() code and not Universal (ga()) js code
The answer is a very brief/rough summary of how I achieved my specific goal. It is not a one-size-fits all solution but hopefully it will give someone a better idea of how to set and extract custom variable data within Google.
The final result was data from the API. From there it's up to you.

Setting up Adobe Analytics eCommerce tracking in GTM

I am currently in the process of setting up Adobe Analytics on a website that is currently using GTM & GA (universal analytics). Ideally I want to leverage the existing data layer to pass values to the Adobe evars/props but the one question I have was how to handle the products field? Adobe requires the products field to be in a very specific format (category;product;qty;total).
Can I build this product string in GTM? Or do I need the developers to hard code this string? I might be overthinking this but I have never installed Adobe thru GTM before
You can use a custom javascript variable (GTM "variables" used to be called "macros" which was a lot less confusing) of the type "custom javascript function" to loop through the products array and assemble the product string.
That is you'd first create a dataLayer variable that returns the product array from the dataLayer and then do a loop; a custom javascript variable in GTM is an anonymous function that returns a value. This would look a bit like that (from top of my head, not exact code; the thing in curly brackets is the datalayer products variable you need to create first):
function() {
var products = {{products}};
var productAdobe = [];
for(i=0;i<products.length;i++) {
prod = products[i];
productAdobe.push(prod[i].category + ";" + prod[i].id + ";" + prod[i].quantity + ";" + prod[i].quantity*prod[i].price);
}
return productAdobe.join("\n");
}
Like I said this is not exactly working code, but should be enough to give you an idea.
Having said that having your developers pass on a proper product string is a much better idea. Using GTM for programming tasks is error prone and makes maintenance hard (and tag management should make your life easier, not harder). And if you already have Adobe Analytics you should have free Access to Adobe DTM which might a better choice to deploy Adobe Analytics (for one thing you cannot host s_code within GTM, as the custom HTML tag has a length limit that is exceeded by the Adobe Tracking code).

Why am I seeing "reference error: "Calendar" is not defined" when I run a Google Spreadsheet API script?

I made a working bound script in a clone of my original Google Spreadsheet, put together over a course of several days.
I then copied my formula to a new spreadsheet.
Suddenly, even though I don't think I made any changes to any relevant code, I'm seeing "reference error: "Calendar" is not defined google API."
I have a lot of code so it would be difficult to paste it all, but the relevant section is here:
var start = (passed as argument to function);
var end = (passed as argument to function);
var calendarId = 'redacted'//source calendar
var optionalArgs = {
timeMin: start.toISOString(),
timeMax: end.toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: null,
orderBy: 'startTime'
};
var response = Calendar.Events.list(calendarId, optionalArgs);
This took me way too long to get through, so dear person of the future, if I've saved you a few minutes, my struggles will be worthwhile.
Calendar API has to be turned on for Calendar.Events.list to work.
In your script's menu, select "Resources" then "Advanced Google Services." You will see a list of APIs with switches.
To use the API for another service, you must turn it on both here and in your Google Developers Console (just follow the link at the bottom of the dialogue window).
Also, I had sort of assumed that in the Google Developers Console, once an API was turned on, it was turned on for you as a user, but there is a unique console for each project, which is what you're taken to when you follow the link. You have to turn it on again for each additional project.

How to create tracking pixel with Google Analytics for 3rd party site?

We need to track conversions that happen on a 3rd party site. The only thing we can place on that site is an image pixel and maybe some JS logic for when to fire it.
I know it is possible to fire a conversion using the Measurement Protocol: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#visitor
Ideally, I'd just give the 3rd party an IMG url and that would be it. The problem is the CID (unique client id).
I can try passing the CID from our site to the 3rd party via URL parameter. However, there are many cases where its not available (e.g., IMG pixcel will be in an email, the goal URL is on printed literature) or the 3rd party is not willing to go through the hassle. Is it best practice to pass this CID in this way?
I can try generating a CID, but I can't find a dead simple way of doing that e.g., var CID = generateCID(). The 3rd party site has its own GA on the page. Can I just take their Google Analytics CID and use it in the image pixel URL?
What the best way to do this? Thank you!
If the 3rd-party site has analytics.js already running then using that client ID is probably best. You can get it by doing the following:
var cid;
ga(function(tracker) {
cid = tracker.get('clientId'));
});
If analytics.js is not running, or if you can't access the ga variable for some reason, you can just generate the client ID randomly. This is approximately what Google does. It's a random 31-bit integer with the current date string appended:
var cid = Math.floor(Math.random() * 0x7FFFFFFF) + "." +
Math.floor(Date.now() / 1000);
Only to complement #Philip Walton excellent answer, Google Analytics expects a random UUID (version 4) as the Client ID, according to the official Documentation.
Client ID
Required for all hit types.
This anonymously identifies a particular user, device, or browser
instance. For the web, this is generally stored as a first-party
cookie with a two-year expiration. For mobile apps, this is randomly
generated for each particular instance of an application install. The
value of this field should be a random UUID (version 4) as described
in http://www.ietf.org/rfc/rfc4122.txt
#broofa provided a simple way to generate a RFC4122-compliant UUID in JavaScript here. Quoting it here for the sake of completeness:
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});

Why data i get from google analytics API not match with google analytics web interface?

I used Google API to get data from google analytics, but the metrics not the same with the web interface of google analytics.
ie: I get data on 2015-03-01 - It return pageviews 79
But on web interface of google analytics, it is 80.
I had searched on some question the same me, but almost them show the way to solve is Sampling level.
I tried to set other Sampling level
DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"),
endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics));
if (dimensions != null)
{
request.Dimensions = string.Join(",", dimensions);
}
request.SamplingLevel = DataResource.GaResource.GetRequest.SamplingLevelEnum.HIGHERPRECISION;
request.StartIndex = startIndex;
return request;
after that, the result return the same before, it not change.
So, anyone know this issue?
Simple its sampled data vs. unsampled data which you can read about here: https://support.google.com/analytics/answer/1042498?hl=en
For API work i normally use a web query explorer to verify that my API call's are being sent and responses match to verify the data: https://ga-dev-tools.appspot.com/explorer/

Resources