Google People API在Web应用中失效,重复触发授权同意界面
Google People API Web应用授权循环问题解决
问题根源
你的代码中存在权限范围(Scope)不匹配的核心问题:
index.php请求的是联系人权限Google\Service\PeopleService::CONTACTSoauth2callback.php中却添加了云端硬盘只读权限Google\Service\Drive::DRIVE_METADATA_READONLY
这导致获取的Access Token没有访问联系人的权限,回到index.php时客户端判定无有效令牌,反复触发授权跳转,形成循环。
修正步骤
- 统一权限范围:将
oauth2callback.php中的Scope替换为联系人权限 - 更新废弃方法:把
setAuthConfigFile替换为当前推荐的setAuthConfig - 验证Redirect URI一致性:确保两处代码中的Redirect URI完全相同,且与Google Cloud控制台中配置的OAuth 2.0授权重定向URI一致
修正后的oauth2callback.php代码
<?php require_once __DIR__.'/vendor/autoload.php'; session_start(); $client = new Google\Client(); $client->setAuthConfig('credentials.json'); $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/gc-web/oauth2callback.php'); // 替换为正确的联系人权限范围 $client->addScope(Google\Service\PeopleService::CONTACTS); if (! isset($_GET['code'])) { $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); } else { $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/gc-web'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); } ?>
额外检查项
- 确认服务器已启用Session支持,
session_start()能正常工作 - 确保
credentials.json文件路径正确,且权限配置为Web应用类型(而非桌面/CLI应用)
内容的提问来源于stack exchange,提问作者Zain Farooq
相关产品推荐
相关产品推荐

