Search code examples
phpgoogle-calendar-apigoogle-api-php-clientgoogle-workspaceservice-accounts

Google API subscribe a user to a calendar


My PHP code uses a service account to create a new user in G Suite/Google Workspace. That part is working fine, but then I'd like to auto-subscribe the new user to some of our standard office calendars. When I run the following code, the calendar is added to the service account's list, not the new user.

$service = new Google_Service_Calendar($client);
$calendarListEntry = new Google_Service_Calendar_CalendarListEntry();
$calendarListEntry->setId("CalendarID");
$calendarListEntry = $service->calendarList->insert($calendarListEntry);

Is there anyway to insert into anther users calendarList?


Solution

  • A service account has its own google calendar account any actions you preform will be preformed on the service accounts google calendar account.

    However if you want to impersonate a user when you declarer your client you need to ensure that you add the subject or the person who you wish to impersonate.

    putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
    $client = new Google\Client();
    $client->useApplicationDefaultCredentials();
    Set the scopes required for the API you are going to call
    $client->addScope(Google\Service\CALENDAR::CALENDAR);
    $client->setSubject($user_to_impersonate);