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

Google OAuth2如何获取用户邮箱?现有代码仅能获取令牌

解决方法

要在现有Google OAuth2流程中获取用户邮箱,只需两步修改:

1. 扩展OAuth授权范围

当前你的授权范围仅包含AdWords权限,需要添加获取用户邮箱的权限。修改SCOPE常量,加入https://www.googleapis.com/auth/userinfo.email(或简写email),多个范围用空格分隔:

private const SCOPE = 'https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/userinfo.email';

这会让用户在授权环节看到"查看您的电子邮件地址"的权限请求,只有用户同意后,后续才能获取邮箱信息。

2. 获取access token后调用用户信息API

拿到有效的access token后,向Google的用户信息接口发送请求,提取邮箱地址。在现有代码获取$accessToken之后添加以下代码:

// 调用Google用户信息API获取邮箱
$userInfoUrl = 'https://www.googleapis.com/oauth2/v2/userinfo';
$authHeader = "Authorization: Bearer {$accessToken}";

// 用cURL发送请求
$curl = curl_init($userInfoUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, [$authHeader]);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);

// 解析响应获取邮箱
$userInfo = json_decode($response, true);
$userEmail = $userInfo['email'] ?? '';

执行后$userEmail变量就会存储用户的邮箱地址。如果需要获取姓名等更多用户资料,还可以添加https://www.googleapis.com/auth/userinfo.profile到授权范围中。


内容的提问来源于stack exchange,提问作者Shibbir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:35:12