文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
总结下整个openid、session_key获取的流程:
注册微信小程序、登录后台在设置中获得appId和secret(密钥)
调用wx.login()接口获取登录凭证js_code
调用wx.request()接口把js_code发送到服务器后台
在服务器后台,已知appId、secret、js_code
然后调用官方提供的http接口,即可返回获取openId、session_key
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
// 登录
wx.login({
success: res => {
// ------ 获取凭证 ------
var code = res.code;
if (code) {
// console.log('获取用户登录凭证:' + code);
// ------ 发送凭证 ------
wx.request({
url: '后台通过获取前端传的code返回openid的接口地址',
data: { code: code },
method: 'POST',
header: {
'content-type': 'application/json'
},
success: function (res) {
if (res.statusCode == 200) {
// console.log("获取到的openid为:" + res.data)
// that.globalData.openid = res.data
wx.setStorageSync('openid', res.data)
} else {
console.log(res.errMsg)
}
},
})
} else {
console.log('获取用户登录失败:' + res.errMsg);
}
}
})
涉及到安全问题,最好将openid在后台加密为token后返回前端缓存,不宜在前端保存openid