wx-auth-sdk 1.2.15 → 1.2.17

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
@@ -3,7 +3,7 @@ const s = {
3
3
  rafId: null,
4
4
  isProtected: !1,
5
5
  restorePending: !1
6
- }, h = {
6
+ }, d = {
7
7
  /**
8
8
  * 启用弹窗保护
9
9
  */
@@ -14,9 +14,9 @@ const s = {
14
14
  if (n.type === "childList")
15
15
  for (const i of n.removedNodes) {
16
16
  if (i.nodeType !== Node.ELEMENT_NODE) continue;
17
- const a = i;
18
- if (a.id === e.modalId || a.querySelector?.(`#${e.modalId}`)) {
19
- console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), h.safeRestore(e);
17
+ const h = i;
18
+ if (h.id === e.modalId || h.querySelector?.(`#${e.modalId}`)) {
19
+ console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), d.safeRestore(e);
20
20
  return;
21
21
  }
22
22
  }
@@ -32,10 +32,10 @@ const s = {
32
32
  return;
33
33
  }
34
34
  const n = document.getElementById(e.modalId);
35
- (!n || !n.isConnected || h.isHidden(n)) && (console.warn(
35
+ (!n || !n.isConnected || d.isHidden(n)) && (console.warn(
36
36
  "[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
37
- { has: !!n, connected: n?.isConnected, hidden: n ? h.isHidden(n) : null }
38
- ), h.safeRestore(e)), s.isProtected && (s.rafId = requestAnimationFrame(t));
37
+ { has: !!n, connected: n?.isConnected, hidden: n ? d.isHidden(n) : null }
38
+ ), d.safeRestore(e)), s.isProtected && (s.rafId = requestAnimationFrame(t));
39
39
  };
40
40
  s.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
41
41
  },
@@ -52,7 +52,7 @@ const s = {
52
52
  if (!s.restorePending) {
53
53
  s.restorePending = !0;
54
54
  try {
55
- h.restoreFn(e);
55
+ d.restoreFn(e);
56
56
  } finally {
57
57
  requestAnimationFrame(() => {
58
58
  s.restorePending = !1;
@@ -86,7 +86,7 @@ const s = {
86
86
  }
87
87
  n();
88
88
  }
89
- }, p = {
89
+ }, w = {
90
90
  apiBase: "https://wx-auth.shenzjd.com",
91
91
  // 后端API地址(默认值)
92
92
  onVerified: null,
@@ -104,12 +104,12 @@ const s = {
104
104
  silent: !1
105
105
  // 默认不静默
106
106
  };
107
- let r = { ...p }, l = "", u = {
107
+ let r = { ...w }, c = "", l = {
108
108
  isOpen: !1,
109
109
  resolveAuth: null,
110
110
  currentStep: "qr"
111
111
  };
112
- function w(e) {
112
+ function p(e) {
113
113
  try {
114
114
  if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
115
115
  return "";
@@ -119,9 +119,9 @@ function w(e) {
119
119
  return "";
120
120
  }
121
121
  }
122
- const c = {
122
+ const a = {
123
123
  getRootDomain() {
124
- return w(window.location.hostname);
124
+ return p(window.location.hostname);
125
125
  },
126
126
  // 获取Cookie
127
127
  getCookie(e) {
@@ -135,10 +135,10 @@ const c = {
135
135
  const n = this.getRootDomain(), i = n ? `;domain=${n}` : "", f = window.location.protocol === "https:" ? ";Secure" : "";
136
136
  document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${i}${f};SameSite=Strict`;
137
137
  },
138
- // 删除Cookie(匹配相同的 domain)
138
+ // 删除Cookie(匹配相同的 domain + Secure,避免 https 下删不掉)
139
139
  deleteCookie(e) {
140
- const t = this.getRootDomain(), o = t ? `;domain=${t}` : "";
141
- document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o};SameSite=Strict`;
140
+ const t = this.getRootDomain(), o = t ? `;domain=${t}` : "", i = window.location.protocol === "https:" ? ";Secure" : "";
141
+ document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${i};SameSite=Strict`;
142
142
  },
143
143
  // ===== 签名 Token 双存储(Cookie 主 + localStorage 备份) =====
144
144
  // 目标:用户清除 Cookie 后,若服务端认证状态仍有效,可凭备份静默恢复。
@@ -167,7 +167,7 @@ const c = {
167
167
  } catch {
168
168
  }
169
169
  },
170
- // 删除:双删(同时清掉旧版明文 openid Cookie)
170
+ // 删除:双删(同时清掉明文 openid Cookie —— 防御性清理,服务端已下线 openid 通道 2026-08-26)
171
171
  clearToken() {
172
172
  this.deleteCookie("wxauth-token"), this.deleteCookie("wxauth-openid");
173
173
  try {
@@ -201,7 +201,7 @@ const c = {
201
201
  e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
202
202
  return e += "</div>", e;
203
203
  }
204
- }, d = {
204
+ }, u = {
205
205
  // 创建弹窗
206
206
  createModal() {
207
207
  const e = document.createElement("div");
@@ -227,7 +227,7 @@ const c = {
227
227
  <div>
228
228
  <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
229
229
  <div class="wx-auth-note">保持关注,即可一直自动登录</div>
230
- ${c.generateCodeInputs()}
230
+ ${a.generateCodeInputs()}
231
231
  </div>
232
232
 
233
233
  <!-- 消息提示 -->
@@ -255,8 +255,8 @@ const c = {
255
255
  }), t.addEventListener("paste", (n) => {
256
256
  n.preventDefault();
257
257
  const i = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
258
- i && (i.split("").forEach((a, f) => {
259
- e[f] && (e[f].value = a);
258
+ i && (i.split("").forEach((h, f) => {
259
+ e[f] && (e[f].value = h);
260
260
  }), i.length === 6 && setTimeout(() => m.verifyCode(), 300));
261
261
  });
262
262
  });
@@ -265,9 +265,9 @@ const c = {
265
265
  // 显示弹窗
266
266
  show() {
267
267
  let e = document.getElementById("wx-auth-modal");
268
- e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), r.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({
268
+ e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), r.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.style.display = "flex", l.isOpen = !0, d.enable({
269
269
  modalId: "wx-auth-modal",
270
- getState: () => u,
270
+ getState: () => l,
271
271
  onRestore: () => {
272
272
  this.createModal(), r.qrcodeUrl && this.setQrCode(r.qrcodeUrl);
273
273
  const t = document.querySelector(".wx-auth-wechat-name");
@@ -281,7 +281,7 @@ const c = {
281
281
  // 隐藏弹窗
282
282
  hide() {
283
283
  const e = document.getElementById("wx-auth-modal");
284
- e && (e.style.display = "none", u.isOpen = !1, h.disable());
284
+ e && (e.style.display = "none", l.isOpen = !1, d.disable());
285
285
  },
286
286
  // 设置二维码
287
287
  setQrCode(e) {
@@ -309,7 +309,7 @@ const c = {
309
309
  }, m = {
310
310
  // 初始化
311
311
  init(e = {}) {
312
- if (r = { ...p, ...e }, !r.apiBase && typeof window < "u" && (r.apiBase = window.location.origin), !r.apiBase) {
312
+ if (r = { ...w, ...e }, !r.apiBase && typeof window < "u" && (r.apiBase = window.location.origin), !r.apiBase) {
313
313
  console.error("[WxAuth] apiBase is required");
314
314
  return;
315
315
  }
@@ -317,10 +317,10 @@ const c = {
317
317
  const t = document.referrer;
318
318
  if (t)
319
319
  try {
320
- l = new URL(t).hostname;
320
+ c = new URL(t).hostname;
321
321
  } catch {
322
322
  }
323
- !l && window.location.hostname && (l = window.location.hostname), l || (l = "default"), console.log("[WxAuth] 自动获取 siteId:", l);
323
+ !c && window.location.hostname && (c = window.location.hostname), c || (c = "default"), console.log("[WxAuth] 自动获取 siteId:", c);
324
324
  }
325
325
  console.log("[WxAuth] SDK initialized", r), typeof window < "u" && (r.silent ? this.silentCheck() : this.autoCheck());
326
326
  },
@@ -331,45 +331,45 @@ const c = {
331
331
  * - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
332
332
  */
333
333
  async silentCheck() {
334
- const e = c.getToken(), t = c.getCookie("wxauth-openid");
335
- if (!(e || t)) return !1;
336
- const n = l ? `&siteId=${encodeURIComponent(l)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
334
+ const e = a.getToken();
335
+ if (!e) return !1;
336
+ const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `token=${encodeURIComponent(e)}`;
337
337
  try {
338
- const a = await c.request(
339
- `${r.apiBase}/api/auth/check?${i}${n}`
338
+ const n = await a.request(
339
+ `${r.apiBase}/api/auth/check?${o}${t}`
340
340
  );
341
- return a.authenticated ? (a.token && (c.setToken(a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (c.clearToken(), !1);
342
- } catch (a) {
343
- return console.error("[WxAuth] silentCheck 请求失败:", a), !1;
341
+ return n.authenticated ? (n.token && a.setToken(n.token), this.onVerified(n.user), !0) : (a.clearToken(), !1);
342
+ } catch (n) {
343
+ return console.error("[WxAuth] silentCheck 请求失败:", n), !1;
344
344
  }
345
345
  },
346
346
  // 自动检测凭证并验证(内部使用)
347
347
  async autoCheck() {
348
- const e = c.getToken(), t = c.getCookie("wxauth-openid");
349
- if (!(e || t))
348
+ const e = a.getToken();
349
+ if (!e)
350
350
  return this.showAuthModal(), !1;
351
- const n = l ? `&siteId=${encodeURIComponent(l)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
351
+ const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `token=${encodeURIComponent(e)}`;
352
352
  try {
353
- const a = await c.request(
354
- `${r.apiBase}/api/auth/check?${i}${n}`
353
+ const n = await a.request(
354
+ `${r.apiBase}/api/auth/check?${o}${t}`
355
355
  );
356
- 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);
357
- } catch (a) {
358
- return console.error("[WxAuth] 自动验证失败:", a), this.showAuthModal(), !1;
356
+ return n.authenticated ? (console.log("[WxAuth] 自动认证成功(凭证)"), n.token && a.setToken(n.token), this.onVerified(n.user), !0) : (a.clearToken(), this.showAuthModal(), !1);
357
+ } catch (n) {
358
+ return console.error("[WxAuth] 自动验证失败:", n), this.showAuthModal(), !1;
359
359
  }
360
360
  },
361
361
  // 显示认证弹窗(内部使用)
362
362
  async showAuthModal() {
363
- d.show();
363
+ u.show();
364
364
  try {
365
- const t = l ? `?siteId=${encodeURIComponent(l)}` : "", o = await c.request(
365
+ const t = c ? `?siteId=${encodeURIComponent(c)}` : "", o = await a.request(
366
366
  `${r.apiBase}/api/sdk/config${t}`
367
367
  );
368
368
  o.wechatName && !r.wechatName && (r.wechatName = o.wechatName), o.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = o.qrcodeUrl);
369
369
  } catch (t) {
370
370
  console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
371
371
  }
372
- r.qrcodeUrl && d.setQrCode(r.qrcodeUrl);
372
+ r.qrcodeUrl && u.setQrCode(r.qrcodeUrl);
373
373
  const e = document.querySelector(".wx-auth-wechat-name");
374
374
  e && r.wechatName && (e.textContent = `"${r.wechatName}"`), setTimeout(() => {
375
375
  const t = document.querySelector(".wx-auth-input");
@@ -377,28 +377,29 @@ const c = {
377
377
  }, 100);
378
378
  },
379
379
  // 主入口:需要验证时调用
380
+ // 凭证仅签名 Token(Cookie 优先 + localStorage 兜底),不再兼容明文 openid(2026-08-26 服务端已下线 openid 通道)
380
381
  async requireAuth() {
381
- const e = c.getToken(), t = c.getCookie("wxauth-openid");
382
- if (e || t)
382
+ const e = a.getToken();
383
+ if (e)
383
384
  try {
384
- const n = l ? `&siteId=${encodeURIComponent(l)}` : "", i = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`, a = await c.request(
385
- `${r.apiBase}/api/auth/check?${i}${n}`
385
+ const t = c ? `&siteId=${encodeURIComponent(c)}` : "", o = `token=${encodeURIComponent(e)}`, n = await a.request(
386
+ `${r.apiBase}/api/auth/check?${o}${t}`
386
387
  );
387
- if (a.authenticated)
388
- return console.log("[WxAuth] 已认证(凭证)"), a.token && (c.setToken(a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0;
389
- c.clearToken();
390
- } catch (n) {
391
- console.error("[WxAuth] 凭证检查失败:", n);
388
+ if (n.authenticated)
389
+ return console.log("[WxAuth] 已认证(凭证)"), n.token && a.setToken(n.token), this.onVerified(n.user), !0;
390
+ a.clearToken();
391
+ } catch (t) {
392
+ console.error("[WxAuth] 凭证检查失败:", t);
392
393
  }
393
- return await this.showAuthModal(), new Promise((n) => {
394
- u.resolveAuth = n;
394
+ return await this.showAuthModal(), new Promise((t) => {
395
+ l.resolveAuth = t;
395
396
  });
396
397
  },
397
398
  // 验证验证码
398
399
  async verifyCode() {
399
- const e = d.getVerifyCode();
400
+ const e = u.getVerifyCode();
400
401
  if (!e || e.length !== 6) {
401
- d.showMessage("请输入6位验证码", "error");
402
+ u.showMessage("请输入6位验证码", "error");
402
403
  return;
403
404
  }
404
405
  const t = document.querySelector(
@@ -406,21 +407,21 @@ const c = {
406
407
  );
407
408
  t && (t.disabled = !0, t.textContent = "登录中...");
408
409
  try {
409
- const o = l ? `&siteId=${encodeURIComponent(l)}` : "", n = await c.request(
410
+ const o = c ? `&siteId=${encodeURIComponent(c)}` : "", n = await a.request(
410
411
  `${r.apiBase}/api/auth/check?authToken=${e}${o}`
411
412
  );
412
- 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(() => {
413
+ n.authenticated ? (n.token && a.setToken(n.token), t && (t.textContent = "✅ 已登录", t.style.background = "#07C160"), setTimeout(() => {
413
414
  this.onVerified(n.user), this.close(!0);
414
- }, 500)) : (d.showMessage("验证码错误或已过期", "error"), d.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
415
+ }, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "登录"));
415
416
  } catch {
416
- d.showMessage("登录失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "登录");
417
+ u.showMessage("登录失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "登录");
417
418
  }
418
419
  },
419
420
  // 关闭弹窗
420
421
  // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
421
422
  // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
422
423
  close(e = !1) {
423
- d.hide(), u.resolveAuth && (u.resolveAuth(!1), u.resolveAuth = null), !e && typeof r.onClose == "function" && r.onClose();
424
+ u.hide(), l.resolveAuth && (l.resolveAuth(!1), l.resolveAuth = null), !e && typeof r.onClose == "function" && r.onClose();
424
425
  },
425
426
  // 清空本地认证凭证(双重删除:Cookie + localStorage)
426
427
  // 用于"退出登录 / 清空认证状态"按钮。
@@ -428,11 +429,11 @@ const c = {
428
429
  // SDK 会凭备份静默恢复(getToken 优先 Cookie、localStorage 兜底),
429
430
  // 造成"清不掉"的假象——所以必须走这里而非只删 Cookie。
430
431
  clearToken() {
431
- c.clearToken();
432
+ a.clearToken();
432
433
  },
433
434
  // 验证成功回调
434
435
  onVerified(e) {
435
- console.log("[WxAuth] 验证成功", e), typeof r.onVerified == "function" && r.onVerified(e), u.resolveAuth && (u.resolveAuth(!0), u.resolveAuth = null);
436
+ console.log("[WxAuth] 验证成功", e), typeof r.onVerified == "function" && r.onVerified(e), l.resolveAuth && (l.resolveAuth(!0), l.resolveAuth = null);
436
437
  },
437
438
  // 错误回调
438
439
  onError(e) {
@@ -1,6 +1,6 @@
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 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 c=a;if(c.id===e.modalId||c.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"};function g(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const s={getRootDomain(){return g(window.location.hostname)},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
- <div class="wx-auth-overlay" ${i.required?'onclick="event.preventDefault()"':""}></div>
1
+ (function(h,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(h=typeof globalThis<"u"?globalThis:h||self,f(h.WxAuthSDK={}))})(this,(function(h){"use strict";var f=document.createElement("style");f.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(f);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},l={enable(e){if(i.isProtected||typeof window>"u")return;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=>{for(const n of o)if(n.type==="childList")for(const a of n.removedNodes){if(a.nodeType!==Node.ELEMENT_NODE)continue;const p=a;if(p.id===e.modalId||p.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),l.safeRestore(e);return}}}),i.observer.observe(document.body,{childList:!0,subtree:!0});const t=()=>{if(!i.isProtected)return;const{getState:o}=e;if(!o().isOpen){i.rafId=null;return}const n=document.getElementById(e.modalId);(!n||!n.isConnected||l.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?l.isHidden(n):null}),l.safeRestore(e)),i.isProtected&&(i.rafId=requestAnimationFrame(t))};i.rafId=requestAnimationFrame(t),console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)")},disable(){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] 弹窗保护已禁用")},safeRestore(e){if(!i.restorePending){i.restorePending=!0;try{l.restoreFn(e)}finally{requestAnimationFrame(()=>{i.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 r={...m},c="",u={isOpen:!1,resolveAuth:null,currentStep:"qr"};function g(e){try{if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}}const s={getRootDomain(){return g(window.location.hostname)},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}`:"",a=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${a};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}},d={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",r.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=r.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
3
+ <div class="wx-auth-overlay" ${r.required?'onclick="event.preventDefault()"':""}></div>
4
4
  <div class="wx-auth-content">
5
5
  <div class="wx-auth-header">
6
6
  <div class="wx-auth-title">微信登录</div>
@@ -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 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((c,w)=>{e[w]&&(e[w].value=c)}),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=s.getToken(),t=s.getCookie("wxauth-openid");if(!(e||t))return!1;const n=d?`&siteId=${encodeURIComponent(d)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const c=await s.request(`${i.apiBase}/api/auth/check?${a}${n}`);return c.authenticated?(c.token&&(s.setToken(c.token),t&&s.deleteCookie("wxauth-openid")),this.onVerified(c.user),!0):(s.clearToken(),!1)}catch(c){return console.error("[WxAuth] silentCheck 请求失败:",c),!1}},async autoCheck(){const e=s.getToken(),t=s.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 c=await s.request(`${i.apiBase}/api/auth/check?${a}${n}`);return c.authenticated?(console.log("[WxAuth] 自动认证成功(凭证)"),c.token&&(s.setToken(c.token),t&&s.deleteCookie("wxauth-openid")),this.onVerified(c.user),!0):(s.clearToken(),this.showAuthModal(),!1)}catch(c){return console.error("[WxAuth] 自动验证失败:",c),this.showAuthModal(),!1}},async showAuthModal(){l.show();try{const t=d?`?siteId=${encodeURIComponent(d)}`:"",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.getToken(),t=s.getCookie("wxauth-openid");if(e||t)try{const n=d?`&siteId=${encodeURIComponent(d)}`:"",a=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`,c=await s.request(`${i.apiBase}/api/auth/check?${a}${n}`);if(c.authenticated)return console.log("[WxAuth] 已认证(凭证)"),c.token&&(s.setToken(c.token),t&&s.deleteCookie("wxauth-openid")),this.onVerified(c.user),!0;s.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 s.request(`${i.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token?s.setToken(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()},clearToken(){s.clearToken()},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((p,w)=>{e[w]&&(e[w].value=p)}),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"),r.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.style.display="flex",u.isOpen=!0,l.enable({modalId:"wx-auth-modal",getState:()=>u,onRestore:()=>{this.createModal(),r.qrcodeUrl&&this.setQrCode(r.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&r.wechatName&&(t.textContent=`"${r.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,l.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(r={...m,...e},!r.apiBase&&typeof window<"u"&&(r.apiBase=window.location.origin),!r.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",r),typeof window<"u"&&(r.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=s.getToken();if(!e)return!1;const t=c?`&siteId=${encodeURIComponent(c)}`:"",o=`token=${encodeURIComponent(e)}`;try{const n=await s.request(`${r.apiBase}/api/auth/check?${o}${t}`);return n.authenticated?(n.token&&s.setToken(n.token),this.onVerified(n.user),!0):(s.clearToken(),!1)}catch(n){return console.error("[WxAuth] silentCheck 请求失败:",n),!1}},async autoCheck(){const e=s.getToken();if(!e)return this.showAuthModal(),!1;const t=c?`&siteId=${encodeURIComponent(c)}`:"",o=`token=${encodeURIComponent(e)}`;try{const n=await s.request(`${r.apiBase}/api/auth/check?${o}${t}`);return n.authenticated?(console.log("[WxAuth] 自动认证成功(凭证)"),n.token&&s.setToken(n.token),this.onVerified(n.user),!0):(s.clearToken(),this.showAuthModal(),!1)}catch(n){return console.error("[WxAuth] 自动验证失败:",n),this.showAuthModal(),!1}},async showAuthModal(){d.show();try{const t=c?`?siteId=${encodeURIComponent(c)}`:"",o=await s.request(`${r.apiBase}/api/sdk/config${t}`);o.wechatName&&!r.wechatName&&(r.wechatName=o.wechatName),o.qrcodeUrl&&!r.qrcodeUrl&&(r.qrcodeUrl=o.qrcodeUrl)}catch(t){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",t)}r.qrcodeUrl&&d.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-wechat-name");e&&r.wechatName&&(e.textContent=`"${r.wechatName}"`),setTimeout(()=>{const t=document.querySelector(".wx-auth-input");t&&t.focus()},100)},async requireAuth(){const e=s.getToken();if(e)try{const t=c?`&siteId=${encodeURIComponent(c)}`:"",o=`token=${encodeURIComponent(e)}`,n=await s.request(`${r.apiBase}/api/auth/check?${o}${t}`);if(n.authenticated)return console.log("[WxAuth] 已认证(凭证)"),n.token&&s.setToken(n.token),this.onVerified(n.user),!0;s.clearToken()}catch(t){console.error("[WxAuth] 凭证检查失败:",t)}return await this.showAuthModal(),new Promise(t=>{u.resolveAuth=t})},async verifyCode(){const e=d.getVerifyCode();if(!e||e.length!==6){d.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(`${r.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?(n.token&&s.setToken(n.token),t&&(t.textContent="✅ 已登录",t.style.background="#07C160"),setTimeout(()=>{this.onVerified(n.user),this.close(!0)},500)):(d.showMessage("验证码错误或已过期","error"),d.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch{d.showMessage("登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){d.hide(),u.resolveAuth&&(u.resolveAuth(!1),u.resolveAuth=null),!e&&typeof r.onClose=="function"&&r.onClose()},clearToken(){s.clearToken()},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof r.onVerified=="function"&&r.onVerified(e),u.resolveAuth&&(u.resolveAuth(!0),u.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof r.onError=="function"&&r.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(x)),h.WxAuth=x,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.2.15",
3
+ "version": "1.2.17",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",