1. index.html 引入企业微信js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
<script src="https://rescdn.qqmail.com/node/ww/wwopenmng/js/sso/wwLogin-1.0.0.js" type="text/javascript"></script>
</body>
</html>
2. login.vue
<template>
<div class="login-form-main">
<div id="wx-qrcode"></div>
</div>
</template>
<script lang="ts" setup>
import { onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
watch(
() => router.currentRoute.value.fullPath,
async () => {
if (route.query.code) {
try {
const code = decodeURIComponent(route.query.code as string);
// 直接调用自己登录接口(注意交互 加个loading 啥的)
// const res = await getUserInfo({ code: code });
router.push({ name: "home" });
} catch (err) {
// 自己的登录接口失败(可能过期啥的)直接重新进入登录页
console.log(err);
router.replace({
name: "login"
});
initCode();
}
}
}
);
onMounted(() => {
initCode();
});
//初始化企业微信
const initCode = () => {
WwLogin({
id: "wx-qrcode", // 登录页面显示二维码的容器id
appid: " ", // 企业微信的CorpID,在企业微信管理端查看
agentid: " ", // 授权方的网页应用id,在具体的网页应用中查看
redirect_uri: encodeURIComponent("http://test.com") // 重定向的地址,需要进行encode 也可以指定路由的 比如 http://test.com/#/login
});
};
</script>
<style scoped>
#wx-qrcode {
display: flex;
align-items: center;
justify-content: center;
}
.login-form-main {
position: relative;
}
</style>
本地测试
大家可能遇到redirect_uri必须填写正确的回调地址,才能正确的显示二维码。本地测试写代码啥的不太方便,可更改host文件。
假设企业微信中你的回调地址是 test.com
你前端本地启动的地址是 192.168.0.6 (注意必须80端口启动)
更改电脑host文件 加入 192.168.0.6 test.com
局域网内别人想访问的话 也更改他自己的host文件 192.168.0.6 test.com
这样直接访问 test.com 即刻和线上环境一样了。