Files
whatsapp/diagnostico_whatsapp_avanzado.php
T
2026-01-21 08:28:54 -05:00

258 lines
10 KiB
PHP

<?php
/**
* Diagnóstico avanzado de WhatsApp API
* Fecha: 5 de enero de 2026
*/
require_once 'config/config.php';
header('Content-Type: text/html; charset=utf-8');
echo "<!DOCTYPE html>
<html>
<head>
<title>Diagnóstico WhatsApp API</title>
<style>
body { font-family: 'Segoe UI', sans-serif; margin: 20px; background: #f5f5f5; }
.container { max-width: 900px; margin: 0 auto; }
.card { background: white; padding: 20px; margin: 15px 0; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
.success { color: #28a745; font-weight: bold; }
.error { color: #dc3545; font-weight: bold; }
.warning { color: #ffc107; font-weight: bold; }
.info { color: #17a2b8; font-weight: bold; }
pre { background: #f8f9fa; padding: 10px; border-radius: 4px; overflow-x: auto; }
.config-table { width: 100%; border-collapse: collapse; }
.config-table th, .config-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
.config-table th { background-color: #f2f2f2; }
</style>
</head>
<body>
<div class='container'>
<h1>🔍 Diagnóstico WhatsApp API</h1>";
// 1. Verificar configuraciones
echo "<div class='card'>
<h2>📋 Configuración Actual</h2>
<table class='config-table'>
<tr><th>Parámetro</th><th>Valor</th><th>Estado</th></tr>";
$config_items = [
'WHATSAPP_TOKEN' => WHATSAPP_TOKEN,
'WHATSAPP_PHONE_NUMBER_ID' => WHATSAPP_PHONE_NUMBER_ID,
'WHATSAPP_API_URL' => WHATSAPP_API_URL,
'WEBHOOK_VERIFY_TOKEN' => WEBHOOK_VERIFY_TOKEN
];
foreach ($config_items as $key => $value) {
$status = '';
if ($key === 'WHATSAPP_TOKEN') {
$display_value = substr($value, 0, 20) . '...';
$status = ($value !== 'TU_TOKEN_DE_WHATSAPP_AQUI' && !empty($value)) ?
"<span class='success'>✅ Configurado</span>" :
"<span class='error'>❌ No configurado</span>";
} elseif ($key === 'WHATSAPP_PHONE_NUMBER_ID') {
$display_value = $value;
$status = ($value !== 'TU_PHONE_ID_AQUI' && !empty($value)) ?
"<span class='success'>✅ Configurado</span>" :
"<span class='error'>❌ No configurado</span>";
} else {
$display_value = $value;
$status = !empty($value) ?
"<span class='success'>✅ Configurado</span>" :
"<span class='error'>❌ No configurado</span>";
}
echo "<tr><td><strong>$key</strong></td><td>$display_value</td><td>$status</td></tr>";
}
echo "</table></div>";
// 2. Verificar conexión a base de datos
echo "<div class='card'>
<h2>🗄️ Base de Datos</h2>";
try {
$db = Database::getInstance();
echo "<p class='success'>✅ Conexión a base de datos exitosa</p>";
// Verificar tabla system_config
try {
$configs = $db->fetchAll("SELECT config_key, config_value FROM system_config WHERE config_key IN ('whatsapp_token', 'whatsapp_phone_number_id', 'whatsapp_api_url')");
if (!empty($configs)) {
echo "<h3>Configuración en BD:</h3>";
echo "<table class='config-table'>";
echo "<tr><th>Clave</th><th>Valor</th></tr>";
foreach ($configs as $config) {
$display = ($config['config_key'] === 'whatsapp_token') ?
substr($config['config_value'], 0, 20) . '...' :
$config['config_value'];
echo "<tr><td>" . htmlspecialchars($config['config_key']) . "</td><td>" . htmlspecialchars($display) . "</td></tr>";
}
echo "</table>";
} else {
echo "<p class='warning'>⚠️ No hay configuración de WhatsApp en la base de datos</p>";
}
} catch (Exception $e) {
echo "<p class='warning'>⚠️ Tabla system_config no encontrada: " . $e->getMessage() . "</p>";
}
} catch (Exception $e) {
echo "<p class='error'>❌ Error de base de datos: " . $e->getMessage() . "</p>";
}
echo "</div>";
// 3. Probar conectividad con Facebook Graph API
echo "<div class='card'>
<h2>🌐 Conectividad Facebook Graph API</h2>";
if (WHATSAPP_TOKEN !== 'TU_TOKEN_DE_WHATSAPP_AQUI' && WHATSAPP_PHONE_NUMBER_ID !== 'TU_PHONE_ID_AQUI') {
// Prueba 1: Verificar el Phone Number ID
echo "<h3>📞 Verificación del Phone Number ID</h3>";
$ch = curl_init();
$url = WHATSAPP_API_URL . WHATSAPP_PHONE_NUMBER_ID;
$headers = [
'Authorization: Bearer ' . WHATSAPP_TOKEN,
'Content-Type: application/json'
];
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => true
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
echo "<p><strong>URL:</strong> $url</p>";
echo "<p><strong>HTTP Code:</strong> $httpCode</p>";
if ($error) {
echo "<p class='error'>❌ Error cURL: $error</p>";
} else {
$decoded = json_decode($response, true);
if ($httpCode === 200) {
echo "<p class='success'>✅ Phone Number ID válido</p>";
echo "<h4>Información del número:</h4>";
echo "<pre>" . json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "</pre>";
} else {
echo "<p class='error'>❌ Phone Number ID inválido o sin permisos</p>";
echo "<h4>Respuesta de la API:</h4>";
echo "<pre>" . json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "</pre>";
if (isset($decoded['error'])) {
echo "<div class='error'>";
echo "<h4>Detalles del error:</h4>";
echo "<p><strong>Mensaje:</strong> " . htmlspecialchars($decoded['error']['message'] ?? 'N/A') . "</p>";
echo "<p><strong>Tipo:</strong> " . htmlspecialchars($decoded['error']['type'] ?? 'N/A') . "</p>";
echo "<p><strong>Código:</strong> " . htmlspecialchars($decoded['error']['code'] ?? 'N/A') . "</p>";
if (isset($decoded['error']['error_subcode'])) {
echo "<p><strong>Subcódigo:</strong> " . htmlspecialchars($decoded['error']['error_subcode']) . "</p>";
}
echo "</div>";
}
}
}
// Prueba 2: Verificar permisos del token
echo "<h3>🔑 Verificación de permisos del token</h3>";
$ch = curl_init();
$debugUrl = "https://graph.facebook.com/debug_token?input_token=" . WHATSAPP_TOKEN . "&access_token=" . WHATSAPP_TOKEN;
curl_setopt_array($ch, [
CURLOPT_URL => $debugUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => true
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if (!$error && $httpCode === 200) {
$decoded = json_decode($response, true);
if (isset($decoded['data'])) {
echo "<h4>Información del token:</h4>";
echo "<pre>" . json_encode($decoded['data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "</pre>";
}
} else {
echo "<p class='warning'>⚠️ No se pudo verificar el token: $error</p>";
}
} else {
echo "<p class='error'>❌ Token o Phone Number ID no configurados correctamente</p>";
}
echo "</div>";
// 4. Recomendaciones
echo "<div class='card'>
<h2>💡 Recomendaciones y Soluciones</h2>";
$recommendations = [];
if (WHATSAPP_TOKEN === 'TU_TOKEN_DE_WHATSAPP_AQUI') {
$recommendations[] = "❌ <strong>Configure el token de WhatsApp:</strong> Vaya a la configuración del sistema y ingrese su token de WhatsApp Business API.";
}
if (WHATSAPP_PHONE_NUMBER_ID === 'TU_PHONE_ID_AQUI') {
$recommendations[] = "❌ <strong>Configure el Phone Number ID:</strong> Vaya a la configuración del sistema y ingrese su Phone Number ID.";
}
if (WHATSAPP_PHONE_NUMBER_ID === '858157464051987') {
$recommendations[] = "⚠️ <strong>Phone Number ID problemático:</strong> El ID '858157464051987' está generando errores. Verifique que:
<ul>
<li>El número esté verificado en Facebook Business</li>
<li>Tenga los permisos correctos (whatsapp_business_messaging)</li>
<li>La aplicación esté en modo de producción</li>
<li>El token tenga acceso a este número</li>
</ul>";
}
$recommendations[] = "✅ <strong>Verificar en Meta for Developers:</strong>
<ul>
<li>Vaya a <a href='https://developers.facebook.com/apps' target='_blank'>Facebook for Developers</a></li>
<li>Seleccione su aplicación de WhatsApp Business</li>
<li>Vaya a Configuración > WhatsApp > Números de teléfono</li>
<li>Verifique que el número esté activo y verificado</li>
<li>Copie el Phone Number ID correcto</li>
</ul>";
$recommendations[] = "🔧 <strong>Pasos para resolver el error:</strong>
<ol>
<li>Verifique que el Phone Number ID sea correcto</li>
<li>Asegúrese de que el token tenga permisos para el número</li>
<li>Verifique que la aplicación esté aprobada para producción</li>
<li>Compruebe que el número esté verificado en Meta Business</li>
</ol>";
foreach ($recommendations as $rec) {
echo "<div style='margin: 10px 0; padding: 10px; border-left: 4px solid #007bff; background: #f8f9ff;'>$rec</div>";
}
echo "</div>";
echo "<div class='card'>
<h2>🛠️ Acciones Rápidas</h2>
<div style='display: flex; gap: 10px; flex-wrap: wrap;'>
<a href='index.php#system_config' style='padding: 10px 20px; background: #007bff; color: white; text-decoration: none; border-radius: 5px;'>⚙️ Ir a Configuración</a>
<a href='configurar_whatsapp.php' style='padding: 10px 20px; background: #28a745; color: white; text-decoration: none; border-radius: 5px;'>📱 Configurar WhatsApp</a>
<a href='test_whatsapp_completo.php' style='padding: 10px 20px; background: #17a2b8; color: white; text-decoration: none; border-radius: 5px;'>🧪 Probar API</a>
</div>
</div>";
echo "</div></body></html>";
?>