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

mat*_*k22 9 php google-analytics-api oauth-2.0 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."
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止生成此错误的代码:

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>';
}
Run Code Online (Sandbox Code Playgroud)

我正在运行一个函数来运行类似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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我得到了"缺少Google_Client :: authenticate()的参数1,"任何想法? (4认同)