wx-auth-sdk 1.2.1 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/wx-auth.js +87 -87
- package/dist/wx-auth.umd.js +4 -4
- package/package.json +1 -1
package/dist/wx-auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const c = {
|
|
2
2
|
observer: null,
|
|
3
3
|
healthCheckTimer: null,
|
|
4
4
|
isProtected: !1
|
|
@@ -8,40 +8,40 @@ const r = {
|
|
|
8
8
|
* @param config 配置选项
|
|
9
9
|
*/
|
|
10
10
|
enable(e) {
|
|
11
|
-
if (
|
|
11
|
+
if (c.isProtected || typeof window > "u") return;
|
|
12
12
|
const { modalId: t, getState: o } = e;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
if (
|
|
16
|
-
|
|
17
|
-
if (
|
|
18
|
-
const d =
|
|
13
|
+
c.observer = new MutationObserver((s) => {
|
|
14
|
+
s.forEach((i) => {
|
|
15
|
+
if (i.type === "childList")
|
|
16
|
+
i.removedNodes.forEach((a) => {
|
|
17
|
+
if (a.nodeType === Node.ELEMENT_NODE) {
|
|
18
|
+
const d = a;
|
|
19
19
|
(d.id === t || d.querySelector?.(`#${t}`)) && (console.warn(
|
|
20
20
|
"[WxAuth] 检测到弹窗被删除,正在自动恢复..."
|
|
21
21
|
), this.restore(e));
|
|
22
22
|
}
|
|
23
23
|
});
|
|
24
|
-
else if (
|
|
25
|
-
const
|
|
26
|
-
|
|
24
|
+
else if (i.type === "attributes") {
|
|
25
|
+
const a = i.target;
|
|
26
|
+
a.id === t && i.attributeName === "style" && a.style.display === "none" && o().isOpen && (console.warn(
|
|
27
27
|
"[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."
|
|
28
|
-
),
|
|
28
|
+
), a.style.display = "flex");
|
|
29
29
|
}
|
|
30
30
|
});
|
|
31
|
-
}),
|
|
31
|
+
}), c.observer.observe(document.body, {
|
|
32
32
|
childList: !0,
|
|
33
33
|
subtree: !0,
|
|
34
34
|
attributes: !0,
|
|
35
35
|
attributeFilter: ["style"]
|
|
36
|
-
}),
|
|
36
|
+
}), c.healthCheckTimer = window.setInterval(() => {
|
|
37
37
|
this.healthCheck(e);
|
|
38
|
-
}, 1e3),
|
|
38
|
+
}, 1e3), c.isProtected = !0, console.log("[WxAuth] 弹窗保护已启用");
|
|
39
39
|
},
|
|
40
40
|
/**
|
|
41
41
|
* 禁用弹窗保护
|
|
42
42
|
*/
|
|
43
43
|
disable() {
|
|
44
|
-
|
|
44
|
+
c.observer && (c.observer.disconnect(), c.observer = null), c.healthCheckTimer && (clearInterval(c.healthCheckTimer), c.healthCheckTimer = null), c.isProtected = !1, console.log("[WxAuth] 弹窗保护已禁用");
|
|
45
45
|
},
|
|
46
46
|
/**
|
|
47
47
|
* 健康检查(定时器调用)
|
|
@@ -50,28 +50,28 @@ const r = {
|
|
|
50
50
|
healthCheck(e) {
|
|
51
51
|
const { modalId: t, getState: o } = e;
|
|
52
52
|
if (!o().isOpen) return;
|
|
53
|
-
const
|
|
54
|
-
if (!
|
|
53
|
+
const s = document.getElementById(t);
|
|
54
|
+
if (!s) {
|
|
55
55
|
console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."), this.restore(e);
|
|
56
56
|
return;
|
|
57
57
|
}
|
|
58
|
-
|
|
58
|
+
s.style.display === "none" && (console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."), s.style.display = "flex");
|
|
59
59
|
},
|
|
60
60
|
/**
|
|
61
61
|
* 恢复弹窗
|
|
62
62
|
* @param config 配置选项
|
|
63
63
|
*/
|
|
64
64
|
restore(e) {
|
|
65
|
-
const { modalId: t, getState: o, onRestore:
|
|
65
|
+
const { modalId: t, getState: o, onRestore: s } = e;
|
|
66
66
|
if (!o().isOpen) return;
|
|
67
|
-
const
|
|
68
|
-
if (
|
|
69
|
-
|
|
67
|
+
const i = document.getElementById(t);
|
|
68
|
+
if (i) {
|
|
69
|
+
i.style.display = "flex";
|
|
70
70
|
return;
|
|
71
71
|
}
|
|
72
|
-
|
|
72
|
+
s();
|
|
73
73
|
}
|
|
74
|
-
},
|
|
74
|
+
}, w = {
|
|
75
75
|
apiBase: "https://wx-auth.shenzjd.com",
|
|
76
76
|
// 后端API地址(默认值)
|
|
77
77
|
siteId: "",
|
|
@@ -89,19 +89,19 @@ const r = {
|
|
|
89
89
|
qrcodeUrl: ""
|
|
90
90
|
// 二维码URL(可选,会自动获取)
|
|
91
91
|
};
|
|
92
|
-
let
|
|
92
|
+
let n = { ...w }, l = {
|
|
93
93
|
isOpen: !1,
|
|
94
94
|
resolveAuth: null,
|
|
95
95
|
currentStep: "qr"
|
|
96
96
|
};
|
|
97
|
-
const
|
|
97
|
+
const r = {
|
|
98
98
|
// 从 apiBase 自动推导根域名(用于跨子域名共享 Cookie)
|
|
99
99
|
// auth.shenzjd.com → .shenzjd.com
|
|
100
100
|
// parse.shenzjd.com → .shenzjd.com
|
|
101
101
|
// localhost / 127.0.0.1 / IP → 不设置 domain
|
|
102
102
|
getRootDomain() {
|
|
103
103
|
try {
|
|
104
|
-
const e = new URL(
|
|
104
|
+
const e = new URL(n.apiBase || window.location.origin).hostname;
|
|
105
105
|
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
106
106
|
return "";
|
|
107
107
|
const t = e.split(".");
|
|
@@ -119,13 +119,13 @@ const l = {
|
|
|
119
119
|
setCookie(e, t) {
|
|
120
120
|
const o = /* @__PURE__ */ new Date();
|
|
121
121
|
o.setTime(o.getTime() + 720 * 60 * 60 * 1e3);
|
|
122
|
-
const
|
|
123
|
-
document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${
|
|
122
|
+
const s = this.getRootDomain(), i = s ? `;domain=${s}` : "", d = window.location.protocol === "https:" ? ";Secure" : "";
|
|
123
|
+
document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${i}${d};SameSite=Strict`;
|
|
124
124
|
},
|
|
125
125
|
// 删除Cookie(匹配相同的 domain)
|
|
126
126
|
deleteCookie(e) {
|
|
127
127
|
const t = this.getRootDomain(), o = t ? `;domain=${t}` : "";
|
|
128
|
-
document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}`;
|
|
128
|
+
document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o};SameSite=Strict`;
|
|
129
129
|
},
|
|
130
130
|
// 发送请求
|
|
131
131
|
async request(e, t = {}) {
|
|
@@ -157,10 +157,10 @@ const l = {
|
|
|
157
157
|
// 创建弹窗
|
|
158
158
|
createModal() {
|
|
159
159
|
const e = document.createElement("div");
|
|
160
|
-
e.id = "wx-auth-modal", e.className = "wx-auth-modal",
|
|
161
|
-
const t =
|
|
160
|
+
e.id = "wx-auth-modal", e.className = "wx-auth-modal", n.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
|
|
161
|
+
const t = n.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';
|
|
162
162
|
return e.innerHTML = `
|
|
163
|
-
<div class="wx-auth-overlay" ${
|
|
163
|
+
<div class="wx-auth-overlay" ${n.required ? 'onclick="event.preventDefault()"' : ""}></div>
|
|
164
164
|
<div class="wx-auth-content">
|
|
165
165
|
<div class="wx-auth-header">
|
|
166
166
|
<div class="wx-auth-title">微信认证</div>
|
|
@@ -178,7 +178,7 @@ const l = {
|
|
|
178
178
|
<!-- 验证码输入区域 -->
|
|
179
179
|
<div>
|
|
180
180
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
181
|
-
${
|
|
181
|
+
${r.generateCodeInputs()}
|
|
182
182
|
</div>
|
|
183
183
|
|
|
184
184
|
<!-- 消息提示 -->
|
|
@@ -197,18 +197,18 @@ const l = {
|
|
|
197
197
|
setTimeout(() => {
|
|
198
198
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
199
199
|
e.length && e.forEach((t, o) => {
|
|
200
|
-
t.addEventListener("input", (
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
}), t.addEventListener("keydown", (
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
}), t.addEventListener("paste", (
|
|
207
|
-
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
e[d] && (e[d].value =
|
|
211
|
-
}),
|
|
200
|
+
t.addEventListener("input", (s) => {
|
|
201
|
+
const i = s.target.value.replace(/\D/g, "");
|
|
202
|
+
s.target.value = i, i && o < 5 && e[o + 1].focus(), o === 5 && i && setTimeout(() => h.verifyCode(), 300);
|
|
203
|
+
}), t.addEventListener("keydown", (s) => {
|
|
204
|
+
const i = s.target;
|
|
205
|
+
s.key === "Backspace" && !i.value && o > 0 ? e[o - 1].focus() : s.key === "ArrowLeft" && o > 0 ? (s.preventDefault(), e[o - 1].focus()) : s.key === "ArrowRight" && o < 5 && (s.preventDefault(), e[o + 1].focus());
|
|
206
|
+
}), t.addEventListener("paste", (s) => {
|
|
207
|
+
s.preventDefault();
|
|
208
|
+
const i = s.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
209
|
+
i && (i.split("").forEach((a, d) => {
|
|
210
|
+
e[d] && (e[d].value = a);
|
|
211
|
+
}), i.length === 6 && setTimeout(() => h.verifyCode(), 300));
|
|
212
212
|
});
|
|
213
213
|
});
|
|
214
214
|
}, 100);
|
|
@@ -216,13 +216,13 @@ const l = {
|
|
|
216
216
|
// 显示弹窗
|
|
217
217
|
show() {
|
|
218
218
|
let e = document.getElementById("wx-auth-modal");
|
|
219
|
-
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"),
|
|
219
|
+
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), n.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.style.display = "flex", l.isOpen = !0, f.enable({
|
|
220
220
|
modalId: "wx-auth-modal",
|
|
221
|
-
getState: () =>
|
|
221
|
+
getState: () => l,
|
|
222
222
|
onRestore: () => {
|
|
223
|
-
this.createModal(),
|
|
223
|
+
this.createModal(), n.qrcodeUrl && this.setQrCode(n.qrcodeUrl);
|
|
224
224
|
const t = document.querySelector(".wx-auth-wechat-name");
|
|
225
|
-
t &&
|
|
225
|
+
t && n.wechatName && (t.textContent = `"${n.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
|
|
226
226
|
const o = document.querySelector(".wx-auth-input");
|
|
227
227
|
o && o.focus();
|
|
228
228
|
}, 100);
|
|
@@ -232,7 +232,7 @@ const l = {
|
|
|
232
232
|
// 隐藏弹窗
|
|
233
233
|
hide() {
|
|
234
234
|
const e = document.getElementById("wx-auth-modal");
|
|
235
|
-
e && (e.style.display = "none",
|
|
235
|
+
e && (e.style.display = "none", l.isOpen = !1, f.disable());
|
|
236
236
|
},
|
|
237
237
|
// 设置二维码
|
|
238
238
|
setQrCode(e) {
|
|
@@ -260,70 +260,70 @@ const l = {
|
|
|
260
260
|
}, h = {
|
|
261
261
|
// 初始化
|
|
262
262
|
init(e = {}) {
|
|
263
|
-
if (
|
|
263
|
+
if (n = { ...w, ...e }, !n.apiBase && typeof window < "u" && (n.apiBase = window.location.origin), !n.apiBase) {
|
|
264
264
|
console.error("[WxAuth] apiBase is required");
|
|
265
265
|
return;
|
|
266
266
|
}
|
|
267
|
-
if (!
|
|
267
|
+
if (!n.siteId && typeof window < "u") {
|
|
268
268
|
const t = document.referrer;
|
|
269
269
|
if (t)
|
|
270
270
|
try {
|
|
271
271
|
const o = new URL(t);
|
|
272
|
-
|
|
272
|
+
n.siteId = o.hostname;
|
|
273
273
|
} catch {
|
|
274
274
|
}
|
|
275
|
-
!
|
|
275
|
+
!n.siteId && window.location.hostname && (n.siteId = window.location.hostname), n.siteId || (n.siteId = "default"), console.log("[WxAuth] 自动获取 siteId:", n.siteId);
|
|
276
276
|
}
|
|
277
|
-
console.log("[WxAuth] SDK initialized",
|
|
277
|
+
console.log("[WxAuth] SDK initialized", n), typeof window < "u" && this.autoCheck();
|
|
278
278
|
},
|
|
279
279
|
// 自动检测 Cookie 并验证(内部使用)
|
|
280
280
|
async autoCheck() {
|
|
281
|
-
const e =
|
|
282
|
-
if (!e)
|
|
281
|
+
const e = r.getCookie("wxauth-token"), t = r.getCookie("wxauth-openid");
|
|
282
|
+
if (!(e || t))
|
|
283
283
|
return this.showAuthModal(), !1;
|
|
284
|
-
const
|
|
284
|
+
const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
|
|
285
285
|
try {
|
|
286
|
-
const
|
|
287
|
-
`${
|
|
286
|
+
const a = await r.request(
|
|
287
|
+
`${n.apiBase}/api/auth/check?${i}${s}`
|
|
288
288
|
);
|
|
289
|
-
return
|
|
290
|
-
} catch (
|
|
291
|
-
return console.error("[WxAuth] 自动验证失败:",
|
|
289
|
+
return a.authenticated ? (console.log("[WxAuth] 自动认证成功(Cookie)"), a.token && (r.setCookie("wxauth-token", a.token), t && r.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (r.deleteCookie("wxauth-token"), t && r.deleteCookie("wxauth-openid"), this.showAuthModal(), !1);
|
|
290
|
+
} catch (a) {
|
|
291
|
+
return console.error("[WxAuth] 自动验证失败:", a), this.showAuthModal(), !1;
|
|
292
292
|
}
|
|
293
293
|
},
|
|
294
294
|
// 显示认证弹窗(内部使用)
|
|
295
295
|
async showAuthModal() {
|
|
296
296
|
u.show();
|
|
297
297
|
try {
|
|
298
|
-
const t =
|
|
299
|
-
`${
|
|
298
|
+
const t = n.siteId ? `?siteId=${encodeURIComponent(n.siteId)}` : "", o = await r.request(
|
|
299
|
+
`${n.apiBase}/api/sdk/config${t}`
|
|
300
300
|
);
|
|
301
|
-
o.wechatName && !
|
|
301
|
+
o.wechatName && !n.wechatName && (n.wechatName = o.wechatName), o.qrcodeUrl && !n.qrcodeUrl && (n.qrcodeUrl = o.qrcodeUrl);
|
|
302
302
|
} catch (t) {
|
|
303
303
|
console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
|
|
304
304
|
}
|
|
305
|
-
|
|
305
|
+
n.qrcodeUrl && u.setQrCode(n.qrcodeUrl);
|
|
306
306
|
const e = document.querySelector(".wx-auth-wechat-name");
|
|
307
|
-
e &&
|
|
307
|
+
e && n.wechatName && (e.textContent = `"${n.wechatName}"`), setTimeout(() => {
|
|
308
308
|
const t = document.querySelector(".wx-auth-input");
|
|
309
309
|
t && t.focus();
|
|
310
310
|
}, 100);
|
|
311
311
|
},
|
|
312
312
|
// 主入口:需要验证时调用
|
|
313
313
|
async requireAuth() {
|
|
314
|
-
const e =
|
|
315
|
-
if (e)
|
|
314
|
+
const e = r.getCookie("wxauth-token"), t = r.getCookie("wxauth-openid");
|
|
315
|
+
if (e || t)
|
|
316
316
|
try {
|
|
317
|
-
const
|
|
318
|
-
`${
|
|
317
|
+
const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`, a = await r.request(
|
|
318
|
+
`${n.apiBase}/api/auth/check?${i}${s}`
|
|
319
319
|
);
|
|
320
|
-
if (
|
|
321
|
-
return console.log("[WxAuth] 已认证(Cookie)"), this.onVerified(
|
|
322
|
-
} catch (
|
|
323
|
-
console.error("[WxAuth] Cookie check failed:",
|
|
320
|
+
if (a.authenticated)
|
|
321
|
+
return console.log("[WxAuth] 已认证(Cookie)"), a.token && (r.setCookie("wxauth-token", a.token), t && r.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0;
|
|
322
|
+
} catch (s) {
|
|
323
|
+
console.error("[WxAuth] Cookie check failed:", s);
|
|
324
324
|
}
|
|
325
|
-
return await this.showAuthModal(), new Promise((
|
|
326
|
-
|
|
325
|
+
return await this.showAuthModal(), new Promise((s) => {
|
|
326
|
+
l.resolveAuth = s;
|
|
327
327
|
});
|
|
328
328
|
},
|
|
329
329
|
// 验证验证码
|
|
@@ -338,11 +338,11 @@ const l = {
|
|
|
338
338
|
);
|
|
339
339
|
t && (t.disabled = !0, t.textContent = "验证中...");
|
|
340
340
|
try {
|
|
341
|
-
const o =
|
|
342
|
-
`${
|
|
341
|
+
const o = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", s = await r.request(
|
|
342
|
+
`${n.apiBase}/api/auth/check?authToken=${e}${o}`
|
|
343
343
|
);
|
|
344
|
-
|
|
345
|
-
this.close(), this.onVerified(
|
|
344
|
+
s.authenticated ? (s.token ? r.setCookie("wxauth-token", s.token) : s.user && s.user.openid && r.setCookie("wxauth-openid", s.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
|
|
345
|
+
this.close(), this.onVerified(s.user);
|
|
346
346
|
}, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
|
|
347
347
|
} catch {
|
|
348
348
|
u.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
|
|
@@ -350,15 +350,15 @@ const l = {
|
|
|
350
350
|
},
|
|
351
351
|
// 关闭弹窗
|
|
352
352
|
close() {
|
|
353
|
-
u.hide(),
|
|
353
|
+
u.hide(), l.resolveAuth && (l.resolveAuth(!1), l.resolveAuth = null), typeof n.onClose == "function" && n.onClose();
|
|
354
354
|
},
|
|
355
355
|
// 验证成功回调
|
|
356
356
|
onVerified(e) {
|
|
357
|
-
console.log("[WxAuth] 验证成功", e), typeof
|
|
357
|
+
console.log("[WxAuth] 验证成功", e), typeof n.onVerified == "function" && n.onVerified(e), l.resolveAuth && (l.resolveAuth(!0), l.resolveAuth = null);
|
|
358
358
|
},
|
|
359
359
|
// 错误回调
|
|
360
360
|
onError(e) {
|
|
361
|
-
console.error("[WxAuth] 错误", e), typeof
|
|
361
|
+
console.error("[WxAuth] 错误", e), typeof n.onError == "function" && n.onError(e);
|
|
362
362
|
}
|
|
363
363
|
};
|
|
364
364
|
typeof window < "u" && (window.WxAuth = h);
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(
|
|
1
|
+
(function(h,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(h=typeof globalThis<"u"?globalThis:h||self,p(h.WxAuthSDK={}))})(this,(function(h){"use strict";var p=document.createElement("style");p.textContent=`.wx-auth-modal{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,sans-serif}.wx-auth-overlay{position:absolute;width:100%;height:100%;background:#00000080;animation:wxAuthFadeIn .2s ease}.wx-auth-content{position:relative;width:350px;max-width:90vw;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 10px 40px #0003;animation:wxAuthSlideUp .3s ease}.wx-auth-header{background:#07c160;color:#fff;padding:16px 20px;display:flex;align-items:center;justify-content:space-between}.wx-auth-title{font-size:16px;font-weight:600;flex:1;text-align:center}.wx-auth-close{background:none;border:none;color:#fff;font-size:24px;cursor:pointer;width:30px;height:30px;line-height:1;padding:0;position:absolute;right:10px;top:50%;transform:translateY(-50%);opacity:.8}.wx-auth-close:hover{opacity:1}.wx-auth-body{padding:20px;text-align:center}.wx-auth-desc{font-size:15px;color:#333;margin-bottom:16px;font-weight:500}.wx-auth-hint{font-size:15px;color:#333;margin-top:12px;margin-bottom:16px;font-weight:500}.wx-auth-qrcode-container{width:180px;height:180px;margin:0 auto 8px;border:2px solid #07C160;border-radius:8px;overflow:hidden;background:#f5f5f5}.wx-auth-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-inputs{display:flex;gap:8px;justify-content:center;margin:20px 0}.wx-auth-input{width:42px;height:50px;font-size:20px;font-weight:600;text-align:center;border:2px solid #DCDCDC;border-radius:8px;outline:none;transition:all .2s;color:#333}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16033}.wx-auth-input:disabled{background:#f5f5f5;color:#999}.wx-auth-success-icon{font-size:48px;margin-bottom:8px}.wx-auth-success-text{font-size:16px;color:#07c160;font-weight:600}.wx-auth-message{font-size:13px;padding:8px 12px;border-radius:6px;margin:8px 0;line-height:1.4}.wx-auth-message-info{background:#e8f4ff;color:#06c;border:1px solid #B3D9FF}.wx-auth-message-success{background:#f0fdf4;color:#07c160;border:1px solid #07C160}.wx-auth-message-error{background:#fef2f2;color:#dc2626;border:1px solid #DC2626}.wx-auth-actions{display:flex;gap:10px;margin-top:16px}.wx-auth-btn{flex:1;padding:12px 16px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all .2s;outline:none}.wx-auth-btn:active{transform:scale(.98)}.wx-auth-btn:disabled{opacity:.5;cursor:not-allowed}.wx-auth-btn-primary{background:#07c160;color:#fff}.wx-auth-btn-primary:hover:not(:disabled){background:#06ad56}.wx-auth-btn-secondary{background:#f2f2f2;color:#333}.wx-auth-btn-secondary:hover:not(:disabled){background:#e5e5e5}@keyframes wxAuthFadeIn{0%{opacity:0}to{opacity:1}}@keyframes wxAuthSlideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.wx-auth-content{width:95vw;margin:20px}.wx-auth-qrcode-container{width:160px;height:160px}.wx-auth-inputs{gap:6px}.wx-auth-input{width:38px;height:46px;font-size:18px}}@media(prefers-color-scheme:dark){.wx-auth-content{background:#1a1a1a}.wx-auth-desc,.wx-auth-hint{color:#e5e5e5}}.wx-auth-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}.wx-auth-optional .wx-auth-desc:after{content:"(可点击右上角关闭)";display:block;font-size:12px;color:#999;margin-top:4px;font-weight:400}
|
|
2
|
+
/*$vite$:1*/`,document.head.appendChild(p);const d={observer:null,healthCheckTimer:null,isProtected:!1},x={enable(e){if(d.isProtected||typeof window>"u")return;const{modalId:t,getState:o}=e;d.observer=new MutationObserver(i=>{i.forEach(a=>{if(a.type==="childList")a.removedNodes.forEach(s=>{if(s.nodeType===Node.ELEMENT_NODE){const l=s;(l.id===t||l.querySelector?.(`#${t}`))&&(console.warn("[WxAuth] 检测到弹窗被删除,正在自动恢复..."),this.restore(e))}});else if(a.type==="attributes"){const s=a.target;s.id===t&&a.attributeName==="style"&&s.style.display==="none"&&o().isOpen&&(console.warn("[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."),s.style.display="flex")}})}),d.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}),d.healthCheckTimer=window.setInterval(()=>{this.healthCheck(e)},1e3),d.isProtected=!0,console.log("[WxAuth] 弹窗保护已启用")},disable(){d.observer&&(d.observer.disconnect(),d.observer=null),d.healthCheckTimer&&(clearInterval(d.healthCheckTimer),d.healthCheckTimer=null),d.isProtected=!1,console.log("[WxAuth] 弹窗保护已禁用")},healthCheck(e){const{modalId:t,getState:o}=e;if(!o().isOpen)return;const i=document.getElementById(t);if(!i){console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."),this.restore(e);return}i.style.display==="none"&&(console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."),i.style.display="flex")},restore(e){const{modalId:t,getState:o,onRestore:i}=e;if(!o().isOpen)return;const a=document.getElementById(t);if(a){a.style.display="flex";return}i()}},w={apiBase:"https://wx-auth.shenzjd.com",siteId:"",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:""};let n={...w},c={isOpen:!1,resolveAuth:null,currentStep:"qr"};const r={getRootDomain(){try{const e=new URL(n.apiBase||window.location.origin).hostname;if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+720*60*60*1e3);const i=this.getRootDomain(),a=i?`;domain=${i}`:"",l=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${a}${l};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o};SameSite=Strict`},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}catch(o){throw console.error("[WxAuth] Request error:",o),o}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},u={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",n.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=n.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
|
|
3
3
|
<div class="wx-auth-overlay" ${n.required?'onclick="event.preventDefault()"':""}></div>
|
|
4
4
|
<div class="wx-auth-content">
|
|
5
5
|
<div class="wx-auth-header">
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
<!-- 验证码输入区域 -->
|
|
19
19
|
<div>
|
|
20
20
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
21
|
-
${
|
|
21
|
+
${r.generateCodeInputs()}
|
|
22
22
|
</div>
|
|
23
23
|
|
|
24
24
|
<!-- 消息提示 -->
|
|
@@ -30,4 +30,4 @@
|
|
|
30
30
|
</div>
|
|
31
31
|
</div>
|
|
32
32
|
</div>
|
|
33
|
-
`,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",i=>{const a=i.target.value.replace(/\D/g,"");i.target.value=a,a&&o<5&&e[o+1].focus(),o===5&&a&&setTimeout(()=>f.verifyCode(),300)}),t.addEventListener("keydown",i=>{const a=i.target;i.key==="Backspace"&&!a.value&&o>0?e[o-1].focus():i.key==="ArrowLeft"&&o>0?(i.preventDefault(),e[o-1].focus()):i.key==="ArrowRight"&&o<5&&(i.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",i=>{i.preventDefault();const a=i.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);a&&(a.split("").forEach((
|
|
33
|
+
`,document.body.appendChild(e),this.bindInputEvents(),e},bindInputEvents(){setTimeout(()=>{const e=document.querySelectorAll(".wx-auth-input");e.length&&e.forEach((t,o)=>{t.addEventListener("input",i=>{const a=i.target.value.replace(/\D/g,"");i.target.value=a,a&&o<5&&e[o+1].focus(),o===5&&a&&setTimeout(()=>f.verifyCode(),300)}),t.addEventListener("keydown",i=>{const a=i.target;i.key==="Backspace"&&!a.value&&o>0?e[o-1].focus():i.key==="ArrowLeft"&&o>0?(i.preventDefault(),e[o-1].focus()):i.key==="ArrowRight"&&o<5&&(i.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",i=>{i.preventDefault();const a=i.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);a&&(a.split("").forEach((s,l)=>{e[l]&&(e[l].value=s)}),a.length===6&&setTimeout(()=>f.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),n.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.style.display="flex",c.isOpen=!0,x.enable({modalId:"wx-auth-modal",getState:()=>c,onRestore:()=>{this.createModal(),n.qrcodeUrl&&this.setQrCode(n.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&n.wechatName&&(t.textContent=`"${n.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const o=document.querySelector(".wx-auth-input");o&&o.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",c.isOpen=!1,x.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},showMessage(e,t="info"){const o=document.querySelector(".wx-auth-message");o&&(o.textContent=e,o.className=`wx-auth-message wx-auth-message-${t}`,o.style.display="block",setTimeout(()=>{o.textContent===e&&(o.style.display="none")},3e3))},getVerifyCode(){const e=document.querySelectorAll(".wx-auth-input");return e.length?Array.from(e).map(t=>t.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(t=>t.value=""),e[0]&&e[0].focus()}},f={init(e={}){if(n={...w,...e},!n.apiBase&&typeof window<"u"&&(n.apiBase=window.location.origin),!n.apiBase){console.error("[WxAuth] apiBase is required");return}if(!n.siteId&&typeof window<"u"){const t=document.referrer;if(t)try{const o=new URL(t);n.siteId=o.hostname}catch{}!n.siteId&&window.location.hostname&&(n.siteId=window.location.hostname),n.siteId||(n.siteId="default"),console.log("[WxAuth] 自动获取 siteId:",n.siteId)}console.log("[WxAuth] SDK initialized",n),typeof window<"u"&&this.autoCheck()},async autoCheck(){const e=r.getCookie("wxauth-token"),t=r.getCookie("wxauth-openid");if(!(e||t))return this.showAuthModal(),!1;const i=n.siteId?`&siteId=${encodeURIComponent(n.siteId)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const s=await r.request(`${n.apiBase}/api/auth/check?${a}${i}`);return s.authenticated?(console.log("[WxAuth] 自动认证成功(Cookie)"),s.token&&(r.setCookie("wxauth-token",s.token),t&&r.deleteCookie("wxauth-openid")),this.onVerified(s.user),!0):(r.deleteCookie("wxauth-token"),t&&r.deleteCookie("wxauth-openid"),this.showAuthModal(),!1)}catch(s){return console.error("[WxAuth] 自动验证失败:",s),this.showAuthModal(),!1}},async showAuthModal(){u.show();try{const t=n.siteId?`?siteId=${encodeURIComponent(n.siteId)}`:"",o=await r.request(`${n.apiBase}/api/sdk/config${t}`);o.wechatName&&!n.wechatName&&(n.wechatName=o.wechatName),o.qrcodeUrl&&!n.qrcodeUrl&&(n.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}n.qrcodeUrl&&u.setQrCode(n.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&n.wechatName&&(e.textContent=`"${n.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=r.getCookie("wxauth-token"),t=r.getCookie("wxauth-openid");if(e||t)try{const i=n.siteId?`&siteId=${encodeURIComponent(n.siteId)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`,s=await r.request(`${n.apiBase}/api/auth/check?${a}${i}`);if(s.authenticated)return console.log("[WxAuth] 已认证(Cookie)"),s.token&&(r.setCookie("wxauth-token",s.token),t&&r.deleteCookie("wxauth-openid")),this.onVerified(s.user),!0}catch(i){console.error("[WxAuth] Cookie check failed:",i)}return await this.showAuthModal(),new Promise(i=>{c.resolveAuth=i})},async verifyCode(){const e=u.getVerifyCode();if(!e||e.length!==6){u.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="验证中...");try{const o=n.siteId?`&siteId=${encodeURIComponent(n.siteId)}`:"",i=await r.request(`${n.apiBase}/api/auth/check?authToken=${e}${o}`);i.authenticated?(i.token?r.setCookie("wxauth-token",i.token):i.user&&i.user.openid&&r.setCookie("wxauth-openid",i.user.openid),t&&(t.textContent="✅ 成功",t.style.background="#07C160"),setTimeout(()=>{this.close(),this.onVerified(i.user)},500)):(u.showMessage("验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch{u.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(){u.hide(),c.resolveAuth&&(c.resolveAuth(!1),c.resolveAuth=null),typeof n.onClose=="function"&&n.onClose()},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof n.onVerified=="function"&&n.onVerified(e),c.resolveAuth&&(c.resolveAuth(!0),c.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof n.onError=="function"&&n.onError(e)}};typeof window<"u"&&(window.WxAuth=f),h.WxAuth=f,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
|