如何使用存储的刷新令牌获取更新的访问令牌

时间:2013-04-02 17:42:54

标签: php oauth-2.0 google-analytics-api google-api-php-client

我正在构建一个应用程序,允许管理员验证对其分析帐户的访问权限以供脱机使用,并将刷新令牌存储在数据库中。

现在,当我尝试在前端使用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的东西 - 从数据库中输入值,从管理员先前在线验证它。

2 个答案:

答案 0 :(得分: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 :(得分: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;
}

您可以将try下的语句替换为抛出异常的行,我想这将是

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

或者您也可以尝试按照此处给出的解决方案刷新令牌:

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