美好的一天。我尝试了解谷歌日历api,然后我遇到了一个奇怪的问题,然后使用Oauth2。我第一次正常授权并添加事件,但在1小时后(令牌过期后)我有401错误(凭证无效)。我刷新令牌(使用refresh_token),但再次出现401错误。在https://www.googleapis.com/oauth2/v1/tokeninfo和
上测试了新令牌{
"issued_to": "***.apps.googleusercontent.com",
"audience": "***.apps.googleusercontent.com",
"scope": "https://www.googleapis.com/auth/calendar",
"expires_in": 3581,
"access_type": "offline"
}
但我有401错误然后我尝试插入事件。
持续1天。第二天,我得到了新的令牌,它再次工作了1个小时。
我的测试代码:
require_once 'google-php-api/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secret***.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
if ($_GET['logout'] == "1") {
session_unset();
} else {
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
if ($client->isAccessTokenExpired()) {
$oldToken = json_decode(file_get_contents("token.json"));
$client->refreshToken($oldToken->refresh_token);
$newAccessToken = $client->getAccessToken();
$newAccessToken['refresh_token'] = $refreshToken;
$_SESSION['access_token'] = $newAccessToken;
$client->setAccessToken($_SESSION['access_token']);
} else {
file_put_contents("token.json", json_encode($_SESSION['access_token']));
}
print_r($_SESSION['access_token']);
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2016-10-06T10:13:00.000',
'timeZone' => 'GMT +03:00',
),
'end' => array(
'dateTime' => '2016-10-06T10:15:00.000',
'timeZone' => 'GMT +03:00',
),
'attendees' => array(
array(
'email' => 'sbakul77@gmail.com',
'resource' => true
),
),
"creator"=> array(
"email" => "email@example.com",
"displayName" => "Example",
"self"=> true
),
"guestsCanInviteOthers" => false,
"guestsCanModify" => false,
"guestsCanSeeOtherGuests" => false,
));
$calendarId = '**@gmail.com';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s, Event id: %s', $event->htmlLink, $event->id);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
为什么会这样?为什么我的刷新令牌是“无效凭证”?