流程:
1.前端用wx.login()方法拿到code,然后把code给后端;
2.后端拿code,appid,secret去请求微信后台接口;
3.接口会返回用户数据,包括openid和session_key,拿到openId再返回给前端
小程序端:
// 登录wx.login({success: res => {console.log("login success res",res)// 发送 res.code 到后台换取 openId, sessionKey, unionIdwx.request({url: 'http://localhost:8086/getUserInfo',data: { code: res.code },method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECTheader: {'content-type': 'application/x-www-form-urlencoded'},// 设置请求的 headersuccess: function (res) {console.log('获取用户unionId', res);},fail: function () {console.log("index.js wx.request CheckCallUser fail");},complete: function () {// complete}})}})
node.js端
//获取openIdapp.post("/getUserInfo", async (req, res) => {console.log('从前台获取来的req.body',req.body);if(req.body.code) {let options = {method: 'POST',url: 'https://api.weixin.qq.com/sns/jscode2session?',formData: {appid: "wx7xxxxxxx0",//appidsecret: "710fxxxxxxx45b1a",//密钥,在小程序后台获取js_code: req.body.code,//用户codegrant_type: 'authorization_code'}};request(options, (error, response, body) => {if(error) { //请求异常时,返回错误信息res.json({"status": "error",})} else {let _data = JSON.parse(body);res.json(_data);console.log('返回的用户id:',_data);}})}})
成功
如果一直返回 40092 ,检查appid前后端是否一致,密钥是否错误