【问题标题】:Google Analytics Embed Api Server-side authorization C#Google Analytics Embed Api 服务器端授权 C#
【发布时间】:2016-01-23 17:52:41
【问题描述】:

我正在尝试使用 C# 使用 Google Analytics Embed API Server Side 授权,代码如下

  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;
    }

创建一个 Service 实例可以正常工作,并且还能够获取原始数据,但我们需要使用 Embed API,问题是在 _accessToken 中没有检索到值,我们需要能够访问嵌入的API。

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

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

【问题讨论】:

标签: c# google-analytics access-token


【解决方案1】:

试试这个:

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();
}

【讨论】:

    猜你喜欢
    • 2015-10-20
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2013-07-23
    相关资源
    最近更新 更多