使用相同设置访问另一个日历 - Google 日历 API PHP

Access another calendar using same settings - Google Calendar API PHP

我正在使用 Google 日历 PHP API.

从日历中获取事件

一切都适用于初始日历,但现在我正在尝试使用相同的设置从另一个日历(相同的 Google 帐户)接收事件。

日志中出现以下错误:

PHP 致命错误:/www/apache/domains/www.domain.ee/htdocs/wp-content/themes/THEME/booking/vendor/google/apiclient/src/Google/Http/REST.[=36 中的消息 'Error calling GET https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID.calendar.google.com/events?maxResults=999&orderBy=startTime&singleEvents=true&timeZone=Europe%2FTallinn&timeMin=2016-09-19T00%3A01%3A00Z&timeMax=2018-07-17T00%3A00%3A00Z: (404) Not Found' 未捕获异常 'Google_Service_Exception' =]:79

这里是代码:(我唯一需要更改的是 $calendarId

require_once 'vendor/autoload.php';

$client_email = 'name@name.iam.gserviceaccount.com';
$private_key = file_get_contents('name.p12');
$scopes = array('https://www.googleapis.com/auth/calendar');
$credentials = new Google_Auth_AssertionCredentials(
    $client_email,
    $scopes,
    $private_key
);

$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion();
}

$service = new Google_Service_Calendar($client);

// Print the next 999 events on the user's calendar.
$calendarId = 'calendar_id@group.calendar.google.com';
$optParams = array(
  'maxResults' => 999,
  'orderBy' => 'startTime',
  'singleEvents' => TRUE,
  'timeZone' => 'Europe/Tallinn',
  'timeMin' => '2016-09-19T00:01:00Z',
  'timeMax' => '2018-07-17T00:00:00Z',
);
$results = $service->events->listEvents($calendarId, $optParams);

正在将相同的数据插入 Google APIs Explorer returns 正是我正在寻找的事件。

从 Google 日历 API 中的处理 API 错误,您有时得到的 error 404 意味着找不到指定的资源。其他可能的原因是请求的资源(具有提供的 ID)从未存在或访问用户无法访问的日历。

此处建议的操作是使用 exponential backoff

基于此SO question, another caused of this issue is when accessing private calendar with a service account,如果您拥有包含这些日历的域,则需要执行授权委托,或者您需要与服务帐户的电子邮件地址共享私人日历。