Я работаю над отображением диаграмм Google Analytics на своем веб-сайте c # MVC с помощью Embed API, я использовал пример кода Google и ссылки по следующим ссылкам: https://ga -dev-tools.appspot.com / embed-api/ server-side-authorization / https://developers.google.com/analytics/devguides/reporting/core/v4/samples
Это мой код контроллера для аутентификации и получения токена доступа:
public ActionResult Index()
{
var credential = AthenticateGoogleAPI();
var accessToken = credential.GetAccessTokenForRequestAsync().Result;
ViewBag.AccessToken = accessToken;
return View();
}
public ServiceAccountCredential AthenticateGoogleAPI()
{
//google APIs Authenication
string[] scopes = new string[] { AnalyticsReportingService.Scope.Analytics }; // view and manage your Google Analytics data
var keyFilePath = Server.MapPath("~/Areas/Admin/Contents/XXXX-XXXXXXX.p12"); // Downloaded from https://console.developers.google.com
var serviceAccountEmail = "XXXXXX@XXXXXXX.iam.gserviceaccount.com"; // found https://console.developers.google.com
//loading the Key file
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new
ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
return credential;
}
Приведенный выше код работает нормально и корректно возвращает токен доступа,Это мой код просмотра:
HTML:
<div class="row">
<div id="chart-1-container"></div>
<div id="chart-2-container"></div>
</div>
Сценарии:
<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>
<script>
gapi.analytics.ready(function () {
/**
* Authorize the user with an access token obtained server side.
*/
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': '@ViewBag.AccessToken'
}
});
/**
* 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:XXXXXXXXX', // <-- 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();
/**
* Creates a new DataChart instance showing top 5 most popular demos/tools
* amongst returning users only.
* It will be rendered inside an element with the id "chart-3-container".
*/
var dataChart2 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:XXXXXXXXX', // <-- Replace with the ids value for your view.
'start-date': '30daysAgo',
'end-date': 'yesterday',
'metrics': 'ga:pageviews',
'dimensions': 'ga:pagePathLevel1',
'sort': '-ga:pageviews',
'filters': 'ga:pagePathLevel1!=/',
'max-results': 7
},
chart: {
'container': 'chart-2-container',
'type': 'PIE',
'options': {
'width': '100%',
'pieHole': 4/9,
}
}
});
dataChart2.execute();
});
</script>
Я получаю сообщение об ошибке в консоли браузера, и диаграммы не отображаются;ничего не видно на виду!Я запутался и не могу найти проблему, и мне нужна помощь ... это мои ошибки консоли developper, связанные с Google API:
![enter image description here](https://i.stack.imgur.com/gf0HO.png)
и
![enter image description here](https://i.stack.imgur.com/hoAVs.png)