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

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

谷歌有一个例子,但基于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 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 task = ((ITokenAccess)credential).GetAccessTokenForRequestAsync(); task.Wait(); var bearer = task.Result; ViewBag.Token = bearer; } catch (AggregateException ex) { throw ex.InnerException; } return View(); } } 

视图

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

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

在此处输入图像描述

详情

在此处输入图像描述

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

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

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

在此处输入图像描述

并没有任何控制台错误。