我正在使用Google API客户端访问Google Analytics。我想在离线模式下访问数据,所以我需要一个刷新令牌。我如何获得refresh_token?
答案 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');