Google Analytics Embed API php Авторизация на стороне сервера

В настоящее время я работаю над добавлением диаграмм Google Analytics в мою панель администратора.
Настройте учетную запись службы на console.developers.google.com и загрузите файл ключей json. Проблема в том, что я получаю ошибку «Invalid Credentials».

предварительный просмотр ошибок:
https://i.gyazo.com/7037c8ce12b6c18ff2c1a83f153891b6.png

PHP:

$credentials_file = BASE_PATH.'cms/xxxxxx-224915-f1a6ced8529f.json';
$client = new Google_Client();
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$client->setAuthConfig($credentials_file);
$client->useApplicationDefaultCredentials();
$client->fetchAccessTokenWithAssertion();
$accesstoken = $client->getAccessToken();
echo '<pre>';
print_r($accesstoken);
echo '</pre>';
$accesstoken = $accesstoken['access_token'];

результат из print_r:

Array
(
[access_token] => ya29.c.ElltBmCiGHIaslfJVEh1RYQ6xl5hpDs4IPDa-Lfqiv4VRMNUDYmZB97m7TXdmwe4fcM7XnepK2TLv5o10Jtopy1jvWRV769QG7hNoPU4nqWrkzsAVsxBgmb8nQ
[expires_in] => 3600
[token_type] => Bearer
[created] => 1544375409
)

JavaScript + HTML:

<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>
<div id="chart-2-container"></div>
<script>

gapi.analytics.ready(function() {

/**
* Authorize the user with an access token obtained server side.
*/
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': '{{<?php echo $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:186343526', // <-- 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:186343526', // <-- 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>

Протестировал токен доступа по указанному ниже URL-адресу, и, похоже, он работает нормально.
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=

{
"issued_to": "105249894857195252623",
"audience": "105249894857195252623",
"scope": "https://www.googleapis.com/auth/analytics.readonly",
"expires_in": 3127,
"access_type": "offline"}

0

Решение

быстрое решение было:

  gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': '<?php echo $accesstoken["access_token"]; ?>'
}
});
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector