如何使用谷歌访问令牌获取用户电子邮件?

2022-08-31 00:30:07

我遵循了所有这些步骤。

https://developers.google.com/+/web/signin/

我有客户端 ID 和客户端密码。

我现在获得了访问令牌,如何获取用户配置文件和包含访问令牌的电子邮件?以及如何检查用户是否登录?


答案 1

使用 OAuth2,您可以通过 scope 参数请求权限。(文档。我想你想要的范围是 https://www.googleapis.com/auth/userinfo.emailhttps://www.googleapis.com/auth/userinfo.profile 的。

然后,获取访问令牌后,获取配置文件信息就很简单了。(我假设您已经能够将返回的授权代码兑换为访问令牌?只需向 https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken} 发出 get 请求,该请求将返回配置文件数据的 JSON 数组,包括电子邮件:

{
    "id": "00000000000000",
    "email": "fred.example@gmail.com",
    "verified_email": true,
    "name": "Fred Example",
    "given_name": "Fred",
    "family_name": "Example",
    "picture": "https://lh5.googleusercontent.com/-2Sv-4bBMLLA/AAAAAAAAAAI/AAAAAAAAABo/bEG4kI2mG0I/photo.jpg",
    "gender": "male",
    "locale": "en-US"
}

没有保证,但试试这个:

$url = "https://www.googleapis.com/oauth2/v1/userinfo";
$request = apiClient::$io->makeRequest($client->sign(new apiHttpRequest($url, 'GET')));

if ((int)$request->getResponseHttpCode() == 200) {
    $response = $request->getResponseBody();
    $decodedResponse = json_decode($response, true);
    //process user info
  } else {
    $response = $request->getResponseBody();
    $decodedResponse = json_decode($response, true);
    if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
      $response = $decodedResponse['error'];
    }
  }
}

答案 2

试试这个

$accessToken = 'access token';
$userDetails = file_get_contents('https://www.googleapis.com/oauth2/v1/userinfo?access_token=' . $accessToken);
$userData = json_decode($userDetails);

if (!empty($userData)) {

  $googleUserId = '';
  $googleEmail = '';
  $googleVerified = '';
  $googleName = '';
  $googleUserName = '';

  if (isset($userData->id)) {
    $googleUserId = $userData->id;
  }
  if (isset($userData->email)) {
    $googleEmail = $userData->email;
    $googleEmailParts = explode("@", $googleEmail);
    $googleUserName = $googleEmailParts[0];
  }
  if (isset($userData->verified_email)) {
    $googleVerified = $userData->verified_email;
  }
  if (isset($userData->name)) {
    $googleName = $userData->name;
  }
} else {

  echo "Not logged In";
}