微信授权没搞过?

微信公众号号的网页授权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 + "=([^&]*)(&|$)");      //构造一个含有目标参数的正则表达式对象
    let r = window.location.search.substr(1).match(reg);        //匹配目标参数
    if (r != null) return decodeURIComponent(r[2]); return null;   //返回参数值 
  }
```


在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中拼上即可啦。
```

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


![](https://user-gold-cdn.xitu.io/2020/6/21/172d70b9f003f145?w=972&h=902&f=jpeg&s=102579)


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值