-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsimple-proxy-server.js
More file actions
188 lines (161 loc) · 5.48 KB
/
Copy pathsimple-proxy-server.js
File metadata and controls
188 lines (161 loc) · 5.48 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
/**
* 微信API极简转发服务
* 功能:将请求转发到微信官方API,保留原始IP和Headers
* 运行:node simple-proxy-server.js
* 依赖:仅需要Node.js内置模块,无需安装第三方包
*/
const http = require('http');
const https = require('https');
const url = require('url');
// 配置参数
const PORT = process.env.PORT || 80;
const WECHAT_API_HOST = 'api.weixin.qq.com';
const LOG_REQUESTS = process.env.LOG_REQUESTS === 'true';
// 请求统计
let requestCount = 0;
let successCount = 0;
let errorCount = 0;
/**
* 创建到微信API的请求
*/
function createWechatRequest(reqOptions, reqData, res) {
const wechatReq = https.request(reqOptions, (wechatRes) => {
// 设置响应头
Object.keys(wechatRes.headers).forEach(key => {
// 跳过一些可能冲突的headers
if (!['connection', 'transfer-encoding'].includes(key.toLowerCase())) {
res.setHeader(key, wechatRes.headers[key]);
}
});
res.writeHead(wechatRes.statusCode);
// 转发响应数据
wechatRes.pipe(res);
successCount++;
if (LOG_REQUESTS) {
console.log(`✅ ${reqOptions.method} ${reqOptions.path} -> ${wechatRes.statusCode}`);
}
});
// 处理错误
wechatReq.on('error', (err) => {
console.error(`❌ Proxy error: ${err.message}`);
errorCount++;
if (!res.headersSent) {
res.writeHead(502, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
error: 'Proxy Error',
message: 'Failed to connect to WeChat API',
details: err.message
}));
}
});
// 发送请求数据
if (reqData) {
wechatReq.write(reqData);
}
wechatReq.end();
}
/**
* 处理HTTP请求
*/
const server = http.createServer((req, res) => {
requestCount++;
// 记录请求信息
if (LOG_REQUESTS) {
const timestamp = new Date().toISOString();
console.log(`\n[${timestamp}] ${req.method} ${req.url}`);
console.log(`Headers:`, JSON.stringify(req.headers, null, 2));
}
// 处理健康检查
if (req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
status: 'OK',
uptime: process.uptime(),
stats: {
total_requests: requestCount,
success_count: successCount,
error_count: errorCount
}
}));
return;
}
// 解析URL
const parsedUrl = url.parse(req.url);
// 构造微信API请求选项
const wechatOptions = {
hostname: WECHAT_API_HOST,
port: 443,
path: parsedUrl.path,
method: req.method,
headers: {
// 保留原始headers,但替换Host
...req.headers,
host: WECHAT_API_HOST,
// 确保必要的headers
'User-Agent': req.headers['user-agent'] || 'WeChatProxy/1.0',
'Accept': req.headers.accept || '*/*'
}
};
// 处理请求体(POST/PUT等)
let reqData = null;
const contentLength = parseInt(req.headers['content-length'] || '0');
if (contentLength > 0 && (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH')) {
reqData = Buffer.alloc(contentLength);
let offset = 0;
req.on('data', (chunk) => {
chunk.copy(reqData, offset);
offset += chunk.length;
});
req.on('end', () => {
createWechatRequest(wechatOptions, reqData, res);
});
req.on('error', (err) => {
console.error('Request error:', err);
errorCount++;
res.writeHead(400);
res.end('Bad Request');
});
} else {
// GET/HEAD等无body请求
createWechatRequest(wechatOptions, null, res);
}
});
/**
* 优雅关闭处理
*/
process.on('SIGTERM', () => {
console.log('\n🛑 收到SIGTERM信号,正在关闭服务器...');
server.close(() => {
console.log('✅ 服务器已关闭');
process.exit(0);
});
});
process.on('SIGINT', () => {
console.log('\n🛑 收到SIGINT信号,正在关闭服务器...');
server.close(() => {
console.log('✅ 服务器已关闭');
process.exit(0);
});
});
// 启动服务器
server.listen(PORT, () => {
console.log(`🚀 微信API代理服务已启动`);
console.log(`📡 监听端口: ${PORT}`);
console.log(`🎯 目标API: https://${WECHAT_API_HOST}`);
console.log(`🏥 健康检查: http://localhost:${PORT}/health`);
console.log(`📊 日志记录: ${LOG_REQUESTS ? '开启' : '关闭'} (设置环境变量 LOG_REQUESTS=true 开启)`);
console.log('\n📝 使用说明:');
console.log('1. 确保你的服务器IP已在微信公众平台白名单中');
console.log('2. 在Coze中配置服务器地址为你的域名');
console.log('3. 调用微信API时会自动转发到官方接口');
console.log('\n⏰ 服务运行中,按 Ctrl+C 停止服务');
});
// 错误处理
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error(`❌ 端口 ${PORT} 已被占用,请更换端口或关闭占用进程`);
} else {
console.error('❌ 服务器错误:', err);
}
process.exit(1);
});