2

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';
}
?>
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
Andy Hawes
  • 86
  • 1
  • 6
  • 1
    Are you sending the primary calendar ID to clear($cal_id)?? because calendar.clear method clears only primary calendar.. – SGC Jan 29 '15 at 19:04
  • Thanks for that, it didn't fix the error, but I was not sending primary, I have changed the code to: $service->calendars->clear('primary'); – Andy Hawes Jan 29 '15 at 20:28
  • Hey @SGC do you have any other insight into what may be causing my error? Or any sample code I can copy? – Andy Hawes Jan 30 '15 at 12:06

1 Answers1

1

After much trial and error I found a way to clear the Google Calendar using the API v3.

I was unable to get the clear command to work, so instead do this I had to: 1. read all events in the calendar 2. delete each one

Firstly ensure your Google Calendar is setup correctly to allow any of this stuff to work - there are 4 simple steps detailed in the answer here Inserting Google Calendar Entries with Service Account

Next, here is the code I used - note the last 2 references to xxxxxxxxxxxx@googlemail.com are the calendar owner email address - the delete would NOT work with either 'primary' or the $service_account_name.

If you are playing with this stuff I hope this helps, as then the last 2 days of my life I spent trying to work this out were not totally wasted :)

<?php
session_start();
require_once '../google-api-php-client-master/autoload.php';
//Google credentials
$client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
$service_account_name = 'xxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com';
$key_file_location = '../google-api-php-client-master/API Project-xxxxxxxxxxx.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();

/* ------------------------- We are now properly authenticated ------------------- */

$cal = new Google_Service_Calendar($client);
$event_list = $cal->events->listEvents('xxxxxxxxxxxx@googlemail.com');

$events = $event_list->getItems();

// loop through all events read from calendar

foreach ($events as $event)
{
    $myEvent=$event->getId();
    $mySummary=$event->getSummary();
    $MyStart=$event->getStart()->getDateTime();
    $MyEnd=$event->getEnd()->getDateTime();
    echo 'about to delete event '.$mySummary.' ID: ('.$myEvent.')<br />';
    // now delete the event found
    try {
      $cal->events->delete('xxxxxxxxxxxx@googlemail.com', $myEvent);
      echo 'Success.<br />';
    } catch (Exception $e) {
      var_dump($e->getMessage());
      die('Event Delete Failed.');
    }
}
?>
Community
  • 1
  • 1
Andy Hawes
  • 86
  • 1
  • 6
  • If you want to delete events then above code works, but you said you want to clear the content of the calendar. For this you have to use clear method.. – SGC Jan 30 '15 at 16:36
  • Yes @SGC I would have preferred to clear, as I expect it would have been more efficient, but for the life of me I couldn't get it to work, so this was my workaround. If you have sample code for the clear method, or know where I can find any that's up to date and works online I'd welcome it. Google documentation leaves a lot to be desired... – Andy Hawes Jan 30 '15 at 22:11