Let's move step by step through the OAuth 2.0 flow setup and coding using PHP for your Google Calendar integration.


What We’re Building

➡️ A PHP app that:

  1. Lets users (like Jack) authorize your website to access their Google Calendar.
  2. Retrieves an access token (and refresh token).
  3. Lets them create/edit/delete events on Google Calendar directly from your website.

Prerequisites

RequirementDescription
PHP Version PHP 7.x or higher
Composer Dependency manager for PHP
Verified Domains Your domain and subdomains verified in Google Search Console
SSL HTTPS is required for OAuth 2.0

Step 1: Install the Google API Client Library for PHP

➤ Install via Composer

In your project directory, run:

bash
composer require google/apiclient:^2.0

If you don’t have Composer:


Step 2: Create a Google Cloud Project & OAuth Credentials

➤ Recap of Setup:

  1. Go to Google Cloud Console.
  2. Create a new project or use an existing one.
  3. Go to APIs & ServicesLibrary ➜ Enable Google Calendar API.
  4. Go to CredentialsCreate CredentialsOAuth client ID.
  5. Set redirect URIs (e.g., https://www.japansailing.com/oauth2callback.php).

➡️ Save your Client ID and Client Secret.


Step 3: Create Files for OAuth 2.0 Flow

We’ll need:

  1. index.php ➜ The landing page with the Connect Google Calendar button.
  2. oauth2callback.php ➜ The callback handler after user authorization.
  3. calendar.php ➜ To create/edit/delete events.

index.php

php
<?php require_once 'vendor/autoload.php'; // Composer autoload session_start(); // Initialize Google Client $client = new Google_Client(); $client->setAuthConfig('credentials.json'); // Your OAuth credentials JSON file $client->addScope(Google_Service_Calendar::CALENDAR); $client->setRedirectUri('https://www.japansailing.com/oauth2callback.php'); $client->setAccessType('offline'); // To get refresh token $client->setPrompt('consent'); // Prompt for consent every time $authUrl = $client->createAuthUrl(); echo "<h1>Welcome to Japan Sailing!</h1>"; echo "<a href='$authUrl'>Connect Google Calendar</a>";

➡️ Replace credentials.json with the actual file you downloaded from Google Cloud Console OR manually pass the Client ID/Secret like:

php
$client->setClientId('YOUR_CLIENT_ID'); $client->setClientSecret('YOUR_CLIENT_SECRET');

oauth2callback.php

php
<?php require_once 'vendor/autoload.php'; session_start(); $client = new Google_Client(); $client->setAuthConfig('credentials.json'); $client->addScope(Google_Service_Calendar::CALENDAR); $client->setRedirectUri('https://www.japansailing.com/oauth2callback.php'); if (! isset($_GET['code'])) { header('Location: index.php'); exit(); } else { $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); if (isset($token['error'])) { echo "Error fetching token: " . $token['error']; exit(); } $_SESSION['access_token'] = $token; header('Location: calendar.php'); }

➡️ This page handles Google’s redirect, exchanges the code for a token, and stores it in $_SESSION.


calendar.php

Now that we have an access token, let's do something useful—create an event!

php
<?php require_once 'vendor/autoload.php'; session_start(); if (! isset($_SESSION['access_token']) || empty($_SESSION['access_token'])) { header('Location: index.php'); exit(); } $client = new Google_Client(); $client->setAuthConfig('credentials.json'); $client->addScope(Google_Service_Calendar::CALENDAR); $client->setAccessToken($_SESSION['access_token']); // Refresh the token if it's expired if ($client->isAccessTokenExpired()) { $refreshToken = $_SESSION['access_token']['refresh_token']; $client->fetchAccessTokenWithRefreshToken($refreshToken); $_SESSION['access_token'] = $client->getAccessToken(); } $service = new Google_Service_Calendar($client); // Example: Create a new event $event = new Google_Service_Calendar_Event(array( 'summary' => 'Team Meeting', 'location' => 'Zoom', 'description' => 'Discussing sailing events!', 'start' => array( 'dateTime' => '2025-03-18T10:00:00', 'timeZone' => 'Asia/Tokyo', ), 'end' => array( 'dateTime' => '2025-03-18T11:00:00', 'timeZone' => 'Asia/Tokyo', ), 'attendees' => array( array('email' => ''), ), )); $calendarId = 'primary'; // Or use a specific calendar ID $event = $service->events->insert($calendarId, $event); echo 'Event created: <a href="' . $event->htmlLink . '" target="_blank">' . $event->htmlLink . '</a>';

Step 4: Securely Store Tokens

If you don’t want to use $_SESSION, store access tokens/refresh tokens in a database:

  • Associate them with your user accounts.
  • Use encryption for refresh tokens.

Step 5: Additional Operations

➤ List Events

php
$events = $service->events->listEvents($calendarId); foreach ($events->getItems() as $event) { echo $event->getSummary() . " - " . $event->getStart()->getDateTime() . "<br>"; }

➤ Update Event

php
$eventId = 'YOUR_EVENT_ID'; $event = $service->events->get($calendarId, $eventId); $event->setSummary('Updated Summary'); $updatedEvent = $service->events->update($calendarId, $event->getId(), $event);

➤ Delete Event

php
$service->events->delete($calendarId, $eventId);

Step 6: Testing

Test your workflow:

  1. Go to index.php
  2. Authenticate with Google
  3. Create an event via calendar.php

Optional Enhancements

EnhancementDetails
Frontend UI Use Bootstrap 5 forms or modals to handle event creation without page reloads
FullCalendar.js Display events on your website in a dynamic calendar view
Error Handling Show user-friendly messages if something fails
Logging Track API calls and user activity for auditing