node-easywechat
Version:
EasyWechat SDK for Node.js (NOT OFFICIAL)
60 lines (59 loc) • 2.16 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Utils_1 = require("../Core/Support/Utils");
const merge_1 = __importDefault(require("merge"));
class LegacySignature {
constructor(merchant) {
this.merchant = merchant;
}
/**
* V2版本的签名计算,并返回带签名字段的参数集合
* @param params 参数集合
* @returns
*/
sign(params) {
var _a, _b;
let nonce = (0, Utils_1.randomString)();
let attributes = (0, merge_1.default)(true, {
nonce_str: nonce,
sub_mch_id: (_a = params['sub_mch_id']) !== null && _a !== void 0 ? _a : null,
sub_appid: (_b = params['sub_appid']) !== null && _b !== void 0 ? _b : null,
}, params);
let signString = '';
let sparator = '';
let keys = Object.keys(attributes);
keys = keys.sort();
for (let i = 0; i < keys.length; i++) {
if (keys[i] == 'sign' || typeof attributes[keys[i]] === undefined || attributes[keys[i]] === null)
continue;
signString += sparator + keys[i] + '=' + attributes[keys[i]];
sparator = '&';
}
let key = this.merchant.getV2SecretKey();
if (!key) {
throw new Error('Missing V2 API key.');
}
signString += '&key=' + key;
let sign = '';
let type = params['sign_type'] ? (params['sign_type'] + '').toLowerCase() : 'md5';
switch (type) {
case 'sha1':
case 'md5':
sign = (0, Utils_1.createHash)(signString, type);
break;
case 'hmac-sha256':
case 'hmac_sha256':
type = type.replace(/^hmac[\-|_]/i, '');
sign = (0, Utils_1.createHmac)(signString, key, type);
break;
}
if (!sign) {
throw new Error('Failed to sign the request.');
}
params.sign = (sign + '').toUpperCase();
return params;
}
}
module.exports = LegacySignature;
;