我需要检索Google服务帐户的访问令牌,然后我会使用该令牌从Google Analytics获取结果。我已经用PHP做过了,但我在使用.NET时遇到了困难,我使用了Google Docs中的一个例子,但我遇到了一些问题。这是代码:
private static String ACTIVITY_ID = "1111111";
public static void Test()
{
Console.WriteLine("Plus API - Service Account");
Console.WriteLine("==========================");
String serviceAccountEmail = "*@developer.gserviceaccount.com";
var certificate = new X509Certificate2(System.Web.Hosting.HostingEnvironment.MapPath("~/*.p12"), "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { PlusService.Scope.PlusMe }
}.FromCertificate(certificate));
// Create the service.
var service = new PlusService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Plus API Sample",
});
Activity activity = service.Activities.Get(ACTIVITY_ID).Execute();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
它在线上崩溃了:
Activity activity = service.Activities.Get(ACTIVITY_ID).Execute();
出现以下错误:
Google.Apis.Requests.RequestError
Not Found [404]
Errors [
Message[Not Found] Location[ - ] Reason[notFound] Domain[global]
]
为了获得令牌,我错过了什么或做错了什么?此外,ACTIVITY_ID
是从Google Analytics中的视图中获取的ID还是其他内容?
答案 0 :(得分:1)
可能与this问题大致相同,您需要设置User
属性:
var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
{
Scopes = new[] { "https://www.googleapis.com/somescope" },
User = "theuser@gmail.com"
}.FromPrivateKey(cr.private_key));