vue-解決在微信內建瀏覽器中呼叫支付寶支付的問題
阿新 • • 發佈:2019-01-03
我的思路大概是這樣的
1. 驗證是否是在微信內建瀏覽器中呼叫支付寶
2.給支付頁面的url加上呼叫介面所需的引數(因為在微信裡是不能直接呼叫支付寶的需要呼叫外部瀏覽器)
3.在外部瀏覽器中完成支付跳轉頁面
第一步:
payment: 是選擇支付頁面,pay-mask是用於在微信內建瀏覽器中呼叫支付寶的中間頁
payment主要程式碼:
let ua = window.navigator.userAgent.toLowerCase()
ua.match(/MicroMessenger/i) == "micromessenger"
這兩句程式碼就是判斷使用者是否是用微信內建瀏覽器開啟的頁面
如果是的話我們就需要把呼叫支付介面所需要的介面引數傳給另一個頁面(你也可以就在當前頁做處理,我這樣做是因為我想加一個提示頁)
pay-mask程式碼如下:
<template> <div class="mask"> <!-- 提示在瀏覽器開啟彈框 --> <div class="pay-mask" v-show="isWeiXi"> </div> <div class="payform"></div> </div> </template> <script type="text/ecmascript-6"> /* 解決在微信瀏覽器中無法呼叫支付寶支付: 1.拿到從支付頁傳遞過來的引數重組成自己需要的資料 2.清除舊的快取資料(防止出現意外bug) 3.驗證是否是微信瀏覽器(不是就把拿到的key和token存進本地快取中,用於其他介面呼叫) 4.請求資料介面拿到支付寶的支付表單裝進頁面中完成支付 */ export default { name: 'payMask', data () { return { isWeiXi: true, theRequest: {} } }, methods: { // 獲取當前微信瀏覽器url地址引數 getUrlParams() { // 清除舊的快取資料 // window.localStorage.clear() let theRequest = new Object(); let url = location.href; //獲取url中"?"符後的字串 let strs = []; if (url.indexOf("?") != -1) { var str = url.substr(parseInt(url.indexOf("?")+1)); strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } this.theRequest = theRequest; }, // 監控微信瀏覽器 isWeiXin() { let ua = window.navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) != "micromessenger") { this.isWeiXi = false // 重新儲存新的token(在外部瀏覽器開啟支付完成後是沒有token這些資料的所以需要在瀏覽器一開啟的時候就去存一次資料) window.localStorage.setItem("channelId", this.theRequest.channelId); window.localStorage.setItem("userKey",JSON.stringify(this.theRequest.userKey)); window.localStorage.setItem("userToken",JSON.stringify(this.theRequest.userToken)); if(this.theRequest.memberTypeName){ // 呼叫支付寶支付 this.zfbPayBuy(this.theRequest) } else { this.zfbPayBuySocial(this.theRequest) } } else { this.isWeiXi = true } }, // 支付寶支付(會員) zfbPayBuy(data){ // 請求介面拿到介面返回的支付表單(介面直接返回的,我們直接裝進頁面就可以了) this.axios.payBuy(data).then(res => { if (res.status == 0) { let payHtml = document.querySelector(".payform"); payHtml.innerHTML = res.result; let paySub = payHtml.getElementsByTagName("input")[1]; paySub.click() } }) }, //支付寶支付(社保) zfbPayBuySocial(data) { this.axios.buySocial(data).then(res => { if (res.status == 0) { let payHtml = document.querySelector(".payform") payHtml.innerHTML = res.result let paySub = payHtml.getElementsByTagName("input")[1] paySub.click() } }) }, }, created() { // 拿去當前地址引數 this.getUrlParams() if(JSON.stringify(this.theRequest) != '{}'){ this.isWeiXin() } }, mounted(){ // 更新一下當前瀏覽器地址(防止在微信裡呼叫外部瀏覽器的時候出現意外bug) window.location.href = window.location.href } } </script> <style scoped lang="less"> .pay-mask { width: 100%; min-height: 100%; position:fixed; z-index: 99; background-color: rgba(0, 0, 0,.6); background-image: url('../../image/icon/confirm.png'); background-repeat: no-repeat; } </style>
如果有更好的解決方案或者有疑問清留言