0
votes

I'm using the Google O Auth 2.0 PHP API Client Library to authorize my app and get access tokens and refresh tokens. I do get access tokens.

The JSON returned has an access_token, token_type, expires, and id_token, I believe, but it doesn't have a refresh_token.

I've tried getting just the refresh_token with the library, but I get NULL.

This is the first authorization because I am using prompt=consent parameter in my url redirect and am manually disapproving my app in the Google accounts console each time before doing this, still not getting a refresh token.

Here is my code which gets the access token successfully, but no refresh token:

$client = new Google_Client();
$client->setAuthConfig('php/client_secret.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(array('email', 'profile', 'calendar'));
$token=$client->fetchAccessTokenWithAuthCode(urldecode($authCode));

Here is my code that returns null for the refresh token:

$client = new Google_Client();
$client->setAuthConfig('php/client_secret.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(array('email', 'profile', 'calendar'));
$client->authenticate(urldecode($authCode));
$token=$client->getRefreshToken();
1

1 Answers

1
votes

I'm hoping to shed some light here. I'm not sure if I properly understand your implementation but this is how I do it.

<?php session_start(); 

//INCLUDE PHP CLIENT LIBRARY
require_once 'vendor/autoload.php';

// Create client object
$client = new Google_Client(); 
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/Test.php');
$client->setAuthConfig("client_secret.json");
$client->addScope(array('email', 'profile'));
$client->setAccessType('offline');
$client->setApprovalPrompt('force');

if( !isset($_GET["code"]) ){

  $authUrl = $client->createAuthUrl();
  header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));

} else {

  $authCode = $_GET['code'];
  $token = $client->fetchAccessTokenWithAuthCode(urldecode($authCode));

  var_dump($token);

}

?>

This is what I'm getting after running the above script:

array (size=6)
  'access_token' => string 'ya29.-r76enex2-m8QUZv-kdRwV4huHSC-' (length=129)
  'token_type' => string 'Bearer' (length=6)
  'expires_in' => int 3599
  'refresh_token' => string '1/T8z2Gw78wporTviu3In8' (length=45)
  'id_token' => string 'eyJhbGciOiJIsImtpZCc4M2VkMGMifQ.'... (length=1209)
  'created' => int 1488420909

I noticed that if I used $client->addScope(array('email', 'profile', 'calendar'));, I was getting an error so I removed calendar. As far as I understand, when you are using $client->setAccessType('offline'); and $client->setApprovalPrompt('force');, you should be prompt to allow offline access and if you click "Allow" you should get a refresh token as how I do.