Files
whatsapp/api/request_large_file.php
T
2026-02-21 07:37:36 -05:00

157 lines
5.4 KiB
PHP

<?php
/**
* API: Solicitar archivo grande
*
* Genera un token único, crea la solicitud en BD y envía el enlace
* al cliente por WhatsApp.
*
* POST /api/request_large_file.php
* Body: { user_id: int, phone_number: string }
*
* Respuesta: { success: bool, request_id: int, token: string, upload_url: string }
*/
require_once __DIR__ . '/../config/config.php';
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', 0);
requireAuthentication();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
exit;
}
try {
$input = json_decode(file_get_contents('php://input'), true);
$userId = intval($input['user_id'] ?? 0);
$phoneNumber = trim($input['phone_number'] ?? '');
if (!$userId || empty($phoneNumber)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'Se requiere user_id y phone_number']);
exit;
}
$db = Database::getInstance();
// Verificar que el usuario existe
$user = $db->fetch("SELECT id, phone_number, name FROM users WHERE id = ?", [$userId]);
if (!$user) {
http_response_code(404);
echo json_encode(['success' => false, 'error' => 'Usuario no encontrado']);
exit;
}
// Usar el teléfono de la BD si no se proporcionó
$phone = !empty($phoneNumber) ? $phoneNumber : $user['phone_number'];
// Verificar si hay una solicitud pendiente activa (no expirada)
$existing = $db->fetch(
"SELECT id, token, expires_at FROM file_requests
WHERE user_id = ? AND status = 'pending' AND expires_at > NOW()
ORDER BY created_at DESC LIMIT 1",
[$userId]
);
if ($existing) {
// Reutilizar solicitud existente — reenviar enlace
$token = $existing['token'];
$requestId = $existing['id'];
} else {
// Generar nuevo token único (48 caracteres alfanuméricos)
$token = bin2hex(random_bytes(24));
// Operador que solicita
$requestedBy = $_SESSION['user_id'] ?? null;
// Crear solicitud — expira en 24 horas
$expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours'));
$requestId = $db->insert('file_requests', [
'token' => $token,
'user_id' => $userId,
'phone_number' => $phone,
'requested_by' => $requestedBy,
'status' => 'pending',
'max_file_size' => 52428800, // 50MB
'allowed_types' => 'image,document',
'expires_at' => $expiresAt,
]);
}
// Construir URL de carga
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$appUrl = $protocol . '://' . $_SERVER['HTTP_HOST'];
$uploadUrl = $appUrl . '/upload.php?token=' . $token;
// Enviar mensaje por WhatsApp con el enlace
$whatsapp = new WhatsAppService();
// Mensaje amigable con el enlace
$message = "📎 *Enlace para enviar archivos grandes*\n\n"
. "Hola" . ($user['name'] ? ", " . $user['name'] : "") . ".\n\n"
. "Le enviamos este enlace seguro para que pueda subir archivos de gran tamaño (hasta 50 MB):\n\n"
. "👉 " . $uploadUrl . "\n\n"
. "✅ Puede subir imágenes o documentos.\n"
. "🔒 El enlace es seguro y exclusivo para usted.\n"
. "⏰ Válido por 24 horas.\n\n"
. "_Si tiene alguna duda, estamos aquí para ayudarle._";
$sendResult = $whatsapp->sendTextMessage($phone, $message, [
'context_type' => 'file_request',
'file_request_id' => $requestId,
]);
// Guardar ID del mensaje enviado
if ($sendResult && isset($sendResult['messages'][0]['id'])) {
$messageId = $sendResult['messages'][0]['id'];
$db->update('file_requests',
['message_sent_id' => $messageId],
'id = ?', [$requestId]
);
}
// Crear notificación para el log
$db->insert('notifications', [
'user_id' => $userId,
'type' => 'file_request_sent',
'message' => 'Se envió enlace de carga de archivos a ' . ($user['name'] ?: $phone),
'data' => json_encode([
'request_id' => $requestId,
'token' => $token,
'upload_url' => $uploadUrl,
]),
'is_read' => 0,
]);
echo json_encode([
'success' => true,
'request_id' => $requestId,
'token' => $token,
'upload_url' => $uploadUrl,
'expires_at' => $existing ? $existing['expires_at'] : $expiresAt,
'message' => 'Enlace enviado al cliente por WhatsApp',
]);
} catch (Exception $e) {
$errorDetail = date('[Y-m-d H:i:s] ') . 'request_large_file ERROR: ' . $e->getMessage() . "\n" . $e->getTraceAsString() . "\n\n";
error_log('Error en request_large_file: ' . $e->getMessage() . ' | Trace: ' . $e->getTraceAsString());
@file_put_contents(__DIR__ . '/../logs/app_errors.log', $errorDetail, FILE_APPEND);
http_response_code(500);
echo json_encode(['success' => false, 'error' => 'Error interno: ' . $e->getMessage()]);
}