node封装获取微信小程序用户信息

295 阅读1分钟
/*
 * @Author: 
 * @Date: 2021-09-27 09:54:43
 * @LastEditors: 
 * @LastEditTime: 2021-09-27 11:44:25
 * @msg: 对于微信授权的封装
 */
const request = require("request");
const crypto = require("crypto");

class wechat {
  constructor(appId, appSecret) {
    this.appId = appId;
    this.appSecret = appSecret;
  }
  getOpenid(code) {
    let options = {
      method: "POST",
      url: "https://api.weixin.qq.com/sns/jscode2session?",
      formData: {
        appid: this.appId,
        secret: this.appSecret,
        js_code: code,
        grant_type: "authorization_code",
      },
    };
    return new Promise((resolve, reject) => {
      request(options, (error, response, body) => {
        if (error) {
          reject(error);
          return;
        }
        let newBody = JSON.parse(body);
        if (!newBody.openid) {
          reject(newBody.errcode);
          return;
        }
        this.appid = newBody.openid;
        this.sessionKey = newBody.session_key;
        resolve(newBody.openid);
      });
    });
  }
  async getUserInfo(code, encryptedData, iv) {
    // 先通过code 获取到用户的openid和session_key,方便后面解密
    await this.getOpenid(code);
    // 使用base64进行解码
    const sessionKey = Buffer.from(this.sessionKey, "base64");
    encryptedData = Buffer.from(encryptedData, "base64");
    iv = Buffer.from(iv, "base64");
    let userInfo;
    let decoded;
    try {
      // 解密
      let decipher = crypto.createDecipheriv("aes-128-cbc", sessionKey, iv);
      // 设置自动 padding 为 true,删除填充补位
      decipher.setAutoPadding(true);
      decoded = decipher.update(encryptedData, "binary", "utf8");
      decoded += decipher.final("utf8");
      userInfo = JSON.parse(decoded);
    } catch (error) {
      throw new Error("Illegal Buffer");
    }
    if (userInfo.watermark.appid !== this.appId) {
      throw new Error("Illegal Buffer");
    }

    return userInfo;
  }
}

module.exports = wechat;