You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google People API在Web应用中失效,重复触发授权同意界面

Google People API Web应用授权循环问题解决

问题根源

你的代码中存在权限范围(Scope)不匹配的核心问题:

  • index.php请求的是联系人权限Google\Service\PeopleService::CONTACTS
  • oauth2callback.php中却添加了云端硬盘只读权限Google\Service\Drive::DRIVE_METADATA_READONLY

这导致获取的Access Token没有访问联系人的权限,回到index.php时客户端判定无有效令牌,反复触发授权跳转,形成循环。

修正步骤

  1. 统一权限范围:将oauth2callback.php中的Scope替换为联系人权限
  2. 更新废弃方法:把setAuthConfigFile替换为当前推荐的setAuthConfig
  3. 验证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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:06:24