首页 > 解决方案 > 如何获取用户当前认证用户的电子邮件地址?当前返回 null

问题描述

我想查看当前在我的 WebApp 中登录并通过身份验证的用户的电子邮件和个人资料名称。

我的应用程序的后端是 PHP,我目前正在使用官方的 google API PHP 客户端库并可以访问用户的 Google Drive 帐户。

为了获得名称,我一直在尝试通过 userinfo 端点。

$service = new Google_Service_Drive($client);
echo(serialize($googleOAuth->userinfo->get()->name) . '   ');

但是,这并没有给我当前返回空的用户电子邮件地址。

这些是我向用户请求的授权范围:

$client->setScopes(Google_Service_Drive::DRIVE);
$client->setScopes(Google_Service_Oauth2::USERINFO_EMAIL);
$client->setScopes(Google_Service_Oauth2::USERINFO_PROFILE);

我如何获得电子邮件?

编辑

我添加了范围:

$client->addScope('email');
$client->addScope('profile');

然后它与 Google_Service_Oauth2 对象一起工作。

标签: phpgoogle-apigoogle-drive-apigoogle-oauthgoogle-api-php-client

解决方案


我不建议为此使用 userinfo 端点,返回的数据并不总是返回。你应该去看看people api people.get

$service = new Google_Service_People($client);
$response = $service->people->get("people/me");

推荐阅读