我正在开发一个客户端web应用程序,用户可以在其中使用日期、时间、location...etc来预订驱动器
客户要求每次预订都作为事件添加到他的google日历上
我创建了一个API并下载了PHP客户端:https://github.com/google/google-api-php-client
但是当我尝试添加一个事件时,我得到了一个“需要登录”的错误
如何在不使用OAuth和同意画面的情况下直接添加事件,因为该功能会在后台自动执行,我拥有对gmail账户的完全访问权限。
发布于 2018-06-03 10:08:17
我使用一个服务帐户和基于此answer的一些步骤使其工作,以下是我所做的:
1-在Google Developer Console上创建项目。
2-转到Credentials并创建一个密钥类型为JSON的服务帐户密钥,将下载一个JSON文件,将其移动到您的项目文件夹中。
3-从Library选项卡中启用Calendar API,搜索Calendar API并启用它。
4-转到您的Google Calendar
5-转到设置->添加日历->新日历,之后将弹出通知/吐司单击配置,向下滚动以与特定人员共享->添加人员,在电子邮件字段添加服务帐户ID,您可以从Credentials ->管理服务帐户获取它,然后设置更改事件的权限并单击发送。
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://stackoverflow.com/questions/50656151
复制相似问题