vue实现微信公众号授权登录

Posted 乔Joe乔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue实现微信公众号授权登录相关的知识,希望对你有一定的参考价值。

用户在微信端中访问第三方网页,可以通过微信网页授权机制获取用户的基本信息,进而实现所需要的业务逻辑。

    1. 在网页授权域名中下载微信网页授权域名的配置文件

    2. 将下载好的配置文件上传至填写域名或路径指向的web服务器(或虚拟主机)的目录

    3. 后端进行相关业务代码编写

  1. 前端相关业务代码编写

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

    1. 第一   在router文件夹下的index.js中进行路由拦截

    2. 第三   截取url中的code传递给API,API拿着code向微信服务器请求,获取access_token和openod

    3. 第四    API端携带access_token再次请求微信服务器,获得用户头像和昵称。并将其存到数据库和缓存,返回token

    import Vue from 'vue'import Router from 'vue-router'import auther from '@/views/auth' // 授权页面Vue.use(Router)
    const router = new Router({/** 相关的路由路径 **/  routes:[{    path: '/auth',    name: 'auth',    component: auther  }]})router.beforeEach((to, from, next) => { let ua=navigator.userAgent.toLowerCase();  if(ua.match(/MicroMessenger/i) == "micromessenger"){    if (to.name != 'auth') { // 判断当前是否为授权页面          let userinfo = sessionStorage.getItem('userinfo'// 如果为数组需要JSON.parse()        if (!userinfo) { // 判断当前用户是否存在 这里也可以是token            // 保存当前路由地址,授权完成后跳转此地址 let redirect_uri = window.location.href.substring(0, window.location.href.lastIndexOf(".")-5) +'#/auth'            let appID = ''// 授权的appID              // 这里的url 是需要重定向回的链接地址,需要对重定向链接地址进行编码               // 编码是因为微信会把链接中的 # 进行锚点处理              // 重定向地址为授权页面            sessionStorage.setItem('beforeUrl', to.fullPath)                        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2be747a0c568377e&redirect_uri=${encodeURIComponent(redirect_uri)}&response_type=code&scope=snsapi_userinfo&state=STATE&#wechat_redirect`;        } else {         next() }     } else { next() }  } })


    第二步: 新建一个页面,页面命名为"auth",编写以下代码:

    <template><!-- 这里可以写一些加载的动画布局 --></template>
    <script>export default { name: "auth", data() { return { params: "" }; }, created() { this.params = this.getParmas(); this.wxlogin(); },  methods: {    getParmas() { let url = location.search; //获取url中"?"符后的字串 let theRequest = new Object(); if (url.indexOf("?") != -1) { let str = url.substr(1); let strs = str.split("&"); for (let i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]); } } return theRequest; },    wxlogin() {      let url = 'xxxxx'// 请求的接口地址   this.$ajax(        `https://url?code=${this.params.code}` // this.params.code 返回给后台的code  ).then(res => { if (res.data.status === 1) { sessionStorage.setItem("userinfo", JSON.stringify(res.data.data)); this.$router.push(sessionStorage.getItem("beforeUrl")) } }); } }};</script>


以上是关于vue实现微信公众号授权登录的主要内容,如果未能解决你的问题,请参考以下文章

微信公众号实现手机授权网页登录功能

微信公众号网页获取用户授权取得openid,和使用openid进行协助登录逻辑(Vue样例)

公众号微信第三方登录(静默授权和非静默授权)(具体代码:U盘 新浪云SAE)

微信公众号网页授权登录获取用户基本信息

快速实现微信公众号认证授权开发

个人网站可以申请微信授权登录吗?