Files
whatsapp/fix_phone_number_id.php
T
2026-01-12 11:06:43 -05:00

220 lines
10 KiB
PHP

<?php
/**
* Corrección rápida para Phone Number ID problemático
* Fecha: 10 de enero de 2026
*
* Este script corrige específicamente el Phone Number ID problemático '858157464051987'
*/
require_once 'config/config.php';
// Solo permitir ejecución directa (no via include)
if (basename(__FILE__) !== basename($_SERVER['SCRIPT_NAME'])) {
die('Acceso no autorizado');
}
$message = '';
$error = '';
$currentPhoneId = WHATSAPP_PHONE_NUMBER_ID;
$isProblematic = ($currentPhoneId === '858157464051987');
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
if ($_POST['action'] === 'update_phone_id') {
$newPhoneId = trim($_POST['new_phone_id'] ?? '');
$newToken = trim($_POST['whatsapp_token'] ?? '');
if (empty($newPhoneId)) {
$error = 'El Phone Number ID es obligatorio';
} elseif (empty($newToken)) {
$error = 'El Token de WhatsApp es obligatorio';
} elseif (!preg_match('/^\d{10,20}$/', $newPhoneId)) {
$error = 'Phone Number ID debe ser numérico (10-20 dígitos)';
} elseif (!preg_match('/^EAA[A-Za-z0-9_-]+$/', $newToken)) {
$error = 'Formato de token inválido. Debe empezar con EAA';
} else {
try {
// Probar la nueva configuración antes de guardar
$testUrl = "https://graph.facebook.com/v22.0/{$newPhoneId}";
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "Authorization: Bearer {$newToken}\r\n"
]
]);
$testResponse = @file_get_contents($testUrl, false, $context);
$httpCode = 200;
if (isset($http_response_header)) {
foreach ($http_response_header as $header) {
if (strpos($header, 'HTTP/') === 0) {
$httpCode = (int) substr($header, 9, 3);
}
}
}
if ($httpCode !== 200) {
$error = 'No se puede validar el Phone Number ID. Verifique que sea correcto y que tenga permisos.';
} else {
// Actualizar en base de datos
$pdo = createDbConnection();
// Verificar si existe la tabla system_config
$tableExists = $pdo->query("SHOW TABLES LIKE 'system_config'")->rowCount() > 0;
if ($tableExists) {
// Actualizar Phone Number ID
$stmt = $pdo->prepare("
INSERT INTO system_config (config_key, config_value, updated_at)
VALUES (?, ?, NOW())
ON DUPLICATE KEY UPDATE config_value = VALUES(config_value), updated_at = NOW()
");
$stmt->execute(['whatsapp_phone_number_id', $newPhoneId]);
// Actualizar Token
$stmt->execute(['whatsapp_token', $newToken]);
$message = "✅ Configuración actualizada correctamente. Phone Number ID: {$newPhoneId}";
// Refrescar la página para mostrar la nueva configuración
header("Location: " . $_SERVER['PHP_SELF'] . "?updated=1");
exit;
} else {
$error = 'La tabla system_config no existe. Ejecute la instalación primero.';
}
}
} catch (Exception $e) {
$error = 'Error al actualizar configuración: ' . $e->getMessage();
}
}
}
}
// Si se redirigió después de actualizar
if (isset($_GET['updated'])) {
$message = "✅ Configuración actualizada correctamente.";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Corrección Phone Number ID - WhatsApp Bot</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="bg-light">
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card shadow">
<div class="card-header bg-danger text-white">
<h4 class="mb-0">
<i class="fas fa-exclamation-triangle"></i>
Corrección Phone Number ID Problemático
</h4>
</div>
<div class="card-body">
<?php if ($message): ?>
<div class="alert alert-success">
<i class="fas fa-check-circle"></i> <?= htmlspecialchars($message) ?>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>
<div class="alert alert-warning">
<h5><i class="fas fa-info-circle"></i> Problema Detectado</h5>
<p>El sistema está intentando usar el Phone Number ID: <code><?= htmlspecialchars($currentPhoneId) ?></code></p>
<?php if ($isProblematic): ?>
<p class="text-danger fw-bold">
⚠️ Este ID está generando el error: "Object with ID '858157464051987' does not exist, cannot be loaded due to missing permissions, or does not support this operation"
</p>
<?php endif; ?>
</div>
<div class="alert alert-info">
<h5><i class="fas fa-lightbulb"></i> Cómo obtener el Phone Number ID correcto:</h5>
<ol>
<li>Ve a <a href="https://developers.facebook.com/apps" target="_blank">Facebook for Developers</a></li>
<li>Selecciona tu app de WhatsApp Business</li>
<li>En el menú izquierdo, ve a "WhatsApp" → "API Setup"</li>
<li>Copia el "Phone Number ID" que aparece ahí</li>
<li>También copia tu "Access Token" si ha cambiado</li>
</ol>
</div>
<form method="POST" class="mt-4">
<input type="hidden" name="action" value="update_phone_id">
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="whatsapp_token" class="form-label">
<i class="fas fa-key"></i> WhatsApp Token *
</label>
<input type="text"
class="form-control"
id="whatsapp_token"
name="whatsapp_token"
value="<?= htmlspecialchars(WHATSAPP_TOKEN === 'TU_TOKEN_DE_WHATSAPP_AQUI' ? '' : WHATSAPP_TOKEN) ?>"
placeholder="EAA..."
required>
<div class="form-text">Debe empezar con EAA</div>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="new_phone_id" class="form-label">
<i class="fas fa-phone"></i> Nuevo Phone Number ID *
</label>
<input type="text"
class="form-control"
id="new_phone_id"
name="new_phone_id"
placeholder="123456789012345"
pattern="\d{10,20}"
required>
<div class="form-text">Solo números, 10-20 dígitos</div>
</div>
</div>
</div>
<div class="d-grid gap-2">
<button type="submit" class="btn btn-primary btn-lg">
<i class="fas fa-save"></i>
Actualizar Configuración
</button>
</div>
</form>
<hr>
<div class="text-center">
<a href="index.php" class="btn btn-secondary">
<i class="fas fa-arrow-left"></i> Volver al Panel
</a>
<a href="encontrar_phone_id.php" class="btn btn-info">
<i class="fas fa-search"></i> Encontrar Phone ID
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>