67 lines
1.9 KiB
Python
67 lines
1.9 KiB
Python
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}") |