php - Google Cal API - 检查事件的脚本

标签 php google-calendar-api google-api-php-client

我想构建一个脚本,通过 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/

相关文章:

PHP 如何上传到 Youtube 用户的 channel

erlang - 如何在 Zotonic Erlang CMS 中嵌入和显示 Google 日历

python - 是否有可用于 google calendar api 的管理员帐户?

google-api - 在谷歌日历 API v3 中插入​​新的 calendarEntry 返回 404

php - 使用 cron 执行 PHP 将文件上传到 Google 驱动器

php - Google Calendar API v3 - 不创建事件(服务器到服务器身份验证)

php - 从 Google OAuth 2.0 PHP API 获取用户信息

javascript - 炫耀无法站出来的内容

PHP:通过关联数组发出循环

PHP - 使用 XMLWriter 将数据库导出为 XML 时缺少标签