微信支付比较简单
基本的步骤
一、app前端获取统一下单(服务器提供)
二、拿到获取到的数据调用微信sdk支付
三、支付成功后的跳转(此时分为同步通知和异步通知)
四、服务器接受通知后做业务处理
统一下单
var request = require('request');
var xml2js = require('xml2js'); //支付返回的数据都是xml形式
var wxPay = function (req, res) {
var subject = req.query.subject;
var bodys = req.query.body;
var amount = parseFloat(req.query.amount);
var chinaCoinNum = parseInt(req.query.chinaCoinNum);
var outTradeId = uuid.v1().replace(/\-/g, '');
var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
var appid = 'xxxxxxxxxx'; //appid
var mch_id = 'xxxxxxxxxxx'; //商户号
var notify_url = 'https://xxxxxxxx/wxPay/notify';
var out_trade_no = outTradeId;
var total_fee = amount * 100;
var attach = 'XXapp';
var body = bodys; //客户端商品描述
var nonce_str = createNonceStr();
var formData = "";
formData += "" + appid + " "; //appid
formData += "" + attach + " "; //附加数据
formData += "" + body + ""; //商品或支付单简要描述
formData += "" + mch_id + " "; //商户号
formData += "" + nonce_str + " "; //随机字符串,不长于32位
formData += "" + notify_url + " "; //支付成功后微信服务器通过POST请求通知这个地址
formData += "" + out_trade_no + " "; //订单号
formData += "xx.xx.xx.xx "; //服务端ip
formData += "" + total_fee + " "; //金额
formData += "APP "; //类型APP
formData += "" + wxPayTool.paysign(appid, attach, body, mch_id, nonce_str, notify_url, out_trade_no, '47.97.209.61', total_fee, 'APP') + " ";
formData += " ";
request(
{
url: url,
method: 'POST',
body: formData
}, function (err, response, body) {
if (!err && response.statusCode == 200) {
var parser = new xml2js.Parser({trim: true, explicitArray: false, explicitRoot: false});//解析签名结果xml转json
parser.parseString(body, function (err, result) {
console.log("result", result);
var timeStamp = Date.parse(new Date()) / 1000;
var sign = wxPayTool.paySignTwo(appid, nonce_str, 'Sign=WXPay', mch_id, result['prepay_id'], timeStamp);//得到prepay再次签名
res.end(JSON.stringify({
"flag": "success",
"result": {
'outTradeId': outTradeId,
'appId': appid,
'partnerId': mch_id,
'prepayId': result['prepay_id'],
'nonce_str': nonce_str,
'time_stamp': timeStamp,
'package_value': 'Sign=WXPay',
'sign': sign
}
}));//返回给客户端数据
});
}
}
);};
前端调用支付
具体看appSDK支付文档,这里就不做阐述,主要讲解后台
通知
同步通知
同步通知需要后台提供给客户端一个接口,后台通过前端传过来的参数查询订单号返回给客户端支付结果(业务逻辑做好在异步通知做,因为会有很多因素影响,例如客户端支付成功后网络异常,此时没有办法查询订单,就没有办法做业务处理)
var queryOrder = function (req, res) {
var appid = "xxxxxxx"; //appid
var mch_id = "xxxxxxxxx";//微信商户后台 商户号
var nonce_str = req.body.nonce_str;//在统一下单时生成的唯一的随机字符串
var out_trade_no = req.body.out_trade_no;//在统一下单时生成的唯一的随机订单号
req.outTradeId = req.body.out_trade_no;
var sign = wxPayTool.querySign(appid, mch_id, nonce_str, out_trade_no);//查询签名
var formData = "";
formData += "" + appid + " "; //appid
formData += "" + mch_id + " "; //商户号
formData += "" + nonce_str + " "; //随机字符串,不长于32位。
formData += "" + out_trade_no + " ";
formData += "" + sign + " ";
formData += " ";
var regUrl = "https://api.mch.weixin.qq.com/pay/orderquery"; //查询api
request(
{
url: regUrl,
method: 'POST',
body: formData
}, function (err, response, body) {
if (!err && response.statusCode == 200) {
var parser = new xml2js.Parser({trim: true, explicitArray: false, explicitRoot: false});//解析签名结果xml转json
parser.parseString(body, function (err, result) {
console.log("queryResult", result);
if (result['return_code'] == "SUCCESS" && result['result_code'] == "SUCCESS") {
if (result['trade_state'] == "SUCCESS") {
getIfDetail(result['out_trade_no'], function (rs) {
if (rs.amount * 100 == result['total_fee'] * 1) { //比对金额是否一样,注意:微信返回的是分 一般存储是元 所以需要转换一下
var info = {
"flag": "success",
};
res.end(JSON.stringify(info));
} else {
var info = {
"flag": "failed",
"msg": "订单金额不符"
};
res.end(JSON.stringify(info));
console.log(info);
}
});
}
}
});
}
}
);};
异步通知
支付完成后后台接受支付宝的异步通知(在统一下单的时候传入notify_url)
直接上代码
var wxNotifys = function (req, res) {
var parser = new xml2js.Parser({trim: true, explicitArray: false, explicitRoot: false});//xml转json
parser.parseString(req.rawBody, function (err, result) {
console.log("result", result);
if (result['return_code'] == "SUCCESS" && result['result_code'] == "SUCCESS") {
var xml = ' ';
res.end(xml); //返回给支付宝通知,否则支付宝会不断请求该通知接口
}
}
});
} else {
var xml = ' ';
res.end(xml);
}
});};
wx支付签名方法
直接贴代码
var request = require('request');
var xml2js = require('xml2js');
var crypto = require('crypto');
var paysign = function(appid,attach,body,mch_id,nonce_str,notify_url,out_trade_no,spbill_create_ip,total_fee,trade_type) { //统一下单签名
var ret = {
"appid": appid,
"attach": attach,
"body": body,
"mch_id": mch_id,
"nonce_str": nonce_str,
"notify_url":notify_url,
"out_trade_no":out_trade_no,
"spbill_create_ip":spbill_create_ip,
"total_fee":total_fee,
"trade_type":trade_type
};
var string = raw(ret);
var key = 'xxxxxxxxxxx';
string = string + '&key='+key; //key为在微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
console.log("签名");
console.log(crypto.createHash('md5').update(string,'utf8').digest('hex').toUpperCase());
return crypto.createHash('md5').update(string,'utf8').digest('hex').toUpperCase();
};
var raw = function(args) {
var keys = Object.keys(args);
keys = keys.sort();
var newArgs = {};
keys.forEach(function (key) {
newArgs[key.toLowerCase()] = args[key];
});
var string = '';
for (var k in newArgs) {
string += '&' + k + '=' + newArgs[k];
}
string = string.substr(1);
console.log(string);
return string;
};
var buildXML = function(json){
var builder = new xml2js.Builder();
return builder.buildObject(json);
};
var paySignTwo = function(appid,notifystr,packagevalue,mchid,prepayid,timestamp) { //参数名不可改,必须严格一模一样
var ret = {
"appid": appid,
"noncestr": notifystr,
"package": packagevalue,
"partnerid": mchid,
"prepayid": prepayid,
"timestamp":timestamp
};
var string = raw(ret);
var key = 'xxxxxxxxxxx';
string = string + '&key='+key; //key为在微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
console.log("签名");
console.log(crypto.createHash('md5').update(string,'utf8').digest('hex').toUpperCase());
return crypto.createHash('md5').update(string,'utf8').digest('hex').toUpperCase();
};
//查询签名sign
var querySign = function(appid,mch_id,nonce_str,out_trade_no){
var ret = {
"appid": appid,
"mch_id": mch_id,
"nonce_str":nonce_str,
"out_trade_no":out_trade_no//注意左边参数名
};
console.log("查询签名验证的参数",ret);
var string = raw(ret);
var key = "xxxxxxxxxxxx";
string = string + '&key='+key;
return crypto.createHash('md5').update(string,'utf8').digest('hex').toUpperCase();
};
module.exports={
paysign:paysign,
raw : raw,
paySignTwo : paySignTwo,
buildXML:buildXML,
querySign:querySign
};
nodejs ,express 4.x坑
express4.x里将body-parser分离出来,而对于微信支付的结果通知里的数据是XML的,其就“无法”解析
在app.js里面配置
npm install --save body-parser-xml
var bodyParser = require("body-parser");
require("body-parser-xml")(bodyParser);
app.use(bodyParser.xml({
limit: "1MB", // Reject payload bigger than 1 MB
xmlParseOptions: {
normalize: true, // Trim whitespace inside text nodes
normalizeTags: true, // Transform tags to lowercase
explicitArray: false // Only put nodes in array if >1
},
verify: function(req, res, buf, encoding) {
if(buf && buf.length) {
// Store the raw XML
req.rawBody = buf.toString(encoding || "utf8");
}
}
}));
app.use(bodyParser.json());
nodejs 微信支付到此基本上就完成了,app客户端比较简单,后台稍微麻烦一点,操作都放在后台这样子比较安全一些。第一次写支付,记录一下。