vue项目接入微信公众号支付(JSAPI方式)
步骤一:调用后台接口获取appid,渠道appid后跳转微信官方给定的特殊连接,并拼上appid及redirectUri,如下:
let redirectURI = encodeURIComponent(URIString) // url需要encode
window.location = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + response.data.data.jsapiAppId + '&redirect_uri=' + redirectURI + '&response_type=code&scope=snsapi_base&state=WXPaySTATE#wechat_redirect'
步骤二:微信重定向到redirect_uri指定页面后,会在地址后添加参数code及state,前端取下这2个参数,调取后台接口获取openId
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') } } }
步骤三:调起微信支付
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 } ) }
步骤四:微信支付成功后前端无法准确获取到订单是否已创建完成,故支付完成后会跳转到另一个支付完成页,然后调取后台接口来判断支付是否成功
posted on 2018-05-02 15:22 zhoujian917 阅读(19436) 评论(0) 编辑 收藏 举报