Google Analytics - How to get the client_id (anonymous client id) sent with Measurement Protocol - google-analytics

we are seding requests like this throught the google analytics measurement protocol to track user interaction there. For us its important to be to link a interaction to a specific user so we where happy to be able to set the "cid" attribute of the protocol.
my problem is that I cannot find this Client ID somewhere inside the reports of google analytics. Even when customizing the reports I cannot find a Dimension which allows me to display this information.
http://www.google-analytics.com/collect?
v=1 // Version.
&tid=UA-XXXX-Y // Tracking ID / Property ID.
&cid=555 // Anonymous Client ID.
&t=event // Event hit type
&ec=video // Event Category. Required.
&ea=play // Event Action. Required.
&cm18=8000
&cd6=crocodile
Do you have an idea of how the cid could be found there?

Client id is assigned to a user(client) viewing your site by google analytics. Here is an example of how you can get the client id if you're using jQuery.
$(document).ready(function() {
setGaClientId();
});
var setGaClientId = function(){
if(typeof(ga) != 'undefined'){
ga(function(tracker) {
console.log(tracker.get('clientId')); //actually do something here
});
}
}

Related

Google analytics api Get the userID / ClientID

I want to get the usage data of my customer out of google analytics, to make some usability analysis with it. For this, I need something that I can determine, which event was done by which user. Is there a possibility in a google analytics api to get this two parts linked?
You could add a user ID as a custom dimension, you'd probably want to set the scope to user.
https://support.google.com/analytics/answer/2709828?hl=en
This would allow you to connect up which users performed which actions.
Of course you can! :) I have used it in a lot of projects.
https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits
Example:
ga('send', {
hitType: 'event',
eventCategory: 'Video',
eventAction: 'play',
eventLabel: 'cats.mp4'
});
Since clientId has been made available through the API as ga:clientId you can use this value.
I would recommend using a custom User Id though - setting you own generated User Id in the script using the Universal Analytics User ID feature and in your backend db.
Also add the id to any link you send to your clients via email/sms/etc. that lands on your homepage to follow up on marketing performance.
You would need to have some javascript that grab the id and set it on the pageview. (like Linker, but adjusted for user id)
Note to anyone using the Universal Analytics User ID feature The values returned in ga:clientId is actually the userId Even more interessting. (As of time of writing) GA fails if you request clientId from a User ID view. So you should use a non-User ID view to get the User ID. :)

How to tie together front and back end events in google analytics?

I am tracking user events on the front end with google analytics, but I would also like to send back end events and be able to match up events for the same user in google analytics.
It looks like I should be able to pass the uid parameter: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#uid but it looks like I also have to pass the tid parameter https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#tid .
The docs say that "All collected data is associated by this ID" (the tid).
What should I pass for the tid? Why can't I just pass the uid, if that is supposed to be a mechanism for tying events together?
I would like the backend to pass the uid to the front end (actually a one-way hash of the email), and then refer to the user in google analytics with this uid.
Is this feasible? I'm a bit confused about how to implement this.
Many thanks!
The "tid" - Tracking ID - is the Web Property, i.e. the "slot" in your Analytics account that the data goes to. If you do not send a tracking id the calls will disappear in limbo. You find the tid in your property settings under "Tracking Code". It is a string that starts "UA-" and so is also sometimes referred to as UA-ID).
The User ID will not help you to identify users, at least not by default, since it is not exposed in the Analytics interface (it should really be called the "cross device identification id", since that is what it's for). You need to create a custom dimension and pass the value of the User ID there if you want to identify users. Per TOS you must take care that no third party, including Google, can resolve your User ID (or any other datapoint) into something that identifies a person, altough of course you can use yourself to connect data to other data in your backend system.
Actually there is a proper way. I've implemented this for myself.
There's a Client ID parameter, that should be passed with your requests.
And here's you have two options:
Create this client id manually (by generating UUID) on server-side and pass it to front-end. Then use this value when you create your tracker and also use it for server-side requests.
//creating of a tracker with manually generated client id
ga('create', 'UA-XXXXX-Y', {
'storage': 'none',
'clientId': '76c24efd-ec42-492a-92df-c62cfd4540a3'
});
Of course, you'll need to implement some logic of storing client id in cookie, for example.
You can use client id that is being generated automatically by ga and then send it to the server-side by your method of choice. I've implemented it through cookies:
// Creates a default tracker.
ga('create', 'UA-XXXXX-Y', auto);
// Gets the client ID of the default tracker and logs it.
ga(function(tracker) {
var clientId = tracker.get('clientId');
//setting the cookie with jQuery help
$.cookie("client-id", clientId , { path : "/" });
});
Then on the back-end just access this cookie and use that client id for your requests.
Also some information con be found here: What is the client ID when sending tracking data to google analytics via the measurement protocol?

Google Measurement Protocol not registering custom dimensions

I'm using the Google Analytics Measurement Protocol to register events with HTTP requests. I'm building this for a Roku app I'm working on. The events are getting sent and registered, but it seems the custom dimensions aren't working.
Here's what I'm sending
Destination URL:
https://ssl.google-analytics.com/collect
POST body:
v=1 // version
&dh=www.my-site.com // document hostname
&tid=UA-XXXXXXXX-X // Tracking ID / Property ID
&uid=(a user id) // user id
&cid=(an assigned UUID) // Anonymous Client ID
&sr=1280x720 // screen resolution of the tv
&t=event // Event hit type
&ec=ExampleCategory // Event Category. Required
&ea=ExampleAction // Event Action. Required
&el=ExampleLabel // Event label
&cd1=WAAA // Custom dimension 1, Station
&cd2=(some id) // Custom dimension 2, User ID
&z=1432199801 // Cache buster
When I go to Behavior > Events > Top Events in Google Analytics and set the secondary dimension as being Station for instance, none of the events show up. The events show up when I take off the secondary dimension though, so it seems like Google Analytics just isn't liking something about the custom definitions.
I've tried waiting 24 hours to see if there's a time delay problem, but that didn't help.
I've also made sure to turn on the custom definitions and set them to "Hit" scope type from the Admin panel in Analytics as well.
When I submit the above to https://ssl.google-analytics.com/debug/collect (the validation server that returns errors if there's something wrong with the request), it says the request is valid.
Any idea what could be going on here?
Thanks for the help!

tracking sign-ups with google analytics

our marketing consultant has asked me to help with configuring google analytics to setup Goal Tracking for User Signups... from what I've read this is accomplished by assigning the URL of the page the user is directed to after a successful signup to the Goal you are trying to track.
but what if the URL your user is directed to is a URL they regularly visit? e.g. after signing up they are directed to their profile page - which is the same page they visit every time they login. is there some way to configure a referer to go with the goal URL so that it is the pair of them that define the goal? e.g. user visits /profile and is referred by /signup.
further complication: what if after signup the user is directed to a different page depending on the user type? it would be nice to configure a single Goal with multiple URLs (but still using the referer restriction described above).
an alternative would be to use an event... if the server creates a user then it could signal the view to output the javascript code that generates the appropriate event.
or... is there a way for server-side code to send events to google analytics? is there an api?
If your users are directed to is a URL they regularly visit you can make a conditional statement for the goal occasion with a virtual pageview, have a look at this: http://services.google.com/analytics/breeze/en/et_vps/index.html
If after signup the user is directed to a different page depending on the user type, you can use regular expressions to set goal URL pattern, like this ^user./login./(type1|type2|type3)/$, look here for more info: http://services.google.com/analytics/breeze/en/regex_ga/index.html
I came across this question in google and believe I found a more appropriate answer.
Google Analytics now provide a service called Analytics Measurement Protocol.
This will allow you to send server-side requests to track your users activities in your analytics account.
To track a sign up event as mentioned in the question, the best way I can see would be to first create an event based goal in your account with the category set to 'users' and an action as 'sign_up' (you can optionally provide a label and value). Then in your code once a successful sign-up occurs (maybe when a user confirms their activation email link?), send a POST request to www.google-analytics.com/collect with the following payload:
v=1 // Version.
&tid=UA-XXXXX-Y // Tracking ID / Property ID.
&cid=555 // Anonymous Client ID.
&t=event // Event hit type
&ec=user // Event Category. Required.
&ea=sign_up // Event Action. Required.
&el=label // Event label.
&ev=1 // Event value.
A full list of the parameters and their meanings are defined here: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
You could use an event that is triggered when the user submits the sign-up form :
onsubmit="_gaq.push(['_trackEvent', 'Category','Action','Label','Value']);"
and use the Category / Action / Label data model in Google Analytics to pass whatever data you need to pass, for example :
onsubmit="_gaq.push(['_trackEvent', 'Sign-up','Premium','6-month',6]);"
You then have to configure this Goal in Google Analytics as an Event, which lets you choose which combination of each of the fields Category / Action / Label / Value you want to use.
Another option, maybe less maintenance-heavy, is to use a query-string to identify people that get back to the Profile page after having just signed up. So instead of sending them back to /user/profile after they sign up, you send them back to /user/profile/?sign-up=true.
You will then be able to track these pages as a URL goal in GA using a Regular expression like :
\?sign-up=true
I wrote a helper function for tracking GA events.
function trackGoogleAnalyticsEvent(category, action, label) {
try {
ga('send', 'event', category, action, label);
} catch (e) {
console.warn('Google analytics error: ' + e);
}
}
Usage:
trackGoogleAnalyticsEvent('Signup', 'Signup Success', 'Facebook');

Tracking email opens in Google Analytics

We have tracking in our emails to track clicks back to our site through Google Analytics. But is there a way to track opens? I would imagine I have to add a google tracking image to the email somewhere. Possibly javascript too?
As others have pointed out, you can't use Javascript in email. The actual tracking is done by a request for __utm.gif though and the Javascript just constructs the GET parameters.
Google supports non-Javascript uses of Google Analytics per their Mobile web docs:
http://code.google.com/mobile/analytics/docs/web/
They document the full list of parameters, but the only necessary parameters are:
Parameter Description
utmac Google Analytics account ID
utmn Random ID to prevent the browser from caching the returned image
utmp Relative path of the page to be tracked
utmr Complete referral URL
The reference that describes all of the parameters that the Google Analytics tracking GIF allows is here. Use it to build an <img> tag in your email that references the GA GIF.
According to this post, the minimum required fields are:
utmwv=4.3
utmn=<random#>&
utmhn=<hostname>&
utmhid=<random#>&
utmr=-&
utmp=<URL>&
utmac=UA-XXXX-1&
utmcc=_utma%3D<utma cookie>3B%2B_utmz%3D<utmz cookie>%3B
It sounds like you are using campaign tracking for GA but also want to know how many opens there were. This is possible to do with Google Analytics, since they track pageviews or events by use of pixel tracking as all (I think?) email tracking does. You cannot use javascript, however, since that will not execute in an email.
Using Google Analytics pixel tracking:
The easiest way would be to use browser developer tools such as Firebug for Firefox or Opera's Dragonfly to capture a utm.gif request and copy the URL. Modify the headers to suit your needs. You can count it either as an event or pageview. If you count it as an event it should look something like this:
http://www.google-analytics.com/__utm.gif?utmwv=4.8.6&utmn=1214284135&utmhn=www.yoursite.com&utmt=event&utme=email_open&utmcs=utf-8&utmul=en&utmje=1&utmfl=10.1%20r102&utmdt=email_title&utmhid={10-digit time code}&utmr=0&utmp=email_name&utmac=UA-{your account}
You can use this to understand what describes what in the headers.
I better post this to save everyone the trouble of trying to construct that monstrous UTM gif URL.
You can now use the new Measurement Protocol API to send a POST request and easily record events, page views, hits, or almost any other type of measurement. It's super easy!
POST /collect HTTP/1.1
Host: www.google-analytics.com
payload_data
For example, here's a code snippet to send an event in C# (using SSL endpoint):
public void SendEvent(string eventCategory = null, string eventAction = null, string eventLabel = null, int? eventValue = null)
{
using(var httpClient = new HttpClient() {BaseAddress = new Uri("https://ssl.google-analytics.com/")}) {
var payload = new Dictionary<string, string>();
// Required Data
payload.Add("v", "1"); // Version
payload.Add("tid", "UA-XXX"); // UA account
payload.Add("aip", "1"); // Anonymize IP
payload.Add("cid", Guid.NewGuid().ToString()); // ClientID
payload.Add("t", "event"); // Hit Type
// Optional Data
payload.Add("ni", "1"); // Non-interactive hit
// Event Data
if (eventCategory != null)
{
payload.Add("ec", eventCategory);
}
if (eventAction != null)
{
payload.Add("ea", eventAction);
}
if (eventLabel != null)
{
payload.Add("el", eventLabel);
}
if (eventValue != null)
{
payload.Add("ev", eventValue.Value.ToString(CultureInfo.InvariantCulture));
}
using (var postData = new FormUrlEncodedContent(payload))
{
var response = httpClient.PostAsync("collect?z=" + DateTime.Now.Ticks, postData).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Could not send event data to GA");
}
}
}
}
Way easier than the hack with the __utm gif.
Helpful Example
You can easily add this to emails by doing this:
In an email:
<img src="{url}/newsletter/track.gif?newsletterName=X" />
In your MVC site, for example, NewsletterController:
public ActionResult Track(string newsletterName) {
using(var ga = new AnalyticsFacade()) {
ga.TrackEmailOpen(newsletterName);
}
return Content("~/images/pixel.gif", "image/gif");
}
In your Global.asax or RouteConfig:
routes.MapRoute(
"newsletteropen",
"newsletter/track.gif",
new
{
controller = "Newsletter",
action = "Track"
});
BOOM, done, son. You can now track email opens using a much nicer API that's supported and documented.
Is your requirement is to track how many times an e-mail is open by given user. We have similar problem. We are using SMTP relay server and wanted to track how many times our marketing e-mails are open in addition to google-analytics which register an even only when someone clicks inside link to our site in e-mail.
This is our solution. It is based on making a REST call by overriding image element of html (our e-mails are html base)
where TRACKING is dynamically generated url which points to our REST service with tracking information about person to which e-mail was send. It is something like that
//def trackingURL = URLEncoder.encode("eventName=emailTracking&entityType=employee&entityRef=" + email.empGuid, "UTF-8");
trackingURL = baseUrl + "/tracking/create?" + trackingURL;
It will be something like "https://fiction.com:8080/marketplace/tracking/Create?eventName=email&entityType=Person&entityRef=56"
When when actual e-mail html is generated it, TRACKING will be replaced by
Important point is to return a response of type image and return a one pixel transparent image with REST response.
So i'll assume that the email contains a link to your Site. Certainly GA can record how often that link is clicked because clicking the link will open the page in turn causing the function *_trackPageview()* to be called, which is recorded by GA as a pageview.
So as long as that page has the standard GA page tag, no special configuration is required--either to the GA code in your web page markup or to the GA Browser. The only additional work you have to do is so that you can distinguish those page views from page views by visitors from another source.
To do that, you just need to tag this link. Unless you have your own system in place and it's working for you, i recommend using Google URL Builder to do this for you. Google URL Builder is just a web-form in which you enter descriptive terms for your marketing campaign: Campaign Source, Campaign Medium, Campaign Content, Campaign Name. Once you've entered values for each of these terms, as well as entered your Site's URL, Google will instantly generate a 'tagged link' for you (by concatenating the values to your Site's URL).
This URL generated by Google URL Builder is the link that would be placed in the text of your marketing email.

Resources