使用 php 将事件添加到 google 日历

adding an event to google calendar using php

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

客户要求在他的google日历

中将每个预订添加为一个事件

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

但是当我尝试添加一个事件时,我得到一个 "Login Required" 错误

如何在不使用 OAuth 和同意屏幕的情况下直接添加事件,因为该功能将在后台自动执行,我对 gmail 帐户具有完全访问权限。

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

1- 在 Google Developer Console.

上创建一个项目

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

3- 从库选项卡启用日历 API,搜索日历 API 并启用它。

4- 转到您的 Google Calendar

5- 转到设置 -> 添加日历 -> 新日历,然后 notification/toast 会弹出点击配置,向下滚动到与特定人员共享 -> 添加人员,在电子邮件字段添加服务帐户 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://github.com/google/google-api-php-client
https://developers.google.com/calendar/quickstart/php
How to insert event to user google calendar using php?