Create Google Calendar Event Using PHP

Google Calendar is scheduling service provided by Google. You can use google calendar API to create, modified, delete, list the event of current user calendar.

To create Google Calendar Event we need follow below step

  1. Create Application in Google Developer Console. How to create application check the post. click here
  2. After creating application download credential and rename as credentials.json
  3. Install the google library in our application using composer
//composer.json file
{
    "require": {
        "google/apiclient": "^2.0"
    }
}

we are using Google Calendar API
version 3 for this tutorial. Ok so now let’s look into the code

Assuming you have credential.json file with you

Created class/calendar.php file in your project and paste the bellow code.

<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/include/intialise.php';

class Calendar
{
    private $client;

    function __construct()
    {
        $client = new Google_Client();
        $client->setApplicationName('Google Calendar API PHP Quickstart');
        $client->setAuthConfig(ROOT_PATH.'/credentials.json');
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');
        $client->setScopes(array('https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
        $this->client=$client;
        $this->google_oauth =new Google_Service_Oauth2($this->client);
    }

    public function GetCalendarAccessUrl()   // Generate Google calendar access url and login url
    {
        return $this->client->createAuthUrl();
    }

    public function Authenticate($code=NULL) // Authenticate user after redirecting from google
    {
        
        if(!empty($code)) //  pass the AuthCode return by google
        {
            $this->client->authenticate($code); //  Authonticate Auth code
            $access_token = $this->client->getAccessToken(); // Get Access token
            $refresh_token=$this->client->getRefreshToken();  // Get Refresh token
          
            if(!empty($access_token)) 
            {
                $_SESSION['access_token']=$access_token;
            }
            if(!empty($refresh_token))
            {
                $_SESSION['refresh_token']=$refresh_token;
            }

        }
        $this->client->setAccessToken($_SESSION['access_token']); // set the access token

        // check the access token is expired or not if expired fetcg new one using refresh token
        if ($this->client->isAccessTokenExpired()) {
            $access_stoken =$this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
        }
        
        
        
        return $this->client;
    }

    public function GetEvent($client,$calendarId='') // Get calendar event details
    {
        try {
            $service = new Google_Service_Calendar($client);
            // Print the next 10 events on the user's calendar.
         
            $results = $service->events->get('primary', $calendarId);
            $events = $results->getSummary();
            return $results;
            }
            catch (Google_Service_Exception $e ) {
                if(json_decode($e->getMessage())->error->message!='Not Found')
               {
                $response_data['code']=1;
                $response_data['message']=json_decode($e->getMessage())->error->message;
                $response_data['data']='';
                return $response_data;
               }
               
            } 
    
    }

    public function get_user_profile()  // Get user profile calendar event details
    {
        return($this->google_oauth->userinfo->get());
    }

    public function CreateEvent($client,$data)  // Create calendar event details
    {
        try {
            $service = new Google_Service_Calendar($client);
            $calendarId = 'primary';
        
            $event = new Google_Service_Calendar_Event(array(
                'summary' => $data['summary'],
                'location' => $data['location'],
                'description' => $data['description'],
                'start' => array(
                'dateTime' =>  $data['start_date_time'], //The (inclusive) start time of the event. For a recurring event, this is the start time of the first instance.
                'timeZone' => 'Asia/Kolkata',
                ),
                'end' => array(
                'dateTime' => $data['end_date_time'], //The (exclusive) end time of the event. For a recurring event, this is the end time of the first instance.
                'timeZone' => 'Asia/Kolkata',
                ),
                'recurrence' => array(
                    "RRULE:FREQ=WEEKLY;UNTIL=".date('Ymd\THis\Z',strtotime($data['end_date'])).";BYDAY=".$data['cal_weekly_days'].""
                ),
                'attendees' => array( ),
                'reminders' => array(
                'useDefault' => FALSE,
                'overrides' => array(
                    array('method' => 'email', 'minutes' => 30),
                    array('method' => 'popup', 'minutes' => 10),
                ),
                ),
            ));
            // dd($event);
            $events = $service->events->Insert($calendarId, $event);
          
            if (empty($events)) {
                $response_data['code']=1;
                $response_data['message']="Error While Creating Google calendar Event";
                $response_data['data']='';
                return $response_data;
            } else {
                $response_data['code']=0;
                $response_data['message']="Google calendar Event Created";
                $response_data['data']=$this->GetEvent($client,$events->getId());
                return $response_data;
            }
        }
        catch (Google_Service_Exception $e ) {
            $response_data['code']=1;
            $response_data['message']=json_decode($e->getMessage())->error->message;
            $response_data['data']='';
            return $response_data;
        }
    }

}
?>

2) google_calander_access.php

<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/include/intialise.php';
$calendar = new Calendar();

if(!empty($_GET['code']))
{
    $calendar->Authenticate($_GET['code']);
    if($calendar->get_user_profile())
    {
        $_SESSION['user_info']['name']=$calendar->get_user_profile()['name'];
    }
    header('Location:index.php');
}
elseif(!empty($_POST))
{

    $client=$calendar->Authenticate();
    $days_off=array('MON');  // mention day that we don't won't to create event

    $cal_week_days=array('SU' => 'SUN', 'MO' => 'MON', 'TU' => 'TUE', 'WE' => 'WED', 'TH' => 'THU', 'FR' => 'FRI', 'SA' => 'SAT');
    // declare week days

    $cal_all_week_except_days_off = array_flip(array_diff($cal_week_days, $days_off)); //diffrent value // array fip change key value pair
    $cal_weekly_days=implode(',',$cal_all_week_except_days_off); //comma separated value

    $event_dates=explode('-',$_POST['daterange']);
    $response_data['start_date_time']=$start_time = gmdate("Y-m-d\TH:i:s\Z",strtotime($event_dates[0]));  
    $response_data['end_date_time']=gmdate("Y-m-d\TH:i:s\Z",strtotime($event_dates[0].' +1 hour'));
    $response_data['end_date']=gmdate("Y-m-d\TH:i:s\Z",strtotime($event_dates[1]));
    $response_data['summary']=$_POST['event_name'];
    $response_data['location']=$_POST['event_location'];
    $response_data['description']=$_POST['event_description'];
    $response_data['cal_weekly_days']=$cal_weekly_days;  // event occur only for this week day

    $calendar_response=$calendar->CreateEvent($client,$response_data); // Create google calendar event 

    if(!$calendar_response['code'])
    {
        echo "<h4>".$calendar_response['message']."</h4>";
        echo "<pre>".json_encode($calendar_response['data'], JSON_PRETTY_PRINT)."</pre>";
    }
    else
    {
        echo $calendar_response['message'];exit;
    }
    
    
}
else
{
    header('Location:login.php');
}

?>

Add a Comment

Your email address will not be published. Required fields are marked *