Google Analytics嵌入Api服务器端授权C#

时间:2015-10-24 06:15:52

标签: c# google-analytics access-token

我正在尝试使用C#使用Google Analytics Embed API服务器端授权,代码如下

  public ActionResult Dashboard()
    {
        ViewBag.Message = "Dashboard.";
        var scopes = new string[]
        {
            AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data
            AnalyticsService.Scope.AnalyticsReadonly,
            AnalyticsService.Scope.AnalyticsEdit
        };
        const string serviceAccountEmail = "526261635050-fofbfeicvbpgumafa114te878787878@developer.gserviceaccount.com";  
        const string keyFilePath = @"D:\key.p12";

        var status = RequestAccessTokenAsync(keyFilePath,scopes,serviceAccountEmail);
        ViewBag.Token = _accessToken;

        return View();
    }

    private async Task<bool> RequestAccessTokenAsync(string certificateFile, string[] scope, string serviceAccount)
    {
        var certificate = new X509Certificate2(certificateFile, "notasecret", X509KeyStorageFlags.Exportable);
        var serviceAccountCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccount)
        {
            Scopes = scope
        }.FromCertificate(certificate));

        var status = await serviceAccountCredential.RequestAccessTokenAsync(CancellationToken.None);
        if (status)
            _accessToken = serviceAccountCredential.Token.AccessToken;
        return status;
    }

使服务实例工作正常并且还能够获取原始数据但我们需要使用Embed API,问题是_accessToken中没有检索到值,我们需要能够访问嵌入式API。

任何想法/想法都会有所帮助。

在google演示网站上,提供的示例适用于python - https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

1 个答案:

答案 0 :(得分:2)

试试这个:

public ActionResult Dashboard()
{
    ViewBag.Message = "Dashboard.";
    var scopes = new string[]
    {
        AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data
        AnalyticsService.Scope.AnalyticsReadonly,
        AnalyticsService.Scope.AnalyticsEdit
    };
    const string serviceAccountEmail = "526261635050-fofbfeicvbpgumafa114te878787878@developer.gserviceaccount.com";  
    const string keyFilePath = @"D:\key.p12";

    var certificate = new X509Certificate2(certificateFile, "notasecret", X509KeyStorageFlags.Exportable);
    var serviceAccountCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        Scopes = scope
    }.FromCertificate(certificate));

    Task<string> task = ((ITokenAccess)serviceAccountCredential).GetAccessTokenForRequestAsync();
    task.Wait();
    var _accessToken = task.Result;

    ViewBag.Token = _accessToken;

    return View();
}