【问题标题】:Can't refresh token无法刷新令牌
【发布时间】:2014-10-09 12:34:37
【问题描述】:

当我第一次从我的网络浏览器输入我的 index.php 时,我被重定向到 Google,以证明我的应用程序有权访问我的帐户。然后我希望应用程序保存刷新令牌并且不再问我。但是当我尝试通过另一个浏览器访问 index.php 时,它再次问我同样的事情。我想以 cronjob 的形式访问 index.php,所以它不能每次都要求谷歌帐户。

这是我的代码:

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);

if (isset($_REQUEST['logout'])) {
    write_token("");
}

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    write_token($client->getAccessToken());
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (strlen(read_token()) > 1) {
    $client->setAccessToken(read_token());
    if ($client->isAccessTokenExpired()) {
        write_token("");
    }
} elseif(!isset($_GET['code'])) { // The IF NOT CODE prevent loop when refreshing token
    $authUrl = $client->createAuthUrl();
    header('Location: ' . $authUrl); // Update token if expired
}

谢谢!

/埃里克

【问题讨论】:

    标签: php google-drive-api


    【解决方案1】:

    在使用以下代码之前,已经授权应用程序的用户可以跳过提示。请参阅this answer 了解更多信息。

    要在 cron 作业中进行这项工作,当没有用户登录浏览器时,您需要请求离线访问并使用刷新令牌。请参阅this answer 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2019-10-26
      • 2022-12-14
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 2017-08-11
      相关资源
      最近更新 更多