我尝试在我的网站上显示Google Analytics数据,但使用服务器端授权。
Google演示展示了如何使用Python执行此操作,但我尝试使用PHP。 https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/
这是我的代码。我哪里错了?
提前致谢!
<?php
require_once( 'google-api-php-client-2.2.0/vendor/autoload.php' );
$accessToken = initializeAnalytics();
function initializeAnalytics()
{
$KEY_FILE_LOCATION = __DIR__ . 'analytics-serviceacc.json';
$client = new Google_Client();
$client->setApplicationName("My Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
$accessToken = $token['access_token'];
return $accessToken;
}
echo $accessToken;
?>
<!DOCTYPE html>
<html>
<head>
<title>Analytics Dashboard</title>
</head>
<body>
<script>
(function(w,d,s,g,js,fjs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
</script>
<div id="chart-1-container"></div>
<script>
gapi.analytics.ready(function() {
gapi.analytics.auth.authorize({
serverAuth: {
access_token: '<?php echo $accessToken ?>'
}
});
var dataChart = new gapi.analytics.googleCharts.DataChart({
query: {
ids: "XXXXXXXXXXX",
metrics: 'ga:sessions',
dimensions: 'ga:date',
'start-date': '30daysAgo',
'end-date': 'yesterday',
},
chart: {
container: 'chart-1-container',
type: 'LINE',
}
});
dataChart.execute();
});
</script>
</body>
</html>
检索访问令牌。但Google Analytics图表仍然无法显示。
但是我从谷歌那里得到了代码,所以应该有效吗?