Google API Client ''refresh token must be passed in or set as part of setAccessToken'' Error

395 Views Asked by At

I can get Google Access Token on browser like below, but I can not renew it. After I tried to renew it, I faced this error: refresh token must be passed in or set as part of setAccessToken.

I get Google Access Token like this, it works well this script:


$client = new \Google_Client();
$client->setAuthConfigFile(base_path().'/google-config.json');
$client->setAuthConfig(base_path().'/google-config.json');
$client->setRedirectUri('https://example.com/get-token');   
$client->addScope("https://www.googleapis.com/auth/forms.body");
$client->addScope("https://www.googleapis.com/auth/forms.responses.readonly");
$client->setAccessType('offline');
$client->setApprovalPrompt('force');

if (! isset($_GET['code'])) 
{
    // Redirect to get request
    $auth_url = $client->createAuthUrl();
    return redirect(filter_var($auth_url, FILTER_SANITIZE_URL));
}
else 
{
    // Set auth & token
    $client->authenticate($_GET['code']);
    $this->google_token = $client->getAccessToken();
    // Write to local file this code =  $this->google_token
}

I tried to renew the token using fetchAccessTokenWithRefreshToken method but, I faced this error: refresh token must be passed in or set as part of setAccessToken

I saw that $client->getRefreshToken() return null, I don't know why?

// Load previously authorized credentials from a file. I get this var from a local file
if ($data ) 
{
    $accessToken = $data;
    $client->setAccessToken($accessToken); 
}

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) 
{   
    $refreshTokenSaved = $client->getRefreshToken();
    # !!! refreshTokenSaved returns null
    
    // update access token
    $client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
    # !! It stops here with the error.

    // pass access token to some variable
    $accessTokenUpdated = $client->getAccessToken();

    // append refresh token
    $accessTokenUpdated['refresh_token'] = $refreshTokenSaved;

    //Set the new acces token
    $accessToken = $refreshTokenSaved;
    
    $client->setAccessToken($accessToken);

    // save to file...
}

I use Laravel 9.x.

How can I solve this issue? My aim is that automatically renew the token for Google Forms.

Thank you!

1

There are 1 best solutions below

2
Linda Lawton - DaImTo On

if your not getting a refresh token back you need to go to revoke the users access and then request authorization again. PHP only returns the refresh token with the first authorization subsequent auth requests don't include it.

Either use the revoke endpoint or do it directly in your google account under security remove the access to the third party application.