coa-wx-pay-isv
Version:
轻量的的微信支付SDK服务商版 for Node.js
74 lines (73 loc) • 2.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoaWxPayIsvBin = void 0;
const coa_error_1 = require("coa-error");
const coa_helper_1 = require("coa-helper");
const coa_secure_1 = require("coa-secure");
const coa_xml_1 = require("coa-xml");
const https_1 = require("https");
const baseURL = 'https://api.mch.weixin.qq.com';
class CoaWxPayIsvBin {
constructor(config) {
this.config = config;
this.httpsAgent = new https_1.Agent({ pfx: config.pfx, passphrase: config.mchId });
}
// 生成签名
generateSignature(object) {
const paramList = [];
coa_helper_1._.forEach(object, (v, k) => {
if (v)
paramList.push(k + '=' + v);
});
paramList.sort(undefined);
paramList.push('key=' + this.config.key);
const paramString = paramList.join('&');
return coa_secure_1.secure.md5(paramString).toUpperCase();
}
// 生成随机字符串
generateNonceString() {
return Math.random().toString(36).substr(2, 15);
}
// 转换为已经签名的XML参数
async toSignedXmlParams(param, signName = 'sign') {
param[signName] = this.generateSignature(param);
return await coa_xml_1.xml.encode(param);
}
// 进行post请求
async post(url, data, config = {}) {
const res = await (0, coa_helper_1.axios)({
url,
data,
baseURL,
method: 'POST',
...config,
}).catch((e) => e);
// 处理结果
try {
return await this.handleResult(res);
}
catch (e) {
this.onRequestError(e, res);
throw e;
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onRequestError(error, response) {
// handle request error
}
// 处理响应结果
async handleResult(res) {
const text = res.data || '';
if (!text)
coa_error_1.CoaError.throw('CoaWxPayIsv.ServeCallError', '微信支付服务器数据异常');
if (!text.startsWith('<xml'))
return text;
const info = await coa_xml_1.xml.decode(text);
info.return_code === 'SUCCESS' ||
coa_error_1.CoaError.throw('CoaWxPayIsv.ServeReturnError', info.return_msg);
info.result_code === 'SUCCESS' ||
coa_error_1.CoaError.throw('CoaWxPayIsv.ServeResultError', info.err_code + ':' + info.err_code_des);
return coa_helper_1.$.camelCaseKeys(info);
}
}
exports.CoaWxPayIsvBin = CoaWxPayIsvBin;