Vue项目开发微信支付的两种方式以及截取code的方法


注释:本文章切不可直接使用 只是给自己提个醒,逻辑全靠自己的逻辑
首先开发vue项目得先看懂微信公众号里面的文档,看懂了 才好去发挥 ↓
微信开发文档

其实刚开始开发觉得好麻烦,其实不然大部分核心操作还是在后端的那儿,不过后端那儿可以使用官方给的deme,里面改改就可以使用自己的逻辑了,其实前端并不需要做太多的操作,,,,,好了 废话不多讲 下面开始步骤

首先是微信获取授权

官方给的方法有两种授权方式,一种静默授权,另一种就是非静默授权(ps:我在说废话)
:这两种的含义就是一种有弹出框让用户自己来点击授权,另一种就是在不弹出授权框的情况下的到用户code,
详情见链接 授权步骤 这步特别重要 没有授权获取code你啥都不能做
1 第一步:用户同意授权,获取code
2 第二步:通过code换取网页授权access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
5 附:检验授权凭证(access_token)是否有效

废话不多说直接氪代码

 mounted() {
    this.getCode();
  },
  methods: {
    getCode() {
      // 非静默授权,第一次有弹框
      var that = this;
      // that.code = that.getUrlCode(); // 截取code 这是使用的原生截取 当时不清楚vue的路由可以截取不过这样截取相对于 vue路由的hash模式不友好 hash模式会在授权过后的地址里面加上#  别跟着我搞 要想严格点要不让你的后台配置好 要不就按照原生的方式来截取
      that.code = that.$route.query.code ;  //vue路由截取code  
      if(that.code != undefined){
         storage.setItem("code",that.code);
      }else{
        that.code = storage.getItem('code') //这儿是存code  会话存储 是我封装的 如果你想存起来可以用vuex
      }
      var modelUrl = encodeURIComponent(that.modelUrl)
      if(that.code == undefined){
        window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=微信公众号appid&redirect_uri=你的域名(这里域名需要解析)&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
      }
    },

这样进来过后就能拿到code了 至于你怎么存 怎么拿就是你自己的逻辑思维了
附上原生截取方法:

  UrlCode() {
      // 截取url中的code方法  这里的判断只是针对于我自己的项目 你要用只是借鉴  不懂就去百度
      var url = location.search;  //获取url
      var that = this;
      if (url.indexOf("?") != -1) {
        var m1 = url.substr(1);
        var b = m1.split("=")
        if(b.length==2){
          this.modelUrl = url
        }else{
          var m2 = storage.getItem('modelUrl')+"&"+m1
          var a = m2.split("&")
          this.code = a[2].split("=")[1];
        }
        
      }
      return this.code;
    },

获取到了code,接下来就要去用这个code去后台那儿换去微信需要的值了 就是一个请求 传你的这个code到后台

这里会用ajax传或者用axios来搞都一样 反正接口正确了 后台给你返回来的东西就是了 你在存起来

传到后台过后后台给你返回来的参数(接下来才是重点,支付)

后台需要哪些值呢官网都列出来了:
官网jsapi

	"appId":"wx2421b1c4370ec43b",     //公众号名称,由商户传入     
     "timeStamp":"1395712654",         //时间戳,自1970年以来的秒数     
     "nonceStr":"e61463f8efa94090b1f366cccfbbb444", //随机串     
     "package":"prepay_id=u802345jgfjsdfgsdg888",     
     "signType":"MD5",         //微信签名方式:     
     "paySign":"70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 

在给去后台的方法有两种

一种是官网原生的

function onBridgeReady(){
   WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
         "appId":"wx2421b1c4370ec43b",     //公众号名称,由商户传入     
         "timeStamp":"1395712654",         //时间戳,自1970年以来的秒数     
         "nonceStr":"e61463f8efa94090b1f366cccfbbb444", //随机串     
         "package":"prepay_id=u802345jgfjsdfgsdg888",     
         "signType":"MD5",         //微信签名方式:     
         "paySign":"70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
      },
      function(res){
      if(res.err_msg == "get_brand_wcpay_request:ok" ){
      // 使用以上方式判断前端返回,微信团队郑重提示:
            //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
      } 
   }); 
}
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();
}

还有一种方法就是 使用wx的wx-js-sdk

import wx from 'weixin-js-sdk'
import store from '@/store'

export default {
  /* 初始化wxjsdk各种接口 */
  init(apiList = [], url) {
    //需要使用的api列表
    return new Promise((resolve, reject) => {
      getSignature(store.state.page.initLink).then(res => {
        if (res.appId) {
          wx.config({
            // debug: true, 
            appId: res.appId,
            timestamp: res.timestamp, 
            nonceStr: res.nonceStr, 
            signature: res.signature,
            jsApiList: apiList
          })
          wx.ready(res => {
            // 微信SDK准备就绪后执行的回调。
            resolve(wx, res)
          })
        } else {
          reject(res)
        }
      })
    })
  }
}
//页面上使用
import wechatUtil from '@/utils/wechatUtil'
  wechatUtil
        .init([
          'updateAppMessageShareData',
          'onMenuShareAppMessage',
          'onMenuShareTimeline',
          'updateTimelineShareData'
        ])
        .then((wx, res) => {
         	// 这里写微信的接口
        })

反正就是把那几个值 放进去就ok了

最后附上我自己的代码 逻辑有点混乱 我自己看得懂就好了

mounted() {
    this.getCode();
  },
  methods: {
    getCode() {
      // 非静默授权,第一次有弹框
      var that = this;
      // that.code = that.getUrlCode(); // 截取code
      that.code = that.$route.query.code ;  //截取code
      if(that.code != undefined){
         storage.setItem("code",that.code);
      }else{
        that.code = storage.getItem('code')
      }
      if(that.code == undefined){
        window.location.href = "你配置的地址";
      }else{
        that.getCodeht()
      }
    },
    // getUrlCode() {
    //   // 截取url中的code方法
    //   var url = location.search;
    //   var that = this;
    //   if (url.indexOf("?") != -1) {
    //     var m1 = url.substr(1);
    //     var b = m1.split("=")
    //     if(b.length==2){
    //       this.modelUrl = url
    //     }else{
    //       var m2 = storage.getItem('modelUrl')+"&"+m1
    //       var a = m2.split("&")
    //       this.code = a[2].split("=")[1];
    //     } 
    //   }
    //   return this.code;
    // },
    getCodeht() {
      var that = this;
        var code = that.code;
        that.$axios
          .postUsercode({
            code
          })
          .then(res => {
            that.datas = res;
            storage.setItem('userInfo', res.userInfo); //会话存储用户信息
          });
      }
    },
    pay() {
      var that = this;
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            that.onBridgeReady,
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", that.onBridgeReady);
          document.attachEvent("onWeixinJSBridgeReady", that.onBridgeReady);
        }
      } else {
        this.onBridgeReady();
      }
    },
    onBridgeReady() {
      var that = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: that.datas.appId, //公众号名称,由商户传入
          timeStamp: that.datas.timeStamp, //时间戳,自1970年以来的秒数
          nonceStr: that.datas.nonceStr, //随机串
          package: that.datas.package,
          signType: that.datas.signType, //微信签名方式:
          paySign: that.datas.paySign //微信签名
        },
        function(res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            storage.clear("code");  //我自己的逻辑 成功过后需要把之前存进去的东西都卸载掉
            storage.clear('datai');
            storage.clear('userInfo');
            window.location.href = '/success.html'
            //支付成功后跳转的页面
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
           	//取消支付后的逻辑
          } else if (res.err_msg == "get_brand_wcpay_request:fail") {
            WeixinJSBridge.call("closeWindow");
          } //使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
        }
      );
    },
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值