Mom*_*nSh 1 google-calendar-api google-api-php-client
我正在开发一个客户端Web应用程序,用户可以在其中预订带有日期,时间,位置等的驱动器
客户要求将所有预订作为活动添加到他的Google日历中
我创建了一个API密钥并下载了PHP API客户端:https : //github.com/google/google-api-php-client
但是,当我尝试添加事件时,出现“需要登录”错误
我如何直接添加事件而无需使用OAuth和同意屏幕,因为该功能将在后端自动执行,因此我拥有对gmail帐户的完全访问权限。
我使用服务帐户来工作,并根据此答案执行了一些步骤,这是我所做的:
1-在Google Developer Console上创建一个项目。
2-转到凭据并创建密钥类型为JSON的服务帐户密钥,将下载一个JSON文件,并将其移至您的项目文件夹。
3-从“库”选项卡中启用Calendar API,搜索Calendar API并启用它。
4-转到您的Google日历
5-转到设置->添加日历->新日历,之后会弹出通知/吐司,单击配置,向下滚动到与特定人员共享->添加人员,在电子邮件字段上添加服务帐户ID,您可以从凭据->管理服务帐户中获取它,然后设置权限以更改事件并单击发送。
6-下载PHP客户端库。
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);
?>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
这里发生的是该事件是由与您自己的Google帐户不同的服务帐户创建的,并且具有自己的数据,因此,如果您不与服务帐户共享日历并将日历ID设置为主,则会创建您无法正常访问的服务帐户日历上的事件。
我希望这对任何人都有帮助。
参考:
https : //stackoverflow.com/a/26067547/8702128
https://github.com/google/google-api-php-client
https://developers.google.com/calendar/quickstart/php
如何插入用户事件使用PHP的谷歌日历?
归档时间: |
|
查看次数: |
5179 次 |
最近记录: |