替微信小程序加上支付功能時,許多人會發現入口藏得不太好找:小程序的建置在公眾號後台,但支付相關的說明卻散落在小程序 API 文件裡,一時之間讓人搞不清它到底屬於公眾號支付還是 App 支付。本文把整個支付流程拆成三個步驟,並附上簽名計算的細節,幫助你快速打通金流。
小程序支付的官方文件入口(嵌在小程序 API 中):https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_3&index=1
小程序支付三大步驟
1. 預支付
2. 根據預支付資料加簽名,發起支付
3. 支付回呼
步驟一:預支付
前端先把需支付的信息(訂單號、金額等)提交給開發者伺服器,伺服器再轉送給微信,最後回傳前端真正要用來支付的資訊。開發者伺服器的預支付接口範例:
https://()htm?total_fee=100&cid=6001&orderCodes=2016120119 { "sign":"A2****************A6", "timestamp":"14****************68", "package":"Sign=WXPay", "partnerId":"14****************02", "appid":"wx****************ab", "nonceStr":"9f****************37", "prepayId":"wx****************54" }
步驟二:發起支付
要注意的是,發起支付時不需要上傳 appid,但簽名 paySign 需要用到 appid,而且必須放在第一個:
wx.requestPayment({ nonceStr: res.data.nonceStr, package: "prepay_id="+res.data.prepayId, signType: 'MD5', timeStamp: res.data.timestamp, paySign: sign,//<strong><span style="color:#ff0000;">五個字段參與簽名(區分大小寫):appId,nonceStr,package,signType,timeStamp(需要注意的是,這5個參數簽名排序的順序按照ASCII字典序排序)</span></strong> success: function(res){ console.log("支付成功"); }, fail: function() { }, complete: function() { } })
生成簽名 sign
簽名計算可參考官方文件:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_3&index=1&t=20161122
MD5 加密工具下載:https://code.csdn.net/snippets/2019875/master/download
var MD5Util = require('../../../utils/md5.js'); var sign = ''; //<strong><span style="color:#ff0000;">順序按照ASCII字典序排序</span></strong> var signA = "appId="+app.appId+"&nonceStr="+res.data.nonceStr+"&package=prepay_id="+res.data.prepayId+"&signType=MD5&timeStamp="+res.data.timestamp; var signB = signA+"&key="+app.key; sign = MD5Util.MD5(signB).toUpperCase();
官方文件對簽名流程有更詳細的描述。假設傳送參數如下:
appid: wxd930ea5d5a258f4f(需要注意的是appid 在wx.requestPayment({})發起支付是不上傳,但是簽名時需要) mch_id: 10000100 device_info: 1000 body: test nonce_str: ibuaiVcKdpRxkhJA
第一步:把參數整理成 key=value,並按參數名 ASCII 字典序排序:
stringA="appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_id=10000100&nonce_str=ibuaiVcKdpRxkhJA";
第二步:拼接 API 密鑰並計算簽名:
stringSignTemp="stringA&key=192006250b4c09247ec02edce69f6a2d" sign=MD5(stringSignTemp).toUpperCase()="9A0A8659F005D6984697E2CA0A9CF3B7"
此時的 sign 即作為 wx.requestPayment 上傳參數 paySign 使用。最終送出的資料如下:
<xml> <appid>wxd930ea5d5a258f4f</appid> <mch_id>10000100</mch_id> <device_info>1000<device_info> <body>test</body> <nonce_str>ibuaiVcKdpRxkhJA</nonce_str> <sign>9A0A8659F005D6984697E2CA0A9CF3B7</sign> <xml>
掌握「預支付、發起支付、支付回呼」這三個環節,並特別留意簽名時的 ASCII 字典序排序與 appid 的位置規則,微信小程序支付就能順利串接完成。