您的位置:首页 > 移动开发 > 微信开发

NodeJS微信支付签名代码

2017-07-25 00:00 141 查看
//统一下单签名参数顺序
let ss1Str = ['appid', 'body', 'mch_id', 'nonce_str', 'notify_url', 'out_trade_no', 'spbill_create_ip', 'total_fee', 'trade_type'];
//支付签名参数顺序(公众号)
let ss2Str = ['appId', 'nonceStr', 'package', 'signType', 'timeStamp'];
//支付签名参数顺序(APP)
let ss3Str = ['appid', 'noncestr', 'package', 'partnerid', 'prepayid', 'timestamp'];

/**
* 微信签名
*/
router.get('/wxpay/sign2', function (req, res) {
let statementId = req.queryData.statementId;
let userId = req.queryData.userId;
let ids = statementId.split(',');
Statement.findAll({
where: {
id: {$in: ids}
}
}).then((list) => {
let sum = 0;
let ids = '';
let contractId = '';
let remark = '';
list.forEach(function (st) {
if (st.state == 0) {
sum += st.sum;
ids += st.id + ',';
contractId = st.contractId;
if (st.num > 0) {
remark += '第' + st.num + '期' + st.remark + ',';
} else if (st.num == 0) {
remark += st.remark + ',';
} else if (st.num == -1) {
remark += st.title + ' ' + st.remark + ',';
}
}
});

if (sum == 0 || ids.length == 0) {
res.json({result: false, message: '未找到可以支付的记录'});
} else {
OrderPay.build({
sum: sum,
type: 1,
contractId: contractId,
statementIds: ids,
payerId: userId,
remark: remark
}).save().then(function (orderPay) {
let ipAddress = getClientIp(req);
console.log('ipAddress===' + ipAddress);
ipAddress = '218.205.52.3';
let cost = parseInt(orderPay.sum*100);
console.log('cost=' + cost);
//调用微信接口下单
let map = initMap();
map['notify_url'] = config.jhkj.weixin.notify_url; //通知地址
map['spbill_create_ip'] = ipAddress;
map['body'] = config.jhkj.weixin.appname + '-' + orderPay.remark; //商品描述
map['out_trade_no'] = orderPay.id; //商户订单号
map['total_fee'] = cost; //总金额

let signData = signup(map, ss1Str);

unifiedorder(signData, function(body) {
xml2js.parseString(body, function(err, result) {
if (result.xml.return_code[0] == 'FAIL') {
res.json({result: false, message: result.xml.return_msg[0]});
return;
} else if (result.xml.result_code[0] == 'FAIL') {
if (result.xml.err_code[0] == 'OUT_TRADE_NO_USED') { //商户订单号重复
} else if (result.xml.err_code[0] == 'ORDERPAID') { //商户订单已支付
}
res.json({result: false, message: result.xml.err_code_des[0]});
} else {
//统一下单成功,返回签名信息
let prepayId = result.xml.prepay_id[0];
let map2 = {
"appid": config.jhkj.weixin.appid
,"timestamp": new Date().getTime().toString().substring(0, 10)
,"noncestr": uuid.v1().replace(/\-/g,"")
,"package": "Sign=WXPay"
,"prepayid": prepayId
,"partnerid": config.jhkj.weixin.mch_id
};
map2.paySign = getSignStr(map2, ss3Str);
res.json({result: true, payJSON: map2, prepayId: prepayId, out_trade_no: orderPay.id });
}
});
});
});
}
});
});

/**
* 微信统一下单
* @param data
* @param callback
*/
function unifiedorder(data, callback) {
let opt = {
method: 'POST'
,host: 'api.mch.weixin.qq.com'
,port: 443
,path: '/pay/unifiedorder'
,headers: {
'Content-Type': 'text/xml;charset=utf-8'
,'Content-Length': iconv.encode(data, 'utf8').length
}
};

let reqVideo = https.request(opt, function(serverFeedback) {
serverFeedback.setEncoding('utf-8');
console.log('getVideo:' + serverFeedback.statusCode);
if (serverFeedback.statusCode == 200) {
let body = "";
serverFeedback
.on('data', function (data) { body += data; })
.on('end', function () {
console.log(body);
callback(body);
});
} else {
console.log(serverFeedback.statusCode);
}
});
reqVideo.write(iconv.encode(data, 'utf8'));
reqVideo.end();
}

/**
* 生成签名字符串
* @param map
* @param arrStr
* @returns {string}
*/
function getSignStr(map, arrStr) {
let stringA = '';
let index = 0;
arrStr.forEach(function(key) {
stringA += (index++ != 0 ? '&' : '') + key + '=' + map[key];
});
stringA += '&key=' + config.jhkj.weixin.paykey;
return utils.md5(stringA).toUpperCase();
}

/**
* 获取签名数据
* @param map
* @param arrStr
*/
function signup(map, arrStr) {
let sign = getSignStr(map, arrStr);
let data = '<xml>';
arrStr.forEach(function(key) {
if (key == 'body') {
data += '<' + key + '><![CDATA[' + map[key] + ']]></' + key + '>';
} else {
data += '<' + key + '>' + map[key] + '</' + key + '>';
}
});
data += '<sign>' + sign + '</sign>';
data += '</xml>';

return data;
}

/**
* 初始化基础参数map
* @returns {{}}
*/
function initMap() {
let map = {};
map['appid'] = config.jhkj.weixin.appid;
map['mch_id'] = config.jhkj.weixin.mch_id;
map['trade_type'] = 'APP';
map['nonce_str'] = uuid.v1().replace(/\-/g,"");
return map;
}

/**
* 获取用户端IP地址
* @param req
* @returns {*}
*/
function getClientIp(req) {
let ipaddress = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
if (ipaddress.indexOf(',') >= 0) {
ipaddress = ipaddress.split(',')[0];
}
return ipaddress;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: