This commit is contained in:
lizandrogd
2026-01-21 14:36:29 -05:00
parent 9b35b990ab
commit 9881a94301
5 changed files with 148 additions and 1 deletions
+67 -1
View File
@@ -11,6 +11,43 @@ ini_set('log_errors', 1);
require_once '../config/config.php';
// Helper logger para debugging específico de este endpoint
function smm_log($msg) {
static $triedInit = false;
$path = __DIR__ . '/send_media_message_debug.log';
$dir = dirname($path);
$entry = date('[Y-m-d H:i:s] ') . $msg . PHP_EOL;
$ok = false;
// Intentar crear directorio si es necesario
if (!is_dir($dir) && !file_exists($dir)) {
@mkdir($dir, 0755, true);
}
// Intentar abrir y escribir
$fp = @fopen($path, 'a');
if ($fp) {
if (@fwrite($fp, $entry) !== false) {
$ok = true;
}
@fclose($fp);
}
// Si falla, fallback a error_log y marcar bandera
if (!$ok) {
@error_log("smm_log (fallback): " . $msg);
global $smm_log_write_failed;
$smm_log_write_failed = true;
}
if (!$triedInit) {
$triedInit = true;
if (isset($smm_log_write_failed) && $smm_log_write_failed) {
@error_log('smm_log: debug log write failed, check permissions on ' . $dir);
}
}
}
// Verificar autenticación
requireAuthentication();
@@ -52,15 +89,18 @@ function sendMediaByLinkToWhatsApp($whatsapp, $recipient, $mediaUrl, $mediaType,
try {
$rawInput = file_get_contents('php://input');
error_log("send_media_message.php - Raw input: " . $rawInput);
smm_log("Raw input: " . $rawInput);
$input = json_decode($rawInput, true);
if (!$input) {
error_log("send_media_message.php - JSON decode failed");
smm_log("JSON decode failed. Raw: " . $rawInput);
throw new Exception('Datos no válidos - JSON inválido');
}
error_log("send_media_message.php - Input decoded: " . json_encode($input));
smm_log("Input decoded: " . json_encode($input));
// Validar campos requeridos
if (empty($input['recipient']) || empty($input['media_url']) || empty($input['media_type'])) {
@@ -111,15 +151,19 @@ try {
try {
$uploadResult = $whatsapp->uploadMedia($localFilePath, $mimeType);
error_log("send_media_message.php - Archivo subido a WhatsApp: " . json_encode($uploadResult));
smm_log("Upload result: " . json_encode($uploadResult));
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);
smm_log("Media ID obtained: " . $mediaId);
// Enviar mensaje usando media_id
$response = sendMediaByIdToWhatsApp($whatsapp, $recipient, $mediaId, $mediaType, $caption, $filename);
smm_log("Send media by id response: " . json_encode($response));
} else {
smm_log("Upload did not return id: " . json_encode($uploadResult));
throw new Exception('Error al subir archivo a WhatsApp: ' . json_encode($uploadResult));
}
} catch (Exception $e) {
@@ -143,8 +187,24 @@ try {
}
}
// Si no hay id, pero la respuesta es un string (posible JSON crudo), intentar decodificar
if (!$sentMessageId && is_string($response)) {
$maybe = json_decode($response, true);
if (is_array($maybe)) {
error_log("send_media_message.php - Decoded raw response string to array for inspection");
// Reasignar response para usar la estructura decodificada
$response = $maybe;
if (isset($response['conversations'][0]['id'])) {
$sentMessageId = $response['conversations'][0]['id'];
} elseif (isset($response['messages'][0]['id'])) {
$sentMessageId = $response['messages'][0]['id'];
}
}
}
if ($response && $sentMessageId) {
error_log("send_media_message.php - Respuesta de WhatsApp exitosa: " . json_encode($response));
smm_log("WhatsApp response (successful): " . json_encode($response));
// Guardar en base de datos
$db = Database::getInstance();
@@ -190,7 +250,13 @@ try {
]);
} 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));
// Añadir contexto adicional para debugging: guardar la respuesta cruda y tipo
$raw = is_string($response) ? $response : json_encode($response);
error_log("send_media_message.php - Raw response: " . substr($raw, 0, 2000));
smm_log("Raw response: " . substr($raw, 0, 2000));
throw new Exception('Error al enviar mensaje: ' . $raw);
}
} catch (Exception $e) {