wx-auth-sdk 1.2.11 → 1.2.12

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 CHANGED
@@ -1,4 +1,4 @@
1
- const i = {
1
+ const r = {
2
2
  observer: null,
3
3
  rafId: null,
4
4
  isProtected: !1,
@@ -8,54 +8,54 @@ const i = {
8
8
  * 启用弹窗保护
9
9
  */
10
10
  enable(e) {
11
- if (i.isProtected || typeof window > "u") return;
12
- i.observer && (i.observer.disconnect(), i.observer = null), i.rafId !== null && (cancelAnimationFrame(i.rafId), i.rafId = null), i.isProtected = !0, i.restorePending = !1, i.observer = new MutationObserver((o) => {
11
+ if (r.isProtected || typeof window > "u") return;
12
+ r.observer && (r.observer.disconnect(), r.observer = null), r.rafId !== null && (cancelAnimationFrame(r.rafId), r.rafId = null), r.isProtected = !0, r.restorePending = !1, r.observer = new MutationObserver((o) => {
13
13
  for (const n of o)
14
14
  if (n.type === "childList")
15
- for (const r of n.removedNodes) {
16
- if (r.nodeType !== Node.ELEMENT_NODE) continue;
17
- const a = r;
15
+ for (const i of n.removedNodes) {
16
+ if (i.nodeType !== Node.ELEMENT_NODE) continue;
17
+ const a = i;
18
18
  if (a.id === e.modalId || a.querySelector?.(`#${e.modalId}`)) {
19
19
  console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), h.safeRestore(e);
20
20
  return;
21
21
  }
22
22
  }
23
- }), i.observer.observe(document.body, {
23
+ }), r.observer.observe(document.body, {
24
24
  childList: !0,
25
25
  subtree: !0
26
26
  });
27
27
  const t = () => {
28
- if (!i.isProtected) return;
28
+ if (!r.isProtected) return;
29
29
  const { getState: o } = e;
30
30
  if (!o().isOpen) {
31
- i.rafId = null;
31
+ r.rafId = null;
32
32
  return;
33
33
  }
34
34
  const n = document.getElementById(e.modalId);
35
35
  (!n || !n.isConnected || h.isHidden(n)) && (console.warn(
36
36
  "[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
37
37
  { has: !!n, connected: n?.isConnected, hidden: n ? h.isHidden(n) : null }
38
- ), h.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
38
+ ), h.safeRestore(e)), r.isProtected && (r.rafId = requestAnimationFrame(t));
39
39
  };
40
- i.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
40
+ r.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
41
41
  },
42
42
  /**
43
43
  * 禁用弹窗保护
44
44
  */
45
45
  disable() {
46
- i.observer && (i.observer.disconnect(), i.observer = null), i.rafId !== null && (cancelAnimationFrame(i.rafId), i.rafId = null), i.isProtected = !1, i.restorePending = !1, console.log("[WxAuth] 弹窗保护已禁用");
46
+ r.observer && (r.observer.disconnect(), r.observer = null), r.rafId !== null && (cancelAnimationFrame(r.rafId), r.rafId = null), r.isProtected = !1, r.restorePending = !1, console.log("[WxAuth] 弹窗保护已禁用");
47
47
  },
48
48
  /**
49
49
  * 同一帧内避免重复恢复
50
50
  */
51
51
  safeRestore(e) {
52
- if (!i.restorePending) {
53
- i.restorePending = !0;
52
+ if (!r.restorePending) {
53
+ r.restorePending = !0;
54
54
  try {
55
55
  h.restoreFn(e);
56
56
  } finally {
57
57
  requestAnimationFrame(() => {
58
- i.restorePending = !1;
58
+ r.restorePending = !1;
59
59
  });
60
60
  }
61
61
  }
@@ -79,14 +79,14 @@ const i = {
79
79
  restoreFn(e) {
80
80
  const { modalId: t, getState: o, onRestore: n } = e;
81
81
  if (!o().isOpen) return;
82
- const r = document.getElementById(t);
83
- if (r) {
84
- r.style.display = "flex", r.style.visibility = "visible", r.style.opacity = "1";
82
+ const i = document.getElementById(t);
83
+ if (i) {
84
+ i.style.display = "flex", i.style.visibility = "visible", i.style.opacity = "1";
85
85
  return;
86
86
  }
87
87
  n();
88
88
  }
89
- }, m = {
89
+ }, p = {
90
90
  apiBase: "https://wx-auth.shenzjd.com",
91
91
  // 后端API地址(默认值)
92
92
  onVerified: null,
@@ -104,7 +104,7 @@ const i = {
104
104
  silent: !1
105
105
  // 默认不静默
106
106
  };
107
- let s = { ...m }, u = "", d = {
107
+ let s = { ...p }, l = "", u = {
108
108
  isOpen: !1,
109
109
  resolveAuth: null,
110
110
  currentStep: "qr"
@@ -134,14 +134,49 @@ const c = {
134
134
  setCookie(e, t) {
135
135
  const o = /* @__PURE__ */ new Date();
136
136
  o.setTime(o.getTime() + 365 * 24 * 60 * 60 * 1e3);
137
- const n = this.getRootDomain(), r = n ? `;domain=${n}` : "", f = window.location.protocol === "https:" ? ";Secure" : "";
138
- document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${r}${f};SameSite=Strict`;
137
+ const n = this.getRootDomain(), i = n ? `;domain=${n}` : "", f = window.location.protocol === "https:" ? ";Secure" : "";
138
+ document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${i}${f};SameSite=Strict`;
139
139
  },
140
140
  // 删除Cookie(匹配相同的 domain)
141
141
  deleteCookie(e) {
142
142
  const t = this.getRootDomain(), o = t ? `;domain=${t}` : "";
143
143
  document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o};SameSite=Strict`;
144
144
  },
145
+ // ===== 签名 Token 双存储(Cookie 主 + localStorage 备份) =====
146
+ // 目标:用户清除 Cookie 后,若服务端认证状态仍有效,可凭备份静默恢复。
147
+ // 存储的是签名 Token(HMAC,不可伪造),而非明文 openid(永久凭证),
148
+ // 与 Cookie 同策略(均非 HttpOnly),安全模型零降级。
149
+ // 注意:localStorage 按站点隔离(不跨子域),Cookie 是根域共享。
150
+ // localStorage 备份的 key(避免与接入方业务 key 冲突,加前缀)
151
+ get storageKey() {
152
+ return "wxauth-token";
153
+ },
154
+ // 读取:Cookie 优先(权威),localStorage 兜底(备份,用于恢复)
155
+ getToken() {
156
+ const e = this.getCookie("wxauth-token");
157
+ if (e) return e;
158
+ try {
159
+ return window.localStorage.getItem(this.storageKey);
160
+ } catch {
161
+ return null;
162
+ }
163
+ },
164
+ // 写入:Cookie + localStorage 双写(验证成功后调用,同步刷新备份)
165
+ setToken(e) {
166
+ this.setCookie("wxauth-token", e);
167
+ try {
168
+ window.localStorage.setItem(this.storageKey, e);
169
+ } catch {
170
+ }
171
+ },
172
+ // 删除:双删(同时清掉旧版明文 openid Cookie)
173
+ clearToken() {
174
+ this.deleteCookie("wxauth-token"), this.deleteCookie("wxauth-openid");
175
+ try {
176
+ window.localStorage.removeItem(this.storageKey);
177
+ } catch {
178
+ }
179
+ },
145
180
  // 发送请求
146
181
  async request(e, t = {}) {
147
182
  try {
@@ -168,7 +203,7 @@ const c = {
168
203
  e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
169
204
  return e += "</div>", e;
170
205
  }
171
- }, l = {
206
+ }, d = {
172
207
  // 创建弹窗
173
208
  createModal() {
174
209
  const e = document.createElement("div");
@@ -214,17 +249,17 @@ const c = {
214
249
  const e = document.querySelectorAll(".wx-auth-input");
215
250
  e.length && e.forEach((t, o) => {
216
251
  t.addEventListener("input", (n) => {
217
- const r = n.target.value.replace(/\D/g, "");
218
- n.target.value = r, r && o < 5 && e[o + 1].focus(), o === 5 && r && setTimeout(() => p.verifyCode(), 300);
252
+ const i = n.target.value.replace(/\D/g, "");
253
+ n.target.value = i, i && o < 5 && e[o + 1].focus(), o === 5 && i && setTimeout(() => m.verifyCode(), 300);
219
254
  }), t.addEventListener("keydown", (n) => {
220
- const r = n.target;
221
- n.key === "Backspace" && !r.value && o > 0 ? e[o - 1].focus() : n.key === "ArrowLeft" && o > 0 ? (n.preventDefault(), e[o - 1].focus()) : n.key === "ArrowRight" && o < 5 && (n.preventDefault(), e[o + 1].focus());
255
+ const i = n.target;
256
+ n.key === "Backspace" && !i.value && o > 0 ? e[o - 1].focus() : n.key === "ArrowLeft" && o > 0 ? (n.preventDefault(), e[o - 1].focus()) : n.key === "ArrowRight" && o < 5 && (n.preventDefault(), e[o + 1].focus());
222
257
  }), t.addEventListener("paste", (n) => {
223
258
  n.preventDefault();
224
- const r = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
225
- r && (r.split("").forEach((a, f) => {
259
+ const i = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
260
+ i && (i.split("").forEach((a, f) => {
226
261
  e[f] && (e[f].value = a);
227
- }), r.length === 6 && setTimeout(() => p.verifyCode(), 300));
262
+ }), i.length === 6 && setTimeout(() => m.verifyCode(), 300));
228
263
  });
229
264
  });
230
265
  }, 100);
@@ -232,9 +267,9 @@ const c = {
232
267
  // 显示弹窗
233
268
  show() {
234
269
  let e = document.getElementById("wx-auth-modal");
235
- e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.style.display = "flex", d.isOpen = !0, h.enable({
270
+ e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.style.display = "flex", u.isOpen = !0, h.enable({
236
271
  modalId: "wx-auth-modal",
237
- getState: () => d,
272
+ getState: () => u,
238
273
  onRestore: () => {
239
274
  this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
240
275
  const t = document.querySelector(".wx-auth-wechat-name");
@@ -248,7 +283,7 @@ const c = {
248
283
  // 隐藏弹窗
249
284
  hide() {
250
285
  const e = document.getElementById("wx-auth-modal");
251
- e && (e.style.display = "none", d.isOpen = !1, h.disable());
286
+ e && (e.style.display = "none", u.isOpen = !1, h.disable());
252
287
  },
253
288
  // 设置二维码
254
289
  setQrCode(e) {
@@ -273,10 +308,10 @@ const c = {
273
308
  const e = document.querySelectorAll(".wx-auth-input");
274
309
  e.forEach((t) => t.value = ""), e[0] && e[0].focus();
275
310
  }
276
- }, p = {
311
+ }, m = {
277
312
  // 初始化
278
313
  init(e = {}) {
279
- if (s = { ...m, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
314
+ if (s = { ...p, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
280
315
  console.error("[WxAuth] apiBase is required");
281
316
  return;
282
317
  }
@@ -284,10 +319,10 @@ const c = {
284
319
  const t = document.referrer;
285
320
  if (t)
286
321
  try {
287
- u = new URL(t).hostname;
322
+ l = new URL(t).hostname;
288
323
  } catch {
289
324
  }
290
- !u && window.location.hostname && (u = window.location.hostname), u || (u = "default"), console.log("[WxAuth] 自动获取 siteId:", u);
325
+ !l && window.location.hostname && (l = window.location.hostname), l || (l = "default"), console.log("[WxAuth] 自动获取 siteId:", l);
291
326
  }
292
327
  console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
293
328
  },
@@ -298,45 +333,45 @@ const c = {
298
333
  * - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
299
334
  */
300
335
  async silentCheck() {
301
- const e = c.getCookie("wxauth-token"), t = c.getCookie("wxauth-openid");
336
+ const e = c.getToken(), t = c.getCookie("wxauth-openid");
302
337
  if (!(e || t)) return !1;
303
- const n = u ? `&siteId=${encodeURIComponent(u)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
338
+ const n = l ? `&siteId=${encodeURIComponent(l)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
304
339
  try {
305
340
  const a = await c.request(
306
- `${s.apiBase}/api/auth/check?${r}${n}`
341
+ `${s.apiBase}/api/auth/check?${i}${n}`
307
342
  );
308
- return a.authenticated ? (a.token && (c.setCookie("wxauth-token", a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (c.deleteCookie("wxauth-token"), t && c.deleteCookie("wxauth-openid"), !1);
343
+ return a.authenticated ? (a.token && (c.setToken(a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (c.clearToken(), !1);
309
344
  } catch (a) {
310
345
  return console.error("[WxAuth] silentCheck 请求失败:", a), !1;
311
346
  }
312
347
  },
313
- // 自动检测 Cookie 并验证(内部使用)
348
+ // 自动检测凭证并验证(内部使用)
314
349
  async autoCheck() {
315
- const e = c.getCookie("wxauth-token"), t = c.getCookie("wxauth-openid");
350
+ const e = c.getToken(), t = c.getCookie("wxauth-openid");
316
351
  if (!(e || t))
317
352
  return this.showAuthModal(), !1;
318
- const n = u ? `&siteId=${encodeURIComponent(u)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
353
+ const n = l ? `&siteId=${encodeURIComponent(l)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
319
354
  try {
320
355
  const a = await c.request(
321
- `${s.apiBase}/api/auth/check?${r}${n}`
356
+ `${s.apiBase}/api/auth/check?${i}${n}`
322
357
  );
323
- return a.authenticated ? (console.log("[WxAuth] 自动认证成功(Cookie)"), a.token && (c.setCookie("wxauth-token", a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (c.deleteCookie("wxauth-token"), t && c.deleteCookie("wxauth-openid"), this.showAuthModal(), !1);
358
+ return a.authenticated ? (console.log("[WxAuth] 自动认证成功(凭证)"), a.token && (c.setToken(a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (c.clearToken(), this.showAuthModal(), !1);
324
359
  } catch (a) {
325
360
  return console.error("[WxAuth] 自动验证失败:", a), this.showAuthModal(), !1;
326
361
  }
327
362
  },
328
363
  // 显示认证弹窗(内部使用)
329
364
  async showAuthModal() {
330
- l.show();
365
+ d.show();
331
366
  try {
332
- const t = u ? `?siteId=${encodeURIComponent(u)}` : "", o = await c.request(
367
+ const t = l ? `?siteId=${encodeURIComponent(l)}` : "", o = await c.request(
333
368
  `${s.apiBase}/api/sdk/config${t}`
334
369
  );
335
370
  o.wechatName && !s.wechatName && (s.wechatName = o.wechatName), o.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = o.qrcodeUrl);
336
371
  } catch (t) {
337
372
  console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
338
373
  }
339
- s.qrcodeUrl && l.setQrCode(s.qrcodeUrl);
374
+ s.qrcodeUrl && d.setQrCode(s.qrcodeUrl);
340
375
  const e = document.querySelector(".wx-auth-wechat-name");
341
376
  e && s.wechatName && (e.textContent = `"${s.wechatName}"`), setTimeout(() => {
342
377
  const t = document.querySelector(".wx-auth-input");
@@ -345,26 +380,27 @@ const c = {
345
380
  },
346
381
  // 主入口:需要验证时调用
347
382
  async requireAuth() {
348
- const e = c.getCookie("wxauth-token"), t = c.getCookie("wxauth-openid");
383
+ const e = c.getToken(), t = c.getCookie("wxauth-openid");
349
384
  if (e || t)
350
385
  try {
351
- const n = u ? `&siteId=${encodeURIComponent(u)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`, a = await c.request(
352
- `${s.apiBase}/api/auth/check?${r}${n}`
386
+ const n = l ? `&siteId=${encodeURIComponent(l)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`, a = await c.request(
387
+ `${s.apiBase}/api/auth/check?${i}${n}`
353
388
  );
354
389
  if (a.authenticated)
355
- return console.log("[WxAuth] 已认证(Cookie)"), a.token && (c.setCookie("wxauth-token", a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0;
390
+ return console.log("[WxAuth] 已认证(凭证)"), a.token && (c.setToken(a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0;
391
+ c.clearToken();
356
392
  } catch (n) {
357
- console.error("[WxAuth] Cookie check failed:", n);
393
+ console.error("[WxAuth] 凭证检查失败:", n);
358
394
  }
359
395
  return await this.showAuthModal(), new Promise((n) => {
360
- d.resolveAuth = n;
396
+ u.resolveAuth = n;
361
397
  });
362
398
  },
363
399
  // 验证验证码
364
400
  async verifyCode() {
365
- const e = l.getVerifyCode();
401
+ const e = d.getVerifyCode();
366
402
  if (!e || e.length !== 6) {
367
- l.showMessage("请输入6位验证码", "error");
403
+ d.showMessage("请输入6位验证码", "error");
368
404
  return;
369
405
  }
370
406
  const t = document.querySelector(
@@ -372,32 +408,32 @@ const c = {
372
408
  );
373
409
  t && (t.disabled = !0, t.textContent = "验证中...");
374
410
  try {
375
- const o = u ? `&siteId=${encodeURIComponent(u)}` : "", n = await c.request(
411
+ const o = l ? `&siteId=${encodeURIComponent(l)}` : "", n = await c.request(
376
412
  `${s.apiBase}/api/auth/check?authToken=${e}${o}`
377
413
  );
378
- n.authenticated ? (n.token ? c.setCookie("wxauth-token", n.token) : n.user && n.user.openid && c.setCookie("wxauth-openid", n.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
414
+ n.authenticated ? (n.token ? c.setToken(n.token) : n.user && n.user.openid && c.setCookie("wxauth-openid", n.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
379
415
  this.onVerified(n.user), this.close(!0);
380
- }, 500)) : (l.showMessage("验证码错误或已过期", "error"), l.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
416
+ }, 500)) : (d.showMessage("验证码错误或已过期", "error"), d.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
381
417
  } catch {
382
- l.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
418
+ d.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
383
419
  }
384
420
  },
385
421
  // 关闭弹窗
386
422
  // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
387
423
  // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
388
424
  close(e = !1) {
389
- l.hide(), d.resolveAuth && (d.resolveAuth(!1), d.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
425
+ d.hide(), u.resolveAuth && (u.resolveAuth(!1), u.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
390
426
  },
391
427
  // 验证成功回调
392
428
  onVerified(e) {
393
- console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), d.resolveAuth && (d.resolveAuth(!0), d.resolveAuth = null);
429
+ console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), u.resolveAuth && (u.resolveAuth(!0), u.resolveAuth = null);
394
430
  },
395
431
  // 错误回调
396
432
  onError(e) {
397
433
  console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
398
434
  }
399
435
  };
400
- typeof window < "u" && (window.WxAuth = Object.freeze(p));
436
+ typeof window < "u" && (window.WxAuth = Object.freeze(m));
401
437
  export {
402
- p as WxAuth
438
+ m as WxAuth
403
439
  };
@@ -1,5 +1,5 @@
1
1
  (function(f,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(f=typeof globalThis<"u"?globalThis:f||self,p(f.WxAuthSDK={}))})(this,(function(f){"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:30px;padding:0;opacity:.85;flex-shrink:0}.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:4px;font-weight:500}.wx-auth-note{font-size:12px;color:#888;margin-bottom:14px;line-height:1.4;white-space:nowrap}.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-note{color:#aaa}}.wx-auth-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}
2
- /*$vite$:1*/`,document.head.appendChild(p);const a={observer:null,rafId:null,isProtected:!1,restorePending:!1},h={enable(e){if(a.isProtected||typeof window>"u")return;a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!0,a.restorePending=!1,a.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const r of n.removedNodes){if(r.nodeType!==Node.ELEMENT_NODE)continue;const d=r;if(d.id===e.modalId||d.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),h.safeRestore(e);return}}}),a.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!a.isProtected)return;const{getState:o}=e;if(!o().isOpen){a.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||h.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?h.isHidden(n):null}),h.safeRestore(e)),a.isProtected&&(a.rafId=requestAnimationFrame(t))};a.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){a.observer&&(a.observer.disconnect(),a.observer=null),a.rafId!==null&&(cancelAnimationFrame(a.rafId),a.rafId=null),a.isProtected=!1,a.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!a.restorePending){a.restorePending=!0;try{h.restoreFn(e)}finally{requestAnimationFrame(()=>{a.restorePending=!1})}}},isHidden(e){if(e.style.display==="none"||e.style.visibility==="hidden"||e.style.opacity==="0")return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||parseFloat(t.opacity)===0)return!0}catch{}return!1},restoreFn(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const r=document.getElementById(t);if(r){r.style.display="flex",r.style.visibility="visible",r.style.opacity="1";return}n()}},m={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let i={...m},c="",u={isOpen:!1,resolveAuth:null,currentStep:"qr"};const s={getRootDomain(){try{const e=new URL(i.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()+365*24*60*60*1e3);const n=this.getRootDomain(),r=n?`;domain=${n}`:"",w=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${r}${w};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}},l={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",i.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=i.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
2
+ /*$vite$:1*/`,document.head.appendChild(p);const r={observer:null,rafId:null,isProtected:!1,restorePending:!1},h={enable(e){if(r.isProtected||typeof window>"u")return;r.observer&&(r.observer.disconnect(),r.observer=null),r.rafId!==null&&(cancelAnimationFrame(r.rafId),r.rafId=null),r.isProtected=!0,r.restorePending=!1,r.observer=new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const a of n.removedNodes){if(a.nodeType!==Node.ELEMENT_NODE)continue;const s=a;if(s.id===e.modalId||s.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),h.safeRestore(e);return}}}),r.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!r.isProtected)return;const{getState:o}=e;if(!o().isOpen){r.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||h.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?h.isHidden(n):null}),h.safeRestore(e)),r.isProtected&&(r.rafId=requestAnimationFrame(t))};r.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){r.observer&&(r.observer.disconnect(),r.observer=null),r.rafId!==null&&(cancelAnimationFrame(r.rafId),r.rafId=null),r.isProtected=!1,r.restorePending=!1,console.log("[WxAuth] 弹窗保护已禁用")},safeRestore(e){if(!r.restorePending){r.restorePending=!0;try{h.restoreFn(e)}finally{requestAnimationFrame(()=>{r.restorePending=!1})}}},isHidden(e){if(e.style.display==="none"||e.style.visibility==="hidden"||e.style.opacity==="0")return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||parseFloat(t.opacity)===0)return!0}catch{}return!1},restoreFn(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const a=document.getElementById(t);if(a){a.style.display="flex",a.style.visibility="visible",a.style.opacity="1";return}n()}},m={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let i={...m},d="",u={isOpen:!1,resolveAuth:null,currentStep:"qr"};const c={getRootDomain(){try{const e=new URL(i.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()+365*24*60*60*1e3);const n=this.getRootDomain(),a=n?`;domain=${n}`:"",w=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${a}${w};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`},get storageKey(){return"wxauth-token"},getToken(){const e=this.getCookie("wxauth-token");if(e)return e;try{return window.localStorage.getItem(this.storageKey)}catch{return null}},setToken(e){this.setCookie("wxauth-token",e);try{window.localStorage.setItem(this.storageKey,e)}catch{}},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem(this.storageKey)}catch{}},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}},l={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",i.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=i.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
3
3
  <div class="wx-auth-overlay" ${i.required?'onclick="event.preventDefault()"':""}></div>
4
4
  <div class="wx-auth-content">
5
5
  <div class="wx-auth-header">
@@ -19,7 +19,7 @@
19
19
  <div>
20
20
  <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
21
21
  <div class="wx-auth-note">取消关注公众号后将被取消认证,请保持关注</div>
22
- ${s.generateCodeInputs()}
22
+ ${c.generateCodeInputs()}
23
23
  </div>
24
24
 
25
25
  <!-- 消息提示 -->
@@ -31,4 +31,4 @@
31
31
  </div>
32
32
  </div>
33
33
  </div>
34
- `,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",n=>{const r=n.target.value.replace(/\D/g,"");n.target.value=r,r&&o<5&&e[o+1].focus(),o===5&&r&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const r=n.target;n.key==="Backspace"&&!r.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const r=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);r&&(r.split("").forEach((d,w)=>{e[w]&&(e[w].value=d)}),r.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),i.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.style.display="flex",u.isOpen=!0,h.enable({modalId:"wx-auth-modal",getState:()=>u,onRestore:()=>{this.createModal(),i.qrcodeUrl&&this.setQrCode(i.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&i.wechatName&&(t.textContent=`"${i.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",u.isOpen=!1,h.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()}},x={init(e={}){if(i={...m,...e},!i.apiBase&&typeof window<"u"&&(i.apiBase=window.location.origin),!i.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{c=new URL(t).hostname}catch{}!c&&window.location.hostname&&(c=window.location.hostname),c||(c="default"),console.log("[WxAuth] 自动获取 siteId:",c)}console.log("[WxAuth] SDK initialized",i),typeof window<"u"&&(i.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=s.getCookie("wxauth-token"),t=s.getCookie("wxauth-openid");if(!(e||t))return!1;const n=c?`&siteId=${encodeURIComponent(c)}`:"",r=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const d=await s.request(`${i.apiBase}/api/auth/check?${r}${n}`);return d.authenticated?(d.token&&(s.setCookie("wxauth-token",d.token),t&&s.deleteCookie("wxauth-openid")),this.onVerified(d.user),!0):(s.deleteCookie("wxauth-token"),t&&s.deleteCookie("wxauth-openid"),!1)}catch(d){return console.error("[WxAuth] silentCheck 请求失败:",d),!1}},async autoCheck(){const e=s.getCookie("wxauth-token"),t=s.getCookie("wxauth-openid");if(!(e||t))return this.showAuthModal(),!1;const n=c?`&siteId=${encodeURIComponent(c)}`:"",r=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const d=await s.request(`${i.apiBase}/api/auth/check?${r}${n}`);return d.authenticated?(console.log("[WxAuth] 自动认证成功(Cookie)"),d.token&&(s.setCookie("wxauth-token",d.token),t&&s.deleteCookie("wxauth-openid")),this.onVerified(d.user),!0):(s.deleteCookie("wxauth-token"),t&&s.deleteCookie("wxauth-openid"),this.showAuthModal(),!1)}catch(d){return console.error("[WxAuth] 自动验证失败:",d),this.showAuthModal(),!1}},async showAuthModal(){l.show();try{const t=c?`?siteId=${encodeURIComponent(c)}`:"",o=await s.request(`${i.apiBase}/api/sdk/config${t}`);o.wechatName&&!i.wechatName&&(i.wechatName=o.wechatName),o.qrcodeUrl&&!i.qrcodeUrl&&(i.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}i.qrcodeUrl&&l.setQrCode(i.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&i.wechatName&&(e.textContent=`"${i.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=s.getCookie("wxauth-token"),t=s.getCookie("wxauth-openid");if(e||t)try{const n=c?`&siteId=${encodeURIComponent(c)}`:"",r=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`,d=await s.request(`${i.apiBase}/api/auth/check?${r}${n}`);if(d.authenticated)return console.log("[WxAuth] 已认证(Cookie)"),d.token&&(s.setCookie("wxauth-token",d.token),t&&s.deleteCookie("wxauth-openid")),this.onVerified(d.user),!0}catch(n){console.error("[WxAuth] Cookie check failed:",n)}return await this.showAuthModal(),new Promise(n=>{u.resolveAuth=n})},async verifyCode(){const e=l.getVerifyCode();if(!e||e.length!==6){l.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="验证中...");try{const o=c?`&siteId=${encodeURIComponent(c)}`:"",n=await s.request(`${i.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token?s.setCookie("wxauth-token",n.token):n.user&&n.user.openid&&s.setCookie("wxauth-openid",n.user.openid),t&&(t.textContent="✅ 成功",t.style.background="#07C160"),setTimeout(()=>{this.onVerified(n.user),this.close(!0)},500)):(l.showMessage("验证码错误或已过期","error"),l.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch{l.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(e=!1){l.hide(),u.resolveAuth&&(u.resolveAuth(!1),u.resolveAuth=null),!e&&typeof i.onClose=="function"&&i.onClose()},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof i.onVerified=="function"&&i.onVerified(e),u.resolveAuth&&(u.resolveAuth(!0),u.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof i.onError=="function"&&i.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),f.WxAuth=x,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
34
+ `,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",n=>{const a=n.target.value.replace(/\D/g,"");n.target.value=a,a&&o<5&&e[o+1].focus(),o===5&&a&&setTimeout(()=>x.verifyCode(),300)}),t.addEventListener("keydown",n=>{const a=n.target;n.key==="Backspace"&&!a.value&&o>0?e[o-1].focus():n.key==="ArrowLeft"&&o>0?(n.preventDefault(),e[o-1].focus()):n.key==="ArrowRight"&&o<5&&(n.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",n=>{n.preventDefault();const a=n.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);a&&(a.split("").forEach((s,w)=>{e[w]&&(e[w].value=s)}),a.length===6&&setTimeout(()=>x.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),i.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.style.display="flex",u.isOpen=!0,h.enable({modalId:"wx-auth-modal",getState:()=>u,onRestore:()=>{this.createModal(),i.qrcodeUrl&&this.setQrCode(i.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&i.wechatName&&(t.textContent=`"${i.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",u.isOpen=!1,h.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()}},x={init(e={}){if(i={...m,...e},!i.apiBase&&typeof window<"u"&&(i.apiBase=window.location.origin),!i.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{d=new URL(t).hostname}catch{}!d&&window.location.hostname&&(d=window.location.hostname),d||(d="default"),console.log("[WxAuth] 自动获取 siteId:",d)}console.log("[WxAuth] SDK initialized",i),typeof window<"u"&&(i.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=c.getToken(),t=c.getCookie("wxauth-openid");if(!(e||t))return!1;const n=d?`&siteId=${encodeURIComponent(d)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const s=await c.request(`${i.apiBase}/api/auth/check?${a}${n}`);return s.authenticated?(s.token&&(c.setToken(s.token),t&&c.deleteCookie("wxauth-openid")),this.onVerified(s.user),!0):(c.clearToken(),!1)}catch(s){return console.error("[WxAuth] silentCheck 请求失败:",s),!1}},async autoCheck(){const e=c.getToken(),t=c.getCookie("wxauth-openid");if(!(e||t))return this.showAuthModal(),!1;const n=d?`&siteId=${encodeURIComponent(d)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const s=await c.request(`${i.apiBase}/api/auth/check?${a}${n}`);return s.authenticated?(console.log("[WxAuth] 自动认证成功(凭证)"),s.token&&(c.setToken(s.token),t&&c.deleteCookie("wxauth-openid")),this.onVerified(s.user),!0):(c.clearToken(),this.showAuthModal(),!1)}catch(s){return console.error("[WxAuth] 自动验证失败:",s),this.showAuthModal(),!1}},async showAuthModal(){l.show();try{const t=d?`?siteId=${encodeURIComponent(d)}`:"",o=await c.request(`${i.apiBase}/api/sdk/config${t}`);o.wechatName&&!i.wechatName&&(i.wechatName=o.wechatName),o.qrcodeUrl&&!i.qrcodeUrl&&(i.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}i.qrcodeUrl&&l.setQrCode(i.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&i.wechatName&&(e.textContent=`"${i.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=c.getToken(),t=c.getCookie("wxauth-openid");if(e||t)try{const n=d?`&siteId=${encodeURIComponent(d)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`,s=await c.request(`${i.apiBase}/api/auth/check?${a}${n}`);if(s.authenticated)return console.log("[WxAuth] 已认证(凭证)"),s.token&&(c.setToken(s.token),t&&c.deleteCookie("wxauth-openid")),this.onVerified(s.user),!0;c.clearToken()}catch(n){console.error("[WxAuth] 凭证检查失败:",n)}return await this.showAuthModal(),new Promise(n=>{u.resolveAuth=n})},async verifyCode(){const e=l.getVerifyCode();if(!e||e.length!==6){l.showMessage("请输入6位验证码","error");return}const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="验证中...");try{const o=d?`&siteId=${encodeURIComponent(d)}`:"",n=await c.request(`${i.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token?c.setToken(n.token):n.user&&n.user.openid&&c.setCookie("wxauth-openid",n.user.openid),t&&(t.textContent="✅ 成功",t.style.background="#07C160"),setTimeout(()=>{this.onVerified(n.user),this.close(!0)},500)):(l.showMessage("验证码错误或已过期","error"),l.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch{l.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(e=!1){l.hide(),u.resolveAuth&&(u.resolveAuth(!1),u.resolveAuth=null),!e&&typeof i.onClose=="function"&&i.onClose()},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof i.onVerified=="function"&&i.onVerified(e),u.resolveAuth&&(u.resolveAuth(!0),u.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof i.onError=="function"&&i.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),f.WxAuth=x,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.2.11",
3
+ "version": "1.2.12",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",