Le Long
Le Long

Reputation: 21

Google Calendar API V3 Delete API

I have a trouble when trying to use delete api (The documentation from Google). My system is using Google Account Service to create multiple events. The problem occurs when I try to delete all events by using the delete api The code in cakephp framework.

$service->calendars->delete(GOOGLE_CALENDAR_ID);

I checked some events on calendar, It could delete some events then return an error

"code": 500, "message": "Backend Error"

Anybody can help me ?

Thanks

Upvotes: 0

Views: 955

Answers (1)

Sunil
Sunil

Reputation: 185

CakePHP 3.x in Google Calendar API

Set configuration file in app_globle.php

[
'Google' => [
      'ClientID' => '7441260037.apps.googleusercontent.com',
        'ClientSecret' => 'kashdjahdkjshdkjhjAs',
        'RedirectUrl' => 'http://' . env("HTTP_HOST") . '/oauth2calendars',
        'ClientCredentials' => WWW_ROOT . 'files'. DS.'google.txt',
        'Scopes' => implode(' ', [Google_Service_Calendar::CALENDAR, Google_Service_Drive::DRIVE, Google_Service_Drive::DRIVE_FILE, Google_Service_Drive::DRIVE_APPDATA, Google_Service_Drive::DRIVE_METADATA]),
    ]
]

Route

 $routes->connect('/events/add', ['controller' => 'Events', 'action' => 'add', ['_name' => 'add-event']);

    $routes->connect('/events/edit/:id', ['controller' => 'Events', 'action' => 'edit', ['id' => '\d+', 'pass' => ['id'], '_name' => 'edit-event']);

    $routes->connect('/events/delete/:id', ['controller' => 'Events', 'action' => 'delete', ['id' => '\d+', 'pass' => ['id'], '_name' => 'delete-event']);

**

  • Controller

**

use Google_Client;
use Google_Service_Calendar;
use Google_Service_Calendar_Event;
use Google_Service_Drive;
use Google_Service_Drive_DriveFile;

Authorize the google Oauth /** * get Google calendar client */

 private function getClient()
    {
        $client = new Google_Client();
        $client->setAccessType("offline");
        $client->setClientId(Configure::read('Google.ClientID'));
        $client->setClientSecret(Configure::read('Google.ClientSecret'));
        $client->setRedirectUri(Configure::read('Google.RedirectUrl'));
        $client->setScopes(Configure::read('Google.Scopes'));
        $credentialsPath = Configure::read('Google.Credentials');
        if (file_exists($credentialsPath)) {
            $accessToken = json_decode(file_get_contents($credentialsPath), true);
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            return $this->redirect($authUrl);
        }
        $client->setAccessToken($accessToken);
        // Refresh the token if it's expired.
        if ($client->isAccessTokenExpired()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
        }
        return $client;
    }

/** * Create Google Calendar event */

 public function createCredentials()
    {
       $client = new Google_Client();
        $client->setAccessType("offline");
        $client->setClientId(Configure::read('Google.ClientID'));
        $client->setClientSecret(Configure::read('Google.ClientSecret'));
        $client->setRedirectUri(Configure::read('Google.RedirectUrl'));
        $client->setScopes(Configure::read('Google.Scopes'));

               if (isset($this->request->query['code'])) {
            $client->authenticate($this->request->query['code']);
            $token = json_encode($client->getAccessToken());
            $credentialsPath =WWW_ROOT . 'files'. DS.'google.txt';
            if (!file_exists(dirname($credentialsPath))) {
                mkdir(dirname($credentialsPath), 0700, true);
            }
            $file = new File($credentialsPath, true);
            $file->write($token);
            $client->setAccessToken($token);
            return $this->redirect(‘/add-event’);
        }
    }

Add event functionality

Public function add()
{
$client = $this->getClient();
if ($this->request->is('post')) {
                $dateStart = new \DateTime($this->request->data['start_date_time'], new \DateTimeZone('Asia/Kolkata'));
                $dateStart->setTimezone(new \DateTimeZone('UTC'));
                $startDate = $dateStart->format('Y-m-d H:i:s');
                $dateEnd = new \DateTime($this->request->data['end_date_time'], new \DateTimeZone('Asia/Kolkata'));
                $dateEnd->setTimezone(new \DateTimeZone('UTC'));
                $endDate = $dateEnd->format('Y-m-d H:i:s');
                $guests = $this->request->data['guests'];
                $eventGuest = [];
                $service = new Google_Service_Calendar($client);
                foreach ($guests as $key => $value) {
                    $eventGuest[$key]['email'] = $value;
                }
                $eventData = [
                    'summary' => $this->request->data['name'],
                    'location' => $this->request->data['location'],
                    'description' => $this->request->data['description'],
                    'start' => [
                        'dateTime' => date("c", strtotime($startDate)),
                    ],
                    'end' => [
                        'dateTime' => date("c", strtotime($endDate)),
                    ],
                    'attendees' => $eventGuest,
                    'reminders' => [
                        'useDefault' => true,
                    ],
                    'visibility' => 'private',
                    'privateCopy' => true,
                ];
                $event = new Google_Service_Calendar_Event($eventData);
                $sendNotifications = ['sendNotifications' => true];
                $calendarId = 'primary';
                $eventDataResponse = $service->events->insert($calendarId, $event, $sendNotifications);
          }

}

Edit event //event id $id

Public function edit($id)
{
$client = $this->getClient();
 if ($this->request->is(['patch', 'post', 'put'])) {
                $service = new Google_Service_Calendar($client);
                if (isset($eventID) && !empty($eventID)) {
                    $eventData = $service->events->get('primary', $eventID);
                }
                $guests = $this->request->data['guests'];
                $eventGuest = [];
                foreach ($guests as $key => $value) {
                    $eventGuest[$key]['email'] = $value;
                }
                $eventData->setSummary($this->request->data['name']);
                $eventData->setDescription($this->request->data['description']);
                $eventData->setLocation($this->request->data['location']);
                $eventData->setAttendees($eventGuest);
                $sendNotifications = ['sendNotifications' => true];
                $updatedEvent = $service->events->update('primary', $eventData->getId(), $eventData, $sendNotifications);
                                             $this->Flash->error(__('Event could not be update. Please, try again.'));
            }
}
Deleted event
//event id $id
// if google calendar in event is exist otherwise  not to dispaly
Public function delete($id)
{
 $client = $this->getClient();
            if ($this->request->is(['post', 'put', 'patch'])) {
 $service = new Google_Service_Calendar($client);
                $sendNotifications = ['sendNotifications' => true];
                $service->events->delete('primary', $eventID, $sendNotifications);
    }
}

Upvotes: 1

Related Questions