SoFunction
Updated on 2024-10-30

WeChat applet - get user session_key,openid,unionid - Backend for nodejs

WeChat applet - get user session_key,openid,unionid - nodejs8.0+ backend

Steps:

1, through the interface to get code both jscode, passed to the back end;

2. Back-end requests

/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

address, it will be able to get the openid and unionid.

Applet interface promising and encapsulation

1. Create a file in the utils folder

/**
 * Promise-ized applet interface
 */
class Wechat {
 /**
  * Login
  * @return {Promise}
  */
 static login() {
  return new Promise((resolve, reject) => ({ success: resolve, fail: reject }));
 };
 
 /**
  * Get user information
  * @return {Promise}
  */
 static getUserInfo() {
  return new Promise((resolve, reject) => ({ success: resolve, fail: reject }));
 };
 
 /**
  * Initiate a web request
  * @param {string} url
  * @param {object} params
  * @return {Promise}
  */
 static request(url, params, method = "GET", type = "json") {
  ("Parameters passed to the backend", params);
  return new Promise((resolve, reject) => {
   let opts = {
    url: url,
    data: ({}, params),
    method: method,
    header: { 'Content-Type': type },
    success: resolve,
    fail: reject
   }
   ("Requested URL", );
   (opts);
  });
 };
 
 /**
  * Get microsoft data, pass it to the backend.
  */
 static getCryptoData() {
  let code = "";
  return ()
   .then(data => {
    code = ;
    ("The code obtained by the login interface:", code);
    return ();
   })
   .then(data => {
    ("getUserInfo interface"., data);
    let obj = {
     js_code: code,
    };
    return (obj);
   })
   .catch(e => {
    (e);
    return (e);
   })
 };
 
 /**
  * Get openid from backend
  * @param {object} params
  */
 static getMyOpenid(params) {
  let url = '/api/openid';
  return (url, params, "POST", "application/x-www-form-urlencoded");
 };
}
 = Wechat;

2. Modify the file of the small program

let wechat = require('./utils/');
App({
 onLaunch() {
  ();
 },
 getUserInfo() {
  ()
   .then(d => {
    return (d);
   })
   .then(d => {
    ("openid from the backend", );
   })
   .catch(e => {
    (e);
   })
 }
})

The backend, nodejs, is the framework of the project generated with the express command line.

1, create a common folder, create utils file, use the request module to request the interface, promote the request

const request = require("request");
class Ut {
 
    /**
     * Promise-ized 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 ( != 200) {
		    return reject(`back statusCode:${}`);
		}
		return resolve(d);
	    });
	})
    };
 
};
 
 = Ut;

2, new routing, appId, secret in the background of the small program to get

("/openid", async (req, res) => {
 const Ut = require("../common/utils");
 try {
  ();
  let appId = "wx70xxxxxxbed01b";
  let secret = "5ec6exxxxxx49bf161a79dd4";
  let { js_code } = ;
  let opts = {
   url: `/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`
  }
  let r1 = await (opts);
  r1 = (r1);
  (r1);
  (r1);
 }
 catch (e) {
  (e);
  ('');
 }
})

Results:

This return result does not have a unionid, and according to the official statement, it needs to be in theWeChat Open PlatformBind the applet;

Reference address:

/debug/wxadoc/dev/api/

/debug/wxadoc/dev/api/

The above is a small introduction to the WeChat small program to get session_key,openid,unionid method detailed integration, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. I would also like to thank you very much for your support of my website!