【问题标题】:Google Oauth refresh TokenGoogle Oauth 刷新令牌
【发布时间】:2016-09-27 21:33:08
【问题描述】:

我正在尝试使用 Google Oauth 访问 Google Analytics(分析)数据。 除了令牌外,它工作正常。令牌在一小时后过期,我不知道如何刷新它。有一行“为简单起见,我们只存储 accessToken。如果它过期,请使用 refreshToken 获取一个新的”,但我不知道如何...... 这是我的代码

$client_id = 'xxxxxxxxxx.apps.googleusercontent.com';

// From the APIs console
$client_secret = 'xxxxxxxxxxxxx';

 // Url to your this page, must match the one in the APIs console
$redirect_uri = 'mylocalurl.php';


session_start();
include('GoogleAnalyticsAPI.class.php');

$ga = new GoogleAnalyticsAPI(); 
$ga->auth->setClientId($client_id);
$ga->auth->setClientSecret($client_secret);
$ga->auth->setRedirectUri($redirect_uri);

if (isset($_GET['force_oauth'])) {
    $_SESSION['oauth_access_token'] = null;
}


/*
 *  Step 1: Check if we have an oAuth access token in our session
 *          If we've got $_GET['code'], move to the next step
 */
if (!isset($_SESSION['oauth_access_token']) && !isset($_GET['code'])) {
    // Go get the url of the authentication page, redirect the client and go get that token!
    $url = $ga->auth->buildAuthUrl();
    header("Location: ".$url);
} 

/*
 *  Step 2: Returning from the Google oAuth page, the access token should be in $_GET['code']
 */
if (!isset($_SESSION['oauth_access_token']) && isset($_GET['code'])) {
    $auth = $ga->auth->getAccessToken($_GET['code']);
    if ($auth['http_code'] == 200) {
        $accessToken    = $auth['access_token'];
        $refreshToken   = $auth['refresh_token'];
        $tokenExpires   = $auth['expires_in'];
        $tokenCreated   = time();

        // For simplicity of the example we only store the accessToken
        // If it expires use the refreshToken to get a fresh one
        $_SESSION['oauth_access_token'] = $accessToken;
    } else {
        die("Sorry, something wend wrong retrieving the oAuth tokens");
    }
}

谢谢

【问题讨论】:

    标签: oauth


    【解决方案1】:

    我不确定在 PHP 中执行此操作的详细信息,但有一个端点可以请求刷新访问令牌。

    API 端点是https://accounts.google.com/o/oauth2/token,请求的主体应该是这样的

    {
       'refresh_token' => your_stored_refresh_token,
       'client_id' => ENV['CLIENT_ID'],
       'client_secret' => ENV['CLIENT_SECRET'],
       'grant_type' => 'refresh_token'
    }
    

    如果成功,该请求将返回一个新的访问令牌。

    【讨论】:

      猜你喜欢
      • 2015-06-27
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 2012-06-05
      • 1970-01-01
      • 2020-05-05
      • 2015-07-03
      相关资源
      最近更新 更多