微信授权没搞过?

152 阅读2分钟

微信公众号号的网页授权vue的具体实现。

没搞过的同学可以先看看官方的文档https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

我在这里提供一个授权的可选方案,供大家参考,有不妥之处欢迎指正。

我这个项目有个需求,是可以在首页,个人中心页面等多个页面都要进行判断如果用户没有登录,那么就弹出微信授权页面,让用户点授权。所以我们本着能‘偷懒就偷懒原则’。封装一个公用组建在需要的页面引入即可。

在这里我封装了一个叫accredit.vue的组件。

在这里我们首先

  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATUS#wechat_redirect`;

这一行代码就是直接在h5页面上弹授权页面的代码。

回调地址是你在微信公众平台绑定好的。

(这里我多一嘴,我们有的同学是直接用微信公众测试平台https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login进行开发的,这里是需要登录微信开放平台https://open.weixin.qq.com/进行平台绑定公众号,注册时候需要企业的信息等,如果不绑定,单单只是用微信测试平台,接口返回的信息是没有UnionID的,别的信息都有的,如用户名字头像,openid等都有)

登录时候把code给后端换取access_token,和openid,再拿着openid和access_token去拿去用户信息。

上代码:

<template>
    <div></div>
</template>

<script>

import { getUrlParam } from "@/common/js/dom.js";
import {
    oauth2Access_token,
    wechatGettoken,
    wechatUserinfo
} from "@/http/httpUrl.js";
export default {
    name: "accredit",
    data() {
        return {
            access_token: "",
            openid: 0
        };
    },
    props: ["reUrl"],
    mounted() {
            let state = this.$route.query.state || getUrlParam("state");
            let userInfo = localStorage.getItem("userInfo");
            let _this = this;
            if (!code &&userInfo1 == undefined) {
            //用户没登录就弹出授权弹窗
                this.wxAccess();
            }
             if (code && userInfo == undefined) {
                wechatGettoken({
                    code: code
                }).then(res => {
                    console.log("登录后结果", res);
                    let role = res.data.role;
                    _this.access_token = res.data.token.access_token;
                    _this.openid = res.data.token.openid;
                    _this.getUserInfo();
                });
            }
       
    },
    methods: {
        wxLogin(appid, url) {
            let redirect_uri = encodeURIComponent(url);
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATUS#wechat_redirect`;
        },
        // 弹出微信登录
        wxAccess() {
            let reUrl = `http://baidu.com/${this.reUrl}`;
            //第一个参数是appID, 第二个是回调地址。
            this.wxLogin("wx0612345678a", reUrl);
        },
        //获取用户信息
        getUserInfo() {
            wechatUserinfo({
                access_token: this.access_token,
                openid: this.openid
            }).then(res => {
                console.log("获取微信用户信息", res);
                if(res.data.openid != undefined) {
                    localStorage.setItem("userInfo", encodeURI(JSON.stringify(res.data)));
                    //  _this.$store.commit('PERMISSION',encodeURIComponent(JSON.stringify(newObj)));
                }
                
            });
        }
    }
};
</script>

dom.js

  // 获取url上的参数
export const getUrlParam = (name) => {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;//构造一个含有目标参数的正则表达式对象
    let r = window.location.search.substr(1).match(reg);&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; //匹配目标参数
    if (r != null) return decodeURIComponent(r[2]); return null;&emsp;&emsp;&emsp;//返回参数值&emsp;
  }

在main.js中全局注册组件

// 引入公用微信登录组件
import Accredit from 'pages/login/accredit'
Vue.component('wxLogin', Accredit)

然后在需要的页面直接调用

   <!-- 引入微信登录 -->
        <wxLogin reUrl="my"/>

大功告成!!

另外有的页面比如详情页面是有参数的,怎么半呢,父子组件传参传过来后,

   wxAccess() {
            let reUrl = `http://baidu.com/${this.reUrl}`;
            //第一个参数是appID, 第二个是回调地址。
            this.wxLogin("wx0612345678a", reUrl);
        },
        在这里面回调地址reUrl中拼上即可啦。

好啦看到这里,可以加群啦,公众号不定期更新技术常用干货,一同成长啦。嘻嘻!

另有github每日更新,github.com/qdleader