使用php

时间:2018-06-02 10:52:54

标签: google-calendar-api google-api-php-client

我正在开发一个客户端网络应用程序,用户可以在其中预订带有日期,时间,位置等的驱动器

客户要求每个预订都作为活动添加到他的谷歌日历

我创建了一个API密钥并下载了PHP API客户端: https://github.com/google/google-api-php-client

但是当我尝试添加事件时,我收到“需要登录”错误

如何直接添加事件而无需使用OAuth和同意屏幕,因为该功能将在后端自动执行,我可以完全访问gmail帐户。

1 个答案:

答案 0 :(得分:5)

我使用服务帐户和基于此answer的一些步骤开始工作,这就是我所做的:

1-在Google Developer Console上创建项目。

2-转到凭据并创建密钥类型为JSON的服务帐户密钥,将下载JSON文件,将其移至项目文件夹。

3-从“库”选项卡启用Calendar API,搜索Calendar API并启用它。

4-转到Google Calendar

5-转到设置 - >添加日历 - >新日历,之后将弹出通知/吐司点击配置,向下滚动到与特定人共享 - >添加人员,在电子邮件字段中添加服务帐户ID,您可以从凭据中获取 - >管理服务帐户,然后设置权限以更改事件,然后单击发送。

6-下载PHP client library

7-现在您需要获取日历ID,从日历设置向下滚动到您将找到它的最后一部分,或者这是一个示例代码来获取它,在响应中查找它,它将是这样的'j85tnbuj1e5tgnizqt9faf2i88@group.calendar.google.com':

<?php
require_once 'google-api/vendor/autoload.php';

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=google-api/test-calendar-serivce-1ta558q3xvg0.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

$calendarList = $service->calendarList->listCalendarList();
print_r($calendarList);
?>

8-您现在可以向日历添加事件,示例代码:

$event = new Google_Service_Calendar_Event(array(
  'summary' => 'Test Event',
  'description' => 'Test Event',
  'start' => array(
    'dateTime' => '2018-06-02T09:00:00-07:00'
  ),
  'end' => array(
    'dateTime' => '2018-06-10T09:00:00-07:00'
  )
));

$calendarId = 'j85tnbuj1e5tgnizqt9faf2i88@group.calendar.google.com';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);

此处发生的事件是,该活动是由与您自己的Google帐户不同的服务帐户创建的,并且拥有自己的数据,因此如果您没有与服务帐户共享日历并将日历ID设置为主要帐户将在服务帐户日历上创建您无法正常访问的活动。

我希望这对任何人都有帮助。

参考文献:
https://stackoverflow.com/a/26067547/8702128
https://github.com/google/google-api-php-client
https://developers.google.com/calendar/quickstart/php
How to insert event to user google calendar using php?

相关问题