我正在使用 Google API 客户端访问 Google Analytics。我想在离线模式下访问数据,所以我需要一个刷新令牌。如何获得 refresh_token?
问问题
10829 次
2 回答
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;
}
?>
于 2012-07-03T17:30:27.150 回答
4
对于 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,Google 文档没有提到:
$client->setApprovalPrompt('force');
于 2017-06-04T09:15:13.367 回答