Google Analytics API 3 - Error: "invalid_grant", Description: ", Uri:" "
I got rid of this zero reputation issue today!
I am trying to create a very simple Google Analytics Data Query Console application using a service account. I have installed 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 hidden keys):
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 of the following sources:
+3
source to share
1 answer
It turns out I had the wrong credentials, in case anyone else has a problem:
- Double check that you are using a service account ending with "@ developer.gserviceaccount.com"
- Verify that the downloaded file
.p12
is in your debug folder and you are supplying the correct secret key password (given to you when you created your service account).
+9
source to share