您的問題的最佳答案是說不要使用該教程。該教程極其過時並使用舊的PHP-client-Lib,這已報告給Google。
PHP客戶端庫
的谷歌PHP客戶端庫的最新版本可以在Github上找到。 google-api-php-client每當有任何更改時,這個客戶端庫會定期更新。您需要將整個src/Google目錄複製到您的應用程序的目錄中。除非你真的知道你在做什麼,否則我不建議只採取你需要的文件。
的oauth2
有3個步驟的oauth2這就是爲什麼它被稱爲3條腿的認證。在第一步中,您要求用戶爲您提供訪問權限,第二步是用戶爲您提供訪問權限,第三步和最後一步是您交換用戶訪問數據的訪問權限。
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>
此代碼是直接從我的教程撕開:Google Oauth2 PHP - Google Analytics API的教程保持最新。如果這篇文章比較陳舊,你可能想看看代碼中是否有任何改變。
該教程是日期的出路,試試這個:http://www.daimto.com/google-oauth2-php/ – DaImTo 2014-10-01 06:17:42