连接谷歌日历API获取空数组结果与php


Connect Google Calendar API get empty array result with php

我正在尝试使用PHP和Google官方PHP客户端库读取我的Google日历事件。

我在Google开发人员控制台中创建了一个service account,它似乎可以工作,我可以连接到日历,但是我得到一个空数组:

Google_Service_Calendar_CalendarList对象 ( [collection_key:受保护] => 项目 [internal_gapi_mappings:受保护] => 数组 ( ) [etag] => [项目类型:受保护] => Google_Service_Calendar_CalendarListEntry [项目数据类型:受保护] => 数组 [种类] => [下一页令牌] => [下一个同步令牌] => [模型数据:受保护] => 数组 ( [错误] => 数组 ( [错误] => 数组 ( [0] => 数组 ( [域] => 全局 [原因] => 权限不足 [消息] => 权限不足) ) [代码] => 403 [消息] =>权限不足) ) [已处理:受保护] => 数组 ( ) )

我的代码:

define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
session_start();
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setAuthConfigFile('client_secret.json');
$client->setAccessType('offline');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        $client->setAccessToken($_SESSION['access_token']);
        #$client->setUseObjects(true);
        $cal=new Google_Service_Calendar($client);
        $calendarList=$cal->calendarList->listCalendarList();
        while(true) {
                foreach ($calendarList->getItems() as $calendarListEntry) {
                        echo $calendarListEntry;
                }
                $pageToken = $calendarList->getNextPageToken();
                if ($pageToken) {
                        $optParams = array('pageToken' => $pageToken);
                        $calendarList = $service->calendarList->listCalendarList($optParams);
                } else {
                        break;
                }
        }
} else {
        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google/oauth2callback.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}   

谁能告诉我我做错了什么提前感谢您的帮助。

您正在使用服务帐户进行连接。 服务帐号有自己的

Google 日历帐号,默认情况下,该帐号没有任何日历,默认情况下也无法访问您的 Google 日历帐号。

这就是以下消息告诉您的内容:

权限不足

如果您想向服务帐号授予对您的 Google 日历的访问权限,则需要使用服务帐号电子邮件地址,并与其共享您的 Google 日历,就像与任何其他用户共享一样。