我正在使用 Google 分析 API (PHP) 来检索我的帐户信息,我使用以下方式检索了刷新令牌:
if (isset($_SESSION['token'])) {
// echo $_SESSION['token'].'<br />';
$authObj = json_decode($_SESSION['token']);
$accessToken = $authObj->access_token;
$refreshToken = $authObj->refresh_token;
$tokenType = $authObj->token_type;
$expiresIn = $authObj->expires_in;
echo 'access_token = ' . $accessToken;
echo '<br />';
echo 'refresh_token = ' . $refreshToken;
echo '<br />';
echo 'token_type = ' . $tokenType;
echo '<br />';
echo 'expires_in = ' . $expiresIn;
echo '<br />';
}
之后我复制了返回的值$refreshToken
,我注释了前一个函数并调用了如下方法:
$refreshToken = '1/YZiV9J********vMjey8*****************';
$client->refreshToken($refreshToken);
这很完美,但是一个小时后它通过一个错误告诉我访问令牌已过期。
我怎么知道访问令牌已过期,我找到了这篇文章,这家伙解决了他的问题,但他没有发布答案。以及如何使用相同的刷新令牌生成一个新令牌而无需再次通过授权过程,因为我正在通过终端运行我的代码。
我在下面发布了我项目的一个片段。
谢谢!
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
$scriptUri = 'http://domainname.com';
session_start();
$client = new Google_Client();
$client->setApplicationName('Google Analytics project');
$client->setClientId('************.apps.googleusercontent.com');
$client->setClientSecret('S**********************1T');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('**************************-1c');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline');
$client->setUseObjects(true);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$authObj = json_decode($_SESSION['token']);
$accessToken = $authObj->access_token;
$refreshToken = $authObj->refresh_token;
$tokenType = $authObj->token_type;
$expiresIn = $authObj->expires_in;
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
// Create analytics service object. See next step below.
$analytics = new Google_AnalyticsService($client);
runMainDemo($analytics);
}
function runMainDemo(&$analytics) {
try {
// Step 2. Get the user's first profile ID.
$profileId = getProfileId($analytics);
if (isset($profileId)) {
// Step 3. Query the Core Reporting API.
$results = getResults($analytics, $profileId);
// Step 4. Output the results.
printResults($results);
}
}
catch (apiServiceException $e) {
// Error from the API.
print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
}
catch (Exception $e) {
print 'There wan a general error : ' . $e->getMessage();
}
}
function getProfileId(&$analytics) {
//My code to retrieve data
}