步驟一:調用後臺接口獲取appid,渠道appid後跳轉微信官方給定的特殊鏈接,並拼上appid及redirectUri,以下:前端
async getWeChatPayOpenId (code, state) { let response = await this.$http.wxOpenId(code, state)
if (response && response.data) { if (response.data.code === 1 && response.data.data) { let policyId = sessionStorage.getItem('pid') let channelId = sessionStorage.getItem('cid') let orderNo = this.$route.query.orderNo let bidProductNo = this.$route.query.bidProductNo // 0是普通充值 2是商品詳情頁充值 let payEntryUri = 0 if (orderNo) { payEntryUri = 2 } else { orderNo = '' } let params = { policyId: policyId, channelId: channelId, payEntryUri: payEntryUri, orderNo: orderNo, bidProductNo: bidProductNo, wxTradeType: 'JSAPI', openId: response.data.data.openid } this.rechargeUserCoins(params) // 支付接口 } else { this.$vux.toast.text(response.data.message || '數據獲取失敗', 'middle') } } }
步驟三:調起微信支付api
async rechargeUserCoins (params) { this.$vux.loading.show({ text: 'loading' }) let response = await this.$http.rechargeUserCoins(params).catch((err) => { this.$vux.toast.text(err.message, 'middle') }) this.$vux.loading.hide() if (response && response.data && response.data.code === 1) { // 判斷支付類型 if (response.data.data.channelId === 'wx') { // 微信支付 if (response.data.data.appId) { // JSAPI方式 let opthions = { appId: response.data.data.appId, timeStamp: response.data.data.timeStamp, nonceStr: response.data.data.nonceStr, package: response.data.data.packageJson, signType: response.data.data.signType, paySign: response.data.data.paySign, Url: response.data.data.returnUrl } jsSDK(opthions) } } else { this.$vux.toast.text(response.data.message || '下單失敗,請重試', 'middle') } }
jsSDK是把微信官方的方法提出來從新定義的方法名,代碼以下:微信
export function jsSDK (params) { if (typeof window.WeixinJSBridge === 'undefined') { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', function () { onBridgeReady(params) }, false) } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', function () { onBridgeReady(params) }) document.attachEvent('onWeixinJSBridgeReady', function () { onBridgeReady(params) }) } } else { onBridgeReady(params) } } function onBridgeReady (params) { window.WeixinJSBridge.invoke( 'getBrandWCPayRequest', { 'appId': params.appId, // 公衆號名稱,由商戶傳入 'timeStamp': params.timeStamp, // 時間戳,自1970年以來的秒數 'nonceStr': params.nonceStr, // 隨機串 'package': params.package, 'signType': params.signType, // 微信簽名方式: 'paySign': params.paySign // 微信簽名 }, function (res) { location.href = params.Url } ) }
步驟四:微信支付成功後前端沒法準確獲取到訂單是否已建立完成,故支付完成後會跳轉到另外一個支付完成頁,而後調取後臺接口來判斷支付是否成功session