wx-auth-sdk 1.2.10 → 1.2.11

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/README.md CHANGED
@@ -29,7 +29,7 @@ WxAuth.init({
29
29
 
30
30
  SDK 会自动:
31
31
 
32
- - 从 `document.referrer` 或当前域名获取 `siteId`
32
+ - 从 `document.referrer` 或当前域名自动获取站点标识(`siteId`,无需配置)
33
33
  - 从后端拉取公众号名称和二维码
34
34
  - 使用内置 API 地址
35
35
 
@@ -43,7 +43,6 @@ SDK 会自动:
43
43
 
44
44
  ```ts
45
45
  WxAuth.init({
46
- siteId?: string, // 站点标识(可选,自动获取)
47
46
  apiBase?: string, // 后端地址(可选,默认官方服务)
48
47
  required?: boolean, // 是否强制认证(默认 true)
49
48
  silent?: boolean, // 静默初始化(默认 false),true 时不弹窗
@@ -53,6 +52,8 @@ WxAuth.init({
53
52
  });
54
53
  ```
55
54
 
55
+ > `siteId` 无需配置:SDK 自动从 `document.referrer` 或当前域名获取并上报。
56
+
56
57
  ### `WxAuth.requireAuth()`
57
58
 
58
59
  手动触发认证(用于"登录"按钮、切换账号)。返回 `Promise<boolean>`。
package/dist/index.d.ts CHANGED
@@ -43,7 +43,6 @@ export declare const WxAuth: {
43
43
  */
44
44
  export declare interface WxAuthConfig {
45
45
  apiBase: string;
46
- siteId?: string;
47
46
  onVerified?: ((user: any) => void) | null;
48
47
  onError?: ((error: any) => void) | null;
49
48
  onClose?: (() => void) | null;
package/dist/wx-auth.js CHANGED
@@ -3,20 +3,20 @@ const i = {
3
3
  rafId: null,
4
4
  isProtected: !1,
5
5
  restorePending: !1
6
- }, l = {
6
+ }, h = {
7
7
  /**
8
8
  * 启用弹窗保护
9
9
  */
10
10
  enable(e) {
11
11
  if (i.isProtected || typeof window > "u") return;
12
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) => {
13
- for (const s of o)
14
- if (s.type === "childList")
15
- for (const r of s.removedNodes) {
13
+ for (const n of o)
14
+ if (n.type === "childList")
15
+ for (const r of n.removedNodes) {
16
16
  if (r.nodeType !== Node.ELEMENT_NODE) continue;
17
17
  const a = r;
18
18
  if (a.id === e.modalId || a.querySelector?.(`#${e.modalId}`)) {
19
- console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), l.safeRestore(e);
19
+ console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), h.safeRestore(e);
20
20
  return;
21
21
  }
22
22
  }
@@ -31,11 +31,11 @@ const i = {
31
31
  i.rafId = null;
32
32
  return;
33
33
  }
34
- const s = document.getElementById(e.modalId);
35
- (!s || !s.isConnected || l.isHidden(s)) && (console.warn(
34
+ const n = document.getElementById(e.modalId);
35
+ (!n || !n.isConnected || h.isHidden(n)) && (console.warn(
36
36
  "[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
37
- { has: !!s, connected: s?.isConnected, hidden: s ? l.isHidden(s) : null }
38
- ), l.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
37
+ { has: !!n, connected: n?.isConnected, hidden: n ? h.isHidden(n) : null }
38
+ ), h.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
39
39
  };
40
40
  i.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
41
41
  },
@@ -52,7 +52,7 @@ const i = {
52
52
  if (!i.restorePending) {
53
53
  i.restorePending = !0;
54
54
  try {
55
- l.restoreFn(e);
55
+ h.restoreFn(e);
56
56
  } finally {
57
57
  requestAnimationFrame(() => {
58
58
  i.restorePending = !1;
@@ -77,20 +77,18 @@ const i = {
77
77
  * 恢复弹窗
78
78
  */
79
79
  restoreFn(e) {
80
- const { modalId: t, getState: o, onRestore: s } = e;
80
+ const { modalId: t, getState: o, onRestore: n } = e;
81
81
  if (!o().isOpen) return;
82
82
  const r = document.getElementById(t);
83
83
  if (r) {
84
84
  r.style.display = "flex", r.style.visibility = "visible", r.style.opacity = "1";
85
85
  return;
86
86
  }
87
- s();
87
+ n();
88
88
  }
89
- }, p = {
89
+ }, m = {
90
90
  apiBase: "https://wx-auth.shenzjd.com",
91
91
  // 后端API地址(默认值)
92
- siteId: "",
93
- // 站点标识(可选,用于区分来源网站)
94
92
  onVerified: null,
95
93
  // 验证成功回调
96
94
  onError: null,
@@ -106,19 +104,19 @@ const i = {
106
104
  silent: !1
107
105
  // 默认不静默
108
106
  };
109
- let n = { ...p }, c = {
107
+ let s = { ...m }, u = "", d = {
110
108
  isOpen: !1,
111
109
  resolveAuth: null,
112
110
  currentStep: "qr"
113
111
  };
114
- const d = {
112
+ const c = {
115
113
  // 从 apiBase 自动推导根域名(用于跨子域名共享 Cookie)
116
114
  // auth.shenzjd.com → .shenzjd.com
117
115
  // parse.shenzjd.com → .shenzjd.com
118
116
  // localhost / 127.0.0.1 / IP → 不设置 domain
119
117
  getRootDomain() {
120
118
  try {
121
- const e = new URL(n.apiBase || window.location.origin).hostname;
119
+ const e = new URL(s.apiBase || window.location.origin).hostname;
122
120
  if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
123
121
  return "";
124
122
  const t = e.split(".");
@@ -136,8 +134,8 @@ const d = {
136
134
  setCookie(e, t) {
137
135
  const o = /* @__PURE__ */ new Date();
138
136
  o.setTime(o.getTime() + 365 * 24 * 60 * 60 * 1e3);
139
- const s = this.getRootDomain(), r = s ? `;domain=${s}` : "", h = window.location.protocol === "https:" ? ";Secure" : "";
140
- document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${r}${h};SameSite=Strict`;
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`;
141
139
  },
142
140
  // 删除Cookie(匹配相同的 domain)
143
141
  deleteCookie(e) {
@@ -170,14 +168,14 @@ const d = {
170
168
  e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
171
169
  return e += "</div>", e;
172
170
  }
173
- }, u = {
171
+ }, l = {
174
172
  // 创建弹窗
175
173
  createModal() {
176
174
  const e = document.createElement("div");
177
- e.id = "wx-auth-modal", e.className = "wx-auth-modal", n.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
178
- const t = n.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';
175
+ e.id = "wx-auth-modal", e.className = "wx-auth-modal", s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
176
+ const t = s.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';
179
177
  return e.innerHTML = `
180
- <div class="wx-auth-overlay" ${n.required ? 'onclick="event.preventDefault()"' : ""}></div>
178
+ <div class="wx-auth-overlay" ${s.required ? 'onclick="event.preventDefault()"' : ""}></div>
181
179
  <div class="wx-auth-content">
182
180
  <div class="wx-auth-header">
183
181
  <div class="wx-auth-title">微信认证</div>
@@ -196,7 +194,7 @@ const d = {
196
194
  <div>
197
195
  <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
198
196
  <div class="wx-auth-note">取消关注公众号后将被取消认证,请保持关注</div>
199
- ${d.generateCodeInputs()}
197
+ ${c.generateCodeInputs()}
200
198
  </div>
201
199
 
202
200
  <!-- 消息提示 -->
@@ -215,18 +213,18 @@ const d = {
215
213
  setTimeout(() => {
216
214
  const e = document.querySelectorAll(".wx-auth-input");
217
215
  e.length && e.forEach((t, o) => {
218
- t.addEventListener("input", (s) => {
219
- const r = s.target.value.replace(/\D/g, "");
220
- s.target.value = r, r && o < 5 && e[o + 1].focus(), o === 5 && r && setTimeout(() => f.verifyCode(), 300);
221
- }), t.addEventListener("keydown", (s) => {
222
- const r = s.target;
223
- s.key === "Backspace" && !r.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());
224
- }), t.addEventListener("paste", (s) => {
225
- s.preventDefault();
226
- const r = s.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
227
- r && (r.split("").forEach((a, h) => {
228
- e[h] && (e[h].value = a);
229
- }), r.length === 6 && setTimeout(() => f.verifyCode(), 300));
216
+ 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);
219
+ }), 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());
222
+ }), t.addEventListener("paste", (n) => {
223
+ n.preventDefault();
224
+ const r = n.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
225
+ r && (r.split("").forEach((a, f) => {
226
+ e[f] && (e[f].value = a);
227
+ }), r.length === 6 && setTimeout(() => p.verifyCode(), 300));
230
228
  });
231
229
  });
232
230
  }, 100);
@@ -234,13 +232,13 @@ const d = {
234
232
  // 显示弹窗
235
233
  show() {
236
234
  let e = document.getElementById("wx-auth-modal");
237
- 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, l.enable({
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({
238
236
  modalId: "wx-auth-modal",
239
- getState: () => c,
237
+ getState: () => d,
240
238
  onRestore: () => {
241
- this.createModal(), n.qrcodeUrl && this.setQrCode(n.qrcodeUrl);
239
+ this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
242
240
  const t = document.querySelector(".wx-auth-wechat-name");
243
- t && n.wechatName && (t.textContent = `"${n.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
241
+ t && s.wechatName && (t.textContent = `"${s.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
244
242
  const o = document.querySelector(".wx-auth-input");
245
243
  o && o.focus();
246
244
  }, 100);
@@ -250,7 +248,7 @@ const d = {
250
248
  // 隐藏弹窗
251
249
  hide() {
252
250
  const e = document.getElementById("wx-auth-modal");
253
- e && (e.style.display = "none", c.isOpen = !1, l.disable());
251
+ e && (e.style.display = "none", d.isOpen = !1, h.disable());
254
252
  },
255
253
  // 设置二维码
256
254
  setQrCode(e) {
@@ -275,24 +273,23 @@ const d = {
275
273
  const e = document.querySelectorAll(".wx-auth-input");
276
274
  e.forEach((t) => t.value = ""), e[0] && e[0].focus();
277
275
  }
278
- }, f = {
276
+ }, p = {
279
277
  // 初始化
280
278
  init(e = {}) {
281
- if (n = { ...p, ...e }, !n.apiBase && typeof window < "u" && (n.apiBase = window.location.origin), !n.apiBase) {
279
+ if (s = { ...m, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
282
280
  console.error("[WxAuth] apiBase is required");
283
281
  return;
284
282
  }
285
- if (!n.siteId && typeof window < "u") {
283
+ if (typeof window < "u") {
286
284
  const t = document.referrer;
287
285
  if (t)
288
286
  try {
289
- const o = new URL(t);
290
- n.siteId = o.hostname;
287
+ u = new URL(t).hostname;
291
288
  } catch {
292
289
  }
293
- !n.siteId && window.location.hostname && (n.siteId = window.location.hostname), n.siteId || (n.siteId = "default"), console.log("[WxAuth] 自动获取 siteId:", n.siteId);
290
+ !u && window.location.hostname && (u = window.location.hostname), u || (u = "default"), console.log("[WxAuth] 自动获取 siteId:", u);
294
291
  }
295
- console.log("[WxAuth] SDK initialized", n), typeof window < "u" && (n.silent ? this.silentCheck() : this.autoCheck());
292
+ console.log("[WxAuth] SDK initialized", s), typeof window < "u" && (s.silent ? this.silentCheck() : this.autoCheck());
296
293
  },
297
294
  /**
298
295
  * 静默验证(silent 模式专用)
@@ -301,73 +298,73 @@ const d = {
301
298
  * - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
302
299
  */
303
300
  async silentCheck() {
304
- const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
301
+ const e = c.getCookie("wxauth-token"), t = c.getCookie("wxauth-openid");
305
302
  if (!(e || t)) return !1;
306
- const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
303
+ const n = u ? `&siteId=${encodeURIComponent(u)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
307
304
  try {
308
- const a = await d.request(
309
- `${n.apiBase}/api/auth/check?${r}${s}`
305
+ const a = await c.request(
306
+ `${s.apiBase}/api/auth/check?${r}${n}`
310
307
  );
311
- return a.authenticated ? (a.token && (d.setCookie("wxauth-token", a.token), t && d.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (d.deleteCookie("wxauth-token"), t && d.deleteCookie("wxauth-openid"), !1);
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);
312
309
  } catch (a) {
313
310
  return console.error("[WxAuth] silentCheck 请求失败:", a), !1;
314
311
  }
315
312
  },
316
313
  // 自动检测 Cookie 并验证(内部使用)
317
314
  async autoCheck() {
318
- const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
315
+ const e = c.getCookie("wxauth-token"), t = c.getCookie("wxauth-openid");
319
316
  if (!(e || t))
320
317
  return this.showAuthModal(), !1;
321
- const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
318
+ const n = u ? `&siteId=${encodeURIComponent(u)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
322
319
  try {
323
- const a = await d.request(
324
- `${n.apiBase}/api/auth/check?${r}${s}`
320
+ const a = await c.request(
321
+ `${s.apiBase}/api/auth/check?${r}${n}`
325
322
  );
326
- return a.authenticated ? (console.log("[WxAuth] 自动认证成功(Cookie)"), a.token && (d.setCookie("wxauth-token", a.token), t && d.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0) : (d.deleteCookie("wxauth-token"), t && d.deleteCookie("wxauth-openid"), this.showAuthModal(), !1);
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);
327
324
  } catch (a) {
328
325
  return console.error("[WxAuth] 自动验证失败:", a), this.showAuthModal(), !1;
329
326
  }
330
327
  },
331
328
  // 显示认证弹窗(内部使用)
332
329
  async showAuthModal() {
333
- u.show();
330
+ l.show();
334
331
  try {
335
- const t = n.siteId ? `?siteId=${encodeURIComponent(n.siteId)}` : "", o = await d.request(
336
- `${n.apiBase}/api/sdk/config${t}`
332
+ const t = u ? `?siteId=${encodeURIComponent(u)}` : "", o = await c.request(
333
+ `${s.apiBase}/api/sdk/config${t}`
337
334
  );
338
- o.wechatName && !n.wechatName && (n.wechatName = o.wechatName), o.qrcodeUrl && !n.qrcodeUrl && (n.qrcodeUrl = o.qrcodeUrl);
335
+ o.wechatName && !s.wechatName && (s.wechatName = o.wechatName), o.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = o.qrcodeUrl);
339
336
  } catch (t) {
340
337
  console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
341
338
  }
342
- n.qrcodeUrl && u.setQrCode(n.qrcodeUrl);
339
+ s.qrcodeUrl && l.setQrCode(s.qrcodeUrl);
343
340
  const e = document.querySelector(".wx-auth-wechat-name");
344
- e && n.wechatName && (e.textContent = `"${n.wechatName}"`), setTimeout(() => {
341
+ e && s.wechatName && (e.textContent = `"${s.wechatName}"`), setTimeout(() => {
345
342
  const t = document.querySelector(".wx-auth-input");
346
343
  t && t.focus();
347
344
  }, 100);
348
345
  },
349
346
  // 主入口:需要验证时调用
350
347
  async requireAuth() {
351
- const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
348
+ const e = c.getCookie("wxauth-token"), t = c.getCookie("wxauth-openid");
352
349
  if (e || t)
353
350
  try {
354
- const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`, a = await d.request(
355
- `${n.apiBase}/api/auth/check?${r}${s}`
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}`
356
353
  );
357
354
  if (a.authenticated)
358
- return console.log("[WxAuth] 已认证(Cookie)"), a.token && (d.setCookie("wxauth-token", a.token), t && d.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0;
359
- } catch (s) {
360
- console.error("[WxAuth] Cookie check failed:", s);
355
+ return console.log("[WxAuth] 已认证(Cookie)"), a.token && (c.setCookie("wxauth-token", a.token), t && c.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0;
356
+ } catch (n) {
357
+ console.error("[WxAuth] Cookie check failed:", n);
361
358
  }
362
- return await this.showAuthModal(), new Promise((s) => {
363
- c.resolveAuth = s;
359
+ return await this.showAuthModal(), new Promise((n) => {
360
+ d.resolveAuth = n;
364
361
  });
365
362
  },
366
363
  // 验证验证码
367
364
  async verifyCode() {
368
- const e = u.getVerifyCode();
365
+ const e = l.getVerifyCode();
369
366
  if (!e || e.length !== 6) {
370
- u.showMessage("请输入6位验证码", "error");
367
+ l.showMessage("请输入6位验证码", "error");
371
368
  return;
372
369
  }
373
370
  const t = document.querySelector(
@@ -375,32 +372,32 @@ const d = {
375
372
  );
376
373
  t && (t.disabled = !0, t.textContent = "验证中...");
377
374
  try {
378
- const o = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", s = await d.request(
379
- `${n.apiBase}/api/auth/check?authToken=${e}${o}`
375
+ const o = u ? `&siteId=${encodeURIComponent(u)}` : "", n = await c.request(
376
+ `${s.apiBase}/api/auth/check?authToken=${e}${o}`
380
377
  );
381
- s.authenticated ? (s.token ? d.setCookie("wxauth-token", s.token) : s.user && s.user.openid && d.setCookie("wxauth-openid", s.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
382
- this.onVerified(s.user), this.close(!0);
383
- }, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
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(() => {
379
+ this.onVerified(n.user), this.close(!0);
380
+ }, 500)) : (l.showMessage("验证码错误或已过期", "error"), l.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
384
381
  } catch {
385
- u.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
382
+ l.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
386
383
  }
387
384
  },
388
385
  // 关闭弹窗
389
386
  // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
390
387
  // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
391
388
  close(e = !1) {
392
- u.hide(), c.resolveAuth && (c.resolveAuth(!1), c.resolveAuth = null), !e && typeof n.onClose == "function" && n.onClose();
389
+ l.hide(), d.resolveAuth && (d.resolveAuth(!1), d.resolveAuth = null), !e && typeof s.onClose == "function" && s.onClose();
393
390
  },
394
391
  // 验证成功回调
395
392
  onVerified(e) {
396
- console.log("[WxAuth] 验证成功", e), typeof n.onVerified == "function" && n.onVerified(e), c.resolveAuth && (c.resolveAuth(!0), c.resolveAuth = null);
393
+ console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), d.resolveAuth && (d.resolveAuth(!0), d.resolveAuth = null);
397
394
  },
398
395
  // 错误回调
399
396
  onError(e) {
400
- console.error("[WxAuth] 错误", e), typeof n.onError == "function" && n.onError(e);
397
+ console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
401
398
  }
402
399
  };
403
- typeof window < "u" && (window.WxAuth = Object.freeze(f));
400
+ typeof window < "u" && (window.WxAuth = Object.freeze(p));
404
401
  export {
405
- f as WxAuth
402
+ p as WxAuth
406
403
  };
@@ -1,6 +1,6 @@
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 a={observer:null,rafId:null,isProtected:!1,restorePending:!1},l={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 i of o)if(i.type==="childList")for(const s of i.removedNodes){if(s.nodeType!==Node.ELEMENT_NODE)continue;const d=s;if(d.id===e.modalId||d.querySelector?.(`#${e.modalId}`)){console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."),l.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 i=document.getElementById(e.modalId);(!i||!i.isConnected||l.isHidden(i))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!i,connected:i?.isConnected,hidden:i?l.isHidden(i):null}),l.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{l.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:i}=e;if(!o().isOpen)return;const s=document.getElementById(t);if(s){s.style.display="flex",s.style.visibility="visible",s.style.opacity="1";return}i()}},w={apiBase:"https://wx-auth.shenzjd.com",siteId:"",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};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()+365*24*60*60*1e3);const i=this.getRootDomain(),s=i?`;domain=${i}`:"",x=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${s}${x};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
- <div class="wx-auth-overlay" ${n.required?'onclick="event.preventDefault()"':""}></div>
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=`
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">
6
6
  <div class="wx-auth-title">微信认证</div>
@@ -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
- ${r.generateCodeInputs()}
22
+ ${s.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",i=>{const s=i.target.value.replace(/\D/g,"");i.target.value=s,s&&o<5&&e[o+1].focus(),o===5&&s&&setTimeout(()=>p.verifyCode(),300)}),t.addEventListener("keydown",i=>{const s=i.target;i.key==="Backspace"&&!s.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 s=i.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);s&&(s.split("").forEach((d,x)=>{e[x]&&(e[x].value=d)}),s.length===6&&setTimeout(()=>p.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,l.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,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()}},p={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"&&(n.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=r.getCookie("wxauth-token"),t=r.getCookie("wxauth-openid");if(!(e||t))return!1;const i=n.siteId?`&siteId=${encodeURIComponent(n.siteId)}`:"",s=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const d=await r.request(`${n.apiBase}/api/auth/check?${s}${i}`);return d.authenticated?(d.token&&(r.setCookie("wxauth-token",d.token),t&&r.deleteCookie("wxauth-openid")),this.onVerified(d.user),!0):(r.deleteCookie("wxauth-token"),t&&r.deleteCookie("wxauth-openid"),!1)}catch(d){return console.error("[WxAuth] silentCheck 请求失败:",d),!1}},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)}`:"",s=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`;try{const d=await r.request(`${n.apiBase}/api/auth/check?${s}${i}`);return d.authenticated?(console.log("[WxAuth] 自动认证成功(Cookie)"),d.token&&(r.setCookie("wxauth-token",d.token),t&&r.deleteCookie("wxauth-openid")),this.onVerified(d.user),!0):(r.deleteCookie("wxauth-token"),t&&r.deleteCookie("wxauth-openid"),this.showAuthModal(),!1)}catch(d){return console.error("[WxAuth] 自动验证失败:",d),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)}`:"",s=e?`token=${encodeURIComponent(e)}`:`openid=${encodeURIComponent(t||"")}`,d=await r.request(`${n.apiBase}/api/auth/check?${s}${i}`);if(d.authenticated)return console.log("[WxAuth] 已认证(Cookie)"),d.token&&(r.setCookie("wxauth-token",d.token),t&&r.deleteCookie("wxauth-openid")),this.onVerified(d.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.onVerified(i.user),this.close(!0)},500)):(u.showMessage("验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch{u.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(e=!1){u.hide(),c.resolveAuth&&(c.resolveAuth(!1),c.resolveAuth=null),!e&&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=Object.freeze(p)),h.WxAuth=p,Object.defineProperty(h,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 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"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.2.10",
3
+ "version": "1.2.11",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",