2014-10-09 161 views
0

當我第一次從我的網絡瀏覽器輸入我的index.php時,我被重定向到Google,以確認我的應用程序訪問我的帳戶。然後,我希望應用程序保存刷新標記,不要再問我。但是當我嘗試訪問index.php時,另一個瀏覽器再次問我同樣的事情。我想以cronjob的身份訪問index.php,因此每次都不能要求提供Google帳戶。無法刷新令牌

這裏是我的代碼:

$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 
} 

謝謝!

/埃裏克

回答

0

提示可以跳過那些已經授權使用下面的代碼之前的應用程序的用戶。有關更多信息,請參閱this answer

要在cron作業中完成此項工作,當沒有用戶登錄到瀏覽器時,您需要請求脫機訪問並使用刷新令牌。有關更多信息,請參見this answer