首先,請確保將設置訪問類型的刷新令牌抓取爲脫機。 然後創建一個單獨的頁面進行報告。 單獨的頁面應該爲所有報告使用帳戶ID和刷新令牌,並且如果它在令牌上給您一個錯誤,您可以自己刷新它,或者將它們發送回登錄頁面。
您只需申請一次憑證即可訪問所有帳戶。在PHP指南只使用第一個帳戶,但是你可以通過所有這些迭代,並獲得更多的
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/creds/client_secrets.json');
$client->setIncludeGrantedScopes(true);
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_Analytics::ANALYTICS_EDIT);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_Analytics($client);
$accounts=getAccountIds($analytics);
foreach($accounts as $acc)
{
var_dump($acc);
}
}
else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
記住憑據不是用戶的登錄名和密碼。這是一個刷新令牌,可讓您在將來訪問其帳戶。在這種情況下,服務帳戶不適用於您。這將是一個壞主意。我有一個教程系列,可能會幫助你開始。 http://www.daimto.com/google-development-beginners/ Dimi發佈的答案中的代碼應該可以工作。 – DaImTo
啊哈,這是我的問題 - 我沒有意識到使用令牌而不是憑據,謝謝 – Michal