Google API PHP客户端 - 检索日历列表和事件

时间:2014-06-02 20:55:02

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

google calendar api的文档已过期,我甚至无法获得简单的日历列表。到目前为止,这是我的代码。

<?php
require_once "includes/partials/_header.php";
set_include_path(get_include_path() . '/google-api-php-client/src');

$client_id = 'xxxx.apps.googleusercontent.com';
$service_account = 'xxxx@developer.gserviceaccount.com';
$p12 = 'xxxx-privatekey.p12';

session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';

$client = new Google_Client();
$client->setApplicationName("Calendrier");

if (isset($_SESSION['token'])) {
 $client->setAccessToken($_SESSION['token']);
}

$key = file_get_contents($p12);
$client->setClientId($client_id);
$cred = new Google_Auth_AssertionCredentials(
    $service_account,
    array('https://www.googleapis.com/auth/calendar'),
    $key);

$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

$cal = new Google_Service_Calendar($client);

$events = $cal->calendarList->listCalendarList();
echo "<pre>";
print_r($events);
echo"</pre>";

while(true) {
    foreach ($events->getItems() as $event) {
    echo $event->getSummary();
        print_r($event);
  }
  $pageToken = $events->getNextPageToken();
  if ($pageToken) {
    $optParams = array('pageToken' => $pageToken);
    $events = $service->calendarList->listCalendarList($optParams);
  } else {
    break;
  }
}
?>

我从不同的网站获得了很多这些代码,因为文档已经过时了,现在我完全陷入困境,因为我一整天都在谷歌上搜索。有什么见解吗?

我到目前为止得到的是这样的回复,没有“项目”

Google_Service_Calendar_CalendarList Object
(
    [etag] => "xxxxxxxxxxxx"
    [itemsType:protected] => Google_Service_Calendar_CalendarListEntry
    [itemsDataType:protected] => array
    [kind] => calendar#calendarList
    [nextPageToken] => 
    [nextSyncToken] => 00001401741798955000
    [collection_key:protected] => items
    [modelData:protected] => Array
        (
            [items] => Array
                (
                )

        )

    [processed:protected] => Array
        (
        )

)

1 个答案:

答案 0 :(得分:3)

好吧,在我花在这上面的所有时间之后,这是令人尴尬的。出于某种原因,我从未尝试过公开日历。我只是假设您可以通过所有授权步骤从项目帐户访问日历。猜不是。

轻松修复...只需在其设置中公开日历。

for events用

替换$ cal-&gt; calendarlist part
$cal->events->listEvents('calendarID', $optionalParams);

注意:我甚至不确定会话中的所有授权/访问令牌内容是否需要google cal的文档页面仍然使用旧的PHP客户端。我相信它应该只使用服务帐户(setAssertionCredentials),其余的会话我不确定。