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) {
await this.getOpenid(code);
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);
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;