使用API v3访问Google日历

5
我正在尝试使用Google Calendar v3 API重写一款遗留应用程序,这是我之前没有编写过的。我已经实现了google-api-php-client,在开发者控制台中创建了API密钥并完成了身份验证过程。我获得了一个accessToken,并将其持久化存储在数据库中,当它过期时,我可以很好地刷新该令牌。然而,我无法与日历进行任何操作。我正在遵循现有的有限文档,并具有以下内容:
$this->client = new Google_Client();
$this->client->setClientId( $this->settings['clientId'] );
$this->client->setClientSecret( $this->settings['clientSecret'] );
$this->client->setAccessToken( $this->settings['accessToken'] );

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

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

while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
    echo $calendarListEntry->getSummary();
}

$pageToken = $calendarList->getNextPageToken();

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

我收到的错误信息是:
Message:  Undefined property: Google_Service_Calendar_CalendarList::$items

我已经检查了我的Google日历帐户,所有的日历都是共享的,所以应该没有问题,尽管我不明白为什么这是个问题,因为我正在使用一个经过身份验证的帐户。有人能提供建议吗?非常感谢。

你尝试过在这里调试你的日历列表调用吗?https://developers.google.com/google-apps/calendar/v3/reference/calendarList/list#try-it 确保你从“$calendarList->getItems()”得到了响应。 - Sir_Faenor
是的,当我使用“尝试”功能时,它可以很好地返回日历。 - madebyhippo
你能发布 var_dump($calendarList->getItems()) 的输出吗? - Sir_Faenor
是的,对它进行 var_dump 返回 NULL。 - madebyhippo
1个回答

2
您收到的错误信息是:
Message:  Undefined property: Google_Service_Calendar_CalendarList::$items

由于对象为空

替换

while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
    echo $calendarListEntry->getSummary();
}Undefined property

使用这个方法可以摆脱错误。
if ($calendarList->getItems()) {
    foreach ($calendarList->getItems() as $calendarListEntry) {
    echo $calendarListEntry->getSummary();

    }

同时调整以下内容
$this->client = new Google_Client();

需要

$client = new Google_Client();

那也不行。返回错误信息:“无法在写入上下文中使用方法返回值”。 - madebyhippo
1
它修复了那个特定的问题 - 但我仍然得到“Message: Undefined property: Google_Service_Calendar_CalendarList::$items” - madebyhippo
将 $this->client = new Google_Client(); 更改为 $client = new Google_Client(); - Jonny C
您提供的代码无效。按照我的建议修复第一行后,代码可以正常工作。您在CodeIgniter中还有一个单独的问题。 - Jonny C
让我们在聊天中继续这个讨论 - Jonny C
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接