如何从Google检索用户的电子邮件

时间:2014-05-29 14:33:53

标签: php oauth google-api google-oauth

我在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

4 个答案:

答案 0 :(得分:5)

哎呀,刚刚找到它:

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

答案 1 :(得分:4)

更简单,你可以这样做:

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

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

答案 2 :(得分:2)

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

答案 3 :(得分:0)

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。