I've 'googled' the life out of this issue today with zero resolve!
I am trying to build a very simple Google Analytics data request console app using a Service account. I have set up all the required details in the Google Developers Console but I am getting the following error:
An unhandled exception of type 'Google.Apis.Auth.OAuth2.Responses.TokenResponseException'
occurred in Google.Apis.dll
Additional information: Error:"invalid_grant", Description:"", Uri:""
Below is the code in my console app (with keys hidden):
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Analytics;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using System;
namespace GoogleAnalyticsAPI
{
public class Program
{
public static void Main(string[] args)
{
string profileId = "12345678";
string serviceAccountEmail = "123456789abcdefghijklmnopq@developer.gserviceaccount.com";
X509Certificate2 certificate = new X509Certificate2(@"PrivateKey.p12", "mypassword", X509KeyStorageFlags.Exportable);
// Create credentials
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
// Create the service
var service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Google Analytics API"
});
string startDate = "2014-07-01";
string endDate = "2010-07-31";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(string.Format("ga:{0}", profileId), startDate, endDate, "ga:visits, ga:newVisits");
request.Dimensions = "ga:city";
GaData data = request.Execute();
}
}
}
Any help here would be greatly appreciated!
Note, here are some sources I've followed:
It turns out I had the wrong credentials, if anyone else has the same problem:
.p12
file is located in your debug folder and you supply the correct private key password (given to you when you create your service account).