Google.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Overtrue\Socialite\Providers;
  3. use Overtrue\Socialite\User;
  4. /**
  5. * @see https://developers.google.com/identity/protocols/OpenIDConnect [OpenID Connect]
  6. */
  7. class Google extends Base
  8. {
  9. public const NAME = 'google';
  10. protected string $scopeSeparator = ' ';
  11. protected array $scopes = [
  12. 'https://www.googleapis.com/auth/userinfo.email',
  13. 'https://www.googleapis.com/auth/userinfo.profile',
  14. ];
  15. protected function getAuthUrl(): string
  16. {
  17. return $this->buildAuthUrlFromBase('https://accounts.google.com/o/oauth2/v2/auth');
  18. }
  19. protected function getTokenUrl(): string
  20. {
  21. return 'https://www.googleapis.com/oauth2/v4/token';
  22. }
  23. /**
  24. * @param string $code
  25. *
  26. * @return array
  27. * @throws \GuzzleHttp\Exception\GuzzleException
  28. * @throws \Overtrue\Socialite\Exceptions\AuthorizeFailedException
  29. */
  30. public function tokenFromCode($code): array
  31. {
  32. $response = $this->getHttpClient()->post($this->getTokenUrl(), [
  33. 'form_params' => $this->getTokenFields($code),
  34. ]);
  35. return $this->normalizeAccessTokenResponse($response->getBody());
  36. }
  37. /**
  38. * @param string $code
  39. *
  40. * @return array
  41. */
  42. protected function getTokenFields($code): array
  43. {
  44. return parent::getTokenFields($code) + ['grant_type' => 'authorization_code'];
  45. }
  46. /**
  47. * @param string $token
  48. * @param array|null $query
  49. *
  50. * @return array
  51. * @throws \GuzzleHttp\Exception\GuzzleException
  52. */
  53. protected function getUserByToken(string $token, ?array $query = []): array
  54. {
  55. $response = $this->getHttpClient()->get('https://www.googleapis.com/userinfo/v2/me', [
  56. 'headers' => [
  57. 'Accept' => 'application/json',
  58. 'Authorization' => 'Bearer '.$token,
  59. ],
  60. ]);
  61. return \json_decode($response->getBody(), true) ?? [];
  62. }
  63. /**
  64. * @param array $user
  65. *
  66. * @return \Overtrue\Socialite\User
  67. */
  68. protected function mapUserToObject(array $user): User
  69. {
  70. return new User([
  71. 'id' => $user['id'] ?? null,
  72. 'username' => $user['email'] ?? null,
  73. 'nickname' => $user['name'] ?? null,
  74. 'name' => $user['name'] ?? null,
  75. 'email' => $user['email'] ?? null,
  76. 'avatar' => $user['picture'] ?? null,
  77. ]);
  78. }
  79. }