2013-04-02 120 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

相关问题