wx-auth-sdk 1.2.6 → 1.2.7
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 +108 -248
- package/dist/wx-auth.css +1 -1
- package/dist/wx-auth.js +99 -83
- package/dist/wx-auth.umd.js +4 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,305 +1,165 @@
|
|
|
1
1
|
# 微信订阅号认证 SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
轻量级前端认证 SDK — 用户扫码关注公众号 → 输入 6 位验证码 → 认证成功。
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
基于 Vite 构建,**零依赖,< 15 KB**。
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 安装
|
|
6
10
|
|
|
7
|
-
### NPM 方式(推荐)
|
|
8
11
|
```bash
|
|
9
12
|
npm install wx-auth-sdk
|
|
10
13
|
```
|
|
11
14
|
|
|
12
|
-
|
|
13
|
-
```html
|
|
14
|
-
<link rel="stylesheet" href="https://cdn.example.com/wx-auth.css">
|
|
15
|
-
<script src="https://cdn.example.com/wx-auth.umd.js"></script>
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
## 🚀 极简接入
|
|
19
|
-
|
|
20
|
-
### 零配置接入(推荐)
|
|
15
|
+
---
|
|
21
16
|
|
|
22
|
-
|
|
17
|
+
## 快速开始(零配置)
|
|
23
18
|
|
|
24
19
|
```typescript
|
|
25
20
|
import { WxAuth } from 'wx-auth-sdk';
|
|
26
|
-
import 'wx-auth-sdk/dist/
|
|
27
|
-
|
|
28
|
-
// ✅ 零配置 - SDK 自动获取所有信息
|
|
29
|
-
WxAuth.init({
|
|
30
|
-
onVerified: (user) => {
|
|
31
|
-
console.log('认证成功', user);
|
|
32
|
-
}
|
|
33
|
-
});
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
**SDK 会自动:**
|
|
37
|
-
- ✅ 从 `document.referrer` 或当前域名自动获取 `siteId`
|
|
38
|
-
- ✅ 从后端 `/api/sdk/config` 自动获取公众号名称和二维码
|
|
39
|
-
- ✅ 使用默认 API 地址 `https://wx-auth.shenzjd.com`
|
|
40
|
-
|
|
41
|
-
就是这么简单!✅
|
|
42
|
-
|
|
43
|
-
### 自定义配置
|
|
21
|
+
import 'wx-auth-sdk/dist/wx-auth.css';
|
|
44
22
|
|
|
45
|
-
如果需要手动指定配置(可选):
|
|
46
|
-
|
|
47
|
-
```typescript
|
|
48
23
|
WxAuth.init({
|
|
49
|
-
siteId: 'my-website', // ← 可选:手动指定站点 ID(不填则自动获取)
|
|
50
|
-
required: false, // ← 可选:认证模式(默认 true)
|
|
51
24
|
onVerified: (user) => {
|
|
52
25
|
console.log('认证成功', user);
|
|
53
|
-
},
|
|
54
|
-
onClose: () => {
|
|
55
|
-
console.log('用户关闭了认证弹窗');
|
|
56
26
|
}
|
|
57
27
|
});
|
|
58
28
|
```
|
|
59
29
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
SDK 支持两种认证模式:
|
|
30
|
+
SDK 会自动:
|
|
63
31
|
|
|
64
|
-
|
|
32
|
+
- 从 `document.referrer` 或当前域名获取 `siteId`
|
|
33
|
+
- 从后端拉取公众号名称和二维码
|
|
34
|
+
- 使用内置 API 地址
|
|
65
35
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
```typescript
|
|
69
|
-
WxAuth.init({
|
|
70
|
-
siteId: 'paid-content',
|
|
71
|
-
required: true, // 强制认证(默认值,可省略)
|
|
72
|
-
onVerified: (user) => {
|
|
73
|
-
console.log('认证成功', user);
|
|
74
|
-
// 解锁付费内容
|
|
75
|
-
}
|
|
76
|
-
});
|
|
77
|
-
```
|
|
36
|
+
---
|
|
78
37
|
|
|
79
|
-
|
|
80
|
-
- ❌ 不显示关闭按钮
|
|
81
|
-
- ❌ 点击遮罩层无效
|
|
82
|
-
- ✅ 必须完成认证才能继续操作
|
|
38
|
+
## API
|
|
83
39
|
|
|
84
|
-
|
|
40
|
+
### `WxAuth.init(options)`
|
|
85
41
|
|
|
86
|
-
|
|
42
|
+
初始化 SDK。自动检测 Cookie,已登录静默通过,未登录弹出认证窗。
|
|
87
43
|
|
|
88
|
-
```
|
|
44
|
+
```ts
|
|
89
45
|
WxAuth.init({
|
|
90
|
-
siteId
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
onClose: () => {
|
|
97
|
-
console.log('用户关闭了认证弹窗');
|
|
98
|
-
// 处理关闭后的逻辑,如显示受限模式
|
|
99
|
-
}
|
|
46
|
+
siteId?: string, // 站点标识(可选,自动获取)
|
|
47
|
+
apiBase?: string, // 后端地址(可选,默认官方服务)
|
|
48
|
+
required?: boolean, // 是否强制认证(默认 true)
|
|
49
|
+
onVerified?: (user) => void,
|
|
50
|
+
onError?: (err) => void,
|
|
51
|
+
onClose?: () => void, // required=false 时关闭弹窗的回调
|
|
100
52
|
});
|
|
101
53
|
```
|
|
102
54
|
|
|
103
|
-
**特点:**
|
|
104
|
-
- ✅ 显示关闭按钮(右上角 ×)
|
|
105
|
-
- ✅ 点击遮罩可关闭弹窗
|
|
106
|
-
- ✅ 关闭时触发 `onClose` 回调
|
|
107
|
-
|
|
108
|
-
## ⚙️ 配置说明
|
|
109
|
-
|
|
110
|
-
| 参数 | 类型 | 必填 | 说明 |
|
|
111
|
-
|------|------|------|------|
|
|
112
|
-
| `siteId` | `string` | ❌ | **站点唯一标识**(可选,自动从 referrer/域名获取) |
|
|
113
|
-
| `apiBase` | `string` | ❌ | 后端 API 地址(**默认值已配置**,可省略) |
|
|
114
|
-
| `required` | `boolean` | ❌ | 是否必须认证(默认 `true`,强制认证) |
|
|
115
|
-
| `onVerified` | `(user) => void` | ❌ | 验证成功回调 |
|
|
116
|
-
| `onError` | `(error) => void` | ❌ | 错误回调 |
|
|
117
|
-
| `onClose` | `() => void` | ❌ | 用户关闭弹窗回调(仅在 `required=false` 时触发) |
|
|
118
|
-
|
|
119
|
-
> **说明:**
|
|
120
|
-
> - ✅ **所有参数都无需手动配置**
|
|
121
|
-
> - `siteId`:自动从 `document.referrer` 或当前域名获取
|
|
122
|
-
> - `apiBase`:使用默认值 `https://wx-auth.shenzjd.com`
|
|
123
|
-
> - `wechatName` / `qrcodeUrl`:自动从后端获取
|
|
124
|
-
> - ⚠️ 接入方配置自己的公众号名称和二维码**无效**(统一使用"神族九帝"公众号)
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
## 🔧 API 方法
|
|
128
|
-
|
|
129
|
-
### `WxAuth.init(options)`
|
|
130
|
-
初始化 SDK,自动检测 Cookie 并静默认证。
|
|
131
|
-
|
|
132
|
-
**行为:**
|
|
133
|
-
- 检查 `wxauth-openid` Cookie
|
|
134
|
-
- 已认证 → 触发 `onVerified` 回调(静默通过)
|
|
135
|
-
- 未认证 → 显示认证弹窗
|
|
136
|
-
|
|
137
55
|
### `WxAuth.requireAuth()`
|
|
138
|
-
手动触发认证流程(用于重新认证、切换账号)。
|
|
139
56
|
|
|
140
|
-
|
|
57
|
+
手动触发认证(用于"登录"按钮、切换账号)。返回 `Promise<boolean>`。
|
|
141
58
|
|
|
142
59
|
### `WxAuth.close()`
|
|
143
|
-
关闭认证弹窗。
|
|
144
60
|
|
|
145
|
-
|
|
146
|
-
- 用户手动关闭弹窗 → 触发 `onClose` 回调
|
|
147
|
-
- 调用 `requireAuth()` 后关闭 → Promise resolve(false)
|
|
61
|
+
关闭弹窗。`required=false` 时触发 `onClose` 回调。
|
|
148
62
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
- ✅ **自动聚焦** - 首个输入框自动获得焦点
|
|
152
|
-
- ✅ **粘贴支持** - 自动识别 6 位数字粘贴
|
|
153
|
-
- ✅ **键盘导航** - 支持退格、方向键
|
|
154
|
-
- ✅ **自动验证** - 输入完成自动提交
|
|
155
|
-
- ✅ **静默认证** - 有 Cookie 时不显示弹窗
|
|
156
|
-
- ✅ **灵活认证** - 支持强制/可选认证模式
|
|
157
|
-
- ✅ **防删除保护** - MutationObserver + 定时器
|
|
158
|
-
|
|
159
|
-
## 📦 构建产物
|
|
63
|
+
---
|
|
160
64
|
|
|
65
|
+
## 认证流程
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
用户访问
|
|
69
|
+
│
|
|
70
|
+
▼
|
|
71
|
+
初始化 WxAuth.init()
|
|
72
|
+
│
|
|
73
|
+
▼
|
|
74
|
+
读取 Cookie
|
|
75
|
+
│
|
|
76
|
+
├── 有效 ──────────── onVerified() ✅ 静默通过
|
|
77
|
+
│
|
|
78
|
+
└── 无效 ──→ 显示弹窗
|
|
79
|
+
│
|
|
80
|
+
▼
|
|
81
|
+
扫码关注公众号
|
|
82
|
+
│
|
|
83
|
+
▼
|
|
84
|
+
公众号回复 6 位验证码
|
|
85
|
+
│
|
|
86
|
+
▼
|
|
87
|
+
用户输入验证码
|
|
88
|
+
│
|
|
89
|
+
▼
|
|
90
|
+
后端校验
|
|
91
|
+
│
|
|
92
|
+
┌───────┴────────┐
|
|
93
|
+
│ │
|
|
94
|
+
成功 失败
|
|
95
|
+
│ │
|
|
96
|
+
▼ ▼
|
|
97
|
+
保存 Cookie 提示错误
|
|
98
|
+
onVerified() 重新输入
|
|
161
99
|
```
|
|
162
|
-
dist/
|
|
163
|
-
├── wx-auth.js # ES Module (7.1 kB)
|
|
164
|
-
├── wx-auth.umd.js # UMD (11 kB)
|
|
165
|
-
├── wx-auth.css # 样式 (3.4 kB)
|
|
166
|
-
└── index.d.ts # TypeScript 类型声明
|
|
167
|
-
```
|
|
168
|
-
|
|
169
|
-
**总计:** < 12 KB(零依赖)
|
|
170
|
-
|
|
171
|
-
## 🔨 开发构建
|
|
172
100
|
|
|
173
|
-
|
|
174
|
-
# 安装依赖
|
|
175
|
-
npm install
|
|
101
|
+
---
|
|
176
102
|
|
|
177
|
-
|
|
178
|
-
npm run build
|
|
103
|
+
## 两种模式
|
|
179
104
|
|
|
180
|
-
|
|
181
|
-
npm run type-check
|
|
182
|
-
```
|
|
105
|
+
### 强制认证 `required: true`(默认)
|
|
183
106
|
|
|
184
|
-
|
|
107
|
+
必须完成认证才能继续,关闭按钮隐藏,点击遮罩无效。
|
|
185
108
|
|
|
186
109
|
```
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
验证成功 → 保存 Cookie → onVerified 回调
|
|
110
|
+
弹窗
|
|
111
|
+
┌──────────────────────────┐
|
|
112
|
+
│ 微信认证 │
|
|
113
|
+
│ │
|
|
114
|
+
│ 1. 扫码关注公众号 │
|
|
115
|
+
│ ┌──────┐ │
|
|
116
|
+
│ │ 二维码 │ │
|
|
117
|
+
│ └──────┘ │
|
|
118
|
+
│ │
|
|
119
|
+
│ 2. 发送"验证码"获取 │
|
|
120
|
+
│ 取消关注公众号后将被 │ ← 新增提示
|
|
121
|
+
│ 取消认证,请保持关注 │
|
|
122
|
+
│ [_][_][_][_][_][_] │
|
|
123
|
+
│ │
|
|
124
|
+
│ [ 验证 ] │
|
|
125
|
+
└──────────────────────────┘
|
|
204
126
|
```
|
|
205
127
|
|
|
206
|
-
|
|
128
|
+
### 可选认证 `required: false`
|
|
207
129
|
|
|
208
|
-
|
|
209
|
-
- **Session**:AES-256-GCM 加密
|
|
210
|
-
- **Cookie**:HttpOnly + SameSite=Lax
|
|
211
|
-
- **防删除**:双重保护机制
|
|
130
|
+
用户可主动关闭弹窗,关闭时执行 `onClose` 回调。
|
|
212
131
|
|
|
213
|
-
## 💡 使用场景
|
|
214
|
-
|
|
215
|
-
### 场景 1:零配置接入(推荐)
|
|
216
|
-
|
|
217
|
-
```typescript
|
|
218
|
-
// ✅ 什么都不用配置,一行代码即可
|
|
219
|
-
WxAuth.init({
|
|
220
|
-
onVerified: (user) => {
|
|
221
|
-
console.log('认证成功', user);
|
|
222
|
-
}
|
|
223
|
-
});
|
|
224
132
|
```
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
// 解锁付费内容
|
|
235
|
-
unlockPremiumContent();
|
|
236
|
-
}
|
|
237
|
-
});
|
|
133
|
+
弹窗
|
|
134
|
+
┌──────────────────────────┐
|
|
135
|
+
│ 微信认证 [×] │
|
|
136
|
+
│ ... │
|
|
137
|
+
└──────────────────────────┘
|
|
138
|
+
↓
|
|
139
|
+
用户点击 × 或遮罩
|
|
140
|
+
↓
|
|
141
|
+
onClose() → 继续浏览受限内容
|
|
238
142
|
```
|
|
239
143
|
|
|
240
|
-
|
|
144
|
+
---
|
|
241
145
|
|
|
242
|
-
|
|
243
|
-
WxAuth.init({
|
|
244
|
-
required: false, // 可选认证
|
|
245
|
-
onVerified: (user) => {
|
|
246
|
-
// 解锁评论、点赞等功能
|
|
247
|
-
enableSocialFeatures();
|
|
248
|
-
},
|
|
249
|
-
onClose: () => {
|
|
250
|
-
// 用户跳过认证,显示受限内容
|
|
251
|
-
showLimitedMode();
|
|
252
|
-
}
|
|
253
|
-
});
|
|
254
|
-
```
|
|
146
|
+
## 功能清单
|
|
255
147
|
|
|
256
|
-
|
|
148
|
+
| 功能 | 支持 |
|
|
149
|
+
|------|------|
|
|
150
|
+
| 自动聚焦第一个输入框 | ✅ |
|
|
151
|
+
| 输入一位自动跳到下一格 | ✅ |
|
|
152
|
+
| 粘贴 6 位数字自动识别 | ✅ |
|
|
153
|
+
| 键盘左右/退格导航 | ✅ |
|
|
154
|
+
| 输入完成自动提交 | ✅ |
|
|
155
|
+
| 有 Cookie 静默认证 | ✅ |
|
|
156
|
+
| F12 删弹窗自动恢复 | ✅ |
|
|
257
157
|
|
|
258
|
-
|
|
259
|
-
// 用户点击"登录"或"切换账号"时触发
|
|
260
|
-
async function handleLogin() {
|
|
261
|
-
const success = await WxAuth.requireAuth();
|
|
262
|
-
if (success) {
|
|
263
|
-
// 认证成功,继续登录流程
|
|
264
|
-
await login();
|
|
265
|
-
} else {
|
|
266
|
-
// 用户关闭弹窗,取消登录
|
|
267
|
-
console.log('用户取消认证');
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
```
|
|
158
|
+
---
|
|
271
159
|
|
|
272
|
-
|
|
160
|
+
## 开发
|
|
273
161
|
|
|
274
|
-
```
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
// 删除旧 Cookie
|
|
278
|
-
document.cookie = 'wxauth-openid=; path=/; max-age=0';
|
|
279
|
-
// 重新认证
|
|
280
|
-
await WxAuth.requireAuth();
|
|
281
|
-
}
|
|
162
|
+
```bash
|
|
163
|
+
npm install
|
|
164
|
+
npm run build
|
|
282
165
|
```
|
|
283
|
-
|
|
284
|
-
## 📚 完整文档
|
|
285
|
-
|
|
286
|
-
完整的项目文档请参考项目根目录的 `README.md`,包含:
|
|
287
|
-
- 后端 API 详细配置
|
|
288
|
-
- 微信后台配置指南
|
|
289
|
-
- Docker 部署方案
|
|
290
|
-
- 环境变量说明
|
|
291
|
-
- 常见问题解答
|
|
292
|
-
|
|
293
|
-
## 🤝 依赖
|
|
294
|
-
|
|
295
|
-
**零依赖** - 纯原生 JavaScript + TypeScript
|
|
296
|
-
|
|
297
|
-
## 📄 许可证
|
|
298
|
-
|
|
299
|
-
MIT License
|
|
300
|
-
|
|
301
|
-
---
|
|
302
|
-
|
|
303
|
-
**版本**: 1.2.0
|
|
304
|
-
**构建时间**: 2025-06-28
|
|
305
|
-
**状态**: ✅ 生产就绪
|
package/dist/wx-auth.css
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
.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:1;padding:0;position:absolute;right:10px;top:50%;transform:translateY(-50%);opacity:.8}.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:
|
|
1
|
+
.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:1;padding:0;position:absolute;right:10px;top:50%;transform:translateY(-50%);opacity:.8}.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}
|
package/dist/wx-auth.js
CHANGED
|
@@ -1,77 +1,92 @@
|
|
|
1
|
-
const
|
|
1
|
+
const i = {
|
|
2
2
|
observer: null,
|
|
3
|
-
|
|
4
|
-
isProtected: !1
|
|
5
|
-
|
|
3
|
+
rafId: null,
|
|
4
|
+
isProtected: !1,
|
|
5
|
+
restorePending: !1
|
|
6
|
+
}, l = {
|
|
6
7
|
/**
|
|
7
8
|
* 启用弹窗保护
|
|
8
|
-
* @param config 配置选项
|
|
9
9
|
*/
|
|
10
10
|
enable(e) {
|
|
11
|
-
if (
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
(
|
|
20
|
-
|
|
21
|
-
), this.restore(e));
|
|
11
|
+
if (i.isProtected || typeof window > "u") return;
|
|
12
|
+
i.observer && (i.observer.disconnect(), i.observer = null), i.rafId !== null && (cancelAnimationFrame(i.rafId), i.rafId = null), i.isProtected = !0, i.restorePending = !1, i.observer = new MutationObserver((o) => {
|
|
13
|
+
for (const s of o)
|
|
14
|
+
if (s.type === "childList")
|
|
15
|
+
for (const r of s.removedNodes) {
|
|
16
|
+
if (r.nodeType !== Node.ELEMENT_NODE) continue;
|
|
17
|
+
const a = r;
|
|
18
|
+
if (a.id === e.modalId || a.querySelector?.(`#${e.modalId}`)) {
|
|
19
|
+
console.warn("[WxAuth] 检测到弹窗被删除,正在恢复..."), l.safeRestore(e);
|
|
20
|
+
return;
|
|
22
21
|
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
const a = i.target;
|
|
26
|
-
a.id === t && i.attributeName === "style" && a.style.display === "none" && o().isOpen && (console.warn(
|
|
27
|
-
"[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."
|
|
28
|
-
), a.style.display = "flex");
|
|
29
|
-
}
|
|
30
|
-
});
|
|
31
|
-
}), c.observer.observe(document.body, {
|
|
22
|
+
}
|
|
23
|
+
}), i.observer.observe(document.body, {
|
|
32
24
|
childList: !0,
|
|
33
|
-
subtree: !0
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
25
|
+
subtree: !0
|
|
26
|
+
});
|
|
27
|
+
const t = () => {
|
|
28
|
+
if (!i.isProtected) return;
|
|
29
|
+
const { getState: o } = e;
|
|
30
|
+
if (!o().isOpen) {
|
|
31
|
+
i.rafId = null;
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const s = document.getElementById(e.modalId);
|
|
35
|
+
(!s || !s.isConnected || l.isHidden(s)) && (console.warn(
|
|
36
|
+
"[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
|
|
37
|
+
{ has: !!s, connected: s?.isConnected, hidden: s ? l.isHidden(s) : null }
|
|
38
|
+
), l.safeRestore(e)), i.isProtected && (i.rafId = requestAnimationFrame(t));
|
|
39
|
+
};
|
|
40
|
+
i.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
|
|
39
41
|
},
|
|
40
42
|
/**
|
|
41
43
|
* 禁用弹窗保护
|
|
42
44
|
*/
|
|
43
45
|
disable() {
|
|
44
|
-
|
|
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] 弹窗保护已禁用");
|
|
45
47
|
},
|
|
46
48
|
/**
|
|
47
|
-
*
|
|
48
|
-
* @param config 配置选项
|
|
49
|
+
* 同一帧内避免重复恢复
|
|
49
50
|
*/
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
51
|
+
safeRestore(e) {
|
|
52
|
+
if (!i.restorePending) {
|
|
53
|
+
i.restorePending = !0;
|
|
54
|
+
try {
|
|
55
|
+
l.restoreFn(e);
|
|
56
|
+
} finally {
|
|
57
|
+
requestAnimationFrame(() => {
|
|
58
|
+
i.restorePending = !1;
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
/**
|
|
64
|
+
* 检查 modal 是否被隐藏(display:none / visibility:hidden / opacity:0 任一即认为不可见)
|
|
65
|
+
*/
|
|
66
|
+
isHidden(e) {
|
|
67
|
+
if (e.style.display === "none" || e.style.visibility === "hidden" || e.style.opacity === "0") return !0;
|
|
68
|
+
try {
|
|
69
|
+
const t = window.getComputedStyle(e);
|
|
70
|
+
if (t.display === "none" || t.visibility === "hidden" || parseFloat(t.opacity) === 0)
|
|
71
|
+
return !0;
|
|
72
|
+
} catch {
|
|
57
73
|
}
|
|
58
|
-
|
|
74
|
+
return !1;
|
|
59
75
|
},
|
|
60
76
|
/**
|
|
61
77
|
* 恢复弹窗
|
|
62
|
-
* @param config 配置选项
|
|
63
78
|
*/
|
|
64
|
-
|
|
79
|
+
restoreFn(e) {
|
|
65
80
|
const { modalId: t, getState: o, onRestore: s } = e;
|
|
66
81
|
if (!o().isOpen) return;
|
|
67
|
-
const
|
|
68
|
-
if (
|
|
69
|
-
|
|
82
|
+
const r = document.getElementById(t);
|
|
83
|
+
if (r) {
|
|
84
|
+
r.style.display = "flex", r.style.visibility = "visible", r.style.opacity = "1";
|
|
70
85
|
return;
|
|
71
86
|
}
|
|
72
87
|
s();
|
|
73
88
|
}
|
|
74
|
-
},
|
|
89
|
+
}, m = {
|
|
75
90
|
apiBase: "https://wx-auth.shenzjd.com",
|
|
76
91
|
// 后端API地址(默认值)
|
|
77
92
|
siteId: "",
|
|
@@ -89,12 +104,12 @@ const c = {
|
|
|
89
104
|
qrcodeUrl: ""
|
|
90
105
|
// 二维码URL(可选,会自动获取)
|
|
91
106
|
};
|
|
92
|
-
let n = { ...
|
|
107
|
+
let n = { ...m }, c = {
|
|
93
108
|
isOpen: !1,
|
|
94
109
|
resolveAuth: null,
|
|
95
110
|
currentStep: "qr"
|
|
96
111
|
};
|
|
97
|
-
const
|
|
112
|
+
const d = {
|
|
98
113
|
// 从 apiBase 自动推导根域名(用于跨子域名共享 Cookie)
|
|
99
114
|
// auth.shenzjd.com → .shenzjd.com
|
|
100
115
|
// parse.shenzjd.com → .shenzjd.com
|
|
@@ -119,8 +134,8 @@ const r = {
|
|
|
119
134
|
setCookie(e, t) {
|
|
120
135
|
const o = /* @__PURE__ */ new Date();
|
|
121
136
|
o.setTime(o.getTime() + 365 * 24 * 60 * 60 * 1e3);
|
|
122
|
-
const s = this.getRootDomain(),
|
|
123
|
-
document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${
|
|
137
|
+
const s = this.getRootDomain(), r = s ? `;domain=${s}` : "", h = window.location.protocol === "https:" ? ";Secure" : "";
|
|
138
|
+
document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${r}${h};SameSite=Strict`;
|
|
124
139
|
},
|
|
125
140
|
// 删除Cookie(匹配相同的 domain)
|
|
126
141
|
deleteCookie(e) {
|
|
@@ -178,7 +193,8 @@ const r = {
|
|
|
178
193
|
<!-- 验证码输入区域 -->
|
|
179
194
|
<div>
|
|
180
195
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
181
|
-
|
|
196
|
+
<div class="wx-auth-note">取消关注公众号后将被取消认证,请保持关注</div>
|
|
197
|
+
${d.generateCodeInputs()}
|
|
182
198
|
</div>
|
|
183
199
|
|
|
184
200
|
<!-- 消息提示 -->
|
|
@@ -198,17 +214,17 @@ const r = {
|
|
|
198
214
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
199
215
|
e.length && e.forEach((t, o) => {
|
|
200
216
|
t.addEventListener("input", (s) => {
|
|
201
|
-
const
|
|
202
|
-
s.target.value =
|
|
217
|
+
const r = s.target.value.replace(/\D/g, "");
|
|
218
|
+
s.target.value = r, r && o < 5 && e[o + 1].focus(), o === 5 && r && setTimeout(() => f.verifyCode(), 300);
|
|
203
219
|
}), t.addEventListener("keydown", (s) => {
|
|
204
|
-
const
|
|
205
|
-
s.key === "Backspace" && !
|
|
220
|
+
const r = s.target;
|
|
221
|
+
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());
|
|
206
222
|
}), t.addEventListener("paste", (s) => {
|
|
207
223
|
s.preventDefault();
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
e[
|
|
211
|
-
}),
|
|
224
|
+
const r = s.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
225
|
+
r && (r.split("").forEach((a, h) => {
|
|
226
|
+
e[h] && (e[h].value = a);
|
|
227
|
+
}), r.length === 6 && setTimeout(() => f.verifyCode(), 300));
|
|
212
228
|
});
|
|
213
229
|
});
|
|
214
230
|
}, 100);
|
|
@@ -216,9 +232,9 @@ const r = {
|
|
|
216
232
|
// 显示弹窗
|
|
217
233
|
show() {
|
|
218
234
|
let e = document.getElementById("wx-auth-modal");
|
|
219
|
-
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",
|
|
235
|
+
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({
|
|
220
236
|
modalId: "wx-auth-modal",
|
|
221
|
-
getState: () =>
|
|
237
|
+
getState: () => c,
|
|
222
238
|
onRestore: () => {
|
|
223
239
|
this.createModal(), n.qrcodeUrl && this.setQrCode(n.qrcodeUrl);
|
|
224
240
|
const t = document.querySelector(".wx-auth-wechat-name");
|
|
@@ -232,7 +248,7 @@ const r = {
|
|
|
232
248
|
// 隐藏弹窗
|
|
233
249
|
hide() {
|
|
234
250
|
const e = document.getElementById("wx-auth-modal");
|
|
235
|
-
e && (e.style.display = "none",
|
|
251
|
+
e && (e.style.display = "none", c.isOpen = !1, l.disable());
|
|
236
252
|
},
|
|
237
253
|
// 设置二维码
|
|
238
254
|
setQrCode(e) {
|
|
@@ -257,10 +273,10 @@ const r = {
|
|
|
257
273
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
258
274
|
e.forEach((t) => t.value = ""), e[0] && e[0].focus();
|
|
259
275
|
}
|
|
260
|
-
},
|
|
276
|
+
}, f = {
|
|
261
277
|
// 初始化
|
|
262
278
|
init(e = {}) {
|
|
263
|
-
if (n = { ...
|
|
279
|
+
if (n = { ...m, ...e }, !n.apiBase && typeof window < "u" && (n.apiBase = window.location.origin), !n.apiBase) {
|
|
264
280
|
console.error("[WxAuth] apiBase is required");
|
|
265
281
|
return;
|
|
266
282
|
}
|
|
@@ -278,15 +294,15 @@ const r = {
|
|
|
278
294
|
},
|
|
279
295
|
// 自动检测 Cookie 并验证(内部使用)
|
|
280
296
|
async autoCheck() {
|
|
281
|
-
const e =
|
|
297
|
+
const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
|
|
282
298
|
if (!(e || t))
|
|
283
299
|
return this.showAuthModal(), !1;
|
|
284
|
-
const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "",
|
|
300
|
+
const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
|
|
285
301
|
try {
|
|
286
|
-
const a = await
|
|
287
|
-
`${n.apiBase}/api/auth/check?${
|
|
302
|
+
const a = await d.request(
|
|
303
|
+
`${n.apiBase}/api/auth/check?${r}${s}`
|
|
288
304
|
);
|
|
289
|
-
return a.authenticated ? (console.log("[WxAuth] 自动认证成功(Cookie)"), a.token && (
|
|
305
|
+
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);
|
|
290
306
|
} catch (a) {
|
|
291
307
|
return console.error("[WxAuth] 自动验证失败:", a), this.showAuthModal(), !1;
|
|
292
308
|
}
|
|
@@ -295,7 +311,7 @@ const r = {
|
|
|
295
311
|
async showAuthModal() {
|
|
296
312
|
u.show();
|
|
297
313
|
try {
|
|
298
|
-
const t = n.siteId ? `?siteId=${encodeURIComponent(n.siteId)}` : "", o = await
|
|
314
|
+
const t = n.siteId ? `?siteId=${encodeURIComponent(n.siteId)}` : "", o = await d.request(
|
|
299
315
|
`${n.apiBase}/api/sdk/config${t}`
|
|
300
316
|
);
|
|
301
317
|
o.wechatName && !n.wechatName && (n.wechatName = o.wechatName), o.qrcodeUrl && !n.qrcodeUrl && (n.qrcodeUrl = o.qrcodeUrl);
|
|
@@ -311,19 +327,19 @@ const r = {
|
|
|
311
327
|
},
|
|
312
328
|
// 主入口:需要验证时调用
|
|
313
329
|
async requireAuth() {
|
|
314
|
-
const e =
|
|
330
|
+
const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
|
|
315
331
|
if (e || t)
|
|
316
332
|
try {
|
|
317
|
-
const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "",
|
|
318
|
-
`${n.apiBase}/api/auth/check?${
|
|
333
|
+
const s = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`, a = await d.request(
|
|
334
|
+
`${n.apiBase}/api/auth/check?${r}${s}`
|
|
319
335
|
);
|
|
320
336
|
if (a.authenticated)
|
|
321
|
-
return console.log("[WxAuth] 已认证(Cookie)"), a.token && (
|
|
337
|
+
return console.log("[WxAuth] 已认证(Cookie)"), a.token && (d.setCookie("wxauth-token", a.token), t && d.deleteCookie("wxauth-openid")), this.onVerified(a.user), !0;
|
|
322
338
|
} catch (s) {
|
|
323
339
|
console.error("[WxAuth] Cookie check failed:", s);
|
|
324
340
|
}
|
|
325
341
|
return await this.showAuthModal(), new Promise((s) => {
|
|
326
|
-
|
|
342
|
+
c.resolveAuth = s;
|
|
327
343
|
});
|
|
328
344
|
},
|
|
329
345
|
// 验证验证码
|
|
@@ -338,10 +354,10 @@ const r = {
|
|
|
338
354
|
);
|
|
339
355
|
t && (t.disabled = !0, t.textContent = "验证中...");
|
|
340
356
|
try {
|
|
341
|
-
const o = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", s = await
|
|
357
|
+
const o = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", s = await d.request(
|
|
342
358
|
`${n.apiBase}/api/auth/check?authToken=${e}${o}`
|
|
343
359
|
);
|
|
344
|
-
s.authenticated ? (s.token ?
|
|
360
|
+
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(() => {
|
|
345
361
|
this.close(), this.onVerified(s.user);
|
|
346
362
|
}, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
|
|
347
363
|
} catch {
|
|
@@ -350,18 +366,18 @@ const r = {
|
|
|
350
366
|
},
|
|
351
367
|
// 关闭弹窗
|
|
352
368
|
close() {
|
|
353
|
-
u.hide(),
|
|
369
|
+
u.hide(), c.resolveAuth && (c.resolveAuth(!1), c.resolveAuth = null), typeof n.onClose == "function" && n.onClose();
|
|
354
370
|
},
|
|
355
371
|
// 验证成功回调
|
|
356
372
|
onVerified(e) {
|
|
357
|
-
console.log("[WxAuth] 验证成功", e), typeof n.onVerified == "function" && n.onVerified(e),
|
|
373
|
+
console.log("[WxAuth] 验证成功", e), typeof n.onVerified == "function" && n.onVerified(e), c.resolveAuth && (c.resolveAuth(!0), c.resolveAuth = null);
|
|
358
374
|
},
|
|
359
375
|
// 错误回调
|
|
360
376
|
onError(e) {
|
|
361
377
|
console.error("[WxAuth] 错误", e), typeof n.onError == "function" && n.onError(e);
|
|
362
378
|
}
|
|
363
379
|
};
|
|
364
|
-
typeof window < "u" && (window.WxAuth =
|
|
380
|
+
typeof window < "u" && (window.WxAuth = Object.freeze(f));
|
|
365
381
|
export {
|
|
366
|
-
|
|
382
|
+
f as WxAuth
|
|
367
383
|
};
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(h,
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(
|
|
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:1;padding:0;position:absolute;right:10px;top:50%;transform:translateY(-50%);opacity:.8}.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:""};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
3
|
<div class="wx-auth-overlay" ${n.required?'onclick="event.preventDefault()"':""}></div>
|
|
4
4
|
<div class="wx-auth-content">
|
|
5
5
|
<div class="wx-auth-header">
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
<!-- 验证码输入区域 -->
|
|
19
19
|
<div>
|
|
20
20
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
21
|
+
<div class="wx-auth-note">取消关注公众号后将被取消认证,请保持关注</div>
|
|
21
22
|
${r.generateCodeInputs()}
|
|
22
23
|
</div>
|
|
23
24
|
|
|
@@ -30,4 +31,4 @@
|
|
|
30
31
|
</div>
|
|
31
32
|
</div>
|
|
32
33
|
</div>
|
|
33
|
-
`,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
|
|
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"&&this.autoCheck()},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"})}));
|