【问题标题】:Youtube api cannot refresh access tokenYoutube api 无法刷新访问令牌
【发布时间】:2017-08-11 06:34:23
【问题描述】:

我之前在使用 Google 帐户访问 Youtube 的 API 时遇到了问题。所以我创建了一个新的 gmail 帐户并设法让它工作。不仅在一小时后。我发现刷新令牌没有刷新。我不知道为什么。这变得令人沮丧,因为我似乎不得不不再使用 Youtube 服务了。

这是我下面的代码:也许我做错了什么。

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$client->setAccessType('offline');
$client->setApprovalPrompt('force'); // this line is important when you revoke permission from your app, it will prompt google approval dialogue box forcefully to user to grant offline access


// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
$_SESSION[$tokenSessionKey] = $manually_stored_token; //$client->getAccessToken();



if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}


// Check to ensure that the access token was successfully acquired.
if($client->isAccessTokenExpired()) {

          $client->refreshToken($refresh_token);
          if(!$client->isAccessTokenExpired()) {
               // do something
          } else {
              // refresh access token not granted
          }


} else if ($client->getAccessToken()) {

    // do something

} else {
       // do something
}

我检查了我的帐户https://myaccount.google.com/u/0/security,在“登录和安全性”下查看了对您 Google 帐户的授权访问权限,我仍然拥有授权。所以我不知道为什么它不刷新我的令牌。

【问题讨论】:

  • 客户端库应该只在需要时刷新您的访问令牌。是什么让您认为不是?
  • 我绝对知道它不会刷新,因为我设置了断点来知道我的令牌何时过期,然后尝试刷新。这工作了大约一个星期,直到它停止了。我没有改变任何东西,至少我知道!

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


【解决方案1】:

当您首次授权时,您会在回复中同时获得 access_tokenrefresh_token
之后,您只会收到access_token 回复。 refresh_token 您必须保存并重复使用。

如果您因任何原因丢失它,您必须重置您的授权访问。

我遇到了这个问题,因为没人能给我答案。

基本解决方法是“取消授权”用户,然后再次“重新授权”他们。如果您不这样做,您将永远不会收到refresh_token 的回复。

测试和检查。打开您正在获得授权的帐户。
进入仪表板并找到“与您的帐户相关联的应用程序”部分。
在那里您会看到您的应用,并且可以手动将其删除以进行测试。
但是,您稍后需要为此编写代码,但对于测试来说已经足够了。

【讨论】:

    猜你喜欢
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2018-01-05
    • 2013-08-28
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多