所以我真的复制了Google示例中的代码(https://developers.google.com/google-apps/calendar/quickstart/php)并尽可能地遵循其说明,然后我的日历工作得很好 . 但是我想出了什么是错的 .
我相信我的问题的根源是这一行:
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
因为那条线给了我这个错误
Uncaught LogicException:刷新令牌必须传入或设置为setAccessToken的一部分
有类似的问题(Get refresh token google api,Not receiving Google OAuth refresh token)但我似乎无法用他们的答案来解决我的问题 .
另一个说明;当我测试时, $client->getRefreshToken()
似乎正在返回 null
,这就是我认为 $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
失败的原因 .
所以这是直接来自相关示例的代码片段
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
那段代码给了我错误,因为 $client->getRefreshToken()
是 null
,但我假设我需要使用刷新令牌来获取一个新令牌,如果没有刷新令牌我不能这样做?
另请注意,这已在调用开始时设置
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
1 回答
请注意,访问令牌的生命周期有限,一旦发生,这会导致您的日历停止工作 . 因此,正如Token expiration中所建议的那样,您应该在代码中写入以预测授予的令牌可能不再起作用的可能性 . 这就是刷新令牌变得非常有用的地方,它允许您的应用程序获得新的访问令牌,而无需再次通过授权过程 .
要请求refresh token,请在您的身份验证请求中添加
access_type=offline
. 但是,这个GitHub post建议您可以通过在请求中提供参数access_type=offline&approval_prompt=force
来获取刷新令牌 .有关更多有用的提示,我认为以下链接将是有益的:
The OAuth 2.0 Authorization Framework
OAuth2 and Google APIs Library for PHP
How and when to use the refresh token with PHP Google Calender API