1

I have a database with some google analytics data from our clients. I have three values: AuthKeyId, ProfileId and AnalyticsID. How can I use this data to get the data from google?

Here's the code I tried but I'm getting unauthorized error message:

    string authToken = "XXxXXxxx_XXX_xxxx...."; // this seems to be wrong

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

    string ids = "ga:XXXXXXX";       // this is the ID, the correct one
    string metrics = "ga:pageviews";
    string startDate = "2013-06-25";
    string endDate = "2013-07-25";

    //Optional:
    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);
user3043457
  • 523
  • 1
  • 5
  • 16

2 Answers2

1

Google analytics auth tokens do not last forever. The have to be renewed. If what you have there is a refresh token, they don't expire unless the user that granted permission revokes access.

The best way to go is with a service account as @Petr is suggested.

There are a few more steps to creating the service account and generating the .p12 file you will need. You can follow the directions for setting up a service account here: Connecting to Google Analytics API in a Rails app

Google's code examples seem to be lacking in the c# arena but I did find this post: How do I use a Service Account to Access the Google Analytics API V3 with .NET C#?

Community
  • 1
  • 1
jk.
  • 14,365
  • 4
  • 43
  • 58
0

Create a project in Google API Console, which Google actually requires (also noted in the GA docs):

  1. Register your application in the Google Developers Console.
  2. Authorize access to Google Analytics data.
  3. Create an Analytics service object.

Hope this helps!

Petr Havlik
  • 3,307
  • 1
  • 19
  • 17