且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Google Calendar API v3/Google API客户端库显示所有可用日历的列表?

更新时间:2022-03-17 23:15:48

服务帐户不需要提示用户访问权限,因为您必须对其进行设置.转到Google日历网站.找到日历设置",然后转到日历"选项卡,找到要访问的日历,然后单击共享:编辑设置",就像添加个人电子邮件地址一样添加服务帐户电子邮件地址.就像您与任何其他用户共享服务帐户一样,这将赋予该服务帐户相同的访问权限.

A service account doesn’t need to prompt a user for access because you have to set it up. Go to the Google Calendar website. Find the Calendar Settings , then go to the Calendars tab, find the calendar you want to access and click on "Shared: Edit settings" add the service account email address like you would a persons email address. This will give the service account the same access as if you where sharing it with any other user.

<?php
session_start();        
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';     
/************************************************   
 The following 3 values an befound in the setting   
 for the application you created on Google      
 Developers console.         Developers console.
 The Key file should be placed in a location     
 that is not accessable from the web. outside of 
 web root.   

 In order to access your GA account you must    
 Add the Email address as a user at the     
 ACCOUNT Level in the GA admin.         
 ************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com';     
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';     
$client = new Google_Client();      
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);    
// seproate additional scopes with a comma   
$scopes ="https://www.googleapis.com/auth/calendar.readonly";   
$cred = new Google_Auth_AssertionCredentials(    
    $Email_address,      
    array($scopes),     
    $key         
    );      
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {        
    $client->getAuth()->refreshTokenWithAssertion($cred);       
}       
$service = new Google_Service_Calendar($client);    

?>

<html><body>

<?php
$calendarList  = $service->calendarList->listCalendarList();
print_r($calendarList);
while(true) {
    foreach ($calendarList->getItems() as $calendarListEntry) {
        echo "<a href='Oauth2.php?type=event&id=".$calendarListEntry->id." '>".$calendarListEntry->getSummary()."</a><br>\n";
    }
    $pageToken = $calendarList->getNextPageToken();
    if ($pageToken) {
        $optParams = array('pageToken' => $pageToken);
        $calendarList = $service->calendarList->listCalendarList($optParams);
    } else {
        break;
    }
}    

?>
</html> 

从教程带有PHP的Google日历API –服务中摘录的

代码帐户