微信支付签名加密在postman中使用

下面代码写在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);
        }
});

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值