diff --git a/api/webhook.php b/api/webhook.php index 6599837..2ec6ec5 100644 --- a/api/webhook.php +++ b/api/webhook.php @@ -98,6 +98,11 @@ class WhatsAppWebhook { } private function processconversations($value) { + // Detectar si este mensaje llegó al número turnero + $receivingPhoneId = $value['metadata']['phone_number_id'] ?? null; + $turneroPhoneId = getConfigFromDB('whatsapp_phone_number_id_turnero', ''); + $isTurnero = $receivingPhoneId && $turneroPhoneId && ($receivingPhoneId === $turneroPhoneId); + // Aceptar tanto payloads con 'conversations' como con 'messages' (WhatsApp varía según la integración) $items = []; if (isset($value['conversations']) && is_array($value['conversations'])) { @@ -299,7 +304,8 @@ class WhatsAppWebhook { 'content' => $messageText, 'media_url' => $mediaUrl, 'status' => 'received', - 'is_read' => 0 + 'is_read' => 0, + 'canal' => $isTurnero ? 'turnero' : 'bot', ]; // Guardar whatsapp_media_id si el mediaUrl es un ID numérico de WhatsApp @@ -413,11 +419,13 @@ class WhatsAppWebhook { 'timestamp' => date('Y-m-d H:i:s') ]); - // Procesar con bot (protección contra excepciones externas) - try { - $this->botService->processMessage($user, $messageText, $messageType); - } catch (Exception $e) { - error_log("Bot processing failed: " . $e->getMessage()); + // Procesar con bot solo si el mensaje llegó al número principal + if (!$isTurnero) { + try { + $this->botService->processMessage($user, $messageText, $messageType); + } catch (Exception $e) { + error_log("Bot processing failed: " . $e->getMessage()); + } } } diff --git a/services/WhatsAppService.php b/services/WhatsAppService.php index f9ccc46..2e7e7c1 100644 --- a/services/WhatsAppService.php +++ b/services/WhatsAppService.php @@ -22,14 +22,23 @@ class WhatsAppService private $db; private $rateLimitMonitor; - public function __construct() + public function __construct($canal = null) { // Obtener configuración desde base de datos $config = getWhatsAppConfigFromDB(); - - $this->token = $config['token']; // Usar token de BD - $this->phoneNumberId = $config['phone_number_id']; // Usar phone_number_id de BD - $this->apiUrl = $config['api_url'] ?: 'https://graph.facebook.com/v22.0/'; // Usar api_url de BD + + $this->token = $config['token']; + $this->phoneNumberId = $config['phone_number_id']; + $this->apiUrl = $config['api_url'] ?: 'https://graph.facebook.com/v22.0/'; + + // Si se especifica canal 'turnero', usar el phone ID del número turnero + if ($canal === 'turnero') { + $turneroPhoneId = getConfigFromDB('whatsapp_phone_number_id_turnero', ''); + if ($turneroPhoneId) { + $this->phoneNumberId = $turneroPhoneId; + } + } + $this->db = Database::getInstance(); // Inicializar monitor de rate limit