最近需要在微信小程序中用到在線支付功能陆盘,于是看了一下官方的文檔,發(fā)現(xiàn)要在小程序里實現(xiàn)微信支付還是很方便的,如果你以前開發(fā)過服務號下的微信支付镇匀,那么你會發(fā)現(xiàn)其實小程序里的微信支付和服務號里的開發(fā)過程如出一轍钮莲,下面我就具體說一下小程序里微信支付的開發(fā)流程和注意點免钻。
1.開通微信支付和微信商戶號
這個過程就和開通服務號的微信支付過程一樣,沒有什么可以說的崔拥。
2.獲得用戶的openid
首頁我們需要在小程序的客戶端js中獲取當前用戶的openid,通過調用wx.login方法可以得到用戶的code,然后開發(fā)者服務器使用登錄憑證 code 獲取 openid伯襟。
wx.login({
success: function(res) {
if (res.code) {
//發(fā)起網(wǎng)絡請求
wx.request({
url: 'https://yourwebsit/onLogin',
method: 'POST',
data: {
code: res.code
},
success: function(res) {
var openid = res.data.openid;
},
fail: function(err) {
console.log(err)
}
})
} else {
console.log('獲取用戶登錄態(tài)失敗握童!' + res.errMsg)
}
}
});
var code = req.param("code");
request({
url: "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code",
method: 'GET'
}, function(err, response, body) {
if (!err && response.statusCode == 200) {
res.json(JSON.parse(body));
}
});
3.獲取prepay_id和支付簽名驗證paySign
這一步的過程就和服務號里的微信支付過程一樣姆怪,分為客戶端和服務器端
首先來看一下客戶端js
在服務號里,我們是通過如下的代碼來調起支付功能
function jsApiCall()
{
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
{
"appId":"", //公眾號名稱澡绩,由商戶傳入
"timeStamp":"", //時間戳稽揭,自1970年以來的秒數(shù)
"nonceStr":"", //隨機串
"package":"prepay_id=<%=prepay_id%>",
"signType":"MD5", //微信簽名方式:
"paySign":"<%=_paySignjs%>" //微信簽名
},
function(res){
WeixinJSBridge.log(res.err_msg);
if( res.err_msg =="get_brand_wcpay_request:ok"){
alert("支付成功!");
}else{
alert("支付失敗!");
}
}
);
}
在小程序里,我們是通過wx.requestPayment方法來調起支付功能肥卡,當然在這之前溪掀,我們先要獲取prepay_id。
wx.request({
url: 'https://yourwebsit/service/getPay',
method: 'POST',
data: {
bookingNo:bookingNo, /*訂單號*/
total_fee:total_fee, /*訂單金額*/
openid:openid
},
header: {
'content-type': 'application/json'
},
success: function(res) {
wx.requestPayment({
'timeStamp':timeStamp,
'nonceStr': nonceStr,
'package': 'prepay_id='+res.data.prepay_id,
'signType': 'MD5',
'paySign': res.data._paySignjs,
'success':function(res){
console.log(res);
},
'fail':function(res){
console.log('fail:'+JSON.stringify(res));
}
})
},
fail: function(err) {
console.log(err)
}
})
那在服務器端主要要實現(xiàn)的是prepay_id的獲取和簽名paySign
var bookingNo = req.param("bookingNo");
var total_fee = req.param("total_fee");
var openid = req.param("openid");
var body = "費用說明";
var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
var formData = "<xml>";
formData += "<appid>appid</appid>"; //appid
formData += "<attach>test</attach>";
formData += "<body>" + body + "</body>";
formData += "<mch_id>mch_id</mch_id>"; //商戶號
formData += "<nonce_str>nonce_str</nonce_str>";
formData += "<notify_url>notify_url</notify_url>";
formData += "<openid>" + openid + "</openid>";
formData += "<out_trade_no>" + bookingNo + "</out_trade_no>";
formData += "<spbill_create_ip>spbill_create_ip</spbill_create_ip>";
formData += "<total_fee>" + total_fee + "</total_fee>";
formData += "<trade_type>JSAPI</trade_type>";
formData += "<sign>" + paysignjsapi(appid, attach, body, mch_id, nonce_str, notify_url, openid, bookingNo, spbill_create_ip, total_fee, 'JSAPI') + "</sign>";
formData += "</xml>";
request({
url: url,
method: 'POST',
body: formData
}, function(err, response, body) {
if(!err && response.statusCode == 200) {
var prepay_id = getXMLNodeValue('prepay_id', body.toString("utf-8"));
var tmp = prepay_id.split('[');
var tmp1 = tmp[2].split(']');
//簽名
var _paySignjs = paysignjs(appid, mch_id, 'prepay_id=' + tmp1[0], 'MD5',timeStamp);
var o = {
prepay_id: tmp1[0],
_paySignjs: _paySignjs
}
res.send(o);
}
});
下面是用到的函數(shù)
function paysignjs(appid, nonceStr, package, signType, timeStamp) {
var ret = {
appId: appid,
nonceStr: nonceStr,
package: package,
signType: signType,
timeStamp: timeStamp
};
var string = raw1(ret);
string = string + '&key='+key;
console.log(string);
var crypto = require('crypto');
return crypto.createHash('md5').update(string, 'utf8').digest('hex');
};
function raw1(args) {
var keys = Object.keys(args);
keys = keys.sort()
var newArgs = {};
keys.forEach(function(key) {
newArgs[key] = args[key];
});
var string = '';
for(var k in newArgs) {
string += '&' + k + '=' + newArgs[k];
}
string = string.substr(1);
return string;
};
function paysignjsapi(appid, attach, body, mch_id, nonce_str, notify_url, openid, 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,
openid: openid,
out_trade_no: out_trade_no,
spbill_create_ip: spbill_create_ip,
total_fee: total_fee,
trade_type: trade_type
};
var string = raw(ret);
string = string + '&key='+key;
var crypto = require('crypto');
return crypto.createHash('md5').update(string, 'utf8').digest('hex');
};
function raw(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);
return string;
};
function getXMLNodeValue(node_name, xml) {
var tmp = xml.split("<" + node_name + ">");
var _tmp = tmp[1].split("</" + node_name + ">");
return _tmp[0];
}
這樣簡單3步步鉴,小程序的微信支付功能就接上了揪胃,下面是測試的支付效果圖