使用服务帐户访问 google 日历但答案变量为空

using service account to access google calendar but answer variables are empty

我创建了一个服务帐户来访问某个 google 日历。此服务帐户用户还获得了日历设置中的权限,如本博客所述:“”。

正如我在 Google Cloud Platform 下的 APIs + Services -> Credentials Service Account 部分中看到的那样,创建的服务帐户每次都用于所有服务(最近 30 天),当我启动它时php 脚本,但在浏览器中 window 我没有收到任何错误,身份验证会有问题但是: 未捕获错误:在 null 中调用成员函数 getSummary() php 脚本的行... Google Cloud Platform 中的脚本和设置如上述 post.

中所述

知道可能是什么问题吗?自 2019 年 post 以来,google 日历 api 有什么变化吗?

require '../google-api-php-client/vendor/autoload.php';
ini_set('display_errors', 1);

$client = new Google_Client();
$client->addScope("https://www.googleapis.com/auth/calendar");

$client->setAuthConfig(dirname(__FILE__).'/credentials/credentials.json');

$service = new Google_Service_Calendar($client);

$calendarList = $service->calendarList->listCalendarList();

while(true) {

  foreach ($calendarList->getItems() as $calendarListEntry) {
    echo $calendarListEntry->getSummary();
    echo "\n------------------------------\n\n";

    // get events 
    $events = $service->events->listEvents($calendarListEntry->id);

    foreach ($events->getItems() as $event) {
        echo "- " . $event->getSummary() . "\n";
        echo "- " . $event->getStart()->getDateTime() . "\n\n";
    }

  }

  $pageToken = $calendarList->getNextPageToken();

  if ($pageToken) {
    $optParams = array('pageToken' => $pageToken);
    $calendarList = $service->calendarList->listCalendarList($optParams);
  } else {

    echo "break";
   break;
  }

}
    echo "calendar summary: " . $calendarListEntry->getSummary();
    echo "\ncalendar id: " . $calendarListEntry->getId();
    echo "\n------------------------------\n\n";

显然 $calendarList 和 $calendarListEntry 是空的....

function getSummary() 无法呈现任何结果(为 null 或空)的原因是新服务帐户用户的 calendarList 为空。通过在任何其他日历中向服务帐户用户授予权限,不会自动将此日历插入到服务帐户用户的日历列表中。

所以您首先必须为服务帐户插入/创建一个日历列表:

$calendarListEntry = new Google_Service_Calendar_CalendarListEntry();
$calendarListEntry->setId("calendar_address_you_want_to_add");
$createdCalendarListEntry = $service->calendarList->insert($calendarListEntry);
echo $createdCalendarListEntry->getSummary();

现在使用第一个脚本时,您将获得 calendarEvents(只要日历中发布了任何即将发生的事件)getSummary() 函数和 getId() 函数的结果。