我想构建一个脚本,通过 Google 日历 PHP 客户端检查经过身份验证的用户的 Google 日历。我能够构建一个简单的页面,让用户进行身份验证并授予日历事件权限。我收到一个 token ,然后通过以下方式获取 15 个即将举行的事件:
$googleCal = new Google_Service_Calendar($googleClient);
$results = $googleCal->events->listEvents($calendarId, $optParams);
但是我正在努力解决的是如何保存它,以便我可以让脚本每天检查它以查看是否添加了新事件。我认为我已经很接近了,只是努力冲过终点线。
谢谢!
--
更新,我正在尝试使用刷新 token ,这是我的代码:
public function checkRedirectCode()
{
if(isset($_GET['code']))
{
$this->client->authenticate($_GET['code']);
// $this->setToken($this->client->getRefreshToken());
$this->setToken($this->client->getAccessToken());
$this->storeUser($this->getPayload());
return true;
}
return false;
}
public function setToken($token)
{
$_SESSION['access_token'] = $token;
$this->client->setAccessToken($token);
}
我已经能够回显刷新 token ,所以我知道我得到了正确的刷新 token ,但每当我使用注释掉的字符串时,我都会收到错误。有什么想法吗?
最佳答案
为了使您的脚本能够在原始访问 token 的生命周期(仅持续一小时)之外被调用,您需要在初始授权期间检索并存储刷新 token ,然后使用它来生成新的访问权限每次脚本运行时都会生成 token 。
Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.
https://developers.google.com/identity/protocols/OAuth2#basicsteps (4. 如有必要,请刷新访问 token 。)
用户对您的应用进行身份验证后,将使用 code
查询字符串返回到您的重定向 URI。
以下是验证和获取刷新 token 的示例(这使用 Analytics,但对于其他服务应该相同):
$client = new Google_Client();
$client->setClientId('xxx');
$client->setClientSecret('xxx');
$client->setRedirectUri('xxx');
//authenticate with the code returned from google
$authenticate = $client->authenticate($_GET['code']);
//get the refresh token
$refreshToken = $client->getRefreshToken();
//store refresh token in database...
然后,当您运行日常脚本时,使用刷新 token (从数据库检索)生成新的访问 token :
$client = new Google_Client();
$client->setClientId('xxx');
$client->setClientSecret('yyy');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->refreshToken($user->refresh_token);
$newToken = $client->getAccessToken();
$client->setAccessToken($newToken);
关于php - Google Cal API - 检查事件的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35591224/