This blog post will help create an event on Google Calendar.
The blog post covers version 3 of Calendar API. The code snippet will use the HTML form and PHP Curl code for processing.
Google also provides a PHP Client Library, through which you can make Calendar API calls, but it is 6 MB in size. So I think it’s better to write small code snippet functions.
Prerequisites
1. Create Google Application and API credentials
Open the https://console.developers.google.com/ and create a new project. You can select an existing project.
2. Click “Credentials” and create a new OAuth client ID
- Select the application type as “web application“.
- Enter the name of the credentials details. It is to identify the details.
- You can leave empty “Authorized Javascript origins“
- Enter your web URL for redirection.
After these steps, you will get authentication details.
Create a Google OAuth2 authentication link.
You use this link for Google authentication consent. Scope parameters have space between two scopes.
URL: https://accounts.google.com/o/oauth2/auth
Parameters :
scope=https://www.googleapis.com/auth/calendar openid
redirect_uri=http://localhost/google-api/google-cal-event.php
response_type=code
client_id=xxxx
access_type=offline
URL will look like below
https://accounts.google.com/o/oauth2/v2/auth?response_type=code&scope=https://www.googleapis.com/auth/calendar openid&redirect_uri=<redirect_uri> &client_id=<client_id>&access_type=offline
Authenticate and Get Redirect to URL
Open the URL in the browser. It will ask for Google access permission. After successful authentication, you will redirect to your mentioned redirect URL.
Get Access Token
After successful authentication and redirection, you will get a “code” parameter in the URL. For access token, you can use POSTMAN API console or use the following PHP code snippet.
define('CLIENT_ID', 'xxxx'); define('CLIENT_SECRET', 'xxxx'); define('REDIRECT_URIS', 'http://example.com/google-calendar-event-api/redirect-url.php'); if(isset($_GET['code'])){ $client_id = CLIENT_ID; $redirect_uri = REDIRECT_URIS; $client_secret = CLIENT_SECRET; $code = $_GET['code']; $token_data = GetAccessToken($client_id, $redirect_uri, $client_secret, $code); /* echo 'Access Token: '. $token_data['access_token']; echo '<br/>'; echo 'Refresh Token: '. $token_data['refresh_token']; */ echo '<pre>'; print_r($token_data); echo '</pre>'; } else { echo 'No direct access'; } function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) { $url = 'https://www.googleapis.com/oauth2/v4/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 new Exception('Error : Failed to receieve access token'); return $data; }
Get Access Token using a refresh token
Generally, the access token expires time is too low. But the refresh token has a longer expiration time than the access token. So it a better idea to get an access token using the refresh token. So we don’t log-in to Google on every token expiration.
function RefreshAccessToken($client_id, $redirect_uri, $client_secret, $refresh_token){ $url = 'https://www.googleapis.com/oauth2/v4/token'; $curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&refresh_token='. $refresh_token . '&grant_type=refresh_token'; $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 new Exception('Error : Failed to receieve access token'); return $data; }
Google Calendar Event create
The API call to get the user’s Calendar timezone
function GetUserCalendarTimezone($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) throw new Exception('Error : Failed to get timezone'); return $data['value']; }
Create Google Calendar event function
Checkout the API URL for parameter details. https://developers.google.com/calendar/v3/reference/events/insert
function CreateCalendarEvent($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 new Exception('Error : Failed to create event'); return $data['id']; }
HTML Form for Event submit
<div class="container"> <?php if(isset($_GET['event_id'])) echo '<div class="alert alert-success">Google Calendar event created.</div>'; ?> <form method="post"> <div class="form-row"> <div class="form-group col-md-6"> <label for="event_title">Event Title</label> <input type="text" class="form-control" id="event_title" name="event_title" placeholder="Event Title" require=""> </div> <div class="form-group col-md-6"> <label for="event_date">Event Date</label> <div class="input-group date"> <input type="text" class="form-control" value="<?php echo date('Y-m-d') ?>" id="event_date" name="event_date"> <div class="input-group-addon"> <span class="glyphicon glyphicon-th"></span> </div> </div> </div> </div> <button type="submit" class="btn btn-primary">Add Google Calendar Event</button> </form> </div>
Form submit action
define('CLIENT_ID', 'xxxx'); define('CLIENT_SECRET', 'xxxx'); define('REDIRECT_URIS', 'http://example.com/google-calendar-event-api/redirect-url.php'); $access_token = 'xxxxx'; if(isset($_POST['event_title'])){ $user_timezone = GetUserCalendarTimezone($access_token); $calendar_id = 'primary'; $event_title = $_POST['event_title']; // Event starting & finishing at a specific time //$full_day_event = 0; //$event_time = [ 'start_time' => '2020-12-31T15:00:00', 'end_time' => '2020-12-31T16:00:00' ]; // Full day event $full_day_event = 1; $event_time = [ 'event_date' => date('Y-m-d', strtotime($_POST['event_date'])) ]; $data = CreateCalendarEvent($calendar_id, $event_title, $full_day_event, $event_time, $user_timezone, $access_token); if($data != ''){ header('Location:google-event-form.php?event_id='.$data); exit; } }
Comments
Good day! This is my 1st comment here so I just wanted to give a quick shout out and say I really enjoy reading through your articles.
Can you suggest any other blogs/websites/forums that deal with
the same subjects? Appreciate it!