Google Analytics API - Programmatically fetch page views in server side
Asked Answered
R

1

6

We have a web application that consists of several pages. We registered our web app domain to Google Analytics and page views tracking works as expected (In the Analytics panel we can see page views for each page). Now we want this page views info to be stored in the back-end inside our DB. So we want to create a back-end process that will run once each day, and fetch the page views from Analytics API.

This is of course need to be done in code. From initial research it seems that in order to access Analytics API an authentication process must take place, meaning a human user must type in an id and password.

The question is, can it be done with code only ?

Raceway answered 24/7, 2011 at 11:45 Comment(0)
R
10
    //-------------- Get Auth Token -------------------

    WebClient webClient = new WebClient();
    NameValueCollection data = new NameValueCollection();
    data.Add("accountType", "GOOGLE");
    data.Add("Email", "[email protected]");
    data.Add("Passwd", "xxxx");//Passwd, not a misspell.
    data.Add("service", "analytics");
    data.Add("source", "xxxx-xxxx-xx");//Could be anything.

    byte[] bytes = webClient.UploadValues("https://www.google.com/accounts/ClientLogin", "POST", data);
    string tokens = Encoding.UTF8.GetString(bytes);
    string authToken = extractAuthToken(tokens);

    //-------------- Get page views -------------------

    string feed = "https://www.google.com/analytics/feeds/data";

    //Required:
    string ids = "ga:xxxx";
    string metrics = "ga:pageviews";
    string startDate = "2011-06-25";
    string endDate = "2011-07-25";

    //Optional:
    string dimensions = "ga:pagePath";
    string sort = "-ga:pageviews";            

    string feedUrl = string.Format("{0}?ids={1}&dimensions={2}&metrics={3}&sort={4}&start-date={5}&end-date={6}",
        feed, ids, dimensions, metrics, sort, startDate, endDate);

    webClient.Headers.Add("Authorization", "GoogleLogin " + authToken);
    string result = webClient.DownloadString(feedUrl);

    //-------------- Extract data from xml -------------------

    XDocument xml = XDocument.Parse(result);
    var ns1 = "{http://www.w3.org/2005/Atom}";
    var ns2 = "{http://schemas.google.com/analytics/2009}";

    var q = from entry in xml.Descendants()
            where entry.Name == ns1 + "entry"
            select new
            {
                PagePath = entry.Element(ns2 + "dimension").Attribute("value").Value,
                Views = entry.Element(ns2 + "metric").Attribute("value").Value
            };

    //-------------- Do something with data -------------------
    foreach (var page in q)
    {
        Debug.WriteLine(page.PagePath + " " + page.Views);                
    }

    //-------------- Help Method -------------------
    private string extractAuthToken(string data)
    {          
        var tokens = data.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);            
        return tokens.Where(token => token.StartsWith("Auth=")).Single();
    }
Raceway answered 25/7, 2011 at 10:35 Comment(5)
It's important that you write leading 0's in the date parameters. 2011-07-01 WILL work but 2011-07-1 WON'T. Not using leading 0's will result in a 400 bad request error.Saccharate
@Saccharate Yes , I was banging my head about this one. I was using this code ,and set endDate to DateTime.Now. But suddenly one day it stopped working. Took me few hours to figure this out. Using DateTime.Now.ToString("yyyy-MM-dd"); solved this.Raceway
how do you get the pageview of a single page or all pages that match an expression?Majewski
I'm able to use this code from localhost but when I run it from production environment (tried on many dedicated servers I have access to that have NOT exceed the daily quota for sure), and I get the 403 Forbidden message with the same exact code on production. Anyone know why that occurs??Jay
What is source supposed to be?Vulgarity

© 2022 - 2024 — McMap. All rights reserved.