import request from '@/utils/request' // 微信支付(未调用后台接口) export function wxPay(url, param, methodType, successCallBack, failCallBack) { if (!isWechat()) return const promise = initiateRequest(url, param, methodType) if (promise) { promise.then(res => { if (res) { initAndInvokeWxJSBridge(res, successCallBack, failCallBack) } }) } } // 微信支付(已调用后台接口,paySign为后台接口返回数据) export function wxPayByPaySign(paySign, successCallBack, failCallBack) { if (!isWechat()) return if (paySign) { initAndInvokeWxJSBridge(paySign, successCallBack, failCallBack) } } function invokeWxPay(resData, successCallBack, failCallBack) { WeixinJSBridge.invoke('getBrandWCPayRequest', resData, res => { const msg = res.err_msg ? res.err_msg : res.errMsg; switch (msg) { case 'get_brand_wcpay_request:ok': if(successCallBack) { successCallBack(res) } break default: WeixinJSBridge.log('支付失败!'+msg+',请返回重试.'); if(failCallBack){ failCallBack(res) } break } }) } function initAndInvokeWxJSBridge(resData, successCallBack, failCallBack) { if (typeof WeixinJSBridge === 'undefined') { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', invokeWxPay(resData, successCallBack, failCallBack), false) } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', invokeWxPay(resData, successCallBack, failCallBack)) document.attachEvent('onWeixinJSBridgeReady', invokeWxPay(resData, successCallBack, failCallBack)) } } else { invokeWxPay(resData, successCallBack, failCallBack) } } function isWechat() { const ua = window.navigator.userAgent.toLowerCase(); return ua.match(/micromessenger/i) == 'micromessenger' } function initiateRequest(url, param, methodType) { if (methodType && url) { const t = methodType.toLowerCase() switch (t) { case 'post': return request.post({ url: url, params: param }) case 'get': return request.get({ url: url, params: param }) case 'put': return request.put({ url: url, params: param, header: { "content-type": "application/x-www-form-urlencoded" } }) default : return request.post({ url: url, params: param }) } } return null }