How can PHP be used to integrate Google Calendar into a website for booking appointments?
To integrate Google Calendar into a website for booking appointments using PHP, you can utilize the Google Calendar API to create, update, and delete events. This involves setting up OAuth 2.0 authentication, making API requests to interact with the calendar, and handling responses to display available time slots or confirm appointments.
// Include Google API client library
require_once 'vendor/autoload.php';
// Set up OAuth 2.0 credentials
$client = new Google_Client();
$client->setAuthConfig('credentials.json');
$client->setScopes(Google_Service_Calendar::CALENDAR);
// Authenticate with Google API
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Calendar($client);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// Make API requests to interact with Google Calendar
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Appointment',
'location' => 'Location',
'description' => 'Description',
'start' => array(
'dateTime' => '2023-01-01T09:00:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2023-01-01T10:00:00',
'timeZone' => 'America/Los_Angeles',
),
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
echo 'Event created: ' . $event->htmlLink;