Files
wacloud-meta-dev/application/controllers/webhook/Receive.php
T
2026-10-09 09:01:52 +00:00

361 lines
12 KiB
PHP

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Receive extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function index()
{
header('Content-Type: application/json');
// ✅ 1. Verifikasi Webhook dari Meta
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$verify_token = '9b8f999598fb2d51504c1062f15b2e26b9db19786b0bc67e5a54695ac37653d1'; // ubah dengan token kamu
$mode = $this->input->get('hub_mode');
$token = $this->input->get('hub_verify_token');
$challenge = $this->input->get('hub_challenge');
if ($mode === 'subscribe' && $token === $verify_token) {
echo $challenge;
exit;
} else {
http_response_code(403);
exit;
}
}
// ✅ 2. Terima data JSON dari Meta
$input = file_get_contents('php://input');
$data = json_decode($input, true);
// Simpan log mentah
$this->db->insert('logs', [
'event' => 'webhook_received',
'data' => json_encode($data)
]);
if (!isset($data['entry'][0]['changes'][0])) {
http_response_code(400);
echo json_encode(['status' => 'no_change']);
exit;
}
$change = $data['entry'][0]['changes'][0];
$value = $change['value'] ?? [];
$name = $value['contacts'][0]['profile']['name'] ?? '';
$messages = $value['messages'] ?? [];
$statuses = $value['statuses'] ?? [];
$metadata = $value['metadata'] ?? [];
$phone_number_id = $metadata['phone_number_id'] ?? null;
if (!$phone_number_id) {
http_response_code(400);
echo json_encode(['status' => 'no_phone_id']);
exit;
}
// Ambil data akun WA dari DB
$whatsapp_number = $this->db->where('phone_number_id', $phone_number_id)
->get('whatsapp_numbers')
->row_array();
if (!$whatsapp_number) {
http_response_code(404);
echo json_encode(['status' => 'unknown_number']);
exit;
}
//
// 📥 PESAN MASUK
//
if (!empty($messages)) {
foreach ($messages as $msg) {
$from = $msg['from'];
$msg_id = $msg['id'] ?? null;
$type = $msg['type'] ?? 'unknown';
$timestamp = isset($msg['timestamp'])
? date('Y-m-d H:i:s', $msg['timestamp'])
: date('Y-m-d H:i:s');
$text = '';
$content = null;
switch ($type) {
case 'text':
$text = $msg['text']['body'] ?? '';
$content = $msg['text'] ?? null;
break;
case 'image':
$text = '[Gambar diterima]';
$content = [
'id' => $msg['image']['id'] ?? '',
'mime_type' => $msg['image']['mime_type'] ?? '',
'caption' => $msg['image']['caption'] ?? ''
];
break;
case 'document':
$text = '[Dokumen diterima]';
$content = [
'id' => $msg['document']['id'] ?? '',
'filename' => $msg['document']['filename'] ?? '',
'mime_type' => $msg['document']['mime_type'] ?? '',
'caption' => $msg['document']['caption'] ?? ''
];
break;
case 'audio':
$text = '[Audio diterima]';
$content = [
'id' => $msg['audio']['id'] ?? '',
'mime_type' => $msg['audio']['mime_type'] ?? '',
'voice' => $msg['audio']['voice'] ?? false
];
break;
case 'video':
$text = '[Video diterima]';
$content = [
'id' => $msg['video']['id'] ?? '',
'mime_type' => $msg['video']['mime_type'] ?? '',
'caption' => $msg['video']['caption'] ?? ''
];
break;
case 'sticker':
$text = '[Stiker diterima]';
$content = [
'id' => $msg['sticker']['id'] ?? '',
'mime_type' => $msg['sticker']['mime_type'] ?? ''
];
break;
case 'location':
$text = '[Lokasi diterima]';
$content = [
'latitude' => $msg['location']['latitude'] ?? '',
'longitude' => $msg['location']['longitude'] ?? '',
'name' => $msg['location']['name'] ?? '',
'address' => $msg['location']['address'] ?? ''
];
break;
case 'contacts':
$text = '[Kontak diterima]';
$content = $msg['contacts'] ?? [];
break;
case 'button':
$text = '[Tombol ditekan]';
$content = [
'button' => $msg['button']['text'] ?? '',
'payload' => $msg['button']['payload'] ?? ''
];
break;
case 'interactive':
$text = '[Interaksi diterima]';
$interactive = $msg['interactive'] ?? [];
$content = $interactive;
if (isset($interactive['button_reply'])) {
$text = '[Tombol Dipilih] ' . ($interactive['button_reply']['title'] ?? '');
} elseif (isset($interactive['list_reply'])) {
$text = '[List Dipilih] ' . ($interactive['list_reply']['title'] ?? '');
}
break;
default:
$text = '[Pesan tipe ' . $type . ']';
$content = $msg ?? null;
}
// 🔍 Cari atau buat session
$session = $this->db->where([
'customer_number' => $from,
'whatsapp_number_id' => $whatsapp_number['id']
])->order_by('id', 'DESC')->get('sessions')->row_array();
if (!$session) {
$this->db->insert('sessions', [
'whatsapp_number_id' => $whatsapp_number['id'],
'user_id' => 1,
'customer_number' => $from,
'customer_name' => $name,
'status' => 'open'
]);
$session_id = $this->db->insert_id();
} else {
$session_id = $session['id'];
if (!empty($name) && $session['customer_name'] !== $name) {
$this->db->where('id', $session_id)->update('sessions', [
'customer_name' => $name
]);
}
}
// 💾 Simpan pesan ke tabel messages
$this->db->insert('messages', [
'session_id' => $session_id,
'direction' => 'in',
'message_type' => $type,
'message_body' => $text,
'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
'whatsapp_message_id' => $msg_id,
'status' => 'received',
'timestamp' => $timestamp
]);
$message_db_id = $this->db->insert_id();
$hasFile = false;
$insertId = null;
// ✅ Simpan ke message_files kalau ada file/media
if (in_array($type, ['image','document','audio','video','sticker'])) {
$media_id = $content['id'] ?? null;
$mime_type = $content['mime_type'] ?? null;
$meta_url = "https://graph.facebook.com/v20.0/{$media_id}";
$this->db->insert('message_files', [
'message_id' => $message_db_id,
'customer_number' => $from,
'meta_id' => $media_id,
'meta_url' => $meta_url,
'mime_type' => $mime_type,
'status' => 'pending',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
$insertId = $this->db->insert_id();
$hasFile = true;
}
// ⏰ Update waktu terakhir session
$this->db->where('id', $session_id)->update('sessions', [
'last_message_at' => date('Y-m-d H:i:s'),
'status' => 'open'
]);
$successDownload = true;
// Jika ada file, download dulu
if ($hasFile && $insertId) {
$url = base_url('get_file/download/' . $insertId);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // timeout 10 detik
$downloadResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$decoded = json_decode($downloadResponse, true);
// Cek sukses download: JSON valid dan status success=true
if (!$decoded || !isset($decoded['success']) || $decoded['success'] !== true) {
$successDownload = false;
log_message('error', "File ID {$insertId} gagal diunduh. Response: " . $downloadResponse);
}
}
// Kirim ke Node.js hanya jika:
// 1. Tidak ada file, atau
// 2. Ada file tapi berhasil di-download
$this->db->select('
m.id,
m.session_id,
m.direction,
m.message_type,
m.message_body,
m.content,
m.status,
m.timestamp,
f.file_name,
f.file_url,
f.mime_type,
f.file_size,
g.name
');
$this->db->from('messages m');
$this->db->join('message_files f', 'f.message_id = m.id', 'left');
$this->db->join('users g', 'g.id = m.user_id', 'left');
$this->db->where('m.id', $message_db_id);
$dataPesan = $this->db->get()->row_array();
$payload = [
'sender_id' => 1,
'receiver_id' => $whatsapp_number['id'],
'session_id' => $session_id,
'message' => $dataPesan,
'direction' => 'in'
];
$nodeJsUrl = 'http://manjapro.net:2233/triggerMessage';
$ch = curl_init($nodeJsUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$nodeResponse = curl_exec($ch);
$nodeHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($nodeHttpCode !== 200) {
log_message('error', "Gagal kirim pesan ID {$message_db_id} ke Node.js. HTTP: {$nodeHttpCode}, Response: {$nodeResponse}");
}
}
}
//
// 📤 STATUS PESAN KELUAR
//
if (!empty($statuses)) {
foreach ($statuses as $status) {
$message_id = $status['id'];
$recipient_id = $status['recipient_id'] ?? '';
$status_name = $status['status'];
$timestamp = date('Y-m-d H:i:s', $status['timestamp']);
// Update status di messages
$this->db
->where('whatsapp_message_id', $message_id)
->update('messages', [
'status' => $status_name
]);
// Log status
$this->db->insert('logs', [
'event' => 'message_status',
'data' => json_encode([
'message_id' => $message_id,
'recipient_id' => $recipient_id,
'status' => $status_name,
'timestamp' => $timestamp
])
]);
// // Update status di messages
// $this->db
// ->where('id', $session_id)
// ->update('sessions', [
// 'last_message_at' => date('Y-m-d H:i:s'),
// 'status' => 'open'
// ]);
}
}
echo json_encode(['status' => 'ok']);
exit;
}
}