因此,我试图刷新访问 token 以使其正常工作。
访问 token 过期后,我将运行refreshToken()并传递refresh_token以从Google获得新的access_token。
有时它似乎可以正常工作,但是在此之后,我仍然收到错误消息 invalid_grant 。好像我要经过几天才能不重新授权访问我的YouTube channel 。
我在做任何重要的事情吗?
if ($client->getAccessToken()) {
if($client->isAccessTokenExpired()) {
$newToken = $client->getAccessToken();
//Run refreshToken() and pass in the refresh token to get a fresh access token.
$client->refreshToken($newToken['refresh_token']);
//Take old key object and replace everything except for refresh_token
$newKey = $client->getAccessToken();
$newKeyWithRefreshToken = json_decode($oldKey);
$newKeyWithRefreshToken->access_token = $newKey['access_token'];
$newKeyWithRefreshToken->token_type = $newKey['token_type'];
$newKeyWithRefreshToken->expires_in = $newKey['expires_in'];
$newKeyWithRefreshToken->created = $newKey['created'];
//save to db
DB::getInstance()->update('channel', $channelId , array(
'credentials' => json_encode($newKeyWithRefreshToken)
));
最佳答案
在获得Google授权后,您会收到一个 token ,该 token 将在1小时或3600秒内过期,并且通常会过期。因此,您需要的是刷新 token 以获取新的工作 token 。
这是您需要的步骤:
$token = $client->getAccessToken();
$authObj = json_decode($token);
if(isset($authObj->refresh_token)) {
save_refresh_token($authObj->refresh_token);
}
保存此refresh_token很重要,然后您可以使用更新
$client->refreshToken($your_saved_refresh_token);
然后将新的访问 token 设置为 session :
$_SESSION['access_token'] = $client->getAccessToken();
有关更多信息,请检查此SO question。
关于php - 通过refresh_token获取新的access_token非常不可靠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40848122/