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.
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: