您的当前位置:首页>全部文章>文章详情

Vue history模式下实现微信授权登录

发表于:2022-02-22 16:04:09浏览:2128次TAG: #Vue #history模式 #微信授权登录

使用Vue开发的SPA项目H5版的微信站,需要在进行微信授权登录,项目使用的是history的路由模式。

History模式和Hash模式的区别

众所周知,VUE的SPA单页面项目中使用的vue-router路由有hash模式和history模式两种,其默认是hash模式。history模式与hash模式的区别主要有:

hash模式下地址栏的URL路径中会包含一个‘#’号字符,而history模式下地址栏的URL中没有‘#’号。相对来说,history模式比hash模式看起来要美观些。

访问路劲和URL参数位置、拼接先后顺序有所差异。history模式下路径紧接根域名,其后拼接URL地址所需的参数;hash模式下,根域名后紧接的是URL所需的参数,其次是‘#’拼接所访问的文件所在服务器的路径。
两种路由模式的地址跳转方式页有所差异。具体差异请访问 vue-router官方网站 进一步了解,并根据所需选择合适的路由模式。

开发思路


因为需要先进行微信授权,所以当用户打开网页时会优先进行用户授权信息校验,为了提升用户体验,避免用户明显感觉到微信授权时的页面跳转,所以在vue-router的全局权限中加以控制,即在路由生命周期钩子的router.beforeEach阶段进行拦截处理。
无论从打开的URL是哪一个路径下进行访问的,都会优先触发router.beforeEach生命周期钩子函数,在router.beforeEach中判断用户信息,依据是否存在用户信息来判断是否进行微信授权。然后将微信授权的信息存储在了sessionStorage中。

router.js文件代码:

router.beforeEach((to, from, next) => {
    // 微信授权页路径(空白页)
    if (to.path === "/wx_auth") {
        next();
        return;
    }
    // 校验微信授权时存储的微信授权信息
    let wxInfo = sessionStorage.getItem("微信授权信息_key");
    // 没有用户信息(即未进行微信授权)
    if (!wxInfo) {
        // 存储默认打开时访问的页面路径
        sessionStorage.setItem("wxRedirectUrl", to.path);
        // 处理URL地址栏所携带的参数
        let search = window.location.search;
        if (search.includes("params_key") && search.includes("&")) {
            search = search.split("&")[0];
        }
        // 微信授权获取用户信息指定的路径
        let redirect_uri = encodeURIComponent(`微信服务器域名/wx_auth${search}`);
        // 随机参数(可不传)
        let randomParams = '&state=123';
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo${randomParams}#wechat_redirect`;
        return;
    }
});

WeChatAuth.vue微信授权页代码:


created() {
    let code = this.getQueryString("code");
    if (code) {
        this.getToken(code);
    } else {
        this.$router.replace("/");
    }
},
methods: {
    // 获取地址栏参数
    getQueryString(n) {
        let r,
            reg = new RegExp("(^|&)" + n + "=([^&]*)(&|$)");
        r = window.location.search.substr(1).match(reg);
        return r ? decodeURI(r[2]) : null;
    },
    // 获取token
    getToken(code) {
        this.$axios
            .get("wxauth_api", { params: { code } })
            .then(res => {
                if (res.data.code == 1) {
                    let data = res.data.result_data;
                    // 校验获取到的用户信息是否为空(code只能用一次)
                    if (!flag) {
                        // 存储微信授权用户信息
                        sessionStorage.setItem("wxInfo", JSON.stringify(data));
                        // 获取初次访问的URL地址
                        let redirectUrl = sessionStorage.getItem("wxRedirectUrl");
                        // 重新打开指定页面
                        this.$router.replace(redirectUrl);
                    } else {
                        if (sessionStorage.getItem("wxInfo")) {
                            let redirectUrl = sessionStorage.getItem("wxRedirectUrl");
                            this.$router.replace(redirectUrl);
                        }
                    }
                } else {
                    console.log("用户授权失败:", res.data.message);
                }
            })
            .catch(err => { });
    }
}

PS:微信授权时有code,就进行微信授权操作,获取用户信息校验通过之后跳转指定路径。有code值但获取用户校验信息失败可能是由于刷新所造成的,此时也跳转到固定的访问页面。主要是防止回退时,页面停留在微信授权页没有反应,这样不利于提升用户体验。