php - 通过refresh_token获取新的access_token非常不可靠

标签 php youtube youtube-api google-oauth youtube-data-api

因此,我试图刷新访问 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/

相关文章:

javascript - 是否可以通过 YouTube API 获取有多少人正在观看 YouTube 直播视频?

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数 1 是资源

android - 如何使用YouTube API V3从Android应用上传视频?

youtube - YouTube OEmbed服务不适用于带有播放列表和索引查询参数的视频网址

YouTube 重复的视频 ID

javascript - 如何从 youtube api 获取值?

php - 我想使用 mysql 数据库的内容显示不同的页面

php - 我如何使用 jQuery 来处理特定的 div,而不是在当前文档中 - 在包含 HTML 的变量中?

php - 将联接与 SQL 查询结合使用

python - 使用 Python 和 selenium 从 Tweet 中提取 YouTube 链接