I'm attempting to have my php application call Google's Calendar API using the service to service authentication. I have administrative access over my Education G Suite, and have performed the following steps as indicated here: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
- Created a service account with domain-wide authority, and saved the proper credentials.
- Added the Calendar (Read-Write) https://www.googleapis.com/auth/calendar scope to my admin account under "Managed API Client Access" using my ClientID (which is confirmed by the UI)
- Made the proper calls to the php API client, attempting to both impersonate the admin and another user account, per the examples here: https://developers.google.com/api-client-library/php/auth/service-accounts
However, when I attempt to obtain any calendar information I continue to get the following error:
Google_Service_Exception: { "error": "unauthorized_client", "error_description": "Client is unauthorized to retrieve access tokens using this method." }
Per googling, this would typically mean that I haven't delegated domain-wide authority, but I definitely have. I've tried other Google apis with the same results.
Here's my code. Thanks for any thoughts or help.
<?php require_once __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=****/client_secret.json');
$user_to_impersonate = 'user@****.com';
$user_scopes = array(
Google_Service_Calendar::CALENDAR
);
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject($user_to_impersonate);
$client->setScopes($user_scopes);
$client->setAccessType('offline');
$calendar = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $calendar->events->listEvents($calendarId, $optParams);
...
?>