wx-auth-sdk 1.2.9 → 1.2.10

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/index.d.ts CHANGED
@@ -11,7 +11,7 @@ export declare const WxAuth: {
11
11
  showAuthModal(): Promise<void>;
12
12
  requireAuth(): Promise<boolean>;
13
13
  verifyCode(): Promise<void>;
14
- close(): void;
14
+ close(skipOnClose?: boolean): void;
15
15
  onVerified(user: any): void;
16
16
  onError(error: any): void;
17
17
  };
package/dist/wx-auth.js CHANGED
@@ -1,4 +1,4 @@
1
- const s = {
1
+ const i = {
2
2
  observer: null,
3
3
  rafId: null,
4
4
  isProtected: !1,
@@ -8,11 +8,11 @@ const s = {
8
8
  * 启用弹窗保护
9
9
  */
10
10
  enable(e) {
11
- if (s.isProtected || typeof window > "u") return;
12
- s.observer && (s.observer.disconnect(), s.observer = null), s.rafId !== null && (cancelAnimationFrame(s.rafId), s.rafId = null), s.isProtected = !0, s.restorePending = !1, s.observer = new MutationObserver((o) => {
13
- for (const i of o)
14
- if (i.type === "childList")
15
- for (const r of i.removedNodes) {
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) => {
13
+ for (const s of o)
14
+ if (s.type === "childList")
15
+ for (const r of s.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}`)) {
@@ -20,42 +20,42 @@ const s = {
20
20
  return;
21
21
  }
22
22
  }
23
- }), s.observer.observe(document.body, {
23
+ }), i.observer.observe(document.body, {
24
24
  childList: !0,
25
25
  subtree: !0
26
26
  });
27
27
  const t = () => {
28
- if (!s.isProtected) return;
28
+ if (!i.isProtected) return;
29
29
  const { getState: o } = e;
30
30
  if (!o().isOpen) {
31
- s.rafId = null;
31
+ i.rafId = null;
32
32
  return;
33
33
  }
34
- const i = document.getElementById(e.modalId);
35
- (!i || !i.isConnected || l.isHidden(i)) && (console.warn(
34
+ const s = document.getElementById(e.modalId);
35
+ (!s || !s.isConnected || l.isHidden(s)) && (console.warn(
36
36
  "[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
37
- { has: !!i, connected: i?.isConnected, hidden: i ? l.isHidden(i) : null }
38
- ), l.safeRestore(e)), s.isProtected && (s.rafId = requestAnimationFrame(t));
37
+ { has: !!s, connected: s?.isConnected, hidden: s ? l.isHidden(s) : null }
38
+ ), l.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
39
39
  };
40
- s.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
40
+ i.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
41
41
  },
42
42
  /**
43
43
  * 禁用弹窗保护
44
44
  */
45
45
  disable() {
46
- s.observer && (s.observer.disconnect(), s.observer = null), s.rafId !== null && (cancelAnimationFrame(s.rafId), s.rafId = null), s.isProtected = !1, s.restorePending = !1, console.log("[WxAuth] 弹窗保护已禁用");
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] 弹窗保护已禁用");
47
47
  },
48
48
  /**
49
49
  * 同一帧内避免重复恢复
50
50
  */
51
51
  safeRestore(e) {
52
- if (!s.restorePending) {
53
- s.restorePending = !0;
52
+ if (!i.restorePending) {
53
+ i.restorePending = !0;
54
54
  try {
55
55
  l.restoreFn(e);
56
56
  } finally {
57
57
  requestAnimationFrame(() => {
58
- s.restorePending = !1;
58
+ i.restorePending = !1;
59
59
  });
60
60
  }
61
61
  }
@@ -77,14 +77,14 @@ const s = {
77
77
  * 恢复弹窗
78
78
  */
79
79
  restoreFn(e) {
80
- const { modalId: t, getState: o, onRestore: i } = e;
80
+ const { modalId: t, getState: o, onRestore: s } = 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
- i();
87
+ s();
88
88
  }
89
89
  }, p = {
90
90
  apiBase: "https://wx-auth.shenzjd.com",
@@ -136,7 +136,7 @@ const d = {
136
136
  setCookie(e, t) {
137
137
  const o = /* @__PURE__ */ new Date();
138
138
  o.setTime(o.getTime() + 365 * 24 * 60 * 60 * 1e3);
139
- const i = this.getRootDomain(), r = i ? `;domain=${i}` : "", h = window.location.protocol === "https:" ? ";Secure" : "";
139
+ const s = this.getRootDomain(), r = s ? `;domain=${s}` : "", h = window.location.protocol === "https:" ? ";Secure" : "";
140
140
  document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${r}${h};SameSite=Strict`;
141
141
  },
142
142
  // 删除Cookie(匹配相同的 domain)
@@ -215,15 +215,15 @@ const d = {
215
215
  setTimeout(() => {
216
216
  const e = document.querySelectorAll(".wx-auth-input");
217
217
  e.length && e.forEach((t, o) => {
218
- t.addEventListener("input", (i) => {
219
- const r = i.target.value.replace(/\D/g, "");
220
- i.target.value = r, r && o < 5 && e[o + 1].focus(), o === 5 && r && setTimeout(() => f.verifyCode(), 300);
221
- }), t.addEventListener("keydown", (i) => {
222
- const r = i.target;
223
- i.key === "Backspace" && !r.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());
224
- }), t.addEventListener("paste", (i) => {
225
- i.preventDefault();
226
- const r = i.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
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
227
  r && (r.split("").forEach((a, h) => {
228
228
  e[h] && (e[h].value = a);
229
229
  }), r.length === 6 && setTimeout(() => f.verifyCode(), 300));
@@ -303,10 +303,10 @@ const d = {
303
303
  async silentCheck() {
304
304
  const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
305
305
  if (!(e || t)) return !1;
306
- const i = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
306
+ const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
307
307
  try {
308
308
  const a = await d.request(
309
- `${n.apiBase}/api/auth/check?${r}${i}`
309
+ `${n.apiBase}/api/auth/check?${r}${s}`
310
310
  );
311
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);
312
312
  } catch (a) {
@@ -318,10 +318,10 @@ const d = {
318
318
  const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
319
319
  if (!(e || t))
320
320
  return this.showAuthModal(), !1;
321
- const i = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
321
+ const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
322
322
  try {
323
323
  const a = await d.request(
324
- `${n.apiBase}/api/auth/check?${r}${i}`
324
+ `${n.apiBase}/api/auth/check?${r}${s}`
325
325
  );
326
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);
327
327
  } catch (a) {
@@ -351,16 +351,16 @@ const d = {
351
351
  const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
352
352
  if (e || t)
353
353
  try {
354
- const i = 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}${i}`
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}`
356
356
  );
357
357
  if (a.authenticated)
358
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 (i) {
360
- console.error("[WxAuth] Cookie check failed:", i);
359
+ } catch (s) {
360
+ console.error("[WxAuth] Cookie check failed:", s);
361
361
  }
362
- return await this.showAuthModal(), new Promise((i) => {
363
- c.resolveAuth = i;
362
+ return await this.showAuthModal(), new Promise((s) => {
363
+ c.resolveAuth = s;
364
364
  });
365
365
  },
366
366
  // 验证验证码
@@ -375,19 +375,21 @@ const d = {
375
375
  );
376
376
  t && (t.disabled = !0, t.textContent = "验证中...");
377
377
  try {
378
- const o = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", i = await d.request(
378
+ const o = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", s = await d.request(
379
379
  `${n.apiBase}/api/auth/check?authToken=${e}${o}`
380
380
  );
381
- i.authenticated ? (i.token ? d.setCookie("wxauth-token", i.token) : i.user && i.user.openid && d.setCookie("wxauth-openid", i.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
382
- this.close(), this.onVerified(i.user);
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
383
  }, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
384
384
  } catch {
385
385
  u.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
386
386
  }
387
387
  },
388
388
  // 关闭弹窗
389
- close() {
390
- u.hide(), c.resolveAuth && (c.resolveAuth(!1), c.resolveAuth = null), typeof n.onClose == "function" && n.onClose();
389
+ // skipOnClose=true:验证成功路径调用,只隐藏 UI + resolve(false) 兜底,不触发 onClose
390
+ // (onClose 语义 = 用户主动关闭,验证成功关闭不属于用户关闭)
391
+ close(e = !1) {
392
+ u.hide(), c.resolveAuth && (c.resolveAuth(!1), c.resolveAuth = null), !e && typeof n.onClose == "function" && n.onClose();
391
393
  },
392
394
  // 验证成功回调
393
395
  onVerified(e) {
@@ -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.close(),this.onVerified(i.user)},500)):(u.showMessage("验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch{u.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(){u.hide(),c.resolveAuth&&(c.resolveAuth(!1),c.resolveAuth=null),typeof n.onClose=="function"&&n.onClose()},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof n.onVerified=="function"&&n.onVerified(e),c.resolveAuth&&(c.resolveAuth(!0),c.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof n.onError=="function"&&n.onError(e)}};typeof window<"u"&&(window.WxAuth=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",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"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.2.9",
3
+ "version": "1.2.10",
4
4
  "description": "微信订阅号认证 SDK - 极简版",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",
@@ -50,12 +50,15 @@
50
50
  "dev": "vite",
51
51
  "build": "vite build",
52
52
  "preview": "vite preview",
53
- "type-check": "tsc --noEmit"
53
+ "type-check": "tsc --noEmit",
54
+ "test": "vitest run"
54
55
  },
55
56
  "devDependencies": {
56
57
  "@types/node": "^22.19.3",
58
+ "jsdom": "^30.0.1",
57
59
  "typescript": "~5.9.3",
58
60
  "vite": "^7.2.4",
59
- "vite-plugin-dts": "^4.5.4"
61
+ "vite-plugin-dts": "^4.5.4",
62
+ "vitest": "^4.1.11"
60
63
  }
61
64
  }