如何检索用户'来自谷歌的电子邮件



我使用的是PHP中的Google客户端库
我已成功通过身份验证
缺少一件简单的事情(我添加了正确的范围(。如何检索我完成身份验证过程后用户的电子邮件
以下是我所拥有的:

$client = new Google_Client();
$client->setClientId(MYCLIENTID);
$client->setClientSecret(MYSECRET);
$client->setRedirectUri(SOMEURLINMYSYSTEM);
$service = new Google_Service_Oauth2($client);
$client->addScope(Google_Service_Oauth2::USERINFO_EMAIL);
$client->authenticate($_GET['code']);//I have the right code, and I am being authenticated
//TODO Get from google the user's email ?????????

我在这里使用PHP库:https://code.google.com/p/google-api-php-client/wiki/OAuth2

oops,刚刚找到它:

$client = new Google_Client();
$client->setClientId(MYCLIENTID);
$client->setClientSecret(MYSECRET);
$client->setRedirectUri(SOMEURLINMYSYSTEM);
$service = new Google_Service_Oauth2($client);
$client->addScope(Google_Service_Oauth2::USERINFO_EMAIL);
$client->authenticate($_GET['code']);//I have the right code, and I am being authenticated
$client->authenticate($code);
$plus = new Google_Service_Plus($client);
$person = $plus->people->get('me');
var_dump($person);

更简单的是,您可以这样做:

$user = $service->userinfo->get();
echo $user->name;
echo $user->id;
echo $user->email;
echo $user->link;
echo $user->picture;
$plus = new Google_Service_Plus($client);
$person = $plus->people->get('me');
$email = ($person['emails'][0]['value']);

为了实现这一点,也不要忘记范围:

$client->addScope('https://www.googleapis.com/auth/userinfo.email');
$client->addScope('https://www.googleapis.com/auth/userinfo.profile');
// $client->addScope(Google_Service_Plus::PLUS_ME);

Google OAuth 2-获取用户电子邮件

$client = new Google_Client();
$client->addScope(Google_Service_Plus::USERINFO_EMAIL);
$client->addScope(Google_Service_Plus::USERINFO_PROFILE);
$tokeninfo = $client->verifyIdToken();
echo $tokeninfo->name;
echo $tokeninfo->email;

更新:似乎只有在有效的"访问令牌"(首次登录(期间才可用。

如果你有setAccessType("offline"(和setApprovalPrompt("auto"(,那么"name"属性稍后将不可用,你需要使用上面文章中提到的Google Plus。

相关内容

  • 没有找到相关文章

最新更新