Google API 总是提示?

Google API always prompting?

我在应用程序 awlays 提示用户在令牌过期(1 小时)后授予对应用程序的访问权限时遇到问题。我正在寻找较旧的问题,但没有任何帮助。如果有人有时间检查我的代码并发现错误,我将不胜感激。

  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;
}

您需要做的第一件事是开始从 token.json 文件中读取刷新令牌。我现在没有安装 php,所以我无法测试它。只需确保加载它,然后使用 setRefreshToken 将其设置为客户端对象的一部分。要测试它,只需打印出 $client 对象以确保其已设置。

$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);
  }

然后当您检查 isAccessTokenExpired 时,库应该会自动为您加载一个新的访问令牌。

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