wx-auth-sdk 1.2.29 → 1.2.31

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
@@ -1,8 +1,11 @@
1
- # 微信订阅号认证 SDK
1
+ # 微信登录 SDK
2
2
 
3
- 轻量级前端认证 SDK — 用户扫码关注公众号 → 输入 6 位验证码 → 认证成功。
3
+ 轻量级前端认证 SDK — 弹窗内置两种登录方式,用户任选其一:
4
4
 
5
- 基于 Vite 构建,**零依赖,< 15 KB**。
5
+ - **小程序扫码**(默认):网页展示小程序码 → 微信扫码 → 小程序内点「确认登录」→ 网页自动登录,全程无需输入验证码
6
+ - **公众号验证码**:扫码关注公众号 → 发送"验证码" → 输入 6 位数字完成认证
7
+
8
+ 基于 Vite 构建,**零依赖,gzip 后 < 10 KB**。
6
9
 
7
10
  ---
8
11
 
@@ -35,6 +38,50 @@ SDK 会自动:
35
38
 
36
39
  ---
37
40
 
41
+ ## 两种登录方式(双 Tab)
42
+
43
+ 弹窗固定提供两个 Tab,用户可自由切换,**默认展示小程序扫码并立即出码**:
44
+
45
+ ```
46
+ ┌──────────────────────────────────┐
47
+ │ 微信登录 [×] │
48
+ │ ┌──────────┬──────────┐ │
49
+ │ │ 小程序登录 │ 公众号登录 │ ← Tab │
50
+ │ └──────────┴──────────┘ │
51
+ │ (内容区随 Tab 切换) │
52
+ └──────────────────────────────────┘
53
+ ```
54
+
55
+ ### Tab 一:小程序扫码(默认)
56
+
57
+ 网页出码 → 用户微信扫码打开小程序确认页 → 点「确认登录」→ 网页每 2 秒轮询,确认后自动完成登录。
58
+
59
+ ```
60
+ 网页弹窗展示小程序码
61
+ │
62
+ ▼
63
+ 用户微信扫码 → 打开小程序确认页
64
+ │
65
+ ▼
66
+ 小程序内展示目标站点 → 用户点「确认登录」
67
+ │
68
+ ▼
69
+ 网页轮询命中 → 领取签名 Token → onVerified() ✅
70
+ ```
71
+
72
+ 要点:
73
+
74
+ - **无需输入验证码**,也不用关注公众号(小程序用户与公众号用户是两条独立身份记录,见下方 `user.type`)
75
+ - 二维码 **5 分钟有效**,过期后画面盖「二维码已过期」遮罩,点「刷新二维码」重新出码
76
+ - **主要面向桌面端浏览器**——手机屏幕上的二维码无法用同一部微信长按识别,手机端用户请切换到公众号验证码 Tab
77
+ - 出码失败(后端未配置小程序 / 微信接口异常)会**自动回落公众号验证码 Tab** 并提示,不会卡死用户
78
+
79
+ ### Tab 二:公众号验证码
80
+
81
+ 传统方式:微信扫码关注公众号 → 向公众号发送"验证码" → 输入收到的 6 位数字 → 认证成功。
82
+
83
+ ---
84
+
38
85
  ## 登录态与 Cookie 域
39
86
 
40
87
  认证成功后,SDK 将签名 Token 写入 Cookie(**按根域存储,会话 Cookie——不设有效期,浏览器关闭即失效**)。Cookie 的 `domain` 由**当前页面域名**推导,而不是后端地址(apiBase):
@@ -59,7 +106,7 @@ SDK 会自动:
59
106
 
60
107
  ### `WxAuth.init(options)`
61
108
 
62
- 初始化 SDK。自动检测 Cookie,已登录静默通过,未登录弹出认证窗。
109
+ 初始化 SDK。自动检测 Cookie,已登录静默通过,未登录弹出认证窗(默认小程序扫码 Tab)。
63
110
 
64
111
  ```ts
65
112
  WxAuth.init({
@@ -73,6 +120,7 @@ WxAuth.init({
73
120
  ```
74
121
 
75
122
  > `siteId` 无需配置:SDK 自动从 `document.referrer` 或当前域名获取并上报。
123
+ > `wechatName` / `qrcodeUrl` 仍接受配置,但接入方配置无效——统一由后端 `/api/sdk/config` 下发(统一使用"神族九帝"公众号)。
76
124
 
77
125
  ### `WxAuth.requireAuth()`
78
126
 
@@ -82,6 +130,14 @@ WxAuth.init({
82
130
 
83
131
  关闭弹窗。`required=false` 时触发 `onClose` 回调。
84
132
 
133
+ ### `WxAuth.clearToken()`
134
+
135
+ 清空本地登录凭证(Cookie)。用于"退出登录"按钮的本地清理。
136
+
137
+ ### `WxAuth.revoke()`
138
+
139
+ 服务端注销:吊销当前 Token(加入后端黑名单,任何设备/子域立即失效)+ 清本地凭证。网络失败时自动降级为仅本地清理,不阻塞退出流程。返回 `Promise<boolean>`。
140
+
85
141
  ---
86
142
 
87
143
  ## 认证流程
@@ -93,33 +149,50 @@ WxAuth.init({
93
149
  初始化 WxAuth.init()
94
150
  │
95
151
  ▼
96
- 读取 Cookie
152
+ 读取 Cookie(会话级)
97
153
  │
98
154
  ├── 有效 ──────────── onVerified() ✅ 静默通过
99
155
  │
100
- └── 无效 ──→ 显示弹窗
101
- │
102
- ▼
103
- 扫码关注公众号
104
- │
105
- ▼
106
- 公众号回复 6 位验证码
156
+ └── 无效 ──→ 显示弹窗(默认小程序扫码 Tab,立即出码)
107
157
  │
108
- ▼
109
- 用户输入验证码
110
- │
111
- ▼
112
- 后端校验
113
- │
114
- ┌───────┴────────┐
115
- │ │
116
- 成功 失败
117
- │ │
118
- ▼ ▼
119
- 保存 Cookie 提示错误
120
- onVerified() 重新输入
158
+ ┌───────┴─────────────────┐
159
+ ▼ ▼
160
+ 小程序扫码 Tab 公众号验证码 Tab
161
+ │ │
162
+ 微信扫码打开小程序 扫码关注公众号
163
+ │ │
164
+ 小程序内「确认登录」 发送"验证码"获取 6 位数字
165
+ │ │
166
+ 网页轮询自动领取 Token 用户输入验证码 → 后端校验
167
+ │ │
168
+ └───────┬─────────────────┘
169
+ ▼
170
+ 保存 Cookie
171
+ onVerified()
121
172
  ```
122
173
 
174
+ > 小程序扫码出码失败时自动切换到公众号验证码 Tab(降级路径)。
175
+
176
+ ---
177
+
178
+ ## `onVerified(user)` 回调数据
179
+
180
+ 两种登录方式成功后回调结构一致(对齐 `/api/auth/check`):
181
+
182
+ ```ts
183
+ interface AuthUser {
184
+ openid: string; // 内部统一身份(小程序用户带 mp: 前缀)
185
+ type: 'mp' | 'official'; // 身份类型:小程序 / 公众号
186
+ mpOpenid: string | null; // 裸小程序 openid(公众号用户为 null),可直接作业务侧 key
187
+ unionid?: string;
188
+ nickname?: string | null;
189
+ headimgurl?: string | null;
190
+ authenticatedAt: string;
191
+ }
192
+ ```
193
+
194
+ > 同一个人在公众号与小程序登录会得到**两条独立的用户记录**(`type` 不同)。业务侧需要区分或关联时读 `type` / `mpOpenid`;不关心差异的接入方无需任何改动——两种方式签发的 Token 结构完全同构。
195
+
123
196
  ---
124
197
 
125
198
  ## 两种模式
@@ -130,19 +203,15 @@ WxAuth.init({
130
203
 
131
204
  ```
132
205
  弹窗
133
- ┌──────────────────────────┐
134
- │ 微信认证 │
135
- │ │
136
- │ 1. 扫码关注公众号 │
137
- │ ┌──────┐ │
138
- │ │ 二维码 │ │
139
- │ └──────┘ │
140
- │ │
141
- │ 2. 发送"验证码"获取 │
142
- │ [_][_][_][_][_][_] │
143
- │ │
144
- │ [ 验证 ] │
145
- └──────────────────────────┘
206
+ ┌──────────────────────────────────┐
207
+ │ 微信登录 │
208
+ │ [ 小程序登录 ] [ 公众号登录 ] │
209
+ │ │
210
+ │ ┌──────────┐ │
211
+ │ │ 小程序码 │ ← 默认出码 │
212
+ │ └──────────┘ │
213
+ │ 微信扫描二维码,打开小程序确认登录 │
214
+ └──────────────────────────────────┘
146
215
  ```
147
216
 
148
217
  ### 可选认证 `required: false`
@@ -151,10 +220,10 @@ WxAuth.init({
151
220
 
152
221
  ```
153
222
  弹窗
154
- ┌──────────────────────────┐
155
- │ 微信认证 [×] │
156
- │ ... │
157
- └──────────────────────────┘
223
+ ┌──────────────────────────────────┐
224
+ │ 微信登录 [×] │
225
+ │ ... │
226
+ └──────────────────────────────────┘
158
227
  ↓
159
228
  用户点击 × 或遮罩
160
229
  ↓
@@ -167,6 +236,11 @@ WxAuth.init({
167
236
 
168
237
  | 功能 | 支持 |
169
238
  |------|------|
239
+ | 双 Tab 登录方式(小程序扫码 / 公众号验证码) | ✅ |
240
+ | 默认小程序扫码、打开弹窗立即出码 | ✅ |
241
+ | 小程序扫码无需输验证码(扫码 → 小程序内确认 → 网页自动登录) | ✅ |
242
+ | 出码失败自动回落公众号验证码 Tab | ✅ |
243
+ | 小程序码 5 分钟过期 + 一键刷新 | ✅ |
170
244
  | 自动聚焦第一个输入框 | ✅ |
171
245
  | 输入一位自动跳到下一格 | ✅ |
172
246
  | 粘贴 6 位数字自动识别 | ✅ |
@@ -175,6 +249,7 @@ WxAuth.init({
175
249
  | 有 Cookie 静默认证 | ✅ |
176
250
  | Cookie 按页面根域写入(跨子域共享) | ✅ |
177
251
  | 会话 Cookie 登录态(浏览器关闭即失效,下次重新扫码) | ✅ |
252
+ | 服务抖动/限流重试,不误清凭证、不误弹码框 | ✅ |
178
253
  | F12 删弹窗自动恢复 | ✅ |
179
254
 
180
255
  > **登录态有效期(2026-08-30)**:登录态只活在当前浏览器进程内(会话 Cookie,不再写 localStorage 备份)。关闭浏览器后需重新扫码登录;同一浏览器会话内刷新、新开标签页均保持登录。
package/dist/wx-auth.js CHANGED
@@ -109,7 +109,7 @@ let r = { ...q }, u = "", a = {
109
109
  resolveAuth: null,
110
110
  currentStep: "qr",
111
111
  mpSession: null
112
- }, h = "code", f = 0;
112
+ }, f = "code", h = 0;
113
113
  function A(e) {
114
114
  try {
115
115
  if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
@@ -201,41 +201,43 @@ function v(e) {
201
201
  const t = e;
202
202
  return t ? t.isNetworkError ? !0 : typeof t.status == "number" ? t.status >= 500 || t.status === 429 : !1 : !1;
203
203
  }
204
- function x(e) {
204
+ function y(e) {
205
205
  return new Promise((t) => setTimeout(t, e));
206
206
  }
207
- const C = 2e3, E = 3e3;
207
+ const C = 3e3, E = 2e3, I = 3e3;
208
208
  function k() {
209
- f++;
209
+ h++;
210
210
  }
211
211
  async function S(e) {
212
- for (; e === f && a.isOpen; ) {
213
- const t = a.mpSession;
214
- if (!t || Date.now() >= t.expiresAt) break;
215
- try {
216
- const o = await c.request(
217
- `${r.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
218
- );
219
- if (e !== f) return;
220
- if (o.status === "confirmed" && o.token) {
221
- w.completeLogin(o);
222
- return;
223
- }
224
- if (o.status === "expired") {
225
- a.mpSession = null;
226
- break;
212
+ if (await y(C), !(e !== h || !a.isOpen)) {
213
+ for (; e === h && a.isOpen; ) {
214
+ const t = a.mpSession;
215
+ if (!t || Date.now() >= t.expiresAt) break;
216
+ try {
217
+ const o = await c.request(
218
+ `${r.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`
219
+ );
220
+ if (e !== h) return;
221
+ if (o.status === "confirmed" && o.token) {
222
+ w.completeLogin(o);
223
+ return;
224
+ }
225
+ if (o.status === "expired") {
226
+ a.mpSession = null;
227
+ break;
228
+ }
229
+ } catch (o) {
230
+ if (e !== h) return;
231
+ if (!v(o)) break;
232
+ await y(I);
233
+ continue;
227
234
  }
228
- } catch (o) {
229
- if (e !== f) return;
230
- if (!v(o)) break;
231
- await x(E);
232
- continue;
235
+ await y(E);
233
236
  }
234
- await x(C);
237
+ e === h && a.isOpen && f === "mp" && l.showMpExpired();
235
238
  }
236
- e === f && a.isOpen && h === "mp" && l.showMpExpired();
237
239
  }
238
- async function y(e) {
240
+ async function x(e) {
239
241
  const t = u ? `&siteId=${encodeURIComponent(u)}` : "", o = `${r.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;
240
242
  for (let n = 0; ; n++)
241
243
  try {
@@ -244,27 +246,27 @@ async function y(e) {
244
246
  } catch (s) {
245
247
  if (!v(s) || n >= b.length)
246
248
  return { kind: "transient" };
247
- await x(b[n]);
249
+ await y(b[n]);
248
250
  }
249
251
  }
250
- const I = 300 * 1e3;
252
+ const T = 300 * 1e3;
251
253
  let m = null;
252
- function T() {
254
+ function M() {
253
255
  return !m || Date.now() >= m.expiresAt ? (m = null, null) : {
254
256
  wechatName: m.wechatName,
255
257
  qrcodeUrl: m.qrcodeUrl
256
258
  };
257
259
  }
258
- async function M() {
260
+ async function $() {
259
261
  const e = u ? `?siteId=${encodeURIComponent(u)}` : "", t = await c.request(
260
262
  `${r.apiBase}/api/sdk/config${e}`
261
263
  ), o = {
262
264
  wechatName: t.wechatName,
263
265
  qrcodeUrl: t.qrcodeUrl
264
266
  };
265
- return m = { ...o, expiresAt: Date.now() + I }, o;
267
+ return m = { ...o, expiresAt: Date.now() + T }, o;
266
268
  }
267
- function $(e) {
269
+ function L(e) {
268
270
  e.wechatName && !r.wechatName && (r.wechatName = e.wechatName), e.qrcodeUrl && !r.qrcodeUrl && (r.qrcodeUrl = e.qrcodeUrl);
269
271
  }
270
272
  const l = {
@@ -364,7 +366,7 @@ const l = {
364
366
  onRestore: () => {
365
367
  this.createModal(), r.qrcodeUrl && this.setQrCode(r.qrcodeUrl);
366
368
  const s = document.querySelector(".wx-auth-wechat-name");
367
- s && r.wechatName && (s.textContent = `"${r.wechatName}"`), this.bindInputEvents(), h === "mp" && w.switchMode("mp"), setTimeout(() => {
369
+ s && r.wechatName && (s.textContent = `"${r.wechatName}"`), this.bindInputEvents(), f === "mp" && w.switchMode("mp"), setTimeout(() => {
368
370
  const d = document.querySelector(".wx-auth-input");
369
371
  d && d.focus();
370
372
  }, 100);
@@ -454,7 +456,7 @@ const l = {
454
456
  async silentCheck() {
455
457
  const e = c.getToken();
456
458
  if (!e) return !1;
457
- const t = await y(e);
459
+ const t = await x(e);
458
460
  return t.kind === "ok" ? (t.result.token && c.setToken(t.result.token), this.onVerified(t.result.user), !0) : (t.kind === "transient" && console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"), !1);
459
461
  },
460
462
  // 自动检测凭证并验证(内部使用)
@@ -462,7 +464,7 @@ const l = {
462
464
  const e = c.getToken();
463
465
  if (!e)
464
466
  return this.showAuthModal(), !1;
465
- const t = await y(e);
467
+ const t = await x(e);
466
468
  return t.kind === "ok" ? (console.log("[WxAuth] 自动认证成功(凭证)"), t.result.token && c.setToken(t.result.token), this.onVerified(t.result.user), !0) : t.kind === "transient" ? (console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"), this.onError({
467
469
  code: "server_error",
468
470
  retryable: !0,
@@ -475,14 +477,14 @@ const l = {
475
477
  // /api/sdk/config(公众号名称/码图)改为后台拉取,不再阻塞渲染。
476
478
  async showAuthModal() {
477
479
  l.show(), this.switchMode("mp");
478
- let e = T();
480
+ let e = M();
479
481
  if (!e)
480
482
  try {
481
- e = await M();
483
+ e = await $();
482
484
  } catch (o) {
483
485
  console.warn("[WxAuth] 获取后端配置失败,使用默认配置", o);
484
486
  }
485
- e && $(e), r.qrcodeUrl && l.setQrCode(r.qrcodeUrl);
487
+ e && L(e), r.qrcodeUrl && l.setQrCode(r.qrcodeUrl);
486
488
  const t = document.querySelector(".wx-auth-wechat-name");
487
489
  t && r.wechatName && (t.textContent = `"${r.wechatName}"`), setTimeout(() => {
488
490
  const o = document.querySelector(".wx-auth-input");
@@ -491,19 +493,19 @@ const l = {
491
493
  },
492
494
  // 切换登录方式(tab 点击 / 默认模式设定)
493
495
  switchMode(e) {
494
- h = e;
496
+ f = e;
495
497
  const t = document.getElementById("wx-auth-modal");
496
498
  if (!t) return;
497
499
  t.querySelectorAll(".wx-auth-tab").forEach((s) => {
498
- s.classList.toggle("wx-auth-tab-active", s.dataset.mode === h);
500
+ s.classList.toggle("wx-auth-tab-active", s.dataset.mode === f);
499
501
  });
500
502
  const o = t.querySelector(".wx-auth-panel-code"), n = t.querySelector(".wx-auth-panel-mp");
501
- o && (o.style.display = h === "code" ? "" : "none"), n && (n.style.display = h === "mp" ? "" : "none"), h === "mp" ? this.startMpLogin() : k();
503
+ o && (o.style.display = f === "code" ? "" : "none"), n && (n.style.display = f === "mp" ? "" : "none"), f === "mp" ? this.startMpLogin() : k();
502
504
  },
503
505
  // 小程序扫码登录:出码(有未过期会话则复用)+ 启动轮询
504
506
  async startMpLogin() {
505
507
  if (!a.isOpen) return;
506
- const e = ++f;
508
+ const e = ++h;
507
509
  if (l.setMpExpiredVisible(!1), l.setMpStatus("", !0), a.mpSession && Date.now() < a.mpSession.expiresAt) {
508
510
  l.setMpQr(a.mpSession.qrDataUrl), S(e);
509
511
  return;
@@ -513,7 +515,7 @@ const l = {
513
515
  method: "POST",
514
516
  body: { siteId: u }
515
517
  });
516
- if (e !== f || !a.isOpen) return;
518
+ if (e !== h || !a.isOpen) return;
517
519
  if (!t.ticket || !t.qrDataUrl) throw new Error("create 响应缺少 ticket/qrDataUrl");
518
520
  a.mpSession = {
519
521
  ticket: String(t.ticket),
@@ -521,7 +523,7 @@ const l = {
521
523
  expiresAt: Date.now() + (Number(t.expiresIn) || 300) * 1e3
522
524
  }, l.setMpQr(a.mpSession.qrDataUrl), S(e);
523
525
  } catch (t) {
524
- if (e !== f || !a.isOpen) return;
526
+ if (e !== h || !a.isOpen) return;
525
527
  console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码", t), this.switchMode("code"), l.showMessage("小程序扫码暂不可用,请使用公众号验证码登录", "error");
526
528
  }
527
529
  },
@@ -530,7 +532,7 @@ const l = {
530
532
  async requireAuth() {
531
533
  const e = c.getToken();
532
534
  if (e) {
533
- const t = await y(e);
535
+ const t = await x(e);
534
536
  if (t.kind === "ok")
535
537
  return console.log("[WxAuth] 已认证(凭证)"), t.result.token && c.setToken(t.result.token), this.onVerified(t.result.user), !0;
536
538
  if (t.kind === "transient")
@@ -549,7 +551,7 @@ const l = {
549
551
  // 再 close()(否则 close() 会先把 Promise resolve 成 false 并清空 resolveAuth)
550
552
  // close(true):验证成功关闭不触发 onClose(onClose 仅语义 = 用户主动关闭)
551
553
  completeLogin(e) {
552
- if (e?.token && c.setToken(e.token), h === "mp")
554
+ if (e?.token && c.setToken(e.token), f === "mp")
553
555
  l.setMpStatus("✅ 登录成功", !1);
554
556
  else {
555
557
  const t = document.querySelector(".wx-auth-btn-primary");
@@ -1,5 +1,5 @@
1
1
  (function(w,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(w=typeof globalThis<"u"?globalThis:w||self,m(w.WxAuthSDK={}))})(this,(function(w){"use strict";var m=document.createElement("style");m.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-tabs{display:flex;gap:8px;margin-bottom:16px}.wx-auth-tab{flex:1;padding:8px 0;font-size:13px;border:1px solid #DCDCDC;background:#f7f7f7;color:#666;border-radius:6px;cursor:pointer;transition:all .2s}.wx-auth-tab:active{transform:scale(.98)}.wx-auth-tab-active{background:#07c160;border-color:#07c160;color:#fff;font-weight:600}.wx-auth-mp-loading{height:100%;display:flex;align-items:center;justify-content:center}.wx-auth-spinner{width:28px;height:28px;border:3px solid #e5e5e5;border-top-color:#07c160;border-radius:50%;animation:wxAuthSpin 1s linear infinite}@keyframes wxAuthSpin{to{transform:rotate(360deg)}}.wx-auth-mp-qrcode{width:100%;height:100%;display:none;object-fit:contain}.wx-auth-mp-container{position:relative}.wx-auth-mp-expired{position:absolute;inset:0;z-index:1;display:none;flex-direction:column;align-items:center;justify-content:center;gap:10px;background:#ffffffeb}.wx-auth-mp-expired-text{font-size:13px;color:#666}.wx-auth-mp-expired .wx-auth-mp-refresh{flex:none;width:auto;margin:0;padding:8px 18px;font-size:13px}.wx-auth-mp-status{font-size:13px;color:#666;margin:4px 0 12px;min-height:18px;line-height:1.4}.wx-auth-mp-hint{margin:12px 0 4px}.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-input{background:#2a2a2a;border-color:#444;color:#e5e5e5}.wx-auth-input:focus{border-color:#07c160;box-shadow:0 0 0 2px #07c16040}.wx-auth-input:disabled{background:#333;color:#888}.wx-auth-qrcode-container{background:#2a2a2a}.wx-auth-tab{background:#2a2a2a;border-color:#444;color:#aaa}.wx-auth-tab-active{background:#07c160;border-color:#07c160;color:#fff}.wx-auth-spinner{border-color:#444;border-top-color:#07c160}.wx-auth-mp-status{color:#aaa}.wx-auth-mp-expired{background:#1a1a1aeb}.wx-auth-mp-expired-text{color:#aaa}.wx-auth-btn-secondary{background:#2a2a2a;color:#e5e5e5}.wx-auth-btn-secondary:hover:not(:disabled){background:#333}.wx-auth-message-info{background:#0d2a1f;color:#7cc4ff;border-color:#1f4a6b}.wx-auth-message-success{background:#0d2a1a;color:#4ade80;border-color:#1f6b3a}.wx-auth-message-error{background:#2a0d0d;color:#f87171;border-color:#6b1f1f}}.wx-auth-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}
2
- /*$vite$:1*/`,document.head.appendChild(m);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},f={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 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] 检测到弹窗被删除,正在恢复..."),f.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||f.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?f.isHidden(n):null}),f.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{f.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 r=document.getElementById(t);if(r){r.style.display="flex",r.style.visibility="visible",r.style.opacity="1";return}n()}},S={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...S},l="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},h="code",p=0;function I(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 c={getRootDomain(){return I(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=this.getRootDomain(),n=o?`;domain=${o}`:"",d=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};path=/${n}${d};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",r=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${r};SameSite=Strict`},getToken(){return this.getCookie("wxauth-token")},setToken(e){this.setCookie("wxauth-token",e)},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem("wxauth-token")}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){const n=new Error(`HTTP ${o.status}`);throw n.status=o.status,n}return await o.json()}catch(o){const n=o;throw n.status===void 0&&(n.isNetworkError=!0),console.error("[WxAuth] Request error:",o),n}},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}},q=[1e3,3e3];function y(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function b(e){return new Promise(t=>setTimeout(t,e))}const E=2e3,T=3e3;function k(){p++}async function C(e){for(;e===p&&s.isOpen;){const t=s.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await c.request(`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==p)return;if(o.status==="confirmed"&&o.token){g.completeLogin(o);return}if(o.status==="expired"){s.mpSession=null;break}}catch(o){if(e!==p)return;if(!y(o))break;await b(T);continue}await b(E)}e===p&&s.isOpen&&h==="mp"&&u.showMpExpired()}async function v(e){const t=l?`&siteId=${encodeURIComponent(l)}`:"",o=`${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await c.request(o);return r.authenticated?{kind:"ok",result:r}:r.error==="rate_limited"||r.error==="server_error"?{kind:"transient"}:{kind:"invalid",result:r}}catch(r){if(!y(r)||n>=q.length)return{kind:"transient"};await b(q[n])}}const M=300*1e3;let x=null;function $(){return!x||Date.now()>=x.expiresAt?(x=null,null):{wechatName:x.wechatName,qrcodeUrl:x.qrcodeUrl}}async function D(){const e=l?`?siteId=${encodeURIComponent(l)}`:"",t=await c.request(`${a.apiBase}/api/sdk/config${e}`),o={wechatName:t.wechatName,qrcodeUrl:t.qrcodeUrl};return x={...o,expiresAt:Date.now()+M},o}function N(e){e.wechatName&&!a.wechatName&&(a.wechatName=e.wechatName),e.qrcodeUrl&&!a.qrcodeUrl&&(a.qrcodeUrl=e.qrcodeUrl)}const u={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=a.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>',o=`<div class="wx-auth-tabs">
2
+ /*$vite$:1*/`,document.head.appendChild(m);const i={observer:null,rafId:null,isProtected:!1,restorePending:!1},f={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 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] 检测到弹窗被删除,正在恢复..."),f.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||f.isHidden(n))&&(console.warn("[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",{has:!!n,connected:n?.isConnected,hidden:n?f.isHidden(n):null}),f.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{f.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 r=document.getElementById(t);if(r){r.style.display="flex",r.style.visibility="visible",r.style.opacity="1";return}n()}},S={apiBase:"https://wx-auth.shenzjd.com",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:"",silent:!1};let a={...S},l="",s={isOpen:!1,resolveAuth:null,currentStep:"qr",mpSession:null},p="code",h=0;function E(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 c={getRootDomain(){return E(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=this.getRootDomain(),n=o?`;domain=${o}`:"",d=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};path=/${n}${d};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"",r=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}${r};SameSite=Strict`},getToken(){return this.getCookie("wxauth-token")},setToken(e){this.setCookie("wxauth-token",e)},clearToken(){this.deleteCookie("wxauth-token"),this.deleteCookie("wxauth-openid");try{window.localStorage.removeItem("wxauth-token")}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){const n=new Error(`HTTP ${o.status}`);throw n.status=o.status,n}return await o.json()}catch(o){const n=o;throw n.status===void 0&&(n.isNetworkError=!0),console.error("[WxAuth] Request error:",o),n}},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}},q=[1e3,3e3];function b(e){const t=e;return t?t.isNetworkError?!0:typeof t.status=="number"?t.status>=500||t.status===429:!1:!1}function y(e){return new Promise(t=>setTimeout(t,e))}const I=3e3,T=2e3,M=3e3;function k(){h++}async function C(e){if(await y(I),!(e!==h||!s.isOpen)){for(;e===h&&s.isOpen;){const t=s.mpSession;if(!t||Date.now()>=t.expiresAt)break;try{const o=await c.request(`${a.apiBase}/api/auth/mp-scan/status?ticket=${encodeURIComponent(t.ticket)}`);if(e!==h)return;if(o.status==="confirmed"&&o.token){g.completeLogin(o);return}if(o.status==="expired"){s.mpSession=null;break}}catch(o){if(e!==h)return;if(!b(o))break;await y(M);continue}await y(T)}e===h&&s.isOpen&&p==="mp"&&u.showMpExpired()}}async function v(e){const t=l?`&siteId=${encodeURIComponent(l)}`:"",o=`${a.apiBase}/api/auth/check?token=${encodeURIComponent(e)}${t}`;for(let n=0;;n++)try{const r=await c.request(o);return r.authenticated?{kind:"ok",result:r}:r.error==="rate_limited"||r.error==="server_error"?{kind:"transient"}:{kind:"invalid",result:r}}catch(r){if(!b(r)||n>=q.length)return{kind:"transient"};await y(q[n])}}const $=300*1e3;let x=null;function D(){return!x||Date.now()>=x.expiresAt?(x=null,null):{wechatName:x.wechatName,qrcodeUrl:x.qrcodeUrl}}async function P(){const e=l?`?siteId=${encodeURIComponent(l)}`:"",t=await c.request(`${a.apiBase}/api/sdk/config${e}`),o={wechatName:t.wechatName,qrcodeUrl:t.qrcodeUrl};return x={...o,expiresAt:Date.now()+$},o}function L(e){e.wechatName&&!a.wechatName&&(a.wechatName=e.wechatName),e.qrcodeUrl&&!a.qrcodeUrl&&(a.qrcodeUrl=e.qrcodeUrl)}const u={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=a.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>',o=`<div class="wx-auth-tabs">
3
3
  <button type="button" class="wx-auth-tab" data-mode="mp" onclick="WxAuth.switchMode('mp')">小程序登录</button>
4
4
  <button type="button" class="wx-auth-tab" data-mode="code" onclick="WxAuth.switchMode('code')">公众号登录</button>
5
5
  </div>`,n=`<div class="wx-auth-panel wx-auth-panel-mp" style="display:none">
@@ -52,4 +52,4 @@
52
52
  <div class="wx-auth-message" style="display:none"></div>
53
53
  </div>
54
54
  </div>
55
- `,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(()=>g.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,A)=>{e[A]&&(e[A].value=d)}),r.length===6&&setTimeout(()=>g.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.querySelectorAll(".wx-auth-input").forEach(r=>r.value="");const o=e.querySelector(".wx-auth-message");o&&(o.textContent="",o.className="wx-auth-message",o.style.display="none");const n=e.querySelector(".wx-auth-btn-primary");n&&(n.disabled=!1,n.textContent="登录",n.style.background=""),k(),s.mpSession=null,e.style.display="flex",s.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>s,onRestore:()=>{this.createModal(),a.qrcodeUrl&&this.setQrCode(a.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&a.wechatName&&(r.textContent=`"${a.wechatName}"`),this.bindInputEvents(),h==="mp"&&g.switchMode("mp"),setTimeout(()=>{const d=document.querySelector(".wx-auth-input");d&&d.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",s.isOpen=!1,k(),s.mpSession=null,f.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},setMpQr(e){const t=document.getElementById("wx-auth-modal"),o=t?.querySelector(".wx-auth-mp-qrcode"),n=t?.querySelector(".wx-auth-mp-loading");o&&(o.src=e,o.style.display="block",n&&(n.style.display="none"),this.setMpExpiredVisible(!1),this.setMpStatus("",!1))},setMpExpiredVisible(e){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");o&&(o.style.display=e?"flex":"none")},setMpStatus(e,t){const o=document.getElementById("wx-auth-modal"),n=o?.querySelector(".wx-auth-mp-status");n&&(n.textContent=e,n.style.display=e?"block":"none");const r=o?.querySelector(".wx-auth-mp-loading");if(r&&(r.style.display=t?"flex":"none"),t){const d=o?.querySelector(".wx-auth-mp-qrcode");d&&(d.style.display="none")}},showMpExpired(){this.setMpExpiredVisible(!0)},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()}},g={init(e={}){if(a={...S,...e},x=null,!a.apiBase&&typeof window<"u"&&(a.apiBase=window.location.origin),!a.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{l=new URL(t).hostname}catch{}!l&&window.location.hostname&&(l=window.location.hostname),l||(l="default"),console.log("[WxAuth] 自动获取 siteId:",l)}console.log("[WxAuth] SDK initialized",a),typeof window<"u"&&(a.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=await v(e);return t.kind==="ok"?(t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=c.getToken();if(!e)return this.showAuthModal(),!1;const t=await v(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0):t.kind==="transient"?(console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(){u.show(),this.switchMode("mp");let e=$();if(!e)try{e=await D()}catch(o){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",o)}e&&N(e),a.qrcodeUrl&&u.setQrCode(a.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&a.wechatName&&(t.textContent=`"${a.wechatName}"`),setTimeout(()=>{const o=document.querySelector(".wx-auth-input");o&&o.focus()},100)},switchMode(e){h=e;const t=document.getElementById("wx-auth-modal");if(!t)return;t.querySelectorAll(".wx-auth-tab").forEach(r=>{r.classList.toggle("wx-auth-tab-active",r.dataset.mode===h)});const o=t.querySelector(".wx-auth-panel-code"),n=t.querySelector(".wx-auth-panel-mp");o&&(o.style.display=h==="code"?"":"none"),n&&(n.style.display=h==="mp"?"":"none"),h==="mp"?this.startMpLogin():k()},async startMpLogin(){if(!s.isOpen)return;const e=++p;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),s.mpSession&&Date.now()<s.mpSession.expiresAt){u.setMpQr(s.mpSession.qrDataUrl),C(e);return}try{const t=await c.request(`${a.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:l}});if(e!==p||!s.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");s.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(s.mpSession.qrDataUrl),C(e)}catch(t){if(e!==p||!s.isOpen)return;console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码",t),this.switchMode("code"),u.showMessage("小程序扫码暂不可用,请使用公众号验证码登录","error")}},async requireAuth(){const e=c.getToken();if(e){const t=await v(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0;if(t.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(),new Promise(t=>{s.resolveAuth=t})},completeLogin(e){if(e?.token&&c.setToken(e.token),h==="mp")u.setMpStatus("✅ 登录成功",!1);else{const t=document.querySelector(".wx-auth-btn-primary");t&&(t.textContent="✅ 已登录",t.style.background="#07C160")}setTimeout(()=>{this.onVerified(e?.user),this.close(!0)},500)},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=l?`&siteId=${encodeURIComponent(l)}`:"",n=await c.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?this.completeLogin(n):(u.showMessage(n.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(y(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),s.resolveAuth&&(s.resolveAuth(!1),s.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=a.apiBase&&!/\/$/.test(a.apiBase)?a.apiBase:"https://wx-auth.shenzjd.com",o=await fetch(`${t}/api/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),credentials:"include"});o.ok||console.warn("[WxAuth] revoke 请求失败,降级本地清理",o.status)}catch(t){console.warn("[WxAuth] revoke 网络异常,降级本地清理",t)}return this.clearToken(),!0},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof a.onVerified=="function"&&a.onVerified(e),s.resolveAuth&&(s.resolveAuth(!0),s.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof a.onError=="function"&&a.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(g)),w.WxAuth=g,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})}));
55
+ `,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(()=>g.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,A)=>{e[A]&&(e[A].value=d)}),r.length===6&&setTimeout(()=>g.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e?(e.classList.remove("wx-auth-required","wx-auth-optional"),a.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional")):e=this.createModal(),e.querySelectorAll(".wx-auth-input").forEach(r=>r.value="");const o=e.querySelector(".wx-auth-message");o&&(o.textContent="",o.className="wx-auth-message",o.style.display="none");const n=e.querySelector(".wx-auth-btn-primary");n&&(n.disabled=!1,n.textContent="登录",n.style.background=""),k(),s.mpSession=null,e.style.display="flex",s.isOpen=!0,f.enable({modalId:"wx-auth-modal",getState:()=>s,onRestore:()=>{this.createModal(),a.qrcodeUrl&&this.setQrCode(a.qrcodeUrl);const r=document.querySelector(".wx-auth-wechat-name");r&&a.wechatName&&(r.textContent=`"${a.wechatName}"`),this.bindInputEvents(),p==="mp"&&g.switchMode("mp"),setTimeout(()=>{const d=document.querySelector(".wx-auth-input");d&&d.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",s.isOpen=!1,k(),s.mpSession=null,f.disable())},setQrCode(e){if(!e)return;const t=document.querySelector(".wx-auth-qrcode");t&&(t.src=e,t.style.display="block")},setMpQr(e){const t=document.getElementById("wx-auth-modal"),o=t?.querySelector(".wx-auth-mp-qrcode"),n=t?.querySelector(".wx-auth-mp-loading");o&&(o.src=e,o.style.display="block",n&&(n.style.display="none"),this.setMpExpiredVisible(!1),this.setMpStatus("",!1))},setMpExpiredVisible(e){const o=document.getElementById("wx-auth-modal")?.querySelector(".wx-auth-mp-expired");o&&(o.style.display=e?"flex":"none")},setMpStatus(e,t){const o=document.getElementById("wx-auth-modal"),n=o?.querySelector(".wx-auth-mp-status");n&&(n.textContent=e,n.style.display=e?"block":"none");const r=o?.querySelector(".wx-auth-mp-loading");if(r&&(r.style.display=t?"flex":"none"),t){const d=o?.querySelector(".wx-auth-mp-qrcode");d&&(d.style.display="none")}},showMpExpired(){this.setMpExpiredVisible(!0)},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()}},g={init(e={}){if(a={...S,...e},x=null,!a.apiBase&&typeof window<"u"&&(a.apiBase=window.location.origin),!a.apiBase){console.error("[WxAuth] apiBase is required");return}if(typeof window<"u"){const t=document.referrer;if(t)try{l=new URL(t).hostname}catch{}!l&&window.location.hostname&&(l=window.location.hostname),l||(l="default"),console.log("[WxAuth] 自动获取 siteId:",l)}console.log("[WxAuth] SDK initialized",a),typeof window<"u"&&(a.silent?this.silentCheck():this.autoCheck())},async silentCheck(){const e=c.getToken();if(!e)return!1;const t=await v(e);return t.kind==="ok"?(t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0):(t.kind==="transient"&&console.warn("[WxAuth] silentCheck 服务暂时不可用,跳过(凭证保留)"),!1)},async autoCheck(){const e=c.getToken();if(!e)return this.showAuthModal(),!1;const t=await v(e);return t.kind==="ok"?(console.log("[WxAuth] 自动认证成功(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0):t.kind==="transient"?(console.warn("[WxAuth] 服务暂时不可用,跳过自动认证(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1):(this.showAuthModal(),!1)},async showAuthModal(){u.show(),this.switchMode("mp");let e=D();if(!e)try{e=await P()}catch(o){console.warn("[WxAuth] 获取后端配置失败,使用默认配置",o)}e&&L(e),a.qrcodeUrl&&u.setQrCode(a.qrcodeUrl);const t=document.querySelector(".wx-auth-wechat-name");t&&a.wechatName&&(t.textContent=`"${a.wechatName}"`),setTimeout(()=>{const o=document.querySelector(".wx-auth-input");o&&o.focus()},100)},switchMode(e){p=e;const t=document.getElementById("wx-auth-modal");if(!t)return;t.querySelectorAll(".wx-auth-tab").forEach(r=>{r.classList.toggle("wx-auth-tab-active",r.dataset.mode===p)});const o=t.querySelector(".wx-auth-panel-code"),n=t.querySelector(".wx-auth-panel-mp");o&&(o.style.display=p==="code"?"":"none"),n&&(n.style.display=p==="mp"?"":"none"),p==="mp"?this.startMpLogin():k()},async startMpLogin(){if(!s.isOpen)return;const e=++h;if(u.setMpExpiredVisible(!1),u.setMpStatus("",!0),s.mpSession&&Date.now()<s.mpSession.expiresAt){u.setMpQr(s.mpSession.qrDataUrl),C(e);return}try{const t=await c.request(`${a.apiBase}/api/auth/mp-scan/create`,{method:"POST",body:{siteId:l}});if(e!==h||!s.isOpen)return;if(!t.ticket||!t.qrDataUrl)throw new Error("create 响应缺少 ticket/qrDataUrl");s.mpSession={ticket:String(t.ticket),qrDataUrl:String(t.qrDataUrl),expiresAt:Date.now()+(Number(t.expiresIn)||300)*1e3},u.setMpQr(s.mpSession.qrDataUrl),C(e)}catch(t){if(e!==h||!s.isOpen)return;console.warn("[WxAuth] 小程序码生成失败,回落公众号验证码",t),this.switchMode("code"),u.showMessage("小程序扫码暂不可用,请使用公众号验证码登录","error")}},async requireAuth(){const e=c.getToken();if(e){const t=await v(e);if(t.kind==="ok")return console.log("[WxAuth] 已认证(凭证)"),t.result.token&&c.setToken(t.result.token),this.onVerified(t.result.user),!0;if(t.kind==="transient")return console.warn("[WxAuth] 认证状态检查暂时不可用(凭证保留)"),this.onError({code:"server_error",retryable:!0,message:"登录服务暂时不可用,请稍后重试"}),!1}return await this.showAuthModal(),new Promise(t=>{s.resolveAuth=t})},completeLogin(e){if(e?.token&&c.setToken(e.token),p==="mp")u.setMpStatus("✅ 登录成功",!1);else{const t=document.querySelector(".wx-auth-btn-primary");t&&(t.textContent="✅ 已登录",t.style.background="#07C160")}setTimeout(()=>{this.onVerified(e?.user),this.close(!0)},500)},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=l?`&siteId=${encodeURIComponent(l)}`:"",n=await c.request(`${a.apiBase}/api/auth/check?authToken=${e}${o}`);n.authenticated?this.completeLogin(n):(u.showMessage(n.error==="rate_limited"?"尝试过于频繁,请稍后再试":"验证码错误或已过期","error"),u.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="登录"))}catch(o){u.showMessage(b(o)?"服务暂时不可用,请稍后重试":"登录失败,请重试","error"),t&&(t.disabled=!1,t.textContent="登录")}},close(e=!1){u.hide(),s.resolveAuth&&(s.resolveAuth(!1),s.resolveAuth=null),!e&&typeof a.onClose=="function"&&a.onClose()},clearToken(){c.clearToken()},async revoke(){const e=c.getToken();if(e)try{const t=a.apiBase&&!/\/$/.test(a.apiBase)?a.apiBase:"https://wx-auth.shenzjd.com",o=await fetch(`${t}/api/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),credentials:"include"});o.ok||console.warn("[WxAuth] revoke 请求失败,降级本地清理",o.status)}catch(t){console.warn("[WxAuth] revoke 网络异常,降级本地清理",t)}return this.clearToken(),!0},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof a.onVerified=="function"&&a.onVerified(e),s.resolveAuth&&(s.resolveAuth(!0),s.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof a.onError=="function"&&a.onError(e)}};typeof window<"u"&&(window.WxAuth=Object.freeze(g)),w.WxAuth=g,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "wx-auth-sdk",
3
- "version": "1.2.29",
4
- "description": "微信订阅号认证 SDK - 极简版",
3
+ "version": "1.2.31",
4
+ "description": "微信登录 SDK - 小程序扫码 / 公众号验证码双方式,零依赖",
5
5
  "type": "module",
6
6
  "main": "./dist/wx-auth.umd.js",
7
7
  "module": "./dist/wx-auth.js",
@@ -21,19 +21,13 @@
21
21
  "wechat",
22
22
  "wx",
23
23
  "auth",
24
- "subscription",
25
24
  "sdk",
26
- "微信认证",
27
- "订阅号",
25
+ "miniprogram",
26
+ "wxa",
27
+ "微信登录",
28
+ "小程序",
28
29
  "公众号",
29
- "微信",
30
- "认证",
31
- "订阅号认证",
32
- "公众号认证",
33
- "微信认证",
34
- "微信订阅号认证",
35
- "微信订阅号认证系统",
36
- "微信订阅号认证SDK"
30
+ "扫码登录"
37
31
  ],
38
32
  "author": "wu529778790",
39
33
  "license": "MIT",