How to read events and delete all events in Google

2019-05-19 00:41发布

问题:

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';
}
?>

回答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.');
    }
}
?>