diff --git a/api/version/media-url.php b/api/version/media-url.php index 1e11cd3..5cf8126 100644 --- a/api/version/media-url.php +++ b/api/version/media-url.php @@ -7,6 +7,19 @@ */ require_once __DIR__ . '/../../config/config.php'; +// Debugging helpers: log errors to a file and initialize control vars +error_reporting(E_ALL); +ini_set('display_errors', '0'); +ini_set('log_errors', '1'); +ini_set('error_log', __DIR__ . '/media-url_error.log'); + +function media_log($msg) { + @file_put_contents(__DIR__ . '/media-url_debug.log', date('[Y-m-d H:i:s] ') . $msg . PHP_EOL, FILE_APPEND | LOCK_EX); +} + +$resolvedFromGraph = false; +$decoded = null; + $isGet = $_SERVER['REQUEST_METHOD'] === 'GET'; $accept = $_SERVER['HTTP_ACCEPT'] ?? ''; $wantsJson = strpos($accept, 'application/json') !== false; @@ -83,12 +96,17 @@ if ($providedUrl) { $err = curl_error($ch); curl_close($ch); - if (!$err && $httpCode < 400) { + if ($err || $httpCode >= 400) { + media_log("Graph API fetch failed for mid {$mid} - http: {$httpCode} - err: {$err} - resp: " . substr($response ?? '', 0, 1000)); + } else { $decoded = json_decode($response, true); $resolvedUrl = $decoded['url'] ?? ($decoded['data'][0]['url'] ?? null); if ($resolvedUrl) { $mediaUrl = $resolvedUrl; $resolvedFromGraph = true; + media_log("Resolved media URL from Graph for mid {$mid}: {$mediaUrl}"); + } else { + media_log("Graph returned no media URL for mid {$mid} - resp: " . substr($response ?? '', 0, 1000)); } } // Si hubo error o no devolvió URL, seguimos usando la URL provista como fallback @@ -99,11 +117,21 @@ if ($providedUrl) { $apiUrl = rtrim(getConfigFromDB('whatsapp_api_url', 'https://graph.facebook.com/v22.0/'), '/'); $endpoint = "{$apiUrl}/{$mediaId}"; + if (empty($token)) { + media_log("Missing whatsapp_token for Graph API request to {$endpoint}"); + http_response_code(500); + header('Content-Type: application/json; charset=utf-8'); + echo json_encode(['success' => false, 'error' => 'Missing whatsapp_token in configuration']); + exit; + } + + media_log("Graph API request to {$endpoint}"); + $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => true, - CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . $token ], + CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . $token, 'Accept: application/json' ], CURLOPT_TIMEOUT => 15, ]); $response = curl_exec($ch);