欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解微信小程序-获取用户session_key,openid,unionid - 后端为nodejs

程序员文章站 2022-05-26 11:41:43
微信小程序-获取用户session_key,openid,unionid - 后端为nodejs8.0+ 步骤: 1、通过wx.login接口获取code既jscode...

微信小程序-获取用户session_key,openid,unionid - 后端为nodejs8.0+

步骤:

1、通过wx.login接口获取code既jscode,传递到后端;

2、后端请求

https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=jscode&grant_type=authorization_code

地址,就能获取到openid和unionid。

小程序接口promise化和封装 

1、utils文件夹下创建wechat.js文件

/**
 * promise化小程序接口
 */
class wechat {
 /**
  * 登陆
  * @return {promise} 
  */
 static login() {
  return new promise((resolve, reject) => wx.login({ success: resolve, fail: reject }));
 };
 
 /**
  * 获取用户信息
  * @return {promise} 
  */
 static getuserinfo() {
  return new promise((resolve, reject) => wx.getuserinfo({ success: resolve, fail: reject }));
 };
 
 /**
  * 发起网络请求
  * @param {string} url 
  * @param {object} params 
  * @return {promise} 
  */
 static request(url, params, method = "get", type = "json") {
  console.log("向后端传递的参数", params);
  return new promise((resolve, reject) => {
   let opts = {
    url: url,
    data: object.assign({}, params),
    method: method,
    header: { 'content-type': type },
    success: resolve,
    fail: reject
   }
   console.log("请求的url", opts.url);
   wx.request(opts);
  });
 };
 
 /**
  * 获取微信数据,传递给后端
  */
 static getcryptodata() {
  let code = "";
  return this.login()
   .then(data => {
    code = data.code;
    console.log("login接口获取的code:", code);
    return this.getuserinfo();
   })
   .then(data => {
    console.log("getuserinfo接口", data);
    let obj = {
     js_code: code,
    };
    return promise.resolve(obj);
   })
   .catch(e => {
    console.log(e);
    return promise.reject(e);
   })
 };
 
 /**
  * 从后端获取openid
  * @param {object} params 
  */
 static getmyopenid(params) {
  let url = 'https://xx.xxxxxx.cn/api/openid';
  return this.request(url, params, "post", "application/x-www-form-urlencoded");
 };
}
module.exports = wechat;

2、修改小程序的app.js文件

let wechat = require('./utils/wechat.js');
app({
 onlaunch() {
  this.getuserinfo();
 },
 getuserinfo() {
  wechat.getcryptodata()
   .then(d => {
    return wechat.getmyopenid(d);
   })
   .then(d => {
    console.log("从后端获取的openid", d.data);
   })
   .catch(e => {
    console.log(e);
   })
 }
})

后端nodejs,是用的express命令行生成的项目框架,

1、创建common文件夹,创建utils文件,使用request模块请求接口,promise化request

const request = require("request");
class ut {
 
    /**
     * promise化request
     * @param {object} opts 
     * @return {promise<[]>}
     */
    static promisereq(opts = {}) {
	return new promise((resolve, reject) => {
	    request(opts, (e, r, d) => {
		if (e) {
		    return reject(e);
		}
	        if (r.statuscode != 200) {
		    return reject(`back statuscode:${r.statuscode}`);
		}
		return resolve(d);
	    });
	})
    };
 
};
 
module.exports = ut;

2、新增路由,appid、secret在小程序的后台获取

router.post("/openid", async (req, res) => {
 const ut = require("../common/utils");
 try {
  console.log(req.body);
  let appid = "wx70xxxxxxbed01b";
  let secret = "5ec6exxxxxx49bf161a79dd4";
  let { js_code } = req.body;
  let opts = {
   url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`
  }
  let r1 = await ut.promisereq(opts);
  r1 = json.parse(r1);
  console.log(r1);
  res.json(r1);
 }
 catch (e) {
  console.log(e);
  res.json('');
 }
})

结果:

详解微信小程序-获取用户session_key,openid,unionid - 后端为nodejs

这个返回结果没有unionid,按照官方的说法,需要在绑定小程序;

参考地址:

https://mp.weixin.qq.com/debug/wxadoc/dev/api/uinionid.html

以上所述是小编给大家介绍的微信小程序获取session_key,openid,unionid的方法详解整合,希望对大家有所帮助