Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - Google Analytics Embed API Server Side Authorization not rendering the charts with C#

I am trying to render charts using Server Side Authorization in C# but I am not able to do it.

Google has an example but based on Python and I need to build based on C# MVC: https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

I have created the Service Account and downloaded the JSON file:

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

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>

Nothing renders, and I get a diferent Token everytime I refresh the View, and all this erros in the console:

enter image description here

Detail

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I got finally get it running, the only thing a had to do (after hours of research) was to remove the {{ }} from access_token: property:

    gapi.analytics.ready(function () {

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

And I can get now a Google Analytics chart with no user's login at all:

enter image description here

And no any console error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...