I’m working on a PHP script that connects to Google Calendar API but I’m having trouble with the authentication flow. Right now my application requires users to click a login link and enter their Google credentials every time. I want to bypass this manual authentication step completely so events get created automatically when the script runs.
<?php
require_once 'vendor/autoload.php';
use Google\Client;
use Google\Service\Calendar;
session_start();
$googleClient = new Client();
$googleClient->setApplicationName("My Calendar App");
$googleClient->setClientId('your_client_id');
$googleClient->setClientSecret('your_client_secret');
$googleClient->setRedirectUri('your_redirect_url');
$googleClient->setDeveloperKey('your_api_key');
$calendarService = new Calendar($googleClient);
if (isset($_GET['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$googleClient->authenticate($_GET['code']);
$_SESSION['access_token'] = $googleClient->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
exit();
}
if (isset($_SESSION['access_token'])) {
$googleClient->setAccessToken($_SESSION['access_token']);
}
if ($googleClient->getAccessToken()) {
$calendars = $calendarService->calendarList->listCalendarList();
echo "<h1>Available Calendars</h1><pre>" . print_r($calendars, true) . "</pre>";
$_SESSION['access_token'] = $googleClient->getAccessToken();
$newEvent = new Google\Service\Calendar\Event();
$newEvent->setSummary('Meeting');
$newEvent->setLocation('Conference Room');
$startTime = new Google\Service\Calendar\EventDateTime();
$startTime->setDateTime('2024-01-15T14:00:00.000-08:00');
$newEvent->setStart($startTime);
$endTime = new Google\Service\Calendar\EventDateTime();
$endTime->setDateTime('2024-01-15T15:30:00.000-08:00');
$newEvent->setEnd($endTime);
$insertedEvent = $calendarService->events->insert('primary', $newEvent);
$eventList = $calendarService->events->listEvents('primary');
echo "<pre>" . print_r($eventList, true) . "</pre>";
} else {
$loginUrl = $googleClient->createAuthUrl();
echo "<a href='$loginUrl'>Authorize Access</a>";
exit();
}
?>
I’m wondering if using a service account would solve this authentication issue or if I need to store tokens in a database and handle token refresh automatically. What’s the best approach to make this work without manual user intervention each time the script executes?