在企业微信里面添加h5页面 进行登录授权

时间:2024-04-02 20:36:31

1.需求:在企业微信里面添加h5页面 进行登录授权,获取到用户的code,进行登入id的验证

2.步骤:

  • 根据企业微信开发者中心中构造网页授权链接进行授权

在这里插入图片描述

  • 在企业微信内部进行配置,拿到appid,redirect_uri,agentid参数步骤参考这篇文章

  • 由于企业微信进入页面之前会进行授权,然后再进行跳转咱们系统的首页(也是就redirect_uri中的地址),那么就会有两种解决方案:

    ① 有一个页面用于授权,然后在跳转首页
    ② 直接将授权的操作写在首页中,在首页进行授权,然后再跳转首页(我用的是这种方式)
    在这里插入图片描述
    首页进行授权的代码如下:

   //判断是否授权
  const CORPID = '    '; //appid参数
  const REDIRECT_URI = encodeURI(' ');  //redirect_uri参数
  const AGENTID =  '  '; //agentid 参数
  const searchParams = new URLSearchParams(window.location.search);

  const code = (route.query.code as string) || (searchParams.get('code') as string);
  const state = (route.query.state as string) || (searchParams.get('state') as string);
  const token = computed(() => userStore.getToken);
  
  //路由上没有code的情况下,进行企业微信授权
  if (!code) {
    const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${CORPID}&redirect_uri=${REDIRECT_URI}/index.html&response_type=code&scope=snsapi_base&state=1&agentid=${AGENTID}#wechat_redirect`;
    window.location.href = authUrl;
  }
  
 //存在code且不存在token的情况下走登录的接口
  if (code && (token.value == null || token.value == 'null')) { 
    userStore.resetUserStore();
    login({
      code: code,
      state: state,
    }).then((res) => {
      userStore.setToken(res.token);
    });
  }