get_oauth_token.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. <?php
  2. /**
  3. * Get an OAuth2 token from Google.
  4. * * Install this script on your server so that it's accessible
  5. * as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
  6. * e.g.: http://localhost/phpmail/get_oauth_token.php
  7. * * Ensure dependencies are installed with 'composer install'
  8. * * Set up an app in your Google developer console
  9. * * Set the script address as the app's redirect URL
  10. * If no refresh token is obtained when running this file, revoke access to your app
  11. * using link: https://accounts.google.com/b/0/IssuedAuthSubTokens and run the script again.
  12. * This script requires PHP 5.4 or later
  13. * PHP Version 5.4
  14. */
  15. namespace League\OAuth2\Client\Provider;
  16. require 'vendor/autoload.php';
  17. use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
  18. use League\OAuth2\Client\Token\AccessToken;
  19. use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
  20. use Psr\Http\Message\ResponseInterface;
  21. session_start();
  22. //If this automatic URL doesn't work, set it yourself manually
  23. $redirectUri = isset($_SERVER['HTTPS']) ? 'https://' : 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  24. //$redirectUri = 'http://localhost/phpmailer/get_oauth_token.php';
  25. //These details obtained are by setting up app in Google developer console.
  26. $clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com';
  27. $clientSecret = 'RANDOMCHARS-----lGyjPcRtvP';
  28. class Google extends AbstractProvider
  29. {
  30. use BearerAuthorizationTrait;
  31. const ACCESS_TOKEN_RESOURCE_OWNER_ID = 'id';
  32. /**
  33. * @var string If set, this will be sent to google as the "access_type" parameter.
  34. * @link https://developers.google.com/accounts/docs/OAuth2WebServer#offline
  35. */
  36. protected $accessType;
  37. /**
  38. * @var string If set, this will be sent to google as the "hd" parameter.
  39. * @link https://developers.google.com/accounts/docs/OAuth2Login#hd-param
  40. */
  41. protected $hostedDomain;
  42. /**
  43. * @var string If set, this will be sent to google as the "scope" parameter.
  44. * @link https://developers.google.com/gmail/api/auth/scopes
  45. */
  46. protected $scope;
  47. public function getBaseAuthorizationUrl()
  48. {
  49. return 'https://accounts.google.com/o/oauth2/auth';
  50. }
  51. public function getBaseAccessTokenUrl(array $params)
  52. {
  53. return 'https://accounts.google.com/o/oauth2/token';
  54. }
  55. public function getResourceOwnerDetailsUrl(AccessToken $token)
  56. {
  57. return ' ';
  58. }
  59. protected function getAuthorizationParameters(array $options)
  60. {
  61. if (is_array($this->scope)) {
  62. $separator = $this->getScopeSeparator();
  63. $this->scope = implode($separator, $this->scope);
  64. }
  65. $params = array_merge(
  66. parent::getAuthorizationParameters($options),
  67. array_filter([
  68. 'hd' => $this->hostedDomain,
  69. 'access_type' => $this->accessType,
  70. 'scope' => $this->scope,
  71. // if the user is logged in with more than one account ask which one to use for the login!
  72. 'authuser' => '-1'
  73. ])
  74. );
  75. return $params;
  76. }
  77. protected function getDefaultScopes()
  78. {
  79. return [
  80. 'email',
  81. 'openid',
  82. 'profile',
  83. ];
  84. }
  85. protected function getScopeSeparator()
  86. {
  87. return ' ';
  88. }
  89. protected function checkResponse(ResponseInterface $response, $data)
  90. {
  91. if (!empty($data['error'])) {
  92. $code = 0;
  93. $error = $data['error'];
  94. if (is_array($error)) {
  95. $code = $error['code'];
  96. $error = $error['message'];
  97. }
  98. throw new IdentityProviderException($error, $code, $data);
  99. }
  100. }
  101. protected function createResourceOwner(array $response, AccessToken $token)
  102. {
  103. return new GoogleUser($response);
  104. }
  105. }
  106. //Set Redirect URI in Developer Console as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
  107. $provider = new Google(
  108. array(
  109. 'clientId' => $clientId,
  110. 'clientSecret' => $clientSecret,
  111. 'redirectUri' => $redirectUri,
  112. 'scope' => array('https://mail.google.com/'),
  113. 'accessType' => 'offline'
  114. )
  115. );
  116. if (!isset($_GET['code'])) {
  117. // If we don't have an authorization code then get one
  118. $authUrl = $provider->getAuthorizationUrl();
  119. $_SESSION['oauth2state'] = $provider->getState();
  120. header('Location: ' . $authUrl);
  121. exit;
  122. // Check given state against previously stored one to mitigate CSRF attack
  123. } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
  124. unset($_SESSION['oauth2state']);
  125. exit('Invalid state');
  126. } else {
  127. // Try to get an access token (using the authorization code grant)
  128. $token = $provider->getAccessToken(
  129. 'authorization_code',
  130. array(
  131. 'code' => $_GET['code']
  132. )
  133. );
  134. // Use this to get a new access token if the old one expires
  135. echo 'Refresh Token: ' . $token->getRefreshToken();
  136. }