55 lines
1.9 KiB
TypeScript
55 lines
1.9 KiB
TypeScript
import QRCode, { QRCodeToDataURLOptions } from 'qrcode';
|
|
import { logginSuccess } from '../login-handle.ts';
|
|
import { query } from '../query.ts';
|
|
export const useCreateLoginQRCode = (el?: HTMLCanvasElement) => {
|
|
var opts: QRCodeToDataURLOptions = {
|
|
errorCorrectionLevel: 'H',
|
|
type: 'image/jpeg',
|
|
margin: 1,
|
|
width: 300,
|
|
};
|
|
let timer: any = null;
|
|
const createQrcode = async (state: string) => {
|
|
const url = new URL(window.location.href);
|
|
const loginUrl = new URL(url.pathname, url.origin);
|
|
loginUrl.searchParams.set('state', '1-' + state);
|
|
console.log('生成登录二维码链接:', loginUrl.toString());
|
|
var img = el || document.getElementById('qrcode')! as HTMLCanvasElement;
|
|
const res = await QRCode.toDataURL(img!, loginUrl.toString(), opts);
|
|
};
|
|
const checkLogin = async (state: string) => {
|
|
const res = await fetch(`/api/router?path=wx&key=checkLogin&state=${state}`).then((res) => res.json());
|
|
if (res.code === 200) {
|
|
console.log(res);
|
|
const token = res.data;
|
|
if (token) {
|
|
localStorage.setItem('token', token.accessToken);
|
|
await query.setLoginToken(token);
|
|
}
|
|
clear();
|
|
logginSuccess();
|
|
} else {
|
|
timer = setTimeout(() => {
|
|
checkLogin(state);
|
|
console.log('继续检测登录状态');
|
|
}, 2000);
|
|
}
|
|
};
|
|
// 随机生成一个state
|
|
const state = Math.random().toString(36).substring(2, 15);
|
|
createQrcode(state);
|
|
checkLogin(state);
|
|
const timer2 = setInterval(() => {
|
|
const state = Math.random().toString(36).substring(2, 15);
|
|
clearTimeout(timer); // 清除定时器
|
|
createQrcode(state); // 90秒后更新二维码
|
|
checkLogin(state);
|
|
console.log('更新二维码');
|
|
}, 90000);
|
|
const clear = () => {
|
|
clearTimeout(timer);
|
|
clearInterval(timer2);
|
|
console.log('停止检测登录状态');
|
|
}
|
|
return { createQrcode, clear };
|
|
}; |