vue脚手架,微信公众号授权(微信网页授权)

版权声明: https://blog.csdn.net/xiasohuai/article/details/84193195

如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。

首先我做了一个H5小项目,然后申请公众号,然后在【自定义菜单】中输入想填写的,公众号菜单名称,以及页面地址:

然后,我们在我们的前端页面写调用服务器接口,得到授权。当然这里,后端操作的多。前端只需要请求接口即可。

前端应该做什么呢?

首先,在我们的vue架子下,找到路由router文件夹下的index.js,写以下代码:

router.beforeEach(( to, from, next ) => {
  if (to.name != 'auth') {//判断当前是否是新建的auth路由空白页面
    let _token = sessionStorage.getItem('wechataccess_token');
    if (!_token) {//如果没有token,则让它授权
      //保存当前路由地址,授权后还会跳到此地址
      sessionStorage.setItem('beforeUrl', to.fullPath);
      //授权请求,并跳转http://m.water.ui-tech.cn/auth路由页面
      window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx777aaa1aaaaa7a77&redirect_uri=http%3A%2F%2Fm.water.ui-tech.cn%2Fauth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
    } else {
      next();
    }
  } else {
    next();
  }
});

然后,新建一个路由空白页面,我起的名字是auth(就是上面所说的:授权请求,并跳转http://m.water.ui-tech.cn/auth路由页面),在auth.js中写入以下代码:

created(){
    if (this.$route.query.code) {//如果连接中能拿到code说明此时access_token没有或者已过期,需要重新获取token
      let obj = {};
      var url = 'http://api......' + this.$route.query.code;
      this.$get(url).then(res => {
        if (res.data.retCode == 200) {
          //因为浏览器刷新vuex的值就初始化了,所以需要存到浏览器中
          sessionStorage.setItem('wechataccess_token', res.data.data.access_token);
          sessionStorage.setItem('wechatuser_userName', res.data.data.userName);
          sessionStorage.setItem('wechatuser_id', res.data.data.user_id);
          .........   
          let url = sessionStorage.getItem("beforeUrl");
          //跳转
          this.$router.push(url);
        } else {
          this.Toast(res.data.message);
        }
      })
    }
  },

具体请参考,微信公众号授权文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

猜你喜欢

转载自blog.csdn.net/xiasohuai/article/details/84193195