Google Analytics嵌入API服务器端授权不使用C#呈现图表

时间:2017-01-28 00:19:43

标签: javascript c# asp.net-mvc google-analytics google-oauth

我正在尝试使用C#中的服务器端授权来呈现图表,但我无法做到。

Google有一个例子,但基于Python,我需要基于C#MVC构建: https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

我创建了服务帐户并下载了JSON文件:

的Controler

public class StatsController : Controller
{
    // GET: Stats
    public async Task<ActionResult> Index()
    {
        var json = "C:\\temp\\client_secrets.json";

        string[] scopes = new string[] { AnalyticsReportingService.Scope.AnalyticsReadonly }; // Put your scopes here

        var stream = new FileStream(json, FileMode.Open, FileAccess.Read);

        var credential = GoogleCredential.FromStream(stream);
        credential = credential.CreateScoped(scopes);

        try
        {
            Task<string> task = ((ITokenAccess)credential).GetAccessTokenForRequestAsync();
            task.Wait();
            var bearer = task.Result;

            ViewBag.Token = bearer;
        }
        catch (AggregateException ex)
        {
            throw ex.InnerException;
        }

        return View();
    }
}

查看

<script>
(function(w,d,s,g,js,fs){
  g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
  js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
  js.src='https://apis.google.com/js/platform.js';
  fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>

<div id="chart-1-container"></div>

<script>

gapi.analytics.ready(function() {

  /**
   * Authorize the user with an access token obtained server side.
   */
  gapi.analytics.auth.authorize({
    'serverAuth': {
      'access_token': '{{ @ViewBag.Token }}'
    }
  });


  /**
   * Creates a new DataChart instance showing sessions over the past 30 days.
   * It will be rendered inside an element with the id "chart-1-container".
   */
  var dataChart1 = new gapi.analytics.googleCharts.DataChart({
    query: {
      'ids': 'ga:XXXX', // <-- Replace with the ids value for your view.
      'start-date': '30daysAgo',
      'end-date': 'yesterday',
      'metrics': 'ga:sessions,ga:users',
      'dimensions': 'ga:date'
    },
    chart: {
      'container': 'chart-1-container',
      'type': 'LINE',
      'options': {
        'width': '100%'
      }
    }
  });
  dataChart1.execute();

});
</script>

什么都没有呈现,每次刷新View时都会得到一个不同的令牌,以及控制台中的所有这些错误:

enter image description here

详细

enter image description here

1 个答案:

答案 0 :(得分:9)

我终于让它运行了,唯一需要做的事情(经过数小时的研究)就是从access_token中删除{{}}:property:

    gapi.analytics.ready(function () {

        gapi.analytics.auth.authorize({
            serverAuth: {
                access_token: '@ViewBag.Token'
            }
        });
    });

我现在可以获得一个完全没有用户登录的Google Analytics图表:

enter image description here

没有任何控制台错误。