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

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);
});

Related

Google Analytics: segment discrepancy between API and web reporting

I've had an analytics reporting API running for a while now and unfiltered view results from the API match the web reporting. The issue I'm seeing is when adding a segment to the API report request. The web reporting is frequently returning different values than the API for a handful of the segment/view_id combinations. I'm looking for a recommended settings to review here to understand what is causing the discrepancy, as I'm not sure if this is an program code/API issue, web reporting issue or a configuration for segment/view_id issue.
Notes:
When incorrect, it appears that the web reporting numbers for sessions is averaging 10% higher than what the API returns
A single segment is applied to many view_ids we manage and a high percentage (~80%) are showing the discrepancy, the remainder match.
the modified and created dates for this segment are 5 months old per the web interface, meaning there is not a configuration change within the segment causing the discrepancy
we've compared 2018 YTD to eliminate a time lag data update as an issue.
segments appear to be link to our master account level and applied to the accounts we manage.
currently using v4 of the analytics API for .Net (C#)
Current Questions:
Could this be a setting in how a particular segment was created?
Why would some segment/view_ids match and others not?
Is there a account, property or view_id permission/configuration setting to review as it relates to applying segments?
Any help or insights on what to review here would be helpful.
Forgot the code snippet:
var segmentDimension = new Dimension { Name = "ga:segment" };
var DefaultReportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { date, SourceMedium, Campaign, AdContent, Keyword },
Metrics = new List<Metric> { sessions, Users, NewUsers, Bounces, pageViews, SessionDuration, Goal01Completion, Goal02Completion, Goal03Completion, Goal04Completion },
ViewId = v_id,
PageSize = 10000
};
if (!(segmentId == ""))
{
DefaultReportRequest.Dimensions.Add(segmentDimension);
Google.Apis.AnalyticsReporting.v4.Data.Segment segment = new Google.Apis.AnalyticsReporting.v4.Data.Segment() { SegmentId = segmentId };
DefaultReportRequest.Segments = new List<Google.Apis.AnalyticsReporting.v4.Data.Segment> { segment };
};
var getReportsRequest5 = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { DefaultReportRequest }
};
var batchRequest5 = reportingService.Reports.BatchGet(getReportsRequest5);
var response5 = batchRequest5.Execute();
Thanks in advance for your help,
Mike
Update 2:
After reviewing this further the API call is always pulling a single day of data "Yesterday". The web reporting when pulling that single specific day of data matches. If the web reporting pulls a time range of data around those specific dates (ex: +/- 3 days) the numbers no longer match. It seems like sampling could be in play here, but the web reports we are running indicate 100% of sessions in both pulls. I think the question is how to determine which is more accurate a single day or a time range of data. Has anyone investigate this, I've reproduced it on several of our view_ids.
Thanks,
Mike
Update 3 (rseolution):
Turns out the issue was with how the segment was created and being applied to web reporting. The segment was focused at the User level, meaning aggregated values would change based on the time frame selected. The desired state was having the filters apply to a single day, making session focus a better then user as it contained the segment to the session.
Thanks all,
Mike
Without knowing too much about the details of the segments and views, the first thing I'd like to confirm with you is that you're aware of sampling in GA.
Unless they're all 360 accounts, you'll be subjected to sampling depending on the sessions you're returning for 2018 YTD. Note, sampling is based on sessions on the property level, not view level.
Another thing you can do in your code is to check if the sampling of the % of data matches with the web version VIA the response from the API. On the web version, the sampling info is here:https://i.stack.imgur.com/hcPGD.png

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?

Can I manually tell google the gclid?

Here's the scenario: visitor 1 (V1) clicks on an ad and gets a gclid as part of their __utmz cookie. V1 passes the url to visitor 2 (V2) on another computer. V2 visits the page from the specified url and therefore does not get a gclid. V2 completes the conversion, but adwords does not record the conversion as there is no gclid for V2.
If I can track all the above with some confidence, can I send the gclid from V1 to google when V2 completes their conversion?
Can I overwrite the __utmz cookie or can I add any javascript prior to the adwords conversion tracking script?
If I understand correctly, what you are trying to do is to maintain the campaign information if the user that was exposed to the ad sends the link to someone else. This is a major problem with user tracking in general and I see couple of methods that could help you to circumvent that.
First, gclid is used for adwords tracking. Theoretically you can save it in a cookie and then push it as a parameter to every URL that V1 is visiting and this way to maintain the campaign information when she shares the URL. This is possible, but the downside is that the data will appear as a new session of V1, not a new visitor (V2). From Google documentation:
...User A then copies this URL (containing the auto-tagging parameter)
and posts it in another location such as a public discussion board
(forum) or a social network, or sends it in an email or chat window to
other recipients.
Next, User B clicks this link (containing the gclid value) and arrives
at your website. Even though User B has never been to the website
before, this user will have the first session attributed to the same
click id (gclid) value that was assigned to the original User A. In
this case, you see new sessions (caused by User B) from an old
campaign.
Unfortunately there is no workaround to this scenario at the moment.
(source: https://support.google.com/analytics/answer/4588454?hl=en)
The downside however is that you fix a solution only for Google Adwords, while you may have campaigns on different platforms and sites that do not employ the gclid, but for which you use the UTM parameters.
Another solution I've stumble upon in the past is this one: http://www.lunametrics.com/blog/2013/10/02/direct-monster-fix-dark-social/ This script adds a unique query string parameter to every URL. If this URL is shared, in your GA reports it will show data in a custom dimension that denotes the user that shared the URL (V1) and those that used that URL (V2). This way you can analyze the "power of sharing". The downside is that you don't see the conversion under the campaign in question on GA. Never tried this script, only read about it.
Finally, you can make your own cookie and store the campaign information there. Then, you can append it with a parameter to every page that V1 views on your site. If V1 shares it, the campaign information will pass with this parameter to V2. The downside is that you will not see the conversion under the campaign in question on GA, only the parameter. However, you can see in your conversions report how many of campaign-->referral conversions you had by looking at the URL that led to the conversions (in the Reverse Goal Path, for instance). In addition, you are able to track this way not only Adwords campaigns with referrals, but any campaign. Try this project: https://github.com/dm-guy/utm-alternative. This project will help you with creating your own campaign tracking, but not with pushing it to the URL.
I work on AdWords conversion tracking. Here's how I'd do it using AdWords Conversion Import...
If the GCLID is passed in the URL to V2, then the site can grab the GCLID for V2's visit and store it in a cookie (provided you craft some JS to do so).
Then, when the conversion occurs, you've got another bit of JS that collects the cookie and stores it somewhere along with the date/time of the conversion and the type of conversion (this type should match an equivalent conversion type that you've defined in your AdWords account).
Once you have this process in place, you can batch the conversion records up daily and import it into AdWords via the conversion import service (https://support.google.com/adwords/answer/2998031).
The gclid value pertains to Adwords and Adwords only. To give credit to the converting gclid, you need to send the _ga cookie value in the URL query as such:
foo.com?_ga=1.2.xxxxxxxx.xxxxxxxxx
The x's above represent the clientID and this value needs to be cookied using JS:
<script>
function() {
var coo = window.location.href.split("_ga=")[1].split('.');
var cid = coo[2]+"."+coo[3];
return cid;
}
</script>
Have this above the UA tracking code:
<script>
ga('create', 'UA-xxxxxx-xx', {'clientId' : '<?php echo implode(".",array_slice(explode(".", $_GET["_ga"]), -2, 2)); ?>'});
</script>
Remember you must return the _ga cookie value in the URL in order for it fire off on this page. What's clever is, if you can record to a database IP and the associated _ga cookie value, you can track a user across different browsers and/or devices PROVIDED they are using the same IP address.

Store Locator API + Geolocation

I am trying to create a Store Locator with the Google API, very similar to the one in the Google examples here:
http://storelocator.googlecode.com/git/examples/panel.html
However I've hit a wall trying to get the Store Locator API to get the user's position through Geolocation, so when I click on Get Direction in the infowindow I get directions to the user position; instead of having to type my address in the: Where are you? Panel box.
In the documentation what I have seen is that geolocation is a boolean in the View Option that is set to True by default. But this does not solve my problem.
Does anyone have any idea on how to do this?
seems that the googlecode page you said is no longer exist. So I can't give any further insight about what you want to make.
However, by your description, Luckily I made similar site few months ago. It is on Grocery Store Near Me .
The concept of Geolocation is an HTML5 (actually W3C) Geolocation API which is now already embed in most modern browser. It is an API which you can obtain user's location (latitude, longitude, altitude, and accuracy).
you can call it with simply
navigator.geolocation.getCurrentPosition(success, error, geo_options);
Success and error is a callback function in which you can define.
In my case, the function looks like these
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
// use the lat and long to call function to fetch an API through AJAX
fetchStoreData(latitude, longitude);
}
In the Store Locator schema (like mine in Grocery Store Near Me), Geolocation is used to obtains user lat and long. The lat and long, then send to server via AJAX to get data about nearby store location.
The server serve an API in which accept lat and long as parameter, then fetch the store data (either using database, or other external API like foursquare), then you can display it either on list, or on a maps.

Switching to cross domain tracking from previous Google Analytics implementation

We have in place a simple implementation of GA and have had for some time, the only additional methods we use are setVar and setSessionTimeout. Is there a way we can switch to a cross-domain tracking configuration of GA (where certain links are wired via the _link method) without losing existing tracking data on client systems?
I've run a lot of tests and the more issues solved, the more issues that come up. In a nutshell:
Pre-implementation, the client has these cookies: __utm(a, b, c, z, v). The first step was to change the code and add the _setAllowLinker and _setAllowHash methods, but this was throwing a TypeError. I found this could be avoided by deleting the __utmv cookie before calling the pageTracker methods, and then calling _setVar again afterward.
The new code in place seems to be working OK without throwing an error:
document.cookie = '__utmv=; expires=Tue, 22 Jun 2010 11:57:00 GMT;'+
' path=/; domain=XXXXXXX';
var pageTracker=_gat._getTracker(UA-XXXXXXXX);
pageTracker._setAllowLinker(true);
pageTracker._setAllowHash(false);
pageTracker._setSessionTimeout(XXXXX);
pageTracker._setVar(XXXXX);
pageTracker._trackPageview();
The cookies are now updated to not use a hash value, so their values can now be used cross domain, but the problem is that the values in the __utm cookies have been refreshed with new values which means we're losing user history (and new visits will explode).
For example, __utma:
Before - XX-HASHVALUE-XX.1379282990.1277294951.1277294951.1277294951.1
After - 1.26318765.1277294984.1277294984.1277294984.1
If it's not possible to switch to cross-domain GA configuration without losing user history, is there a way to fake it on the link which will click through to the next domain. That is, constructing the link URL from the cookies and replacing all the hashvalue prefixes with a 1?
Thanks!
Unfortunately it seems there is no proper way to do this using the ga.js API. I've gone with this solution:
var pageTracker = _gat._getTracker("UA-123456-7");
if (getCookie('__utma') && getCookie('__utma').substr(0, 2) == '1.') {
// hash value safely removed, flick GA API switch
pageTracker._setAllowHash(false);
}
pageTracker._trackPageview();
if (getCookie('__utmc') != '1') {
// remove hash values from all GA cookies
eraseCookieHash();
}
In the eraseCookieHash function, each cookie is updated manually to replace the hash value with a 1, using the guide at http://code.google.com/apis/analytics/docs/concepts/gaConceptsCookies.html to determine the expires value.

Resources