/* -------------------- 配置 -------------------- */ const sPayMallUrl = "http://127.0.0.1:8092"; /* -------------------- 工具函数 -------------------- */ function setCookie(name, value, days) { const date = new Date(); date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`; } /* -------------------- 主逻辑 -------------------- */ document.addEventListener("DOMContentLoaded", () => { // 1) 先拿二维码 ticket fetch(`${sPayMallUrl}/api/v1/login/weixin_qrcode_ticket`) .then(res => res.json()) .then(data => { if (data.code !== "0000") { console.error("获取二维码 ticket 失败:", data.info); return; } const ticket = data.data; const qrCodeImg = document.getElementById("qr-code-img"); qrCodeImg.src = `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${ticket}`; qrCodeImg.classList.remove("pulse"); // 2) 轮询确认登录 const intervalId = setInterval(() => checkLoginStatus(ticket, intervalId), 3000); }) .catch(err => console.error("请求失败:", err)); }); /* -------------------- 轮询检查登录 -------------------- */ function checkLoginStatus(ticket, intervalId) { fetch(`${sPayMallUrl}/api/v1/login/check_login?ticket=${ticket}`) .then(res => res.json()) .then(data => { if (data.code === "0000") { // 登录成功,停轮询 clearInterval(intervalId); // 把 token 写入 cookie(30 天) setCookie("loginToken", data.data, 30); // 跳转首页 window.location.href = "./index.html"; } else { console.info("login wait"); } }) .catch(err => console.error("请求失败:", err)); }