update
This commit is contained in:
57
src/modules/wx-mp/qr.ts
Normal file
57
src/modules/wx-mp/qr.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import QRCode, { QRCodeToDataURLOptions } from 'qrcode';
|
||||
import { redirectHome } 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();
|
||||
setTimeout(() => {
|
||||
redirectHome();
|
||||
}, 1000);
|
||||
} 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 };
|
||||
};
|
||||
Reference in New Issue
Block a user