18

I was wondering if I can send google analytics tracking data to google by sending custom URL requests. I assumed I could build my own URLs and fire a request to get events tracked something like this: http://google.com/analytics-endpoint?id=UA-34900236-1&event=some_event, I haven't found any documentation about this though and was wondering if this is even possible? If so, could some one point me to the right documents?

The background for anyone who is interested: I'm currently trying to add google analytics support to a Mono for Android application. I could not get any of the c# google analytics libraries to compile, because required .net libraries are missing from Mono for Android.

6 Answers 6

22

As an addition to @P.T.'s answer I want to note that Google released an official API to send data to Google Analytics now. This is the Google Analytics Measurement Protocol. This is probably the safest solution because it is an "official" and documented API.

4
9

Inspired by @i.amniels answer, I wrote a small wrapper around the Google Analytics Measurement Protocol to track events on the server side of our web application.

Here's a gist with a class you can start with. It simply wraps the boiler plate code of sending POST request to the Google Analytics measurement protocol endpoint.

Using that wrapper you'll be able to write this:

GoogleAnalyticsApi.TrackEvent("Video", "Play", "Vacation 2014")
4
  • 1
    Thanks for sharing. This was helpful in getting started with a GitHub repository I created: github.com/jakejgordon/Universal-Analytics-For-DotNet and a NuGet package: nuget.org/packages/UniversalAnalyticsMeasurementProtocolWrapper . I will say it looks like you forgot to dispose of your requests so this code will give an "operation timed out" if it runs more than a couple of times. Commented Aug 19, 2014 at 2:03
  • 1
    @jakejgordon: Thanks for your feedback and your package! My gist was really just a place to start for someone who hasn't seen the approach, yet. It surely can be improved, so thanks for stepping forward to do so :-)
    – Oliver
    Commented Aug 19, 2014 at 11:18
  • Supports New version Global Site Tag (gtag.js) ? Commented Mar 26, 2018 at 11:20
  • @PreguntonCojoneroCabrón I don't know - I'm not using this anymore. Since my answer is almost 4 years old, chances are it doesn't.
    – Oliver
    Commented Mar 26, 2018 at 21:13
4

Yes, you can do HTTP requests directly to Google Analytics to track arbitrary applications. This is what the existing GA library for Android does for example (it issues HTTP_GET requests with a very specific set of URL parameters).

There is no official documentation for using the underlying HTTP API as a client, but you can rely on it being pretty stable given the number of ancient javascript snippets lying around on the web, and the fixed library code that is compiled into existing Android applications. The GIF parameter troubleshooting doc explains the how analytics data is encoded.

Here is an existing project that provides a client library for pure Java applications: http://code.google.com/p/jgoogleanalytics/

If you want to re-implement this in C#, the magic seems to all be in here: http://code.google.com/p/jgoogleanalytics/source/browse/trunk/src/main/java/com/boxysystems/jgoogleanalytics/GoogleAnalytics_v1_URLBuildingStrategy.java

3
2

Inspired by @Oliver answer, I have updated C# code to be more up to date on sending POST data:

namespace Helpers
{
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading.Tasks;

    // More information about API - see https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
    public class GoogleAnalyticsHelper
    {
        private readonly string endpoint = "https://www.google-analytics.com/collect";
        private readonly string googleVersion = "1";
        private readonly string googleTrackingId; // UA-XXXXXXXXX-XX
        private readonly string googleClientId; // 555 - any user identifier

        public GoogleAnalyticsHelper(string trackingId, string clientId)
        {
            this.googleTrackingId = trackingId;
            this.googleClientId = clientId;
        }

        public async Task<HttpResponseMessage> TrackEvent(string category, string action, string label, int? value = null)
        {
            if (string.IsNullOrEmpty(category))
              throw new ArgumentNullException(nameof(category));

            if (string.IsNullOrEmpty(action))
              throw new ArgumentNullException(nameof(action));

            using (var httpClient = new HttpClient())
            {
                var postData = new List<KeyValuePair<string, string>>()
                {
                    new KeyValuePair<string, string>("v", googleVersion),
                    new KeyValuePair<string, string>("tid", googleTrackingId),
                    new KeyValuePair<string, string>("cid", googleClientId),
                    new KeyValuePair<string, string>("t", "event"),
                    new KeyValuePair<string, string>("ec", category),
                    new KeyValuePair<string, string>("ea", action)
                };

                if (label != null)
                {
                    postData.Add(new KeyValuePair<string, string>("el", label));
                }

                if (value != null)
                {
                    postData.Add(new KeyValuePair<string, string>("ev", value.ToString()));
                }


                return await httpClient.PostAsync(endpoint, new FormUrlEncodedContent(postData)).ConfigureAwait(false);
            }
        }
    }
}

Can be found on GitHub Gist

Usage:

var helper = new GoogleAnalyticsHelper("UA-XXXXXXXXX-XX", "555");
var result = helper.TrackEvent("Orders", "Order Checkout", "OrderId #31337").Result;
if (!result.IsSuccessStatusCode)
{
    new Exception("something went wrong");
}
2
1

Yes, this is possible. Because Google Analytics will store every URL page request it is on. Those are visible under Content tab on the left menu, then find URL or Page Content. You can see every page request listed. So if you fired this off due to a link like <a href="more.php?id=8&event=sales">LINK</a> Analytics would store the full URL.

However, there is no direct route to your Analytics account via the URL you have provided hoping to get a similar answer to: This is the best you can do, I think.

You could make a page that literally has tracking code on every page. That way, Google Analytics will capture all the stuff going on. Then, you can add your "event" to the end of EVERY link on the page, so that when a user clicks a link, it will redirect to the appropriate page on your site, but it will also record (in the URL from the href of the link) on Google Analytics, because GA sees everything going on inside the page, INCLUDING the full URL of the href value of a link. So, if your link looked like this, Google Analytics would record the whole URL, which you can later retrieve:

<a href="page2.php?id=4492&event=clickedCatalog&preference=yellow">Link!</a>

...will record the full URL (page2.php?id=4492&event=clickedCatalog&preference=yellow) in GA, which you can see in the list of URLs visited on your site, by clicking through the menu called Context on the left hand side of Google Analytics main page.

8
  • Thanks for your answer. What I'm trying to do is track events in a mobile application by sending requests to the google analytics api. I don't think I understand entirely what you are suggesting here. Commented Sep 29, 2012 at 14:05
  • You could make a page that literally has tracking code on every page. That way, Google Analytics will capture all the stuff going on. Then, you can add your "event" to the end of EVERY link on the page, so that when a user clicks a link, it will redirect to the appropriate page on your site, but it will also record (in the URL from the href of the link) on Google Analytics, because GA sees everything going on inside the page, INCLUDING the full URL of the href value of a link. So, if your link looked like this, Google Analytics would record the whole URL, which you can later retrieve:
    – L0j1k
    Commented Sep 29, 2012 at 14:07
  • <a href="page2.php?id=4492&event=clickedCatalog&preference=yellow">Link!</a> will record the full URL (page2.php?id=4492&event=clickedCatalog&preference=yellow) in GA, which you can see in the list of URLs visited on your site, by clicking through the menu called Context on the left hand side of Google Analytics main page.
    – L0j1k
    Commented Sep 29, 2012 at 14:09
  • Ah now I get it, so you're suggesting to involve a request to a page on my own webserver which then gets tracked. I would assume though, that a simple request to my server would not be enough, because the embedded javascript on that page would need to be executed. So that would mean embedding a Webview in Android which is a lot of overhead. Commented Sep 29, 2012 at 14:30
  • But I could use a server side php script which I found here: developers.google.com/analytics/devguides/collection/other/…. I'll test that, thank you for pointing me in this direction. I'd still prefer a direct request to google analytics though. But you think this is not possible, right? Commented Sep 29, 2012 at 14:32
0

In addition to @pavel-morshenyuk answer, if you want to correlate the event to the user who actioned on it, the code below will map the request to the google client id.

 string clientId = Guid.NewGuid().ToString();

 if (Request != null && Request.Cookies != null && Request.Cookies.Get("_ga") != null && Request.Cookies.Get("_ga").Value != null)
 {
    clientId = Request.Cookies.Get("_ga").Value;
    clientId = clientId.Replace("GA1.2.", "");
    clientId = clientId.Replace("GA1.1.", "");
 }

note at some point, this may need to be tweaked if GA changes their internal cookie tracking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.