diff --git a/lib/api_common.js b/lib/api_common.js index 34c92f7..60156d8 100644 --- a/lib/api_common.js +++ b/lib/api_common.js @@ -216,7 +216,7 @@ class API { err.code = 40001; throw err; } - return this.getAccessToken(); + throw new Error('can\'t set access token'); } } diff --git a/lib/util.js b/lib/util.js index 1f9341f..2efd3ae 100644 --- a/lib/util.js +++ b/lib/util.js @@ -1,4 +1,5 @@ 'use strict'; +const crypto = require('crypto'); /*! * 对提交参数一层封装,当POST JSON,并且结果也为JSON时使用 */ @@ -42,3 +43,30 @@ function _replaceOneChar(c) { exports.replaceJSONCtlChars = function (str) { return str.replace(JSONCtlCharsRE, _replaceOneChar); }; + +/** + * 小程序加密数据解密算法 + * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html + * @param {string} sessionKey + * @param {string} iv + * @param {string} encryptedData + * @returns {Object} + */ +exports.decryptDataForMiniProgram = function (sessionKey, iv, encryptedData) { + const sessionKeyBuffer = Buffer.from(sessionKey, 'base64'); + const ivBuffer = Buffer.from(iv, 'base64'); + const encryptedBuffer = Buffer.from(encryptedData, 'base64'); + + try { + const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKeyBuffer, ivBuffer); + // 设置自动 padding 为 true,删除填充补位 + decipher.setAutoPadding(true); + const decoded = + decipher.update(encryptedBuffer, 'binary', 'utf8') + + decipher.final('utf8'); + + return JSON.parse(decoded); + } catch (err) { + throw new Error('解密失败'); + } +}; diff --git a/package.json b/package.json index 12d800f..29fa0f0 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "co-wechat-api", + "name": "co-wechat-api-new", "version": "3.11.0", "description": "微信公共平台Node库API,ES6版本", "main": "index.js", @@ -30,7 +30,7 @@ "rewire": "*", "travis-cov": "*" }, - "author": "Jackson Tian", + "author": "Salamander", "license": "MIT", "readmeFilename": "README.md", "directories": {