Home > WeChat Applet > Mini Program Development > How to obtain user session_key, openid, unioni in WeChat applet (code)

How to obtain user session_key, openid, unioni in WeChat applet (code)

不言
Release: 2018-09-07 16:26:27
Original
6091 people have browsed it

Obtain user session_key, openid, and unioni in the WeChat mini program. This is a function that can often be seen in mini programs. So how to implement the mini program to obtain session_key, openid, and unionid; this article will introduce to you about the backend. The node.js WeChat applet implements the method of obtaining user session_key, openid, and unionid.

Steps:

1. Obtain the code and jscode through the wx.login interface and pass it to the backend;

2 , backend request

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

address, you can get the openid and unionid .

Mini program interface promise and encapsulation

1. Create the wechat.js file in the utils folder

/**
 * 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;
Copy after login

2. Modify the app.js file of the mini program

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);
      })
  }
})
Copy after login

The back-end nodejs is a project framework generated using the express command line,

1. Create a common folder, create a utils file, use the request module to request the interface, and promise the 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;
Copy after login

2. Add a new route, and obtain the appId and secret in the background of the mini program.

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(&#39;&#39;);
  }
})
Copy after login

Result:

How to obtain user session_key, openid, unioni in WeChat applet (code)

This return result does not have a unionid. According to the official statement, it needs to be sent to WeChat Open platformBind mini program;

Related recommendations:

How to get the user’s openid from WeChat mini program

# #Introduction to how to obtain the parameters openid & session_key in the mini program

The above is the detailed content of How to obtain user session_key, openid, unioni in WeChat applet (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template