full
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Enviar mensaje multimedia
|
||||
* Fecha: 13 de enero de 2026
|
||||
*/
|
||||
|
||||
require_once '../config/config.php';
|
||||
|
||||
// Verificar autenticación
|
||||
requireAuthentication();
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: POST');
|
||||
header('Access-Control-Allow-Headers: Content-Type');
|
||||
|
||||
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);
|
||||
|
||||
if (!$input) {
|
||||
throw new Exception('Datos no válidos');
|
||||
}
|
||||
|
||||
// Validar campos requeridos
|
||||
if (empty($input['recipient']) || empty($input['media_url']) || empty($input['media_type'])) {
|
||||
throw new Exception('Faltan campos requeridos: recipient, media_url, media_type');
|
||||
}
|
||||
|
||||
$recipient = $input['recipient'];
|
||||
$mediaUrl = $input['media_url'];
|
||||
$mediaType = $input['media_type']; // image, video, audio, document
|
||||
$caption = $input['caption'] ?? null;
|
||||
$filename = $input['filename'] ?? null;
|
||||
|
||||
// Inicializar servicio de WhatsApp
|
||||
$whatsapp = new WhatsAppService();
|
||||
|
||||
// Enviar según tipo de media
|
||||
$response = null;
|
||||
|
||||
switch ($mediaType) {
|
||||
case 'image':
|
||||
$response = $whatsapp->sendImageMessage($recipient, $mediaUrl, $caption);
|
||||
break;
|
||||
|
||||
case 'video':
|
||||
$response = $whatsapp->sendVideoMessage($recipient, $mediaUrl, $caption);
|
||||
break;
|
||||
|
||||
case 'audio':
|
||||
$response = $whatsapp->sendAudioMessage($recipient, $mediaUrl);
|
||||
break;
|
||||
|
||||
case 'document':
|
||||
$response = $whatsapp->sendDocumentMessage($recipient, $mediaUrl, $filename, $caption);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Exception('Tipo de media no soportado: ' . $mediaType);
|
||||
}
|
||||
|
||||
if ($response && isset($response['messages'][0]['id'])) {
|
||||
// Guardar en base de datos
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Obtener usuario
|
||||
$user = $db->fetch(
|
||||
"SELECT id FROM users WHERE phone_number = ?",
|
||||
[$recipient]
|
||||
);
|
||||
|
||||
if ($user) {
|
||||
$db->insert('conversations', [
|
||||
'user_id' => $user['id'],
|
||||
'message_id' => $response['messages'][0]['id'],
|
||||
'direction' => 'outgoing',
|
||||
'message_type' => $mediaType,
|
||||
'content' => $caption ?? $filename ?? '',
|
||||
'media_url' => $mediaUrl,
|
||||
'status' => 'sent',
|
||||
'created_at' => date('Y-m-d H:i:s')
|
||||
]);
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Mensaje multimedia enviado correctamente',
|
||||
'data' => $response
|
||||
]);
|
||||
} else {
|
||||
throw new Exception('Error al enviar mensaje: ' . json_encode($response));
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error en send_media_message.php: " . $e->getMessage());
|
||||
http_response_code(500);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Subir archivos multimedia
|
||||
* Fecha: 13 de enero de 2026
|
||||
*/
|
||||
|
||||
require_once '../config/config.php';
|
||||
|
||||
// Verificar autenticación
|
||||
requireAuthentication();
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: POST');
|
||||
header('Access-Control-Allow-Headers: Content-Type');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
http_response_code(405);
|
||||
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
|
||||
exit;
|
||||
}
|
||||
|
||||
try {
|
||||
// Verificar que se subió un archivo
|
||||
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
|
||||
throw new Exception('No se recibió ningún archivo o hubo un error en la carga');
|
||||
}
|
||||
|
||||
$file = $_FILES['file'];
|
||||
$fileSize = $file['size'];
|
||||
$fileName = basename($file['name']);
|
||||
$fileTmpPath = $file['tmp_name'];
|
||||
$fileType = $file['type'];
|
||||
|
||||
// Validar tamaño según tipo
|
||||
$maxSize = 16 * 1024 * 1024; // 16MB por defecto
|
||||
|
||||
if (strpos($fileType, 'image/') === 0) {
|
||||
$maxSize = 5 * 1024 * 1024; // 5MB para imágenes
|
||||
} elseif (strpos($fileType, 'application/') === 0) {
|
||||
$maxSize = 100 * 1024 * 1024; // 100MB para documentos
|
||||
}
|
||||
|
||||
if ($fileSize > $maxSize) {
|
||||
throw new Exception('El archivo es demasiado grande. Máximo: ' . ($maxSize / 1024 / 1024) . 'MB');
|
||||
}
|
||||
|
||||
// Validar tipos de archivo permitidos
|
||||
$allowedTypes = [
|
||||
// Imágenes
|
||||
'image/jpeg', 'image/jpg', 'image/png', 'image/webp',
|
||||
// Videos
|
||||
'video/mp4', 'video/3gpp', 'video/quicktime',
|
||||
// Audios
|
||||
'audio/aac', 'audio/mp3', 'audio/mpeg', 'audio/ogg', 'audio/amr', 'audio/webm',
|
||||
// Documentos
|
||||
'application/pdf',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.ms-powerpoint',
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation'
|
||||
];
|
||||
|
||||
if (!in_array($fileType, $allowedTypes)) {
|
||||
throw new Exception('Tipo de archivo no permitido: ' . $fileType);
|
||||
}
|
||||
|
||||
// Crear directorio de uploads si no existe
|
||||
$uploadDir = __DIR__ . '/../uploads/';
|
||||
if (!is_dir($uploadDir)) {
|
||||
mkdir($uploadDir, 0755, true);
|
||||
}
|
||||
|
||||
// Generar nombre único
|
||||
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
|
||||
$uniqueName = uniqid('media_', true) . '.' . $extension;
|
||||
$uploadPath = $uploadDir . $uniqueName;
|
||||
|
||||
// Mover archivo
|
||||
if (!move_uploaded_file($fileTmpPath, $uploadPath)) {
|
||||
throw new Exception('Error al guardar el archivo en el servidor');
|
||||
}
|
||||
|
||||
// Construir URL pública
|
||||
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
|
||||
$host = $_SERVER['HTTP_HOST'];
|
||||
$publicUrl = $protocol . '://' . $host . '/whatsapp/uploads/' . $uniqueName;
|
||||
|
||||
// Determinar tipo de medio
|
||||
$mediaType = 'document';
|
||||
if (strpos($fileType, 'image/') === 0) {
|
||||
$mediaType = 'image';
|
||||
} elseif (strpos($fileType, 'video/') === 0) {
|
||||
$mediaType = 'video';
|
||||
} elseif (strpos($fileType, 'audio/') === 0) {
|
||||
$mediaType = 'audio';
|
||||
}
|
||||
|
||||
// Guardar información en base de datos (opcional)
|
||||
$db = Database::getInstance();
|
||||
$mediaId = $db->insert('media_files', [
|
||||
'filename' => $fileName,
|
||||
'unique_name' => $uniqueName,
|
||||
'file_type' => $fileType,
|
||||
'file_size' => $fileSize,
|
||||
'media_type' => $mediaType,
|
||||
'file_path' => $uploadPath,
|
||||
'public_url' => $publicUrl,
|
||||
'uploaded_by' => $_SESSION['user']['id'] ?? null,
|
||||
'created_at' => date('Y-m-d H:i:s')
|
||||
]);
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Archivo subido correctamente',
|
||||
'data' => [
|
||||
'id' => $mediaId,
|
||||
'filename' => $fileName,
|
||||
'url' => $publicUrl,
|
||||
'type' => $mediaType,
|
||||
'mime_type' => $fileType,
|
||||
'size' => $fileSize
|
||||
]
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error en upload_media.php: " . $e->getMessage());
|
||||
http_response_code(500);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user