python api
def get_wx_user_openid(code:str=None):
infoList = {}
try:
#code为传参 appid--小程序appid secret--小程序密钥
github_url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code"
r = requests.get(github_url)
info = json.loads(r.text)
if(info['openid']):
infoList['info'] = info
infoList['code'] = 0
# print("成功")
else:
infoList['code'] = 101
infoList['msg'] = info['errmsg']
infoList['errcode'] = info['40163']
# print("失败")
except Exception as e:
infoList["code"] = 200
infoList['msg'] = e.args
# print('接口失败')
return infoList
小程序js
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
console.log(res)
if(res.errMsg=="login:ok"){
wx.request({
url: that.globalData.url+'get_wx_user_openid',
method:'get',
data:{code:res.code},
success:function(data){
console.log(data)
if(data.data.code == 0){
console.log('成功')
wx.setStorageSync('openid', data.data.info.openid)
}else{
wx.showToast({
title: data.data.msg,
duration:3000
})
}
},
fail:function(fails){
console.log(fails)
wx.showToast({
title: '登陆失败!',
duration:3000
})
}
})
}
}
})