接入教程
1. 在Google Cloud Platform创建项目并启用日历API
2. 配置OAuth 2.0凭据获取访问权限
3. 安装Google客户端库到开发环境
4. 使用API密钥初始化日历服务
5. 调用events.list()方法读取日历事件
6. 通过events.insert()创建新日程安排
列出日历事件
import requests
url = 'https://www.googleapis.com/calendar/v3/calendars/primary/events'
params = {
'key': 'YOUR_API_KEY',
'timeMin': '2023-01-01T00:00:00Z',
'maxResults': 10
}
headers = {
'Accept': 'application/json'
}
response = requests.get(url, params=params, headers=headers)
if response.status_code == 200:
events = response.json()
for event in events.get('items', []):
print(event.get('summary', 'No title'))
else:
print(f'Error: {response.status_code}')
创建新事件
<?php
$url = 'https://www.googleapis.com/calendar/v3/calendars/primary/events';
$apiKey = 'YOUR_API_KEY';
$eventData = [
'summary' => '团队会议',
'start' => ['dateTime' => '2023-12-01T14:00:00+08:00'],
'end' => ['dateTime' => '2023-12-01T15:00:00+08:00']
];
$ch = curl_init($url . '?key=' . urlencode($apiKey));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($eventData));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
echo '事件创建成功';
} else {
echo '创建失败,错误码:' . $httpCode;
}
?>
更新现有事件
const fetch = require('node-fetch');
async function updateEvent(eventId) {
const url = `https://www.googleapis.com/calendar/v3/calendars/primary/events/${eventId}`;
const apiKey = 'YOUR_API_KEY';
const updateData = {
summary: '更新的会议主题',
description: '会议内容已更新'
};
try {
const response = await fetch(`${url}?key=${apiKey}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(updateData)
});
if (response.ok) {
const result = await response.json();
console.log('事件更新成功:', result.summary);
} else {
console.error('更新失败:', response.status);
}
} catch (error) {
console.error('请求出错:', error);
}
}
updateEvent('example_event_id_123');
常见问题
如何获取API密钥?
您需要访问Google Cloud Console创建项目,启用Calendar API,然后在凭据页面生成API密钥。请妥善保管您的密钥,不要在前端代码中公开。
API调用频率有限制吗?
是的,Google Calendar API有配额限制。免费使用每天有一定数量的请求限制,具体限制取决于您的项目配置和使用类型。建议查看官方文档了解最新配额信息。
支持哪些类型的认证?
Google Calendar API支持多种认证方式,包括API密钥(用于公开数据)、OAuth 2.0(用于访问用户私有数据)和服务账号(用于服务器间通信)。选择哪种方式取决于您的应用场景。
Aitishiku.com