影刀RPA OAuth2.0认证流程实现授权码模式与客户端模式详解作者林焱调用第三方API时很多平台要求OAuth2.0认证——先获取access_token再用token调接口。这篇把最常见的两种OAuth2.0模式讲清楚并给出在影刀Python代码块中可用的完整实现。什么时候需要OAuth2.0最简单的判断看API文档里有没有提到以下关键词“获取access_token”“Authorization: Bearer xxx”“OAuth2.0授权”“Client ID / Client Secret”常见需要OAuth2.0的平台微信开放平台、企业微信、飞书、百度AI、各大云服务商的API。模式一客户端模式Client Credentials店群矩阵自动化突破运营极限最简单——用Client ID和Client Secret直接换token不需要用户参与importrequests# 1. 获取tokentoken_urlhttps://api.example.com/oauth/tokentoken_data{grant_type:client_credentials,client_id:your_client_id,client_secret:your_client_secret}resprequests.post(token_url,datatoken_data)token_inforesp.json()access_tokentoken_info[access_token]expires_intoken_info.get(expires_in,7200)# 有效期默认2小时print(fToken获取成功有效期{expires_in}秒)# 2. 用token调接口headers{Authorization:fBearer{access_token}}resprequests.get(https://api.example.com/data,headersheaders)模式二授权码模式Authorization Code需要用户同意授权——常用于用微信登录这种场景。在影刀中分为两步第一步引导用户访问授权URLauth_url(https://api.example.com/oauth/authorize?client_idxxxredirect_urihttps://your-redirect.com/callbackresponse_typecodescoperead)print(f请在浏览器中打开以下链接并授权\n{auth_url})# 用户授权后浏览器会跳转到redirect_uriURL里带着code参数第二步用code换tokencodeinput(请输入授权后URL中的code参数)token_urlhttps://api.example.com/oauth/tokentoken_data{grant_type:authorization_code,code:code,client_id:your_client_id,client_secret:your_client_secret,redirect_uri:https://your-redirect.com/callback}resprequests.post(token_url,datatoken_data)token_inforesp.json()access_tokentoken_info[access_token]refresh_tokentoken_info.get(refresh_token)# 用于过期后刷新Token过期自动刷新Token有有效期过期后接口返回401。最好的实践是importtimeclassTokenManager:def__init__(self,client_id,client_secret):self.client_idclient_id self.client_secretclient_secret self.tokenNoneself.expires_at0# 过期时间戳defget_token(self):获取有效token过期自动刷新iftime.time()self.expires_at-60:# 提前1分钟刷新returnself.token resprequests.post(https://api.example.com/oauth/token,data{![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/5563d9c8912d4f31ae8395e1a1bf7a56.png#pic_center)grant_type:client_credentials,client_id:self.client_id,client_secret:self.client_secret})dataresp.json()self.tokendata[access_token]self.expires_attime.time()data.get(expires_in,7200)print(Token已刷新)returnself.token# 使用tmTokenManager(id,secret)tokentm.get_token()# 自动管理有效期踩坑实录坑1Content-Type错误OAuth2.0的token接口要求Content-Type: application/x-www-form-urlencoded。用requests.post(url, data...)不是json即可。如果用了json服务端返回不支持的grant_type。坑2redirect_uri必须完全匹配temu店群自动化报活动案例在平台注册应用时填的redirect_uri和代码里传的redirect_uri必须完全一致包括最后的斜杠。差一个字符都会授权失败。坑3refresh_token只能用一次很多平台的refresh_token是一次性的——用完后旧的refresh_token失效同时返回一个新的refresh_token。你必须保存新的refresh_token否则下次刷新就失败了。坑4access_token泄露不要把token打印到日志里不要硬编码在代码里。如果你的代码要分享给别人务必把client_secret放在配置文件里不要提交到Git仓库。简化方案浏览器手动获取Token如果只是偶尔调用偷懒的方法是在浏览器里登录目标平台F12打开开发者工具 → Application → Cookies/Storage找到access_token复制到影刀的配置文件里这个方案不能自动化但适合快速验证和临时需求。写在最后OAuth2.0是API调用的入场券。掌握客户端模式和授权码模式就能接入绝大多数需要认证的API。Token管理和自动刷新是生产级流程的标配——没有它流程每隔几小时就中断一次烦不死你。