Php create event google calendar

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

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 = '';
$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?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

<?php

classGoogleCalendarApi

{

    publicfunctionGetAccessTokenRefresh($client_id,$redirect_uri,$client_secret, $code)

    {

        $url='https://accounts.google.com/o/oauth2/token';

        $curlPost='client_id='. $client_id.'&redirect_uri='.$redirect_uri.'&client_secret='.$client_secret.'&code='.$code .'&grant_type=authorization_code';

        $ch=curl_init();

        curl_setopt($ch,CURLOPT_URL, $url);

        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

        curl_setopt($ch, CURLOPT_POST,1);

        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);

        curl_setopt($ch, CURLOPT_POSTFIELDS,$curlPost);

        $data=json_decode(curl_exec($ch),true);

        $http_code =curl_getinfo($ch,CURLINFO_HTTP_CODE);

        if($http_code!=200){

            throw newException('Error : Failed to receieve access token');

        }

        return$data;

    }

    public functionGetUserCalendarTimezone($access_token)

    {

        $url_settings='https://www.googleapis.com/calendar/v3/users/me/settings/timezone';

        $ch =curl_init();

        curl_setopt($ch,CURLOPT_URL,$url_settings);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

        curl_setopt($ch,CURLOPT_HTTPHEADER,array('Authorization: Bearer '. $access_token));

        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);

        $data= json_decode(curl_exec($ch),true);

        $http_code=curl_getinfo($ch,CURLINFO_HTTP_CODE);

        if ($http_code!=200)

            thrownewException('Error : Failed to get timezone');

        return $data['value'];

    }

    publicfunctionCreateCalendarEvent($calendar_id,$summary,$all_day, $event_time,$event_timezone,$access_token)

    {

        $url_events='https://www.googleapis.com/calendar/v3/calendars/'. $calendar_id.'/events';

        $curlPost=array('summary'=>$summary);

        if ($all_day==1){

            $curlPost['start']=array('date'=> $event_time['event_date']);

            $curlPost['end']=array('date'=> $event_time['event_date']);

        }else{

            $curlPost['start']= array('dateTime'=>$event_time['start_time'],'timeZone'=>$event_timezone);

            $curlPost['end'] =array('dateTime'=>$event_time['end_time'],'timeZone'=>$event_timezone);

        }

        $ch =curl_init();

        curl_setopt($ch,CURLOPT_URL,$url_events);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

        curl_setopt($ch,CURLOPT_POST,1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);

        curl_setopt($ch,CURLOPT_HTTPHEADER,array('Authorization: Bearer '. $access_token,'Content-Type: application/json'));

        curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($curlPost));

        $data=json_decode(curl_exec($ch),true);

        $http_code= curl_getinfo($ch,CURLINFO_HTTP_CODE);

        if($http_code!=200)

            throw newException('Error : Failed to create event');

        return$data['id'];

    }

}

$capi= newGoogleCalendarApi();

constAPPLICATION_ID='YOUR APPLICATION ID';

constAPPLICATION_REDIRECT_URL='http://127.0.0.1:8081/magento236/add_event.php';

constAPPLICATION_SECRET ='c88TmBa5qo8cPAMMheV0agr9';

if(isset($_GET['code'])){

    $CODE=$_GET['code'];

    $data =$capi->GetAccessTokenRefresh(APPLICATION_ID,APPLICATION_REDIRECT_URL,APPLICATION_SECRET,$CODE);

    $access_token= $data['access_token'];

    $user_timezone=$capi->GetUserCalendarTimezone($data['access_token']);

    $calendar_id ='primary';

    $event_title='Event Title Meetanshi';

// Event starting & finishing at a specific time

    $full_day_event=0;

    $event_time =['start_time'=>'2021-12-15T13:00:00','end_time'=>'2021-12-15T13:15:00'];

// Full day event

    $full_day_event=1;

    $event_time =['event_date'=>'2021-12-15'];

// Create event on primary calendar

    $event_id=$capi->CreateCalendarEvent($calendar_id, $event_title,$full_day_event,$event_time,$user_timezone,$data['access_token']);

    echo'new event added';

    echo'
'
;

    echo'event Id:-'.$event_id;

}else{

    $url=$login_url= 'https://accounts.google.com/o/oauth2/auth?scope='.urlencode('https://www.googleapis.com/auth/calendar').'&redirect_uri='.APPLICATION_REDIRECT_URL.'&response_type=code&client_id='. APPLICATION_ID.'&access_type=offline';

    echo'click here add event';

}

exit();

How do I get Google Calendar events in PHP?

A Google account with Google Calendar enabled..
Step 1: Install the Google Client Library. composer require google/apiclient:^2.0. ... .
Step 2: Set up the sample. Create a file named quickstart.php in your working directory and copy in the following code: ... .
Step 3: Run the sample. Run the sample using the following command:.

How do I create a Google Calendar event?

Event options.
On your computer, open Google Calendar..
In the top left corner, click Create ..
Add a description for your event..
Under the date and time, check the box next to All day..
Click Save..

How do I add an event to my Google Calendar from a website?

Generate a URL to Add Events to Google Calendar.
Open your Google Calendar and select the event you want to share..
Click the three dots to open the option menu..
Click “Publish event”.
Copy the URL and paste the link on any platform you want..

Is Google Calendar API free?

All use of the Google Calendar API is available at no additional cost.