0

I've been block for two days facing 0auth problems after 1 hour on Youtube api. 401 credential error.

$OAUTH2_CLIENT_ID = 'XXXXX';
$OAUTH2_CLIENT_SECRET = 'XXXXX';
$client = new Google_Client();
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$service = new Google_Service_YouTube($client);                            
if (isset($_GET['code'])){
    $accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($accessToken);
    $test=$client->getAccessToken();    
    //TEST REFRESH TOKEN
    print_r($test);
    sleep(10);
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    $test=$client->getAccessToken();
    print_r($test);                                                         
  }    

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
 ... 
  foreach ($files as $file){    
      if ($client->isAccessTokenExpired()) {
         $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
         file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
       } // end if token expired                                     
  ====CALL YOUTUBE API HERE IN FOREACH LOOP ===
  }// end foreach files

}

The result of my test code show me the access token didn't change at all after provided refresh token, even the expiration time have not dicreased 'expires_in'

So that's why I'm facing a credential error after an hour ... I don't know what's wrong with my code, please help me.

This the result of my test code after getting access code, so as you can see the 'new' access token is similar at the previous one and I already tried to use encode_json too on parameter of setAccessToken() and fetchAccessTokenWithRefreshToken(). Not getting error but result still same ...

Array ( [access_token] => ya29.GlvQBuGBfZDQn3E8HWd4wfSbb0hLHsYVGzPBE0boJuB4ien5pcsOGqXlkEyOU7mevDLOGOWbuakTyTiAUVf2bkxNwZXX [expires_in] => 3600 [refresh_token] => 1/KEgjy2t9kTNwCXk-ZtMTSzPSS2xl4XX [scope] => https://www.googleapis.com/auth/youtube [token_type] => Bearer [created] => 1552891085 )

Array ( [access_token] => ya29.GlvQBuGBfZDQn3E8HWd4wfSbb0hLHsYVGzPBE0boJuB4ien5pcsOGqXlkEyOU7mevDLOGOWbuakTyTiAUVf2bkxNwZXX [expires_in] => 3600 [refresh_token] => 1/KEgjy2t9kTNwCXk-ZtMTSzPSS2xl4XX [scope] => https://www.googleapis.com/auth/youtube [token_type] => Bearer [created] => 1552891085 )

Thanks you

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Julian
  • 27
  • 1
  • 9

1 Answers1

0

Access tokens expire after one hour this is how they work. Once the access token has expired you should run your code and fetch a new access token. Fetching a new access token before it expires will result in the same access token.

Your access token was created at created (tip epoch converter) add 3600 (seconds) to find out when it expires.

1552891085 <--- Monday, March 18, 2019 6:38:05 AM

The only thing i can see wrong with your code is Your fetching the access token but not actually using it Oauth2Authentication.php

function getOauth2Client() {
    try {

        $client = buildClient();

        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }

        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 

            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • Thanks for your answer, you mean im not using ; $client->setAccessToken($client->getAccessToken()); after fetchAccessTokenWithRefreshToken ? If it"s what you mean, Yes on this code I didnt, but i already tried and as i explained after fetchAccessTokenWithRefreshToken I still get the exact same access token ... – Julian Mar 18 '19 at 07:31
  • You are going to get the same access token until it expires then you will get a new one. – Linda Lawton - DaImTo Mar 18 '19 at 07:32
  • 1
    Ok it was also one of my another question, i wasnt sure about that. So im gonna tried again with $client->setAccessToken($client->getAccessToken()); after refresh, but i feel this weird specialy when expires in still blocked at 3600 and dont decrease . – Julian Mar 18 '19 at 07:37
  • I linked where i got that code from thats my youtube sample project feel free to dig around in that. 3600 is one hour from created gives you expires – Linda Lawton - DaImTo Mar 18 '19 at 07:38
  • Thanks again for your help, i knew abbout 3600s i mean this field ('expires in') is not supposed to decreased every sec ? and the method isAccessTokenExpired() checking about it ? – Julian Mar 18 '19 at 07:41
  • 3600 wont change its a standard thing telling you how long the access token is valid you then need to use check create to test if its expired. Yes the library probably has a check in the code to test this for you thats why isAccessTokenExpired works. I cant remember what they have the clock skew set to it will probably fetch you a new one five minutes before its due to expire. Its Not google thats not returning you a new access token its the library it knows its not expired. – Linda Lawton - DaImTo Mar 18 '19 at 07:49
  • Thank you ! i launch the script again and i will confirm you it works, i hope in one hour – Julian Mar 18 '19 at 07:55
  • I am here all day let me know if it doesnt. Other wise remember to accept this answer if it helped you. – Linda Lawton - DaImTo Mar 18 '19 at 07:57