Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 949
Patrick Avatar asked Jan 28 '17 00:01

Patrick


1 Answers

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.

like image 72
Patrick Avatar answered Oct 13 '22 18:10

Patrick