- I have created a GSuite account with a domain called redu.club
- I created a project and a service account using GSuite admin email
- Added that service account to the admin calendar using share settings and have given full manage rights.
I am trying to create secondary calendars under the redu-admin@redu.club account. Here is the code I have:
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/redu-service-account.json'); define('SCOPES', Google_Service_Calendar::CALENDAR); function createCalendar() { try { // Create and configure a new client object. $client = new Google_Client(); $client->setApplicationName('Redu'); $client->useApplicationDefaultCredentials(); $client->addScope([SCOPES]); $client->setAccessType('offline'); $service = new Google_Service_Calendar($client); // Calendar creation $calendar = new Google_Service_Calendar_Calendar(); $calendar->setSummary('test'); $calendar->setTimeZone('America/Los_Angeles'); $createdCalendar = $service->calendars->insert($calendar); // Make the newly created calendar public $rule = new Google_Service_Calendar_AclRule(); $scope = new Google_Service_Calendar_AclRuleScope(); $scope->setType("default"); $scope->setValue(""); $rule->setScope($scope); $rule->setRole("reader"); $createdRule = $service->acl->insert($createdCalendar->getId(), $rule); return $createdCalendar->getId(); } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
This code creates a calendar but when I go to the calendar of redu-admin@redu.club, I can’t see it. My guess is it’s creating a calendar under the service account. When I try adding the line
$this->client->setSubject('redu-admin@redu.club');
, the error I get is:
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": "unauthorized_client", "error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."
Any help is greatly appreciated.
Advertisement
Answer
If you want to create a secondary calendar for a user, you need to impersonate this user
You already tried it correctly:
$client = new Google_Client(); $client->setApplicationName('Redu'); $client->useApplicationDefaultCredentials(); $client->addScope([SCOPES]); $client->setAccessType('offline'); $client->setSubject('redu-admin@redu.club'); $service = new Google_Service_Calendar($client);
But there two important steps that need to be followed previously:
- Enable domain-wide delegation for the service account in the GCP console
- Provide the service account the necessary delegation scopes in the Admin console