vue项目中微信公众授权

router.js路由拦截

import Vue from 'vue'
import Router from 'vue-router'
import axios from "axios"
import store from "../store/store.js"


Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/index',
    },
    {
      path: "/index",
      name: 'Index',
      component: () => import('@/components/index'),
      meta: { keepAlive: true }
    },
  
  ]
})

// 解析url参数并获取code
function getUrlParam(name) {
  //name为要获取的参数名
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var rrr = decodeURIComponent(window.location.search);
  var r = rrr.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

// 路由变化时
router.beforeEach((to, from, next) => {
  console.log(to, from);
  // next()
  // 不需要登录的页面:noAuth:true,
  if (to.matched.some(recode => recode.meta.noAuth)) {
    next()
  } else {
    console.log(store.state.authToken)
    // store已存在用户信息直接进入页面
    if (store.state.authToken) {
      next()
      return
    }
    const code = getUrlParam("code") || ''; //获取url 上面的code 
    axios.get(process.env.API_URL + '/pub/wechat/wechatid?code=' + code).then(function (res) {   // 获取用户信息,后端可首先通过cookie,session等判断,没有信息则通过code获取
      console.log(res)
      // 返回用户信息
      if (res.data.code === 100) {
        store.commit('authToken', res.data.data.result.openid)
        store.commit('skbanstate', res.data.data.result.banstate)
        // 判断分享的重定向页面,有了返回分享页面,切删除重定向的页面信息
        var redirectPath = sessionStorage.getItem('redirectPath')
        if (redirectPath) {
          sessionStorage.setItem('redirectPath', '')
          next({ path: redirectPath })
        } else {
          next()
        }
      } else {
        // 上面的获取用户信息接口,如果cookie,session拿不到用户信息,且传递的code为空,则跳转到微信授权页面
        // 删除url中某个参数
        function funcUrlDel(name) {
          var loca = window.location;
          var baseUrl = loca.origin + loca.pathname + "?";
          console.log('loca.hash', loca)
          var query = decodeURIComponent(loca.search.split('?')[1]);
          if (!query) {
            return loca
          }
          if (loca.href.indexOf(name) > -1) {
            var obj = {}
            console.log('query', query)
            var arr = query.indexOf('&') > -1 ? query.split("&") : [query];
            for (var i = 0; i < arr.length; i++) {
              arr[i] = arr[i].split("=");
              obj[arr[i][0]] = arr[i][1];
            };
            delete obj[name];
            var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
            return url
          };
        }
        console.log(res.data.code)
        if (res.data.code === 104 || res.data.code === 101 || res.data.code === 400) {
          console.log(window.location.origin)
          console.log(to.fullPath)
          sessionStorage.setItem('redirectPath', to.fullPath)
          // 这个redirectUrl用 当前页路径或者tof.fullPath(将要进入的路径)
          // let redirectUrl = window.location.href
          // redirectUrl = encodeURIComponent(redirectUrl)
          let redirectURL = encodeURI(
            (
              "http://" +
              document.domain +
              window.location.pathname +
              window.location.search
            ).split("&code")[0]
          ); //获取地址
          console.log(redirectURL)
          if (redirectURL.indexOf('code=') != -1) {
            redirectURL = funcUrlDel('code')
          }
          console.log(redirectURL)
          // const appId = 'wx4340073402255596' //
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectURL}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
        }
      }
    })
  }
});
export default router;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值