本篇文章主要是記錄本人在微信掃碼支付過程中所遇到的問題,給大家一個借鑒作用,希望對你們有幫助
微信公眾號-appid
微信商戶號-mch_id
key值(簽名算法所需,其實就是一個32位的密碼,可以用md5生成一個)(key設置路徑:微信商戶平臺(pay.weixin.qq.com)-->賬戶設置-->API安全-->密鑰設置)
掃碼支付-統一下單
以下才用的是微信模式二,因為比較簡單
let MD5 = require('md5'), xml2js = require('xml2js'), url = "https://api.mch.weixin.qq.com/pay/unifiedorder",// 下單請求地址 appid = '公眾號id', mch_id = '微信商戶號'; notify_url = '回調地址', out_trade_no = '自己設置的訂單號',// 微信會有自己訂單號、我們自己的系統需要設置自己的訂單號 total_fee = '訂單金額',// 注意,單位為分 body = '商品簡單描述', trade_type = 'NATIVE',// 交易類型,JSAPI--公眾號支付、NATIVE--原生掃碼支付、APP--app支付 nonce_str = moment().format('YYYYMMDDHHmmssSSS'),// 隨機字符串32位以下 stringA = `appid=${公眾號id}&body=${body}&mch_id=${微信商戶號}&nonce_str=${nonce_str}¬ify_url=${ notify_url}&out_trade_no=${out_trade_no}&spbill_create_ip=${ctx.request.ip}&total_fee=${total_fee}&trade_type=${trade_type}`, stringSignTemp = stringA + "&key=xxxxxxxxxxxxxxxxx", //注:key為商戶平臺設置的密鑰key sign = MD5(stringSignTemp).toUpperCase(); //注:MD5簽名方式 以上就是我們所需要的一些參數
簽名生成算法見微信官方:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=4_3
spbill_create_ip 是 終端ip地址
下面把所有的參數拼接成xml
const formData = "<xml>"; formData += "<appid>" + appid + "</appid>"; //appid formData += "<body>" + body + "</body>"; //商品或支付單簡要描述 formData += "<mch_id>" + mch_id + "</mch_id>"; //商戶號 formData += "<nonce_str>" + nonce_str + "</nonce_str>"; //隨機字符串,不長于32位 formData += "<notify_url>" + notify_url + "</notify_url>"; //支付成功后微信服務器通過POST請求通知這個地址 formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>"; //訂單號 formData += "<total_fee>" + total_fee + "</total_fee>"; //金額 formData += "<spbill_create_ip>" + ctx.request.ip + "</spbill_create_ip>"; //ip formData += "<trade_type>NATIVE</trade_type>"; //NATIVE會返回code_url ,JSAPI不會返回 formData += "<sign>" + sign + "</sign>"; formData += "</xml>"; // 這里使用了egg里面請求的方式 const resultData = yield ctx.curl(url, { method: 'POST', content: formData, headers: { 'content-type': 'text/html', }, }); // xml轉json格式 xml2js.parseString(resultData.data, function (err, json) { if (err) { new Error("解析xml報錯") } else { var result = formMessage(json.xml); // 轉換成正常的json 數據 console.log(result) //打印出返回的結果 } }) var formMessage = function (result) { var message = {}; if (typeof result === 'object') { var keys = Object.keys(result); for (var i = 0; i < keys.length; i++) { var item = result[keys[i]]; var key = keys[i]; if (!(item instanceof Array) || item.length === 0) { continue; } if (item.length === 1) { var val = item[0]; if (typeof val === 'object') { message[key] = formMessage(val); } else { message[key] = (val || '').trim(); } } else { message[key] = []; for (var j = 0, k = item.length; j < k; j++) { message[key].push(formMessage(itemp[j])); } } } } return message; }
新聞熱點
疑難解答