Search code examples
phpgoogle-apigoogle-oauthgoogle-api-php-client

Google API always prompting?


I am having trouble with application awlays prompting user to grant access to app after token expire (1 hour). I was looking older issues, but nothing helped me. If anyone has time to review my code and find mistake, I would be grateful.

  function getClient()
    {
  $client = new Google_Client();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  //disable SSL
  $guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
  $client->setHttpClient($guzzleClient);
  $sample_passthrough_value = 'someregularstring22';
  $client->setApplicationName('GDrive_Trello');
  $client->setScopes('https://www.googleapis.com/auth/drive');
  $client->setAuthConfig('credentials.json');
  $client->setState($sample_passthrough_value);
  $client->setRedirectUri($redirect_uri);
  $client->setAccessType('offline');
  $client->setIncludeGrantedScopes(true); 
  
  
  $tokenPath = 'token.json';
  if (file_exists($tokenPath)) {
      $accessToken = json_decode(file_get_contents($tokenPath), true);
      $client->setAccessToken($accessToken);
  }

  if ($client->isAccessTokenExpired()) {
      if ($client->getRefreshToken()) {
          $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
      } else {
          $authUrl = $client->createAuthUrl();
          header("Location: " . $authUrl);
          if(isset($_GET['code'])){
              $authCode = $_GET['code'];    
              header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
            } else{
                $authCode= null;
            }
            
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

          if (array_key_exists('error', $accessToken)) {
              throw new Exception(join(', ', $accessToken));
          }
      }
      if (!file_exists(dirname($tokenPath))) {
          mkdir(dirname($tokenPath), 0700, true);
      }
      file_put_contents($tokenPath, json_encode($client->getAccessToken()));
  } 
  return $client;
}

Solution

  • The first thing you need to do is start reading the refresh token from the token.json file. I dont have php installed right now so i cant test this. Just make sure that you load it then use setRefreshToken to set it as part of the client object. To test it just print out the $client object to be sure that its set.

    $tokenPath = 'token.json';
      if (file_exists($tokenPath)) {
          $accessToken = json_decode(file_get_contents($tokenPath), true);
          $refresToken= // do something hear to load that refresh token;
          $client->setAccessToken($accessToken);
          $client->RefreshToken($refresToken);
      }
    

    Then when you check for isAccessTokenExpired the library should automaticly be loading you a new access token.

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