首页 > 解决方案 > 无法使用服务帐户访问从 API 创建的新 Google 日历

问题描述

我们正在使用 Google Calendar API 来创建日历并代表用户管理它们。

为此,我们创建一个带有 ACL 规则的日历,如下所示:

$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('/.../oauth_secret.json');
$client->setRedirectUri(REDIRECT_URI);
$client->authenticate($_GET['code']);
$accessToken = $client->getAccessToken();
$client->setAccessToken($accessToken);
$service = new Google_Service_Calendar($client);

$calendar = new Google_Service_Calendar_Calendar();
$calendar->setSummary($calendarName);
$calendar->setTimeZone('Europe/Paris');
$newCalendar = $service->calendars->insert($calendar);
$calendarId = $newCalendar->getId();

$rule = new Google_Service_Calendar_AclRule();
$scope = new Google_Service_Calendar_AclRuleScope();
$scope->setType("user");
$scope->setValue("295093256...012ulkk4oklusjh8...@developer.gserviceaccount.com");
$rule->setScope($scope);
$rule->setRole("owner");
$service->acl->insert($calendarId, $rule);

因此我们尝试像这样访问日历:

$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('/.../private_key.json');
if ($client->isAccessTokenExpired()) $client->refreshTokenWithAssertion();

$this->service = new Google_Service_Calendar(client);

$calendar = $service->calendarList->get($calendarId);

直到几个月前,这还算完美,但现在我们得到了这个错误:

google_runner error: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "Not Found"
   }
  ],
  "code": 404,
  "message": "Not Found"
 }
}

它仍然适用于之前创建的日历,但不适用于新日历。我正在请求帮助,因为我找不到原因。

请注意,ACL 已在新日历上正确创建,如您在此处看到的:

在此处输入图像描述

任何想法?

标签: google-calendar-api

解决方案


Found it!

Google does not automatically create anymore an entry to the user's calendar list when you create a calendar.

To check if the calendar exists, I just needed to replace:

$calendar = $service->calendarList->get($calendarId);

By

$calendar = $service->calendars->get($calendarId);

推荐阅读