gpt4 book ai didi

google-calendar-api - 使用php向谷歌日历添加事件

转载 作者:行者123 更新时间:2023-12-03 18:28:55 27 4
gpt4 key购买 nike

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

客户要求将每个预订添加为他的谷歌日历上的事件

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

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

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

最佳答案

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

1- 在 Google Developer Console 上创建一个项目.

2- 转到 Credentials 并创建一个 key 类型为 JSON 的服务帐户 key ,将下载一个 JSON 文件,将其移动到您的项目文件夹中。

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

4- 转到您的 Google Calendar

5- 进入设置 -> 添加日历 -> 新日历,之后会弹出一个通知/toast 点击配置,向下滚动到与特定人员共享 -> 添加人员,在电子邮件字段中添加服务帐户 ID,您可以从 Credentials -> Manage service accounts 获取它,然后设置对事件进行更改的权限,然后单击发送。

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?

关于google-calendar-api - 使用php向谷歌日历添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656151/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com