javascript - Google Analytics Embed API 服务器端授权不使用 C# 呈现图表

标签 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 文件:

Controller

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 时我都会得到一个不同的 token ,并且控制台中出现所有这些错误:

enter image description here

细节

enter image description here

最佳答案

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

    gapi.analytics.ready(function () {

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

我现在可以在没有用户登录的情况下获得 Google Analytics 图表:

enter image description here

并且没有任何控制台错误。

关于javascript - Google Analytics Embed API 服务器端授权不使用 C# 呈现图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41905074/

相关文章:

javascript - 无法正确导出 D3 图表

javascript - 如何将文本行分解为 Javascript confirm()?

javascript - 解决数据库中转义字符的最佳方法

c# - TPL Dataflow,仅在所有源数据 block 完成时保证完成

c# - StreamWriter 在系统突然关闭时在文件末尾写入 NUL 字符

c# - 将参数传递给工作?

javascript - 将下拉列表更改为其原始状态

c# - 如果文件存在于 asp.net mvc 中,则返回链接

javascript - JavaScript 新手 : Can I pass a List into this function and have it still work?

asp.net-mvc - 从 FormCollection 元素获取多个复选框