var url = 'http://127.0.0.1:8000/'
onLoad: function () {
var that = this
wx.login({
success: res => {
var code = res.code
// 获取用户的openID 判断是否是新用户
wx.request({
url: url + 'get_unionid/',
method: 'POST',
data: {
code: code
},
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log('首页onLoad方法')
console.log(res)
}
})
}
})
},
python 后端
appid = 'xxxxxxxxxx'
secret = 'xxxxxxxxxxxxxxxxxxxx'
###### 获取unionid
@csrf_exempt
def get_unionid(request):
if request.method == "POST":
data = request.body
data = json.loads(data.decode("utf8"))
code = data.get("code")
get_openid__ = open_union_function(code, appid, secret) # 调用获取openid方法
return HttpResponse(1)
else:
return HttpResponse(0)
# 获取用户的openID,unionID
def open_union_function(code, appid, secret):
url_openid = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code'
r_openid = requests.get(url_openid)
dic = r_openid.json() ## 把获取到的参数转json格式
# dic = r_openid.text ## 展示获取到的参数
unionid = dic['unionid']
openid = dic['openid']
return unionid, openid