我一直在尝试使用PHP访问Google Calendar API v3 . 最初,我想简单列出我可以访问API的用户日历 .
为此,我已经下载了Google API PHP客户端库,并尝试使用以下代码(来自https://mytechscraps.wordpress.com/2014/05/15/accessing-google-calendar-using-the-php-api/的源代码,我的改编):
<?php
//error_reporting(0);
//@ini_set('display_errors', 0);
// If you've used composer to include the library, remove the following line
// and make sure to follow the standard composer autoloading.
// https://getcomposer.org/doc/01-basic-usage.md#autoloading
require_once './google-api-php-client-master/autoload.php';
// Service Account info
$client_id = '754612121864-pmdfssdfakqiqblg6lt9a.apps.googleusercontent.com';
$service_account_name = '754674507864-pm1dsgdsgsdfsdfsdfdflg6lt9a@developer.gserviceaccount.com';
$key_file_location = 'Calendar-7dsfsdgsdfsda953d68dgdsgdsff88a.p12';
$client = new Google_Client();
$client->setApplicationName("Calendar");
$service = new Google_Service_Calendar($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar.readonly'),
$key
);
$client->setAssertionCredentials($cred);
$cals = $service->calendarList->listCalendarList();
print_r($cals);
?>
我在Google Developers控制台中创建了一个服务帐户,并生成了OAuth详细信息,我已经用它来设置相应的变量,这可以从代码中看到 .
此代码返回以下内容:
Google_Service_Calendar_CalendarList Object ( [collection_key:protected] => items [internal_gapi_mappings:protected] => Array ( ) [etag] => "14171313334000" [itemsType:protected] => Google_Service_Calendar_CalendarListEntry [itemsDataType:protected] => array [kind] => calendar#calendarList [nextPageToken] => [nextSyncToken] => 000014121268327000 [modelData:protected] => Array ( [items] => Array ( [0] => Array ( [kind] => calendar#calendarListEntry [etag] => "1417721316542000" [id] => bots@madeupcompany.co.uk [summary] => bots@madeupcompany.co.uk [timeZone] => Europe/London [colorId] => 23 [backgroundColor] => #cd74e6 [foregroundColor] => #000000 [selected] => 1 [accessRole] => reader [defaultReminders] => Array ( ) ) ) ) [processed:protected] => Array ( ) )
问题是,这似乎只返回一个日历的细节 . 也就是bots@madeupcompany.co.uk的日历(我明确与我的服务共享的唯一一个) .
但是,我知道这个谷歌帐户具有对许多其他用户日历的只读访问权限(我可以在以此用户身份登录Google日历时看到它们) .
此外,如果我在此页面上使用Google Apps Explorer:https://developers.google.com/google-apps/calendar/v3/reference/calendarList/list#auth,在以bots@madeupcompany.co.uk登录我的Google帐户后,我会获得所有其他日历的详细信息 .
所以我正在努力解决,为什么Apps Explorer会向我显示所有其他日历,但PHP代码却没有?
1 回答
服务帐户无需提示用户进行访问,因为您必须进行设置 . 转到Google日历网站 . 找到“日历设置”,然后转到“日历”标签,找到要访问的日历,然后单击“共享:编辑设置”,添加服务帐户电子邮件地址,就像添加个人电子邮件地址一样 . 这将为服务帐户提供与您与任何其他用户共享访问权限相同的访问权限 .
代码从教程中删除Google Calendar API with PHP – Service Account