Google Calendar API V3删除API

时间:2017-09-25 08:28:56

标签: google-api google-calendar-api google-apis-explorer

尝试使用delete api(The documentation from Google)时遇到了麻烦。 我的系统正在使用Google帐户服务来创建多个活动。 当我尝试使用delete api删除所有事件时,会发生此问题 cakephp框架中的代码。

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

我在日历上检查了一些事件,它可以删除一些事件然后返回错误

  

“code”:500,      “message”:“后端错误”

任何人都可以帮助我?

由于

1 个答案:

答案 0 :(得分:0)

Google Calendar API中的CakePHP 3.x

在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]),
    ]
]

<强>路线

 $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']);

**

  • 控制器

**

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

授权google Oauth / **      *获取Google日历客户端      * /

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

/ **      * 创建Google日历活动      * /

 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’);
        }
    }

添加活动功能

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);
          }

}

修改活动 // 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);
    }
}