我的思路大概是这样的
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>
如果有更好的解决方案或者有疑问清留言