Maxime Labelle
Maxime Labelle

Reputation: 3639

Using GoogleAnalytics with a Service Account

I'm trying to use the Google.Apis.Analytics.v3 client Library to retrieve metrics and I would like to work with a Service Account.

According to the documentation and several questions here on StackOverflow, I assume this should work. I have already used Service Accounts in the past against the Google BigQuery and Google Cloud Storage APIs, so I thought I could make it to work quite easily.

Unfortunately, each time I perform an operation against Google Analytics, I receive the following error:

TokenResponseException: Additional information: Error:"invalid_grant", Description:"", Uri:""

For the record, here what I have done:

Here is the code I'm using to connect to Google Analytics:

private static AnalyticsService ConnectServiceAccount()
{
    const string serviceAccountId = "xxxxxxxxxx-xxxxxxxxxxxx.apps.googleusercontent.com";
    const string serviceAccountCertificate = "xxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12";
    const string applicationName = "";

    var certificate = GetServiceAccountCertificate(serviceAccountCertificate);
    var credentials = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountId)
    {
        Scopes = new[] {
            AnalyticsService.Scope.Analytics,
            AnalyticsService.Scope.AnalyticsEdit,
            AnalyticsService.Scope.AnalyticsManageUsers,
            AnalyticsService.Scope.AnalyticsProvision,
            AnalyticsService.Scope.AnalyticsReadonly
        },
    }.FromCertificate(certificate)
        );

    var service =
        new AnalyticsService(
            new BaseClientService.Initializer
            {
                GZipEnabled = true,
                HttpClientInitializer = credentials,
            });
    return service;
}

Can someone help me troubleshoot this issue?

Upvotes: 1

Views: 374

Answers (2)

Amine Jallouli
Amine Jallouli

Reputation: 3949

You can find the solution here

The service account is an email address which is like @developer.gserviceaccount.com

Upvotes: 1

jk.
jk.

Reputation: 14435

Looks like you are using the wrong serviceAccountID. It should be the one ending in @developer.gserviceaccount.com

And, you only need to give that email Read and Analyze rights not full control in your analytics account.

I also thought it needed an applicationName. This is the app name in your GA console.

Upvotes: 0

Related Questions