After hours of reading Google API documentation and searching the web I managed to write a simple PHP function to insert an event into my Google Calendar (if anyone wants the code just ask).
However the next thing I want to do is to delete the entire content of my Google calendar. Initially I thought I'd do this by reading all events and then deleting each one, but according to Google I can do this in a single command:
$service->calendars->clear($cal_id);
However since the Google API documentation only covers the actual command and does not show any of the code that needs to precede this, so I've used the authorisation code that worked in the event insert script, but I just cannot get it to work for clearing the data, and I'm getting error:
Notice: Undefined variable: service in index.php on line 68
My entire code follows:
<?php
//
// example code taken from:
// https://developers.google.com/google-apps/calendar/v3/reference/calendars/clear
//
//
calendclear('xxxxxxxxxxx@googlemail.com');
//---------------------------------------------------//
// funtion to delete all events from Google calendar //
//---------------------------------------------------//
function calendclear ($cal_id) {
session_start();
require_once '../google-api-php-client-master/autoload.php';
//Google credentials
$client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
$service_account_name = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com';
$key_file_location = '../google-api-php-client-master/API Project-xxxxxxxxxxxx.p12';
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("Whatever the name of your app is");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
$_SESSION['service_token'] = $client->getAccessToken();
$calendarService = new Google_Service_Calendar($client);
$calendarList = $calendarService->calendarList;
//delete all calendar data
try {
$service->calendars->clear($cal_id);
} catch (Exception $e) {
var_dump($e->getMessage());
}
echo 'Calendar Successfully Cleared';
}
?>