前端web页面通过企微登录

背景:将前端h5页面放入企业微信应用或者从企业微信打开浏览器页面
前提:登录
怎么获取登录token 呢 通过获取获取地址栏的code去请求接口获取token
两种方案的区别是:
方案一在已经登录的情况下每次点击进入页面都需要去拿code
方案二则是当已经登录检测到code已经存在就不需要再去拿code 顾推荐方案二

方案一:在企业微信工作台配置应用并将需要打开的界面及redirecturl给后端配置 (前端也可以配置)即可在浏览器获取到token
方案二:前端页面写入代码

 const autoLogin = () => {
    const appId = 'ww1a2245553f8da44f'
    const redirectUrl = encodeURIComponent(
      `${window.location.origin}${window.location.pathname}${window.location.hash}`,
    )
    const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=#wechat_redirect`
    window.location.replace(url)
  }


  const getQuery = (key) => {
    let val = ''
    const url = window.location.toString()
    const re = new RegExp(`${key}=([^?&#/]*)`, 'i')
    if (re.test(url)) {
      val = url.match(re)[1].toString()
    }

    return val
  }
 if (code === '') {
      autoLogin()
    } else {
    //走登录流程
      const nextUrl = (route.query.next || '/') as string
       try {
        const d = await ApiLogin.wxLogin(code)
        userStore.token = d.data.accessToken
        await userStore.getUserInfo()
        await userStore.getRole()

        if (userStore.userInfo.user && userStore.userInfo.user.userId) {
          const hour = new Date().getHours()
          const thisTime =
            hour < 8
              ? '早上好'
              : hour <= 11
              ? '上午好'
              : hour <= 13
              ? '中午好'
              : hour < 18
              ? '下午好'
              : '晚上好'
          ElNotification({
            title: thisTime,
            message: `欢迎登录${import.meta.env.VITE_APP_TITLE}`,
            type: 'success',
            duration: 3000,
          })
          nextTick(() => {
            router.push(nextUrl)
          })
        } else {
          fullscreenLoading.value = false
          ElMessageBox.alert('没有权限', '系统提醒').then(() => {
            try {
              userStore.token = ''
              userStore.userInfo = {}
            } catch (e) {
              return e
            }
          })
        }
      } catch (ex: any) {
        console.log('fail', ex)
        router.push({
          path: '/error',
          query: {
            message: '登录失败!',
          },
        })
      }
      }

拓展:无论是哪一种登录方式 目的都是获取token 获取tokern的前提就是通过第三方唯一值去获取

前端单点登录是通过获取ticket去置换token及其用户信息

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值