如何检索 "basic profile" 用户和 Google 已验证用户的电子邮件信息

How to retrieve user "basic profile" and email information for Google authenticated user

我正在为网站开发一个简单的 Google 登录集成。我需要用户能够单击按钮,使用 Google 进行身份验证,然后检索一些基本信息 - 姓名、ID 和电子邮件地址。我正在使用 PHP 来完成这项任务,因为它是我对该网站唯一真正的选择。

我一直在尝试使用 PHP API 发现的测试版 here and for the most part have gotten it to work by employing the example laid out here。该示例尝试为应用程序获取用户授权以访问 Drive 文件元数据,因此我需要更改范围以更适合我们需要的信息。我进行了以下调整,它似乎工作正常:

输出:

$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

在:

$client->addScope("email");

使用 Google 进行身份验证后,系统提示我授权应用程序获取基本个人资料信息和电子邮件访问权限。我现在遇到的问题是让应用程序实际检索它已被授权访问的信息。使用我正在使用的 PHP API 版本或 Google 本身提供的示例,我无法找到与我的场景类似的示例。

基本上我需要替换这个:

$drive_service = new Google_Service_Drive($client);
$files_list = $drive_service->files->listFiles(array())->getItems();
echo json_encode($files_list);

使用命令可以获取通过我们的应用程序使用 Google 进行身份验证的用户的姓名、ID 和电子邮件。

编辑: 收到以下答复。必须进行一些小的修改才能使其正常工作。

$google_oauthV2 = new Google_Service_Oauth2($client); [在 Google_Service_Oauth2]

之前添加 'new'

print_r($google_oauthV2->userinfo->get());[不喜欢dump(),改成print_r爆出结果]

通过深入挖掘源代码,我发现 Github - Google_Service_Oauth2.php

$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email',
          'https://www.googleapis.com/auth/plus.me'));
$google_oauthV2 = Google_Service_Oauth2($client);
dump($google_oauthV2->userinfo->get());