我有以下代码
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$newAccessToken = $client->getAccessToken();
$accessToken = array_merge($accessToken, $newAccessToken);
file_put_contents($credentialsPath, json_encode($accessToken));
}
}
但是一个小时后,如果我尝试使用 Youtube Data API,我会收到以下错误,
Fatal error: Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/vendor/google/apiclient/src/Google/Client.php:267 Stack trace: #0 /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/youtube.php(26): Google_Client->fetchAccessTokenWithRefreshToken(NULL) #1 /var/sentora/hostdata/zadmin/public_html/channel/apiwrap.php(3): require_once('/var/sentora/ho...') #2 {main} thrown in /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/vendor/google/apiclient/src/Google/Client.php on line 267
请帮忙。
您需要设置这两项。刷新令牌不会返回,因为我们没有强制approvalPrompt。离线模式还不够。我们必须强制批准提示。另外,重定向 URI 必须在这两个选项之前设置。这对我有用。
$client = new Google_Client();
$client->setApplicationName('Project Name');
$client->setScopes('SCOPES');
$client->setAuthConfig('JSON_FILE_PATH');
$client->setRedirectUri($this->redirectUri);
$client->setAccessType('offline'); //this line is magic point
$client->setApprovalPrompt('force'); //this line is magic point
这对我有用。我可以使用刷新令牌获取新令牌。