相同URL可在浏览器/Postman访问Facebook Graph API,Python脚本报错?
在Graph API Explorer和Postman中,使用相同的URL(包含相同的user_id和access_token)调用接口获取自身元数据时均正常,但Python脚本执行相同请求时,却返回如下OAuthException错误:
Error validating access token: Session has expired on Thursday, 01-Jun-23 21:00:00 PDT. The current time is Saturday, 03-Jun-23 16:56:14 PDT.'', 'type': 'OAuthException', 'code': 190, 'error_subcode': 463, 'fbtrace_id': 'A6-Aw4RWj3hOIuaM2tNZYvk'}
用户已重新生成access_token,但问题依旧。通过Graph API调试工具验证,该令牌状态为有效,还有55分钟过期,数据访问权限3个月后到期,权限包含pages_show_list、pages_read_engagement。
Python脚本片段
class FaceBookUserMetadata(APIView): renderer_classes = [HTMLRenderer] def get(self, request, uat, uid): logger.debug("getFacebookUserMetadata uat = %s ,uid = %s", uat, uid) access_token = uat #"EAADjbVVsAnABAE2e33q1R6LO2hVBZBIiQVuAsPY7AdhKzbgmWWz3fG8kZB9Y7eNre7uO5RWkMBZAHVagi8p4EMMcuFdgAVYVZCvZCiBjIDsasri5nZBWottP8dykL35FyWAfPZCMYSqqRZCSTNM0UWR06dIWalZAHhyKNgyIwFqKy2pz08jrAYsY2AfqIwUgtLzl7ZBcz1h6mTh6Q2hdHJS5XKLqXgNNHB9TZA9g1ZCW7546lzwn8pXqaXmsa8B2V5uP1HR8ZD" user_id = uid #"109566338825219" #here we execute the Facebook API url = f"https://graph.facebook.com/{user_id}?metadata=1&access_token={access_token}" print("/api/metadata/ url = %s", url) response = requests.get(url) logger.debug('result = %s', response) result = response.json() logger.debug('result = %s', result) print("result = %s", result) return Response(result)
Graph API调试数据
App ID 1416530633129895 : MyApp (id obfuscated) Type User App-Scoped User ID Learn More 109566338825219 : Michael Oliver (id obfuscated) User last installed this app via API N/A Issued Unknown Expires 1685840400 (in 55 minutes) Data Access Expires 1693611049 (in about 3 months) Valid True Origin Unknown Scopes pages_show_list, pages_read_engagement Granular Scopes pages_show_list 327913874657245 : My Co pages_read_engagement 327913874657245 : My Co
可能的原因及解决方法
URL编码问题:
access_token中可能包含+、/、=等特殊字符,直接拼接进URL会导致字符被错误解析。建议改用requests的params参数传递,自动处理编码:url = f"https://graph.facebook.com/{user_id}" params = { "metadata": 1, "access_token": access_token } response = requests.get(url, params=params)请求头差异:Graph API Explorer和Postman会自动添加标准的
User-Agent头,而Pythonrequests默认的User-Agent可能被Facebook服务器识别为非标准客户端,触发不同的验证逻辑。手动添加浏览器风格的User-Agent:headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } response = requests.get(url, params=params, headers=headers)令牌传递错误:检查脚本中
uat参数是否完整传递,有没有被截断或修改。在日志中完整打印access_token,确认和Explorer/Postman中使用的完全一致。系统时间偏差:如果Python运行环境的系统时间与实际时间偏差较大,会导致Facebook服务器误判令牌过期。检查服务器系统时间,同步到正确的时区(如PDT)。
内容的提问来源于stack exchange,提问作者Mike Oliver

