近來用uniapp開發H5的時候,需要接入支付,原來都是基于后端框架來做的,所以可謂是一路坑中過,今天整理下大致流程分享給大家。
先封裝util.js,便于后面調用
const isWechat =function(){return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === 'micromessenger';
}
const wechatAppid = function() {return '你的appid';
}
const payed = function(data){WeixinJSBridge.invoke('getBrandWCPayRequest', data, function(respay) {if (respay.err_msg === "get_brand_wcpay_request:ok") {uni.showToast({title:'支付成功',icon:"none"})} else if (respay.err_msg === "get_brand_wcpay_request:cancel") {uni.showToast({title:"取消支付",icon:"none",duration:2000})} else if (respay.err_msg === "get_brand_wcpay_request:fail") {uni.showToast({title:"支付失敗",icon:"none",duration:2000})}}, function(err) {uni.showToast({title:err,icon:"none",duration:2000})})
}
/*** http請求* action 方法名* data 傳輸數據* Method 請求方式 GET POST*/
const Requests = function (action,data,Method='GET',event) {var headers = {'content-type': 'application/json' // 默認值}if (Method == 'POST') {headers = {'content-type': 'application/x-www-form-urlencoded' // 默認值}}uni.request({url: config.requestUrl + action,method:Method,header:headers,data: data,success(res) {if (res.data.status == 100) {return event(res.data);}else {uni.showToast({title: res.data.msg,icon:'none'})}},fail() {uni.showToast({title: '網絡異常',icon: 'none',duration: 2000})}})
}
export default {isWechat,wechatAppid,payed,Requests
}
在需要調用支付的頁面判斷環境跳轉獲取code
先在頁面加載util.js
import util from 'common/util.js'
再在onload里判斷獲取code
if(!options.code === false){this.code =options.code
}else{if(util.isWechat()){let appid = util.wechatAppid();let local = window.location.href;window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+encodeURIComponent(local)+'&response_type=code&scope=snsapi_base&state=1#wechat_redirect'return;}
}
最后再需要支付的地方進行調用
var that = this
//先創建訂單
util.Requests('order/createOrder',{id:that.id},'POST', function(eve) {var eves = eve.result//再從后臺獲取統一下單支付參數util.Requests('pay/pay',{order_id:eves,code:that.code},'POST', function(event) {util.payed(event.result)})
})
ok,至此,就結束了,喵~