11

I've got credentials of an account with access to Google Analytics,

I'm looking to utilise the Analytics Core Reporting API http://code.google.com/apis/analytics/docs/gdata/home.html

I've found examples which use username/password calling setUserCredentials, but have seen comments this is less secure/has a low request limit (And doesn't exist in the lastest client).

Plus I've seem examples which use oauth, but require user interaction and grant access to the users google account.

However I'm looking to run a service which doesn't require any user interaction, and connects to a predefined google account (un-related to the user viewing it).

I can then store the results in a database, and end users can query the results from the database.

I've seen information about using AccessType = Offline when you first login, which then returns an access token and a refreshtoken. http://code.google.com/apis/accounts/docs/OAuth2WebServer.html#offline

In my example though, the end user will never login to the application. Could I have a seperate admin application which gets a refresh token, and stores the refresh token in the config/lookup table? Then the main application can use the refresh token pulling from the config/lookup table, and get an access token to be able to query the Google Analytics account.

I'm looking for a C# example which uses AccessType = Offline, and seperates out the fetching of the refresh token and using the refresh token to get an access token to query the google analytics account.

Ian
  • 1,619
  • 1
  • 14
  • 23

4 Answers4

16

Create your app https://code.google.com/apis/console/

For you App, turn on access to Google Analytics, and create an OAuth 2.0 client ID for your website.

Browse to:

https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=YOUR_APP_ID.apps.googleusercontent.com&access_type=offline&scope=https://www.googleapis.com/auth/analytics.readonly&redirect_uri=HTTP://YOUR_CALL_BACK_URL

Having changed YOUR_APP_ID, YOUR_CALL_BACK_URL to the relevant values.

Important to include access_type=offline.

Press Grant Access, this will redirect to HTTP://YOUR_CALL_BACK_URL?code=THIS_IS_YOUR_CODE. Copy the code in the URL.

With the code, request the Refresh Token using CMD prompt.

curl -d "code=THIS_IS_YOUR_CODE&client_id=YOUR_APP_ID.apps.googleusercontent.com&client_secret=YOUR_APPS_SECRET_CODE&redirect_uri=HTTP://YOUR_CALL_BACK_URL&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token

Having changed THIS_IS_YOUR_CODE, YOUR_APP_ID, YOUR_APPS_SECRET_CODE, YOUR_CALL_BACK_URL to the relevant values.

Record the refresh_token returned.

Download the latest version of the Core Reporting V3.0 .net libraries http://code.google.com/p/google-api-dotnet-client/wiki/Downloads

There is a bug in the current version of Google.Apis.Analytics.v3.cs, to fix this copy the code in this file to your local solution (And don’t reference Google.Apis.Analytics.v3.bin) http://code.google.com/p/google-api-dotnet-client/source/browse/Services/Google.Apis.Analytics.v3.cs?repo=samples&name=20111123-1.1.4344-beta

And change the property Dimensions from a List<system.string> to a string.

Or you'll get an error like me and this guy did http://www.evolutiadesign.co.uk/blog/using-the-google-analytics-api-with-c-shar/

You can then use your Refresh Token, to generate you an Access Token without user interaction, and use the Access Token to run a report against Google Analytics.

using System;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using AnalyticsService = Google.Apis.Analytics.v3.AnalyticsService;

class Program
    {
        public static void Main()
        {
            var client = new WebServerClient(GoogleAuthenticationServer.Description, "YOUR_APP_ID.apps.googleusercontent.com", "YOUR_APPS_SECRET_CODE");
            var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate);
            var asv = new AnalyticsService(auth);
            var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
            request.Dimensions = "ga:pagePath";
            request.Sort = "-ga:visitors";
            request.MaxResults = 5;
            var report =  request.Fetch();
            Console.ReadLine();
        }

        private static IAuthorizationState Authenticate(WebServerClient client)
        {
            IAuthorizationState state = new AuthorizationState(new string[]{}) { RefreshToken = "REFRESH_TOKEN" };

            client.RefreshToken(state);
            return state;
        }
    }
Ian
  • 1,619
  • 1
  • 14
  • 23
  • Ian, I'm stuck on this very same thing. Do you have a working, complete example by any chance? – Sam Delaney May 07 '12 at 07:01
  • Which OAuth clientid model is to be used in this case? I tried with a client Id for web applications and with the Client Id for installed applications to no avail... – t3rse Aug 07 '12 at 23:10
  • 1
    I am tying to use the code you wrote, but when i am trying to compile this, is fails. It gives me the following erorr: Error 2 Argument 1: cannot convert from 'Google.Apis.Authentication.OAuth2.OAuth2Authenticator' to 'Google.Apis.Services.BaseClientService.Initializer' H:\vs12\ManagementAPI\ManagementAPI\Models\Value.cs 27 44 ManagementAPI – Edo Post Mar 27 '13 at 20:04
  • 1
    it fails on the following line: var asv = new AnalyticsService(auth); the auth is this: var auth = new OAuth2Authenticator(client, Authenticate); Witch is called before the first statementd (as in the code above) – Edo Post Mar 27 '13 at 21:01
  • 1
    this works :var auth = new OAuth2Authenticator(client, Authenticate); var initialzr = new Google.Apis.Services.BaseClientService.Initializer(); initialzr.Authenticator = auth; var asv = new Google.Apis.Analytics.v3.AnalyticsService(initialzr); – Matan L Oct 29 '13 at 15:49
  • 1
    You can also use https://developers.google.com/oauthplayground/ to get the refresh token – LeZuse Jan 13 '14 at 07:10
  • Hello! Thanks for explaining. I'm having the same problem i think but i'm not sure what part of your code is relevant to fix this issue. Iv'e posted my problem here: http://stackoverflow.com/questions/22144085/error-could-not-load-type-google-apis-authentication-iauthenticator-from-asse Thank you – WhoAmI Mar 03 '14 at 14:35
4

Great Answer Ian and it helped me to get going in the correct Direction more than any other answer I could find online. Something must have changed in the AnalyticsService object because the line:

var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");

did not work for me and I had to use the following:

var request = asv.Data.Ga.Get("ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID", "2012-01-01", "2012-02-20", "ga:visitors");

Hopefully this will help others like your answer helped me. Thanks!

Ryan Drost
  • 1,184
  • 10
  • 19
1

Ian's answer helped me a lot but I kept getting an error running the curl command. Did some research and found that the steps to get the access code and refresh token can be made easier by going to https://code.google.com/oauthplayground/ and checking your oAuth configuration settings. Top right of the page there is a settings button. selected "Use your own OAuth credentials". You can get your access code and request a refresh token all from here.

Hope this helps.

Cam
  • 166
  • 3
  • 11
0

You can manually get a refresh token from the OAuth Playground. If you are needing a refresh token for a Service Account as I was, make sure you

  1. Click on the settings on the right.
  2. Check Use your own OAuth credentials
  3. Fill in your Client ID and Secret
  4. Close the settings
  5. Click the Refresh button on step 2
  6. Then save the refresh token for use in your app
Josh C
  • 7,461
  • 3
  • 24
  • 21