Php 刷新Google日历API的访问令牌
目前,我正在使用此api,但令牌在3-4小时后过期,如何为Google Calendar api自动刷新访问令牌 目前的代码是:Php 刷新Google日历API的访问令牌,php,google-api,google-calendar-api,google-oauth,google-api-php-client,Php,Google Api,Google Calendar Api,Google Oauth,Google Api Php Client,目前,我正在使用此api,但令牌在3-4小时后过期,如何为Google Calendar api自动刷新访问令牌 目前的代码是: function getClient() { $client = new Google_Client(); $client->setApplicationName('Google Calendar API PHP Quickstart'); $client->setScopes(Google_Service_Calendar::CA
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig(__DIR__ . '/google-calender/credentials.json');
$client->setAccessType('offline');
$client ->setApprovalPrompt ('force');
// Load previously authorized token from a file, if it exists.
$tokenPath =__DIR__ . '/google-calender/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client; }
在请求新的访问令牌后,需要在客户端上设置新的访问令牌
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
myclient->getAccessToken()返回此值:{“访问令牌”:“ya29.gltbbgajz6eymplwdqrwe2mt-yu3sVt539OnKpu1kiy-tNtJ14rSEmopHxKW7\u vj5uz2zhpkofki4mslfaxtwxqrvekrs-GD7Th4taKteX1Q9A4f9UYVzDih-4”,“过期于”:3600,“范围”:“https:\/\/www.googleapis.com\/auth\/calendar”,“令牌类型”:“承载人”,“创建的”:1542807}访问令牌是新的刷新令牌吗?否访问令牌是用于访问API的访问令牌。它仅在一小时(3600)内有效。刷新令牌不会过期,只要您保存了一些,您就可以在需要时通过请求新的访问令牌来使用它访问用户数据。