How do I retrieve user's email from Google

梦想的初衷 提交于 2021-01-27 03:51:38

问题


I am using the Google client library in PHP.
I am successfully authenticated.
Missing a simple thing (I added the right scope). How do I retrieve the user's email after I finish the auth process.
Below is what I have:

$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 ?????????

I am using the PHP library here: https://code.google.com/p/google-api-php-client/wiki/OAuth2


回答1:


Much more simple, you can do it like this:

$user = $service->userinfo->get();

echo $user->name;
echo $user->id;
echo $user->email;
echo $user->link;
echo $user->picture;



回答2:


oops, just found it:

$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);



回答3:


$plus = new Google_Service_Plus($client);
$person = $plus->people->get('me');
$email = ($person['emails'][0]['value']);

For this to work, also don't forget scopes:

$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);



回答4:


Google OAuth 2 - Get User Email

$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;

Update: Seems like this is available only during valid "access token" (first login).

If you have setAccessType("offline") and setApprovalPrompt("auto"), then "name" property will not be later available and you need to use Google Plus like mentioned in above posts.



来源:https://stackoverflow.com/questions/23935913/how-do-i-retrieve-users-email-from-google

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!