Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually sending data to Google Analytics

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.

like image 325
huesforalice Avatar asked Sep 29 '12 13:09

huesforalice


People also ask

Can you import ROI data into Google Analytics?

If you import cost data to Google Analytics, you can use it in different attribution models and compare calculation results along with ROI to properly credit your marketing channels. These results also can be tracked in GA: Conversions — Attribution — Model Comparison Tool.

What format is used to import data in GA?

First, from the Data Import screen in the Admin, click the Manage uploads link next to the Data Set into which you want to upload data. Then, click on the Upload file button, choose the CSV file you created earlier, and upload it. It's that simple!


5 Answers

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.

like image 81
i.amniels Avatar answered Oct 04 '22 03:10

i.amniels


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")
like image 33
Oliver Avatar answered Oct 04 '22 04:10

Oliver


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

like image 28
P.T. Avatar answered Oct 04 '22 03:10

P.T.


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");
}
like image 21
Pavel Morshenyuk Avatar answered Oct 04 '22 04:10

Pavel Morshenyuk


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.

like image 38
L0j1k Avatar answered Oct 04 '22 04:10

L0j1k