-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook-server.ts
More file actions
217 lines (186 loc) · 6.06 KB
/
webhook-server.ts
File metadata and controls
217 lines (186 loc) · 6.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/**
* Webhook 服务器
* 用于接收钉钉机器人的回调消息
* 支持统一回调地址,自动识别机器人
*/
import express, { Request, Response } from 'express';
interface WebhookServerConfig {
port: number;
onCallback: (robotId: string, data: any) => void;
robots?: { [robotId: string]: { accessToken?: string; name?: string } };
}
export class WebhookServer {
private app: any;
private config: WebhookServerConfig;
private server: any = null;
private tokenToRobotMap: Map<string, string> = new Map();
constructor(config: WebhookServerConfig) {
this.config = config;
this.app = express();
// 构建 token 到机器人 ID 的映射
if (config.robots) {
Object.entries(config.robots).forEach(([robotId, robotConfig]) => {
if (robotConfig.accessToken) {
this.tokenToRobotMap.set(robotConfig.accessToken, robotId);
}
});
}
// 解析 JSON 请求体
this.app.use(express.json());
// 设置路由
this.setupRoutes();
}
/**
* 根据 access_token 自动识别机器人 ID
*/
private identifyRobotId(callbackData: any): string | null {
// 方式 1: 从回调数据中获取 robotId 字段
if (callbackData.robotId) {
return callbackData.robotId;
}
// 方式 2: 从 access_token 识别
if (callbackData.accessToken) {
const robotId = this.tokenToRobotMap.get(callbackData.accessToken);
if (robotId) {
return robotId;
}
}
// 方式 3: 钉钉回调中的 senderId 或 conversationId
if (callbackData.senderId || callbackData.conversationId) {
// 可以根据 senderId 或 conversationId 进行映射
// 这里可以扩展自定义映射逻辑
return 'default';
}
return null;
}
private setupRoutes(): void {
// 统一回调接口 - 所有机器人共用
this.app.post('/webhook', (req: Request, res: Response) => {
const callbackData = req.body;
// 自动识别机器人 ID
let robotId = this.identifyRobotId(callbackData);
// 如果无法自动识别,使用默认值或从 URL 参数获取
if (!robotId) {
robotId = req.query.robotId as string || 'default';
}
// 增强回调数据,添加机器人信息
const enhancedData = {
...callbackData,
_robotId: robotId,
_robotName: this.config.robots?.[robotId]?.name || robotId,
_receivedAt: Date.now(),
};
console.log(`收到机器人 ${robotId} 的回调:`, enhancedData);
try {
this.config.onCallback(robotId, enhancedData);
res.json({ success: true, robotId });
} catch (error: any) {
console.error('处理回调失败:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// 带机器人 ID 参数的回调接口(可选)
this.app.post('/webhook/:robotId', (req: Request, res: Response) => {
const { robotId } = req.params;
const callbackData = req.body;
// 增强回调数据
const enhancedData = {
...callbackData,
_robotId: robotId,
_robotName: this.config.robots?.[robotId]?.name || robotId,
_receivedAt: Date.now(),
};
console.log(`收到机器人 ${robotId} 的回调:`, enhancedData);
try {
this.config.onCallback(robotId, enhancedData);
res.json({ success: true, robotId });
} catch (error: any) {
console.error('处理回调失败:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// 特定事件回调接口
this.app.post('/webhook/:robotId/:event', (req: Request, res: Response) => {
const { robotId, event } = req.params;
const callbackData = req.body;
console.log(`收到机器人 ${robotId} 的 ${event} 事件:`, callbackData);
try {
this.config.onCallback(robotId, { event, ...callbackData });
res.json({ success: true, robotId });
} catch (error: any) {
console.error('处理回调失败:', error);
res.status(500).json({ success: false, error: error.message });
}
});
// 健康检查接口
this.app.get('/health', (req: Request, res: Response) => {
res.json({
status: 'ok',
timestamp: Date.now(),
robots: Object.keys(this.config.robots || {}),
});
});
// 获取机器人列表
this.app.get('/robots', (req: Request, res: Response) => {
res.json({
success: true,
message: 'Webhook server is running',
robots: this.config.robots || {},
tokenMap: Object.fromEntries(this.tokenToRobotMap),
});
});
}
/**
* 启动服务器
*/
start(): Promise<void> {
return new Promise((resolve, reject) => {
try {
this.server = this.app.listen(this.config.port, () => {
console.log(`Webhook 服务器已启动,监听端口:${this.config.port}`);
console.log(`回调地址格式:http://localhost:${this.config.port}/webhook/:robotId`);
resolve();
});
this.server.on('error', (error: Error) => {
console.error('Webhook 服务器启动失败:', error);
reject(error);
});
} catch (error) {
reject(error);
}
});
}
/**
* 停止服务器
*/
stop(): Promise<void> {
return new Promise((resolve, reject) => {
if (!this.server) {
resolve();
return;
}
this.server.close((err?: Error) => {
if (err) {
console.error('停止 Webhook 服务器失败:', err);
reject(err);
} else {
console.log('Webhook 服务器已停止');
this.server = null;
resolve();
}
});
});
}
}
/**
* 创建并启动 Webhook 服务器
*/
export function createWebhookServer(
port: number,
onCallback: (robotId: string, data: any) => void,
robots?: { [robotId: string]: { accessToken?: string; name?: string } }
): WebhookServer {
const server = new WebhookServer({ port, onCallback, robots });
server.start();
return server;
}