admin管理员组

文章数量:1558091

项目需求:微信公众号(服务号)访问网页,第一次登录后,再次访问默认自动登录,执行退出后,可重新手动登录。

具体实现如下:
  1. 微信公众号 - 设置 - 公众号设置 - 功能设置 - 配置网页授权域名,用于获取授权code

(以下是订阅号截图,服务号对应位置配置网页授权域名地址)

  1. 微信公众号 - 开发 - 开发者工具 - 绑定开发者微信号,用于调试
  2. 前端使用 appid 调用授权获取code,用code调用接口获取对应的openid实现自动登录
// 以下为具体实现代码
 async mounted () {
   // 判断是否包含code
   const href = window.location.href
   if (href.includes('mp-fe/?code')) { // url包括 mp-fe/?code 证明为从微信跳转回来的
     const url = href.substring(0, href.length - 2) // vue自动在末尾加了 #/ 符号,截取去掉
     const jingPosit = url.indexOf('mp-fe/') + 6 // 获取域名结束的位置
     const urlLeft = url.substring(0, jingPosit) // url左侧部分
     const urlRight = url.substring(jingPosit, url.length) // url右侧部分
     window.location.href = urlLeft + '#/' + urlRight // 拼接跳转
   } else {
     // 判断是否为微信环境
     const ua = navigator.userAgent.toLowerCase()
     if (ua.match(/MicroMessenger/i) == 'micromessenger') {
       // 第一次登录或退出登录,获取code
       if (!this.$route.query.code && !localStorage.OPEN_ID) {
         const appid = '对应appid'
         const redirectUrl = encodeURIComponent(window.location.href)
         const url = `https://open.weixin.qq/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=2020&connect_redirect=1#wechat_redirect`
         window.location.href = url
       // 使用code获取openid
       } else if (this.$route.query.code && !localStorage.OPEN_ID) {
         // 获取openid
         const userInfo = await getOpenId({ code: this.$route.query.code })
         if (userInfo.data.openId && userInfo.data.openId !== null) {
           localStorage.OPEN_ID = userInfo.data.openId
           localStorage.autoLogin = false
         }
         this.$router.push('/')
       // 处理自动登录
       } else if (localStorage.OPEN_ID) {
         if (localStorage.autoLogin === 'true') {
           const res = await chkLog({ openId: localStorage.OPEN_ID })
           if (res.data.data.success) {
             this.saveUserInfo(res.data.data)
             localStorage.setItem('userid', res.data.data.sessionid)
             localStorage.userId = res.data.data.userId
             this.$router.push('/home')
           }
         }
       }
     }
   }
 },

本文标签: 自动登录网页vue