1

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:

  • Created a brand new project in Google Developer Console.
  • Enabled Google Analytics API.
  • Create a "Service Account" Client ID.
  • Take note the "Client ID" the certificate and its password.
  • Add the Service Account "Email address" as a user with full permission on Google Analytics Account.

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?

Maxime Labelle
  • 3,609
  • 2
  • 27
  • 48

2 Answers2

1

You can find the solution here

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

Community
  • 1
  • 1
Amine Jallouli
  • 3,919
  • 8
  • 36
  • 73
0

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.

jk.
  • 14,365
  • 4
  • 43
  • 58