我正在尝试使用服务帐户从我的Google日历中获取活动。我收到了Access Token:
{ “的access_token”: “ya29.AHES6ZR9o2切-GG”, “expires_in”:3600, “创建”:1366631471}
现在这个令牌已过期,当我试图获取事件时,我收到一个错误:
OAuth 2.0访问令牌已过期,并且刷新令牌不可用。对于自动批准的响应,不会返回刷新令牌。
我试图找到在API文档中获取新访问令牌的方法,但没有找到合适的方法。现在我有一个问题:我如何刷新访问令牌?
我用来访问日历的代码:
session_start();
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_CalendarService.php';
define('SERVICE_ACCOUNT_NAME', 'numbers-and-letters@developer.gserviceaccount.com');
define('CLIENT_ID', 'numbers-and-letters.apps.googleusercontent.com');
define('KEY_FILE', '../../key.p12');
$client = new Google_Client();
$client->setApplicationName("app name");
$client->setUseObjects(true);
$client->setClientID(CLIENT_ID);
$key = file_get_contents(KEY_FILE);
if (isset($_SESSION['token']))
{
$client->setAccessToken($_SESSION['token']);
$client->setaccessType('offline');
}
else
{
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/calendar.readonly'),
$key
));
}
try
{
$cal = new Google_CalendarService($client);
$events = $cal->events->listEvents('numbers-and-letters@group.calendar.google.com');
print_r($events);
} catch (Exception $e) echo $e->getMessage();
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
答案 0 :(得分:0)
我解决了!要刷新没有刷新令牌的访问令牌,您想要调用Google_Client类的方法revokeToken()
答案 1 :(得分:0)
刷新令牌的推荐方法是:
if ($client->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion();
}