使用TickTick API请求授权失败,无重定向URL如何获取令牌?
解决TickTick API无重定向URL获取令牌的问题
问题描述
我正在使用TickTick官方开发文档中的API,采用Google Colab笔记本的默认Python版本。已按指引创建了client_id,但不清楚没有重定向URL的情况下如何获取令牌。目标是连接TickTick账号,完成UI界面不支持的批量编辑和删除操作,目前代码如下:
import requests payload = {'client_id': 'Ysf0D223UGhdlY5Y7W', 'scope': 'tasks:write','response_type':'code'} r = requests.get('https://ticktick.com/oauth/authorize', params=payload) r.text
解决方案
针对Google Colab这类无本地服务的环境,无法设置常规重定向URL,推荐使用设备授权流(TickTick API支持该模式),步骤如下:
请求设备授权码
发送POST请求到设备授权端点,获取用于用户验证的相关信息:import requests payload = { 'client_id': 'Ysf0D223UGhdlY5Y7W', 'scope': 'tasks:write tasks:read' # 批量操作需读写权限 } response = requests.post('https://ticktick.com/oauth/device/code', data=payload) device_auth_data = response.json() print(f"请打开链接: {device_auth_data['verification_uri']}") print(f"输入验证码: {device_auth_data['user_code']}")轮询获取访问令牌
用户在浏览器完成验证后,定期向令牌端点请求,直到拿到有效令牌:import time token_payload = { 'client_id': 'Ysf0D223UGhdlY5Y7W', 'device_code': device_auth_data['device_code'], 'grant_type': 'urn:ietf:params:oauth:grant-type:device_code' } while True: token_response = requests.post('https://ticktick.com/oauth/token', data=token_payload) token_data = token_response.json() if token_response.status_code == 200: access_token = token_data['access_token'] refresh_token = token_data.get('refresh_token') print(f"获取令牌成功: {access_token}") break elif token_data.get('error') == 'authorization_pending': # 用户未完成授权,按指定间隔重试 time.sleep(device_auth_data['interval']) else: print(f"授权失败: {token_data['error']}") break使用令牌执行批量操作
拿到access_token后,即可调用API完成批量编辑或删除,示例如下:# 批量删除任务示例 headers = {'Authorization': f'Bearer {access_token}'} task_ids_to_delete = ['task_id_1', 'task_id_2'] # 替换为实际任务ID delete_response = requests.post( 'https://api.ticktick.com/openapi/v1/task/batch/delete', headers=headers, json={'taskIds': task_ids_to_delete} ) print(delete_response.json())
注意事项
- 确保申请的
scope包含所需权限,批量编辑删除至少需要tasks:write和tasks:read - 保存好
refresh_token,可用于刷新过期的access_token,避免重复授权 - 轮询间隔需遵循返回的
interval值,避免频繁请求触发限流
内容的提问来源于stack exchange,提问作者akapulko2020
相关产品推荐
相关产品推荐

