wx-auth-sdk 1.2.6 → 1.2.8
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 +131 -237
- package/dist/index.d.ts +8 -0
- package/dist/wx-auth.css +1 -1
- package/dist/wx-auth.js +131 -94
- package/dist/wx-auth.umd.js +4 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,31 +1,25 @@
|
|
|
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/
|
|
21
|
+
import 'wx-auth-sdk/dist/wx-auth.css';
|
|
27
22
|
|
|
28
|
-
// ✅ 零配置 - SDK 自动获取所有信息
|
|
29
23
|
WxAuth.init({
|
|
30
24
|
onVerified: (user) => {
|
|
31
25
|
console.log('认证成功', user);
|
|
@@ -33,273 +27,173 @@ WxAuth.init({
|
|
|
33
27
|
});
|
|
34
28
|
```
|
|
35
29
|
|
|
36
|
-
|
|
37
|
-
- ✅ 从 `document.referrer` 或当前域名自动获取 `siteId`
|
|
38
|
-
- ✅ 从后端 `/api/sdk/config` 自动获取公众号名称和二维码
|
|
39
|
-
- ✅ 使用默认 API 地址 `https://wx-auth.shenzjd.com`
|
|
30
|
+
SDK 会自动:
|
|
40
31
|
|
|
41
|
-
|
|
32
|
+
- 从 `document.referrer` 或当前域名获取 `siteId`
|
|
33
|
+
- 从后端拉取公众号名称和二维码
|
|
34
|
+
- 使用内置 API 地址
|
|
42
35
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
如果需要手动指定配置(可选):
|
|
46
|
-
|
|
47
|
-
```typescript
|
|
48
|
-
WxAuth.init({
|
|
49
|
-
siteId: 'my-website', // ← 可选:手动指定站点 ID(不填则自动获取)
|
|
50
|
-
required: false, // ← 可选:认证模式(默认 true)
|
|
51
|
-
onVerified: (user) => {
|
|
52
|
-
console.log('认证成功', user);
|
|
53
|
-
},
|
|
54
|
-
onClose: () => {
|
|
55
|
-
console.log('用户关闭了认证弹窗');
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
### 认证模式选择
|
|
61
|
-
|
|
62
|
-
SDK 支持两种认证模式:
|
|
63
|
-
|
|
64
|
-
#### 强制认证模式(默认)
|
|
65
|
-
|
|
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
|
+
silent?: boolean, // 静默初始化(默认 false),true 时不弹窗
|
|
50
|
+
onVerified?: (user) => void,
|
|
51
|
+
onError?: (err) => void,
|
|
52
|
+
onClose?: () => void, // required=false 时关闭弹窗的回调
|
|
100
53
|
});
|
|
101
54
|
```
|
|
102
55
|
|
|
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
56
|
### `WxAuth.requireAuth()`
|
|
138
|
-
手动触发认证流程(用于重新认证、切换账号)。
|
|
139
57
|
|
|
140
|
-
|
|
58
|
+
手动触发认证(用于"登录"按钮、切换账号)。返回 `Promise<boolean>`。
|
|
141
59
|
|
|
142
60
|
### `WxAuth.close()`
|
|
143
|
-
关闭认证弹窗。
|
|
144
61
|
|
|
145
|
-
|
|
146
|
-
- 用户手动关闭弹窗 → 触发 `onClose` 回调
|
|
147
|
-
- 调用 `requireAuth()` 后关闭 → Promise resolve(false)
|
|
62
|
+
关闭弹窗。`required=false` 时触发 `onClose` 回调。
|
|
148
63
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
- ✅ **自动聚焦** - 首个输入框自动获得焦点
|
|
152
|
-
- ✅ **粘贴支持** - 自动识别 6 位数字粘贴
|
|
153
|
-
- ✅ **键盘导航** - 支持退格、方向键
|
|
154
|
-
- ✅ **自动验证** - 输入完成自动提交
|
|
155
|
-
- ✅ **静默认证** - 有 Cookie 时不显示弹窗
|
|
156
|
-
- ✅ **灵活认证** - 支持强制/可选认证模式
|
|
157
|
-
- ✅ **防删除保护** - MutationObserver + 定时器
|
|
158
|
-
|
|
159
|
-
## 📦 构建产物
|
|
64
|
+
---
|
|
160
65
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
66
|
+
## 认证流程
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
用户访问
|
|
70
|
+
│
|
|
71
|
+
▼
|
|
72
|
+
初始化 WxAuth.init()
|
|
73
|
+
│
|
|
74
|
+
▼
|
|
75
|
+
读取 Cookie
|
|
76
|
+
│
|
|
77
|
+
├── 有效 ──────────── onVerified() ✅ 静默通过
|
|
78
|
+
│
|
|
79
|
+
└── 无效 ──→ 显示弹窗
|
|
80
|
+
│
|
|
81
|
+
▼
|
|
82
|
+
扫码关注公众号
|
|
83
|
+
│
|
|
84
|
+
▼
|
|
85
|
+
公众号回复 6 位验证码
|
|
86
|
+
│
|
|
87
|
+
▼
|
|
88
|
+
用户输入验证码
|
|
89
|
+
│
|
|
90
|
+
▼
|
|
91
|
+
后端校验
|
|
92
|
+
│
|
|
93
|
+
┌───────┴────────┐
|
|
94
|
+
│ │
|
|
95
|
+
成功 失败
|
|
96
|
+
│ │
|
|
97
|
+
▼ ▼
|
|
98
|
+
保存 Cookie 提示错误
|
|
99
|
+
onVerified() 重新输入
|
|
167
100
|
```
|
|
168
101
|
|
|
169
|
-
|
|
102
|
+
---
|
|
170
103
|
|
|
171
|
-
##
|
|
104
|
+
## 两种模式
|
|
172
105
|
|
|
173
|
-
|
|
174
|
-
# 安装依赖
|
|
175
|
-
npm install
|
|
106
|
+
### 强制认证 `required: true`(默认)
|
|
176
107
|
|
|
177
|
-
|
|
178
|
-
npm run build
|
|
108
|
+
必须完成认证才能继续,关闭按钮隐藏,点击遮罩无效。
|
|
179
109
|
|
|
180
|
-
# 类型检查
|
|
181
|
-
npm run type-check
|
|
182
110
|
```
|
|
111
|
+
弹窗
|
|
112
|
+
┌──────────────────────────┐
|
|
113
|
+
│ 微信认证 │
|
|
114
|
+
│ │
|
|
115
|
+
│ 1. 扫码关注公众号 │
|
|
116
|
+
│ ┌──────┐ │
|
|
117
|
+
│ │ 二维码 │ │
|
|
118
|
+
│ └──────┘ │
|
|
119
|
+
│ │
|
|
120
|
+
│ 2. 发送"验证码"获取 │
|
|
121
|
+
│ 取消关注公众号后将被 │ ← 新增提示
|
|
122
|
+
│ 取消认证,请保持关注 │
|
|
123
|
+
│ [_][_][_][_][_][_] │
|
|
124
|
+
│ │
|
|
125
|
+
│ [ 验证 ] │
|
|
126
|
+
└──────────────────────────┘
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### 可选认证 `required: false`
|
|
183
130
|
|
|
184
|
-
|
|
131
|
+
用户可主动关闭弹窗,关闭时执行 `onClose` 回调。
|
|
185
132
|
|
|
186
133
|
```
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
↓
|
|
193
|
-
已认证? → 静默通过 → onVerified 回调
|
|
134
|
+
弹窗
|
|
135
|
+
┌──────────────────────────┐
|
|
136
|
+
│ 微信认证 [×] │
|
|
137
|
+
│ ... │
|
|
138
|
+
└──────────────────────────┘
|
|
194
139
|
↓
|
|
195
|
-
|
|
140
|
+
用户点击 × 或遮罩
|
|
196
141
|
↓
|
|
197
|
-
|
|
198
|
-
↓
|
|
199
|
-
公众号自动回复验证码
|
|
200
|
-
↓
|
|
201
|
-
用户输入验证码
|
|
202
|
-
↓
|
|
203
|
-
验证成功 → 保存 Cookie → onVerified 回调
|
|
142
|
+
onClose() → 继续浏览受限内容
|
|
204
143
|
```
|
|
205
144
|
|
|
206
|
-
|
|
145
|
+
---
|
|
207
146
|
|
|
208
|
-
|
|
209
|
-
- **Session**:AES-256-GCM 加密
|
|
210
|
-
- **Cookie**:HttpOnly + SameSite=Lax
|
|
211
|
-
- **防删除**:双重保护机制
|
|
147
|
+
## 功能清单
|
|
212
148
|
|
|
213
|
-
|
|
149
|
+
| 功能 | 支持 |
|
|
150
|
+
|------|------|
|
|
151
|
+
| 自动聚焦第一个输入框 | ✅ |
|
|
152
|
+
| 输入一位自动跳到下一格 | ✅ |
|
|
153
|
+
| 粘贴 6 位数字自动识别 | ✅ |
|
|
154
|
+
| 键盘左右/退格导航 | ✅ |
|
|
155
|
+
| 输入完成自动提交 | ✅ |
|
|
156
|
+
| 有 Cookie 静默认证 | ✅ |
|
|
157
|
+
| F12 删弹窗自动恢复 | ✅ |
|
|
214
158
|
|
|
215
|
-
|
|
159
|
+
---
|
|
216
160
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
}
|
|
223
|
-
});
|
|
161
|
+
## 开发
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
npm install
|
|
165
|
+
npm run build
|
|
224
166
|
```
|
|
225
167
|
|
|
226
|
-
|
|
168
|
+
---
|
|
227
169
|
|
|
228
|
-
|
|
170
|
+
## `silent` 模式:延迟弹窗
|
|
229
171
|
|
|
230
|
-
|
|
231
|
-
WxAuth.init({
|
|
232
|
-
required: true, // 必须认证(也可省略,true 为默认值)
|
|
233
|
-
onVerified: (user) => {
|
|
234
|
-
// 解锁付费内容
|
|
235
|
-
unlockPremiumContent();
|
|
236
|
-
}
|
|
237
|
-
});
|
|
238
|
-
```
|
|
239
|
-
|
|
240
|
-
### 场景 3:可选认证(博客/资讯)
|
|
172
|
+
默认行为下,`init` 遇到未认证会自动弹窗。如果想**自己控制弹窗时机**(比如免费 3 次搜索后再弹),开启 `silent`:
|
|
241
173
|
|
|
242
|
-
```
|
|
174
|
+
```ts
|
|
175
|
+
// 1. 静默初始化:只校验现有 cookie,不调弹窗
|
|
243
176
|
WxAuth.init({
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
enableSocialFeatures();
|
|
248
|
-
},
|
|
249
|
-
onClose: () => {
|
|
250
|
-
// 用户跳过认证,显示受限内容
|
|
251
|
-
showLimitedMode();
|
|
252
|
-
}
|
|
177
|
+
silent: true,
|
|
178
|
+
required: false,
|
|
179
|
+
onVerified: (user) => { /* 标注已认证 */ },
|
|
253
180
|
});
|
|
254
|
-
```
|
|
255
181
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
// 认证成功,继续登录流程
|
|
264
|
-
await login();
|
|
182
|
+
// 2. 业务代码里自由控制弹窗
|
|
183
|
+
// 例:免费搜索 3 次后再要求认证
|
|
184
|
+
let freeSearches = 3;
|
|
185
|
+
async function onSearch() {
|
|
186
|
+
if (freeSearches > 0) {
|
|
187
|
+
freeSearches--;
|
|
188
|
+
doSearch();
|
|
265
189
|
} else {
|
|
266
|
-
//
|
|
267
|
-
|
|
190
|
+
const ok = await WxAuth.requireAuth(); // 手动触发弹窗
|
|
191
|
+
if (ok) doSearch();
|
|
268
192
|
}
|
|
269
193
|
}
|
|
270
194
|
```
|
|
271
195
|
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
async function handleSwitchAccount() {
|
|
277
|
-
// 删除旧 Cookie
|
|
278
|
-
document.cookie = 'wxauth-openid=; path=/; max-age=0';
|
|
279
|
-
// 重新认证
|
|
280
|
-
await WxAuth.requireAuth();
|
|
281
|
-
}
|
|
282
|
-
```
|
|
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
|
-
**状态**: ✅ 生产就绪
|
|
196
|
+
| `silent` | `init()` 行为 | 适用场景 |
|
|
197
|
+
|----------|--------------|---------|
|
|
198
|
+
| `false`(默认) | 需要时自动弹窗 | 付费墙、内测白名单 |
|
|
199
|
+
| `true` | 仅校验 cookie,弹窗由 `requireAuth()` 手动触发 | 免费额度、按需解锁 |
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
export declare const WxAuth: {
|
|
2
2
|
init(options?: Partial<WxAuthConfig>): void;
|
|
3
|
+
/**
|
|
4
|
+
* 静默验证(silent 模式专用)
|
|
5
|
+
* - cookie 有效 → setCookie(token) + onVerified,不调 showAuthModal
|
|
6
|
+
* - cookie 无效 / 不存在 → deleteCookie,不调 showAuthModal
|
|
7
|
+
* - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
|
|
8
|
+
*/
|
|
9
|
+
silentCheck(): Promise<boolean>;
|
|
3
10
|
autoCheck(): Promise<boolean>;
|
|
4
11
|
showAuthModal(): Promise<void>;
|
|
5
12
|
requireAuth(): Promise<boolean>;
|
|
@@ -43,6 +50,7 @@ export declare interface WxAuthConfig {
|
|
|
43
50
|
required?: boolean;
|
|
44
51
|
wechatName?: string;
|
|
45
52
|
qrcodeUrl?: string;
|
|
53
|
+
silent?: boolean;
|
|
46
54
|
}
|
|
47
55
|
|
|
48
56
|
export { }
|
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 s = {
|
|
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
|
-
s.forEach((i) => {
|
|
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)
|
|
15
14
|
if (i.type === "childList")
|
|
16
|
-
i.removedNodes
|
|
17
|
-
if (
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
15
|
+
for (const r of i.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
|
+
}), s.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 (!s.isProtected) return;
|
|
29
|
+
const { getState: o } = e;
|
|
30
|
+
if (!o().isOpen) {
|
|
31
|
+
s.rafId = null;
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const i = document.getElementById(e.modalId);
|
|
35
|
+
(!i || !i.isConnected || l.isHidden(i)) && (console.warn(
|
|
36
|
+
"[WxAuth] 轮询检测到弹窗丢失/隐藏,正在恢复...",
|
|
37
|
+
{ has: !!i, connected: i?.isConnected, hidden: i ? l.isHidden(i) : null }
|
|
38
|
+
), l.safeRestore(e)), s.isProtected && (s.rafId = requestAnimationFrame(t));
|
|
39
|
+
};
|
|
40
|
+
s.rafId = requestAnimationFrame(t), console.log("[WxAuth] 弹窗保护已启用 (MutationObserver + rAF)");
|
|
39
41
|
},
|
|
40
42
|
/**
|
|
41
43
|
* 禁用弹窗保护
|
|
42
44
|
*/
|
|
43
45
|
disable() {
|
|
44
|
-
|
|
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] 弹窗保护已禁用");
|
|
45
47
|
},
|
|
46
48
|
/**
|
|
47
|
-
*
|
|
48
|
-
* @param config 配置选项
|
|
49
|
+
* 同一帧内避免重复恢复
|
|
49
50
|
*/
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
51
|
+
safeRestore(e) {
|
|
52
|
+
if (!s.restorePending) {
|
|
53
|
+
s.restorePending = !0;
|
|
54
|
+
try {
|
|
55
|
+
l.restoreFn(e);
|
|
56
|
+
} finally {
|
|
57
|
+
requestAnimationFrame(() => {
|
|
58
|
+
s.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
|
-
|
|
65
|
-
const { modalId: t, getState: o, onRestore:
|
|
79
|
+
restoreFn(e) {
|
|
80
|
+
const { modalId: t, getState: o, onRestore: i } = 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
|
+
i();
|
|
73
88
|
}
|
|
74
|
-
},
|
|
89
|
+
}, p = {
|
|
75
90
|
apiBase: "https://wx-auth.shenzjd.com",
|
|
76
91
|
// 后端API地址(默认值)
|
|
77
92
|
siteId: "",
|
|
@@ -86,15 +101,17 @@ const c = {
|
|
|
86
101
|
// 是否必须认证(默认强制认证)
|
|
87
102
|
wechatName: "神族九帝",
|
|
88
103
|
// 公众号名称(可选,会自动获取)
|
|
89
|
-
qrcodeUrl: ""
|
|
104
|
+
qrcodeUrl: "",
|
|
90
105
|
// 二维码URL(可选,会自动获取)
|
|
106
|
+
silent: !1
|
|
107
|
+
// 默认不静默
|
|
91
108
|
};
|
|
92
|
-
let n = { ...
|
|
109
|
+
let n = { ...p }, c = {
|
|
93
110
|
isOpen: !1,
|
|
94
111
|
resolveAuth: null,
|
|
95
112
|
currentStep: "qr"
|
|
96
113
|
};
|
|
97
|
-
const
|
|
114
|
+
const d = {
|
|
98
115
|
// 从 apiBase 自动推导根域名(用于跨子域名共享 Cookie)
|
|
99
116
|
// auth.shenzjd.com → .shenzjd.com
|
|
100
117
|
// parse.shenzjd.com → .shenzjd.com
|
|
@@ -119,8 +136,8 @@ const r = {
|
|
|
119
136
|
setCookie(e, t) {
|
|
120
137
|
const o = /* @__PURE__ */ new Date();
|
|
121
138
|
o.setTime(o.getTime() + 365 * 24 * 60 * 60 * 1e3);
|
|
122
|
-
const
|
|
123
|
-
document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${
|
|
139
|
+
const i = this.getRootDomain(), r = i ? `;domain=${i}` : "", h = window.location.protocol === "https:" ? ";Secure" : "";
|
|
140
|
+
document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${r}${h};SameSite=Strict`;
|
|
124
141
|
},
|
|
125
142
|
// 删除Cookie(匹配相同的 domain)
|
|
126
143
|
deleteCookie(e) {
|
|
@@ -178,7 +195,8 @@ const r = {
|
|
|
178
195
|
<!-- 验证码输入区域 -->
|
|
179
196
|
<div>
|
|
180
197
|
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
181
|
-
|
|
198
|
+
<div class="wx-auth-note">取消关注公众号后将被取消认证,请保持关注</div>
|
|
199
|
+
${d.generateCodeInputs()}
|
|
182
200
|
</div>
|
|
183
201
|
|
|
184
202
|
<!-- 消息提示 -->
|
|
@@ -197,18 +215,18 @@ const r = {
|
|
|
197
215
|
setTimeout(() => {
|
|
198
216
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
199
217
|
e.length && e.forEach((t, o) => {
|
|
200
|
-
t.addEventListener("input", (
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
}), t.addEventListener("keydown", (
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
}), t.addEventListener("paste", (
|
|
207
|
-
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
e[
|
|
211
|
-
}),
|
|
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);
|
|
227
|
+
r && (r.split("").forEach((a, h) => {
|
|
228
|
+
e[h] && (e[h].value = a);
|
|
229
|
+
}), r.length === 6 && setTimeout(() => f.verifyCode(), 300));
|
|
212
230
|
});
|
|
213
231
|
});
|
|
214
232
|
}, 100);
|
|
@@ -216,9 +234,9 @@ const r = {
|
|
|
216
234
|
// 显示弹窗
|
|
217
235
|
show() {
|
|
218
236
|
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",
|
|
237
|
+
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), n.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.style.display = "flex", c.isOpen = !0, l.enable({
|
|
220
238
|
modalId: "wx-auth-modal",
|
|
221
|
-
getState: () =>
|
|
239
|
+
getState: () => c,
|
|
222
240
|
onRestore: () => {
|
|
223
241
|
this.createModal(), n.qrcodeUrl && this.setQrCode(n.qrcodeUrl);
|
|
224
242
|
const t = document.querySelector(".wx-auth-wechat-name");
|
|
@@ -232,7 +250,7 @@ const r = {
|
|
|
232
250
|
// 隐藏弹窗
|
|
233
251
|
hide() {
|
|
234
252
|
const e = document.getElementById("wx-auth-modal");
|
|
235
|
-
e && (e.style.display = "none",
|
|
253
|
+
e && (e.style.display = "none", c.isOpen = !1, l.disable());
|
|
236
254
|
},
|
|
237
255
|
// 设置二维码
|
|
238
256
|
setQrCode(e) {
|
|
@@ -257,10 +275,10 @@ const r = {
|
|
|
257
275
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
258
276
|
e.forEach((t) => t.value = ""), e[0] && e[0].focus();
|
|
259
277
|
}
|
|
260
|
-
},
|
|
278
|
+
}, f = {
|
|
261
279
|
// 初始化
|
|
262
280
|
init(e = {}) {
|
|
263
|
-
if (n = { ...
|
|
281
|
+
if (n = { ...p, ...e }, !n.apiBase && typeof window < "u" && (n.apiBase = window.location.origin), !n.apiBase) {
|
|
264
282
|
console.error("[WxAuth] apiBase is required");
|
|
265
283
|
return;
|
|
266
284
|
}
|
|
@@ -274,19 +292,38 @@ const r = {
|
|
|
274
292
|
}
|
|
275
293
|
!n.siteId && window.location.hostname && (n.siteId = window.location.hostname), n.siteId || (n.siteId = "default"), console.log("[WxAuth] 自动获取 siteId:", n.siteId);
|
|
276
294
|
}
|
|
277
|
-
console.log("[WxAuth] SDK initialized", n), typeof window < "u" && this.autoCheck();
|
|
295
|
+
console.log("[WxAuth] SDK initialized", n), typeof window < "u" && (n.silent ? this.silentCheck() : this.autoCheck());
|
|
296
|
+
},
|
|
297
|
+
/**
|
|
298
|
+
* 静默验证(silent 模式专用)
|
|
299
|
+
* - cookie 有效 → setCookie(token) + onVerified,不调 showAuthModal
|
|
300
|
+
* - cookie 无效 / 不存在 → deleteCookie,不调 showAuthModal
|
|
301
|
+
* - 网络错误 → 静默忽略(留给消费者后续 requireAuth 重试)
|
|
302
|
+
*/
|
|
303
|
+
async silentCheck() {
|
|
304
|
+
const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
|
|
305
|
+
if (!(e || t)) return !1;
|
|
306
|
+
const i = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
|
|
307
|
+
try {
|
|
308
|
+
const a = await d.request(
|
|
309
|
+
`${n.apiBase}/api/auth/check?${r}${i}`
|
|
310
|
+
);
|
|
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
|
+
} catch (a) {
|
|
313
|
+
return console.error("[WxAuth] silentCheck 请求失败:", a), !1;
|
|
314
|
+
}
|
|
278
315
|
},
|
|
279
316
|
// 自动检测 Cookie 并验证(内部使用)
|
|
280
317
|
async autoCheck() {
|
|
281
|
-
const e =
|
|
318
|
+
const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
|
|
282
319
|
if (!(e || t))
|
|
283
320
|
return this.showAuthModal(), !1;
|
|
284
|
-
const
|
|
321
|
+
const i = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", r = e ? `token=${encodeURIComponent(e)}` : `openid=${encodeURIComponent(t || "")}`;
|
|
285
322
|
try {
|
|
286
|
-
const a = await
|
|
287
|
-
`${n.apiBase}/api/auth/check?${
|
|
323
|
+
const a = await d.request(
|
|
324
|
+
`${n.apiBase}/api/auth/check?${r}${i}`
|
|
288
325
|
);
|
|
289
|
-
return a.authenticated ? (console.log("[WxAuth] 自动认证成功(Cookie)"), a.token && (
|
|
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);
|
|
290
327
|
} catch (a) {
|
|
291
328
|
return console.error("[WxAuth] 自动验证失败:", a), this.showAuthModal(), !1;
|
|
292
329
|
}
|
|
@@ -295,7 +332,7 @@ const r = {
|
|
|
295
332
|
async showAuthModal() {
|
|
296
333
|
u.show();
|
|
297
334
|
try {
|
|
298
|
-
const t = n.siteId ? `?siteId=${encodeURIComponent(n.siteId)}` : "", o = await
|
|
335
|
+
const t = n.siteId ? `?siteId=${encodeURIComponent(n.siteId)}` : "", o = await d.request(
|
|
299
336
|
`${n.apiBase}/api/sdk/config${t}`
|
|
300
337
|
);
|
|
301
338
|
o.wechatName && !n.wechatName && (n.wechatName = o.wechatName), o.qrcodeUrl && !n.qrcodeUrl && (n.qrcodeUrl = o.qrcodeUrl);
|
|
@@ -311,19 +348,19 @@ const r = {
|
|
|
311
348
|
},
|
|
312
349
|
// 主入口:需要验证时调用
|
|
313
350
|
async requireAuth() {
|
|
314
|
-
const e =
|
|
351
|
+
const e = d.getCookie("wxauth-token"), t = d.getCookie("wxauth-openid");
|
|
315
352
|
if (e || t)
|
|
316
353
|
try {
|
|
317
|
-
const
|
|
318
|
-
`${n.apiBase}/api/auth/check?${
|
|
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}`
|
|
319
356
|
);
|
|
320
357
|
if (a.authenticated)
|
|
321
|
-
return console.log("[WxAuth] 已认证(Cookie)"), a.token && (
|
|
322
|
-
} catch (
|
|
323
|
-
console.error("[WxAuth] Cookie check failed:",
|
|
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);
|
|
324
361
|
}
|
|
325
|
-
return await this.showAuthModal(), new Promise((
|
|
326
|
-
|
|
362
|
+
return await this.showAuthModal(), new Promise((i) => {
|
|
363
|
+
c.resolveAuth = i;
|
|
327
364
|
});
|
|
328
365
|
},
|
|
329
366
|
// 验证验证码
|
|
@@ -338,11 +375,11 @@ const r = {
|
|
|
338
375
|
);
|
|
339
376
|
t && (t.disabled = !0, t.textContent = "验证中...");
|
|
340
377
|
try {
|
|
341
|
-
const o = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "",
|
|
378
|
+
const o = n.siteId ? `&siteId=${encodeURIComponent(n.siteId)}` : "", i = await d.request(
|
|
342
379
|
`${n.apiBase}/api/auth/check?authToken=${e}${o}`
|
|
343
380
|
);
|
|
344
|
-
|
|
345
|
-
this.close(), this.onVerified(
|
|
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);
|
|
346
383
|
}, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
|
|
347
384
|
} catch {
|
|
348
385
|
u.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
|
|
@@ -350,18 +387,18 @@ const r = {
|
|
|
350
387
|
},
|
|
351
388
|
// 关闭弹窗
|
|
352
389
|
close() {
|
|
353
|
-
u.hide(),
|
|
390
|
+
u.hide(), c.resolveAuth && (c.resolveAuth(!1), c.resolveAuth = null), typeof n.onClose == "function" && n.onClose();
|
|
354
391
|
},
|
|
355
392
|
// 验证成功回调
|
|
356
393
|
onVerified(e) {
|
|
357
|
-
console.log("[WxAuth] 验证成功", e), typeof n.onVerified == "function" && n.onVerified(e),
|
|
394
|
+
console.log("[WxAuth] 验证成功", e), typeof n.onVerified == "function" && n.onVerified(e), c.resolveAuth && (c.resolveAuth(!0), c.resolveAuth = null);
|
|
358
395
|
},
|
|
359
396
|
// 错误回调
|
|
360
397
|
onError(e) {
|
|
361
398
|
console.error("[WxAuth] 错误", e), typeof n.onError == "function" && n.onError(e);
|
|
362
399
|
}
|
|
363
400
|
};
|
|
364
|
-
typeof window < "u" && (window.WxAuth =
|
|
401
|
+
typeof window < "u" && (window.WxAuth = Object.freeze(f));
|
|
365
402
|
export {
|
|
366
|
-
|
|
403
|
+
f as WxAuth
|
|
367
404
|
};
|
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:"",silent:!1};let n={...w},c={isOpen:!1,resolveAuth:null,currentStep:"qr"};const r={getRootDomain(){try{const e=new URL(n.apiBase||window.location.origin).hostname;if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return"";const t=e.split(".");return t.length>=2?"."+t.slice(-2).join("."):""}catch{return""}},getCookie(e){const o=`; ${document.cookie}`.split(`; ${e}=`);return o.length===2&&o.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+365*24*60*60*1e3);const i=this.getRootDomain(),s=i?`;domain=${i}`:"",x=window.location.protocol==="https:"?";Secure":"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${s}${x};SameSite=Strict`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o};SameSite=Strict`},async request(e,t={}){try{const o=await fetch(e,{method:t.method||"GET",headers:{"Content-Type":"application/json",...t.headers},body:t.body?JSON.stringify(t.body):null,credentials:"include"});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}catch(o){throw console.error("[WxAuth] Request error:",o),o}},generateCodeInputs(){let e='<div class="wx-auth-inputs">';for(let t=0;t<6;t++)e+=`<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;return e+="</div>",e}},u={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",n.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=n.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
|
|
3
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"&&(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"})}));
|