Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Google Analytics API to show information in C#

I been looking for a good solution all day but google evolve so fast that I can't find something working. What I want to do is that, I have a Web app that has an admin section where user need to be logged in to see the information. In this section I want to show some data from GA, like pageviews for some specific urls. Since it's not the user information that I'm showing but the google analytics'user I want to connect passing information (username/password or APIKey) but I can't find out how. All the sample I found use OAuth2 (witch, if I understand, will ask the visitor to log in using google).

What I found so far :

  • Google official Client Library for .Net : http://code.google.com/p/google-api-dotnet-client/, no sample for GA
  • official developers help : https://developers.google.com/analytics/
  • an other question with code on SO : Google Analytics API - Programmatically fetch page views in server side but I get a 403 when I try to authenticate
  • some source that access the API : http://www.reimers.dk/jacob-reimers-blog/added-google-analytics-reader-for-net downloaded the source but I can't figure out how it works
  • this other question on SO : Google Analytics Access with C# but it does not help
  • while writing this they suggest me this 09 old post Google Analytics API and .Net...

Maybe I'm just tired and that tomorrow it will be easy to find a solution but right now I need help!

Thanks

like image 689
VinnyG Avatar asked Apr 24 '12 22:04

VinnyG


People also ask

Is Google Analytics Reporting API free?

The Google Analytics API is free to use. You don't have to pay for using it. If you run out of quota you can request an increase on the 50000 requests a day.

Can we extract data from Google Analytics?

How to export Google Analytics behavior report. It's very simple. Go to Behavior => Overview, click the “Export” button, and select the format for exporting your report (PDF, Google Sheets, Excel, CSV).


1 Answers

It requires a bit of setup on the google side but it's actually quite simple. I will list step by step.

First you will need to create an application in the Google cloud console and enable the Analytics API.

  • Go to http://code.google.com/apis/console
  • Select the drop down and create a project if you do not already have one
  • Once the project is created click on services
  • From here enable the Analytics API

Now that the Analytics API is enabled the next step will be to enable a service account to access your desired analytics profiles/sites. The service account will allow you to log in without having to prompt a user for credentials.

  • Go to http://code.google.com/apis/console and choose the project you created from the drop down.
  • Next go to the "API Access" section and click the "Create another client id" button.
  • In the Create Client ID window choose service account and click create client id.
  • Download the public key for this account if it doesn't start the download automatically.You will need this later on when you code for authorization.
  • Before exiting copy the service accounts auto generated email address as you will need this in the next step. The client email looks like @developer.gserviceaccount.com

Now that we have a service account you will need to allow this service account to access to your profiles/sites in Google Analytics.

  • Log into Google Analytics.
  • Once logged in click on the Admin button to the bottem left on the screen.
  • In Admin click the account drop down and select the account/site you would like your service account to be able to access then click on "User Management" under the account section.
  • Enter the email address that was generated for your service account and give it read and analyze permission.
  • Repeat these steps for any other account/site you would like your service to have access to.

Now that the setup is done for the service account to access Google Analytics through the API we can start to code.

Get this package from NuGet:

Google.Apis.Analytics.v3 Client Library

Add these usings:

using Google.Apis.Analytics.v3; using Google.Apis.Analytics.v3.Data; using Google.Apis.Services; using System.Security.Cryptography.X509Certificates; using Google.Apis.Auth.OAuth2; using System.Collections.Generic;  using System.Linq; 

Some things to note are.

  • The keyPath is the path to the key file you downloaded with a .p12 file extention.
  • The accountEmailAddress is the api email we got earlier.
  • Scope is an Enum in the Google.Apis.Analytics.v3.AnalyticService class that dictates the url to use in order to authorize (ex: AnalyticsService.Scope.AnalyticsReadonly ).
  • Application name is a name of your choosing that tells the google api what is accessing it (aka: it can be what ever you choose).

Then the code to do some basic calls is as follows.

public class GoogleAnalyticsAPI {     public AnalyticsService Service { get; set; }      public GoogleAnalyticsAPI(string keyPath, string accountEmailAddress)     {         var certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);          var credentials = new ServiceAccountCredential(            new ServiceAccountCredential.Initializer(accountEmailAddress)            {                Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }            }.FromCertificate(certificate));          Service = new AnalyticsService(new BaseClientService.Initializer()             {                 HttpClientInitializer = credentials,                 ApplicationName = "WorthlessVariable"             });     }      public AnalyticDataPoint GetAnalyticsData(string profileId, string[] dimensions, string[] metrics, DateTime startDate, DateTime endDate)     {         AnalyticDataPoint data = new AnalyticDataPoint();         if (!profileId.Contains("ga:"))             profileId = string.Format("ga:{0}", profileId);          //Make initial call to service.         //Then check if a next link exists in the response,         //if so parse and call again using start index param.         GaData response = null;         do         {             int startIndex = 1;             if (response != null && !string.IsNullOrEmpty(response.NextLink))             {                 Uri uri = new Uri(response.NextLink);                 var paramerters = uri.Query.Split('&');                 string s = paramerters.First(i => i.Contains("start-index")).Split('=')[1];                 startIndex = int.Parse(s);             }              var request = BuildAnalyticRequest(profileId, dimensions, metrics, startDate, endDate, startIndex);             response = request.Execute();             data.ColumnHeaders = response.ColumnHeaders;             data.Rows.AddRange(response.Rows);          } while (!string.IsNullOrEmpty(response.NextLink));          return data;     }      private DataResource.GaResource.GetRequest BuildAnalyticRequest(string profileId, string[] dimensions, string[] metrics,                                                                         DateTime startDate, DateTime endDate, int startIndex)     {         DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"),                                                                             endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics));         request.Dimensions = string.Join(",", dimensions);         request.StartIndex = startIndex;         return request;     }      public IList<Profile> GetAvailableProfiles()     {         var response = Service.Management.Profiles.List("~all", "~all").Execute();         return response.Items;     }      public class AnalyticDataPoint     {         public AnalyticDataPoint()         {             Rows = new List<IList<string>>();         }          public IList<GaData.ColumnHeadersData> ColumnHeaders { get; set; }         public List<IList<string>> Rows { get; set; }     } } 

Other Links that will prove helpful:

Analytic API Explorer - Query API From The Web

Analytic API Explorer version 2 - Query API From The Web

Dimensions and Metrics Reference

Hopefully this helps someone trying to do this in the future.

like image 188
LiquaFoo Avatar answered Oct 19 '22 20:10

LiquaFoo