我是Goole API的新手。我想在我的网站上使用Google Calendar API。用户授予我访问权限,我将access token
存储在文件中(例如)。
白天,CRON任务通过获取来与用户的日历进行同步。
除刷新令牌访问权限外,其他所有操作均正常。这是我的代码。
为了进行测试,我将access_token
硬存储了。
<?php
require __DIR__ . '/../vendor/autoload.php';
session_start();
$redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/';
$client = new Google_Client();
$client->setClientId("aaaaaaa");
$client->setClientSecret("bbbbbbbb");
$client->setRedirectUri($redirect_uri);
$client->addScope("email");
$client->addScope(Google_Service_Calendar::CALENDAR);
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAccessType('offline');
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/');
$service = new Google_Service_Oauth2($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
}
//var_dump($_SESSION['access_token']);
if (!isset($_SESSION['access_token']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'] == "")) {
//pour les tests
echo "Come from database for example <br /><br />";
$_SESSION['access_token'] = [
"access_token" =>
yyyyyyyy",
"expires_in" =>
3600,
"scope" =>
"https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/plus.me",
"token_type" =>
"Bearer",
"id_token" =>
"xxxxxxxxxxxxx",
"created" =>
1538556145
];
//Refresh
}
$client->setAccessToken($_SESSION['access_token']);
if ($client->isAccessTokenExpired()) {
echo "<br/><h2>Refresh Token</h2><br />";
// save refresh token to some variable
$refreshTokenSaved = $client->getRefreshToken();
// update access token
$client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
// pass access token to some variable
$accessTokenUpdated = $client->getAccessToken();
// append refresh token
$accessTokenUpdated['refresh_token'] = $refreshTokenSaved;
//Set the new acces token
$_SESSION['access_token'] = $refreshTokenSaved;
$client->setAccessToken($_SESSION['access_token']);
}
$calendar = new Google_Service_Calendar($client);
$calendarList = $calendar->calendarList->listCalendarList();
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary() . "<br>";
}
如果我等待令牌的过期延迟,则在按F5时出现此错误:
致命错误:未捕获LogicException:必须传入刷新令牌 或设置为setAccessToken的一部分 /xcxcxcxcxcxcxcxcxcxcxcx/vendor/google/apiclient/src/Google/Client.php:258 堆栈跟踪:#0 /xcxcxcxcxcxcxcxcxcxcxcxc/quickstart.php(55): Google_Client-> fetchAccessTokenWithRefreshToken(NULL)#1 {main}引发 在 /xcxcxcxcxcxcxcxcxcxcxcx/vendor/google/apiclient/src/Google/Client.php 在第258行
我看到$refreshTokenSaved
是NULL
我想念什么,但是呢?谢谢