From 5155fa36862e90f903e691a2b1d25b8d8330e999 Mon Sep 17 00:00:00 2001 From: 13315423919 <13315423919@qq.com> Date: Wed, 19 Nov 2025 19:42:50 +0800 Subject: [PATCH] Add File --- main/wechat.py | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 main/wechat.py diff --git a/main/wechat.py b/main/wechat.py new file mode 100644 index 0000000..7f8d41e --- /dev/null +++ b/main/wechat.py @@ -0,0 +1,67 @@ +import requests +import json + +def get_wechat_access_token(appid,secret,code): + """ + 正确返回值: + { + "access_token":"ACCESS_TOKEN", + "expires_in":7200, + "refresh_token":"REFRESH_TOKEN", + "openid":"OPENID", + "scope":"SCOPE", + "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" + } + """ + # 微信OAuth2.0 access_token接口URL + url = f'https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code' + + # 发送GET请求 + response = requests.get(url) + + # 检查请求是否成功 + if response.status_code == 200: + # 解析JSON响应 + data = response.json() + return data + else: + # 如果请求失败,打印错误信息 + print(f"Error: {response.status_code}, {response.text}") + return {} + + +def get_wechat_userinfo(access_token,openid): + """ + 正确返回数据 + { + "openid": "OPENID", + "nickname": "NICKNAME", + "sex": 1, + "province": "PROVINCE", + "city": "CITY", + "country": "COUNTRY", + "headimgurl": "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6ficibnY/0", + "privilege": [ + "PRIVILEGE1", + "PRIVILEGE2" + ], + "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" + } + """ + #lang = 'zh_CN' # 可选参数,语言,如:'zh_CN', 'zh_TW', 'en' + + # 微信OAuth2.0 userinfo接口URL + url = f'https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}&lang=zh_CN' + + # 发送GET请求 + response = requests.get(url) + + # 检查请求是否成功 + if response.status_code == 200: + content=response.content.decode("utf-8") + # 解析JSON响应 + data = json.loads(content) + return data + else: + # 如果请求失败,打印错误信息 + raise(f"Error: {response.status_code}, {response.text}") \ No newline at end of file