1
我想創建一個儀表板的谷歌分析數據,但我不知道我怎麼能結合腳本。谷歌分析如何獲取訪問令牌與服務器到服務器OAuth與PHP
我必須使用服務器到服務器的身份驗證這樣https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-php但我無法獲得訪問令牌我的JavaScript驗證
gapi.analytics.auth.authorize({
serverAuth: {
access_token: >>How to get an Access token from PHP<<
}
});
如果我只是做這樣的事情
$KEY_FILE_LOCATION = __DIR__ . '/Service.json';
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
var_dump($client->getAccessToken())
我的getAccessToken始終爲NULL是否有任何其他方法來接收服務器到服務器連接的訪問令牌?我必須找到不需要通過Javascript登錄的方法,因爲所有來自內容管理系統的後端用戶都應該能夠看到數據。
非常感謝。我是新手,如果你能解釋它是如何工作的,而不僅僅是發送鏈接
編輯:換句話說,這是我的整個代碼......爲什麼它不起作用, 哪裏不對?請幫我
<?php
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
$accessToken = initializeAnalytics();
function initializeAnalytics()
{
$KEY_FILE_LOCATION = __DIR__ . '/Service.json';
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$accessToken = $client->getAccessToken();
return $accessToken;
}
?>
<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: "ga:128053216",
metrics: 'ga:sessions',
dimensions: 'ga:date',
'start-date': '30daysAgo',
'end-date': 'yesterday',
},
chart: {
container: 'chart-1-container',
type: 'LINE',
}
});
dataChart.execute();
});
</script>
你需要做一個請求,我認爲它會取一個新的前訪問令牌。嘗試並讓PHP提出請求。 – DaImTo
你能舉個例子嗎?我有點失落。 –