当我第一次从web浏览器输入index.php时,我会被重定向到谷歌,以确保我的应用程序有权访问我的帐户。然后我希望应用程序保存刷新令牌,并且不再询问我。但当我尝试访问index.php-thou另一个浏览器时,它再次问我同样的问题。我想作为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
}
谢谢!
/Erik
对于在使用以下代码之前已经授权应用程序的用户,可以跳过提示。有关详细信息,请参阅此答案。
要在cron作业中实现这一点,当没有用户登录到浏览器时,您需要请求离线访问并使用刷新令牌。有关详细信息,请参阅此答案。