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) {
+18
View File
@@ -0,0 +1,18 @@
[2026-01-21 14:30:04] Raw input: {"recipient":"573168950803","media_url":"http://127.0.0.1:8000/uploads/media_69712939441cb8.59251559.xlsx","media_type":"document","caption":null,"filename":"RECIBO Y VENTAS NOVIEMBRE 2024.xlsx"}
[2026-01-21 14:30:04] Input decoded: {"recipient":"573168950803","media_url":"http:\/\/127.0.0.1:8000\/uploads\/media_69712939441cb8.59251559.xlsx","media_type":"document","caption":null,"filename":"RECIBO Y VENTAS NOVIEMBRE 2024.xlsx"}
[2026-01-21 14:30:05] Upload result: {"id":"2300351387142914"}
[2026-01-21 14:30:05] Media ID obtained: 2300351387142914
[2026-01-21 14:30:07] Send media by id response: {"messaging_product":"whatsapp","contacts":[{"input":"573168950803","wa_id":"573168950803"}],"messages":[{"id":"wamid.HBgMNTczMTY4OTUwODAzFQIAERgSMEJGMDkyNUE1NkYxRkVGMURFAA=="}]}
[2026-01-21 14:30:07] WhatsApp response (successful): {"messaging_product":"whatsapp","contacts":[{"input":"573168950803","wa_id":"573168950803"}],"messages":[{"id":"wamid.HBgMNTczMTY4OTUwODAzFQIAERgSMEJGMDkyNUE1NkYxRkVGMURFAA=="}]}
[2026-01-21 14:33:47] Raw input: {"recipient":"573168950803","media_url":"http://127.0.0.1:8000/uploads/media_69712a19e9c953.62294619.webm","media_type":"audio","caption":null,"filename":"audio_1769024023114.webm"}
[2026-01-21 14:33:47] Input decoded: {"recipient":"573168950803","media_url":"http:\/\/127.0.0.1:8000\/uploads\/media_69712a19e9c953.62294619.webm","media_type":"audio","caption":null,"filename":"audio_1769024023114.webm"}
[2026-01-21 14:33:48] Upload result: {"id":"1286637259965817"}
[2026-01-21 14:33:48] Media ID obtained: 1286637259965817
[2026-01-21 14:33:50] Send media by id response: {"messaging_product":"whatsapp","contacts":[{"input":"573168950803","wa_id":"573168950803"}],"messages":[{"id":"wamid.HBgMNTczMTY4OTUwODAzFQIAERgSMzMwMDNEQTU0RUNBMENDNkM1AA=="}]}
[2026-01-21 14:33:50] WhatsApp response (successful): {"messaging_product":"whatsapp","contacts":[{"input":"573168950803","wa_id":"573168950803"}],"messages":[{"id":"wamid.HBgMNTczMTY4OTUwODAzFQIAERgSMzMwMDNEQTU0RUNBMENDNkM1AA=="}]}
[2026-01-21 14:34:32] Raw input: {"recipient":"573168950803","media_url":"http://127.0.0.1:8000/uploads/media_69712a426bfb28.87046164.webm","media_type":"audio","caption":null,"filename":"audio_1769024055430.webm"}
[2026-01-21 14:34:32] Input decoded: {"recipient":"573168950803","media_url":"http:\/\/127.0.0.1:8000\/uploads\/media_69712a426bfb28.87046164.webm","media_type":"audio","caption":null,"filename":"audio_1769024055430.webm"}
[2026-01-21 14:34:33] Upload result: {"id":"2656357121414699"}
[2026-01-21 14:34:33] Media ID obtained: 2656357121414699
[2026-01-21 14:34:34] Send media by id response: {"messaging_product":"whatsapp","contacts":[{"input":"573168950803","wa_id":"573168950803"}],"messages":[{"id":"wamid.HBgMNTczMTY4OTUwODAzFQIAERgSNkEyNzVBODA0MEQ3RTI3M0I0AA=="}]}
[2026-01-21 14:34:34] WhatsApp response (successful): {"messaging_product":"whatsapp","contacts":[{"input":"573168950803","wa_id":"573168950803"}],"messages":[{"id":"wamid.HBgMNTczMTY4OTUwODAzFQIAERgSNkEyNzVBODA0MEQ3RTI3M0I0AA=="}]}
+38
View File
@@ -290,6 +290,44 @@ if ($wantsJson) {
// Si se pidió proxy (download=1), traer el contenido y retornarlo como descarga
if ($download) {
// Si la URL apunta al mismo servidor (localhost/127.0.0.1 o al host actual), no usar curl (evita deadlocks en PHP built-in server)
$parsedUrl = parse_url($mediaUrl);
$host = isset($parsedUrl['host']) ? strtolower($parsedUrl['host']) : '';
$port = isset($parsedUrl['port']) ? $parsedUrl['port'] : null;
$isLocalHost = in_array($host, ['127.0.0.1', 'localhost']) || ($host && isset($_SERVER['HTTP_HOST']) && stripos($_SERVER['HTTP_HOST'], $host) !== false);
if ($isLocalHost) {
media_log("Serving local file directly for URL: {$mediaUrl}");
// Mapear path a archivo local seguro
$path = $parsedUrl['path'] ?? '';
// Asumir que los archivos subidos están en uploads/
$localPath = realpath(__DIR__ . '/../../' . ltrim($path, '/'));
$base = realpath(__DIR__ . '/../../uploads');
if (!$localPath || strpos($localPath, $base) !== 0 || !file_exists($localPath)) {
http_response_code(404);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['success' => false, 'error' => 'Archivo local no encontrado o ruta inválida', 'path' => $localPath]);
exit;
}
// Determinar mime type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($finfo, $localPath);
finfo_close($finfo);
header_remove('Content-Type');
header('Cache-Control: public, max-age=3600');
if (!empty($contentType)) header('Content-Type: ' . $contentType);
header('Content-Length: ' . filesize($localPath));
header('Content-Disposition: attachment; filename="' . basename($localPath) . '"');
readfile($localPath);
exit;
}
// Si no es local, hacer curl normal (incluye Authorization si aplica)
$ch = curl_init();
// Añadir Authorization si existe token en configuración
$token = getConfigFromDB('whatsapp_token', '');
+21
View File
@@ -20,3 +20,24 @@
[2026-01-21 14:19:26] Request: GET /api/version/media-url.php?id=3932473397057815 GET:{"id":"3932473397057815"} POST:[]
[2026-01-21 14:19:26] Graph API request to https://graph.facebook.com/v22.0/3932473397057815
[2026-01-21 14:19:27] Proxying Facebook media URL with Authorization to https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=3932473397057815&source=getMedia&ext=1769023457&hash=ARleg2ej-5Ypy9H7zywh-D2Y08uzbRBDLZvqCKFPAqdN4g
[2026-01-21 14:29:48] Request: GET /api/version/media-url.php?id=3932473397057815 GET:{"id":"3932473397057815"} POST:[]
[2026-01-21 14:29:48] Graph API request to https://graph.facebook.com/v22.0/3932473397057815
[2026-01-21 14:29:49] Proxying Facebook media URL with Authorization to https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=3932473397057815&source=getMedia&ext=1769024079&hash=ARmHfwDhkYqc87xd4jXybAeb9ffj3GnkkBhs0e52VtnFOg
[2026-01-21 14:30:20] Request: GET /api/version/media-url.php?url=http%3A%2F%2F127.0.0.1%3A8000%2Fuploads%2Fmedia_69712939441cb8.59251559.xlsx&download=1 GET:{"url":"http:\/\/127.0.0.1:8000\/uploads\/media_69712939441cb8.59251559.xlsx","download":"1"} POST:[]
[2026-01-21 14:31:30] Request: GET /api/version/media-url.php?url=http%3A%2F%2F127.0.0.1%3A8000%2Fuploads%2Fmedia_69712939441cb8.59251559.xlsx&download=1 GET:{"url":"http:\/\/127.0.0.1:8000\/uploads\/media_69712939441cb8.59251559.xlsx","download":"1"} POST:[]
[2026-01-21 14:33:27] Request: GET /api/version/media-url.php?id=3932473397057815 GET:{"id":"3932473397057815"} POST:[]
[2026-01-21 14:33:27] Graph API request to https://graph.facebook.com/v22.0/3932473397057815
[2026-01-21 14:33:27] Proxying Facebook media URL with Authorization to https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=3932473397057815&source=getMedia&ext=1769024297&hash=ARkBPTasx5on_6QDJs2baPhBGoihZq5Z5c4vzkSfrPBjQA
[2026-01-21 14:33:32] Request: GET /api/version/media-url.php?url=http%3A%2F%2F127.0.0.1%3A8000%2Fuploads%2Fmedia_69712939441cb8.59251559.xlsx&download=1 GET:{"url":"http:\/\/127.0.0.1:8000\/uploads\/media_69712939441cb8.59251559.xlsx","download":"1"} POST:[]
[2026-01-21 14:33:32] Serving local file directly for URL: http://127.0.0.1:8000/uploads/media_69712939441cb8.59251559.xlsx
[2026-01-21 14:33:40] Request: GET /api/version/media-url.php?id=3932473397057815 GET:{"id":"3932473397057815"} POST:[]
[2026-01-21 14:33:40] Graph API request to https://graph.facebook.com/v22.0/3932473397057815
[2026-01-21 14:33:41] Proxying Facebook media URL with Authorization to https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=3932473397057815&source=getMedia&ext=1769024311&hash=ARksncZdPSkgk9XaVJ3KveKlf2T0pAHd-KxkY-Y4RK31oA
[2026-01-21 14:35:45] Request: GET /api/version/media-url.php?url=http%3A%2F%2F127.0.0.1%3A8000%2Fuploads%2Fmedia_69712939441cb8.59251559.xlsx&download=1 GET:{"url":"http:\/\/127.0.0.1:8000\/uploads\/media_69712939441cb8.59251559.xlsx","download":"1"} POST:[]
[2026-01-21 14:35:45] Serving local file directly for URL: http://127.0.0.1:8000/uploads/media_69712939441cb8.59251559.xlsx
[2026-01-21 14:35:56] Request: GET /api/version/media-url.php?id=3932473397057815 GET:{"id":"3932473397057815"} POST:[]
[2026-01-21 14:35:56] Graph API request to https://graph.facebook.com/v22.0/3932473397057815
[2026-01-21 14:35:57] Proxying Facebook media URL with Authorization to https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=3932473397057815&source=getMedia&ext=1769024447&hash=ARnjjYGswWnH1Qjxi8vvJC4ZGyD5Z9MBWIqcJfjSoNreow
[2026-01-21 14:36:28] Request: GET /api/version/media-url.php?id=3932473397057815 GET:{"id":"3932473397057815"} POST:[]
[2026-01-21 14:36:28] Graph API request to https://graph.facebook.com/v22.0/3932473397057815
[2026-01-21 14:36:28] Proxying Facebook media URL with Authorization to https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=3932473397057815&source=getMedia&ext=1769024478&hash=ARnqos_pCP3NfJt-KYcvnkTwjW6kr9XG7VcoVUSjRh6YAQ
+4
View File
@@ -0,0 +1,4 @@
[21-Jan-2026 14:30:20 America/Bogota] PHP Warning: preg_match(): Unknown modifier '&' in C:\laragon\www\whatsapp\api\version\media-url.php on line 131
[21-Jan-2026 14:31:30 America/Bogota] PHP Warning: preg_match(): Unknown modifier '&' in C:\laragon\www\whatsapp\api\version\media-url.php on line 131
[21-Jan-2026 14:33:32 America/Bogota] PHP Warning: preg_match(): Unknown modifier '&' in C:\laragon\www\whatsapp\api\version\media-url.php on line 131
[21-Jan-2026 14:35:45 America/Bogota] PHP Warning: preg_match(): Unknown modifier '&' in C:\laragon\www\whatsapp\api\version\media-url.php on line 131