wx-auth-sdk 1.0.2 → 1.1.2
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 +274 -0
- package/dist/index.d.ts +2 -1
- package/dist/wx-auth.js +333 -1
- package/dist/wx-auth.umd.js +33 -1
- package/package.json +11 -2
package/README.md
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
# 微信订阅号认证 SDK
|
|
2
|
+
|
|
3
|
+
基于 Vite 构建的轻量级微信订阅号认证 SDK,支持 TypeScript 和多种模块格式。
|
|
4
|
+
|
|
5
|
+
## 📦 安装
|
|
6
|
+
|
|
7
|
+
### NPM 方式(推荐)
|
|
8
|
+
```bash
|
|
9
|
+
npm install wx-auth-sdk
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
### CDN 方式
|
|
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
|
+
### ES Module
|
|
21
|
+
```typescript
|
|
22
|
+
import { WxAuth } from 'wx-auth-sdk';
|
|
23
|
+
import 'wx-auth-sdk/dist/style.css';
|
|
24
|
+
|
|
25
|
+
WxAuth.init({
|
|
26
|
+
apiBase: 'https://auth.shenzjd.com',
|
|
27
|
+
siteId: 'my-website', // 可选,标识你的网站
|
|
28
|
+
// wechatName 和 qrcodeUrl 会自动从后端获取,也可以手动指定
|
|
29
|
+
onVerified: (user) => {
|
|
30
|
+
console.log('认证成功', user);
|
|
31
|
+
},
|
|
32
|
+
onError: (error) => {
|
|
33
|
+
console.error('认证失败', error);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### UMD(浏览器脚本)
|
|
39
|
+
```html
|
|
40
|
+
<link rel="stylesheet" href="./dist/wx-auth.css">
|
|
41
|
+
<script src="./dist/wx-auth.umd.js"></script>
|
|
42
|
+
<script>
|
|
43
|
+
WxAuth.init({
|
|
44
|
+
apiBase: 'https://auth.shenzjd.com',
|
|
45
|
+
siteId: 'my-website', // 可选,标识你的网站
|
|
46
|
+
onVerified: (user) => {
|
|
47
|
+
console.log('认证成功', user);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
</script>
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## ⚙️ 配置选项
|
|
54
|
+
|
|
55
|
+
| 参数 | 类型 | 必填 | 说明 |
|
|
56
|
+
|------|------|------|------|
|
|
57
|
+
| `apiBase` | `string` | ✅ | 后端 API 地址 |
|
|
58
|
+
| `siteId` | `string` | ❌ | 站点标识,用于区分不同接入网站 |
|
|
59
|
+
| `wechatName` | `string` | ❌ | 公众号名称(可选,自动从后端获取) |
|
|
60
|
+
| `qrcodeUrl` | `string` | ❌ | 二维码图片 URL(可选,自动从后端获取) |
|
|
61
|
+
| `onVerified` | `(user) => void` | ❌ | 验证成功回调 |
|
|
62
|
+
| `onError` | `(error) => void` | ❌ | 错误回调 |
|
|
63
|
+
|
|
64
|
+
## 🔧 API 方法
|
|
65
|
+
|
|
66
|
+
### `WxAuth.init(options)`
|
|
67
|
+
初始化 SDK,自动检测 Cookie 并静默认证。
|
|
68
|
+
|
|
69
|
+
**行为:**
|
|
70
|
+
- 检查 `wxauth-openid` Cookie
|
|
71
|
+
- 已认证 → 触发 `onVerified` 回调(静默通过)
|
|
72
|
+
- 未认证 → 显示认证弹窗
|
|
73
|
+
|
|
74
|
+
### `WxAuth.requireAuth()`
|
|
75
|
+
手动触发认证流程(用于重新认证、切换账号)。
|
|
76
|
+
|
|
77
|
+
**返回:** `Promise<boolean>` - 验证成功返回 `true`
|
|
78
|
+
|
|
79
|
+
### `WxAuth.close()`
|
|
80
|
+
关闭认证弹窗。
|
|
81
|
+
|
|
82
|
+
## 🛡️ 弹窗保护机制
|
|
83
|
+
|
|
84
|
+
SDK 内置防删除保护,防止用户从控制台删除认证弹窗:
|
|
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
|
+
```
|
|
154
|
+
|
|
155
|
+
## 🎨 用户体验特性
|
|
156
|
+
|
|
157
|
+
- ✅ **自动聚焦** - 首个输入框自动获得焦点
|
|
158
|
+
- ✅ **粘贴支持** - 自动识别 6 位数字粘贴
|
|
159
|
+
- ✅ **键盘导航** - 支持退格、方向键
|
|
160
|
+
- ✅ **自动验证** - 输入完成自动提交
|
|
161
|
+
- ✅ **静默认证** - 有 Cookie 时不显示弹窗
|
|
162
|
+
- ✅ **防删除保护** - MutationObserver + 定时器
|
|
163
|
+
|
|
164
|
+
## 📦 构建产物
|
|
165
|
+
|
|
166
|
+
```
|
|
167
|
+
dist/
|
|
168
|
+
├── wx-auth.js # ES Module (7.1 kB)
|
|
169
|
+
├── wx-auth.umd.js # UMD (11 kB)
|
|
170
|
+
├── wx-auth.css # 样式 (3.4 kB)
|
|
171
|
+
└── index.d.ts # TypeScript 类型声明
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
**总计:** < 12 KB(零依赖)
|
|
175
|
+
|
|
176
|
+
## 🔨 开发构建
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
# 安装依赖
|
|
180
|
+
pnpm install
|
|
181
|
+
|
|
182
|
+
# 构建 SDK
|
|
183
|
+
pnpm build
|
|
184
|
+
|
|
185
|
+
# 类型检查
|
|
186
|
+
pnpm type-check
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## 📝 认证流程
|
|
190
|
+
|
|
191
|
+
```
|
|
192
|
+
用户访问网站
|
|
193
|
+
↓
|
|
194
|
+
SDK 初始化
|
|
195
|
+
↓
|
|
196
|
+
检查 Cookie wxauth-openid
|
|
197
|
+
↓
|
|
198
|
+
已认证? → 静默通过 → onVerified 回调
|
|
199
|
+
↓
|
|
200
|
+
未认证? → 显示弹窗(二维码 + 6位输入框)
|
|
201
|
+
↓
|
|
202
|
+
用户扫码关注公众号
|
|
203
|
+
↓
|
|
204
|
+
公众号自动回复验证码
|
|
205
|
+
↓
|
|
206
|
+
用户输入验证码
|
|
207
|
+
↓
|
|
208
|
+
验证成功 → 保存 Cookie → onVerified 回调
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## 🔒 安全特性
|
|
212
|
+
|
|
213
|
+
- **验证码**:5分钟过期,一次性使用
|
|
214
|
+
- **Session**:AES-256-GCM 加密
|
|
215
|
+
- **Cookie**:HttpOnly + SameSite=Lax
|
|
216
|
+
- **防删除**:双重保护机制
|
|
217
|
+
|
|
218
|
+
## 🎯 使用场景
|
|
219
|
+
|
|
220
|
+
### 1. 独立网站集成
|
|
221
|
+
```typescript
|
|
222
|
+
import { WxAuth } from 'wx-auth-sdk';
|
|
223
|
+
|
|
224
|
+
WxAuth.init({
|
|
225
|
+
apiBase: 'https://auth.shenzjd.com',
|
|
226
|
+
siteId: 'my-blog', // 标识你的网站
|
|
227
|
+
onVerified: (user) => {
|
|
228
|
+
// 认证成功,允许访问内容
|
|
229
|
+
showContent();
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### 2. 现有系统集成
|
|
235
|
+
```typescript
|
|
236
|
+
// 在用户点击"登录"时触发
|
|
237
|
+
loginButton.onclick = async () => {
|
|
238
|
+
const success = await WxAuth.requireAuth();
|
|
239
|
+
if (success) {
|
|
240
|
+
// 继续原有登录流程
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### 3. 重新认证/切换账号
|
|
246
|
+
```typescript
|
|
247
|
+
// 用户点击"切换账号"
|
|
248
|
+
switchAccountButton.onclick = async () => {
|
|
249
|
+
await WxAuth.requireAuth();
|
|
250
|
+
};
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
## 📚 完整文档
|
|
254
|
+
|
|
255
|
+
完整的项目文档请参考项目根目录的 `README.md`,包含:
|
|
256
|
+
- 后端 API 详细配置
|
|
257
|
+
- 微信后台配置指南
|
|
258
|
+
- Docker 部署方案
|
|
259
|
+
- 环境变量说明
|
|
260
|
+
- 常见问题解答
|
|
261
|
+
|
|
262
|
+
## 🤝 依赖
|
|
263
|
+
|
|
264
|
+
**零依赖** - 纯原生 JavaScript + TypeScript
|
|
265
|
+
|
|
266
|
+
## 📄 许可证
|
|
267
|
+
|
|
268
|
+
MIT License
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
272
|
+
**版本**: 1.1.0
|
|
273
|
+
**构建时间**: 2025-12-30
|
|
274
|
+
**状态**: ✅ 生产就绪
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export declare const WxAuth: {
|
|
2
2
|
init(options?: Partial<WxAuthConfig>): void;
|
|
3
3
|
autoCheck(): Promise<boolean>;
|
|
4
|
-
showAuthModal(): void
|
|
4
|
+
showAuthModal(): Promise<void>;
|
|
5
5
|
requireAuth(): Promise<boolean>;
|
|
6
6
|
verifyCode(): Promise<void>;
|
|
7
7
|
close(): void;
|
|
@@ -36,6 +36,7 @@ export declare const WxAuth: {
|
|
|
36
36
|
*/
|
|
37
37
|
export declare interface WxAuthConfig {
|
|
38
38
|
apiBase: string;
|
|
39
|
+
siteId?: string;
|
|
39
40
|
onVerified?: ((user: any) => void) | null;
|
|
40
41
|
onError?: ((error: any) => void) | null;
|
|
41
42
|
wechatName?: string;
|
package/dist/wx-auth.js
CHANGED
|
@@ -1 +1,333 @@
|
|
|
1
|
-
const
|
|
1
|
+
const n = {
|
|
2
|
+
observer: null,
|
|
3
|
+
healthCheckTimer: null,
|
|
4
|
+
isProtected: !1
|
|
5
|
+
}, f = {
|
|
6
|
+
/**
|
|
7
|
+
* 启用弹窗保护
|
|
8
|
+
* @param config 配置选项
|
|
9
|
+
*/
|
|
10
|
+
enable(e) {
|
|
11
|
+
if (n.isProtected || typeof window > "u") return;
|
|
12
|
+
const { modalId: t, getState: o } = e;
|
|
13
|
+
n.observer = new MutationObserver((r) => {
|
|
14
|
+
r.forEach((i) => {
|
|
15
|
+
if (i.type === "childList")
|
|
16
|
+
i.removedNodes.forEach((c) => {
|
|
17
|
+
if (c.nodeType === Node.ELEMENT_NODE) {
|
|
18
|
+
const d = c;
|
|
19
|
+
(d.id === t || d.querySelector?.(`#${t}`)) && (console.warn(
|
|
20
|
+
"[WxAuth] 检测到弹窗被删除,正在自动恢复..."
|
|
21
|
+
), this.restore(e));
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
else if (i.type === "attributes") {
|
|
25
|
+
const c = i.target;
|
|
26
|
+
c.id === t && i.attributeName === "style" && c.style.display === "none" && o().isOpen && (console.warn(
|
|
27
|
+
"[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."
|
|
28
|
+
), c.style.display = "flex");
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}), n.observer.observe(document.body, {
|
|
32
|
+
childList: !0,
|
|
33
|
+
subtree: !0,
|
|
34
|
+
attributes: !0,
|
|
35
|
+
attributeFilter: ["style"]
|
|
36
|
+
}), n.healthCheckTimer = window.setInterval(() => {
|
|
37
|
+
this.healthCheck(e);
|
|
38
|
+
}, 1e3), n.isProtected = !0, console.log("[WxAuth] 弹窗保护已启用");
|
|
39
|
+
},
|
|
40
|
+
/**
|
|
41
|
+
* 禁用弹窗保护
|
|
42
|
+
*/
|
|
43
|
+
disable() {
|
|
44
|
+
n.observer && (n.observer.disconnect(), n.observer = null), n.healthCheckTimer && (clearInterval(n.healthCheckTimer), n.healthCheckTimer = null), n.isProtected = !1, console.log("[WxAuth] 弹窗保护已禁用");
|
|
45
|
+
},
|
|
46
|
+
/**
|
|
47
|
+
* 健康检查(定时器调用)
|
|
48
|
+
* @param config 配置选项
|
|
49
|
+
*/
|
|
50
|
+
healthCheck(e) {
|
|
51
|
+
const { modalId: t, getState: o } = e;
|
|
52
|
+
if (!o().isOpen) return;
|
|
53
|
+
const r = document.getElementById(t);
|
|
54
|
+
if (!r) {
|
|
55
|
+
console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."), this.restore(e);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
r.style.display === "none" && (console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."), r.style.display = "flex");
|
|
59
|
+
},
|
|
60
|
+
/**
|
|
61
|
+
* 恢复弹窗
|
|
62
|
+
* @param config 配置选项
|
|
63
|
+
*/
|
|
64
|
+
restore(e) {
|
|
65
|
+
const { modalId: t, getState: o, onRestore: r } = e;
|
|
66
|
+
if (!o().isOpen) return;
|
|
67
|
+
const i = document.getElementById(t);
|
|
68
|
+
if (i) {
|
|
69
|
+
i.style.display = "flex";
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
r();
|
|
73
|
+
}
|
|
74
|
+
}, p = {
|
|
75
|
+
apiBase: "",
|
|
76
|
+
// 后端API地址(必填)
|
|
77
|
+
siteId: "",
|
|
78
|
+
// 站点标识(可选,用于区分来源网站)
|
|
79
|
+
onVerified: null,
|
|
80
|
+
// 验证成功回调
|
|
81
|
+
onError: null,
|
|
82
|
+
// 错误回调
|
|
83
|
+
wechatName: "公众号",
|
|
84
|
+
// 公众号名称(可选,会自动获取)
|
|
85
|
+
qrcodeUrl: ""
|
|
86
|
+
// 二维码URL(可选,会自动获取)
|
|
87
|
+
};
|
|
88
|
+
let s = { ...p }, a = {
|
|
89
|
+
isOpen: !1,
|
|
90
|
+
resolveAuth: null,
|
|
91
|
+
currentStep: "qr"
|
|
92
|
+
};
|
|
93
|
+
const l = {
|
|
94
|
+
// 获取Cookie
|
|
95
|
+
getCookie(e) {
|
|
96
|
+
const o = `; ${document.cookie}`.split(`; ${e}=`);
|
|
97
|
+
return o.length === 2 && o.pop()?.split(";").shift() || null;
|
|
98
|
+
},
|
|
99
|
+
// 设置Cookie(30天过期)
|
|
100
|
+
setCookie(e, t) {
|
|
101
|
+
const o = /* @__PURE__ */ new Date();
|
|
102
|
+
o.setTime(o.getTime() + 720 * 60 * 60 * 1e3), document.cookie = `${e}=${t};expires=${o.toUTCString()};path=/`;
|
|
103
|
+
},
|
|
104
|
+
// 删除Cookie
|
|
105
|
+
deleteCookie(e) {
|
|
106
|
+
document.cookie = `${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
|
|
107
|
+
},
|
|
108
|
+
// 发送请求
|
|
109
|
+
async request(e, t = {}) {
|
|
110
|
+
try {
|
|
111
|
+
const o = await fetch(e, {
|
|
112
|
+
method: t.method || "GET",
|
|
113
|
+
headers: {
|
|
114
|
+
"Content-Type": "application/json",
|
|
115
|
+
...t.headers
|
|
116
|
+
},
|
|
117
|
+
body: t.body ? JSON.stringify(t.body) : null,
|
|
118
|
+
credentials: "include"
|
|
119
|
+
});
|
|
120
|
+
if (!o.ok)
|
|
121
|
+
throw new Error(`HTTP ${o.status}`);
|
|
122
|
+
return await o.json();
|
|
123
|
+
} catch (o) {
|
|
124
|
+
throw console.error("[WxAuth] Request error:", o), o;
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
// 生成6位验证码输入框HTML
|
|
128
|
+
generateCodeInputs() {
|
|
129
|
+
let e = '<div class="wx-auth-inputs">';
|
|
130
|
+
for (let t = 0; t < 6; t++)
|
|
131
|
+
e += `<input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="wx-auth-input" data-index="${t}" autocomplete="off" />`;
|
|
132
|
+
return e += "</div>", e;
|
|
133
|
+
}
|
|
134
|
+
}, u = {
|
|
135
|
+
// 创建弹窗
|
|
136
|
+
createModal() {
|
|
137
|
+
const e = document.createElement("div");
|
|
138
|
+
return e.id = "wx-auth-modal", e.className = "wx-auth-modal", e.innerHTML = `
|
|
139
|
+
<div class="wx-auth-overlay"></div>
|
|
140
|
+
<div class="wx-auth-content">
|
|
141
|
+
<div class="wx-auth-header">
|
|
142
|
+
<div class="wx-auth-title">微信认证</div>
|
|
143
|
+
<button class="wx-auth-close" onclick="WxAuth.close()">×</button>
|
|
144
|
+
</div>
|
|
145
|
+
<div class="wx-auth-body">
|
|
146
|
+
<!-- 二维码区域 -->
|
|
147
|
+
<div>
|
|
148
|
+
<div class="wx-auth-desc">1. 微信关注公众号</div>
|
|
149
|
+
<div class="wx-auth-qrcode-container">
|
|
150
|
+
<img class="wx-auth-qrcode" src="" alt="扫码关注" />
|
|
151
|
+
</div>
|
|
152
|
+
</div>
|
|
153
|
+
|
|
154
|
+
<!-- 验证码输入区域 -->
|
|
155
|
+
<div>
|
|
156
|
+
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
157
|
+
${l.generateCodeInputs()}
|
|
158
|
+
</div>
|
|
159
|
+
|
|
160
|
+
<!-- 消息提示 -->
|
|
161
|
+
<div class="wx-auth-message" style="display:none"></div>
|
|
162
|
+
|
|
163
|
+
<!-- 按钮 -->
|
|
164
|
+
<div class="wx-auth-actions">
|
|
165
|
+
<button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">验证</button>
|
|
166
|
+
</div>
|
|
167
|
+
</div>
|
|
168
|
+
</div>
|
|
169
|
+
`, document.body.appendChild(e), this.bindInputEvents(), e;
|
|
170
|
+
},
|
|
171
|
+
// 绑定输入事件
|
|
172
|
+
bindInputEvents() {
|
|
173
|
+
setTimeout(() => {
|
|
174
|
+
const e = document.querySelectorAll(".wx-auth-input");
|
|
175
|
+
e.length && e.forEach((t, o) => {
|
|
176
|
+
t.addEventListener("input", (r) => {
|
|
177
|
+
const i = r.target.value.replace(/\D/g, "");
|
|
178
|
+
r.target.value = i, i && o < 5 && e[o + 1].focus(), o === 5 && i && setTimeout(() => h.verifyCode(), 300);
|
|
179
|
+
}), t.addEventListener("keydown", (r) => {
|
|
180
|
+
const i = r.target;
|
|
181
|
+
r.key === "Backspace" && !i.value && o > 0 ? e[o - 1].focus() : r.key === "ArrowLeft" && o > 0 ? (r.preventDefault(), e[o - 1].focus()) : r.key === "ArrowRight" && o < 5 && (r.preventDefault(), e[o + 1].focus());
|
|
182
|
+
}), t.addEventListener("paste", (r) => {
|
|
183
|
+
r.preventDefault();
|
|
184
|
+
const i = r.clipboardData?.getData("text").replace(/\D/g, "").slice(0, 6);
|
|
185
|
+
i && (i.split("").forEach((c, d) => {
|
|
186
|
+
e[d] && (e[d].value = c);
|
|
187
|
+
}), i.length === 6 && setTimeout(() => h.verifyCode(), 300));
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
}, 100);
|
|
191
|
+
},
|
|
192
|
+
// 显示弹窗
|
|
193
|
+
show() {
|
|
194
|
+
let e = document.getElementById("wx-auth-modal");
|
|
195
|
+
e || (e = this.createModal()), e.style.display = "flex", a.isOpen = !0, f.enable({
|
|
196
|
+
modalId: "wx-auth-modal",
|
|
197
|
+
getState: () => a,
|
|
198
|
+
onRestore: () => {
|
|
199
|
+
this.createModal(), s.qrcodeUrl && this.setQrCode(s.qrcodeUrl);
|
|
200
|
+
const t = document.querySelector(".wx-auth-desc");
|
|
201
|
+
t && s.wechatName && (t.textContent = `1. 微信关注公众号 "${s.wechatName}"`), this.bindInputEvents(), setTimeout(() => {
|
|
202
|
+
const o = document.querySelector(".wx-auth-input");
|
|
203
|
+
o && o.focus();
|
|
204
|
+
}, 100);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
},
|
|
208
|
+
// 隐藏弹窗
|
|
209
|
+
hide() {
|
|
210
|
+
const e = document.getElementById("wx-auth-modal");
|
|
211
|
+
e && (e.style.display = "none", a.isOpen = !1, f.disable());
|
|
212
|
+
},
|
|
213
|
+
// 设置二维码
|
|
214
|
+
setQrCode(e) {
|
|
215
|
+
if (!e) return;
|
|
216
|
+
const t = document.querySelector(".wx-auth-qrcode");
|
|
217
|
+
t && (t.src = e, t.style.display = "block");
|
|
218
|
+
},
|
|
219
|
+
// 显示消息
|
|
220
|
+
showMessage(e, t = "info") {
|
|
221
|
+
const o = document.querySelector(".wx-auth-message");
|
|
222
|
+
o && (o.textContent = e, o.className = `wx-auth-message wx-auth-message-${t}`, o.style.display = "block", setTimeout(() => {
|
|
223
|
+
o.textContent === e && (o.style.display = "none");
|
|
224
|
+
}, 3e3));
|
|
225
|
+
},
|
|
226
|
+
// 获取验证码
|
|
227
|
+
getVerifyCode() {
|
|
228
|
+
const e = document.querySelectorAll(".wx-auth-input");
|
|
229
|
+
return e.length ? Array.from(e).map((t) => t.value).join("") : "";
|
|
230
|
+
},
|
|
231
|
+
// 清空验证码输入
|
|
232
|
+
clearCodeInputs() {
|
|
233
|
+
const e = document.querySelectorAll(".wx-auth-input");
|
|
234
|
+
e.forEach((t) => t.value = ""), e[0] && e[0].focus();
|
|
235
|
+
}
|
|
236
|
+
}, h = {
|
|
237
|
+
// 初始化
|
|
238
|
+
init(e = {}) {
|
|
239
|
+
if (s = { ...p, ...e }, !s.apiBase && typeof window < "u" && (s.apiBase = window.location.origin), !s.apiBase) {
|
|
240
|
+
console.error("[WxAuth] apiBase is required");
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
console.log("[WxAuth] SDK initialized", s), typeof window < "u" && this.autoCheck();
|
|
244
|
+
},
|
|
245
|
+
// 自动检测 Cookie 并验证(内部使用)
|
|
246
|
+
async autoCheck() {
|
|
247
|
+
const e = l.getCookie("wxauth-openid");
|
|
248
|
+
if (!e)
|
|
249
|
+
return this.showAuthModal(), !1;
|
|
250
|
+
const t = s.siteId ? `&siteId=${encodeURIComponent(s.siteId)}` : "";
|
|
251
|
+
try {
|
|
252
|
+
const o = await l.request(
|
|
253
|
+
`${s.apiBase}/api/auth/check?openid=${e}${t}`
|
|
254
|
+
);
|
|
255
|
+
return o.authenticated ? (console.log("[WxAuth] 自动认证成功(Cookie)"), this.onVerified(o.user), !0) : (l.deleteCookie("wxauth-openid"), this.showAuthModal(), !1);
|
|
256
|
+
} catch (o) {
|
|
257
|
+
return console.error("[WxAuth] 自动验证失败:", o), this.showAuthModal(), !1;
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
// 显示认证弹窗(内部使用)
|
|
261
|
+
async showAuthModal() {
|
|
262
|
+
u.show();
|
|
263
|
+
try {
|
|
264
|
+
const t = s.siteId ? `?siteId=${encodeURIComponent(s.siteId)}` : "", o = await l.request(
|
|
265
|
+
`${s.apiBase}/api/sdk/config${t}`
|
|
266
|
+
);
|
|
267
|
+
o.wechatName && !s.wechatName && (s.wechatName = o.wechatName), o.qrcodeUrl && !s.qrcodeUrl && (s.qrcodeUrl = o.qrcodeUrl);
|
|
268
|
+
} catch (t) {
|
|
269
|
+
console.warn("[WxAuth] 获取后端配置失败,使用默认配置", t);
|
|
270
|
+
}
|
|
271
|
+
s.qrcodeUrl && u.setQrCode(s.qrcodeUrl);
|
|
272
|
+
const e = document.querySelector(".wx-auth-desc");
|
|
273
|
+
e && s.wechatName && (e.textContent = `1. 微信关注公众号 "${s.wechatName}"`), setTimeout(() => {
|
|
274
|
+
const t = document.querySelector(".wx-auth-input");
|
|
275
|
+
t && t.focus();
|
|
276
|
+
}, 100);
|
|
277
|
+
},
|
|
278
|
+
// 主入口:需要验证时调用
|
|
279
|
+
async requireAuth() {
|
|
280
|
+
const e = l.getCookie("wxauth-openid");
|
|
281
|
+
if (e)
|
|
282
|
+
try {
|
|
283
|
+
const t = s.siteId ? `&siteId=${encodeURIComponent(s.siteId)}` : "", o = await l.request(
|
|
284
|
+
`${s.apiBase}/api/auth/check?openid=${e}${t}`
|
|
285
|
+
);
|
|
286
|
+
if (o.authenticated)
|
|
287
|
+
return console.log("[WxAuth] 已认证(Cookie)"), this.onVerified(o.user), !0;
|
|
288
|
+
} catch (t) {
|
|
289
|
+
console.error("[WxAuth] Cookie check failed:", t);
|
|
290
|
+
}
|
|
291
|
+
return await this.showAuthModal(), new Promise((t) => {
|
|
292
|
+
a.resolveAuth = t;
|
|
293
|
+
});
|
|
294
|
+
},
|
|
295
|
+
// 验证验证码
|
|
296
|
+
async verifyCode() {
|
|
297
|
+
const e = u.getVerifyCode();
|
|
298
|
+
if (!e || e.length !== 6) {
|
|
299
|
+
u.showMessage("请输入6位验证码", "error");
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const t = document.querySelector(
|
|
303
|
+
".wx-auth-btn-primary"
|
|
304
|
+
);
|
|
305
|
+
t && (t.disabled = !0, t.textContent = "验证中...");
|
|
306
|
+
try {
|
|
307
|
+
const o = s.siteId ? `&siteId=${encodeURIComponent(s.siteId)}` : "", r = await l.request(
|
|
308
|
+
`${s.apiBase}/api/auth/check?authToken=${e}${o}`
|
|
309
|
+
);
|
|
310
|
+
r.authenticated ? (r.user && r.user.openid && l.setCookie("wxauth-openid", r.user.openid), t && (t.textContent = "✅ 成功", t.style.background = "#07C160"), setTimeout(() => {
|
|
311
|
+
this.close(), this.onVerified(r.user);
|
|
312
|
+
}, 500)) : (u.showMessage("验证码错误或已过期", "error"), u.clearCodeInputs(), t && (t.disabled = !1, t.textContent = "验证"));
|
|
313
|
+
} catch {
|
|
314
|
+
u.showMessage("验证失败,请重试", "error"), t && (t.disabled = !1, t.textContent = "验证");
|
|
315
|
+
}
|
|
316
|
+
},
|
|
317
|
+
// 关闭弹窗
|
|
318
|
+
close() {
|
|
319
|
+
u.hide(), a.resolveAuth && (a.resolveAuth(!1), a.resolveAuth = null);
|
|
320
|
+
},
|
|
321
|
+
// 验证成功回调
|
|
322
|
+
onVerified(e) {
|
|
323
|
+
console.log("[WxAuth] 验证成功", e), typeof s.onVerified == "function" && s.onVerified(e), a.resolveAuth && (a.resolveAuth(!0), a.resolveAuth = null);
|
|
324
|
+
},
|
|
325
|
+
// 错误回调
|
|
326
|
+
onError(e) {
|
|
327
|
+
console.error("[WxAuth] 错误", e), typeof s.onError == "function" && s.onError(e);
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
typeof window < "u" && (window.WxAuth = h);
|
|
331
|
+
export {
|
|
332
|
+
h as WxAuth
|
|
333
|
+
};
|
package/dist/wx-auth.umd.js
CHANGED
|
@@ -1 +1,33 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WxAuthSDK={})}(this,function(e){"use strict";var t=document.createElement("style");t.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}}\n/*$vite$:1*/",document.head.appendChild(t);const o={observer:null,healthCheckTimer:null,isProtected:!1},n={enable(e){if(o.isProtected||"undefined"==typeof window)return;const{modalId:t,getState:n}=e;o.observer=new MutationObserver(o=>{o.forEach(o=>{if("childList"===o.type)o.removedNodes.forEach(o=>{if(o.nodeType===Node.ELEMENT_NODE){const n=o;(n.id===t||n.querySelector?.(`#${t}`))&&(console.warn("[WxAuth] 检测到弹窗被删除,正在自动恢复..."),this.restore(e))}});else if("attributes"===o.type){const e=o.target;e.id===t&&"style"===o.attributeName&&"none"===e.style.display&&n().isOpen&&(console.warn("[WxAuth] 检测到弹窗被隐藏,正在自动恢复..."),e.style.display="flex")}})}),o.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}),o.healthCheckTimer=window.setInterval(()=>{this.healthCheck(e)},1e3),o.isProtected=!0,console.log("[WxAuth] 弹窗保护已启用")},disable(){o.observer&&(o.observer.disconnect(),o.observer=null),o.healthCheckTimer&&(clearInterval(o.healthCheckTimer),o.healthCheckTimer=null),o.isProtected=!1,console.log("[WxAuth] 弹窗保护已禁用")},healthCheck(e){const{modalId:t,getState:o}=e;if(!o().isOpen)return;const n=document.getElementById(t);if(!n)return console.warn("[WxAuth] 健康检查:弹窗不存在,正在恢复..."),void this.restore(e);"none"===n.style.display&&(console.warn("[WxAuth] 健康检查:弹窗被隐藏,正在恢复..."),n.style.display="flex")},restore(e){const{modalId:t,getState:o,onRestore:n}=e;if(!o().isOpen)return;const a=document.getElementById(t);a?a.style.display="flex":n()}},a={apiBase:"",onVerified:null,onError:null,wechatName:"公众号",qrcodeUrl:""};let r={...a},i={isOpen:!1,resolveAuth:null,currentStep:"qr"};const s={getCookie(e){const t=`; ${document.cookie}`.split(`; ${e}=`);return 2===t.length&&t.pop()?.split(";").shift()||null},setCookie(e,t){const o=new Date;o.setTime(o.getTime()+2592e6),document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/`},deleteCookie(e){document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`},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");return e.id="wx-auth-modal",e.className="wx-auth-modal",e.innerHTML=`\n <div class="wx-auth-overlay"></div>\n <div class="wx-auth-content">\n <div class="wx-auth-header">\n <div class="wx-auth-title">微信认证</div>\n <button class="wx-auth-close" onclick="WxAuth.close()">×</button>\n </div>\n <div class="wx-auth-body">\n \x3c!-- 二维码区域 --\x3e\n <div>\n <div class="wx-auth-desc">1. 微信关注公众号</div>\n <div class="wx-auth-qrcode-container">\n <img class="wx-auth-qrcode" src="" alt="扫码关注" />\n </div>\n </div>\n\n \x3c!-- 验证码输入区域 --\x3e\n <div>\n <div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>\n ${s.generateCodeInputs()}\n </div>\n\n \x3c!-- 消息提示 --\x3e\n <div class="wx-auth-message" style="display:none"></div>\n\n \x3c!-- 按钮 --\x3e\n <div class="wx-auth-actions">\n <button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">验证</button>\n </div>\n </div>\n </div>\n `,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",t=>{const n=t.target.value.replace(/\D/g,"");t.target.value=n,n&&o<5&&e[o+1].focus(),5===o&&n&&setTimeout(()=>d.verifyCode(),300)}),t.addEventListener("keydown",t=>{const n=t.target;"Backspace"===t.key&&!n.value&&o>0?e[o-1].focus():"ArrowLeft"===t.key&&o>0?(t.preventDefault(),e[o-1].focus()):"ArrowRight"===t.key&&o<5&&(t.preventDefault(),e[o+1].focus())}),t.addEventListener("paste",t=>{t.preventDefault();const o=t.clipboardData?.getData("text").replace(/\D/g,"").slice(0,6);o&&(o.split("").forEach((t,o)=>{e[o]&&(e[o].value=t)}),6===o.length&&setTimeout(()=>d.verifyCode(),300))})})},100)},show(){let e=document.getElementById("wx-auth-modal");e||(e=this.createModal()),e.style.display="flex",i.isOpen=!0,n.enable({modalId:"wx-auth-modal",getState:()=>i,onRestore:()=>{this.createModal(),r.qrcodeUrl&&this.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-desc");e&&r.wechatName&&(e.textContent=`1. 微信关注公众号 "${r.wechatName}"`),this.bindInputEvents(),setTimeout(()=>{const e=document.querySelector(".wx-auth-input");e&&e.focus()},100)}})},hide(){const e=document.getElementById("wx-auth-modal");e&&(e.style.display="none",i.isOpen=!1,n.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(e=>e.value).join(""):""},clearCodeInputs(){const e=document.querySelectorAll(".wx-auth-input");e.forEach(e=>e.value=""),e[0]&&e[0].focus()}},d={init(e={}){r={...a,...e},r.apiBase?(console.log("[WxAuth] SDK initialized",r),"undefined"!=typeof window&&this.autoCheck()):console.error("[WxAuth] apiBase is required")},async autoCheck(){const e=s.getCookie("wxauth-openid");if(!e)return this.showAuthModal(),!1;try{const t=await s.request(`${r.apiBase}/api/auth/check?openid=${e}`);return t.authenticated?(console.log("[WxAuth] 自动认证成功(Cookie)"),this.onVerified(t.user),!0):(s.deleteCookie("wxauth-openid"),this.showAuthModal(),!1)}catch(t){return console.error("[WxAuth] 自动验证失败:",t),this.showAuthModal(),!1}},showAuthModal(){c.show(),r.qrcodeUrl&&c.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-desc");e&&r.wechatName&&(e.textContent=`1. 微信关注公众号 "${r.wechatName}"`),setTimeout(()=>{const e=document.querySelector(".wx-auth-input");e&&e.focus()},100)},async requireAuth(){const e=s.getCookie("wxauth-openid");if(e)try{const t=await s.request(`${r.apiBase}/api/auth/check?openid=${e}`);if(t.authenticated)return console.log("[WxAuth] 已认证(Cookie)"),this.onVerified(t.user),!0}catch(t){console.error("[WxAuth] Cookie check failed:",t)}c.show();try{r.qrcodeUrl&&c.setQrCode(r.qrcodeUrl);const e=document.querySelector(".wx-auth-desc");e&&(e.textContent=`1. 微信关注公众号 "${r.wechatName}"`),setTimeout(()=>{const e=document.querySelector(".wx-auth-input");e&&e.focus()},100)}catch(o){return c.showMessage("加载失败,请重试","error"),!1}return new Promise(e=>{i.resolveAuth=e})},async verifyCode(){const e=c.getVerifyCode();if(!e||6!==e.length)return void c.showMessage("请输入6位验证码","error");const t=document.querySelector(".wx-auth-btn-primary");t&&(t.disabled=!0,t.textContent="验证中...");try{const o=await s.request(`${r.apiBase}/api/auth/check?authToken=${e}`);o.authenticated?(o.user&&o.user.openid&&s.setCookie("wxauth-openid",o.user.openid),t&&(t.textContent="✅ 成功",t.style.background="#07C160"),setTimeout(()=>{this.close(),this.onVerified(o.user)},500)):(c.showMessage("验证码错误或已过期","error"),c.clearCodeInputs(),t&&(t.disabled=!1,t.textContent="验证"))}catch(o){c.showMessage("验证失败,请重试","error"),t&&(t.disabled=!1,t.textContent="验证")}},close(){c.hide(),i.resolveAuth&&(i.resolveAuth(!1),i.resolveAuth=null)},onVerified(e){console.log("[WxAuth] 验证成功",e),"function"==typeof r.onVerified&&r.onVerified(e),i.resolveAuth&&(i.resolveAuth(!0),i.resolveAuth=null)},onError(e){console.error("[WxAuth] 错误",e),"function"==typeof r.onError&&r.onError(e)}};"undefined"!=typeof window&&(window.WxAuth=d),e.WxAuth=d,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
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:"公众号",qrcodeUrl:""};let n={...w},r={isOpen:!1,resolveAuth:null,currentStep:"qr"};const d={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),document.cookie=`${e}=${t};expires=${o.toUTCString()};path=/`},deleteCookie(e){document.cookie=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`},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");return e.id="wx-auth-modal",e.className="wx-auth-modal",e.innerHTML=`
|
|
3
|
+
<div class="wx-auth-overlay"></div>
|
|
4
|
+
<div class="wx-auth-content">
|
|
5
|
+
<div class="wx-auth-header">
|
|
6
|
+
<div class="wx-auth-title">微信认证</div>
|
|
7
|
+
<button class="wx-auth-close" onclick="WxAuth.close()">×</button>
|
|
8
|
+
</div>
|
|
9
|
+
<div class="wx-auth-body">
|
|
10
|
+
<!-- 二维码区域 -->
|
|
11
|
+
<div>
|
|
12
|
+
<div class="wx-auth-desc">1. 微信关注公众号</div>
|
|
13
|
+
<div class="wx-auth-qrcode-container">
|
|
14
|
+
<img class="wx-auth-qrcode" src="" alt="扫码关注" />
|
|
15
|
+
</div>
|
|
16
|
+
</div>
|
|
17
|
+
|
|
18
|
+
<!-- 验证码输入区域 -->
|
|
19
|
+
<div>
|
|
20
|
+
<div class="wx-auth-hint">2. 向公众号发送"验证码"获取</div>
|
|
21
|
+
${d.generateCodeInputs()}
|
|
22
|
+
</div>
|
|
23
|
+
|
|
24
|
+
<!-- 消息提示 -->
|
|
25
|
+
<div class="wx-auth-message" style="display:none"></div>
|
|
26
|
+
|
|
27
|
+
<!-- 按钮 -->
|
|
28
|
+
<div class="wx-auth-actions">
|
|
29
|
+
<button class="wx-auth-btn wx-auth-btn-primary" onclick="WxAuth.verifyCode()">验证</button>
|
|
30
|
+
</div>
|
|
31
|
+
</div>
|
|
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||(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-desc");t&&n.wechatName&&(t.textContent=`1. 微信关注公众号 "${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}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-desc");e&&n.wechatName&&(e.textContent=`1. 微信关注公众号 "${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)},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"})}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wx-auth-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"description": "微信订阅号认证 SDK - 极简版",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/wx-auth.umd.js",
|
|
@@ -35,8 +35,17 @@
|
|
|
35
35
|
"微信订阅号认证系统",
|
|
36
36
|
"微信订阅号认证SDK"
|
|
37
37
|
],
|
|
38
|
-
"author": "",
|
|
38
|
+
"author": "wu529778790",
|
|
39
39
|
"license": "MIT",
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "https://github.com/wu529778790/wx-auth.git",
|
|
43
|
+
"directory": "wx-auth-sdk"
|
|
44
|
+
},
|
|
45
|
+
"homepage": "https://github.com/wu529778790/wx-auth/tree/main/wx-auth-sdk#readme",
|
|
46
|
+
"bugs": {
|
|
47
|
+
"url": "https://github.com/wu529778790/wx-auth/issues"
|
|
48
|
+
},
|
|
40
49
|
"scripts": {
|
|
41
50
|
"dev": "vite",
|
|
42
51
|
"build": "vite build",
|