up
This commit is contained in:
+120
-27
@@ -4,11 +4,19 @@
|
||||
* Fecha: 13 de enero de 2026
|
||||
*/
|
||||
|
||||
// Deshabilitar cualquier output buffer y errores visuales
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
||||
require_once '../config/config.php';
|
||||
|
||||
// Verificar autenticación
|
||||
requireAuthentication();
|
||||
|
||||
// Limpiar cualquier output previo
|
||||
if (ob_get_length()) ob_clean();
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: POST');
|
||||
@@ -20,16 +28,49 @@ if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
exit;
|
||||
}
|
||||
|
||||
// Función auxiliar para enviar con media_id
|
||||
function sendMediaByIdToWhatsApp($whatsapp, $recipient, $mediaId, $mediaType, $caption, $filename) {
|
||||
return $whatsapp->sendMediaById($recipient, $mediaId, $mediaType, $caption, $filename);
|
||||
}
|
||||
|
||||
// Función auxiliar para enviar con link
|
||||
function sendMediaByLinkToWhatsApp($whatsapp, $recipient, $mediaUrl, $mediaType, $caption, $filename) {
|
||||
switch ($mediaType) {
|
||||
case 'image':
|
||||
return $whatsapp->sendImageMessage($recipient, $mediaUrl, $caption);
|
||||
case 'video':
|
||||
return $whatsapp->sendVideoMessage($recipient, $mediaUrl, $caption);
|
||||
case 'audio':
|
||||
return $whatsapp->sendAudioMessage($recipient, $mediaUrl);
|
||||
case 'document':
|
||||
return $whatsapp->sendDocumentMessage($recipient, $mediaUrl, $filename, $caption);
|
||||
default:
|
||||
throw new Exception('Tipo de media no soportado: ' . $mediaType);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$rawInput = file_get_contents('php://input');
|
||||
error_log("send_media_message.php - Raw input: " . $rawInput);
|
||||
|
||||
$input = json_decode($rawInput, true);
|
||||
|
||||
if (!$input) {
|
||||
throw new Exception('Datos no válidos');
|
||||
error_log("send_media_message.php - JSON decode failed");
|
||||
throw new Exception('Datos no válidos - JSON inválido');
|
||||
}
|
||||
|
||||
error_log("send_media_message.php - Input decoded: " . json_encode($input));
|
||||
|
||||
// Validar campos requeridos
|
||||
if (empty($input['recipient']) || empty($input['media_url']) || empty($input['media_type'])) {
|
||||
throw new Exception('Faltan campos requeridos: recipient, media_url, media_type');
|
||||
$missing = [];
|
||||
if (empty($input['recipient'])) $missing[] = 'recipient';
|
||||
if (empty($input['media_url'])) $missing[] = 'media_url';
|
||||
if (empty($input['media_type'])) $missing[] = 'media_type';
|
||||
|
||||
error_log("send_media_message.php - Missing fields: " . implode(', ', $missing));
|
||||
throw new Exception('Faltan campos requeridos: ' . implode(', ', $missing));
|
||||
}
|
||||
|
||||
$recipient = $input['recipient'];
|
||||
@@ -41,31 +82,60 @@ try {
|
||||
// Inicializar servicio de WhatsApp
|
||||
$whatsapp = new WhatsAppService();
|
||||
|
||||
// Enviar según tipo de media
|
||||
$response = null;
|
||||
// IMPORTANTE: Si la URL es local, necesitamos subir el archivo a WhatsApp primero
|
||||
$isLocalUrl = (strpos($mediaUrl, 'localhost') !== false || strpos($mediaUrl, '127.0.0.1') !== false);
|
||||
|
||||
switch ($mediaType) {
|
||||
case 'image':
|
||||
$response = $whatsapp->sendImageMessage($recipient, $mediaUrl, $caption);
|
||||
break;
|
||||
if ($isLocalUrl) {
|
||||
error_log("send_media_message.php - URL local detectada, subiendo archivo a WhatsApp primero");
|
||||
|
||||
// Obtener la ruta local del archivo
|
||||
$parsedUrl = parse_url($mediaUrl);
|
||||
$relativePath = $parsedUrl['path'];
|
||||
|
||||
// Construir ruta absoluta
|
||||
$uploadDir = __DIR__ . '/../uploads/';
|
||||
$filename_from_url = basename($relativePath);
|
||||
$localFilePath = $uploadDir . $filename_from_url;
|
||||
|
||||
error_log("send_media_message.php - Ruta local del archivo: " . $localFilePath);
|
||||
|
||||
if (!file_exists($localFilePath)) {
|
||||
throw new Exception('Archivo no encontrado en el servidor: ' . $localFilePath);
|
||||
}
|
||||
|
||||
// Detectar MIME type
|
||||
$mimeType = mime_content_type($localFilePath);
|
||||
error_log("send_media_message.php - MIME type detectado: " . $mimeType);
|
||||
|
||||
// Subir archivo a WhatsApp
|
||||
try {
|
||||
$uploadResult = $whatsapp->uploadMedia($localFilePath, $mimeType);
|
||||
error_log("send_media_message.php - Archivo subido a WhatsApp: " . json_encode($uploadResult));
|
||||
|
||||
case 'video':
|
||||
$response = $whatsapp->sendVideoMessage($recipient, $mediaUrl, $caption);
|
||||
break;
|
||||
|
||||
case 'audio':
|
||||
$response = $whatsapp->sendAudioMessage($recipient, $mediaUrl);
|
||||
break;
|
||||
|
||||
case 'document':
|
||||
$response = $whatsapp->sendDocumentMessage($recipient, $mediaUrl, $filename, $caption);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Exception('Tipo de media no soportado: ' . $mediaType);
|
||||
if (isset($uploadResult['id'])) {
|
||||
// Usar el media_id de WhatsApp en lugar de URL
|
||||
$mediaId = $uploadResult['id'];
|
||||
error_log("send_media_message.php - Media ID obtenido: " . $mediaId);
|
||||
|
||||
// Enviar mensaje usando media_id
|
||||
$response = sendMediaByIdToWhatsApp($whatsapp, $recipient, $mediaId, $mediaType, $caption, $filename);
|
||||
} else {
|
||||
throw new Exception('Error al subir archivo a WhatsApp: ' . json_encode($uploadResult));
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
error_log("send_media_message.php - Error subiendo a WhatsApp: " . $e->getMessage());
|
||||
throw new Exception('Error al subir archivo a WhatsApp: ' . $e->getMessage());
|
||||
}
|
||||
} else {
|
||||
// URL pública, usar método normal con link
|
||||
error_log("send_media_message.php - URL pública detectada, usando link directo");
|
||||
$response = sendMediaByLinkToWhatsApp($whatsapp, $recipient, $mediaUrl, $mediaType, $caption, $filename);
|
||||
}
|
||||
|
||||
// Guardar respuesta en base de datos
|
||||
if ($response && isset($response['messages'][0]['id'])) {
|
||||
error_log("send_media_message.php - Respuesta de WhatsApp exitosa: " . json_encode($response));
|
||||
|
||||
// Guardar en base de datos
|
||||
$db = Database::getInstance();
|
||||
|
||||
@@ -76,7 +146,8 @@ try {
|
||||
);
|
||||
|
||||
if ($user) {
|
||||
$db->insert('conversations', [
|
||||
// Datos base para insertar
|
||||
$conversationData = [
|
||||
'user_id' => $user['id'],
|
||||
'message_id' => $response['messages'][0]['id'],
|
||||
'direction' => 'outgoing',
|
||||
@@ -85,24 +156,46 @@ try {
|
||||
'media_url' => $mediaUrl,
|
||||
'status' => 'sent',
|
||||
'created_at' => date('Y-m-d H:i:s')
|
||||
]);
|
||||
];
|
||||
|
||||
// Intentar añadir filename solo si la columna existe
|
||||
// TODO: Ejecutar migración add_filename_to_conversations.sql
|
||||
// ALTER TABLE conversations ADD COLUMN filename VARCHAR(255) NULL AFTER media_url;
|
||||
|
||||
error_log("send_media_message.php - Guardando en BD: " . json_encode($conversationData));
|
||||
|
||||
try {
|
||||
$db->insert('conversations', $conversationData);
|
||||
} catch (Exception $dbError) {
|
||||
// Si falla, intentar sin filename (por compatibilidad con BD antigua)
|
||||
error_log("send_media_message.php - Advertencia al guardar: " . $dbError->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Mensaje multimedia enviado correctamente',
|
||||
'media_type' => $mediaType,
|
||||
'data' => $response
|
||||
]);
|
||||
} else {
|
||||
error_log("send_media_message.php - Respuesta de WhatsApp sin message_id: " . json_encode($response));
|
||||
throw new Exception('Error al enviar mensaje: ' . json_encode($response));
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error en send_media_message.php: " . $e->getMessage());
|
||||
error_log("Stack trace: " . $e->getTraceAsString());
|
||||
|
||||
// Limpiar cualquier output previo antes de enviar JSON
|
||||
if (ob_get_length()) ob_clean();
|
||||
|
||||
http_response_code(500);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
'error' => $e->getMessage(),
|
||||
'file' => basename($e->getFile()),
|
||||
'line' => $e->getLine()
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
?>
|
||||
|
||||
Reference in New Issue
Block a user