最近在開發一個微信的商城項目,給大家分享一下關於微信支付的相關的把,先說說商城開發的流程,商城不管是否用微信登錄,都應該可以瀏覽,一直到支付之前才會調用微信登錄。微信登錄可以參考我之前的一片博客,里面寫了純前端的微信登錄(特殊需求,正常應該走后台),
先說說完整的微信支付的流程把:
首先,應該調用后台的一個接口,達到創建訂單,接口要返回訂單號,訂單需要支付的金額。
第二步,調用后台的接口實現微信支付,返回微信jsapi所需要的appid,timestamp,noncestr,package,signtype,paysign
第三步調用微信jsapi喚起微信支付。回調函數來判斷支付成功、失敗、取消
第四步根據不同狀態進行不同操作,成功前往成功頁面,失敗和取消調用取消訂單,將支付中改為代付款
流程就是這樣,當然每個項目都要根據具體情況來實現,比如我們就是通過用戶的userId后台在數據庫檢索appid 分享一下我們的流程把
$.ajax({ type: "POST", url: "http://ip:port/order/create", crossDomain: true, data: JSON.stringify({ userCode: this.userId, shopCode: this.$route.query.shopId, distributionType: pstype, addressProvince: arr[0], addressCity: arr[1], addressBlock: arr[2], addressStreet: this.AddressObj.address, contactPhone: this.AddressObj.phone, contactName: this.AddressObj.name, isFreightInsurance: 0, expressAmount: 0, description: this.liuyan, orderCargoList: [ { cargoCode: this.$route.query.cargoId, cargoCount: this.num, presentPrice: 1, originalPrice: 1, cargoSpec: this.pug, cargoTitle: this.goodtitle, cargoPicture: this.checkimgUrl } ] }), contentType: "application/json", success: res => { let data = JSON.stringify({ userCode: this.userId, orderNumber: res.data.orderNumber, paymentAmount: res.data.paymentAmount, paymentMode: 2, paymentSource: "JSAPI", }); $.ajax({ type: "POST", url: "http://ip:port/order/payment",
crossDomain: true, data: data, contentType: "application/json", success: result => { console.log(result); WeixinJSBridge.invoke( "getBrandWCPayRequest", { appId: result.data.appId, timeStamp: result.data.timeStamp, nonceStr: result.data.nonceStr, package: result.data.package, signType: result.data.signType, paySign: result.data.paySign }, function(wxres) { alert(wxres.err_msg); if (wxres.err_msg == "get_brand_wcpay_request:ok") { // 支付成功 } else if (wxres.err_msg == "get_brand_wcpay_request:cancel") { // 支付取消 alert(JSON.stringify(wxres)); alert('已經取消 准備發送ajax'); alert(res.data.orderNumber); $.ajax({ url:"http://ip:port/order/payment/cancel",
type : "post", data:JSON.stringify({ paymentMode:2, orderNumber:res.data.orderNumber, message:"用戶取消支付", }), contentType: "application/json", success:res=>{ alert('ajax成功') this.tipText = "支付取消", this.tip = true; setTimeout(()=>{ this.tip = false; },1000); }, error:err=>{ alert('ajax失敗') console.log(err); } }) } else { alert('失敗') $.ajax({ url:"http://ip:port/order/payment/cancel",
data:JSON.stringify({ paymentMode:2, orderNumber:res.data.orderNumber, message:"用戶取消支付", }), type : "post", success:res=>{ this.tipText = "支付取消", this.tip = true; setTimeout(()=>{ this.tip = false; },1000); }, error:err=>{ console.log(err); } }) } } ); }, error: err => { alert('支付出現問題了') console.log(err); }, dataType: "json" }); }, error: err => { alert('創建訂單出現問題了'); console.log(err); }, dataType: "json" });
這個就是微信支付的流程,每一步都需要異步去操作,當然可以把ajax封裝好,直接調用即可。
ps:本文僅作為我們當前項目的需要,所傳參數不一定所有都是如此調用,重點看流程。