下面代码写在postman的Pre-request Script里面
const private_key = `-----BEGIN PRIVATE KEY-----
apiclient_cert.p12文件里的内容全部复制过来
-----END PRIVATE KEY-----`;
const mchid = 商户号;
const serialNo = 证书序列化;
let sdk = require('postman-collection');
// request data does not resolve variables which makes sign-error
// see https://github.com/postmanlabs/postman-app-support/issues/3322
function replaceVariables(templateString) {
let tokens = _.uniq(templateString.match(/{{\w*}}/g))
_.forEach(tokens, t => {
let variable = t.replace(/[{}]/g, '')
let value = environment[variable] || globals[variable]
templateString = templateString.replace(new RegExp(t,'g'), value)
});
return templateString
}
var newUrl = new sdk.Url(replaceVariables(request.url));
var now = Date.now();
var timeStamp = Math.round(now / 1000);
var nonceStr = now;
var method = request.method;
var data = "";
var canonicalUrl = newUrl.getPathWithQuery();
if (method == 'POST' || method == 'PUT' || method == 'PATCH') {
var data = pm.request.body.raw;
if (canonicalUrl.endsWith('upload')) {
var result = JSON.parse(JSON.stringify(pm.request.body.formdata));
for (var i in result) {
if (result[i].key == 'meta') {
data = result[i].value;
}
}
}
}
var message = method + "\n"
+ canonicalUrl + "\n"
+ timeStamp + "\n"
+ nonceStr + "\n"
+ data + "\n";
pm.sendRequest("https://wx.gtimg.com/pay/js/apiv3/libs/node-forge@0.7.6/forge.min.js", function (err, res) {
if (err) {
console.log(err);}
else {
eval(res.text());
var privateKey = forge.pki.privateKeyFromPem(private_key);
var sha256 = forge.md.sha256.create();
sha256.update(forge.util.encodeUtf8(message));
var signature = forge.util.encode64(privateKey.sign(sha256));
console.log(`message=[${message}]`);
var auth = `WECHATPAY2-SHA256-RSA2048 mchid="${mchid}",serial_no="${serialNo}",nonce_str="${nonceStr}",timestamp="${timeStamp}",signature="${signature}"`;
pm.environment.set("auth", auth);
}
});