需要在不公布日历的情况下从Calendar API读取

时间:2015-12-03 21:02:55

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

感谢您的时间。我已经找到了关于如何为公共日历执行此操作的文档,但我需要它来创建一个不会与世界共享的日历。

这是我的代码:

include( __DIR__ . '/composer/vendor/google/apiclient/autoload.php' ); 

$client_email = 'me@googletokenaccount.com';
$private_key = file_get_contents('/home/serverSecret.json');
$scopes = array( Google_Service_Drive::DRIVE_METADATA_READONLY );
$credentials = new Google_Auth_AssertionCredentials( $client_email, $scopes, $private_key );

$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ( $client->getAuth()->isAccessTokenExpired() )
{
    $client->getAuth()->refreshTokenWithAssertion();
}

$client->setApplicationName("A Calendar");
$cal = new Google_Service_Calendar($client);
$calendarId = 'me@gmail.com';
$params = array( 'singleEvents' => true, 'orderBy' => 'startTime', 'timeMin' => date(DateTime::ATOM), 'maxResults' => 7 );
$events = $cal->events->listEvents($calendarId, $params); 
$calTimeZone = $events->timeZone;
date_default_timezone_set($calTimeZone);

foreach ($events->getItems() as $event)
{
    // Get the timings
    $eventDateStr = $event->start->dateTime;
    if(empty($eventDateStr)) { $eventDateStr = $event->start->date; } // Handle all-day events
    $temp_timezone = $event->start->timeZone;

// Timezone override if applicable
if (!empty($temp_timezone)) { $timezone = new DateTimeZone($temp_timezone); }
else { $timezone = new DateTimeZone($calTimeZone); }

// Set up the timings
$eventdate = new DateTime($eventDateStr,$timezone);
$link = $event->htmlLink;
$TZlink = $link . "&ctz=" . $calTimeZone;
$newmonth = $eventdate->format("M");
$newday = $eventdate->format("j");
?>
<div class="event-container">
    <div class="eventDate">
    <span class="month"><?=$newmonth?></span>
    <br />
    <span class="day"><?=$newday?></span>
    <span class="dayTrail"></span>
    </div>

    <div class="eventBody">
        <a href="<?=$TZlink?>"><?=$event->summary?></a>
    </div>
</div>
<?php 
} 
?>

当我使用客户端密钥将其与公共日历一起使用时,上述工作正常,但当日历变为私有时,则不能使用。我需要知道如何验证私人日历。

1 个答案:

答案 0 :(得分:0)

您需要OAuth 2.0服务才能访问私人数据:您可能需要创建服务帐户:

  

通常,应用程序在应用程序时使用服务帐户   使用Google API处理自己的数据而不是用户的数据。   例如,使用Google Cloud Datastore获取数据的应用程序   持久性将使用服务帐户来验证其调用   Google Cloud Datastore API。

     

https://developers.google.com/identity/protocols/OAuth2ServiceAccount