C#调用Google Calendar API:如何自动获取用户CalendarId?
解决方案:用Refresh Token自动获取用户Calendar ID
核心逻辑
你持有的refresh token是核心凭证——它能在用户未登录的场景下,直接换取有效的access token,进而调用Google Calendar API拉取用户的全量日历列表(包含primary Calendar ID),全程无需用户手动介入。
分步实现
通过Refresh Token换取Access Token
向Google OAuth2令牌端点发送POST请求,参数如下:- 请求地址:
https://oauth2.googleapis.com/token - 表单参数:
grant_type: 固定值refresh_tokenclient_id: 你的Google Cloud项目客户端IDclient_secret: 你的Google Cloud项目客户端密钥refresh_token: 已存储的用户refresh token
Python示例代码:
import requests token_url = "https://oauth2.googleapis.com/token" payload = { "grant_type": "refresh_token", "client_id": "你的客户端ID", "client_secret": "你的客户端密钥", "refresh_token": "用户的refresh token" } response = requests.post(token_url, data=payload) access_token = response.json().get("access_token")- 请求地址:
调用Calendar List接口获取日历列表
用刚拿到的access token请求Calendar API的日历列表接口,该接口会返回用户名下所有日历的详细信息:- 请求地址:
https://www.googleapis.com/calendar/v3/users/me/calendarList - 请求头:
Authorization: Bearer {access_token}
Python示例代码:
calendar_list_url = "https://www.googleapis.com/calendar/v3/users/me/calendarList" headers = {"Authorization": f"Bearer {access_token}"} response = requests.get(calendar_list_url, headers=headers) calendars = response.json().get("items", [])- 请求地址:
提取并存储目标Calendar ID
遍历返回的日历列表,找到primary字段为true的条目,其id即为primary Calendar ID;如果需要其他日历,也可通过summary(日历名称)筛选:primary_calendar_id = None for cal in calendars: if cal.get("primary"): primary_calendar_id = cal.get("id") break # 将primary_calendar_id写入你的数据库
关键注意点
- 权限校验:获取refresh token时,必须已申请
https://www.googleapis.com/auth/calendar(读写权限)或https://www.googleapis.com/auth/calendar.readonly(只读权限),否则调用Calendar List接口会返回权限错误。 - 异常处理:refresh token可能因用户撤销授权或过期失效,需处理接口返回的
invalid_grant等错误,此时需引导用户重新完成授权流程。
内容的提问来源于stack exchange,提问作者Wannes Limbourg
相关产品推荐
相关产品推荐

