簡體   English   中英

Google Analytics嵌入Api服務器端授權C#

[英]Google Analytics Embed Api Server-side authorization C#

我正在嘗試使用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。

任何想法/想法都會有所幫助。

在谷歌演示網站上,提供的示例是針對python的 - https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

試試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM