我正在尝试使用Google People API,它允许我检索用户的联系人。这是我的代码:
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setClientId('OMITTED');
$client->setClientSecret('OMITTED');
$client->setRedirectUri($scriptUri);
//$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/contacts.readonly', 'profile'));
if (isset($_GET['oauth'])) {
// Start auth flow by redirecting to Google's auth server
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else if (isset($_GET['code'])) {
// Receive auth code from Google, exchange it for an access token, and
// redirect to your base URL
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
} else if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// You have an access token; use it to call the People API
$client->setAccessToken($_SESSION['access_token']);
$people_service = new Google_Service_People($client);
$connections = $people_service->people->get('people/me');
// TODO: Use service object to request People data
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/?oauth';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
调用$ connections行时,抛出以下错误:
未捕获的异常'Google_Service_Exception',显示消息'错误呼叫GET https://people.googleapis.com/v1/people/me :( 403)来电者无权请求“人/我”。请求需要以下范围之一:[个人资料,https://www.googleapis.com/auth/plus.login]。
由于范围设置在上面,我无法弄清楚错误发生的原因。
感谢所有帮助!
答案 0 :(得分:0)
我刚使用你的代码而没有问题。我的猜测是$_SESSION['access_token']
包含一个访问令牌,该令牌没有授权的正确范围。再次通过身份验证流程,以确保获得具有正确授权范围的新访问令牌。