uni-app 微信公众号H5支付技巧

1.封装wechat.js文件

```handlebars
export default {  
        //判断是否在微信中  
    isWechat:function(){  
        var ua = window.navigator.userAgent.toLowerCase();  
        if(ua.match(/micromessenger/i) == 'micromessenger'){  
            return true;  
        }else{  
            return false;  
        }  
    },
	pay:function(data,cb){
	   function onBridgeReady() {
	       WeixinJSBridge.invoke('getBrandWCPayRequest',data,
	       function(res) {
			   // alert(JSON.stringify(res))
			   cb(res)
	       })
	   }
	   if  (typeof WeixinJSBridge == "undefined") {
	       if ( document.addEventListener ) {
	           document.addEventListener('WeixinJSBridgeReady',  onBridgeReady,  false)
	       } else  if  (document.attachEvent) {
	           document.attachEvent('WeixinJSBridgeReady',  onBridgeReady);
	           document.attachEvent('onWeixinJSBridgeReady',  onBridgeReady)
	       }
	   } else {
	       onBridgeReady()
	   }
	},
}
> 2.在main.js中全局挂载wechat.js

```bash
// #ifdef H5  
import wechat from './common/wechat'  
if(wechat.isWechat()){  
    Vue.prototype.$wechat = wechat;  
}  
// #endif  

3.在需要支付的页面调用

getPayData(){
				var _this = this
				// 从后台获取统一下单参数
				_this.buyResume({id:_this.pageData.id}).then(data => {
					// 调用微信支付方法开始支付
					_this.$wechat.pay(data.jssdk,function(res){
						if (res.err_msg == 'get_brand_wcpay_request:ok') {
							// 支付成功
							_this.$helperFn.showToast('付款成功')
							_this.$refs.popup.open()
						}
					})
				}).catch(e => {
					_this.$helperFn.showToast('下单失败,请联系管理员')
				})
			},

猜你喜欢

转载自blog.csdn.net/qq_32837111/article/details/106718693