影刀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_url="https://api.example.com/oauth/token"token_data={"grant_type":"client_credentials","client_id":"your_client_id","client_secret":"your_client_secret"}resp=requests.post(token_url,data=token_data)token_info=resp.json()access_token=token_info["access_token"]expires_in=token_info.get("expires_in",7200)# 有效期,默认2小时print(f"Token获取成功,有效期{expires_in}秒")# 2. 用token调接口headers={"Authorization":f"Bearer{access_token}"}resp=requests.get("https://api.example.com/data",headers=headers)模式二:授权码模式(Authorization Code)
需要用户同意授权——常用于"用微信登录"这种场景。在影刀中分为两步:
第一步:引导用户访问授权URL
auth_url=("https://api.example.com/oauth/authorize""?client_id=xxx""&redirect_uri=https://your-redirect.com/callback""&response_type=code""&scope=read")print(f"请在浏览器中打开以下链接并授权:\n{auth_url}")# 用户授权后,浏览器会跳转到redirect_uri,URL里带着code参数第二步:用code换token
code=input("请输入授权后URL中的code参数:")token_url="https://api.example.com/oauth/token"token_data={"grant_type":"authorization_code","code":code,"client_id":"your_client_id","client_secret":"your_client_secret","redirect_uri":"https://your-redirect.com/callback"}resp=requests.post(token_url,data=token_data)token_info=resp.json()access_token=token_info["access_token"]refresh_token=token_info.get("refresh_token")# 用于过期后刷新Token过期自动刷新
Token有有效期,过期后接口返回401。最好的实践是:
importtimeclassTokenManager:def__init__(self,client_id,client_secret):self.client_id=client_id self.client_secret=client_secret self.token=Noneself.expires_at=0# 过期时间戳defget_token(self):"""获取有效token,过期自动刷新"""iftime.time()<self.expires_at-60:# 提前1分钟刷新returnself.token resp=requests.post("https://api.example.com/oauth/token",data={"grant_type":"client_credentials","client_id":self.client_id,"client_secret":self.client_secret})data=resp.json()self.token=data["access_token"]self.expires_at=time.time()+data.get("expires_in",7200)print("Token已刷新")returnself.token# 使用tm=TokenManager("id","secret")token=tm.get_token()# 自动管理有效期踩坑实录
坑1:Content-Type错误
OAuth2.0的token接口要求Content-Type: application/x-www-form-urlencoded。用requests.post(url, data=...)(不是json=)即可。如果用了json=,服务端返回"不支持的grant_type"。
坑2:redirect_uri必须完全匹配
temu店群自动化报活动案例
在平台注册应用时填的redirect_uri和代码里传的redirect_uri必须完全一致(包括最后的斜杠)。差一个字符都会授权失败。
坑3:refresh_token只能用一次
很多平台的refresh_token是一次性的——用完后旧的refresh_token失效,同时返回一个新的refresh_token。你必须保存新的refresh_token,否则下次刷新就失败了。
坑4:access_token泄露
不要把token打印到日志里,不要硬编码在代码里。如果你的代码要分享给别人,务必把client_secret放在配置文件里,不要提交到Git仓库。
简化方案:浏览器手动获取Token
如果只是偶尔调用,偷懒的方法是:
- 在浏览器里登录目标平台
- F12打开开发者工具 → Application → Cookies/Storage
- 找到access_token,复制到影刀的配置文件里
这个方案不能自动化,但适合快速验证和临时需求。
写在最后
OAuth2.0是API调用的"入场券"。掌握客户端模式和授权码模式,就能接入绝大多数需要认证的API。Token管理和自动刷新是生产级流程的标配——没有它,流程每隔几小时就中断一次,烦不死你。