access user calendar with service account

2019-02-26 03:42发布

问题:

I have a php application on my intranet that needs to add events in the calenders of my users.

I followed the following instructing https://developers.google.com/+/domains/authentication/delegation

I setup the google-api-php client and used the example service-accounts.php as my starting point.

$client_id = 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr.apps.googleusercontent.com';
$service_account_name = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy@developer.gserviceaccount.com';
$key_file_location = 'file.p12';

$client = new Google_Client();
$client->setApplicationName("egw - intranet");
$service = new Google_Service_Calendar($client);
//authenticate
if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/calendar'),
    $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

$event = new Google_Service_Calendar_Event();
$event->setSummary('API V3 TEST');
$event->setLocation('rrrrrrrrrrrrrrrrrrrrrrrrr');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2014-11-03T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2014-11-04T10:25:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('email@domain.com');

$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events- >insert('email2@domain.com', $event);

echo $createdEvent->getId();

I'm recieving 404 not found error. If I manually share the calendar I am using for my test with the service account, It works. But I would like for my program to also work without manually sharing each and every calendar of all my users. Can somebody tell me what I am missing?

Kind regards,

回答1:

You cannot add an event to a calendar that has not been specifically shared with your Google project. You must either share each calendar with the service account, or you must use OAuth2 with web application credentials so that each user can give you access.



回答2:

When I started this the current client google-php-api-client was 1.1.0-beta. Some weeks later we are now at 1.1.2. Upgrading to this version resolved my problem. Adding a service-account gives an application the possibility to identify itself with Google. If you add the scopes to the google admin console as I have done, The service-account has access to all the data specified by the scope for every user in the domain. Thx all for the responses.