Как я могу показать список * всех * доступных календарей с помощью Google Calendar API v3 / Google API Client Library?

Я пытаюсь получить доступ к Google Calendar API v3 с помощью PHP. Сначала я хочу просто перечислить календари пользователей, которые доступны для моего вызова API.

Для этого я загрузил клиентскую библиотеку PHP Google API и попытался использовать следующий код (полученный с моими изменениями из 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 и сгенерировал данные 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] => [email protected] [summary] => [email protected] [timeZone] => Europe/London [colorId] => 23 [backgroundColor] => #cd74e6 [foregroundColor] => #000000 [selected] => 1 [accessRole] => reader [defaultReminders] => Array ( ) ) ) ) [processed:protected] => Array ( ) )

Проблема в том, что, похоже, возвращается информация только об одном календаре. То есть календарь для [email protected] (единственный, которым я явно поделился с моей службой).

Однако я знаю, что эта учетная запись Google имеет доступ только для чтения к ряду календарей других пользователей (я могу видеть их, когда зашел в Календарь Google как этот пользователь).

Кроме того, если я использую Google Apps Explorer на этой странице: https://developers.google.com/google-apps/calendar/v3/reference/calendarList/list#auth, войдя в свою учетную запись Google как [email protected], я получаю подробную информацию о < em> все из этих календарей.

Итак, я пытаюсь понять, почему обозреватель приложений показывает мне все другие календари, а код PHP - нет?


person William Gordon    schedule 05.12.2014    source источник
comment
Вы пытались добавить календари через службы календаря и проверить, есть ли они в списке? developers.google.com/google-apps/calendar/v3/ ссылка /   -  person Sariq Shaikh    schedule 05.12.2014


Ответы (1)


Сервисный аккаунт не должен запрашивать у пользователя доступ, потому что вам нужно его настроить. Перейдите на сайт Календаря Google. Найдите настройки календаря, затем перейдите на вкладку «Календари», найдите календарь, к которому вы хотите получить доступ, и нажмите «Общий доступ: редактировать настройки», добавьте адрес электронной почты учетной записи службы, как если бы вы использовали адрес электронной почты человека. Это предоставит учетной записи службы такой же доступ, как если бы вы делились ею с любым другим пользователем.

<?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> 

код взят из учебника API Календаря Google с PHP - Учетная запись службы

person DaImTo    schedule 05.12.2014