php Google oAuth2 -如何获取用户电子邮件地址

bweufnob  于 2022-12-17  发布在  PHP
关注(0)|答案(1)|浏览(172)

使用下面的代码我可以获得访问和刷新令牌:

private const SCOPE                 = 'https://www.googleapis.com/auth/adwords';
private const AUTHORIZATION_URI     = 'https://accounts.google.com/o/oauth2/v2/auth';
private const OAUTH2_CALLBACK_PATH  = '';
private const REDIRECT_URL          = 'http://localhost:3000/google/google-ads/confirmed';

$code           = $request->input('code');
$scope          = $request->input('scope');
$state          = $request->input('state');
$project_token  = $request->input('project_token');
$project_name   = $request->input('project_name');
$account_name   = $request->input('account_name');
$account_id     = $request->input('account_id');

$clientId       = 'my-client-id--kh3el.apps.googleusercontent.com';
$clientSecret   = 'my-clicent-secret4cCm';
$redirectUrl    = self::REDIRECT_URL;

$oauth2 = new OAuth2(
    [
        'clientId'              => $clientId,
        'clientSecret'          => $clientSecret,
        'authorizationUri'      => self::AUTHORIZATION_URI,
        'redirectUri'           => $redirectUrl . self::OAUTH2_CALLBACK_PATH,
        'tokenCredentialUri'    => CredentialsLoader::TOKEN_CREDENTIAL_URI,
        'scope'                 => self::SCOPE,
        // Create a 'state' token to prevent request forgery. See
        // https://developers.google.com/identity/protocols/OpenIDConnect#createxsrftoken
        // for details.
        'state' => sha1(openssl_random_pseudo_bytes(1024))
    ]
);

// Set the authorization code and fetch refresh and access tokens.
$oauth2->setCode($code);
$authToken = $oauth2->fetchAuthToken();

$refreshToken   = isset( $authToken['refresh_token'] ) ? $authToken['refresh_token'] : '';
$accessToken    = $oauth2->getAccessToken();

现在怎么才能得到邮箱地址?有办法吗?

bvhaajcl

bvhaajcl1#

您需要在OAuth2流中包含一个额外的作用域email,如果这样做,除了访问令牌之外,您还可以交换ID令牌的授权码。
ID令牌包含授权用户的电子邮件地址:

{
  "iss": "https://accounts.google.com",
  "azp": "1234987819200.apps.googleusercontent.com",
  "aud": "1234987819200.apps.googleusercontent.com",
  "sub": "10769150350006150715113082367",
  "at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q",
  "hd": "example.com",
  "email": "jsmith@example.com",
  "email_verified": "true",
  "iat": 1353601026,
  "exp": 1353604926,
  "nonce": "0394852-3190485-2490358"
}

相关问题