wx-auth-sdk 1.1.2 → 1.2.1
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 +150 -119
- package/dist/index.d.ts +3 -1
- package/dist/wx-auth.css +1 -1
- package/dist/wx-auth.js +86 -52
- package/dist/wx-auth.umd.js +6 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,51 +15,114 @@ npm install wx-auth-sdk
|
|
|
15
15
|
<script src="https://cdn.example.com/wx-auth.umd.js"></script>
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
## 🚀
|
|
18
|
+
## 🚀 极简接入
|
|
19
|
+
|
|
20
|
+
### 零配置接入(推荐)
|
|
21
|
+
|
|
22
|
+
**什么都不用配置,一行代码即可完成接入!**
|
|
19
23
|
|
|
20
|
-
### ES Module
|
|
21
24
|
```typescript
|
|
22
25
|
import { WxAuth } from 'wx-auth-sdk';
|
|
23
26
|
import 'wx-auth-sdk/dist/style.css';
|
|
24
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
|
+
### 自定义配置
|
|
44
|
+
|
|
45
|
+
如果需要手动指定配置(可选):
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
25
48
|
WxAuth.init({
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
// wechatName 和 qrcodeUrl 会自动从后端获取,也可以手动指定
|
|
49
|
+
siteId: 'my-website', // ← 可选:手动指定站点 ID(不填则自动获取)
|
|
50
|
+
required: false, // ← 可选:认证模式(默认 true)
|
|
29
51
|
onVerified: (user) => {
|
|
30
52
|
console.log('认证成功', user);
|
|
31
53
|
},
|
|
32
|
-
|
|
33
|
-
console.
|
|
54
|
+
onClose: () => {
|
|
55
|
+
console.log('用户关闭了认证弹窗');
|
|
34
56
|
}
|
|
35
57
|
});
|
|
36
58
|
```
|
|
37
59
|
|
|
38
|
-
###
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
+
});
|
|
51
77
|
```
|
|
52
78
|
|
|
53
|
-
|
|
79
|
+
**特点:**
|
|
80
|
+
- ❌ 不显示关闭按钮
|
|
81
|
+
- ❌ 点击遮罩层无效
|
|
82
|
+
- ✅ 必须完成认证才能继续操作
|
|
83
|
+
|
|
84
|
+
#### 可选认证模式
|
|
85
|
+
|
|
86
|
+
适用于**博客、资讯、社区**等场景,用户可以选择跳过认证:
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
WxAuth.init({
|
|
90
|
+
siteId: 'my-blog',
|
|
91
|
+
required: false, // 可选认证
|
|
92
|
+
onVerified: (user) => {
|
|
93
|
+
console.log('认证成功', user);
|
|
94
|
+
// 解锁评论、点赞等功能
|
|
95
|
+
},
|
|
96
|
+
onClose: () => {
|
|
97
|
+
console.log('用户关闭了认证弹窗');
|
|
98
|
+
// 处理关闭后的逻辑,如显示受限模式
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
**特点:**
|
|
104
|
+
- ✅ 显示关闭按钮(右上角 ×)
|
|
105
|
+
- ✅ 点击遮罩可关闭弹窗
|
|
106
|
+
- ✅ 关闭时触发 `onClose` 回调
|
|
107
|
+
|
|
108
|
+
## ⚙️ 配置说明
|
|
54
109
|
|
|
55
110
|
| 参数 | 类型 | 必填 | 说明 |
|
|
56
111
|
|------|------|------|------|
|
|
57
|
-
| `
|
|
58
|
-
| `
|
|
59
|
-
| `
|
|
60
|
-
| `qrcodeUrl` | `string` | ❌ | 二维码图片 URL(可选,自动从后端获取) |
|
|
112
|
+
| `siteId` | `string` | ❌ | **站点唯一标识**(可选,自动从 referrer/域名获取) |
|
|
113
|
+
| `apiBase` | `string` | ❌ | 后端 API 地址(**默认值已配置**,可省略) |
|
|
114
|
+
| `required` | `boolean` | ❌ | 是否必须认证(默认 `true`,强制认证) |
|
|
61
115
|
| `onVerified` | `(user) => void` | ❌ | 验证成功回调 |
|
|
62
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
|
+
|
|
63
126
|
|
|
64
127
|
## 🔧 API 方法
|
|
65
128
|
|
|
@@ -79,78 +142,9 @@ WxAuth.init({
|
|
|
79
142
|
### `WxAuth.close()`
|
|
80
143
|
关闭认证弹窗。
|
|
81
144
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
### 双重检测机制
|
|
87
|
-
|
|
88
|
-
1. **MutationObserver(实时检测)**
|
|
89
|
-
- 监听 DOM 变化
|
|
90
|
-
- 响应时间:< 100ms
|
|
91
|
-
- 检测场景:`remove()`、`style.display='none'`、`innerHTML=''`
|
|
92
|
-
|
|
93
|
-
2. **定时器兜底(每秒检查)**
|
|
94
|
-
- 每秒检查一次弹窗状态
|
|
95
|
-
- 最大延迟:1 秒
|
|
96
|
-
- 防止 MutationObserver 被绕过
|
|
97
|
-
|
|
98
|
-
### 保护流程
|
|
99
|
-
```
|
|
100
|
-
启用保护 → MutationObserver 监听 → 检测到攻击?→ 立即恢复(< 100ms)
|
|
101
|
-
↓
|
|
102
|
-
定时器检查(每秒) → 检测到异常?→ 恢复(≤ 1000ms)
|
|
103
|
-
```
|
|
104
|
-
|
|
105
|
-
## 📋 后端 API 要求
|
|
106
|
-
|
|
107
|
-
SDK 需要以下后端 API 端点:
|
|
108
|
-
|
|
109
|
-
### 1. SDK 配置获取(可选,推荐)
|
|
110
|
-
```
|
|
111
|
-
GET /api/sdk/config?siteId={siteId}
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
**响应:**
|
|
115
|
-
```json
|
|
116
|
-
{
|
|
117
|
-
"wechatName": "公众号名称",
|
|
118
|
-
"qrcodeUrl": "https://example.com/qrcode.jpg",
|
|
119
|
-
"codeLength": 6
|
|
120
|
-
}
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
> 当 `wechatName` 和 `qrcodeUrl` 未在 `init()` 中手动指定时,SDK 会自动从该接口获取。
|
|
124
|
-
|
|
125
|
-
### 2. 认证检查
|
|
126
|
-
```
|
|
127
|
-
GET /api/auth/check?authToken={code}&siteId={siteId} // 通过验证码验证
|
|
128
|
-
GET /api/auth/check?openid={openid}&siteId={siteId} // 通过 OpenID 验证
|
|
129
|
-
```
|
|
130
|
-
|
|
131
|
-
**响应:**
|
|
132
|
-
```json
|
|
133
|
-
{
|
|
134
|
-
"authenticated": true,
|
|
135
|
-
"user": {
|
|
136
|
-
"openid": "oxxx...",
|
|
137
|
-
"nickname": "用户昵称",
|
|
138
|
-
"headimgurl": "头像URL"
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
```
|
|
142
|
-
|
|
143
|
-
### 2. Session 管理
|
|
144
|
-
```
|
|
145
|
-
POST /api/auth/session // 创建 Session
|
|
146
|
-
GET /api/auth/session // 获取 Session
|
|
147
|
-
DELETE /api/auth/session // 删除 Session
|
|
148
|
-
```
|
|
149
|
-
|
|
150
|
-
### 3. 微信消息处理
|
|
151
|
-
```
|
|
152
|
-
POST /api/wechat/message // 微信消息接收/回复
|
|
153
|
-
```
|
|
145
|
+
**场景:**
|
|
146
|
+
- 用户手动关闭弹窗 → 触发 `onClose` 回调
|
|
147
|
+
- 调用 `requireAuth()` 后关闭 → Promise resolve(false)
|
|
154
148
|
|
|
155
149
|
## 🎨 用户体验特性
|
|
156
150
|
|
|
@@ -159,6 +153,7 @@ POST /api/wechat/message // 微信消息接收/回复
|
|
|
159
153
|
- ✅ **键盘导航** - 支持退格、方向键
|
|
160
154
|
- ✅ **自动验证** - 输入完成自动提交
|
|
161
155
|
- ✅ **静默认证** - 有 Cookie 时不显示弹窗
|
|
156
|
+
- ✅ **灵活认证** - 支持强制/可选认证模式
|
|
162
157
|
- ✅ **防删除保护** - MutationObserver + 定时器
|
|
163
158
|
|
|
164
159
|
## 📦 构建产物
|
|
@@ -177,13 +172,13 @@ dist/
|
|
|
177
172
|
|
|
178
173
|
```bash
|
|
179
174
|
# 安装依赖
|
|
180
|
-
|
|
175
|
+
npm install
|
|
181
176
|
|
|
182
177
|
# 构建 SDK
|
|
183
|
-
|
|
178
|
+
npm run build
|
|
184
179
|
|
|
185
180
|
# 类型检查
|
|
186
|
-
|
|
181
|
+
npm run type-check
|
|
187
182
|
```
|
|
188
183
|
|
|
189
184
|
## 📝 认证流程
|
|
@@ -199,7 +194,7 @@ SDK 初始化
|
|
|
199
194
|
↓
|
|
200
195
|
未认证? → 显示弹窗(二维码 + 6位输入框)
|
|
201
196
|
↓
|
|
202
|
-
|
|
197
|
+
用户扫码关注公众号(神族九帝)
|
|
203
198
|
↓
|
|
204
199
|
公众号自动回复验证码
|
|
205
200
|
↓
|
|
@@ -215,39 +210,75 @@ SDK 初始化
|
|
|
215
210
|
- **Cookie**:HttpOnly + SameSite=Lax
|
|
216
211
|
- **防删除**:双重保护机制
|
|
217
212
|
|
|
218
|
-
##
|
|
213
|
+
## 💡 使用场景
|
|
214
|
+
|
|
215
|
+
### 场景 1:零配置接入(推荐)
|
|
219
216
|
|
|
220
|
-
### 1. 独立网站集成
|
|
221
217
|
```typescript
|
|
222
|
-
|
|
218
|
+
// ✅ 什么都不用配置,一行代码即可
|
|
219
|
+
WxAuth.init({
|
|
220
|
+
onVerified: (user) => {
|
|
221
|
+
console.log('认证成功', user);
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
SDK 会自动获取 `siteId`、`apiBase`、公众号名称和二维码。
|
|
227
|
+
|
|
228
|
+
### 场景 2:强制认证(内容付费)
|
|
223
229
|
|
|
230
|
+
```typescript
|
|
224
231
|
WxAuth.init({
|
|
225
|
-
|
|
226
|
-
siteId: 'my-blog', // 标识你的网站
|
|
232
|
+
required: true, // 必须认证(也可省略,true 为默认值)
|
|
227
233
|
onVerified: (user) => {
|
|
228
|
-
//
|
|
229
|
-
|
|
234
|
+
// 解锁付费内容
|
|
235
|
+
unlockPremiumContent();
|
|
230
236
|
}
|
|
231
237
|
});
|
|
232
238
|
```
|
|
233
239
|
|
|
234
|
-
###
|
|
240
|
+
### 场景 3:可选认证(博客/资讯)
|
|
241
|
+
|
|
235
242
|
```typescript
|
|
236
|
-
|
|
237
|
-
|
|
243
|
+
WxAuth.init({
|
|
244
|
+
required: false, // 可选认证
|
|
245
|
+
onVerified: (user) => {
|
|
246
|
+
// 解锁评论、点赞等功能
|
|
247
|
+
enableSocialFeatures();
|
|
248
|
+
},
|
|
249
|
+
onClose: () => {
|
|
250
|
+
// 用户跳过认证,显示受限内容
|
|
251
|
+
showLimitedMode();
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
### 场景 3:按需触发认证
|
|
257
|
+
|
|
258
|
+
```typescript
|
|
259
|
+
// 用户点击"登录"或"切换账号"时触发
|
|
260
|
+
async function handleLogin() {
|
|
238
261
|
const success = await WxAuth.requireAuth();
|
|
239
262
|
if (success) {
|
|
240
|
-
//
|
|
263
|
+
// 认证成功,继续登录流程
|
|
264
|
+
await login();
|
|
265
|
+
} else {
|
|
266
|
+
// 用户关闭弹窗,取消登录
|
|
267
|
+
console.log('用户取消认证');
|
|
241
268
|
}
|
|
242
|
-
}
|
|
269
|
+
}
|
|
243
270
|
```
|
|
244
271
|
|
|
245
|
-
###
|
|
272
|
+
### 场景 4:切换账号
|
|
273
|
+
|
|
246
274
|
```typescript
|
|
247
|
-
// 用户点击"切换账号"
|
|
248
|
-
|
|
275
|
+
// 用户点击"切换账号"时触发
|
|
276
|
+
async function handleSwitchAccount() {
|
|
277
|
+
// 删除旧 Cookie
|
|
278
|
+
document.cookie = 'wxauth-openid=; path=/; max-age=0';
|
|
279
|
+
// 重新认证
|
|
249
280
|
await WxAuth.requireAuth();
|
|
250
|
-
}
|
|
281
|
+
}
|
|
251
282
|
```
|
|
252
283
|
|
|
253
284
|
## 📚 完整文档
|
|
@@ -269,6 +300,6 @@ MIT License
|
|
|
269
300
|
|
|
270
301
|
---
|
|
271
302
|
|
|
272
|
-
**版本**: 1.
|
|
273
|
-
**构建时间**: 2025-
|
|
303
|
+
**版本**: 1.2.0
|
|
304
|
+
**构建时间**: 2025-06-28
|
|
274
305
|
**状态**: ✅ 生产就绪
|
package/dist/index.d.ts
CHANGED
|
@@ -27,7 +27,7 @@ export declare const WxAuth: {
|
|
|
27
27
|
*
|
|
28
28
|
* 2. 初始化
|
|
29
29
|
* WxAuth.init({
|
|
30
|
-
* apiBase: 'https://
|
|
30
|
+
* apiBase: 'https://wx-auth.shenzjd.com',
|
|
31
31
|
* onVerified: (user) => { console.log('验证通过', user); }
|
|
32
32
|
* });
|
|
33
33
|
*
|
|
@@ -39,6 +39,8 @@ export declare interface WxAuthConfig {
|
|
|
39
39
|
siteId?: string;
|
|
40
40
|
onVerified?: ((user: any) => void) | null;
|
|
41
41
|
onError?: ((error: any) => void) | null;
|
|
42
|
+
onClose?: (() => void) | null;
|
|
43
|
+
required?: boolean;
|
|
42
44
|
wechatName?: string;
|
|
43
45
|
qrcodeUrl?: string;
|
|
44
46
|
}
|
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:16px;font-weight:500}.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}}
|
|
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:16px;font-weight:500}.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-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}.wx-auth-optional .wx-auth-desc:after{content:"(可点击右上角关闭)";display:block;font-size:12px;color:#999;margin-top:4px;font-weight:400}
|
package/dist/wx-auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const r = {
|
|
2
2
|
observer: null,
|
|
3
3
|
healthCheckTimer: null,
|
|
4
4
|
isProtected: !1
|
|
@@ -8,12 +8,12 @@ const n = {
|
|
|
8
8
|
* @param config 配置选项
|
|
9
9
|
*/
|
|
10
10
|
enable(e) {
|
|
11
|
-
if (
|
|
11
|
+
if (r.isProtected || typeof window > "u") return;
|
|
12
12
|
const { modalId: t, getState: o } = e;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
if (
|
|
16
|
-
|
|
13
|
+
r.observer = new MutationObserver((i) => {
|
|
14
|
+
i.forEach((n) => {
|
|
15
|
+
if (n.type === "childList")
|
|
16
|
+
n.removedNodes.forEach((c) => {
|
|
17
17
|
if (c.nodeType === Node.ELEMENT_NODE) {
|
|
18
18
|
const d = c;
|
|
19
19
|
(d.id === t || d.querySelector?.(`#${t}`)) && (console.warn(
|
|
@@ -21,27 +21,27 @@ const n = {
|
|
|
21
21
|
), this.restore(e));
|
|
22
22
|
}
|
|
23
23
|
});
|
|
24
|
-
else if (
|
|
25
|
-
const c =
|
|
26
|
-
c.id === t &&
|
|
24
|
+
else if (n.type === "attributes") {
|
|
25
|
+
const c = n.target;
|
|
26
|
+
c.id === t && n.attributeName === "style" && c.style.display === "none" && o().isOpen && (console.warn(
|
|
27
27
|
"[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."
|
|
28
28
|
), c.style.display = "flex");
|
|
29
29
|
}
|
|
30
30
|
});
|
|
31
|
-
}),
|
|
31
|
+
}), r.observer.observe(document.body, {
|
|
32
32
|
childList: !0,
|
|
33
33
|
subtree: !0,
|
|
34
34
|
attributes: !0,
|
|
35
35
|
attributeFilter: ["style"]
|
|
36
|
-
}),
|
|
36
|
+
}), r.healthCheckTimer = window.setInterval(() => {
|
|
37
37
|
this.healthCheck(e);
|
|
38
|
-
}, 1e3),
|
|
38
|
+
}, 1e3), r.isProtected = !0, console.log("[WxAuth] 弹窗保护已启用");
|
|
39
39
|
},
|
|
40
40
|
/**
|
|
41
41
|
* 禁用弹窗保护
|
|
42
42
|
*/
|
|
43
43
|
disable() {
|
|
44
|
-
|
|
44
|
+
r.observer && (r.observer.disconnect(), r.observer = null), r.healthCheckTimer && (clearInterval(r.healthCheckTimer), r.healthCheckTimer = null), r.isProtected = !1, console.log("[WxAuth] 弹窗保护已禁用");
|
|
45
45
|
},
|
|
46
46
|
/**
|
|
47
47
|
* 健康检查(定时器调用)
|
|
@@ -50,37 +50,41 @@ const n = {
|
|
|
50
50
|
healthCheck(e) {
|
|
51
51
|
const { modalId: t, getState: o } = e;
|
|
52
52
|
if (!o().isOpen) return;
|
|
53
|
-
const
|
|
54
|
-
if (!
|
|
53
|
+
const i = document.getElementById(t);
|
|
54
|
+
if (!i) {
|
|
55
55
|
console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."), this.restore(e);
|
|
56
56
|
return;
|
|
57
57
|
}
|
|
58
|
-
|
|
58
|
+
i.style.display === "none" && (console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."), i.style.display = "flex");
|
|
59
59
|
},
|
|
60
60
|
/**
|
|
61
61
|
* 恢复弹窗
|
|
62
62
|
* @param config 配置选项
|
|
63
63
|
*/
|
|
64
64
|
restore(e) {
|
|
65
|
-
const { modalId: t, getState: o, onRestore:
|
|
65
|
+
const { modalId: t, getState: o, onRestore: i } = e;
|
|
66
66
|
if (!o().isOpen) return;
|
|
67
|
-
const
|
|
68
|
-
if (
|
|
69
|
-
|
|
67
|
+
const n = document.getElementById(t);
|
|
68
|
+
if (n) {
|
|
69
|
+
n.style.display = "flex";
|
|
70
70
|
return;
|
|
71
71
|
}
|
|
72
|
-
|
|
72
|
+
i();
|
|
73
73
|
}
|
|
74
74
|
}, p = {
|
|
75
|
-
apiBase: "",
|
|
76
|
-
// 后端API
|
|
75
|
+
apiBase: "https://wx-auth.shenzjd.com",
|
|
76
|
+
// 后端API地址(默认值)
|
|
77
77
|
siteId: "",
|
|
78
78
|
// 站点标识(可选,用于区分来源网站)
|
|
79
79
|
onVerified: null,
|
|
80
80
|
// 验证成功回调
|
|
81
81
|
onError: null,
|
|
82
82
|
// 错误回调
|
|
83
|
-
|
|
83
|
+
onClose: null,
|
|
84
|
+
// 关闭弹窗回调(仅在 required=false 时触发)
|
|
85
|
+
required: !0,
|
|
86
|
+
// 是否必须认证(默认强制认证)
|
|
87
|
+
wechatName: "神族九帝",
|
|
84
88
|
// 公众号名称(可选,会自动获取)
|
|
85
89
|
qrcodeUrl: ""
|
|
86
90
|
// 二维码URL(可选,会自动获取)
|
|
@@ -91,19 +95,37 @@ let s = { ...p }, a = {
|
|
|
91
95
|
currentStep: "qr"
|
|
92
96
|
};
|
|
93
97
|
const l = {
|
|
98
|
+
// 从 apiBase 自动推导根域名(用于跨子域名共享 Cookie)
|
|
99
|
+
// auth.shenzjd.com → .shenzjd.com
|
|
100
|
+
// parse.shenzjd.com → .shenzjd.com
|
|
101
|
+
// localhost / 127.0.0.1 / IP → 不设置 domain
|
|
102
|
+
getRootDomain() {
|
|
103
|
+
try {
|
|
104
|
+
const e = new URL(s.apiBase || window.location.origin).hostname;
|
|
105
|
+
if (e === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(e))
|
|
106
|
+
return "";
|
|
107
|
+
const t = e.split(".");
|
|
108
|
+
return t.length >= 2 ? "." + t.slice(-2).join(".") : "";
|
|
109
|
+
} catch {
|
|
110
|
+
return "";
|
|
111
|
+
}
|
|
112
|
+
},
|
|
94
113
|
// 获取Cookie
|
|
95
114
|
getCookie(e) {
|
|
96
115
|
const o = `; ${document.cookie}`.split(`; ${e}=`);
|
|
97
116
|
return o.length === 2 && o.pop()?.split(";").shift() || null;
|
|
98
117
|
},
|
|
99
|
-
// 设置Cookie(30
|
|
118
|
+
// 设置Cookie(30天过期,自动设置根域名实现跨子域共享)
|
|
100
119
|
setCookie(e, t) {
|
|
101
120
|
const o = /* @__PURE__ */ new Date();
|
|
102
|
-
o.setTime(o.getTime() + 720 * 60 * 60 * 1e3)
|
|
121
|
+
o.setTime(o.getTime() + 720 * 60 * 60 * 1e3);
|
|
122
|
+
const i = this.getRootDomain(), n = i ? `;domain=${i}` : "";
|
|
123
|
+
document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/${n}`;
|
|
103
124
|
},
|
|
104
|
-
// 删除Cookie
|
|
125
|
+
// 删除Cookie(匹配相同的 domain)
|
|
105
126
|
deleteCookie(e) {
|
|
106
|
-
|
|
127
|
+
const t = this.getRootDomain(), o = t ? `;domain=${t}` : "";
|
|
128
|
+
document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}`;
|
|
107
129
|
},
|
|
108
130
|
// 发送请求
|
|
109
131
|
async request(e, t = {}) {
|
|
@@ -135,17 +157,19 @@ const l = {
|
|
|
135
157
|
// 创建弹窗
|
|
136
158
|
createModal() {
|
|
137
159
|
const e = document.createElement("div");
|
|
138
|
-
|
|
139
|
-
|
|
160
|
+
e.id = "wx-auth-modal", e.className = "wx-auth-modal", s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional");
|
|
161
|
+
const t = s.required ? "" : '<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';
|
|
162
|
+
return e.innerHTML = `
|
|
163
|
+
<div class="wx-auth-overlay" ${s.required ? 'onclick="event.preventDefault()"' : ""}></div>
|
|
140
164
|
<div class="wx-auth-content">
|
|
141
165
|
<div class="wx-auth-header">
|
|
142
166
|
<div class="wx-auth-title">微信认证</div>
|
|
143
|
-
|
|
167
|
+
${t}
|
|
144
168
|
</div>
|
|
145
169
|
<div class="wx-auth-body">
|
|
146
170
|
<!-- 二维码区域 -->
|
|
147
171
|
<div>
|
|
148
|
-
<div class="wx-auth-desc">1.
|
|
172
|
+
<div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
|
|
149
173
|
<div class="wx-auth-qrcode-container">
|
|
150
174
|
<img class="wx-auth-qrcode" src="" alt="扫码关注" />
|
|
151
175
|
</div>
|
|
@@ -173,18 +197,18 @@ const l = {
|
|
|
173
197
|
setTimeout(() => {
|
|
174
198
|
const e = document.querySelectorAll(".wx-auth-input");
|
|
175
199
|
e.length && e.forEach((t, o) => {
|
|
176
|
-
t.addEventListener("input", (
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
}), t.addEventListener("keydown", (
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
}), t.addEventListener("paste", (
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
|
|
200
|
+
t.addEventListener("input", (i) => {
|
|
201
|
+
const n = i.target.value.replace(/\D/g, "");
|
|
202
|
+
i.target.value = n, n && o < 5 && e[o + 1].focus(), o === 5 && n && setTimeout(() => h.verifyCode(), 300);
|
|
203
|
+
}), t.addEventListener("keydown", (i) => {
|
|
204
|
+
const n = i.target;
|
|
205
|
+
i.key === "Backspace" && !n.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());
|
|
206
|
+
}), t.addEventListener("paste", (i) => {
|
|
207
|
+
i.preventDefault();
|
|
208
|
+
const n = i.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
209
|
+
n && (n.split("").forEach((c, d) => {
|
|
186
210
|
e[d] && (e[d].value = c);
|
|
187
|
-
}),
|
|
211
|
+
}), n.length === 6 && setTimeout(() => h.verifyCode(), 300));
|
|
188
212
|
});
|
|
189
213
|
});
|
|
190
214
|
}, 100);
|
|
@@ -192,13 +216,13 @@ const l = {
|
|
|
192
216
|
// 显示弹窗
|
|
193
217
|
show() {
|
|
194
218
|
let e = document.getElementById("wx-auth-modal");
|
|
195
|
-
e
|
|
219
|
+
e ? (e.classList.remove("wx-auth-required", "wx-auth-optional"), s.required ? e.classList.add("wx-auth-required") : e.classList.add("wx-auth-optional")) : e = this.createModal(), e.style.display = "flex", a.isOpen = !0, f.enable({
|
|
196
220
|
modalId: "wx-auth-modal",
|
|
197
221
|
getState: () => a,
|
|
198
222
|
onRestore: () => {
|
|
199
223
|
this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
|
|
200
|
-
const t = document.querySelector(".wx-auth-
|
|
201
|
-
t && s.wechatName && (t.textContent = `
|
|
224
|
+
const t = document.querySelector(".wx-auth-wechat-name");
|
|
225
|
+
t && s.wechatName && (t.textContent = `"${s.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
|
|
202
226
|
const o = document.querySelector(".wx-auth-input");
|
|
203
227
|
o && o.focus();
|
|
204
228
|
}, 100);
|
|
@@ -240,6 +264,16 @@ const l = {
|
|
|
240
264
|
console.error("[WxAuth] apiBase is required");
|
|
241
265
|
return;
|
|
242
266
|
}
|
|
267
|
+
if (!s.siteId && typeof window < "u") {
|
|
268
|
+
const t = document.referrer;
|
|
269
|
+
if (t)
|
|
270
|
+
try {
|
|
271
|
+
const o = new URL(t);
|
|
272
|
+
s.siteId = o.hostname;
|
|
273
|
+
} catch {
|
|
274
|
+
}
|
|
275
|
+
!s.siteId && window.location.hostname && (s.siteId = window.location.hostname), s.siteId || (s.siteId = "default"), console.log("[WxAuth] 自动获取 siteId:", s.siteId);
|
|
276
|
+
}
|
|
243
277
|
console.log("[WxAuth] SDK initialized", s), typeof window < "u" && this.autoCheck();
|
|
244
278
|
},
|
|
245
279
|
// 自动检测 Cookie 并验证(内部使用)
|
|
@@ -269,8 +303,8 @@ const l = {
|
|
|
269
303
|
console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
|
|
270
304
|
}
|
|
271
305
|
s.qrcodeUrl && u.setQrCode(s.qrcodeUrl);
|
|
272
|
-
const e = document.querySelector(".wx-auth-
|
|
273
|
-
e && s.wechatName && (e.textContent = `
|
|
306
|
+
const e = document.querySelector(".wx-auth-wechat-name");
|
|
307
|
+
e && s.wechatName && (e.textContent = `"${s.wechatName}"`), setTimeout(() => {
|
|
274
308
|
const t = document.querySelector(".wx-auth-input");
|
|
275
309
|
t && t.focus();
|
|
276
310
|
}, 100);
|
|
@@ -304,11 +338,11 @@ const l = {
|
|
|
304
338
|
);
|
|
305
339
|
t && (t.disabled = !0, t.textContent = "验证中...");
|
|
306
340
|
try {
|
|
307
|
-
const o = s.siteId ? `&siteId=${encodeURIComponent(s.siteId)}` : "",
|
|
341
|
+
const o = s.siteId ? `&siteId=${encodeURIComponent(s.siteId)}` : "", i = await l.request(
|
|
308
342
|
`${s.apiBase}/api/auth/check?authToken=${e}${o}`
|
|
309
343
|
);
|
|
310
|
-
|
|
311
|
-
this.close(), this.onVerified(
|
|
344
|
+
i.authenticated ? (i.user && i.user.openid && l.setCookie("wxauth-openid", i.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
|
|
345
|
+
this.close(), this.onVerified(i.user);
|
|
312
346
|
}, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
|
|
313
347
|
} catch {
|
|
314
348
|
u.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
|
|
@@ -316,7 +350,7 @@ const l = {
|
|
|
316
350
|
},
|
|
317
351
|
// 关闭弹窗
|
|
318
352
|
close() {
|
|
319
|
-
u.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null);
|
|
353
|
+
u.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null), typeof s.onClose == "function" && s.onClose();
|
|
320
354
|
},
|
|
321
355
|
// 验证成功回调
|
|
322
356
|
onVerified(e) {
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
(function(l,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(l=typeof globalThis<"u"?globalThis:l||self,h(l.WxAuthSDK={}))})(this,(function(l){"use strict";var h=document.createElement("style");h.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:16px;font-weight:500}.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}}
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(h);const s={observer:null,healthCheckTimer:null,isProtected:!1},x={enable(e){if(s.isProtected||typeof window>"u")return;const{modalId:t,getState:o}=e;s.observer=new MutationObserver(i=>{i.forEach(a=>{if(a.type==="childList")a.removedNodes.forEach(u=>{if(u.nodeType===Node.ELEMENT_NODE){const p=u;(p.id===t||p.querySelector?.(`#${t}`))&&(console.warn("[WxAuth] 检测到弹窗被删除,正在自动恢复..."),this.restore(e))}});else if(a.type==="attributes"){const u=a.target;u.id===t&&a.attributeName==="style"&&u.style.display==="none"&&o().isOpen&&(console.warn("[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."),u.style.display="flex")}})}),s.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}),s.healthCheckTimer=window.setInterval(()=>{this.healthCheck(e)},1e3),s.isProtected=!0,console.log("[WxAuth] 弹窗保护已启用")},disable(){s.observer&&(s.observer.disconnect(),s.observer=null),s.healthCheckTimer&&(clearInterval(s.healthCheckTimer),s.healthCheckTimer=null),s.isProtected=!1,console.log("[WxAuth] 弹窗保护已禁用")},healthCheck(e){const{modalId:t,getState:o}=e;if(!o().isOpen)return;const i=document.getElementById(t);if(!i){console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."),this.restore(e);return}i.style.display==="none"&&(console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."),i.style.display="flex")},restore(e){const{modalId:t,getState:o,onRestore:i}=e;if(!o().isOpen)return;const a=document.getElementById(t);if(a){a.style.display="flex";return}i()}},w={apiBase:"",siteId:"",onVerified:null,onError:null,wechatName:"
|
|
3
|
-
<div class="wx-auth-overlay"></div>
|
|
1
|
+
(function(l,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(l=typeof globalThis<"u"?globalThis:l||self,h(l.WxAuthSDK={}))})(this,(function(l){"use strict";var h=document.createElement("style");h.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:16px;font-weight:500}.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-required .wx-auth-close{display:none!important}.wx-auth-optional .wx-auth-overlay{cursor:pointer}.wx-auth-optional .wx-auth-desc:after{content:"(可点击右上角关闭)";display:block;font-size:12px;color:#999;margin-top:4px;font-weight:400}
|
|
2
|
+
/*$vite$:1*/`,document.head.appendChild(h);const s={observer:null,healthCheckTimer:null,isProtected:!1},x={enable(e){if(s.isProtected||typeof window>"u")return;const{modalId:t,getState:o}=e;s.observer=new MutationObserver(i=>{i.forEach(a=>{if(a.type==="childList")a.removedNodes.forEach(u=>{if(u.nodeType===Node.ELEMENT_NODE){const p=u;(p.id===t||p.querySelector?.(`#${t}`))&&(console.warn("[WxAuth] 检测到弹窗被删除,正在自动恢复..."),this.restore(e))}});else if(a.type==="attributes"){const u=a.target;u.id===t&&a.attributeName==="style"&&u.style.display==="none"&&o().isOpen&&(console.warn("[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."),u.style.display="flex")}})}),s.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}),s.healthCheckTimer=window.setInterval(()=>{this.healthCheck(e)},1e3),s.isProtected=!0,console.log("[WxAuth] 弹窗保护已启用")},disable(){s.observer&&(s.observer.disconnect(),s.observer=null),s.healthCheckTimer&&(clearInterval(s.healthCheckTimer),s.healthCheckTimer=null),s.isProtected=!1,console.log("[WxAuth] 弹窗保护已禁用")},healthCheck(e){const{modalId:t,getState:o}=e;if(!o().isOpen)return;const i=document.getElementById(t);if(!i){console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."),this.restore(e);return}i.style.display==="none"&&(console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."),i.style.display="flex")},restore(e){const{modalId:t,getState:o,onRestore:i}=e;if(!o().isOpen)return;const a=document.getElementById(t);if(a){a.style.display="flex";return}i()}},w={apiBase:"https://wx-auth.shenzjd.com",siteId:"",onVerified:null,onError:null,onClose:null,required:!0,wechatName:"神族九帝",qrcodeUrl:""};let n={...w},r={isOpen:!1,resolveAuth:null,currentStep:"qr"};const d={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()+720*60*60*1e3);const i=this.getRootDomain(),a=i?`;domain=${i}`:"";document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/${a}`},deleteCookie(e){const t=this.getRootDomain(),o=t?`;domain=${t}`:"";document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${o}`},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}},c={createModal(){const e=document.createElement("div");e.id="wx-auth-modal",e.className="wx-auth-modal",n.required?e.classList.add("wx-auth-required"):e.classList.add("wx-auth-optional");const t=n.required?"":'<button class="wx-auth-close" onclick="WxAuth.close()">×</button>';return e.innerHTML=`
|
|
3
|
+
<div class="wx-auth-overlay" ${n.required?'onclick="event.preventDefault()"':""}></div>
|
|
4
4
|
<div class="wx-auth-content">
|
|
5
5
|
<div class="wx-auth-header">
|
|
6
6
|
<div class="wx-auth-title">微信认证</div>
|
|
7
|
-
|
|
7
|
+
${t}
|
|
8
8
|
</div>
|
|
9
9
|
<div class="wx-auth-body">
|
|
10
10
|
<!-- 二维码区域 -->
|
|
11
11
|
<div>
|
|
12
|
-
<div class="wx-auth-desc">1.
|
|
12
|
+
<div class="wx-auth-desc">1. 微信关注公众号 <span class="wx-auth-wechat-name"></span></div>
|
|
13
13
|
<div class="wx-auth-qrcode-container">
|
|
14
14
|
<img class="wx-auth-qrcode" src="" alt="扫码关注" />
|
|
15
15
|
</div>
|
|
@@ -30,4 +30,4 @@
|
|
|
30
30
|
</div>
|
|
31
31
|
</div>
|
|
32
32
|
</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 a=i.target.value.replace(/\D/g,"");i.target.value=a,a&&o<5&&e[o+1].focus(),o===5&&a&&setTimeout(()=>f.verifyCode(),300)}),t.addEventListener("keydown",i=>{const a=i.target;i.key==="Backspace"&&!a.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 a=i.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);a&&(a.split("").forEach((u,p)=>{e[p]&&(e[p].value=u)}),a.length===6&&setTimeout(()=>f.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e
|
|
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 a=i.target.value.replace(/\D/g,"");i.target.value=a,a&&o<5&&e[o+1].focus(),o===5&&a&&setTimeout(()=>f.verifyCode(),300)}),t.addEventListener("keydown",i=>{const a=i.target;i.key==="Backspace"&&!a.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 a=i.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);a&&(a.split("").forEach((u,p)=>{e[p]&&(e[p].value=u)}),a.length===6&&setTimeout(()=>f.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",r.isOpen=!0,x.enable({modalId:"wx-auth-modal",getState:()=>r,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",r.isOpen=!1,x.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()}},f={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=d.getCookie("wxauth-openid");if(!e)return this.showAuthModal(),!1;const t=n.siteId?`&siteId=${encodeURIComponent(n.siteId)}`:"";try{const o=await d.request(`${n.apiBase}/api/auth/check?openid=${e}${t}`);return o.authenticated?(console.log("[WxAuth] 自动认证成功(Cookie)"),this.onVerified(o.user),!0):(d.deleteCookie("wxauth-openid"),this.showAuthModal(),!1)}catch(o){return console.error("[WxAuth] 自动验证失败:",o),this.showAuthModal(),!1}},async showAuthModal(){c.show();try{const t=n.siteId?`?siteId=${encodeURIComponent(n.siteId)}`:"",o=await d.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&&c.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=d.getCookie("wxauth-openid");if(e)try{const t=n.siteId?`&siteId=${encodeURIComponent(n.siteId)}`:"",o=await d.request(`${n.apiBase}/api/auth/check?openid=${e}${t}`);if(o.authenticated)return console.log("[WxAuth] 已认证(Cookie)"),this.onVerified(o.user),!0}catch(t){console.error("[WxAuth] Cookie check failed:",t)}return await this.showAuthModal(),new Promise(t=>{r.resolveAuth=t})},async verifyCode(){const e=c.getVerifyCode();if(!e||e.length!==6){c.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 d.request(`${n.apiBase}/api/auth/check?authToken=${e}${o}`);i.authenticated?(i.user&&i.user.openid&&d.setCookie("wxauth-openid",i.user.openid),t&&(t.textContent="✅ 成功",t.style.background="#07C160"),setTimeout(()=>{this.close(),this.onVerified(i.user)},500)):(c.showMessage("验证码错误或已过期","error"),c.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch{c.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(){c.hide(),r.resolveAuth&&(r.resolveAuth(!1),r.resolveAuth=null),typeof n.onClose=="function"&&n.onClose()},onVerified(e){console.log("[WxAuth] 验证成功",e),typeof n.onVerified=="function"&&n.onVerified(e),r.resolveAuth&&(r.resolveAuth(!0),r.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),typeof n.onError=="function"&&n.onError(e)}};typeof window<"u"&&(window.WxAuth=f),l.WxAuth=f,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
|