1

I have the following code

if (file_exists($credentialsPath)) {

    $accessToken = file_get_contents($credentialsPath);

    $client->setAccessToken($accessToken);

    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        $newAccessToken = $client->getAccessToken();
        $accessToken = array_merge($accessToken, $newAccessToken);
        file_put_contents($credentialsPath, json_encode($accessToken));
    }
} 

But after an hour, if I try to use Youtube Data API, I am getting the following error,

Fatal error: Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/vendor/google/apiclient/src/Google/Client.php:267 Stack trace: #0 /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/youtube.php(26): Google_Client->fetchAccessTokenWithRefreshToken(NULL) #1 /var/sentora/hostdata/zadmin/public_html/channel/apiwrap.php(3): require_once('/var/sentora/ho...') #2 {main} thrown in /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/vendor/google/apiclient/src/Google/Client.php on line 267

Please help.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
user810258
  • 31
  • 4

1 Answers1

0

You need to set these 2 things. The refresh token is not returned because we didn't force the approvalPrompt. The offline mode is not enough. We must force the approvalPrompt. Also, the redirect URI must be set before these two options. It worked for me.

$client = new Google_Client();
$client->setApplicationName('Project Name');
$client->setScopes('SCOPES');
$client->setAuthConfig('JSON_FILE_PATH');
$client->setRedirectUri($this->redirectUri);
$client->setAccessType('offline');  //this line is magic point
$client->setApprovalPrompt('force'); //this line is magic point

This is worked for me. i am able to get new token using refresh token.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Jatin Mandanka
  • 411
  • 11
  • 16