phpgoogle-apigoogle-calendar-apigoogle-api-php-clientservice-accounts

Google Calendar Add Event in PHP


I am new to Google Calendar API, and am having a tough time getting the program to work. I am trying to build a webpage to allow other users to book appointments, and the appointment will be auto added to my personal google calendar. So, there would be no login required to create this event, as I'm trying to add to my google calendar and not theirs.

The project does have Calendar API enabled.

I have setup a service account in Google Cloud Console for the project, and generated json file.

I am using my personal gmail account, and have shared the calendar with the service account id xxxxx@xxxxx.iam.gserviceaccount.com and have given it permission to Make changes and manage sharing.

I got the Calendar ID from the Gmail Calendar -> Integrate calendar section.

$serviceAccountFile = "pathtoserviceaccountjson";
$client = new Client();
$client->setApplicationName("Calendar Appointment");
$client->setAuthConfig($serviceAccountFile);
$client->setScopes(Calendar::CALENDAR);
$client->setAccessType('offline');
$calendarId = 'Google calendar id';

$service = new Calendar($client);

$calendarList = $service->calendarList->listCalendarList();

$event = new Calendar\Event(array(
'summary' => 'Test Event',
'description' => 'Test Event',
'start' => array(
  'dateTime' => '2024-12-06T09:00:00-07:00'
),
'end' => array(
  'dateTime' => '2024-12-06T10:00:00-07:00'
)
));

$client->setSubject(subjectline);
$event = $service->events->insert($calendarId, $event);

However, each time I tried to run it, I am getting this error.

Fatal error: Uncaught Google\Service\Exception: { "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."

If it should work, can anyone tell me what I might be doing incorrectly?

Thank you.

I am getting conflicting information on different forums. A lot of the information appeared to be outdated. Does service account work on personal gmail accounts, or will it only work with Google Workspace account?


Solution

  • I am using my personal gmail account,

    Google calendar api only supports service accounts if you are using it from a Google workspace domain account and have configured Domain wide deligation.

    You cant use it with a standard user gmail account, you need to switch to Oauth2 store the refresh token and just use that to access your account.