2013-04-02 148 views
9

我構建的應用程序允許管理員驗證對其離線使用的分析帳戶的訪問權限,並將刷新令牌存儲在數據庫中。如何使用存儲的刷新令牌獲取更新的訪問令牌

現在,當我嘗試使用API​​的前端,它返回以下錯誤:

"Access Token Expired. There wan a general error : The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved." 

這裏是我的代碼,到目前爲止生成此錯誤:

require_once "lib/google/Google_Client.php"; 
require_once "lib/google/contrib/Google_AnalyticsService.php"; 

$_analytics = new analytics(); 
$_googleClient = new Google_Client(); 
$_googleClient->setClientId($_analytics->gaClientId); 
$_googleClient->setClientSecret($_analytics->gaClientSecret); 
$_googleClient->setRedirectUri($_analytics->gaRedirectUri); 
$_googleClient->setScopes($_analytics->gaScope); 
$_googleClient->setAccessType($_analytics->gaAccessType); 

// Returns last access token from the database (this works) 
$_tokenArray['access_token'] = $_analytics->dbAccessToken($_agencyId); 
$_googleClient->setAccessToken(json_encode($_tokenArray)); 

if($_googleClient->isAccessTokenExpired()) { 
    // Don't think this is required for Analytics API V3 
    //$_googleClient->refreshToken($_analytics->dbRefreshToken($_agencyId)); 
    echo 'Access Token Expired'; // Debug 
} 

if (!$_googleClient->getAccessToken()) { 
    echo '<h2>Error - Admin has not setup analytics correct yet</h2>'; 
} 

後我一個運行類似setRefreshToken的函數 - 從管理員之前在線驗證它,從數據庫輸入值。

回答

7

您可以嘗試以下操作,您需要添加代碼以將新令牌存儲在數據庫中。

if($_googleClient->isAccessTokenExpired()) { 
    // Don't think this is required for Analytics API V3 
    //$_googleClient->refreshToken($_analytics->dbRefreshToken($_agencyId)); 
    echo 'Access Token Expired'; // Debug 

    $_googleClient->authenticate(); 
    $NewAccessToken = json_decode($_googleClient->getAccessToken()); 
    $_googleClient->refreshToken($NewAccessToken->refresh_token); 
} 
+1

問題解決了,再加上我試圖使用訪問噸至刷新令牌奧肯,而不是使用刷新標記,因爲它的參數。 #fail - 謝謝! – mattpark22

+1

您是否知道如何強制訪問令牌過期以使用刷新令牌功能來獲取新的訪問令牌? @mpark – Anagio

+1

@Anagio你應該可以運行'$ _googleClient-> refreshToken($ NewAccessToken-> refresh_token);' 強制一個新的令牌。然後,只需比較舊的令牌和新的令牌,看看它是否發生了變化。 –

0

使用try/catch並使用catch重定向/刷新訪問令牌。 下面是我用類似的問題的解決方案:

$plus = new Google_Service_Plus($client); 
try { 
$me = $plus->people->get('me'); 
} catch(Exception $e){ 
     if(!(strpos($_SERVER["REQUEST_URI"],'logout'))){ 
     if (isset($authUrl)){ 
       $redirect = $authUrl; 
     } 
     else{ 
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] .'?logout'; 
     } 
     header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); 
     exit; 
} 

您可以在嘗試用線引發異常更換的說法,我想這將是

$_googleClient->setClientId($_analytics->gaClientId); 

,或者您也可以嘗試令人耳目一新這裏給出的令牌按解決方案:

https://stackoverflow.com/a/22096740/1675384

相關問題