效果
实现步骤
1、项目中document.ejs文件引入企微js链接
注意:技术栈是使用的react + antDesignPro,不同的技术栈有不同的入口文件(如vue在html文件引入)
<script src="https://wwcdn.weixin.qq.com/node/wework/wwopen/js/wwLogin-1.2.7.js"></script>
2、在登录页面放置二维码容器
<div id="ww_login"></div>
3、在登录页面生成二维码
注意:目前项目需求为进入页面就展示二维码,所以在React的useEffect中进行生成的,如果有其它交互可通过其它交互进行动态生成二维码
useEffect(() => {
new WwLogin({
id: 'ww_login',
appid: 'wwa2d9444d52111111',
agentid: '1000000',
redirect_uri: encodeURIComponent('http://oa.zzmjart.com/user/login'),
state: Date.now() + '1000000',
});
}, []);
4、扫码完成后监听路由,处理登录逻辑
注意:目前跟后端约定交互为扫完二维码后跳转项目登录页面,登录页面路由上会拼接code,前端监听路由query里面是否有code,如有code拿到code去调后端接口换取token,后端返回token后进行储存token/跳转页面
import { history } from 'umi';
useEffect(() => {
if (history?.location?.query?.code) {
qwLogin(history?.location?.query);
}
}, [history]);
const qwLogin = async (values) => {
try {
const msg = await cpLogin({ code: values.code });
if (msg.code === 200) {
message.success('登录成功!');
localStorage.setItem('token', msg.data.token);
const redirect = localStorage.getItem('redirect');
if (redirect) {
localStorage.setItem('redirect', '');
location.href = location.origin + decodeURIComponent(redirect);
} else {
location.pathname = '/';
}
return;
}
console.log(msg); // 如果失败去设置用户错误信息
} catch (error) {
message.error('登录失败,请重试!');
}
};
注:本人前端小白 ,如有不对的地方还请多多指教