【问题标题】:Connect Google Calendar API get empty array result with php使用 php 连接 Google Calendar API 获取空数组结果
【发布时间】:2016-03-16 07:59:57
【问题描述】:

我正在尝试使用 PHP 和 Google 的官方 PHP 客户端库来阅读我的 Google 日历活动。

我在Google Developers Console 中创建了一个service account,它似乎可以工作,我可以连接到日历但我得到一个空数组:

Google_Service_Calendar_CalendarList 对象 ( [collection_key:protected] => 项目 [internal_gapi_mappings:protected] => 数组 ( ) [etag] => [itemsType:protected] => Google_Service_Calendar_CalendarListEntry [itemsDataType:protected] => 数组 [种类] => [nextPageToken] => [nextSyncToken] => [modelData:protected] => 数组 ( [error] => 数组 ( [errors] => 数组 ( [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));
}   

谁能告诉我我做错了什么 在此先感谢您的帮助。

【问题讨论】:

    标签: php google-calendar-api google-api-php-client service-accounts


    【解决方案1】:

    您正在使用服务帐户进行连接。服务帐户有自己的 Google 日历帐户,默认情况下没有任何日历,并且默认情况下无权访问您的 Google 日历帐户。

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

    权限不足

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

    【讨论】:

    • 我使用了授权 API 访问 (OAuth 2.0),并在 Google Developers Console 中创建了一个客户端 ID。我该怎么办?
    • 我认为您需要阅读更多内容。您说您使用的是服务帐户,但您的代码适用于 Oauth2。如果您想使用该代码,则需要在 Google 开发人员控制台类型的浏览器中创建 oauth2 凭据。然后它会弹出并询问您访问用户日历的权​​限
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 2016-10-23
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多