微信小程序需要获取用户的openid来作为用户的唯一身份认证,用来存储和更新对应客户信息。 以Node后台为例, 前台发出请求后,后台转发访问对应的微信接口来获取openid.
1. 小程序前端请求:
getUserInfo: function(e) { app.globalData.userInfo = e.detail.userInfo this.setData({ userInfo: e.detail.userInfo, hasUserInfo: true }) wx.login({ success: res => { app.globalData.usercode = res.code //1. 获取usercode作为后面获取openid的参数 } }) var id=null id=wx.getStorageSync('openid') if (!id) { wx.request({ url: getOpenId, //set in config .js //2.后台API method: "POST", data: { js_code: app.globalData.usercode, }, success(res) { var openId = res.data.openid var sessionKey = res.data.session_key console.log(res) wx.setStorageSync("openid", openId) app.globalData.openId = openId if (!!openId) { //3.获取到openid后的处理,可以依照自己的逻辑写 app.globalData.openId = openId wxlogin(openId) } } }) } } })
2. Node JS 后台获取openid:
router.post('/wxgetOpenId', function (req, res, next) { var data=req.body var APP_URL='https://api.weixin.qq.com/sns/jscode2session' var APP_ID='wxXXXXXXXXX' //小程序的app id ,在公众开发者后台可以看到 var APP_SECRET='8ad6f0XXXXXXXXXXXX' //程序的app secrect,在公众开发者后台可以看到 var resData=null var thisRes=res if(!!data.js_code) { request(`${APP_URL}?appid=${APP_ID}&secret=${APP_SECRET}&js_code=${data.js_code}&grant_type=authorization_code`, (error, response, body)=>{ console.log('statusCode:', response && response.statusCode) console.log(body) res.end(body)}) } })