为Google Api Php客户端刷新令牌

时间:2012-06-23 08:45:21

标签: oauth-2.0 access-token google-analytics-api

我正在使用Google API客户端访问Google Analytics。我想在离线模式下访问数据,所以我需要一个刷新令牌。我如何获得refresh_token?

2 个答案:

答案 0 :(得分:7)

尝试使用以下代码:

    <?php
        require_once 'apiClient.php';

        const REDIRECT_URL = 'INSERT YOUR REDIRECT URL HERE';
        const CLIENT_ID = 'INSERT YOUR CLIENT ID HERE';
        const CLIENT_SECRET = 'INSERT YOUR CLIENT SECRET';
        const ANALYTICS_SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';

        // Build a new client object to work with authorization.
        $client = new apiClient();
        $client->setClientId(CLIENT_ID);
        $client->setClientSecret(CLIENT_SECRET);
        $client->setRedirectUri(REDIRECT_URL);
        $client->setScopes(array(ANALYTICS_SCOPE));
        $client->setAccessType('offline');
        $auth = $client->authenticate();


        if ($client->getAccessToken()) {
           $token = $client->getAccessToken();
           $authObj = json_decode($token);
           $refreshToken = $authObj->refresh_token;
        }
        ?>

答案 1 :(得分:1)

对于Google Client v2的PHP SDK:

php composer.phar require google/apiclient:^2.0

您可以尝试使用PHP代码刷新accessToken,如下所示:

<?php

require_once __DIR__ . '/vendor/autoload.php';

define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
  Google_Service_Analytics::ANALYTICS_READONLY)
));

$client = new Google_Client();
$client->setApplicationName('YOUR APPLICATION NAME');
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');

// Input AccessToken from such as session or database 
$accessToken = json_decode('YOUR CURRENT ACEESS TOKEN');

$client->setAccessToken($accessToken);

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    // Get RefreshToken as json which can be reused
    $refreshToken = json_encode($client->getAccessToken());
}

离线访问问题

此外,如果要保留服务器端应用程序中的现有行为,则需要将approval_prompt设置为force,否则可能会从getRefreshToken()返回NULL,文件没有提到:

$client->setApprovalPrompt('force');
  

参考Upcoming changes to OAuth 2.0 endpoint