6

I'm working on a client web app where users can book drives with date, time, location...etc

the client required that every booking is added as an event on his google calendar

I created an API key and downloaded the PHP API client: https://github.com/google/google-api-php-client

But when I try to add an event I get a "Login Required" Error

How can I add an event directly without having to use OAuth and consent screen because the function will be executed automatically in the backend, I have full access to the gmail account.

MomenSh
  • 355
  • 1
  • 3
  • 13
  • 1
    You will need to get authorization from the gmail account, save the token to a database, and then handle the access tokens with the refresh token. You can read more about that here https://developers.google.com/identity/protocols/OAuth2WebServer#exchange-authorization-code – Morfinismo Jun 03 '18 at 01:00

2 Answers2

23

I got it to work using a service account and some steps based on this answer, here is what I did:

1- Create a project on Google Developer Console.

2- Go to Credentials and create a Service account key with key type JSON, a JSON file will be downloaded, move it to your project folder.

3- Enable Calendar API from Library tab, search for Calendar API and enable it.

4- Go to your Google Calendar

5- Go to Settings -> Add calendar -> New calendar, after that a notification/toast will popup click on Configure, scroll down to Share with specific people -> Add people, on the email field add the service account ID, you can get it from Credentials -> Manage service accounts then set the Permission to Make changes to events and click Send.

6- Download the PHP client library.

7- Now you need to get the calendar ID, from calendar settings scroll down to last section you will find it, or here is a sample code to get it, look for it in the response, it will be something like this 'j85tnbuj1e5tgnizqt9faf2i88@group.calendar.google.com':

<?php
require_once 'google-api/vendor/autoload.php';

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=google-api/test-calendar-serivce-1ta558q3xvg0.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

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

8- You can now add events to the calendar, sample code:

$event = new Google_Service_Calendar_Event(array(
  'summary' => 'Test Event',
  'description' => 'Test Event',
  'start' => array(
    'dateTime' => '2018-06-02T09:00:00-07:00'
  ),
  'end' => array(
    'dateTime' => '2018-06-10T09:00:00-07:00'
  )
));

$calendarId = 'j85tnbuj1e5tgnizqt9faf2i88@group.calendar.google.com';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);

What happens here is that the event is created by the service account which is different than your own google account and has it's own data so if you didn't share the calendar with the service account and set the calendar id to primary it will create the event on the service account calendar which you can't access it normally.

I hope this helps anyone.

References:
https://stackoverflow.com/a/26067547/8702128
https://github.com/google/google-api-php-client
https://developers.google.com/calendar/quickstart/php
How to insert event to user google calendar using php?

MomenSh
  • 355
  • 1
  • 3
  • 13
1

I got this to work in php 8.1.10

You need to create a service account at: https://console.cloud.google.com/

But once created, you need to click on the email link which will take you to another page. Then choose KEYS and then click ADD KEY. When prompted choose JSON. This will create a key that you can use in the below example. You will also have to use the service email and enter that into the calendar settings and sharing panel and allow it to "make changes to events".

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// require the Google Client Library and create a new client object
require_once __DIR__.'/vendor/autoload.php';
$client = new Google_Client();

// specify the credentials you obtained when you set up your project
//https://console.cloud.google.com/
$client->setAuthConfig('YOUR JSON CREDENTIAL FILE FROM SERVICE ACCOUNT');
$client->addScope(Google_Service_Calendar::CALENDAR);

// authenticate with the Google Calendar API
$service = new Google_Service_Calendar($client);

// create a new event object
$event = new Google_Service_Calendar_Event();

// specify the details of the event, such as the title, start and end time, etc.
$event->setSummary('Example Event');
$event->setLocation('Example Location');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2022-12-09T09:00:00Z');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2022-12-09T17:00:00Z');
$event->setEnd($end);

// insert the event into the calendar
$calendarId = 'YOUR GOOGLE CALENDAR ID THAT YOU SHARED WITH SERVICE ACCOUNT EMAIL - ALLOW MAKE CHANGES TO EVENTS specify the calendar you want to post the event to
$event = $service->events->insert($calendarId, $event);

// print the event details
echo 'Event created: ' . $event->getHtmlLink();
Aron Nelson
  • 838
  • 1
  • 9
  • 17