vue h5 公众号支付

67 篇文章 7 订阅

由于微信浏览器的限制无法从微信浏览器调起微信支付,需要对接公众号的支付

后端的小伙伴需要做一些微信公众号的配置(商户目录 、域名) 以及 微信商户平台的配置

前端主要的是通过 code 获取 openid 来调起后端的接口拿到支付的参数 来对接微信的sdk的方法

首先通过链接  微信官方平台的链接来获取 code 微信开放文档

https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect

redirect_uri 是要跳转拿到code地址的链接  由于本项目没有特别适合的地方来获取code  所以在首页进行获取

一、获取code

created(){
 var ua = navigator.userAgent.toLowerCase();
     if (ua.match(/MicroMessenger/i) == 'micromessenger') {
     if(this.$store.state.user.smallOpenid) {

     }  else if(!this.$route.query.code){
       this.toWxPay()
     }else  {
       this.$store.dispatch('user/getOpenId',window.location.href.split('?')[1].split('&')[0].split('=')[1])
     }

      } else {
        // this.isweChat = '浏览器'
      console.log('浏览器打开的');

      }
methods: {
    toWxPay(){
          window.location.href=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa9f996fcd50636d4&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
    },
}

首先判断是否在微信浏览器环境下,如果是 再去判断 是否存在了vuex里  若路由没有code 进行获取code  如果路由有code 调取vuex 把数据保存起来 做一个持久化存储起来

import { getOpenId } from '@/api/home'
export default ({
  namespaced: true,
  state: {
    smallOpenid: ''
  },
  mutations: {
    // 获取用户信息
    editOpenId (state, newOpen) {
      state.smallOpenid = newOpen
    }
  },
  actions: {
    async getOpenId (context, code) {
      try {
        const res = await getOpenId(code)
        console.log('getOpenId', res)
        context.commit('editOpenId', res.data.openid)
        // 保存数据
      } catch (err) {
        console.log('getOpenId', err)
      }
    }
  },
  modules: {}
})

二、支付

安装微信的sdk  概述 | 微信开放文档

npm install jweixin-module --save
var wx = require('jweixin-module')

最严谨的话还是在当前要支付页面判断一下是什么环境 

   var ua = navigator.userAgent.toLowerCase()
    // eslint-disable-next-line eqeqeq
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      this.isweChat = '微信'
      console.log('微信打开的')
    } else {
      this.isweChat = '浏览器'
      console.log('浏览器打开的')
    }

 如果是微信的话需要先通过config进行注册 在进行支付

if (this.isweChat === '微信') {
            console.log('走到支付了')
            wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
              appId: res.data.pay.appId, // 必填,公众号的唯一标识
              timestamp: res.data.pay.timeStamp, // 必填,生成签名的时间戳
              nonceStr: res.data.pay.nonceStr, // 必填,生成签名的随机串
              signature: res.data.pay.paySign, // 必填,签名
              jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表
            })
            wx.ready(function () {
              wx.chooseWXPay({
                timestamp: res.data.pay.timeStamp, // 时间戳
                nonceStr: res.data.pay.nonceStr, // 随机数
                package: res.data.pay.package, //
                signType: res.data.pay.signType,
                paySign: res.data.pay.paySign, // 签名
                success: function () {
                  console.log('支付成功')
                  // alert('支付成功')
                  window.location.href = window.location.href + '&orderId=' + res.data.order_id
                },
                cancel: function () {
                  alert('支付取消')
                },
                fail: function () {
                  alert('支付失败')
                }
              })
            })

//微信充值 //支付接口测试 function balance(url, data) { uni.request({ url: cfg.originUrl + '/wx/mp/js_sig.do', data: { route: url }, method: 'GET', success: (res) => { jweixin.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来 appId: res.data.appId, // 必填,公众号的唯一标识 timestamp: res.data.timestamp, // 必填,生成签名的时间戳 nonceStr: res.data.nonceStr, // 必填,生成签名的随机串 signature: res.data.signature, // 必填,签名 jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表 }); jweixin.ready(function() { uni.request({ url: cfg.originUrl + '/wx/recharge/pay.do', method: 'POST', header: { 'Content-type': "application/x-www-form-urlencoded", }, data: JSON.stringify(data), success: function(res) { alert("下单成功"); alert(JSON.stringify(res)); alert(res.data.order_id); all.globalData.orderId = res.data.order_id; uni.setStorageSync('orderId', res.data.order_id); jweixin.chooseWXPay({ timestamp: res.data.payParams.timeStamp, // 支付签名时间戳 nonceStr: res.data.payParams.nonceStr, // 支付签名随机串 package: res.data.payParams.package, // 接口返回的prepay_id参数 signType: res.data.payParams.signType, // 签名方式 paySign: res.data.payParams.paySign, // 支付签名 success: function(e) { alert("支付成功"); alert(JSON.stringify(e)); // 支付成功后的回调函数 } }); } }) }); jweixin.error(function(res) { // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 console.log("验证失败!") }); } }) }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值