phanquocdat123 commited on
Commit
64a39c8
·
verified ·
1 Parent(s): 74fe77f

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +19 -21
server.js CHANGED
@@ -119,10 +119,10 @@ app.get('/', (req, res) => {
119
  });
120
 
121
  // =========================================================
122
- // 🎯 1. ROUTE XÁC MINH WEBHOOK VỚI FACEBOOK (PHƯƠNG THỨC GET)
123
  // =========================================================
124
  app.get('/webhook', (req, res) => {
125
- // Hỗ trợ mở khóa Header cho các bên thứ ba kết nối (CORS)
126
  res.setHeader('Access-Control-Allow-Origin', '*');
127
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
128
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
@@ -130,39 +130,39 @@ app.get('/webhook', (req, res) => {
130
  const mode = req.query['hub.mode'];
131
  const token = req.query['hub.verify_token'];
132
  const challenge = req.query['hub.challenge'];
133
- const VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN || 'huong_kid_secure_2026';
 
 
134
 
135
  console.log(`🔍 [FB Check] Token nhận: "${token}" | Token gốc: "${VERIFY_TOKEN}"`);
136
 
137
- if (mode && token) {
138
- if (mode === 'subscribe' && token === VERIFY_TOKEN) {
139
- console.log('✅ [Facebook] Bắt tay thành công!');
140
- // Ép trả về kết quả định dạng text/plain chuẩn cấu trúc Meta mong muốn
141
- res.status(200).set('Content-Type', 'text/plain').send(challenge);
142
- return;
143
- } else {
144
- console.log('❌ [Facebook] Thất bại: Mã xác minh không khớp');
145
- res.sendStatus(403);
146
- return;
147
- }
148
  }
149
- res.sendStatus(400);
 
150
  });
151
 
152
-
 
 
153
  app.post('/webhook', async (req, res) => {
154
  let body = req.body;
155
  if (body.object === 'page') {
156
- res.status(200).send('EVENT_RECEIVED');
 
157
 
 
158
  for (let entry of body.entry) {
159
  if (entry.messaging) {
160
  let event = entry.messaging[0];
161
  let sender_id = event.sender.id;
162
 
163
- // --- XÁC ĐỊNH NỘI DUNG TIN NHẮN ---
164
  let received_text = "";
165
-
166
  if (event.message && event.message.quick_reply) {
167
  received_text = event.message.quick_reply.payload;
168
  } else if (event.message && event.message.text) {
@@ -171,7 +171,6 @@ app.post('/webhook', async (req, res) => {
171
  received_text = event.postback.payload;
172
  }
173
 
174
- // --- KIỂM TRA TRÙNG TIN NHẮN ---
175
  let message_id = event.message?.mid;
176
  if (message_id) {
177
  if (processedMessages.has(message_id)) continue;
@@ -179,7 +178,6 @@ app.post('/webhook', async (req, res) => {
179
  setTimeout(() => processedMessages.delete(message_id), 600000);
180
  }
181
 
182
- // --- GỬI ĐI XỬ LÝ ---
183
  if (received_text) {
184
  console.log(`📩 Nhận lệnh từ ${sender_id}: ${received_text}`);
185
  const result = await processChatLogicWithTrace(sender_id, received_text);
 
119
  });
120
 
121
  // =========================================================
122
+ // 🎯 1. ROUTE XÁC MINH WEBHOOK (THAM KHẢO LOGIC GOOGLE APPS SCRIPT)
123
  // =========================================================
124
  app.get('/webhook', (req, res) => {
125
+ // Ép cấu hình Header cho phép mọi nền tảng bên ngoài kết nối tự do (CORS)
126
  res.setHeader('Access-Control-Allow-Origin', '*');
127
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
128
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
 
130
  const mode = req.query['hub.mode'];
131
  const token = req.query['hub.verify_token'];
132
  const challenge = req.query['hub.challenge'];
133
+
134
+ // Lấy token từ biến môi trường, nếu trống sẽ tự dùng mã mặc định của bạn
135
+ const VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN || "huong_kid_secure_2026";
136
 
137
  console.log(`🔍 [FB Check] Token nhận: "${token}" | Token gốc: "${VERIFY_TOKEN}"`);
138
 
139
+ if (mode === "subscribe" && token === VERIFY_TOKEN) {
140
+ console.log("✅ Webhook đã được Facebook xác minh thành công!");
141
+
142
+ // MẸO CHÍ MẠNG: Ép kiểu trả về là văn bản thô (text/plain) giống hệt CreateTextOutput của Google
143
+ res.status(200).set('Content-Type', 'text/plain').send(challenge);
144
+ return;
 
 
 
 
 
145
  }
146
+
147
+ res.status(403).set('Content-Type', 'text/plain').send("Lỗi: Mã xác minh không khớp hoặc thiếu tham số.");
148
  });
149
 
150
+ // =========================================================
151
+ // 📩 2. ROUTE NHẬN TIN NHẮN TỪ FACEBOOK (PHƯƠNG THỨC POST)
152
+ // =========================================================
153
  app.post('/webhook', async (req, res) => {
154
  let body = req.body;
155
  if (body.object === 'page') {
156
+ // Trả về EVENT_RECEIVED ngay lập tức để Facebook không báo lỗi timeout
157
+ res.status(200).set('Content-Type', 'text/plain').send('EVENT_RECEIVED');
158
 
159
+ // Xử lý đọc tin nhắn ngầm phía sau
160
  for (let entry of body.entry) {
161
  if (entry.messaging) {
162
  let event = entry.messaging[0];
163
  let sender_id = event.sender.id;
164
 
 
165
  let received_text = "";
 
166
  if (event.message && event.message.quick_reply) {
167
  received_text = event.message.quick_reply.payload;
168
  } else if (event.message && event.message.text) {
 
171
  received_text = event.postback.payload;
172
  }
173
 
 
174
  let message_id = event.message?.mid;
175
  if (message_id) {
176
  if (processedMessages.has(message_id)) continue;
 
178
  setTimeout(() => processedMessages.delete(message_id), 600000);
179
  }
180
 
 
181
  if (received_text) {
182
  console.log(`📩 Nhận lệnh từ ${sender_id}: ${received_text}`);
183
  const result = await processChatLogicWithTrace(sender_id, received_text);