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:
Detail
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:
And no any console error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With