'Youtube Google API Caught Google service Exception 0 message is refresh token must be passed in or set as part of setAccessTokenStack

I am currently facing this problem: once I authorized youtube to access my account and after saving the token in a file called "token.txt," everything runs smoothly until the token expires. My script is not able to refresh the token.

Error

Caught Google service Exception 0 message is refresh token must be passed in or set as part of setAccessTokenStack trace is #0 /home/omqoygue/contest.diamante.live/vendor/google/apiclient/src/Client.php(321): Google\Client->fetchAccessTokenWithRefreshToken(NULL) #1 /home/omqoygue/contest.diamante.live/upload.php(40): Google\Client->refreshToken(NULL) #2 /home/omqoygue/contest.diamante.live/index.php(18): include('/home/omqoygue/...') #3 {main}

This is where the token is created and stored in a file.

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
    $token = json_encode($_SESSION['token']);
    file_put_contents('token.txt', $token);
    foreach ($_SESSION['token'] as $key => $value) {
        echo '<code>'.$key.":".$value."<br>".'</code>';
    }
}

This is the part where the token validity is checked. If it has expired, it should be updated, but this does not happen.

$token = file_get_contents('token.txt');

try {
    // Client init
    $client = new Google_Client();
    $client->setApplicationName($application_name);
    $client->setClientId($client_id);
    $client->setAccessType('offline');
    $client->setAccessToken($token);
    $client->setScopes($scope);
    $client->setClientSecret($client_secret);
    if ($client->getAccessToken()) {
        /**
         * Check to see if our access token has expired. 
         * If so, get a new one and save it to file for future use.
         */
        if ($client->isAccessTokenExpired()) {
            $newToken = json_decode($client->getAccessToken());
            $client->refreshToken($newToken->refreshToken);
            file_put_contents('token.txt', $client->getAccessToken());
        }
    }
}

When the token expires, I have to give permission again to youtube to access my account. I hope someone can help me, I have already checked the other posts on the subject, but they are obsolete.



Solution 1:[1]

If your refresh token is expired then you will need to authorize the app again there is no way around that. The easiest way to do that with your code is to delete 'token.txt' it should prompt you to authorize the app again.

Once your app is set to production instead of testing in Google developer console your token will stop expiring every seven days.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DaImTo