Compare commits

..

40 Commits

Author SHA1 Message Date
84a25a829c Feat(Plugin): Implementación Microservicio PDF, Integración MinIO, Fix Recorte y Overlay de Pagos
Descripción:

Se ha realizado una refactorización mayor del sistema de notificaciones y generación de comprobantes para eliminar dependencias legacy (Imagick/FTP) y modernizar la arquitectura.

🚀 Nuevas Características (Features)
Microservicio PDF (pdf-cropper):

Nuevo servicio en Python (FastAPI + Poppler) desplegado en Docker (Puerto 8050) para la conversión de PDF a Imagen.
Reemplaza la librería Imagick de PHP, aislando el procesamiento pesado fuera del plugin.
Modo Full: Garantiza la conversión del PDF completo respetando su relación de aspecto original (sin recortes ni "square crop").
Overlay de Texto: Capacidad nativa en el backend para sobreescribir texto dinámicamente (ej. cambiar "Tarjeta de crédito Stripe" por "OXXO Pay") basado en parámetros.
Integración S3 / MinIO:

Implementación de
MinioStorageService
.
Los comprobantes (JPG) y Vouchers OXXO se suben automáticamente a MinIO en lugar de usar FTP.
Generación de URLs públicas seguras.
🧹 Mantenimiento y Limpieza (Chores/Refactor)
Limpieza Automática (Cleanup):

Se implementó lógica para eliminar archivos temporales locales (PDFs descargados, JPGs generados) inmediatamente después de una subida exitosa a MinIO.
Aplica tanto para comprobantes de pago como para Vouchers OXXO.
Refactor
ClientCallBellAPI
:

Eliminación de código muerto relacionado con FTP de WordPress.
Implementación de cliente HTTP Guzzle para comunicación con pdf-cropper.
Cache Busting: Se añade Timestamp al nombre de archivo (_time()) para evitar caché agresivo en WhatsApp/Navegadores.
Detección de Método: Lógica preliminar para detectar "OXXO" o "Transferencia" en notas de pago y aplicar Overlay.
Docker Infraestructura:

Actualización de
docker-compose.yml
 para incluir pdf-cropper.
Instalación de fuentes (fonts-dejavu-core) para renderizado correcto de texto.
🐛 Correcciones (Bug Fixes)
Fix Recorte de Imagen: Se eliminó la restricción de relación de aspecto 1:1 (cuadrado) que cortaba headers y footers en documentos rectangulares.
Standardización de Notas: Actualización de
AbstractStripeOperationsFacade
 para incluir explícitamente "OXXO" o "Transferencia" en las notas de pago de UCRM (preparación para lógica de plantillas).
2026-01-14 22:56:17 -06:00
e1937f9ac3 feat: integrate Stripe payments and UI refinements into WhatsApp Dashboard
- Migrated PaymentIntentService with plugin-specific namespacing.
- Added AJAX endpoints for client searching and SPEI reference generation.
- Implemented global premium header with SIIP Blue gradient.
- Optimized sidebar UI: increased logo size to 180px and nav icons/text.
- Improved Dark Mode accessibility with high-contrast primary colors.
- Added "View in CRM" functionality and automated Stripe admin logic.
- Fixed layout nesting issues and polished CSS layering.
2026-01-08 15:30:07 -06:00
f851ea6d7d feat: soporte multi-servicio, optimización lazy loading y sincronización avanzada con CallBell
- Implementación de gestión multi-servicio para contraseñas de antena con etiquetas condicionales.
- Optimización de rendimiento mediante lazy loading para evitar llamadas redundantes a la API de UISP.
- Mejora de sincronización con CallBell: contraseñas en formato JSON, unificación de peticiones PATCH y corrección de comparación de saldo.
- Generación de contraseñas printer-friendly (alfanuméricas + @, #) sin caracteres ambiguos.
- Validación granular de provisionamiento para evitar errores en sitios inactivos.
- Actualización de CHANGELOG.md y README.md.
2026-01-03 11:07:29 -06:00
761cd667b5 feat: soporte multi-servicio, optimización de recursos y refinamiento de contraseñas
- Implementado soporte multi-servicio para antenas con formato "Servicio X: <pass>".
- Añadido sistema de "Lazy Check" para evitar llamadas redundantes a la API de UISP si ya existe una contraseña válida.
- Refinado algoritmo de generación de contraseñas: ahora son "Printer-Friendly" (alfanumérico + @, #) y sin caracteres ambiguos.
- Mejorada la lógica de detección de antenas: validación por etapas (Servicio -> Sitio -> Dispositivo) para evitar errores en sitios inactivas.
- Agregados mensajes informativos de estado en el CRM (⚠️ Sin sitio, ⚠️ Sin antena).
- Corregido bucle infinito de webhooks en entornos de prueba mediante validación de idempotencia.
- Actualizada documentación (README.md y CHANGELOG.md) a la versión 3.0.0.
2026-01-02 22:41:54 -06:00
b0b56a59ce feat: Dashboard administrativo, integración con API UCRM y optimización de Stripe
- Implementación de Dashboard profesional en public.php con CRUD de instaladores.
- Sincronización con la API de UCRM para selección y validación automática de administradores.
- Soporte para creación selectiva de clientes en Stripe (Etiqueta "CREAR CLIENTE STRIPE" vs "CREAR CLABE STRIPE").
- Mejora en la lógica de notificaciones de tareas (nuevo prefijo [CLIENTE-SIN-WHATSAPP]).
- Refactorización integral de fachadas y saneamiento de código muerto.
- Sistema de Modo Oscuro persistente con UI refinada.
2025-12-27 23:15:32 -06:00
5425659428 antes de la limpieza y refacorización del código 2025-12-24 02:03:41 -06:00
0e37fd153f feat(stripe-sync): implementar resolución dinámica de métodos de pago y corregir validación API
- Se agregó 'getPaymentMethodIdByName' para buscar automáticamente el ID de "Transferencia bancaria" por nombre, asegurando portabilidad entre servidores UISP.
- Se implementó el manejo del webhook 'customer_cash_balance_transaction.created' para el registro automático de pagos fondeados.
- Fix: Se corrigió error 422 en la API de UCRM forzando el cast de 'clientId' a integer y 'methodId' a string (GUID).
- Se actualizó la documentación (README/CHANGELOG) con instrucciones de configuración de webhooks.
2025-12-23 14:50:57 -06:00
506615e911 Se agrega nuevo campo en los ajustes del plugin para agregar la API KEY del UNMS con el ID 'unmsApiToken' 2025-10-20 15:13:21 -06:00
2e21e09c2c Corrección de bug para poder utilizar la dirección ip del servicio Puppeteer dentro del código para referencias de OXXO PAGO, también se agregó un campo de configuración para el servicio de Puppeteer así como el código para utilizar dicho campo. 2025-08-01 08:47:33 -06:00
a0f286969a Actualización que ajusta los permisos de acceso a la API del CRM y NMS, además se realizaron cambios en el menú de ajustes para agregar el campo del toke de la api de nms y el campo del id del administrador para pagos en linea con Stripe, además se hizo el ajuste para el bug que no permitía realizar intenciones de pago cuando la cantidad trae signo de pesos 2025-07-31 15:23:49 -06:00
c9e2466353 Solucionado el bug que impedía regresar en la respuesta el monto total hacia el bot de CallBell, lo que hacía que mostrara siempre Cantidad cero, esto se realizó en el archivo AbstractOxxoOperationsFacade.php 2025-06-11 11:07:59 -06:00
8d8a1ec648 Modificaciones para enviar referencias de OXXO PAGO por medio de imagen 2025-06-10 02:46:31 -06:00
c73a51bbf2 Se modificó la información para el envío de notificaciones a llos instaladores en el flujo de trabajo para la desasignación de tareas que hacía que no se viera correctamente la información 2025-06-05 12:01:03 -06:00
5374054289 Cambios para quitar la hora de los mensajes que se envían a los clientes, corrección en la función getVaultCredentials para poder enviar el mensaje con la contraseña al instalador 2025-06-02 17:45:28 -06:00
e899945ca3 Versión 2.8.2 Rutina de envio de mensajes con plantillas de utilidad refactorizado, además tipo de pago 'applied_to_payment' en en analisis de webhooks de Stripe 2025-05-27 15:57:43 -06:00
e34b3ec0f8 Versión 2.8.0 README ACTUALIZADO 2025-05-21 21:39:50 -06:00
3a39a53da6 Versión 2.8.0 2025-05-21 21:31:09 -06:00
7cb26fe735 Se agregó una función que permite recuperar una contraseña de antena en función del ID del cliente y enviarla por mensaje de notificación al instalador para tareas que se le asignen, además de modificaron los IDs de plantillas de mensajes y se eleiminó el campo de dirección para la notioficación de tarea o servicio del instalador. 2025-05-10 11:21:43 -06:00
9a3af1f3d4 Version 2.7.1 con la opción de generar clabes interbancarias por medio de una etiqueta con nombre 'CREARCLABESTRIPE' y además permite crear las clabes de manera automática cuando el cliente pasa de potencial a cliente regular, se corrige un error que permitía generar de manera indefinida clabes para un cliente, además también se agregó la eliminación de la etiqueta 'CREARCLABESTRIPE' de manera automática cuando termina de generar una clabe interbancaria y cliente de Sripe y también valida si ya tiene uno creado con anterioridad para descartar solicitudes hechas a clientes que ya posean dichos datos 2025-03-25 07:46:08 -06:00
96d7fe6b27 Version 2.7.0 con la opción de generar clabes interbancarias por medio de una etiqueta con nombre 'CREARCLABESTRIPE' y además permite crear las clabes de manera automática cuando el cliente pasa de potencial a cliente regular 2025-03-24 22:47:43 -06:00
9db9febc39 Versión 2.6.9.1 con modificaciones para devolver mas campos en la respuesta a una creación de referencia de OXXO, como tal son los campos de oxxo_reference, error, failDescription, clientID, clientFullName, amount como número entero 2025-03-08 08:13:48 +00:00
59aac17968 Versión 2.6.9 con modificaciones para devolver mas campos en la respuesta a una creación de referencia de OXXO, como tal son los campos de oxxo_reference, error, failDescription, clientID, clientFullName, amount 2025-03-08 00:09:06 +00:00
2819804ad8 HotFix para manejo de excepciones de timeout para referencias de oxxo, ahora se envian las claves 'error' y 'url' en el mismo cuerpo de la respuesta, también se mejoró el código del método para crear la referencia de oxxo y el de edición del cliente para agregar los campos personalizados de Site y Antena/Sectorial 2025-03-05 05:33:07 +00:00
4276097212 HotFix para manejo de excepciones de timeout para referencias de oxxo y otros errores versión 2 con ajuste de codigos 2025-03-04 10:04:00 +00:00
cd74cafeda HotFix para manejo de excepciones de timeout para referencias de oxxo y otros errores 2025-03-04 09:32:03 +00:00
398dcc462f Adición de los eventos: [invoice.draft_approved, invoice.add_draft] para sincronizar el saldo del cliente a CallBell así como del evento service.edit 2025-02-18 23:27:27 +00:00
c3824ba827 Hot fix para poder enviar notoficaciones a mas de un contacto de tipo whatsapp en un mismo cliente, verificacion para la sincroniazacion de clientes hacia callbell cuando se agrega una factura o se edita ademas s ajustó para que solo se pueda editar el email en stripe cuando se haga una edición en el CRM 2025-02-18 10:42:18 +00:00
e1e3f409c9 Hot fix para arreglar el error que no permitía generar pagos por referencia 2025-02-06 23:48:51 +00:00
eafc867742 Versión 2.6.3 HOT FIX que arregla el bug que impedía hacer referencias de oxxo porque se duplicaba la multiplicación del factor 100 para la conversión de centavos 2025-02-02 22:42:29 +00:00
12d19c46de Versión 2.6.2 correción de la rutina de envio de pdf 2025-01-27 09:29:45 +00:00
9fc3bcb8d9 Versión 2.6.1 ajuste de la hora, negritas en el folio y el envio correcto de desasignacion de servicio 2025-01-25 16:42:25 +00:00
8e5b144796 Versión 2.6.1 ajuste de la hora, negritas en el folio y el envio correcto de desasignacion de servicio 2025-01-25 16:36:47 +00:00
869331b02c Versión 2.6.0 completa 2025-01-24 16:07:10 +00:00
11b7d7cacc corrección de referencias oxxo con linea return y rutina para ir evaluando los jobs 2025-01-18 03:52:06 +00:00
efd6f36c37 Rework para clientes pontenciales nuevos, eliminacion del tiempo de espera para intentos de creacion de referencias de oxxo 2025-01-14 09:10:39 +00:00
93a0f30eec Hot fix para nuevos clientes potenciales, se evitara hacer un Stripe customer ID, se ajuto el email del cliente por defecto para crear paymenIntent para pagos de Oxxo 2025-01-07 23:14:34 +00:00
3b3cd70ece Cambios para validar cantidad, mas logs para errores y poner email por defecto al cliente, manifest 2025-01-05 19:43:42 +00:00
f7119a4512 Cambios para validar cantidad, mas logs para errores y poner email por defecto al cliente 2025-01-05 19:39:57 +00:00
9e78efdf2f Cambios para procesar referencias oxxo con hasta 5 intentos 2025-01-04 08:36:11 +00:00
1731eb1813 Cambios en el comprobante de pago, imagen sin recorte 2025-01-03 21:36:27 +00:00
7790 changed files with 521370 additions and 71979 deletions

8
.gitignore vendored Executable file
View File

@ -0,0 +1,8 @@
*.pdf
*.log
*.png
*.jpeg
.vscode/
*.zip
vouchers_oxxo/
comprobantes/

5
.vscode/extensions.json vendored Executable file
View File

@ -0,0 +1,5 @@
{
"recommendations": [
"github.copilot-chat"
]
}

69
.vscode/launch.json vendored Executable file
View File

@ -0,0 +1,69 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch",
"port": 9003
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 0,
"runtimeArgs": [
"-dxdebug.start_with_request=yes"
],
"env": {
"XDEBUG_MODE": "debug,develop",
"XDEBUG_CONFIG": "client_port=${port}"
}
},
{
"name": "Launch Built-in web server",
"type": "php",
"request": "launch",
"runtimeArgs": [
"-dxdebug.mode=debug",
"-dxdebug.start_with_request=yes",
"-S",
"localhost:0"
],
"program": "",
"cwd": "${workspaceRoot}",
"port": 9003,
"serverReadyAction": {
"pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
"uriFormat": "http://localhost:%s",
"action": "openExternally"
}
},
{
"name": "Launch built-in server and Debug",
"type": "php",
"request": "launch",
"noDebug": false,
"runtimeArgs": [
"-S",
"localhost:8000",
"-t",
"."
],
"cwd": "${workspaceRoot}/.",
"serverReadyAction": {
"action": "openExternally"
}
},
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch"
}
]
}

123
CHANGELOG.md Executable file
View File

@ -0,0 +1,123 @@
# CHANGELOG - siip-whatsapp-notifications
## VERSIÓN 4.1.0 - 15-01-2026
### 🚀 Nuevas Características (Features)
1. **Microservicio PDF (`pdf-cropper`)**:
* Nuevo servicio en Python (FastAPI + Poppler) desplegado en Docker (Puerto 8050) para la conversión de PDF a Imagen.
* Reemplaza la librería `Imagick` de PHP, aislando el procesamiento pesado fuera del plugin.
* **Modo Full**: Garantiza la conversión del PDF completo respetando su relación de aspecto original (sin recortes ni "square crop").
* **Overlay de Texto**: Capacidad nativa en el backend para sobreescribir texto dinámicamente (ej. cambiar "Tarjeta de crédito Stripe" por "OXXO Pay") basado en parámetros.
2. **Integración S3 / MinIO**:
* Implementación de `MinioStorageService`.
* Los comprobantes (JPG) y Vouchers OXXO se suben automáticamente a MinIO en lugar de usar FTP.
* Generación de URLs públicas seguras.
### 🧹 Mantenimiento y Limpieza (Chores/Refactor)
1. **Limpieza Automática (Cleanup)**:
* Se implementó lógica para eliminar archivos temporales locales (PDFs descargados, JPGs generados) inmediatamente después de una subida exitosa a MinIO.
2. **Refactor `ClientCallBellAPI`**:
* Eliminación de código muerto relacionado con FTP de WordPress.
* Implementación de cliente HTTP Guzzle para comunicación con `pdf-cropper`.
* **Cache Busting**: Se añade Timestamp al nombre de archivo (`_time()`) para evitar caché agresivo en WhatsApp/Navegadores.
### 🐛 Correcciones (Bug Fixes)
1. **Fix Recorte de Imagen**: Se eliminó la restricción de relación de aspecto 1:1 (cuadrado) para evitar recortes.
2. **Standardización de Notas**: Actualización de `AbstractStripeOperationsFacade` para incluir explícitamente "OXXO" o "Transferencia" en las notas de pago.
## VERSIÓN 4.0.0 - 10-01-2026
### 🟢 Novedades (Re-diseño UI/UX + Integ. Pagos)
1**Portal Administrativo Integrado (Stripe + Oxxo)**: Se ha rediseñado completamente el panel administrativo (`Dashboard`) para incluir una sección dedicada a **Pagos Online**, permitiendo la generación de referencias SPEI y OXXO Pay sin salir del portal.
2**Visualización Inline de Vouchers OXXO**: Ahora los comprobantes de pago OXXO se generan y visualizan inmediatamente en una vista partida (Datos + Imagen) dentro del dashboard, eliminando la necesidad de abrir enlaces externos para verificación.
3**Carga FTP Híbrida**: Optimización inteligente que sube los vouchers al servidor FTP solo cuando es necesario (integraciones externas/webhooks) y utiliza visualización local para el administrador, garantizando máxima velocidad de interfaz.
4**Modo Oscuro & UI Premium**: Nueva capa visual con sidebar expandido, cabecera global "Sticky", y un sistema de colores adaptativo (Modo Sol/Luna) para una mejor experiencia de usuario.
5**Seguridad Reforzada**: Refactorización completa del manejo de credenciales, eliminando datos hardcodeados en el código y centralizándolos en la configuración segura del plugin.
### 🔵 Mejoras
1**Navegación Intuitiva**: Menú lateral rediseñado con accesos directos claros a "Pagos Stripe", "Notificaciones" y "Gestión de Instaladores".
2**Feedback Visual**: Nuevas alertas toast y modales informativos para confirmar acciones (Generación de referencias, errores de API, etc.).
3**Compatibilidad**: Ajustes en `manifest.json` y estructura de archivos para asegurar compatibilidad total con las últimas versiones de UISP.
## VERSIÓN 3.1.0 - 07-01-2026
### 🟢 Novedades
1**Re-envío Manual de Notificaciones de Pago**: Se añadió un nuevo apartado en el Dashboard que permite buscar clientes y re-disparar notificaciones de WhatsApp para pagos específicos de forma manual.
2**Buscador de Clientes en Dashboard**: Integración de buscador dinámico para localizar clientes y visualizar su historial de los últimos 10 pagos.
## VERSIÓN 3.0.0 - 02-01-2026
### 🟢 Novedades
1**Soporte Multi-Servicio para Antenas**: Ahora el plugin gestiona múltiples servicios por cliente, mostrando cada contraseña con el formato `Servicio 1: <pass> Servicio 2: <pass> ...`.
2**Validación Granular de Provisionamiento**: Se implementó una lógica de detección por etapas (Servicio -> Sitio UISP -> Dispositivo) para evitar generar contraseñas en sitios "Location Inactive".
3**Lazy Loading & Optimización de Recursos**: Implementación de un "Lazy Check" que detecta si ya hay una contraseña válida en el CRM para omitir llamadas innecesarias a la API de UISP, mejorando la velocidad y reduciendo el consumo de CPU.
### 🔵 Mejoras
1**Etiquetado Inteligente de Servicios**: Las etiquetas `Servicio 1:`, `Servicio 2:` ahora solo aparecen si el cliente tiene múltiples servicios; para un solo servicio, la contraseña se muestra directamente.
2**Sincronización Avanzada con CallBell**:
- Nuevo campo `Password Antena` enviado en formato JSON estructurado.
- Unificación de peticiones PATCH (Resumen + Campos) en una sola llamada para mayor eficiencia.
3**Contraseñas "Printer-Friendly"**: El generador de contraseñas ahora utiliza un set de caracteres optimizado para mini-impresoras térmicas (Alfanumérico + `@`, `#`), eliminando caracteres ambiguos como `l`, `I`, `0`, `O`.
4**Mensajes de Estado en CRM**: Se agregaron alertas visuales en el campo de contraseña para indicar estados de provisión: `⚠️ Sin sitio vinculado`, `⚠️ Sin antena vinculada`, `⚠️ Cliente sin servicios`.
5**Robustez en Entornos de Prueba**: Refinamiento del bypass de desarrollo para mantener la estabilidad de las claves generadas y evitar bucles infinitos de webhooks.
### 🟡 Bugs Resueltos
1**Sincronización de Saldo**: Se corrigió la discrepancia de nombres entre `Saldo Actual` y `Saldo` que causaba actualizaciones redundantes infinitas con CallBell.
2**Parseo de Passwords**: Refinamiento de expresiones regulares para capturar correctamente contraseñas multi-servicio.
3⃣ Se solucionó el bucle infinito de actualizaciones en el atributo `passwordAntenaCliente` que ocurría al detectar cambios en servicios sin dispositivos vinculados.
## VERSIÓN 2.9.3 - 23-12-2025
### 🟢 Novedades
1⃣ Resolución dinámica del ID del método de pago ("Transferencia bancaria") mediante consulta a la API de UISP, mejorando la portabilidad del plugin entre distintos servidores.
2⃣ Implementación de registro de pago automático desde Webhook Stripe para eventos de tipo `customer_cash_balance_transaction.created` (Saldo aplicado).
### 🟡 Bugs Resueltos
1⃣ Se corrigió el error de validación de la API de UCRM (422) mediante el cast explícito de `clientId` a integer y el uso de `methodId` como string.
## VERSIÓN 2.9.2
### 🟡 Bugs Resueltos
1⃣ Se solucionó un bug que impedía obtener la contraseñas de la bóveda, ya que el response de la API cambió en la última actualización y la esstructura nueva impedía acceder al dato del password
## VERSIÓN 2.8.8
### 🟡 Bugs Resueltos
1⃣ Se solucionó un bug que impedía al BOT del CallBell mostrar el monto de la referencia de OXXO en el mensaje donde se le entrega el voucher al cliente, para el caso donde el cliente elegía crear su referencia con la CANTIDAD TOTAL.
## VERSIÓN 2.8.7
### 🟢 Novedades
1⃣ Ahora las referencias de **OXXO Pago** han cambiado, en lugar de enviarse la URL o link de pago al cliente será la imagen del código de barras y la información que aparece en el link directamente en el mensaje, de esta manera será más cómodo para el cliente tener la imagen en su chat a tener que abrir una URL o link externo.
### 🔵 Mejoras
1⃣ Se modificaron nodos del bot ***OXXO_BOT*** para poder adaptar esta actualización correctamente.
2⃣ Mejoras en el código fuente del flujo de trabajo para las referencias de OXXO PAGO.
## VERSIÓN 2.8.6
### 🔵 Mejoras
1⃣ Se modificó la información para el envío de notificaciones a llos instaladores en el flujo de trabajo para la desasignación de tareas que hacía que no se viera correctamente la información
## VERSIÓN 2.8.5
### 🔵 Mejoras
1⃣ Se modificó la información para el envío de notificaciones a los clientes para su visita técnica: ahora ya no se envían las horas en que serán las visitas, SOLO LA FECHA.
2⃣ Se crearon nuevas plantillas de tipo utilidad y se adaptaron al flujo de trabajo en el código.
### 🟡 Bugs Resueltos
1⃣ Se soluciono el bug que impedía enviar notificaciones a los instaladores para nuevas tareas.
## VERSIÓN 2.8.2
### 🟡 Bugs Resueltos
1⃣ No se enviaban las notificaciones de las tareas al instalador. Se cambió la plantilla de CallBell o WhatsApp con 3 variables en lugar de 8.
2⃣ Se agregó un nuevo tipo de pago ("applied_to_payment") en las propiedades de los Webhooks recibidos mediante Stripe por concepto de transferencias bancarias. Ya que sólo se revisaba el tipo de pago "funded" y eso hacía que no enviara los comprobantes de pago a los clientes para todos los casos.
## VERSIÓN 2.8.1
### 🟡 Bugs Resueltos
1⃣ No se enviaban las notificaciones de las tareas al instalador.
## VERSIÓN 2.8.0
### 🟢 Novedades
1⃣ Envío de contraseña de antena en el mensaje que se manda al instalador cuando se le asigna una tarea/servicio.
2⃣ Para clientes nuevos o que no tengan el campo personalizado de “Password Antena Cliente” al actualizarlos se les asignará ese campo o cuando se les actualice su servicio.
3⃣ Ahora se puede modificar tantas veces sea necesaria una tarea o servicio como su fecha o el instalador mientras la tarea permanezca en estado “Abiertos” SIN que se envíen notificaciones a los clientes o instaladores.
4⃣ Se agregó un prefijo al título de la tarea/servicio agendado cuando recién se da de alta para identificar que esta no ha sido notificada aún y se pueden realizar ajustes.
### 🔵 Mejoras
1⃣ Se modificó el flujo de trabajo para el envío de notificaciones a los clientes para su visita técnica, ahora son cuatro distintos tipos de flujo, anteriormente tres.
2⃣ Se reemplazaron algunas plantillas de mensajes de CallBell.
3⃣ Se renombró el uso de la etiqueta “CREARCLABESTRIPE” por “CREAR CLABE STRIPE” para un mejor entendimiento de su uso.
### 🟡 Bugs Resueltos
1⃣ Envío de notificaciones a los clientes y a los instaladores al CERRAR una tarea/servicio (Se mandaban mensajes de asignación y de visita del técnico ) haciendo no posible cerrar las tareas.

File diff suppressed because it is too large Load Diff

261
README.md
View File

@ -1,212 +1,83 @@
# SMS notifier - Twilio # SIIP - WhatsApp Notifications & Integrated Payment Portal
* This plugin sends SMS notifications to clients. ![Version](https://img.shields.io/badge/version-4.1.0-blue.svg?style=for-the-badge)
* SMS is triggered by an event which happened in UCRM, e.g. new invoice has been issued, or client's sevice became suspended. ![UCRM Compatibility](https://img.shields.io/badge/UCRM-v2.1.0%2B-green.svg?style=for-the-badge)
* It only sends SMS to clients having a phone number set in their contacts details. ![Status](https://img.shields.io/badge/status-PRODUCTION-success.svg?style=for-the-badge)
* [Twilio](https://www.twilio.com/) account is required to access its API. ![Author](https://img.shields.io/badge/author-SIIP_INTERNET-orange.svg?style=for-the-badge)
## Configuration Este plugin es una solución integral que transforma tu UCRM en un **Portal Administrativo de Última Generación**. No solo automatiza la comunicación por WhatsApp, sino que integra un Dashboard completo para la gestión de pagos online (Stripe/OXXO), visualización de comprobantes y coordinación de equipos técnicos.
* Install the plugin into UCRM and enable it. I.e. download the plugin [zip file](https://github.com/Ubiquiti-App/UCRM-plugins/raw/master/plugins/sms-twilio/sms-twilio.zip) and upload it to UCRM in System > Plugins. ## 🚀 Novedades v4.1.0 (Performance & Storage)
* Keep execution period at "don't execute automatically" - the plugin will react to webhook events.
* Set up with data which you obtain from [Twilio Console](https://twilio.com/console):
* Account SID
* Auth Token
* SMS number to send from
Note: there are two sets of credentials available, the default ("LIVE credentials") for actual use and [test credentials](https://www.twilio.com/console/project/settings) for development. - **⚡ Microservicio PDF (`pdf-cropper`)**: Nuevo motor de renderizado externo (Python/FastAPI) que reemplaza librerías legacy, aumentando la velocidad y eliminando problemas de memoria en el servidor principal.
- **📦 MinIO / S3 Storage**: Migración completa del almacenamiento de comprobantes. Adiós FTP, hola almacenamiento de objetos seguro y escalable con URLs firmadas y limpieza automática.
- **🖼️ Smart Image Processing**: Generación de imágenes "Full Mode" (sin recortes) y capacidad de **Edición Dinámica de Texto** (Overlay) para personalizar métodos de pago en los comprobantes.
* Customize the texts you wish to send to a client when an event happens ## 🚀 Novedades v4.0.0 (Portal Dashboard)
* Each event has its own row
* Empty row means "do not send SMS for this"
* It is possible to replace predefined variables: `%%some.variable%%`, see full list below
* If a variable is not set for a client, it is replaced with an empty string
* Save the configuration
* Enable the plugin
* Add webhook (button next to Public URL)
* Select events about which to notify clients and save the webhook endpoint
## Usage - **🖥️ Dashboard de Pagos Integrado**: Nueva interfaz visual dentro de UCRM para gestionar cobros de Stripe y OXXO sin salir de la plataforma.
* In UCRM admin, go to System / Webhooks / Endpoints - **🏪 OXXO Pay Híbrido & Visual**: Generación de fichas OXXO con dos modos inteligentes:
* Click Test Endpoint - **Inline (Admin)**: Visualización inmediata del voucher (local) para máxima velocidad.
* Go to System / Plugins / SMS notifications via Twilio - **FTP (Webhook)**: Carga automática a servidor externo para compartir links públicos.
* In the log output, you'll see `Webhook test successful.` - **🌑 UI/UX Premium**: Interfaz rediseñada con Sidebar expandible, cabecera global "Sticky", Modo Oscuro automático y componentes responsivos.
## Variables replaced ---
These are loaded from UCRM API, and reflect the structure returned. ## ⚡ Funcionalidades Principales
Client variables are replaced always; payment invoice and service only with the applicable events.
### Client variables ### 1. Gestión de Cobranza Avanzada
- **Pagos SPEI**: Instrucciones inmediatas con CLABE personalizada.
- **Vouchers OXXO**: Generación instantánea de códigos de barras con vista previa "Split-Screen" (Datos + Imagen).
- **Historial en Tiempo Real**: Consulta los últimos 10 pagos de cualquier cliente al instante.
* `%%client.id%%` => 20 ### 2. Automatización WhatsApp (CallBell)
* `%%client.userIdent%%` => '18' - **Notificaciones Dinámicas**: Envío automático de facturas, recordatorios de pago y avisos de corte.
* `%%client.previousIsp%%` => '' - **Re-envío Manual**: Herramienta para disparar notificaciones específicas desde el Dashboard si el proceso automático falla.
* `%%client.isLead%%` => false - **Sincronización Total**: Mantiene los contactos de CallBell siempre actualizados con los datos del CRM.
* `%%client.clientType%%` => 1
* `%%client.companyName%%` => ''
* `%%client.companyRegistrationNumber%%` => ''
* `%%client.companyTaxId%%` => ''
* `%%client.companyWebsite%%` => ''
* `%%client.street1%%` => '2544 Hillview Drive'
* `%%client.street2%%` => ''
* `%%client.city%%` => 'San Jose'
* `%%client.countryId%%` => 249
* `%%client.stateId%%` => 5
* `%%client.zipCode%%` => '95113'
* `%%client.invoiceStreet1%%` => ''
* `%%client.invoiceStreet2%%` => ''
* `%%client.invoiceCity%%` => ''
* `%%client.invoiceStateId%%` => ''
* `%%client.invoiceCountryId%%` => ''
* `%%client.invoiceZipCode%%` => ''
* `%%client.invoiceAddressSameAsContact%%` => true
* `%%client.note%%` => ''
* `%%client.sendInvoiceByPost%%` => false
* `%%client.invoiceMaturityDays%%` => 14
* `%%client.stopServiceDue%%` => true
* `%%client.stopServiceDueDays%%` => 7
* `%%client.organizationId%%` => 1
* `%%client.tax1Id%%` => 1
* `%%client.tax2Id%%` => ''
* `%%client.tax3Id%%` => ''
* `%%client.registrationDate%%` => '2016-04-26 00:00'
* `%%client.companyContactFirstName%%` => ''
* `%%client.companyContactLastName%%` => ''
* `%%client.isActive%%` => false
* `%%client.firstName%%` => 'Tyson'
* `%%client.lastName%%` => 'Doe'
* `%%client.username%%` => 'tyson.doe@example.com'
* `%%client.accountBalance%%` => 0
* `%%client.accountCredit%%` => 0
* `%%client.accountOutstanding%%` => 0
* `%%client.currencyCode%%` => 'USD'
* `%%client.organizationName%%` => 'UBNT ISP'
* `%%client.invitationEmailSentDate%%` => ''
* `%%client.avatarColor%%` => '#e53935'
* `%%client.addressGpsLat%%` => 37.401482000001
* `%%client.addressGpsLon%%` => -121.966545
* `%%client.message%%` => 'This is an example message sent from the Messaging feature.'
### Invoice variables ### 3. Coordinación Técnica (Jobs/Tasks)
* `%%invoice.id%%` => 4 - **Agenda Inteligente**: Notifica a instaladores sobre nuevas tareas y reprogramaciones.
* `%%invoice.clientId%%` => 20 - **Datos para Técnicos**: Envía coordenadas GPS y contraseñas de equipos (formato impresora térmica) directamente al WhatsApp del técnico.
* `%%invoice.number%%` => '2016050002'
* `%%invoice.createdDate%%` => '2016-05-03 00:00'
* `%%invoice.dueDate%%` => '2016-05-17 00:00'
* `%%invoice.emailSentDate%%` => '2018-08-24 00:00'
* `%%invoice.maturityDays%%` => 14
* `%%invoice.notes%%` => ''
* `%%invoice.adminNotes%%` => ''
* `%%invoice.subtotal%%` => 7.88
* `%%invoice.discount%%` => ''
* `%%invoice.discountLabel%%` => ''
* `%%invoice.total%%` => 7.88
* `%%invoice.amountPaid%%` => 7.88
* `%%invoice.currencyCode%%` => 'USD'
* `%%invoice.status%%` => 3
* `%%invoice.invoiceTemplateId%%` => 1
* `%%invoice.organizationName%%` => 'UBNT ISP'
* `%%invoice.organizationRegistrationNumber%%` => ''
* `%%invoice.organizationTaxId%%` => ''
* `%%invoice.organizationStreet1%%` => '2580 Orchard Parkway'
* `%%invoice.organizationStreet2%%` => ''
* `%%invoice.organizationCity%%` => 'New York'
* `%%invoice.organizationStateId%%` => 1
* `%%invoice.organizationCountryId%%` => 249
* `%%invoice.organizationZipCode%%` => '10017'
* `%%invoice.organizationBankAccountName%%` => ''
* `%%invoice.organizationBankAccountField1%%` => ''
* `%%invoice.organizationBankAccountField2%%` => ''
* `%%invoice.clientFirstName%%` => 'Tyson'
* `%%invoice.clientLastName%%` => 'Doe'
* `%%invoice.clientCompanyName%%` => ''
* `%%invoice.clientCompanyRegistrationNumber%%` => ''
* `%%invoice.clientCompanyTaxId%%` => ''
* `%%invoice.clientStreet1%%` => '685 Third Avenue'
* `%%invoice.clientStreet2%%` => ''
* `%%invoice.clientCity%%` => 'New York'
* `%%invoice.clientCountryId%%` => 249
* `%%invoice.clientStateId%%` => 5
* `%%invoice.clientZipCode%%` => '10017'
* `%%invoice.uncollectible%%` => false
### Payment variables ---
* `%%payment.id%%` => 28
* `%%payment.clientId%%` => 20
* `%%payment.invoiceId%%` => ''
* `%%payment.method%%` => 2
* `%%payment.checkNumber%%` => ''
* `%%payment.createdDate%%` => '2018-08-24 11:36'
* `%%payment.amount%%` => 1
* `%%payment.currencyCode%%` => 'USD'
* `%%payment.note%%` => ''
* `%%payment.receiptSentDate%%` => ''
* `%%payment.providerName%%` => ''
* `%%payment.providerPaymentId%%` => ''
* `%%payment.providerPaymentTime%%` => ''
* `%%payment.creditAmount%%` => 0
* `%%payment.applyToInvoicesAutomatically%%` => false
### Service variables ## 🏗️ Arquitectura del Sistema
* `%%service.id%%` => 23
* `%%service.clientId%%` => 20
* `%%service.status%%` => 1
* `%%service.name%%` => 'Mini'
* `%%service.street1%%` => '622 Hide A Way Road'
* `%%service.street2%%` => ''
* `%%service.city%%` => 'San Jose'
* `%%service.countryId%%` => 249
* `%%service.stateId%%` => 5
* `%%service.zipCode%%` => '95135'
* `%%service.note%%` => ''
* `%%service.addressGpsLat%%` => 37.232849
* `%%service.addressGpsLon%%` => -121.752502
* `%%service.servicePlanId%%` => 1
* `%%service.servicePlanPeriodId%%` => 2
* `%%service.price%%` => 25
* `%%service.hasIndividualPrice%%` => false
* `%%service.totalPrice%%` => 25
* `%%service.currencyCode%%` => 'USD'
* `%%service.invoiceLabel%%` => ''
* `%%service.contractId%%` => ''
* `%%service.contractLengthType%%` => 1
* `%%service.minimumContractLengthMonths%%` => ''
* `%%service.activeFrom%%` => '2016-05-03T00:00:00+0000'
* `%%service.activeTo%%` => ''
* `%%service.contractEndDate%%` => ''
* `%%service.discountType%%` => 0
* `%%service.discountValue%%` => ''
* `%%service.discountInvoiceLabel%%` => ''
* `%%service.discountFrom%%` => ''
* `%%service.discountTo%%` => ''
* `%%service.tax1Id%%` => ''
* `%%service.tax2Id%%` => ''
* `%%service.tax3Id%%` => ''
* `%%service.invoicingStart%%` => '2016-05-03T00:00:00+0000'
* `%%service.invoicingPeriodType%%` => 1
* `%%service.invoicingPeriodStartDay%%` => 1
* `%%service.nextInvoicingDayAdjustment%%` => 0
* `%%service.invoicingProratedSeparately%%` => true
* `%%service.invoicingSeparately%%` => false
* `%%service.sendEmailsAutomatically%%` => false
* `%%service.useCreditAutomatically%%` => true
* `%%service.servicePlanName%%` => 'Mini'
* `%%service.servicePlanPrice%%` => 25
* `%%service.servicePlanPeriod%%` => 3
* `%%service.downloadSpeed%%` => 10
* `%%service.uploadSpeed%%` => 10
* `%%service.hasOutage%%` => true
* `%%service.stopReason%%` => 'Payments overdue'
El plugin utiliza una arquitectura modular basada en **Facades** y **Servicios** para garantizar estabilidad y escalabilidad.
## Developers ### Componentes Clave
* This plugin is MIT-licensed and can be used by developers as a template for integrating with a different messaging solution:
* Create a new plugin based on this one
* Replace the TwilioNotifierFacade and any references to it with a different class which extends AbstractMessageNotifierFacade
* Update libraries in composer.json as needed
* Communicate with the remote system in the sendMessage() function
* Preferably also change the SmsNotifier namespace to some other (not strictly necessary).
Read more about creating your own plugin in the [Developer documentation](https://github.com/Ubiquiti-App/UCRM-plugins/blob/master/docs/index.md). - **Frontend (`public.php`)**: Una Single Page Application (SPA) ligera incrustada en UCRM, construida con Vanilla JS y CSS moderno (Variables, Flexbox/Grid).
- **Despachador (`Plugin.php`)**: Router de eventos que delega acciones a los controladores específicos.
- **Motor de Pagos (`PaymentIntentStripe`)**: Servicio robusto que se comunica con la API de Stripe para crear intenciones de pago y métodos.
- **Generador OXXO (`AbstractOxxoOperationsFacade`)**: Orquesta el flujo complejo: Stripe -> Puppeteer (Screenshot) -> FTP/Local Storage -> Respuesta JSON.
---
## 🛠️ Requisitos e Integraciones
Para desbloquear todo el potencial, el plugin requiere:
1. **UISP/UCRM**: Versión 2.1.0 o superior.
2. **Stripe API**: Keys de producción/test para procesar pagos.
3. **CallBell API**: Token para el envío de mensajes de WhatsApp.
4. **Microservicio Puppeteer**: Contenedor Docker para renderizar los vouchers de OXXO a imagen.
5. **Servidor FTP (Opcional)**: Requerido solo si se desea generar URLs públicas para compartir los vouchers externamente.
---
## 🏷️ Configuración Rápida
El plugin se configura directamente desde el panel de UCRM (`Ajustes -> Plugins -> siip-whatsapp-notifications`).
### Parámetros Críticos
- `ipserver`: Tu dominio UCRM.
- `tokenstripe`: Tu Secret Key de Stripe.
- `tokencallbell`: Tu API Key de CallBell.
- `hostServerFTP` / `user` / `pass`: Credenciales para el almacenamiento de vouchers remotos.
---
## 📝 Registro de Cambios
Para consultar la evolución detallada del proyecto, ver el archivo [CHANGELOG.md](./CHANGELOG.md).

View File

@ -1,73 +1,30 @@
<?php <?php
use GuzzleHttp\Client;
require 'vendor/autoload.php'; require_once __DIR__ . '/vendor/autoload.php';
// $baseUri = 'https://172.16.5.120/crm/api/v1.0/'; //endpoint de la API REST del CRM use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
// $token = '3d5fa4c9-e134-4e8b-b8d7-aae394d48d4d'; //Token para acceder a los recursos del CRM use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
$baseUri = 'https://172.16.5.134/crm/api/v1.0/'; //endpoint de la API REST del CRM
$token = '6abef18c-783d-4dd0-b530-be6e6a7bbd1d'; //Token para acceder a los recursos del CRM
$stripe = new \Stripe\StripeClient('sk_test_51OkG0REFY1WEUtgRH6UxBK5pu80Aq5Iy8EcdPnf0cOWzuVLQTpyLCd7CbPzqMsWMafZOHElCxhEHF7g8boURjWlJ00tBwE0W1M'); //Token de clave privada en modo prueba para la API de Stripe chdir(__DIR__);
//$stripe = new \Stripe\StripeClient('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'); //Token de clave privada en modo prodcucción para la API de Stripe
//cliente GuzzleHttp para consumir API del UISP CRM // Inicializar Log (usando data/ para permisos de escritura)
$clientGuzzleHttp = new Client([ $debugLogPath = __DIR__ . '/data/plugin.log';
'base_uri' => $baseUri, file_put_contents($debugLogPath, "[" . date('Y-m-d H:i:s') . "] Hit StripeWebhook.php - Delegando a Plugin->run()" . PHP_EOL, FILE_APPEND);
'headers' => [
'X-Auth-App-Key' => $token,
'Accept' => 'application/json',
],
'verify' => false,
]);
// Obtén el contenido del cuerpo de la solicitud // Solo permitir acceso si estamos en un entorno UCRM válido
$input = @file_get_contents('php://input'); if (!file_exists(__DIR__ . '/data/config.json')) {
$event_json = json_decode($input); die('Acceso denegado o configuración no encontrada.');
$cadena = json_encode($event_json);
file_put_contents(__DIR__ . '/logsiip.log', "[" . date('Y-m-d H:i:s') . "] " . "Valor json: ".$cadena.PHP_EOL);
// Maneja el evento del webhook
if ($event_json) {
switch ($event_json->type) {
case 'cash_balance.funds_available':
$customer = $event_json->data->object;
$customerId = $customer->id;
$newBalance = $customer->balance; // El nuevo saldo del cliente
try {// Aquí puedes crear un nuevo PaymentIntent o un Cargo (Charge) usando el nuevo saldo
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => 30000,
'currency' => 'mxn',
'customer' => $customerId,
'payment_method_types' => ['customer_balance'],
'payment_method_data' => ['type' => 'customer_balance'],
'confirm' => true,
'payment_method_options' => [
'customer_balance' => [
'funding_type' => 'bank_transfer',
'bank_transfer' => ['type' => 'mx_bank_transfer']
],
],
'metadata' => [
'clientId' => $customerId, // ID del cliente en Ubiquiti
'createdBy' => 'UCRM', // ID de la factura en Ubiquiti
'paymentType' => 'card.one_time',
'signedInAdminId' => 1015,
],
]);
file_put_contents(__DIR__ . '/logsiip.log', "[" . date('Y-m-d H:i:s') . "] " . "PaymentIntent creado: " . $paymentIntent->id . PHP_EOL, FILE_APPEND);
} catch (\Stripe\Exception\ApiErrorException $e) {
file_put_contents(__DIR__ . '/logsiip.log', "[" . date('Y-m-d H:i:s') . "] " ."Error creando PaymentIntent: " . $e->getMessage() . PHP_EOL, FILE_APPEND);
}
break;
// Otros eventos relevantes
}
} }
http_response_code(200); // Responde con un 200 OK a Stripe try {
// Delegar ejecución al Plugin principal
$builder = new \DI\ContainerBuilder();
$container = $builder->build();
$plugin = $container->get(\SmsNotifier\Plugin::class);
$plugin->run();
} catch (\Exception $e) {
file_put_contents($debugLogPath, "[" . date('Y-m-d H:i:s') . "] Error en StripeWebhook.php: " . $e->getMessage() . PHP_EOL, FILE_APPEND);
http_response_code(500);
echo "Error interno";
}

View File

@ -16,6 +16,7 @@
"katzgrau/klogger": "^1.2", "katzgrau/klogger": "^1.2",
"stripe/stripe-php": "^13.11", "stripe/stripe-php": "^13.11",
"ext-imagick": "*", "ext-imagick": "*",
"google/apiclient": "^2.0" "google/apiclient": "^2.0",
"aws/aws-sdk-php": "^3.0"
} }
} }

512
composer.lock generated
View File

@ -4,20 +4,171 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "899edd228cc3a9ded57208726a91db8d", "content-hash": "72a3878ac2514c6e954519ec54c8054c",
"packages": [ "packages": [
{ {
"name": "firebase/php-jwt", "name": "aws/aws-crt-php",
"version": "v6.10.1", "version": "v1.2.7",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/firebase/php-jwt.git", "url": "https://github.com/awslabs/aws-crt-php.git",
"reference": "500501c2ce893c824c801da135d02661199f60c5" "reference": "d71d9906c7bb63a28295447ba12e74723bd3730e"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/firebase/php-jwt/zipball/500501c2ce893c824c801da135d02661199f60c5", "url": "https://api.github.com/repos/awslabs/aws-crt-php/zipball/d71d9906c7bb63a28295447ba12e74723bd3730e",
"reference": "500501c2ce893c824c801da135d02661199f60c5", "reference": "d71d9906c7bb63a28295447ba12e74723bd3730e",
"shasum": ""
},
"require": {
"php": ">=5.5"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35||^5.6.3||^9.5",
"yoast/phpunit-polyfills": "^1.0"
},
"suggest": {
"ext-awscrt": "Make sure you install awscrt native extension to use any of the functionality."
},
"type": "library",
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "AWS SDK Common Runtime Team",
"email": "aws-sdk-common-runtime@amazon.com"
}
],
"description": "AWS Common Runtime for PHP",
"homepage": "https://github.com/awslabs/aws-crt-php",
"keywords": [
"amazon",
"aws",
"crt",
"sdk"
],
"support": {
"issues": "https://github.com/awslabs/aws-crt-php/issues",
"source": "https://github.com/awslabs/aws-crt-php/tree/v1.2.7"
},
"time": "2024-10-18T22:15:13+00:00"
},
{
"name": "aws/aws-sdk-php",
"version": "3.369.11",
"source": {
"type": "git",
"url": "https://github.com/aws/aws-sdk-php.git",
"reference": "014c521eae8eeb1f9562cb512523b17cd6c1bec7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/014c521eae8eeb1f9562cb512523b17cd6c1bec7",
"reference": "014c521eae8eeb1f9562cb512523b17cd6c1bec7",
"shasum": ""
},
"require": {
"aws/aws-crt-php": "^1.2.3",
"ext-json": "*",
"ext-pcre": "*",
"ext-simplexml": "*",
"guzzlehttp/guzzle": "^7.4.5",
"guzzlehttp/promises": "^2.0",
"guzzlehttp/psr7": "^2.4.5",
"mtdowling/jmespath.php": "^2.8.0",
"php": ">=8.1",
"psr/http-message": "^1.0 || ^2.0",
"symfony/filesystem": "^v5.4.45 || ^v6.4.3 || ^v7.1.0 || ^v8.0.0"
},
"require-dev": {
"andrewsville/php-token-reflection": "^1.4",
"aws/aws-php-sns-message-validator": "~1.0",
"behat/behat": "~3.0",
"composer/composer": "^2.7.8",
"dms/phpunit-arraysubset-asserts": "^0.4.0",
"doctrine/cache": "~1.4",
"ext-dom": "*",
"ext-openssl": "*",
"ext-sockets": "*",
"phpunit/phpunit": "^9.6",
"psr/cache": "^2.0 || ^3.0",
"psr/simple-cache": "^2.0 || ^3.0",
"sebastian/comparator": "^1.2.3 || ^4.0 || ^5.0",
"yoast/phpunit-polyfills": "^2.0"
},
"suggest": {
"aws/aws-php-sns-message-validator": "To validate incoming SNS notifications",
"doctrine/cache": "To use the DoctrineCacheAdapter",
"ext-curl": "To send requests using cURL",
"ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages",
"ext-pcntl": "To use client-side monitoring",
"ext-sockets": "To use client-side monitoring"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"autoload": {
"files": [
"src/functions.php"
],
"psr-4": {
"Aws\\": "src/"
},
"exclude-from-classmap": [
"src/data/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "Amazon Web Services",
"homepage": "http://aws.amazon.com"
}
],
"description": "AWS SDK for PHP - Use Amazon Web Services in your PHP project",
"homepage": "http://aws.amazon.com/sdkforphp",
"keywords": [
"amazon",
"aws",
"cloud",
"dynamodb",
"ec2",
"glacier",
"s3",
"sdk"
],
"support": {
"forum": "https://github.com/aws/aws-sdk-php/discussions",
"issues": "https://github.com/aws/aws-sdk-php/issues",
"source": "https://github.com/aws/aws-sdk-php/tree/3.369.11"
},
"time": "2026-01-12T19:14:19+00:00"
},
{
"name": "firebase/php-jwt",
"version": "v6.10.2",
"source": {
"type": "git",
"url": "https://github.com/firebase/php-jwt.git",
"reference": "30c19ed0f3264cb660ea496895cfb6ef7ee3653b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/firebase/php-jwt/zipball/30c19ed0f3264cb660ea496895cfb6ef7ee3653b",
"reference": "30c19ed0f3264cb660ea496895cfb6ef7ee3653b",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -65,40 +216,40 @@
], ],
"support": { "support": {
"issues": "https://github.com/firebase/php-jwt/issues", "issues": "https://github.com/firebase/php-jwt/issues",
"source": "https://github.com/firebase/php-jwt/tree/v6.10.1" "source": "https://github.com/firebase/php-jwt/tree/v6.10.2"
}, },
"time": "2024-05-18T18:05:11+00:00" "time": "2024-11-24T11:22:49+00:00"
}, },
{ {
"name": "google/apiclient", "name": "google/apiclient",
"version": "v2.16.0", "version": "v2.18.2",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/googleapis/google-api-php-client.git", "url": "https://github.com/googleapis/google-api-php-client.git",
"reference": "017400f609c1fb71ab5ad824c50eabd4c3eaf779" "reference": "d8d201ba8a189a3cd7fb34e4da569f2ed440eee7"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/googleapis/google-api-php-client/zipball/017400f609c1fb71ab5ad824c50eabd4c3eaf779", "url": "https://api.github.com/repos/googleapis/google-api-php-client/zipball/d8d201ba8a189a3cd7fb34e4da569f2ed440eee7",
"reference": "017400f609c1fb71ab5ad824c50eabd4c3eaf779", "reference": "d8d201ba8a189a3cd7fb34e4da569f2ed440eee7",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"firebase/php-jwt": "~6.0", "firebase/php-jwt": "^6.0",
"google/apiclient-services": "~0.350", "google/apiclient-services": "~0.350",
"google/auth": "^1.37", "google/auth": "^1.37",
"guzzlehttp/guzzle": "^6.5.8||^7.4.5", "guzzlehttp/guzzle": "^7.4.5",
"guzzlehttp/psr7": "^1.9.1||^2.2.1", "guzzlehttp/psr7": "^2.6",
"monolog/monolog": "^2.9||^3.0", "monolog/monolog": "^2.9||^3.0",
"php": "^7.4|^8.0", "php": "^8.0",
"phpseclib/phpseclib": "^3.0.36" "phpseclib/phpseclib": "^3.0.36"
}, },
"require-dev": { "require-dev": {
"cache/filesystem-adapter": "^1.1", "cache/filesystem-adapter": "^1.1",
"composer/composer": "^1.10.23", "composer/composer": "^1.10.23",
"phpcompatibility/php-compatibility": "^9.2", "phpcompatibility/php-compatibility": "^9.2",
"phpspec/prophecy-phpunit": "^2.0", "phpspec/prophecy-phpunit": "^2.1",
"phpunit/phpunit": "^9.5", "phpunit/phpunit": "^9.6",
"squizlabs/php_codesniffer": "^3.8", "squizlabs/php_codesniffer": "^3.8",
"symfony/css-selector": "~2.1", "symfony/css-selector": "~2.1",
"symfony/dom-crawler": "~2.1" "symfony/dom-crawler": "~2.1"
@ -134,22 +285,22 @@
], ],
"support": { "support": {
"issues": "https://github.com/googleapis/google-api-php-client/issues", "issues": "https://github.com/googleapis/google-api-php-client/issues",
"source": "https://github.com/googleapis/google-api-php-client/tree/v2.16.0" "source": "https://github.com/googleapis/google-api-php-client/tree/v2.18.2"
}, },
"time": "2024-04-24T00:59:47+00:00" "time": "2024-12-16T22:52:40+00:00"
}, },
{ {
"name": "google/apiclient-services", "name": "google/apiclient-services",
"version": "v0.359.0", "version": "v0.389.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/googleapis/google-api-php-client-services.git", "url": "https://github.com/googleapis/google-api-php-client-services.git",
"reference": "e975e6d0efa47f7e49280c4ea7fd6a93b6d7e338" "reference": "6274e67ee52b1a416ccee0a4eaf337d1139cdaf8"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/e975e6d0efa47f7e49280c4ea7fd6a93b6d7e338", "url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/6274e67ee52b1a416ccee0a4eaf337d1139cdaf8",
"reference": "e975e6d0efa47f7e49280c4ea7fd6a93b6d7e338", "reference": "6274e67ee52b1a416ccee0a4eaf337d1139cdaf8",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -178,29 +329,29 @@
], ],
"support": { "support": {
"issues": "https://github.com/googleapis/google-api-php-client-services/issues", "issues": "https://github.com/googleapis/google-api-php-client-services/issues",
"source": "https://github.com/googleapis/google-api-php-client-services/tree/v0.359.0" "source": "https://github.com/googleapis/google-api-php-client-services/tree/v0.389.0"
}, },
"time": "2024-06-10T01:02:17+00:00" "time": "2025-01-05T01:04:21+00:00"
}, },
{ {
"name": "google/auth", "name": "google/auth",
"version": "v1.40.0", "version": "v1.44.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/googleapis/google-auth-library-php.git", "url": "https://github.com/googleapis/google-auth-library-php.git",
"reference": "bff9f2d01677e71a98394b5ac981b99523df5178" "reference": "5670e56307d7a2eac931f677c0e59a4f8abb2e43"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/bff9f2d01677e71a98394b5ac981b99523df5178", "url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/5670e56307d7a2eac931f677c0e59a4f8abb2e43",
"reference": "bff9f2d01677e71a98394b5ac981b99523df5178", "reference": "5670e56307d7a2eac931f677c0e59a4f8abb2e43",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"firebase/php-jwt": "^6.0", "firebase/php-jwt": "^6.0",
"guzzlehttp/guzzle": "^7.4.5", "guzzlehttp/guzzle": "^7.4.5",
"guzzlehttp/psr7": "^2.4.5", "guzzlehttp/psr7": "^2.4.5",
"php": "^8.0", "php": "^8.1",
"psr/cache": "^2.0||^3.0", "psr/cache": "^2.0||^3.0",
"psr/http-message": "^1.1||^2.0" "psr/http-message": "^1.1||^2.0"
}, },
@ -238,28 +389,28 @@
"support": { "support": {
"docs": "https://googleapis.github.io/google-auth-library-php/main/", "docs": "https://googleapis.github.io/google-auth-library-php/main/",
"issues": "https://github.com/googleapis/google-auth-library-php/issues", "issues": "https://github.com/googleapis/google-auth-library-php/issues",
"source": "https://github.com/googleapis/google-auth-library-php/tree/v1.40.0" "source": "https://github.com/googleapis/google-auth-library-php/tree/v1.44.0"
}, },
"time": "2024-05-31T19:16:15+00:00" "time": "2024-12-04T15:34:58+00:00"
}, },
{ {
"name": "guzzlehttp/guzzle", "name": "guzzlehttp/guzzle",
"version": "7.8.1", "version": "7.10.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/guzzle/guzzle.git", "url": "https://github.com/guzzle/guzzle.git",
"reference": "41042bc7ab002487b876a0683fc8dce04ddce104" "reference": "b51ac707cfa420b7bfd4e4d5e510ba8008e822b4"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/41042bc7ab002487b876a0683fc8dce04ddce104", "url": "https://api.github.com/repos/guzzle/guzzle/zipball/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4",
"reference": "41042bc7ab002487b876a0683fc8dce04ddce104", "reference": "b51ac707cfa420b7bfd4e4d5e510ba8008e822b4",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"ext-json": "*", "ext-json": "*",
"guzzlehttp/promises": "^1.5.3 || ^2.0.1", "guzzlehttp/promises": "^2.3",
"guzzlehttp/psr7": "^1.9.1 || ^2.5.1", "guzzlehttp/psr7": "^2.8",
"php": "^7.2.5 || ^8.0", "php": "^7.2.5 || ^8.0",
"psr/http-client": "^1.0", "psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.2 || ^3.0" "symfony/deprecation-contracts": "^2.2 || ^3.0"
@ -270,9 +421,9 @@
"require-dev": { "require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2", "bamarni/composer-bin-plugin": "^1.8.2",
"ext-curl": "*", "ext-curl": "*",
"php-http/client-integration-tests": "dev-master#2c025848417c1135031fdf9c728ee53d0a7ceaee as 3.0.999", "guzzle/client-integration-tests": "3.0.2",
"php-http/message-factory": "^1.1", "php-http/message-factory": "^1.1",
"phpunit/phpunit": "^8.5.36 || ^9.6.15", "phpunit/phpunit": "^8.5.39 || ^9.6.20",
"psr/log": "^1.1 || ^2.0 || ^3.0" "psr/log": "^1.1 || ^2.0 || ^3.0"
}, },
"suggest": { "suggest": {
@ -350,7 +501,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/guzzle/guzzle/issues", "issues": "https://github.com/guzzle/guzzle/issues",
"source": "https://github.com/guzzle/guzzle/tree/7.8.1" "source": "https://github.com/guzzle/guzzle/tree/7.10.0"
}, },
"funding": [ "funding": [
{ {
@ -366,20 +517,20 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2023-12-03T20:35:24+00:00" "time": "2025-08-23T22:36:01+00:00"
}, },
{ {
"name": "guzzlehttp/promises", "name": "guzzlehttp/promises",
"version": "2.0.2", "version": "2.3.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/guzzle/promises.git", "url": "https://github.com/guzzle/promises.git",
"reference": "bbff78d96034045e58e13dedd6ad91b5d1253223" "reference": "481557b130ef3790cf82b713667b43030dc9c957"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/guzzle/promises/zipball/bbff78d96034045e58e13dedd6ad91b5d1253223", "url": "https://api.github.com/repos/guzzle/promises/zipball/481557b130ef3790cf82b713667b43030dc9c957",
"reference": "bbff78d96034045e58e13dedd6ad91b5d1253223", "reference": "481557b130ef3790cf82b713667b43030dc9c957",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -387,7 +538,7 @@
}, },
"require-dev": { "require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2", "bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.36 || ^9.6.15" "phpunit/phpunit": "^8.5.44 || ^9.6.25"
}, },
"type": "library", "type": "library",
"extra": { "extra": {
@ -433,7 +584,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/guzzle/promises/issues", "issues": "https://github.com/guzzle/promises/issues",
"source": "https://github.com/guzzle/promises/tree/2.0.2" "source": "https://github.com/guzzle/promises/tree/2.3.0"
}, },
"funding": [ "funding": [
{ {
@ -449,20 +600,20 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2023-12-03T20:19:20+00:00" "time": "2025-08-22T14:34:08+00:00"
}, },
{ {
"name": "guzzlehttp/psr7", "name": "guzzlehttp/psr7",
"version": "2.6.2", "version": "2.8.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/guzzle/psr7.git", "url": "https://github.com/guzzle/psr7.git",
"reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221" "reference": "21dc724a0583619cd1652f673303492272778051"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/guzzle/psr7/zipball/45b30f99ac27b5ca93cb4831afe16285f57b8221", "url": "https://api.github.com/repos/guzzle/psr7/zipball/21dc724a0583619cd1652f673303492272778051",
"reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221", "reference": "21dc724a0583619cd1652f673303492272778051",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -477,8 +628,8 @@
}, },
"require-dev": { "require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2", "bamarni/composer-bin-plugin": "^1.8.2",
"http-interop/http-factory-tests": "^0.9", "http-interop/http-factory-tests": "0.9.0",
"phpunit/phpunit": "^8.5.36 || ^9.6.15" "phpunit/phpunit": "^8.5.44 || ^9.6.25"
}, },
"suggest": { "suggest": {
"laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
@ -549,7 +700,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/guzzle/psr7/issues", "issues": "https://github.com/guzzle/psr7/issues",
"source": "https://github.com/guzzle/psr7/tree/2.6.2" "source": "https://github.com/guzzle/psr7/tree/2.8.0"
}, },
"funding": [ "funding": [
{ {
@ -565,7 +716,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2023-12-03T20:05:35+00:00" "time": "2025-08-23T21:21:41+00:00"
}, },
{ {
"name": "katzgrau/klogger", "name": "katzgrau/klogger",
@ -623,26 +774,27 @@
}, },
{ {
"name": "laravel/serializable-closure", "name": "laravel/serializable-closure",
"version": "v1.3.3", "version": "v1.3.7",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/laravel/serializable-closure.git", "url": "https://github.com/laravel/serializable-closure.git",
"reference": "3dbf8a8e914634c48d389c1234552666b3d43754" "reference": "4f48ade902b94323ca3be7646db16209ec76be3d"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/laravel/serializable-closure/zipball/3dbf8a8e914634c48d389c1234552666b3d43754", "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/4f48ade902b94323ca3be7646db16209ec76be3d",
"reference": "3dbf8a8e914634c48d389c1234552666b3d43754", "reference": "4f48ade902b94323ca3be7646db16209ec76be3d",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": "^7.3|^8.0" "php": "^7.3|^8.0"
}, },
"require-dev": { "require-dev": {
"nesbot/carbon": "^2.61", "illuminate/support": "^8.0|^9.0|^10.0|^11.0",
"nesbot/carbon": "^2.61|^3.0",
"pestphp/pest": "^1.21.3", "pestphp/pest": "^1.21.3",
"phpstan/phpstan": "^1.8.2", "phpstan/phpstan": "^1.8.2",
"symfony/var-dumper": "^5.4.11" "symfony/var-dumper": "^5.4.11|^6.2.0|^7.0.0"
}, },
"type": "library", "type": "library",
"extra": { "extra": {
@ -679,20 +831,20 @@
"issues": "https://github.com/laravel/serializable-closure/issues", "issues": "https://github.com/laravel/serializable-closure/issues",
"source": "https://github.com/laravel/serializable-closure" "source": "https://github.com/laravel/serializable-closure"
}, },
"time": "2023-11-08T14:08:06+00:00" "time": "2024-11-14T18:34:49+00:00"
}, },
{ {
"name": "monolog/monolog", "name": "monolog/monolog",
"version": "2.9.3", "version": "2.10.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/Seldaek/monolog.git", "url": "https://github.com/Seldaek/monolog.git",
"reference": "a30bfe2e142720dfa990d0a7e573997f5d884215" "reference": "5cf826f2991858b54d5c3809bee745560a1042a7"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/Seldaek/monolog/zipball/a30bfe2e142720dfa990d0a7e573997f5d884215", "url": "https://api.github.com/repos/Seldaek/monolog/zipball/5cf826f2991858b54d5c3809bee745560a1042a7",
"reference": "a30bfe2e142720dfa990d0a7e573997f5d884215", "reference": "5cf826f2991858b54d5c3809bee745560a1042a7",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -769,7 +921,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/Seldaek/monolog/issues", "issues": "https://github.com/Seldaek/monolog/issues",
"source": "https://github.com/Seldaek/monolog/tree/2.9.3" "source": "https://github.com/Seldaek/monolog/tree/2.10.0"
}, },
"funding": [ "funding": [
{ {
@ -781,28 +933,94 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2024-04-12T20:52:51+00:00" "time": "2024-11-12T12:43:37+00:00"
}, },
{ {
"name": "paragonie/constant_time_encoding", "name": "mtdowling/jmespath.php",
"version": "v2.7.0", "version": "2.8.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/paragonie/constant_time_encoding.git", "url": "https://github.com/jmespath/jmespath.php.git",
"reference": "52a0d99e69f56b9ec27ace92ba56897fe6993105" "reference": "a2a865e05d5f420b50cc2f85bb78d565db12a6bc"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/52a0d99e69f56b9ec27ace92ba56897fe6993105", "url": "https://api.github.com/repos/jmespath/jmespath.php/zipball/a2a865e05d5f420b50cc2f85bb78d565db12a6bc",
"reference": "52a0d99e69f56b9ec27ace92ba56897fe6993105", "reference": "a2a865e05d5f420b50cc2f85bb78d565db12a6bc",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": "^7|^8" "php": "^7.2.5 || ^8.0",
"symfony/polyfill-mbstring": "^1.17"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^6|^7|^8|^9", "composer/xdebug-handler": "^3.0.3",
"vimeo/psalm": "^1|^2|^3|^4" "phpunit/phpunit": "^8.5.33"
},
"bin": [
"bin/jp.php"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.8-dev"
}
},
"autoload": {
"files": [
"src/JmesPath.php"
],
"psr-4": {
"JmesPath\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
},
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Declaratively specify how to extract elements from a JSON document",
"keywords": [
"json",
"jsonpath"
],
"support": {
"issues": "https://github.com/jmespath/jmespath.php/issues",
"source": "https://github.com/jmespath/jmespath.php/tree/2.8.0"
},
"time": "2024-09-04T18:46:31+00:00"
},
{
"name": "paragonie/constant_time_encoding",
"version": "v3.0.0",
"source": {
"type": "git",
"url": "https://github.com/paragonie/constant_time_encoding.git",
"reference": "df1e7fde177501eee2037dd159cf04f5f301a512"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/df1e7fde177501eee2037dd159cf04f5f301a512",
"reference": "df1e7fde177501eee2037dd159cf04f5f301a512",
"shasum": ""
},
"require": {
"php": "^8"
},
"require-dev": {
"phpunit/phpunit": "^9",
"vimeo/psalm": "^4|^5"
}, },
"type": "library", "type": "library",
"autoload": { "autoload": {
@ -848,7 +1066,7 @@
"issues": "https://github.com/paragonie/constant_time_encoding/issues", "issues": "https://github.com/paragonie/constant_time_encoding/issues",
"source": "https://github.com/paragonie/constant_time_encoding" "source": "https://github.com/paragonie/constant_time_encoding"
}, },
"time": "2024-05-08T12:18:48+00:00" "time": "2024-05-08T12:36:18+00:00"
}, },
{ {
"name": "paragonie/random_compat", "name": "paragonie/random_compat",
@ -957,16 +1175,16 @@
}, },
{ {
"name": "php-di/php-di", "name": "php-di/php-di",
"version": "7.0.6", "version": "7.0.7",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/PHP-DI/PHP-DI.git", "url": "https://github.com/PHP-DI/PHP-DI.git",
"reference": "8097948a89f6ec782839b3e958432f427cac37fd" "reference": "e87435e3c0e8f22977adc5af0d5cdcc467e15cf1"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/PHP-DI/PHP-DI/zipball/8097948a89f6ec782839b3e958432f427cac37fd", "url": "https://api.github.com/repos/PHP-DI/PHP-DI/zipball/e87435e3c0e8f22977adc5af0d5cdcc467e15cf1",
"reference": "8097948a89f6ec782839b3e958432f427cac37fd", "reference": "e87435e3c0e8f22977adc5af0d5cdcc467e15cf1",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1014,7 +1232,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/PHP-DI/PHP-DI/issues", "issues": "https://github.com/PHP-DI/PHP-DI/issues",
"source": "https://github.com/PHP-DI/PHP-DI/tree/7.0.6" "source": "https://github.com/PHP-DI/PHP-DI/tree/7.0.7"
}, },
"funding": [ "funding": [
{ {
@ -1026,24 +1244,24 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2023-11-02T10:04:50+00:00" "time": "2024-07-21T15:55:45+00:00"
}, },
{ {
"name": "phpseclib/phpseclib", "name": "phpseclib/phpseclib",
"version": "3.0.37", "version": "3.0.43",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/phpseclib/phpseclib.git", "url": "https://github.com/phpseclib/phpseclib.git",
"reference": "cfa2013d0f68c062055180dd4328cc8b9d1f30b8" "reference": "709ec107af3cb2f385b9617be72af8cf62441d02"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/cfa2013d0f68c062055180dd4328cc8b9d1f30b8", "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/709ec107af3cb2f385b9617be72af8cf62441d02",
"reference": "cfa2013d0f68c062055180dd4328cc8b9d1f30b8", "reference": "709ec107af3cb2f385b9617be72af8cf62441d02",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"paragonie/constant_time_encoding": "^1|^2", "paragonie/constant_time_encoding": "^1|^2|^3",
"paragonie/random_compat": "^1.4|^2.0|^9.99.99", "paragonie/random_compat": "^1.4|^2.0|^9.99.99",
"php": ">=5.6.1" "php": ">=5.6.1"
}, },
@ -1120,7 +1338,7 @@
], ],
"support": { "support": {
"issues": "https://github.com/phpseclib/phpseclib/issues", "issues": "https://github.com/phpseclib/phpseclib/issues",
"source": "https://github.com/phpseclib/phpseclib/tree/3.0.37" "source": "https://github.com/phpseclib/phpseclib/tree/3.0.43"
}, },
"funding": [ "funding": [
{ {
@ -1136,7 +1354,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2024-03-03T02:14:58+00:00" "time": "2024-12-14T21:12:59+00:00"
}, },
{ {
"name": "psr/cache", "name": "psr/cache",
@ -1294,20 +1512,20 @@
}, },
{ {
"name": "psr/http-factory", "name": "psr/http-factory",
"version": "1.0.2", "version": "1.1.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/php-fig/http-factory.git", "url": "https://github.com/php-fig/http-factory.git",
"reference": "e616d01114759c4c489f93b099585439f795fe35" "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/php-fig/http-factory/zipball/e616d01114759c4c489f93b099585439f795fe35", "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"reference": "e616d01114759c4c489f93b099585439f795fe35", "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=7.0.0", "php": ">=7.1",
"psr/http-message": "^1.0 || ^2.0" "psr/http-message": "^1.0 || ^2.0"
}, },
"type": "library", "type": "library",
@ -1331,7 +1549,7 @@
"homepage": "https://www.php-fig.org/" "homepage": "https://www.php-fig.org/"
} }
], ],
"description": "Common interfaces for PSR-7 HTTP message factories", "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories",
"keywords": [ "keywords": [
"factory", "factory",
"http", "http",
@ -1343,9 +1561,9 @@
"response" "response"
], ],
"support": { "support": {
"source": "https://github.com/php-fig/http-factory/tree/1.0.2" "source": "https://github.com/php-fig/http-factory"
}, },
"time": "2023-04-10T20:10:41+00:00" "time": "2024-04-15T12:06:14+00:00"
}, },
{ {
"name": "psr/http-message", "name": "psr/http-message",
@ -1555,16 +1773,16 @@
}, },
{ {
"name": "symfony/deprecation-contracts", "name": "symfony/deprecation-contracts",
"version": "v3.4.0", "version": "v3.6.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git", "url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "7c3aff79d10325257a001fcf92d991f24fc967cf" "reference": "63afe740e99a13ba87ec199bb07bbdee937a5b62"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/7c3aff79d10325257a001fcf92d991f24fc967cf", "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/63afe740e99a13ba87ec199bb07bbdee937a5b62",
"reference": "7c3aff79d10325257a001fcf92d991f24fc967cf", "reference": "63afe740e99a13ba87ec199bb07bbdee937a5b62",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1572,12 +1790,12 @@
}, },
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": {
"dev-main": "3.4-dev"
},
"thanks": { "thanks": {
"name": "symfony/contracts", "url": "https://github.com/symfony/contracts",
"url": "https://github.com/symfony/contracts" "name": "symfony/contracts"
},
"branch-alias": {
"dev-main": "3.6-dev"
} }
}, },
"autoload": { "autoload": {
@ -1602,7 +1820,7 @@
"description": "A generic function and convention to trigger deprecation notices", "description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"support": { "support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" "source": "https://github.com/symfony/deprecation-contracts/tree/v3.6.0"
}, },
"funding": [ "funding": [
{ {
@ -1618,20 +1836,20 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2023-05-23T14:45:45+00:00" "time": "2024-09-25T14:21:43+00:00"
}, },
{ {
"name": "symfony/filesystem", "name": "symfony/filesystem",
"version": "v6.4.6", "version": "v6.4.30",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/filesystem.git", "url": "https://github.com/symfony/filesystem.git",
"reference": "9919b5509ada52cc7f66f9a35c86a4a29955c9d3" "reference": "441c6b69f7222aadae7cbf5df588496d5ee37789"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/filesystem/zipball/9919b5509ada52cc7f66f9a35c86a4a29955c9d3", "url": "https://api.github.com/repos/symfony/filesystem/zipball/441c6b69f7222aadae7cbf5df588496d5ee37789",
"reference": "9919b5509ada52cc7f66f9a35c86a4a29955c9d3", "reference": "441c6b69f7222aadae7cbf5df588496d5ee37789",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1639,6 +1857,9 @@
"symfony/polyfill-ctype": "~1.8", "symfony/polyfill-ctype": "~1.8",
"symfony/polyfill-mbstring": "~1.8" "symfony/polyfill-mbstring": "~1.8"
}, },
"require-dev": {
"symfony/process": "^5.4|^6.4|^7.0"
},
"type": "library", "type": "library",
"autoload": { "autoload": {
"psr-4": { "psr-4": {
@ -1665,7 +1886,7 @@
"description": "Provides basic utilities for the filesystem", "description": "Provides basic utilities for the filesystem",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"support": { "support": {
"source": "https://github.com/symfony/filesystem/tree/v6.4.6" "source": "https://github.com/symfony/filesystem/tree/v6.4.30"
}, },
"funding": [ "funding": [
{ {
@ -1676,29 +1897,33 @@
"url": "https://github.com/fabpot", "url": "https://github.com/fabpot",
"type": "github" "type": "github"
}, },
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{ {
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2024-03-21T19:36:20+00:00" "time": "2025-11-26T14:43:45+00:00"
}, },
{ {
"name": "symfony/polyfill-ctype", "name": "symfony/polyfill-ctype",
"version": "v1.29.0", "version": "v1.33.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git", "url": "https://github.com/symfony/polyfill-ctype.git",
"reference": "ef4d7e442ca910c4764bce785146269b30cb5fc4" "reference": "a3cc8b044a6ea513310cbd48ef7333b384945638"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/ef4d7e442ca910c4764bce785146269b30cb5fc4", "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/a3cc8b044a6ea513310cbd48ef7333b384945638",
"reference": "ef4d7e442ca910c4764bce785146269b30cb5fc4", "reference": "a3cc8b044a6ea513310cbd48ef7333b384945638",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=7.1" "php": ">=7.2"
}, },
"provide": { "provide": {
"ext-ctype": "*" "ext-ctype": "*"
@ -1709,8 +1934,8 @@
"type": "library", "type": "library",
"extra": { "extra": {
"thanks": { "thanks": {
"name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill",
"url": "https://github.com/symfony/polyfill" "name": "symfony/polyfill"
} }
}, },
"autoload": { "autoload": {
@ -1744,7 +1969,7 @@
"portable" "portable"
], ],
"support": { "support": {
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.29.0" "source": "https://github.com/symfony/polyfill-ctype/tree/v1.33.0"
}, },
"funding": [ "funding": [
{ {
@ -1755,29 +1980,34 @@
"url": "https://github.com/fabpot", "url": "https://github.com/fabpot",
"type": "github" "type": "github"
}, },
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{ {
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2024-01-29T20:11:03+00:00" "time": "2024-09-09T11:45:10+00:00"
}, },
{ {
"name": "symfony/polyfill-mbstring", "name": "symfony/polyfill-mbstring",
"version": "v1.29.0", "version": "v1.33.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git", "url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec" "reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/9773676c8a1bb1f8d4340a62efe641cf76eda7ec", "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/6d857f4d76bd4b343eac26d6b539585d2bc56493",
"reference": "9773676c8a1bb1f8d4340a62efe641cf76eda7ec", "reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=7.1" "ext-iconv": "*",
"php": ">=7.2"
}, },
"provide": { "provide": {
"ext-mbstring": "*" "ext-mbstring": "*"
@ -1788,8 +2018,8 @@
"type": "library", "type": "library",
"extra": { "extra": {
"thanks": { "thanks": {
"name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill",
"url": "https://github.com/symfony/polyfill" "name": "symfony/polyfill"
} }
}, },
"autoload": { "autoload": {
@ -1824,7 +2054,7 @@
"shim" "shim"
], ],
"support": { "support": {
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.29.0" "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.33.0"
}, },
"funding": [ "funding": [
{ {
@ -1835,12 +2065,16 @@
"url": "https://github.com/fabpot", "url": "https://github.com/fabpot",
"type": "github" "type": "github"
}, },
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{ {
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2024-01-29T20:11:03+00:00" "time": "2024-12-23T08:48:59+00:00"
}, },
{ {
"name": "twilio/sdk", "name": "twilio/sdk",
@ -1965,5 +2199,5 @@
"ext-imagick": "*" "ext-imagick": "*"
}, },
"platform-dev": [], "platform-dev": [],
"plugin-api-version": "2.2.0" "plugin-api-version": "2.6.0"
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 383 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 411 KiB

175
consulta a Gemini.txt Normal file
View File

@ -0,0 +1,175 @@
Pregunta: Algún microservicio que pueda levantar con docker compose y que funcione como API para pasarle un PDF y me devuelva una imagen y recortada en ciertas coordenadas o ajustada a formato cuadrado.
Respuesta: Para lo que necesitas, la mejor opción no es una herramienta genérica (como Gotenberg), ya que estas suelen convertir la página entera pero no permiten recortar por coordenadas en la misma petición.
La solución más limpia y eficiente es crear un microservicio ligero en Python (usando FastAPI y pdf2image) que puedas levantar con Docker. Python tiene las mejores librerías para manipulación de PDFs e imágenes.
Aquí tienes la solución completa "Copy-Paste":
1. Estructura del proyecto
Crea una carpeta (ej. pdf-cropper) con estos 3 archivos:
Dockerfile
main.py
docker-compose.yml
2. El Código (Python + FastAPI)
Este script recibe el PDF, lo convierte a imagen y aplica el recorte o ajuste cuadrado según lo que le pidas.
Archivo: main.py
Python
from fastapi import FastAPI, UploadFile, File, Form
from pdf2image import convert_from_bytes
from PIL import Image
import io
app = FastAPI()
@app.post("/process")
async def process_pdf(
file: UploadFile = File(...),
mode: str = Form("square"), # 'square' o 'coords'
x: int = Form(0),
y: int = Form(0),
w: int = Form(500),
h: int = Form(500)
):
# 1. Leer el archivo PDF en memoria
pdf_bytes = await file.read()
# 2. Convertir la primera página a imagen
# poppler_path no es necesario si se instala en el sistema (ver Dockerfile)
images = convert_from_bytes(pdf_bytes, fmt="jpeg")
if not images:
return {"error": "No se pudo leer el PDF"}
img = images[0] # Tomamos la primera página
# 3. Lógica de recorte
if mode == "square":
# Recorte cuadrado centrado automático
width, height = img.size
new_dim = min(width, height)
left = (width - new_dim) / 2
top = (height - new_dim) / 2
right = (width + new_dim) / 2
bottom = (height + new_dim) / 2
img = img.crop((left, top, right, bottom))
# Opcional: Redimensionar al tamaño final deseado
img = img.resize((w, h))
elif mode == "coords":
# Recorte por coordenadas exactas
img = img.crop((x, y, x + w, y + h))
# 4. Devolver la imagen procesada
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='JPEG', quality=90)
img_byte_arr.seek(0)
from starlette.responses import StreamingResponse
return StreamingResponse(img_byte_arr, media_type="image/jpeg")
3. El Dockerfile
Es crucial instalar poppler-utils, que es el motor que procesa el PDF.
Archivo: Dockerfile
Dockerfile
FROM python:3.9-slim
# Instalar poppler (necesario para pdf2image)
RUN apt-get update && apt-get install -y poppler-utils && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Instalar dependencias de Python
RUN pip install fastapi uvicorn python-multipart pdf2image Pillow
COPY main.py .
# Ejecutar la API
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
4. Docker Compose
Para levantarlo.
Archivo: docker-compose.yml
YAML
services:
pdf-cropper:
build: .
ports:
- "8080:8000"
restart: always
Comando para iniciar:
Bash
docker compose up -d --build
5. Cómo usarlo desde PHP
Ahora tienes una API corriendo en http://localhost:8080/process. Aquí tienes el script PHP para enviarle un PDF y guardar la imagen recortada.
Archivo: cliente.php
PHP
<?php
$pdfPath = 'documento.pdf';
$outputPath = 'resultado.jpg';
// URL de tu microservicio docker
$url = 'http://localhost:8080/process';
$curl = curl_init();
$fields = [
'file' => new CURLFile($pdfPath, 'application/pdf', 'documento.pdf'),
// OPCIÓN A: Recorte cuadrado automático (centrado)
'mode' => 'square',
'w' => 800, // Tamaño final del cuadrado (px)
'h' => 800,
// OPCIÓN B: Coordenadas específicas (descomentar para usar)
// 'mode' => 'coords',
// 'x' => 100, // Píxeles desde la izquierda
// 'y' => 200, // Píxeles desde arriba
// 'w' => 500, // Ancho del recorte
// 'h' => 300 // Alto del recorte
];
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
file_put_contents($outputPath, $response);
echo "Imagen guardada exitosamente en $outputPath";
} else {
echo "Error: " . curl_error($curl);
echo "Respuesta del servidor: " . $response;
}
curl_close($curl);
?>
¿Por qué esta solución?
Atomocidad: Hace la conversión y el recorte en un solo paso de memoria (RAM), sin guardar archivos temporales en disco.
Control: Puedes ajustar la lógica de "cuadrado" (si quieres que sea centrado o desde la esquina superior) modificando fácilmente el main.py.
Ligero: La imagen Docker pesará poco y consumirá memoria solo cuando procese un archivo.

View File

@ -1 +1 @@
{"ipserver":"172.16.5.134","apitoken":"6abef18c-783d-4dd0-b530-be6e6a7bbd1d","tokencallbell":"g8thcZkXGd3xBj2g3TtYNYFMH1fuesbJ.b6a940ea7d78cf6c9e42f067b21c8ddf96e9fa2a9e307bfd0c7c7c4d7fa38f79","tokenstripe":"sk_test_51OkG0REFY1WEUtgRH6UxBK5pu80Aq5Iy8EcdPnf0cOWzuVLQTpyLCd7CbPzqMsWMafZOHElCxhEHF7g8boURjWlJ00tBwE0W1M","unmsApiToken":null,"hostServerFTP":"siip.mx","usernameServerFTP":"siip0001","passServerFTP":"$spGiT,[wa)n","cashPaymentMethodId":false,"courtesyPaymentMethodId":false,"bankTransferPaymentMethodId":true,"paypalPaymentMethodId":true,"creditCardPaypalPaymentMethodId":true,"creditCardStripePaymentMethodId":true,"stripeSubscriptionCreditCardPaymentMethodId":true,"paypalSubscriptionPaymentMethodId":true,"mercadopagoPaymentMethodId":true,"checkPaymentMethodId":true,"customPaymentMethodId":true,"notificationTypeText":false,"debugMode":true,"logging_level":true,"dataInstallersWhatsApp":"{ \"instaladores\": [{\"ID\": 1015, \"nombre\": \"Daniel Peña, \"whatsapp\": 4181878106}, {\"ID\": 1020, \"nombre\": \"Angel Arvizu\", \"whatsapp\": 4123456789}, {\"ID\": 1035,\"nombre\": \"Juan Rostro, \"whatsapp\": 4198765432}] }"} {"ipserver":"venus.siip.mx","apitoken":"gvcnIJqXdUjneVSjhl6THLlQcYXJyIFCcwHKVba2bvIrNraanCTb5VeoWuJ0TFZ9","unmsApiToken":"079c28f5-888c-457d-bd7a-0a4202590f75","tokencallbell":"g8thcZkXGd3xBj2g3TtYNYFMH1fuesbJ.b6a940ea7d78cf6c9e42f067b21c8ddf96e9fa2a9e307bfd0c7c7c4d7fa38f79","tokenstripe":"sk_test_51OkG0REFY1WEUtgRH6UxBK5pu80Aq5Iy8EcdPnf0cOWzuVLQTpyLCd7CbPzqMsWMafZOHElCxhEHF7g8boURjWlJ00tBwE0W1M","hostServerFTP":"siip.mx","usernameServerFTP":"siip0001","passServerFTP":"$spGiT,[wa)n","ipPuppeteer":"172.16.5.134","portPuppeteer":"4100","idPaymentAdminCRM":"1180","cashPaymentMethodId":false,"courtesyPaymentMethodId":false,"bankTransferPaymentMethodId":true,"paypalPaymentMethodId":true,"creditCardPaypalPaymentMethodId":true,"creditCardStripePaymentMethodId":true,"stripeSubscriptionCreditCardPaymentMethodId":true,"paypalSubscriptionPaymentMethodId":true,"mercadopagoPaymentMethodId":true,"checkPaymentMethodId":true,"customPaymentMethodId":true,"notificationTypeText":false,"installersDataWhatsApp":"{\r\n \"instaladores\": [\r\n {\r\n \"id\": 1019,\r\n \"nombre\": \"Mucio Robledo\",\r\n \"whatsapp\": \"4181878106\"\r\n },\r\n {\r\n \"id\": 1173,\r\n \"nombre\": \"Ángel Arvizu\",\r\n \"whatsapp\": \"4181878106\"\r\n },\r\n {\r\n \"id\": 1172,\r\n \"nombre\": \"Juan Rostro\",\r\n \"whatsapp\": \"4181878106\"\r\n },\r\n {\r\n \"id\": 1015,\r\n \"nombre\": \"Daniel Humberto\",\r\n \"whatsapp\": \"4181878106\"\r\n },\r\n {\r\n \"id\": 1131,\r\n \"nombre\": \"Gricelda Avalos\",\r\n \"whatsapp\": \"4181817609\"\r\n }\r\n ]\r\n}","debugMode":true,"logging_level":true,"minioEndpoint":"http://172.16.5.134:9002","minioPublicUrl":"https://aws-venus.siip.mx","minioAccessKey":"minioadmin","minioSecretKey":"minioadmin","minioBucket":"vouchers-oxxo"}

View File

@ -1 +1 @@
{"twilioAccountSid":null,"twilioAuthToken":null,"twilioSmsNumber":null,"displayedErrors":"Not valid configuration: Twilio Account SID must be configured\nNot valid configuration: Twilio Auth Token must be configured","event_client_add":null,"event_client_archive":null,"event_client_delete":null,"event_client_edit":null,"event_invoice_add":null,"event_invoice_add_draft":null,"event_invoice_draft_approved":null,"event_invoice_delete":null,"event_invoice_edit":null,"event_payment_add":null,"event_payment_delete":null,"event_payment_edit":null,"event_payment_unmatch":null,"event_service_activate":null,"event_service_add":null,"event_service_archive":null,"event_service_end":null,"event_service_postpone":null,"event_service_suspend_cancel":null,"event_service_suspend":null,"event_invoice_near_due":null,"event_invoice_overdue":null,"event_client_message":null} {"twilioAccountSid":null,"twilioAuthToken":null,"twilioSmsNumber":null,"displayedErrors":null}

File diff suppressed because one or more lines are too long

35
list_attributes.php Normal file
View File

@ -0,0 +1,35 @@
<?php
require_once __DIR__ . '/vendor/autoload.php';
use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager;
use SmsNotifier\Service\PluginDataValidator;
use SmsNotifier\Factory\NotificationDataFactory;
use SmsNotifier\Facade\PluginNotifierFacade;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use GuzzleHttp\Client;
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$token = $config['apitoken'] ?? '';
$client = new Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$ucrmApi = new UcrmApi($client, $token);
try {
echo "Fecthing custom attributes from $apiUrl\n";
$attributes = $ucrmApi->get('custom-attributes', ['attributeType' => 'client']);
echo "Total attributes: " . count($attributes) . "\n";
foreach ($attributes as $attr) {
echo sprintf("ID: %s | Name: %s | Key: %s\n", $attr['id'], $attr['name'], $attr['key']);
}
} catch (\Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

View File

@ -13,7 +13,7 @@ require 'vendor/autoload.php';
$plugin->run(); $plugin->run();
// cleanup plugin log // cleanup plugin log
$container->get(\SmsNotifier\Service\LogCleaner::class)->clean(); //$container->get(\SmsNotifier\Service\LogCleaner::class)->clean();
} catch (Exception $e) { } catch (Exception $e) {
$logger = new \SmsNotifier\Service\Logger(); $logger = new \SmsNotifier\Service\Logger();
$logger->error($e->getMessage()); $logger->error($e->getMessage());

View File

@ -2,15 +2,37 @@
"version": "1", "version": "1",
"information": { "information": {
"name": "siip-whatsapp-notifications", "name": "siip-whatsapp-notifications",
"displayName": "SIIP - Procesador de Pagos en línea con Stripe, Sincronizador de CallBell y Envío de Notificaciones y comprobantes vía WhatsApp", "displayName": "SIIP - Procesador de Pagos en línea con Stripe, Oxxo y Transferencia, Sincronizador de CallBell y Envío de Notificaciones y comprobantes vía WhatsApp",
"description": "Este plugin sincroniza los clientes del sitema UISP CRM con los contactos de WhatsApp en CallBell, además procesa pagos de Stripe como las trasferencias bancarias y genera referencias de pago vía OXXO, además envía comprobantes de pago en formato imagen PNG vía Whatsapp a los clientes", "description": "Este plugin sincroniza los clientes del sistema UISP CRM con los contactos de WhatsApp en CallBell, además procesa pagos de Stripe como las trasferencias bancarias y genera referencias de pago vía OXXO, además envía comprobantes de pago en formato imagen PNG o texto vía Whatsapp a los clientes",
"url": "https://siip.mx/", "url": "https://siip.mx/",
"version": "2.4.7", "version": "4.1.0",
"unmsVersionCompliancy": { "unmsVersionCompliancy": {
"min": "2.1.0", "min": "2.1.0",
"max": null "max": null
}, },
"author": "SIIP INTERNET" "author": "SIIP INTERNET",
"changelog": [
{
"version": "4.1.0",
"date": "2026-01-15",
"changes": "Implementación de Microservicio PDF, Integración MinIO, Fix Recorte y Soporte overlay textos."
},
{
"version": "4.0.0",
"date": "2026-01-10",
"changes": "Re-diseño completo de UI, integración total de Stripe (SPEI/OXXO), visualización inline de vouchers, optimización de seguridad FTP y modo oscuro."
},
{
"version": "3.1.0",
"date": "2026-01-07",
"changes": "Añadida funcionalidad de re-envío manual de notificaciones de pago."
},
{
"version": "3.0.0",
"date": "2026-01-02",
"changes": "Soporte multi-servicio y optimizaciones de rendimiento."
}
]
}, },
"configuration": [ "configuration": [
{ {
@ -23,10 +45,17 @@
{ {
"key": "apitoken", "key": "apitoken",
"label": "Token de la API UCRM", "label": "Token de la API UCRM",
"description": "Token de autenticación para el uso de la API del sistema UISP UCRM. Contiene 36 caracteres, ejemplo: 3d3fa6c9-e268-6e8b-b4d5-aae394d99d7d", "description": "Token de autenticación necesario para el uso de la API del sistema UISP UCRM, se utiliza para gestionar cualquier información de los clientes. Contiene 64 caracteres y se genera desde el módulo de Ajustes del UISP CRM en la opción de 'Seguridad' y en la sección de 'Claves app'.",
"required": 1, "required": 1,
"type": "text" "type": "text"
}, },
{
"key": "unmsApiToken",
"label": "Token de la API UNMS",
"description": "Token de autenticación necesario para el uso de la API del sistema UISP UNMS, se utiliza para gestionar información de antenas u otros dispositivos de red. Contiene 34 caracteres y se genera desde el módulo de Ajustes del UISP Network en la opción de 'Usuarios' y en apartado de 'API tokens'.",
"required": 0,
"type": "text"
},
{ {
"key": "tokencallbell", "key": "tokencallbell",
"label": "Token de la API de CallBell", "label": "Token de la API de CallBell",
@ -37,17 +66,10 @@
{ {
"key": "tokenstripe", "key": "tokenstripe",
"label": "Token de la API de Stripe", "label": "Token de la API de Stripe",
"description": "Token de autenticación para el uso de la API de Stripe que maneja las funciones realacionadas con los pagos en línea. ", "description": "Token de autenticación para el uso de la API de Stripe que maneja las funciones realacionadas con los pagos en línea (Transferencia y OXXO PAGO). ",
"required": 1, "required": 1,
"type": "text" "type": "text"
}, },
{
"key": "unmsApiToken",
"label": "Token de la API UNMS",
"description": "Token API creado para este plugin en la seccion Network de UNMS, solo necesario cuando se utiliza UNMS v1",
"required": 0,
"type": "text"
},
{ {
"key": "hostServerFTP", "key": "hostServerFTP",
"label": "IP o dominio del servidor FTP", "label": "IP o dominio del servidor FTP",
@ -58,14 +80,35 @@
{ {
"key": "usernameServerFTP", "key": "usernameServerFTP",
"label": "Usuario FTP", "label": "Usuario FTP",
"description": "Nombre de usuario para inicio de sesión el servidor FTP", "description": "Nombre de usuario para inicio de sesión el servidor FTP, necesario para la carga de comprobantes de pago del sistema y su posterior envío",
"required": 1, "required": 1,
"type": "text" "type": "text"
}, },
{ {
"key": "passServerFTP", "key": "passServerFTP",
"label": "Password FTP", "label": "Password FTP",
"description": "Contraseña para inicio de sesión en el servidor FTP", "description": "Contraseña para inicio de sesión en el servidor FTP, necesario para la carga de comprobantes de pago del sistema y su posterior envío",
"required": 1,
"type": "text"
},
{
"key": "ipPuppeteer",
"label": "Dirección IP del servicio de Puppeteer",
"description": "Dirección IP del contenedor docker que ejecuta el servicio de Puppeteer para la generación de comprobantes de pago en formato imagen PNG",
"required": 1,
"type": "text"
},
{
"key": "portPuppeteer",
"label": "Puerto del servicio de Puppeteer",
"description": "Puerto del contenedor docker que ejecuta el servicio de Puppeteer, por defecto es el 3000",
"required": 1,
"type": "text"
},
{
"key": "idPaymentAdminCRM",
"label": "ID del usuario para pagos en línea",
"description": "ID del usuario administrador del CRM asigando para realizar pagos en línea con Stripe. Todos los pagos que llegan desde Stripe se asignan a este usuario. Se recomienda crear un usuario exclusivo para este fin.",
"required": 1, "required": 1,
"type": "text" "type": "text"
}, },
@ -154,10 +197,11 @@
"type": "checkbox" "type": "checkbox"
}, },
{ {
"key": "dataInstallersWhatsApp", "key": "installersDataWhatsApp",
"label": "Datos de los instaladores en formato JSON", "label": "Datos de los instaladores en formato JSON",
"description": "El número identificador (id) del instalador se obtiene desde la API del CRM en su ednpoint \"/api/v1.0/user\" y se debe de obtener el campo 'id' de cada instalador para agregarlo en este campo en formato JSON",
"required": 1, "required": 1,
"type": "text" "type": "textarea"
}, },
{ {
"key": "debugMode", "key": "debugMode",
@ -166,6 +210,41 @@
"required": 0, "required": 0,
"type": "checkbox" "type": "checkbox"
}, },
{
"key": "minioEndpoint",
"label": "MinIO Endpoint (Internal)",
"description": "URL interna para subir archivos (ej: http://localhost:9002)",
"required": 1,
"type": "text"
},
{
"key": "minioPublicUrl",
"label": "MinIO Public URL (External)",
"description": "URL externa para generar enlaces públicos (ej: https://aws-venus.siip.mx)",
"required": 1,
"type": "text"
},
{
"key": "minioAccessKey",
"label": "MinIO Access Key",
"description": "Clave de acceso de MinIO",
"required": 1,
"type": "text"
},
{
"key": "minioSecretKey",
"label": "MinIO Secret Key",
"description": "Clave secreta de MinIO",
"required": 1,
"type": "text"
},
{
"key": "minioBucket",
"label": "MinIO Bucket",
"description": "Nombre del bucket (ej: vouchers-oxxo)",
"required": 1,
"type": "text"
},
{ {
"key": "logging_level", "key": "logging_level",
"label": "enable debug logs", "label": "enable debug logs",
@ -177,19 +256,7 @@
"menu": [ "menu": [
{ {
"key": "Reports", "key": "Reports",
"label": "Borrar comprobantes Wordpress", "label": "Administrar Notificaciones por WhatsApp",
"type": "admin",
"target": "iframe"
},
{
"key": "Reports",
"label": "Generador de Clabes CBM en Stripe",
"type": "admin",
"target": "iframe"
},
{
"key": "Reports",
"label": "Obtener datos del Network de Cliente",
"type": "admin", "type": "admin",
"target": "iframe" "target": "iframe"
} }

1695
public.php

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -13,140 +13,150 @@ class PluginData extends UcrmData
/** /**
* @var string * @var string
*/ */
public $twilioAccountSid; public $ipserver;
/** /**
* @var string * @var string
*/ */
public $apitoken;
/**
* @var string
*/
public $unmsApiToken;
/**
* @var string
*/
public $tokencallbell;
/**
* @var string
*/
public $tokenstripe;
/**
* @var string
*/
public $hostServerFTP;
/**
* @var string
*/
public $usernameServerFTP;
/**
* @var string
*/
public $passServerFTP;
/**
* @var string
*/
public $ipPuppeteer;
/**
* @var string
*/
public $portPuppeteer;
/**
* @var string
*/
public $idPaymentAdminCRM;
/**
* @var bool
*/
public $cashPaymentMethodId;
/**
* @var bool
*/
public $courtesyPaymentMethodId;
/**
* @var bool
*/
public $bankTransferPaymentMethodId;
/**
* @var bool
*/
public $paypalPaymentMethodId;
/**
* @var bool
*/
public $creditCardPaypalPaymentMethodId;
/**
* @var bool
*/
public $creditCardStripePaymentMethodId;
/**
* @var bool
*/
public $stripeSubscriptionCreditCardPaymentMethodId;
/**
* @var bool
*/
public $paypalSubscriptionPaymentMethodId;
/**
* @var bool
*/
public $mercadopagoPaymentMethodId;
/**
* @var bool
*/
public $checkPaymentMethodId;
/**
* @var bool
*/
public $customPaymentMethodId;
/**
* @var bool
*/
public $notificationTypeText;
/**
* @var string
*/
public $installersDataWhatsApp;
/**
* @var bool
*/
public $debugMode;
/**
* @var bool
*/
public $logging_level;
/**
* @var string|null
*/
public $twilioAccountSid;
/**
* @var string|null
*/
public $twilioAuthToken; public $twilioAuthToken;
/** /**
* @var string * @var string|null
*/ */
public $twilioSmsNumber; public $twilioSmsNumber;
/** /**
* @var string * @var string|null
*/ */
public $displayedErrors; public $displayedErrors;
/**
* @var string
*/
public $event_client_add;
/**
* @var string
*/
public $event_client_archive;
/**
* @var string
*/
public $event_client_delete;
/**
* @var string
*/
public $event_client_edit;
/**
* @var string
*/
public $event_invoice_add;
/**
* @var string
*/
public $event_invoice_add_draft;
/**
* @var string
*/
public $event_invoice_draft_approved;
/**
* @var string
*/
public $event_invoice_delete;
/**
* @var string
*/
public $event_invoice_edit;
/**
* @var string
*/
public $event_payment_add;
/**
* @var string
*/
public $event_payment_delete;
/**
* @var string
*/
public $event_payment_edit;
/**
* @var string
*/
public $event_payment_unmatch;
/**
* @var string
*/
public $event_service_activate;
/**
* @var string
*/
public $event_service_add;
/**
* @var string
*/
public $event_service_archive;
/**
* @var string
*/
public $event_service_end;
/**
* @var string
*/
public $event_service_postpone;
/**
* @var string
*/
public $event_service_suspend_cancel;
/**
* @var string
*/
public $event_service_suspend;
/**
* @var string
*/
public $event_invoice_near_due;
/**
* @var string
*/
public $event_invoice_overdue;
/**
* @var string
*/
public $event_client_message;
/**
* @var string
*/
public $logging_level;
} }

View File

@ -4,583 +4,483 @@ declare(strict_types=1);
namespace SmsNotifier\Facade; namespace SmsNotifier\Facade;
use GuzzleHttp\Client;
use SmsNotifier\Data\NotificationData; use SmsNotifier\Data\NotificationData;
use SmsNotifier\Facade\ClientCallBellAPI;
use SmsNotifier\Factory\MessageTextFactory; use SmsNotifier\Factory\MessageTextFactory;
use SmsNotifier\Service\Logger; use SmsNotifier\Service\Logger;
use SmsNotifier\Service\SmsNumberProvider; use SmsNotifier\Service\SmsNumberProvider;
use Twilio\Exceptions\HttpException; use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use SmsNotifier\Facade\ClientCallBellAPI; use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use \DateTime;
/*
* send message to client's number
*/
abstract class AbstractMessageNotifierFacade abstract class AbstractMessageNotifierFacade
{ {
/**
* @var Logger
*/
protected $logger; protected $logger;
/**
* @var MessageTextFactory
*/
protected $messageTextFactory; protected $messageTextFactory;
/**
* @var SmsNumberProvider
*/
protected $clientPhoneNumber; protected $clientPhoneNumber;
protected $ucrmApi;
const SUBJECT_OF_INSTALLER_CHANGE = ["se ha cancelado una tarea que tenías asignada con el folio ", "se te ha desasignado❌ la tarea con el folio "];
const ADDITIONAL_CHANGE_DATA = ["Ya no es necesario realizar la visita técnica.", "En tu lugar asistirá el técnico 👷🏻‍♂️➡️ "];
public function __construct(Logger $logger, MessageTextFactory $messageTextFactory, SmsNumberProvider $clientPhoneNumber) {
public function __construct(
Logger $logger,
MessageTextFactory $messageTextFactory,
SmsNumberProvider $clientPhoneNumber
) {
$this->logger = $logger; $this->logger = $logger;
$this->messageTextFactory = $messageTextFactory; $this->messageTextFactory = $messageTextFactory;
$this->clientPhoneNumber = $clientPhoneNumber; $this->clientPhoneNumber = $clientPhoneNumber;
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$client = new Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$this->ucrmApi = new UcrmApi($client, $config['apitoken'] ?? '');
} }
/* public function verifyPaymentActionToDo(NotificationData $notificationData): void {
* Verify contact type numbers to do notification, update or both $arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
*/ foreach ($arrayPhones as $type => $phones) {
public function verifyPaymentActionToDo(NotificationData $notificationData): void $type = trim(strtolower($type));
{ if (!is_array($phones)) continue;
foreach ($phones as $phone) {
//$this->logger->debug(print_r(json_encode($notificationData),true).PHP_EOL);
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData);
// Procesar el array de teléfonos y ejecutar la función correspondiente
foreach ($arrayPhones as $type => $phone) {
switch ($type) { switch ($type) {
case 'WhatsApp': case 'whatsapp': $this->notifyAndUpdate($notificationData, $phone); break;
$this->notifyAndUpdate($notificationData, $phone); // Ejecuta función de Notificar y Actualizar case 'whatsnotifica': $this->notify($notificationData, $phone); break;
break; case 'whatsactualiza': $this->onlyUpdate($notificationData, $phone); break;
case 'WhatsNotifica': }
$this->notify($notificationData, $phone); // Ejecuta función de Notificar }
break; }
case 'WhatsActualiza': }
$this->onlyUpdate($notificationData, $phone); // Ejecuta función de Actualizar
break; public function verifyClientActionToDo(NotificationData $notificationData): void {
default: $arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
$this->logger->info("Tipo de contacto no reconocido: $type" . PHP_EOL); foreach ($arrayPhones as $type => $phones) {
$type = trim(strtolower($type));
if (!is_array($phones)) continue;
foreach ($phones as $phone) {
if ($type === 'whatsapp' || $type === 'whatsactualiza') $this->onlyUpdate($notificationData, $phone);
}
}
}
public function verifyServiceActionToDo(NotificationData $notificationData): void {
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
foreach ($arrayPhones as $type => $phones) {
$type = trim(strtolower($type));
if (!is_array($phones)) continue;
foreach ($phones as $phone) {
if ($type === 'whatsapp' || $type === 'whatsactualiza') $this->onlyUpdateService($notificationData, $phone);
}
}
}
public function verifyJobActionToDo($jsonNotificationData, $reprogramming = null, $changeInstaller = null): void {
$this->logger->info('Iniciando verifyJobActionToDo');
$clientId = $jsonNotificationData['extraData']['entity']['clientId'];
$installerId = $jsonNotificationData['extraData']['entity']['assignedUserId'];
$jobId = $jsonNotificationData['entityId'];
$dateString = $jsonNotificationData['extraData']['entity']['date'] ?? null;
$formattedDate = $dateString ? sprintf("*%s*", (new DateTime($dateString))->format('d/m/Y')) : '';
$config = PluginConfigManager::create()->loadConfig();
$admin = $this->ucrmApi->get("users/admins/$installerId", []);
$installerName = trim(($admin['firstName'] ?? '') . ' ' . ($admin['lastName'] ?? ''));
$installerWhatsApp = '';
$installers = json_decode($config['installersDataWhatsApp'] ?? '{"instaladores":[]}', true);
foreach ($installers['instaladores'] as $inst) {
if ($inst['id'] == $installerId) { $installerWhatsApp = $inst['whatsapp']; break; }
}
if (empty($installerWhatsApp)) $this->logger->warning("No se encontró número de WhatsApp para el instalador ID: $installerId");
$clientCRM = $this->ucrmApi->get("clients/$clientId", []);
$clientName = trim(($clientCRM['firstName'] ?? '') . ' ' . ($clientCRM['lastName'] ?? ''));
$passCRM = '';
foreach ($clientCRM['attributes'] as $attr) {
if ($attr['key'] === 'passwordAntenaCliente') { $passCRM = $attr['value']; break; }
}
$allPhones = $this->clientPhoneNumber->getAllUcrmClientNumbers($clientCRM);
$phonesStr = implode(', ', array_map(fn($n) => $this->validarNumeroTelefono($n), $allPhones));
$api = new ClientCallBellAPI($config['apitoken'], $config['ipserver'], $config['tokencallbell']);
$title = $jsonNotificationData['extraData']['entity']['title'] ?? '';
$isPending = (stripos($title, '[NOTIFICACION-PENDIENTE]') !== false);
$isNoWhatsApp = (stripos($title, '[CLIENTE-SIN-WHATSAPP]') !== false);
$reprogramming = filter_var($reprogramming, FILTER_VALIDATE_BOOLEAN);
$changeInstaller = filter_var($changeInstaller, FILTER_VALIDATE_BOOLEAN);
$clientPhones = $this->clientPhoneNumber->getUcrmClientNumbers(null, $clientCRM);
$hasClientWhatsApp = false;
foreach ($clientPhones as $type => $phones) {
$type = trim(strtolower($type));
if (($type === 'whatsapp' || $type === 'whatsnotifica') && !empty($phones)) {
$hasClientWhatsApp = true;
break; break;
} }
} }
$shouldNotifyTech = ($isPending || $reprogramming || $changeInstaller);
$shouldNotifyClient = ($isPending || $isNoWhatsApp || $reprogramming || $changeInstaller);
// 1. Notificar al Instalador Anterior (Desasignación)
if ($changeInstaller) {
$prevId = $jsonNotificationData['extraData']['entityBeforeEdit']['assignedUserId'];
$prevAdmin = $this->ucrmApi->get("users/admins/$prevId", []);
$prevWhatsApp = '';
foreach ($installers['instaladores'] as $inst) {
if ($inst['id'] == $prevId) { $prevWhatsApp = $inst['whatsapp']; break; }
} }
if ($prevWhatsApp) {
/* $api->sendJobNotificationWhatsAppToInstaller($this->validarNumeroTelefono($prevWhatsApp), [
* Verify contact type numbers to do client's data update at CallBell "installerName" => "👷🏻‍♂️" . trim(($prevAdmin['firstName'] ?? '') . ' ' . ($prevAdmin['lastName'] ?? '')),
*/ "subjectOfChange" => self::SUBJECT_OF_INSTALLER_CHANGE[1],
public function verifyClientActionToDo(NotificationData $notificationData): void "jobId" => $jobId,
{ "clientFullName" => "[$clientId] $clientName",
"additionalChangeData" => self::ADDITIONAL_CHANGE_DATA[1] . ' *' . $installerName . '*',
//$this->logger->debug(print_r(json_encode($notificationData),true).PHP_EOL); ], $reprogramming, $changeInstaller);
sleep(1);
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData);
// Procesar el array de teléfonos y ejecutar la función correspondiente
foreach ($arrayPhones as $type => $phone) {
switch ($type) {
case 'WhatsApp':
$this->onlyUpdate($notificationData, $phone); // Ejecuta función de Notificar y Actualizar
break;
case 'WhatsActualiza':
$this->onlyUpdate($notificationData, $phone); // Ejecuta función de Actualizar
break;
default:
$this->logger->info("Tipo de contacto no reconocido: $type" . PHP_EOL);
break;
} }
} }
// 2. Notificar al Cliente (si aplica)
$clientNotified = false;
if ($shouldNotifyClient && $hasClientWhatsApp) {
foreach ($clientPhones as $type => $phones) {
$type = trim(strtolower($type));
if (!is_array($phones) || ($type !== 'whatsapp' && $type !== 'whatsnotifica')) continue;
foreach ($phones as $phone) {
if ($api->sendJobNotificationWhatsAppToClient($this->validarNumeroTelefono($phone), ["clientFullName" => $clientName, "jobId" => $jobId, "date" => $formattedDate, "installerName" => $installerName], $reprogramming, $changeInstaller)) {
$clientNotified = true;
}
} }
/*
* Verify contact type numbers to do client's data service status at CallBell
*/
public function verifyServiceActionToDo(NotificationData $notificationData): void
{
//$this->logger->debug(print_r(json_encode($notificationData),true).PHP_EOL);
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData);
// Procesar el array de teléfonos y ejecutar la función correspondiente
foreach ($arrayPhones as $type => $phone) {
switch ($type) {
case 'WhatsApp':
$this->onlyUpdateService($notificationData, $phone); // Ejecuta función de Notificar y Actualizar
break;
case 'WhatsActualiza':
$this->onlyUpdateService($notificationData, $phone); // Ejecuta función de Actualizar
break;
default:
$this->logger->info("Tipo de contacto no reconocido: $type" . PHP_EOL);
break;
} }
} }
// 2. Notificar al Técnico (si aplica)
if ($shouldNotifyTech) {
$passVault = $this->getVaultCredentialsByClientId($clientId);
$api->sendJobNotificationWhatsAppToInstaller($this->validarNumeroTelefono($installerWhatsApp), [
"installerName" => $installerName,
"clientFullName" => "$clientName [ID:$clientId]",
"jobId" => $jobId,
"clientAddress" => $clientCRM['fullAddress'] ?? 'N/A',
"clientWhatsApp" => !empty($phonesStr) ? $phonesStr : 'Sin WhatsApp',
"date" => $formattedDate,
"jobDescription" => $jsonNotificationData['extraData']['entity']['description'] ?? 'S/D',
"gmapsLocation" => ($clientCRM['addressGpsLat'] && $clientCRM['addressGpsLon']) ? "https://www.google.com/maps?q={$clientCRM['addressGpsLat']},{$clientCRM['addressGpsLon']}" : 'N/A',
"passwordAntenaCliente" => $this->comparePasswords($passCRM, $passVault)
], $reprogramming, $changeInstaller);
} }
// 3. Gestión del Título / Prefijos
/* if ($isPending) {
* Verify contact type numbers to do client's data update at CallBell by invoice add or edit if ($clientNotified || $reprogramming || $changeInstaller) {
*/ $newTitle = str_ireplace('[NOTIFICACION-PENDIENTE]', '', $title);
public function verifyInvoiceActionToDo(NotificationData $notificationData): void $this->ucrmApi->patch("scheduling/jobs/$jobId", ['title' => trim($newTitle)]);
{ } else if (!$hasClientWhatsApp) {
$newTitle = str_ireplace('[NOTIFICACION-PENDIENTE]', '[CLIENTE-SIN-WHATSAPP]', $title);
$this->logger->debug(print_r(json_encode($notificationData), true) . PHP_EOL); $this->ucrmApi->patch("scheduling/jobs/$jobId", ['title' => trim($newTitle)]);
}
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData); } else if ($isNoWhatsApp && ($clientNotified || $reprogramming || $changeInstaller)) {
// Procesar el array de teléfonos y ejecutar la función correspondiente $newTitle = str_ireplace('[CLIENTE-SIN-WHATSAPP]', '', $title);
$this->ucrmApi->patch("scheduling/jobs/$jobId", ['title' => trim($newTitle)]);
foreach ($arrayPhones as $type => $phone) {
switch ($type) {
case 'WhatsApp':
$this->onlyUpdate($notificationData, $phone); // Ejecuta función de Notificar y Actualizar
break;
case 'WhatsActualiza':
$this->onlyUpdate($notificationData, $phone); // Ejecuta función de Actualizar
break;
default:
$this->logger->info("Tipo de contacto no reconocido: $type" . PHP_EOL);
break;
} }
} }
public function verifyInvoiceActionToDo(NotificationData $notificationData): void {
$arrayPhones = $this->clientPhoneNumber->getUcrmClientNumbers($notificationData, null);
foreach ($arrayPhones as $type => $phones) {
$type = trim(strtolower($type));
if (!is_array($phones)) continue;
foreach ($phones as $phone) {
if ($type === 'whatsapp' || $type === 'whatsactualiza') $this->onlyUpdate($notificationData, $phone, false);
}
}
} }
/* public function notify(NotificationData $notificationData, $phoneToNotify = null): void {
* Notify to client with the payment receipt via WhatsApp $config = PluginConfigManager::create()->loadConfig();
*/ $api = new ClientCallBellAPI($config['apitoken'], $config['ipserver'], $config['tokencallbell']);
public function notify(NotificationData $notificationData, $phoneToNotify = null): void $phone = $this->validarNumeroTelefono($phoneToNotify);
{ if (!$phone) return;
if ($config['notificationTypeText'] ?? false) $api->sendTextPaymentNotificationWhatsApp($phone, $notificationData);
else $api->sendPaymentNotificationWhatsApp($phone, $notificationData);
}
// $notification_client_data = $notificationData->clientData; //array con los datos del cliente public function notifyAndUpdate(NotificationData $notificationData, $phoneToNotifyAndUpdate = null): void {
$config = PluginConfigManager::create()->loadConfig();
// $notification_client_data_export = json_encode($notification_client_data); $api = new ClientCallBellAPI($config['apitoken'], $config['ipserver'], $config['tokencallbell']);
// $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL); $phone = $this->validarNumeroTelefono($phoneToNotifyAndUpdate);
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create(); if (!$phone) return;
$config = $configManager->loadConfig(); if ($config['notificationTypeText'] ?? false) {
// the "exportFormat" key must be defined in plugin's manifest file, see the link above if ($api->sendTextPaymentNotificationWhatsApp($phone, $notificationData)) {
$IPServer = $config['ipserver']; $contact = json_decode($api->getContactWhatsapp($phone), true);
$UCRMAPIToken = $config['apitoken']; if ($contact) $api->patchWhatsapp($contact, $notificationData);
$CallBellAPIToken = $config['tokencallbell']; }
$notificationTypeText = $config['notificationTypeText'];
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
//$clientPhoneNumber = $this->clientPhoneNumber->getUcrmClientNumber($notificationData);
$clientPhoneNumber = $this->validarNumeroTelefono($phoneToNotify); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp"
//$this->logger->debug("Numero de cel obtenido " . $clientPhoneNumber . PHP_EOL);
if (empty($clientPhoneNumber)) {
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId);
return;
} else { } else {
if ($api->sendPaymentNotificationWhatsApp($phone, $notificationData)) {
$contact = json_decode($api->getContactWhatsapp($phone), true);
if ($notificationTypeText) { if ($contact) $api->patchWhatsapp($contact, $notificationData);
try { }
//$this->logger->debug(sprintf('llego al llamado de sendPaymentNotificationWhatsApp con client_id: %s y número de celular: %s', $notificationData->clientId, $clientPhoneNumber)); }
//$this->sendMessage($notificationData, $clientSmsNumber, $messageBody);
//$this->sendWhatsApp($notificationData, $clientSmsNumber);
if (!$client_callbell_api->sendTextPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData)) {
$this->logger->warning("No se pudo enviar el comprobante para este cliente" . PHP_EOL);
} }
} catch (HttpException $httpException) { public function notifyOverDue(NotificationData $notificationData): void {
//$this->logger->debug('Ocurrio un error en el try catch'); $config = PluginConfigManager::create()->loadConfig();
$this->logger->error($httpException->getCode() . ' ' . $httpException->getMessage()); $api = new ClientCallBellAPI($config['apitoken'], $config['ipserver'], $config['tokencallbell']);
$phone = $this->clientPhoneNumber->getUcrmClientNumber($notificationData);
if ($phone) $api->sendOverdueNotificationWhatsApp($phone, $notificationData);
} }
} else { public function onlyUpdate(NotificationData $notificationData, $phoneToUpdate): void {
try { $config = PluginConfigManager::create()->loadConfig();
//$this->logger->debug(sprintf('llego al llamado de sendPaymentNotificationWhatsApp con client_id: %s y número de celular: %s', $notificationData->clientId, $clientPhoneNumber)); $api = new ClientCallBellAPI($config['apitoken'], $config['ipserver'], $config['tokencallbell']);
//$this->sendMessage($notificationData, $clientSmsNumber, $messageBody); $phone = $this->validarNumeroTelefono($phoneToUpdate);
//$this->sendWhatsApp($notificationData, $clientSmsNumber); $contact = json_decode($api->getContactWhatsapp($phone), true);
if (!$client_callbell_api->sendPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData)) { if ($contact) $api->patchWhatsapp($contact, $notificationData);
$this->logger->warning("No se pudo enviar el comprobante para este cliente" . PHP_EOL);
} }
} catch (HttpException $httpException) { public function onlyUpdateService(NotificationData $notificationData, $phoneToUpdate): void {
//$this->logger->debug('Ocurrio un error en el try catch'); $config = PluginConfigManager::create()->loadConfig();
$this->logger->error($httpException->getCode() . ' ' . $httpException->getMessage()); $api = new ClientCallBellAPI($config['apitoken'], $config['ipserver'], $config['tokencallbell']);
$phone = $this->validarNumeroTelefono($phoneToUpdate);
$contact = json_decode($api->getContactWhatsapp($phone), true);
if ($contact) $api->patchServiceStatusWhatsApp($contact, $notificationData);
} }
} protected function getVaultCredentialsByClientId($clientId): string {
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? '';
$crm = new Client(['base_uri' => "https://{$ipServer}/crm/api/v1.0/", 'verify' => false]);
}
// $messageBody = $this->messageTextFactory->createBody($notificationData);
// if (! $messageBody) {
// $this->logger->info('No text configured for event: ' . $notificationData->eventName);
// return;
// }
}
/*
* Notify to client with the payment receipt via WhatsApp and Update the client's data at CallBell
*/
public function notifyAndUpdate(NotificationData $notificationData, $phoneToNotifyAndUpdate = null): void
{
$this->logger->debug("***Se notifica y actualiza al cliente sobre su pago***" . PHP_EOL);
// $notification_client_data = $notificationData->clientData; //array con los datos del cliente
// $notification_client_data_export = json_encode($notification_client_data);
// $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL);
//$this->logger->debug("Creando instancia callbell ".PHP_EOL);
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
// the "exportFormat" key must be defined in plugin's manifest file, see the link above
$IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell'];
$notificationTypeText = $config['notificationTypeText'];
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
//$this->logger->debug(" instancia callbell creada".PHP_EOL);
//$clientPhoneNumber = $this->validarNumeroTelefono($this->clientPhoneNumber->getUcrmClientNumber($notificationData));
//$clientPhoneNumber = $this->clientPhoneNumber->getUcrmClientNumber($notificationData);
//$clientPhoneNumber = $this->validarNumeroTelefono($this->clientPhoneNumber->getUcrmClientNumber($notificationData)); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp"
$clientPhoneNumber = $this->validarNumeroTelefono($phoneToNotifyAndUpdate);
if (empty($clientPhoneNumber)) {
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId);
return;
} else {
//$this->logger->debug(sprintf('llego al llamado de sendPaymentNotificationWhatsApp con client_id: %s y número de celular: %s', $notificationData->clientId, $clientPhoneNumber));
if ($notificationTypeText) {
$this->logger->debug("Activado el check de mensajes de texto: ".$notificationTypeText.PHP_EOL);
}
if ($notificationTypeText) {
try {
if ($client_callbell_api->sendTextPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData)) {
$response_getContactCallBell = json_decode($client_callbell_api->getContactWhatsapp($clientPhoneNumber), true);
$client_callbell_api->patchWhatsapp($response_getContactCallBell, $notificationData);
} else {
$this->logger->warning("No se pudo enviar el comprobante para este cliente" . PHP_EOL);
}
} catch (\Exception $Exception) {
$this->logger->error($Exception->getCode() . ' ' . $Exception->getMessage());
}
} else {
try { try {
if ($client_callbell_api->sendPaymentNotificationWhatsApp($clientPhoneNumber, $notificationData)) { // OPT: Lazy Check - Si ya tiene pass válido en CRM, no hace falta procesar nada
$response_getContactCallBell = json_decode($client_callbell_api->getContactWhatsapp($clientPhoneNumber), true); $respClient = $crm->get("clients/$clientId", ['headers' => ['X-Auth-Token' => $config['apitoken']]]);
$client_callbell_api->patchWhatsapp($response_getContactCallBell, $notificationData); $clientData = json_decode($respClient->getBody()->getContents(), true);
} else { $passCRM = '';
$this->logger->warning("No se pudo enviar el comprobante para este cliente" . PHP_EOL); if (isset($clientData['attributes'])) {
} foreach ($clientData['attributes'] as $attr) {
if ($attr['key'] === 'passwordAntenaCliente') {
} catch (\Exception $Exception) { $passCRM = $attr['value'] ?? '';
$this->logger->error($Exception->getCode() . ' ' . $Exception->getMessage());
}
}
}
// $messageBody = $this->messageTextFactory->createBody($notificationData);
// if (! $messageBody) {
// $this->logger->info('No text configured for event: ' . $notificationData->eventName);
// return;
// }
}
/*
* Notify to client about Invoice Overdue
*/
public function notifyOverDue(NotificationData $notificationData): void
{
$this->logger->debug("***Se notifica al cliente que la factura de su servicio está vencida***" . PHP_EOL);
// $notification_client_data = $notificationData->clientData; //array con los datos del cliente
// $notification_client_data_export = json_encode($notification_client_data);
// $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL);
//$this->logger->debug("Creando instancia callbell ".PHP_EOL);
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
// the "exportFormat" key must be defined in plugin's manifest file, see the link above
$IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell'];
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken);
//$this->logger->debug(" instancia callbell creada".PHP_EOL);
//$clientPhoneNumber = $this->validarNumeroTelefono($this->clientPhoneNumber->getUcrmClientNumber($notificationData));
$clientPhoneNumber = $this->clientPhoneNumber->getUcrmClientNumber($notificationData);
$this->logger->debug("Numero de cel obtenido " . $clientPhoneNumber . PHP_EOL);
if (empty($clientPhoneNumber)) {
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId);
return;
} else {
try {
//$this->logger->debug(sprintf('llego al llamado de sendPaymentNotificationWhatsApp con client_id: %s y número de celular: %s', $notificationData->clientId, $clientPhoneNumber));
//$this->sendMessage($notificationData, $clientSmsNumber, $messageBody);
//$this->sendWhatsApp($notificationData, $clientSmsNumber);
$client_callbell_api->sendOverdueNotificationWhatsApp($clientPhoneNumber, $notificationData);
} catch (HttpException $httpException) {
//$this->logger->debug('Ocurrio un error en el try catch');
$this->logger->error($httpException->getCode() . ' ' . $httpException->getMessage());
}
}
// $messageBody = $this->messageTextFactory->createBody($notificationData);
// if (! $messageBody) {
// $this->logger->info('No text configured for event: ' . $notificationData->eventName);
// return;
// }
}
/*
* Update the client's data at CallBell
*/
public function onlyUpdate(NotificationData $notificationData, $phoneToUpdate = null): void
{
//$this->logger->info("Se enviará una actualización a Callbell " . PHP_EOL);
$notification_client_data = $notificationData->clientData; //array con los datos del cliente
// $notification_client_data_export = json_encode($notification_client_data);
// $this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL);
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
// the "exportFormat" key must be defined in plugin's manifest file, see the link above
$IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell'];
$StripeToken = $config['tokenstripe'];
$attributes = $notificationData->clientData['attributes']; //Obtener los atributos del cliente
// Variable para almacenar los valores de los atributos que comienzan con "clabe"
// Iterar sobre los atributoss
foreach ($attributes as $attribute) {
// Verificar si la "key" comienza con "stripe"
if (strpos($attribute['key'], 'stripe') === 0) {
// Agregar el valor al array $clabeValues
$customerStripeID = $attribute['value'];
} else if (strpos($attribute['key'], 'clabe') === 0) {// Verificar si la "key" comienza con "clabe"
// Agregar el valor al array $clabeValues
$clabeInterbancaria = $attribute['value'];
}
}
$contacts = $notificationData->clientData['contacts'] ?? []; //Obtener los contactos que tiene el cliente
foreach ($contacts as $contact) {
$types = $contact['types'] ?? []; //Obtener los tipos de contactos del cliente
foreach ($types as $type) {
if ($type['name'] == 'WhatsApp') { //Si el tipo de contacto es Whatsapp
$client_email = $contact['email']; //Asignar el correo del cliente a la variable
break; break;
} }
} }
}
$this->logger->info("Se proceso los contactos " . PHP_EOL);
$stripe = new \Stripe\StripeClient($StripeToken); //Instancia de la clase manejadora de clientes para la API de Stripe
if (!empty($client_email)) {
$stripe->customers->update($customerStripeID, ['email' => $client_email]); //Actualiza el correo electrónico del cliente en la plataforma de Stripe en su correspondiente "customer Stripe ID"
} }
// Si el campo no está vacío y no tiene advertencias, usamos el actual para ahorrar recursos
if (!empty($passCRM) && strpos($passCRM, '⚠️') === false) {
return $passCRM;
}
// 1. Obtener los servicios del cliente
$respSvc = $crm->get('clients/services?clientId=' . $clientId, [
'headers' => ['X-Auth-Token' => $config['apitoken']]
]);
$svcs = json_decode($respSvc->getBody()->getContents(), true);
$clientPhoneNumber = $this->validarNumeroTelefono($phoneToUpdate); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp" if (empty($svcs)) {
$msg = '⚠️ Cliente sin servicios/antenas';
$this->syncPasswordWithCrm((int)$clientId, $msg);
return $msg;
}
$unms = new Client(['base_uri' => "https://{$ipServer}/nms/api/v2.1/", 'verify' => false]);
$allServicePasswords = [];
$isTestEnv = ($ipServer === '172.16.5.134' || $ipServer === 'pruebas.internet.mx' || $ipServer === 'venus.siip.mx');
$numServices = count($svcs);
foreach ($svcs as $index => $svc) {
$label = ($numServices > 1) ? "Servicio " . ($index + 1) . ":" : "";
$siteId = $svc['unmsClientSiteId'] ?? null;
$passwordValue = "";
if (empty($clientPhoneNumber)) { if (!$siteId) {
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId); $passwordValue = "⚠️ Sin sitio";
return;
} else { } else {
if ($isTestEnv) {
// Lógica de bypass: intentar recuperar de la cadena existente
$foundInCRM = false;
if (!empty($passCRM)) {
if ($numServices > 1) {
if (preg_match('/Servicio ' . ($index + 1) . ':\s*([^⚠️\s]+)/', $passCRM, $matches)) {
$passwordValue = $matches[1];
$foundInCRM = true;
}
} else {
// Caso de un solo servicio: si no tiene advertencias ni etiquetas, la tomamos a secas
if (strpos($passCRM, '⚠️') === false && strpos($passCRM, 'Servicio') === false) {
$passwordValue = trim($passCRM);
$foundInCRM = true;
}
}
}
if (!$foundInCRM) {
$passwordValue = $this->generateStrongPassword(16);
}
} else {
// Lógica de producción
try { try {
//$this->logger->debug(sprintf('llego al llamado de sendwhatsapp con client_id: %s y número de celular: %s', $notificationData->clientId, $clientPhoneNumber)); $respDev = $unms->get("devices?siteId=$siteId", [
//$this->sendMessage($notificationData, $clientSmsNumber, $messageBody); 'headers' => ['X-Auth-Token' => $config['unmsApiToken']]
//$this->sendWhatsApp($notificationData, $clientSmsNumber); ]);
$devs = json_decode($respDev->getBody()->getContents(), true);
//$client_callbell_api->sendMessageWhatsApp($clientPhoneNumber, $notificationData); if (empty($devs)) {
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken); $passwordValue = "⚠️ Sin antena";
$response_getContactCallBell = json_decode($client_callbell_api->getContactWhatsapp($clientPhoneNumber), true);
//$this->logger->debug('Se hizo la petición al callbell para obtener el uuid' . PHP_EOL);
$client_callbell_api->patchWhatsapp($response_getContactCallBell, $notificationData, $clabeInterbancaria);
} catch (HttpException $httpException) {
//$this->logger->debug('Ocurrio un error en el try catch');
$this->logger->error($httpException->getCode() . ' ' . $httpException->getMessage());
}
}
// $notificationData_export = var_export($notificationData, true);
// $this->logger->debug('valor de notificationdata: ' . $notificationData_export);
// $messageBody = $this->messageTextFactory->createBody($notificationData);
// if (! $messageBody) {
// $this->logger->info('No text configured for event: ' . $notificationData->eventName);
// return;
// }
}
/*
* Update de status of service at CallBell
*/
public function onlyUpdateService(NotificationData $notificationData, $phoneToUpdate): void
{
//$this->logger->info("Se enviará una actualización del estado del servicio a Callbell, estado del servicio: ".$notificationData->serviceData['status'] . PHP_EOL);
$this->logger->info(json_encode($notificationData) . PHP_EOL);
//$clientID = $notificationData->extraData['entity']['clientId'];
//$this->logger->info("client id " .$clientID. PHP_EOL);
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
// the "exportFormat" key must be defined in plugin's manifest file, see the link above
$IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken'];
$CallBellAPIToken = $config['tokencallbell'];
$clientPhoneNumber = $this->validarNumeroTelefono($phoneToUpdate); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp"
//$this->logger->info("Número de telefono obtenido para actualizar:" .$clientPhoneNumber. PHP_EOL);
if (empty($clientPhoneNumber)) {
$this->logger->warning('No se encontró un teléfono celular válido para el cliente: ' . $notificationData->clientId);
return;
} else { } else {
$passVault = null;
$firstDeviceId = null;
foreach ($devs as $dev) {
$deviceId = $dev['identification']['id'] ?? null;
if (!$deviceId) continue;
if (!$firstDeviceId) $firstDeviceId = $deviceId;
try { try {
//$this->logger->debug(sprintf('llego al llamado de sendwhatsapp con client_id: %s y número de celular: %s', $notificationData->clientId, $clientPhoneNumber)); $respVault = $unms->get("vault/$deviceId/credentials", [
//$this->sendMessage($notificationData, $clientSmsNumber, $messageBody); 'headers' => ['X-Auth-Token' => $config['unmsApiToken']]
//$this->sendWhatsApp($notificationData, $clientSmsNumber); ]);
$vault = json_decode($respVault->getBody()->getContents(), true);
$client_callbell_api = new ClientCallBellAPI($UCRMAPIToken, $IPServer, $CallBellAPIToken); if (isset($vault['credentials'][0]['password'])) {
$response_getContactCallBell = json_decode($client_callbell_api->getContactWhatsapp($clientPhoneNumber), true); $passVault = $vault['credentials'][0]['password'];
$client_callbell_api->patchServiceStatusWhatsApp($response_getContactCallBell, $notificationData); break;
} catch (HttpException $httpException) {
//$this->logger->debug('Ocurrio un error en el try catch');
$this->logger->error($httpException->getCode() . ' ' . $httpException->getMessage());
} }
} catch (\Exception $e) { continue; }
} }
if ($passVault) {
} $passwordValue = $passVault;
} else if ($firstDeviceId) {
/** // Regenerar
* implement in subclass with the specific messaging provider $newPass = $this->generateStrongPassword(16);
* @see TwilioNotifierFacade::sendMessage() try {
*/ $unms->post("vault/$firstDeviceId/credentials/regenerate", [
abstract protected function sendMessage( 'headers' => ['X-Auth-Token' => $config['unmsApiToken']],
NotificationData $notificationData, 'json' => [['username' => 'ubnt', 'password' => $newPass, 'readOnly' => true]]
string $clientSmsNumber, ]);
string $messageBody $passwordValue = $newPass;
): void; } catch (\Exception $e) { $passwordValue = $newPass; }
// /**
// * implement in subclass with the specific messaging provider
// * @see TwilioNotifierFacade::sendWhatsApp()
// */
// abstract protected function sendWhatsApp(
// NotificationData $notificationData,
// string $clientSmsNumber
// ): void;
function validarNumeroTelefono($telefono)
{
// Eliminar espacios y guiones
$telefono = preg_replace('/\s+|-/', '', $telefono);
// Eliminar caracteres no numéricos, excepto el '+' si está al principio
$telefono = preg_replace('/(?!^\+)[^0-9]/', '', $telefono);
// Verificar si el número comienza con "+1" o "1" y tiene 11 dígitos en total
if (
(substr($telefono, 0, 2) === "+1" && strlen($telefono) === 12) ||
(substr($telefono, 0, 1) === "1" && strlen($telefono) === 11)
) {
return $telefono;
}
// Si el número tiene exactamente 10 dígitos, agregar el prefijo "521"
if (strlen($telefono) === 10) {
return "521" . $telefono;
}
// Si el número tiene más de 10 dígitos, verificar que comience con "521"
if (strlen($telefono) > 10) {
if (substr($telefono, 0, 2) === "521" && strlen($telefono) === 12) {
return $telefono;
} else { } else {
// Si no comienza con "52", tomar los últimos 10 dígitos y agregar el prefijo "52" $passwordValue = "⚠️ Sin antena";
return "521" . substr($telefono, -10); }
}
} catch (\Exception $e) {
$passwordValue = "⚠️ Error API";
}
}
}
$allServicePasswords[] = trim("$label $passwordValue");
}
$finalValue = implode(' ', $allServicePasswords);
// Evitar sincronización redundante
if ($finalValue === $passCRM) {
return $finalValue;
}
$this->syncPasswordWithCrm((int)$clientId, $finalValue);
return $finalValue;
} catch (\Exception $e) {
$this->logger->error("Error en getVaultCredentialsByClientId: " . $e->getMessage());
return 'Error: ' . $e->getMessage();
} }
} }
// Si no cumple con ninguna de las condiciones anteriores, retornar cadena vacía private function syncPasswordWithCrm(int $clientId, string $passVault): void {
return ''; $config = PluginConfigManager::create()->loadConfig();
$crm = new Client(['base_uri' => "https://{$config['ipserver']}/crm/api/v1.0/", 'verify' => false]);
try {
$respClient = $crm->get("clients/$clientId", [
'headers' => ['X-Auth-Token' => $config['apitoken']]
]);
$clientData = json_decode($respClient->getBody()->getContents(), true);
$passCRM = '';
$attributeId = 17;
if (isset($clientData['attributes'])) {
foreach ($clientData['attributes'] as $attr) {
if ($attr['key'] === 'passwordAntenaCliente') {
$passCRM = $attr['value'] ?? '';
$attributeId = $attr['customAttributeId'];
break;
}
}
}
if (empty($passCRM) || $passCRM !== $passVault) {
$this->logger->info("Sincronizando pass CRM cliente $clientId.");
$this->patchClientCustomAttribute($clientId, (int)$attributeId, $passVault);
}
} catch (\Exception $e) { $this->logger->warning("Fallo sincronización pass CRM: " . $e->getMessage()); }
} }
protected function generateStrongPassword(int $length = 16): string {
$lower = 'abcdefghijkmnopqrstuvwxyz'; // Eliminamos 'l'
$upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; // Eliminamos 'I', 'O'
$digits = '23456789'; // Eliminamos '1', '0'
$symbols = '@#'; // Solo símbolos amigables para impresoras térmicas
$all = $lower . $upper . $digits . $symbols;
$pwChars = [];
// Asegurar que tenga al menos uno de cada tipo si es posible
$pwChars[] = $lower[random_int(0, strlen($lower) - 1)];
$pwChars[] = $upper[random_int(0, strlen($upper) - 1)];
$pwChars[] = $digits[random_int(0, strlen($digits) - 1)];
$pwChars[] = $symbols[random_int(0, strlen($symbols) - 1)];
for ($i = count($pwChars); $i < $length; $i++) {
$pwChars[] = $all[random_int(0, strlen($all) - 1)];
}
// Mezclar Fisher-Yates
$n = count($pwChars);
for ($i = $n - 1; $i > 0; $i--) {
$j = random_int(0, $i);
$tmp = $pwChars[$i];
$pwChars[$i] = $pwChars[$j];
$pwChars[$j] = $tmp;
}
return implode('', $pwChars);
}
protected function patchClientCustomAttribute(int $clientId, int $attributeId, string $value): bool {
$config = PluginConfigManager::create()->loadConfig();
$crm = new Client(['base_uri' => "https://{$config['ipserver']}/crm/api/v1.0/", 'verify' => false]);
try {
$crm->patch("clients/$clientId", [
'headers' => ['X-Auth-Token' => $config['apitoken']],
'json' => [
"attributes" => [['value' => $value, 'customAttributeId' => $attributeId]]
]
]);
return true;
} catch (\Exception $e) {
$this->logger->error("Error patching custom attribute for client $clientId: " . $e->getMessage());
return false;
}
}
protected function comparePasswords(?string $crm, ?string $vault): string {
if ($vault && strpos($vault, 'Error') !== 0) return $vault;
if ($crm && strpos($crm, 'Error') !== 0) return $crm;
return '⚠️ Probar pass conocida.';
}
protected function validarNumeroTelefono($n): string {
if (!$n) return '';
$n = preg_replace('/\D/', '', (string)$n);
return (strlen($n) === 10) ? '52' . $n : $n;
}
abstract protected function sendWhatsApp(NotificationData $notificationData, string $clientSmsNumber): void;
} }

View File

@ -11,6 +11,8 @@ use SmsNotifier\Service\SmsNumberProvider;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Exception\RequestException;
use Ubnt\UcrmPluginSdk\Service\UcrmApi; use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
/* /*
@ -33,6 +35,12 @@ abstract class AbstractOxxoOperationsFacade
* @var SmsNumberProvider * @var SmsNumberProvider
*/ */
protected $clientPhoneNumber; protected $clientPhoneNumber;
/**
* @var \SmsNotifier\Service\MinioStorageService
*/
protected $minioStorage;
/** /**
* @var UcrmApi * @var UcrmApi
*/ */
@ -44,168 +52,441 @@ abstract class AbstractOxxoOperationsFacade
public function __construct( public function __construct(
Logger $logger, Logger $logger,
MessageTextFactory $messageTextFactory, MessageTextFactory $messageTextFactory,
SmsNumberProvider $clientPhoneNumber SmsNumberProvider $clientPhoneNumber,
\SmsNotifier\Service\MinioStorageService $minioStorage
) { ) {
$this->logger = $logger; $this->logger = $logger;
$this->messageTextFactory = $messageTextFactory; $this->messageTextFactory = $messageTextFactory;
$this->clientPhoneNumber = $clientPhoneNumber; $this->clientPhoneNumber = $clientPhoneNumber;
$this->minioStorage = $minioStorage;
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$client = new Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$this->ucrmApi = new UcrmApi($client, $config['apitoken'] ?? '');
} }
/* /*
* Creates a PaymentIntent for OXXO in Stripe for a Customer * Creates a PaymentIntent for OXXO in Stripe for a Customer
* @param array $event_json
* @param int|null $amount
* @return array
* @throws \GuzzleHttp\Exception\GuzzleException
* @throws \Stripe\Exception\ApiErrorException
* @throws Exception
*/ */
public function createOxxoPaymentIntent($event_json):string public function createOxxoPaymentIntent($event_json, $amount = null, bool $uploadToFtp = true): array
{ {
$this->logger->info("Creando referencia del cliente para oxxo: ".PHP_EOL); // 1. Obtener Referencia de Stripe (Lógica Común)
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create(); $stripeResult = $this->createStripeReference($event_json, $amount);
// Si hubo error en Stripe, retornar el resultado de error
if ($stripeResult['hasError']) {
return $stripeResult['data'];
}
// 2. Procesamiento Síncrono (Generación inmediata)
// Usamos los datos obtenidos de Stripe
$oxxoData = $stripeResult['data'];
return $this->processSynchronousGeneration($oxxoData, $uploadToFtp);
}
/**
* Crea la orden en el servicio Docker y retorna el ID para flujo asíncrono
*/
public function createAsyncOxxoOrder($event_json, $amount = null): array
{
// 1. Obtener Referencia de Stripe
$stripeResult = $this->createStripeReference($event_json, $amount);
if ($stripeResult['hasError']) {
return $stripeResult['data'];
}
$data = $stripeResult['data'];
// 2. Llamar al servicio Docker para crear la orden (POST /orders)
$config = PluginConfigManager::create()->loadConfig();
$ipPuppeteer = $config['ipPuppeteer'];
$portPuppeteer = $config['portPuppeteer'];
$api_url = "http://$ipPuppeteer:$portPuppeteer/orders";
try {
$client = new Client(['timeout' => 5]);
$response = $client->post($api_url, [
'json' => [
'client_id' => $data['clientID'],
'amount' => $data['amount'],
'client_full_name' => $data['clientFullName'],
'oxxo_reference' => $data['oxxo_reference'],
'stripe_url' => $data['url']
]
]);
$orderData = json_decode($response->getBody()->getContents(), true);
// Agregar el order_id al resultado para que el Plugin lo devuelva
$data['order_id'] = $orderData['order_id'] ?? null;
return $data; // Retornamos los datos básicos + order_id
} catch (Exception $e) {
$this->logger->error("Error creando orden asíncrona en Docker: " . $e->getMessage());
// Fallback: Retornar los datos de Stripe aunque falle el guardado en DB local (mejor que nada)
$data['error'] = 'docker_order_creation_failed';
return $data;
}
}
/**
* Trigger para generar la imagen en background, subirla y actualizar la orden
*/
public function generateAndUploadOrder(int $orderId, string $stripeUrl, string $clientFullName, bool $uploadToFtp = true): void
{
$this->logger->info("Iniciando generación en background para Orden #$orderId");
$config = PluginConfigManager::create()->loadConfig();
$ipPuppeteer = $config['ipPuppeteer'];
$portPuppeteer = $config['portPuppeteer'];
// 1. Solicitar Generación (POST /orders/:id/generate)
// Calculamos nombre de archivo
$clientFullNameWithoutSpaces = str_replace(' ', '_', $clientFullName);
$voucherFileName = 'voucher_'.$clientFullNameWithoutSpaces.'_' . time() . '.jpeg';
$output_filename = realpath(__DIR__ . '/../../vouchers_oxxo') . '/'. $voucherFileName;
$generateUrl = "http://$ipPuppeteer:$portPuppeteer/orders/$orderId/generate";
try {
$client = new Client(['timeout' => 60]); // Mayor timeout para Puppeteer
$response = $client->post($generateUrl, [
'json' => [
'url' => $stripeUrl,
'filename' => $voucherFileName,
'clip' => ['x' => 325, 'y' => 30, 'width' => 550, 'height' => 550]
]
]);
if ($response->getStatusCode() === 200) {
// Guardar imagen localmente
$imageContent = $response->getBody()->getContents();
file_put_contents($output_filename, $imageContent);
$this->logger->info("Imagen generada y guardada localmente: $voucherFileName");
$voucherUrl = '';
// 2. Subir a S3/MinIO (si aplica)
if ($uploadToFtp) {
// $voucherUrl = $this->UploadVoucherToWordpressByImageFileName($voucherFileName);
// $this->logger->info("Imagen subida a FTP: $voucherUrl");
// Nueva implementación MinIO
$voucherUrl = $this->minioStorage->uploadFile($output_filename, $voucherFileName);
$this->logger->info("Imagen subida a MinIO: $voucherUrl");
}
// 3. Actualizar Orden (POST /orders/:id/complete)
if ($voucherUrl) {
$completeUrl = "http://$ipPuppeteer:$portPuppeteer/orders/$orderId/complete";
$client->post($completeUrl, [
'json' => ['voucher_image_url' => $voucherUrl]
]);
}
}
} catch (Exception $e) {
$this->logger->error("Error en flujo de background para Orden #$orderId: " . $e->getMessage());
}
}
/**
* Obtiene el estado de una orden desde el servicio Docker
*/
public function getOxxoOrderStatus($orderId): array
{
$config = PluginConfigManager::create()->loadConfig();
$ipPuppeteer = $config['ipPuppeteer'];
$portPuppeteer = $config['portPuppeteer'];
$api_url = "http://$ipPuppeteer:$portPuppeteer/orders/$orderId";
try {
$client = new Client(['timeout' => 5]);
$response = $client->get($api_url);
$data = json_decode($response->getBody()->getContents(), true);
// Si la URL de la imagen es relativa o local, ajustarla si es necesario
// pero el servicio ya guarda la URL completa del FTP si se subió.
return $data;
} catch (Exception $e) {
$this->logger->error("Error obteniendo estado de orden #$orderId: " . $e->getMessage());
return ['error' => 'fetch_failed', 'message' => $e->getMessage()];
}
}
/**
* Lógica extraída de Stripe
* Retorna ['hasError' => bool, 'data' => array]
*/
public function createStripeReference($event_json, $amount = null): array
{
$arrayOxxoPayment = [];
$integerAmount = $amount;
// Inicializar Config y Clientes (Copied logic)
$configManager = PluginConfigManager::create();
$config = $configManager->loadConfig(); $config = $configManager->loadConfig();
$StripeToken = $config['tokenstripe']; $StripeToken = $config['tokenstripe'];
$IPServer = $config['ipserver']; $IPServer = $config['ipserver'];
$tokenCRM = $config['apitoken']; $tokenCRM = $config['apitoken'];
// $this->logger->info("Datos de configuración: ".PHP_EOL);
// $this->logger->info("Stripe token: ".$StripeToken.PHP_EOL);
// $this->logger->info("IP server: ".$IPServer.PHP_EOL);
// $this->logger->info("Token CRM: ".$tokenCRM.PHP_EOL);
$baseUri = 'https://'.$IPServer.'/crm/api/v1.0/'; //endpoint de la API REST del CRM
$stripe = new \Stripe\StripeClient($StripeToken); //Token de clave privada para la API de Stripe $baseUri = 'https://' . $IPServer . '/crm/api/v1.0/';
//$stripe = new \Stripe\StripeClient('sk_test_51OkG0REFY1WEUtgRH6UxBK5pu80Aq5Iy8EcdPnf0cOWzuVLQTpyLCd7CbPzqMsWMafZOHElCxhEHF7g8boURjWlJ00tBwE0W1M'); //Token de clave privada para la API de Stripe modo pruebas if (!isset($this->ucrmApi)) {
// Re-instanciar si es necesario, aunque ya está en consructor
$this->ucrmApi = UcrmApi::create(); // Pero usamos la propiedad de clase
$currentUserAdmin = $this->ucrmApi->get('users/admins',[]); }
$clientID = $event_json->client_id;
// ... Lógica de obtención de cliente, Stripe Customer, PaymentIntent ...
// [RESUMIDO: Copiaremos el tocho de código aquí, simplificado]
$clientID = $event_json['client_id'];
$clientFullName = '';
// --- 1. Obtener Cliente CRM ---
try { try {
$clientGuzzle = new Client([
$clientGuzzleHttp = new Client([
'base_uri' => $baseUri, 'base_uri' => $baseUri,
'headers' => [ 'headers' => ['X-Auth-App-Key' => $tokenCRM, 'Accept' => 'application/json'],
'X-Auth-App-Key' => $tokenCRM, // Cambia el nombre de la cabecera de autorización para el UISP CRM
'Accept' => 'application/json', // Indica que esperamos una respuesta en formato JSON
],
'verify' => false, 'verify' => false,
'timeout' => 5
]); ]);
$resp = $clientGuzzle->get("clients/" . $clientID);
// Hacer la solicitud GET para obtener los datos del cliente $arrayClientCRM = json_decode($resp->getBody()->getContents(), true);
$response = $clientGuzzleHttp->request('GET', "clients/".$clientID); $clientFullName = $arrayClientCRM['firstName'] . ' ' . $arrayClientCRM['lastName'];
// Obtener el cuerpo de la respuesta como JSON } catch (Exception $e) {
$arrayClientCRM = json_decode($response->getBody()->getContents(), true); return ['hasError' => true, 'data' => $this->buildErrorArray('errorGetClient', 'Error obteniendo cliente', $clientID, $clientFullName, $amount)];
// Inicializamos una variable para guardar el valor del 'stripeCustomerId'
$stripeCustomerId = null;
$clientEmail = '';
// Recorrer los atributos para encontrar el 'stripeCustomerId'
foreach ($arrayClientCRM['attributes'] as $attribute) {
if ($attribute['key'] === 'stripeCustomerId') {
$stripeCustomerId = $attribute['value'];
break;
}
} }
// Recorrer los contactos // --- 2. Obtener Email y Stripe ID ---
$clientEmail = 'siip8873@gmail.com'; // Default
foreach ($arrayClientCRM['contacts'] as $contact) { foreach ($arrayClientCRM['contacts'] as $contact) {
if ($contact['email'] != '') { if (!empty($contact['email'])) { $clientEmail = $contact['email']; break; }
$clientEmail = $contact['email'];
break;
}else{
$clientEmail = 'siip8873@gmail.com';
break;
}
} }
$this->logger->info("Se obtuvieron los datos del cliente y Stripe Customer ID: ".$stripeCustomerId.PHP_EOL); $stripeCustomerId = null;
foreach ($arrayClientCRM['attributes'] as $attr) {
} catch (RequestException $e) { if ($attr['key'] === 'stripeCustomerId') { $stripeCustomerId = $attr['value']; break; }
// Manejo de errores en la petición }
$this->logger->error("Error al obtener atributos personalizados del cliente: " . $e->getMessage().PHP_EOL); if (!$stripeCustomerId) {
return ['hasError' => true, 'data' => $this->buildErrorArray('errorGetCustomerStripe', 'Cliente sin Stripe ID', $clientID, $clientFullName, $amount)];
} }
$amount = abs($arrayClientCRM['accountOutstanding']) * 100; // --- 3. Calcular Monto ---
if ($amount === null) {
$amount = abs($arrayClientCRM['accountOutstanding']);
} else {
if(!is_numeric($amount)) $amount = preg_replace('/[^\d.]/', '', $amount);
}
//$this->logger->info("User Admin ID: " . json_encode($currentUserAdmin) . PHP_EOL); if ($amount <= 10) {
if($amount>0){ return ['hasError' => true, 'data' => $this->buildErrorArray('errorsinadeudo', 'Monto insuficiente o sin deuda', $clientID, $clientFullName, $amount)];
}
// --- 4. Crear Payment Intent en Stripe ---
try { try {
// Crear el PaymentIntent vinculado al cliente $amountInCents = intval($amount * 100);
$paymentIntent = $stripe->paymentIntents->create([ $guzzleClient = new Client(['timeout' => 10]);
'amount' => $amount, // Monto en centavos (300 MXN)
// Payment Intent
$piResp = $guzzleClient->post('https://api.stripe.com/v1/payment_intents', [
'auth' => [$StripeToken, ''],
'form_params' => [
'amount' => $amountInCents,
'currency' => 'mxn', 'currency' => 'mxn',
'payment_method_types' => ['customer_balance', 'card' ,'oxxo'], 'payment_method_types' => ['customer_balance', 'card', 'oxxo'],
'description' => 'Pago de servicio de SIIP Internet', 'customer' => $stripeCustomerId,
'customer' => $stripeCustomerId, // Vincular al cliente existente
'metadata' => [ 'metadata' => [
'clientId' => $clientID, // ID del cliente en UISP 'clientId' => $clientID,
'ucrm_client_id' => $clientID, // Backwards compatibility
'createdBy' => 'UCRM', 'createdBy' => 'UCRM',
'paymentType' => 'card.one_time', 'paymentType' => 'card.one_time',
'signedInAdminId' => $currentUserAdmin[0]['id'] 'signedInAdminId' => $config['idPaymentAdminCRM'] ?? 1,
], 'tipoPago' => 'OXXO'
'payment_method_options' => [
'oxxo' => [
'expires_after_days' => 3, // El voucher expira en 3 días
],
], ],
'payment_method_options' => ['oxxo' => ['expires_after_days' => 3]]
]
]); ]);
$paymentIntent = json_decode($piResp->getBody()->getContents(), true);
// Crear un método de pago OXXO con detalles de facturación // Payment Method
$paymentMethod = $stripe->paymentMethods->create([ $firstName = $arrayClientCRM['firstName'] ?? '';
$lastName = $arrayClientCRM['lastName'] ?? '';
$pmResp = $guzzleClient->post('https://api.stripe.com/v1/payment_methods', [
'auth' => [$StripeToken, ''],
'form_params' => [
'type' => 'oxxo', 'type' => 'oxxo',
'billing_details' => [ 'billing_details' => ['name' => "$firstName $lastName", 'email' => $clientEmail]
'name' => $arrayClientCRM['firstName'].' '.$arrayClientCRM['lastName'], // Proporciona el nombre del cliente ]
'email' => $clientEmail, // Proporciona el correo del cliente
],
]); ]);
$paymentMethod = json_decode($pmResp->getBody()->getContents(), true);
// Confirmar el PaymentIntent con el método de pago OXXO // Confirm
$paymentIntent = $stripe->paymentIntents->confirm( $confResp = $guzzleClient->post('https://api.stripe.com/v1/payment_intents/' . $paymentIntent['id'] . '/confirm', [
$paymentIntent->id, 'auth' => [$StripeToken, ''],
['payment_method' => $paymentMethod->id] 'form_params' => ['payment_method' => $paymentMethod['id']]
); ]);
$paymentIntentConfirm = json_decode($confResp->getBody()->getContents(), true);
// Verificar si hay acciones pendientes (next_action)
if (!empty($paymentIntent->next_action) && isset($paymentIntent->next_action->oxxo_display_details)) {
$oxxoPayment = $paymentIntent->next_action->oxxo_display_details;
//print_r($oxxoPayment);
// Obtener la referencia OXXO y la URL del recibo
$oxxo_reference = $oxxoPayment->number;
$oxxo_receipt_url = $oxxoPayment->hosted_voucher_url;
// Mostrar la referencia y la URL del recibo al cliente
$this->logger->info("Referencia OXXO: " . $oxxo_reference.PHP_EOL);
$this->logger->info("URL del recibo: " . $oxxo_receipt_url.PHP_EOL);
return $oxxo_receipt_url;
// echo "Referencia OXXO: " . $oxxo_reference . "\n";
// echo "URL del recibo: " . $oxxo_receipt_url . "\n";
} else {
// Manejo de error si no hay detalles de OXXO
// echo "El PaymentIntent no tiene detalles de OXXO disponibles aún.\n";
// echo "Estado actual del PaymentIntent: " . $paymentIntent->status . "\n";
$this->logger->info("El PaymentIntent no tiene detalles de OXXO disponibles aún. " .PHP_EOL);
$this->logger->info("Estado actual del PaymentIntent: " . $paymentIntent->status.PHP_EOL);
return 'error';
}
} catch (Exception $e) { } catch (Exception $e) {
// Manejar cualquier error return ['hasError' => true, 'data' => $this->buildErrorArray('errorStripeApi', $e->getMessage(), $clientID, $clientFullName, $amount)];
//echo 'Error: ' . $e->getMessage();
$this->logger->error('Error al crear el payment intent: ' . $e->getMessage().PHP_EOL);
return 'error';
} }
}else{
$this->logger->info("Este cliente no tiene adeudos por lo tanto no se puede genear su referencia de oxxo. " .PHP_EOL); // --- 5. Extraer Datos OXXO ---
return 'errorsinadeudo'; if (!empty($paymentIntentConfirm['next_action']['oxxo_display_details'])) {
$oxxoDetails = $paymentIntentConfirm['next_action']['oxxo_display_details'];
return [
'hasError' => false,
'data' => [
'oxxo_reference' => $oxxoDetails['number'],
'url' => $oxxoDetails['hosted_voucher_url'],
'error' => '',
'clientID' => $clientID,
'clientFullName' => $clientFullName,
'amount' => $amount,
'voucher_image_url' => ''
]
];
}
return ['hasError' => true, 'data' => $this->buildErrorArray('errorNoOxxoDetails', 'No se recibieron detalles OXXO', $clientID, $clientFullName, $amount)];
}
private function buildErrorArray($code, $desc, $clientId, $name, $amount) {
return [
'oxxo_reference' => '',
'url' => '',
'error' => $code,
'failDescription' => $desc,
'clientID' => $clientId,
'clientFullName' => $name,
'amount' => $amount,
'voucher_image_url' => ''
];
}
/**
* Crea la orden en el microservicio (Paso 1 del flujo asíncrono)
*/
public function createOxxoOrder($arrayOxxoPayment) {
$config = PluginConfigManager::create()->loadConfig();
$ipPuppeteer = $config['ipPuppeteer'];
$portPuppeteer = $config['portPuppeteer'];
$baseUrl = 'http://'.$ipPuppeteer.':'.$portPuppeteer;
$guzzleClient = new Client(['timeout' => 10]);
try {
$createOrderResp = $guzzleClient->post($baseUrl . '/orders', [
'json' => [
'client_id' => $arrayOxxoPayment['clientID'],
'amount' => $arrayOxxoPayment['amount'],
'client_full_name' => $arrayOxxoPayment['clientFullName'],
'oxxo_reference' => $arrayOxxoPayment['oxxo_reference'],
'stripe_url' => $arrayOxxoPayment['url']
]
]);
$orderData = json_decode($createOrderResp->getBody()->getContents(), true);
$arrayOxxoPayment['order_id'] = $orderData['order_id'] ?? null;
return $arrayOxxoPayment;
} catch (Exception $e) {
$this->logger->error("Error creando orden OXXO: " . $e->getMessage());
return $arrayOxxoPayment;
}
}
/**
* Genera el voucher y lo sube (Paso 2 del flujo asíncrono)
*/
public function generateOxxoVoucher($arrayOxxoPayment, $uploadToFtp) {
if (empty($arrayOxxoPayment['order_id'])) {
$this->logger->error("Intentando generar voucher sin order_id");
return $arrayOxxoPayment;
}
$config = PluginConfigManager::create()->loadConfig();
$ipPuppeteer = $config['ipPuppeteer'];
$portPuppeteer = $config['portPuppeteer'];
$baseUrl = 'http://'.$ipPuppeteer.':'.$portPuppeteer;
$guzzleClient = new Client(['timeout' => 60]);
$clientFullNameWithoutSpaces = str_replace(' ', '_', $arrayOxxoPayment['clientFullName']);
$voucherFileName = 'voucher_'.$clientFullNameWithoutSpaces.'_' . time() . '.jpeg';
$output_filename = realpath(__DIR__ . '/../../vouchers_oxxo') . '/'. $voucherFileName;
$request_data = [
'url' => $arrayOxxoPayment['url'],
'filename' => $voucherFileName,
'clip' => ['x' => 325, 'y' => 30, 'width' => 550, 'height' => 550]
];
try {
$response = $guzzleClient->post($baseUrl . '/orders/' . $arrayOxxoPayment['order_id'] . '/generate', [
'json' => $request_data,
'headers' => ['Accept' => 'image/jpeg, image/png']
]);
if ($response->getStatusCode() === 200) {
file_put_contents($output_filename, $response->getBody()->getContents());
$arrayOxxoPayment['voucher_filename'] = $voucherFileName;
if ($uploadToFtp) {
$url_file = $this->minioStorage->uploadFile($output_filename, $voucherFileName);
$arrayOxxoPayment['voucher_image_url'] = $url_file;
try {
$guzzleClient->post($baseUrl . '/orders/' . $arrayOxxoPayment['order_id'] . '/complete', [
'json' => ['voucher_image_url' => $url_file]
]);
// CLEANUP: Eliminar voucher local tras subida exitosa
if (file_exists($output_filename)) {
unlink($output_filename);
//$this->logger->info("Limpieza: Voucher local eliminado ($voucherFileName)");
}
} catch (Exception $ex) {
$this->logger->warning("No se pudo actualizar URL final: " . $ex->getMessage());
}
}
}
} catch (Exception $e) {
$this->logger->error("Error generando voucher (Puppeteer): " . $e->getMessage());
}
return $arrayOxxoPayment;
}
/**
* Mantiene compatibilidad con llamadas anteriores
*/
private function processSynchronousGeneration($arrayOxxoPayment, $uploadToFtp) {
$arrayOxxoPayment = $this->createOxxoOrder($arrayOxxoPayment);
if (!empty($arrayOxxoPayment['order_id'])) {
$arrayOxxoPayment = $this->generateOxxoVoucher($arrayOxxoPayment, $uploadToFtp);
}
return $arrayOxxoPayment;
} }
}
// /** // /**
@ -221,7 +502,7 @@ abstract class AbstractOxxoOperationsFacade
function validarEmail($email) function validarEmail($email)
{ {
$this->logger->info('SE VALIDA EL EMAIL!!! '.PHP_EOL); $this->logger->debug('SE VALIDA EL EMAIL!!! ' . PHP_EOL);
// Utilizar la función filter_var con el filtro FILTER_VALIDATE_EMAIL para validar el email // Utilizar la función filter_var con el filtro FILTER_VALIDATE_EMAIL para validar el email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Si el email es válido, devolver el email // Si el email es válido, devolver el email
@ -237,21 +518,18 @@ abstract class AbstractOxxoOperationsFacade
{ {
// $log = PluginLogManager::create(); //Initialize Logger // $log = PluginLogManager::create(); //Initialize Logger
// $configManager = PluginConfigManager::create(); $configManager = PluginConfigManager::create();
// $config = $configManager->loadConfig(); $config = $configManager->loadConfig();
// // Configuración de conexión FTP // Configuración de conexión FTP
// $ftp_server = $config['hostServerFTP']; $ftp_server = $config['hostServerFTP'];
// $ftp_username = $config['usernameServerFTP']; $ftp_username = $config['usernameServerFTP'];
// $ftp_password = $config['passServerFTP']; $ftp_password = $config['passServerFTP'];
$remote_folder = "/public_html/wp/wp-content/uploads/img/"; $remote_folder = "/public_html/wp/wp-content/uploads/img/";
// Configuración de conexión FTP // Configuración de conexión FTP
$ftp_server = "siip.mx";
$ftp_username = "siip0001";
$ftp_password = '$spGiT,[wa)n';
$remote_file = "/public_html/wp/wp-content/uploads/img/" . $imageFileName; $remote_file = "/public_html/wp/wp-content/uploads/img/" . $imageFileName;
$file_to_upload = __DIR__ . '/' . $imageFileName; $file_to_upload = __DIR__ . '/' . $imageFileName;
$url = 'https://siip.mx/wp/wp-content/uploads/img/' . $imageFileName; $url = 'https://siip.mx/wp/wp-content/uploads/img/' . $imageFileName;
@ -339,4 +617,150 @@ abstract class AbstractOxxoOperationsFacade
} }
function UploadVoucherToWordpressByImageFileName($imageFileName): string
{
$log = PluginLogManager::create(); //Initialize Logger
$configManager = PluginConfigManager::create();
$config = $configManager->loadConfig();
// Configuración de conexión FTP
$ftp_server = $config['hostServerFTP'];
$ftp_username = $config['usernameServerFTP'];
$ftp_password = $config['passServerFTP'];
$remote_folder = "/public_html/wp/wp-content/uploads/vouchers_oxxo/";
$log->appendLog("Subiendo voucher a worpdpress " . PHP_EOL);
// Configuración de conexión FTP
$remote_file = "/public_html/wp/wp-content/uploads/vouchers_oxxo/" . $imageFileName;
$file_to_upload = __DIR__ . '/../../vouchers_oxxo/' . $imageFileName;
$url = 'https://siip.mx/wp/wp-content/uploads/vouchers_oxxo/' . $imageFileName;
$log->appendLog("file_to_upload: " . $file_to_upload . PHP_EOL);
// Conexión FTP
$ftp_conn = ftp_connect($ftp_server) or die("No se pudo conectar al servidor FTP");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_password);
ftp_pasv($ftp_conn, true);
// Verificar conexión y login
if ($ftp_conn && $login) {
$log->appendLog("Conexión FTP exitosa" . PHP_EOL);
// Cargar archivo
if (ftp_put($ftp_conn, $remote_file, $file_to_upload, FTP_BINARY)) {
$log->appendLog("El archivo ha sido cargado exitosamente." . PHP_EOL);
$log->appendLog("La URL es: " . $url . PHP_EOL);
// try {
// $this->deleteFilesWordpressExceptLastHundred($log, $ftp_conn, $remote_folder);
// } catch (\Exception $e) {
// $log->appendLog("Error en limpieza de archivos antiguos: " . $e->getMessage() . PHP_EOL);
// }
// Cerrar conexión FTP (o dejar abierta si se prefiere, pero mejor cerrar al final si es posible, aunque aquí retornamos directo)
// ftp_close($ftp_conn);
// Cerrar conexión FTP
//ftp_close($ftp_conn); //COMENTAR AQUÍ SI SE BORRAN LOS ARCHIVOS DE WORDPRESS DESCOMENTANDO EL CÓDIGO DE MÁS ABAJO
return $url; //COMENTAR AQUÍ SI SE BORRAN LOS ARCHIVOS DE WORDPRESS DESCOMENTANDO EL CÓDIGO DE MÁS ABAJO
} else {
$log->appendLog("Error al cargar el archivo " . PHP_EOL);
ftp_close($ftp_conn);
return '';
}
//SI SE DECIDE VOLVER A ELIMINAR LOS COMPROBANTES ENTONCES DESCOMENTAR ESTA PARTE DE ABAJO Y COMENTAR LA SECCIÓN DE ARRIBA
// Obtener lista de archivos en la carpeta
// $files = ftp_nlist($ftp_conn, $remote_folder);
// if (is_array($files)) {
// // Eliminar la ruta del directorio de los archivos
// $files = array_map(function ($file) use ($remote_folder) {
// return str_replace($remote_folder, '', $file);
// }, $files);
// // Obtener fechas de modificación
// $filesWithTime = [];
// foreach ($files as $file) {
// $modifiedTime = ftp_mdtm($ftp_conn, $remote_folder . $file);
// if ($modifiedTime != -1) {
// $filesWithTime[$file] = $modifiedTime;
// }
// }
// // Ordenar archivos por fecha de modificación, más recientes primero
// arsort($filesWithTime);
// // Obtener los archivos a eliminar (todos menos los 50 más recientes)
// $filesToDelete = array_slice(array_keys($filesWithTime), 50);
// // Eliminar archivos antiguos
// foreach ($filesToDelete as $file) {
// if (ftp_delete($ftp_conn, $remote_folder . $file)) {
// $log->appendLog("Comprobante eliminado de Wordpress: " . $file . PHP_EOL);
// } else {
// $log->appendLog('Error al borrar comprobante' . $file . PHP_EOL);
// }
// }
// $log->appendLog("Archivos eliminados" . PHP_EOL);
// ftp_close($ftp_conn);
// return $url;
// } else {
// $log->appendLog("No se pudo obtener la lista de archivos de la carpeta FTP" . PHP_EOL);
// ftp_close($ftp_conn);
// return $url;
// }
} else {
$log->appendLog("No se pudo conectar o iniciar sesión en el servidor FTP." . PHP_EOL);
return '';
}
}
function deleteFilesWordpressExceptLastHundred($log, $ftp_conn, $remote_folder): bool
{
// Obtener lista de archivos en la carpeta
$files = ftp_nlist($ftp_conn, $remote_folder);
if (is_array($files)) {
// Eliminar la ruta del directorio de los archivos
$files = array_map(function ($file) use ($remote_folder) {
return str_replace($remote_folder, '', $file);
}, $files);
// Obtener fechas de modificación
$filesWithTime = [];
foreach ($files as $file) {
$modifiedTime = ftp_mdtm($ftp_conn, $remote_folder . $file);
if ($modifiedTime != -1) {
$filesWithTime[$file] = $modifiedTime;
}
}
// Ordenar archivos por fecha de modificación, más recientes primero
arsort($filesWithTime);
// Obtener los archivos a eliminar (todos menos los 50 más recientes)
$filesToDelete = array_slice(array_keys($filesWithTime), 50);
// Eliminar archivos antiguos
foreach ($filesToDelete as $file) {
if (ftp_delete($ftp_conn, $remote_folder . $file)) {
$log->appendLog("Voucher eliminado de Wordpress: " . $file . PHP_EOL);
} else {
$log->appendLog('Error al borrar voucher' . $file . PHP_EOL);
}
}
$log->appendLog("Archivos eliminados" . PHP_EOL);
ftp_close($ftp_conn);
return true;
} else {
$log->appendLog("No se pudo obtener la lista de archivos de la carpeta FTP" . PHP_EOL);
ftp_close($ftp_conn);
return false;
}
}
} }

View File

@ -4,81 +4,60 @@ declare(strict_types=1);
namespace SmsNotifier\Facade; namespace SmsNotifier\Facade;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use SmsNotifier\Data\NotificationData; use SmsNotifier\Data\NotificationData;
use SmsNotifier\Factory\MessageTextFactory; use SmsNotifier\Factory\MessageTextFactory;
use SmsNotifier\Service\Logger; use SmsNotifier\Service\Logger;
use SmsNotifier\Service\SmsNumberProvider; use SmsNotifier\Service\SmsNumberProvider;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use Ubnt\UcrmPluginSdk\Service\UcrmApi; use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use Stripe\StripeClient;
/*
* send message to client's number
*/
abstract class AbstractStripeOperationsFacade abstract class AbstractStripeOperationsFacade
{ {
/**
* @var Logger
*/
protected $logger; protected $logger;
/**
* @var MessageTextFactory
*/
protected $messageTextFactory; protected $messageTextFactory;
/**
* @var SmsNumberProvider
*/
protected $clientPhoneNumber; protected $clientPhoneNumber;
/**
* @var UcrmApi
*/
protected $ucrmApi; protected $ucrmApi;
private $systemAttributesCache = null;
protected $stripeCustomAttributeID; public function __construct(Logger $logger, MessageTextFactory $messageTextFactory, SmsNumberProvider $clientPhoneNumber) {
protected $clabeInterbancariaBanamexID;
public function __construct(
Logger $logger,
MessageTextFactory $messageTextFactory,
SmsNumberProvider $clientPhoneNumber
) {
$this->logger = $logger; $this->logger = $logger;
$this->messageTextFactory = $messageTextFactory; $this->messageTextFactory = $messageTextFactory;
$this->clientPhoneNumber = $clientPhoneNumber; $this->clientPhoneNumber = $clientPhoneNumber;
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$client = new Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$this->ucrmApi = new UcrmApi($client, $config['apitoken'] ?? '');
} }
/* public function createPaymentIntent(array $eventJson): void {
* Creates a PaymentIntent in Stripe for a Customer $config = PluginConfigManager::create()->loadConfig();
*/ $stripe = new StripeClient($config['tokenstripe']);
public function createPaymentIntent($event_json)
{
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
$StripeToken = $config['tokenstripe'];
$stripe = new \Stripe\StripeClient($StripeToken); //Token de clave privada para la API de Stripe
$customerId = $event_json->data->object->customer;
$amount = $event_json->data->object->net_amount;
$stripeQuery = $stripe->customers->retrieve($customerId, []);
$UCRM_clientID = $stripeQuery['metadata']['ucrm_client_id'];
$this->ucrmApi = UcrmApi::create();
$currentUserAdmin = $this->ucrmApi->get('users/admins', []);
//$this->logger->info("User Admin ID: " . json_encode($currentUserAdmin) . PHP_EOL);
$customer = $eventJson['data']['object']['customer'] ?? null;
$amount = $eventJson['data']['object']['net_amount'] ?? 0;
if (!$customer || $amount <= 0) {
$this->logger->warning("Datos inválidos para PaymentIntent: Customer=$customer, Amount=$amount");
return;
}
try { try {
$paymentIntent = $stripe->paymentIntents->create([ $stripeCustomer = $stripe->customers->retrieve($customer);
'amount' => $amount, $ucrmClientId = $stripeCustomer->metadata->ucrm_client_id ?? null;
$pi = $stripe->paymentIntents->create([
'amount' => (int)$amount,
'currency' => 'mxn', 'currency' => 'mxn',
'customer' => $customerId, 'customer' => $customer,
'payment_method_types' => ['customer_balance'], 'payment_method_types' => ['customer_balance'],
'payment_method_data' => ['type' => 'customer_balance'], 'payment_method_data' => ['type' => 'customer_balance'],
'confirm' => true, 'confirm' => true,
@ -89,262 +68,548 @@ abstract class AbstractStripeOperationsFacade
], ],
], ],
'metadata' => [ 'metadata' => [
'clientId' => $UCRM_clientID, // ID del cliente en Ubiquiti 'clientId' => $ucrmClientId,
'createdBy' => 'UCRM', 'createdBy' => 'UCRM',
'paymentType' => 'card.one_time', 'signedInAdminId' => $config['idPaymentAdminCRM'],
'signedInAdminId' => $currentUserAdmin[0]['id'], 'tipoPago' => 'Transferencia Bancaria'
], ],
]); ]);
$this->logger->info("PaymentIntent creado: " . $pi->id);
$this->logger->info("PaymentIntent creado: " . $paymentIntent->id . PHP_EOL); } catch (\Exception $e) {
$this->logger->error("Error creando PaymentIntent: " . $e->getMessage());
}
} catch (\Stripe\Exception\ApiErrorException $e) {
$this->logger->info("Error creando PaymentIntent: " . $e->getMessage() . PHP_EOL);
} }
public function registerPaymentFromWebhook(array $eventJson): void {
$config = PluginConfigManager::create()->loadConfig();
$stripe = new StripeClient($config['tokenstripe']);
$data = $eventJson['data']['object'];
$piId = $data['applied_to_payment']['payment_intent'] ?? null;
if (!$piId) return;
try {
$pi = $stripe->paymentIntents->retrieve($piId);
$clientId = $pi->metadata->clientId ?? null;
if (!$clientId) return;
$methodId = $this->findPaymentMethodId('Transferencia bancaria');
if ($methodId) {
$this->ucrmApi->post('payments', [
'clientId' => (int)$clientId,
'amount' => abs($data['net_amount']) / 100,
'currencyCode' => strtoupper($pi->currency),
'methodId' => $methodId,
'note' => "Transferencia Bancaria (Stripe Saldo) - PI: $piId",
'createdDate' => date('c'),
]);
}
} catch (\Exception $e) {
$this->logger->error("Error al registrar pago en UCRM: " . $e->getMessage());
} }
/*
* Creates the Stripe Customer
*/
public function createStripeClient(NotificationData $notificationData): void
{
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
// the "exportFormat" key must be defined in plugin's manifest file, see the link above
$IPServer = $config['ipserver'];
$UCRMAPIToken = $config['apitoken'];
$StripeToken = $config['tokenstripe'];
//$this->logger->info("Ya dentro del metodo Create Stripe Client " . PHP_EOL);
//$this->sendWhatsApp('Hola Dany');
$this->ucrmApi = UcrmApi::create();
$customAttributes = $this->ucrmApi->get('custom-attributes/', ['attributeType' => 'client']);//Obtener los atributos del sistema que estén vinculados a la entidad "cliente"
//$this->logger->info("result del custom Attributes: " . json_encode($customAttributes) . PHP_EOL);
// Verificar si se obtuvieron los atributos
if ($customAttributes && is_array($customAttributes)) {
foreach ($customAttributes as $attribute) {
// Verificar si 'name' contiene la palabra 'Stripe' sin distinguir mayúsculas y minúsculas
if (isset($attribute['name']) && stripos($attribute['name'], 'Stripe') !== false) {
$this->logger->info("ID correspondiente a 'Customer Stripe ID': " . $attribute['id'] . PHP_EOL);
$this->stripeCustomAttributeID = $attribute['id'];
} else if (isset($attribute['name']) && stripos($attribute['name'], 'Clabe') !== false) {
//$this->logger->info("ID correspondiente a 'Clabe Interbancaria Banamex': " . $attribute['id'] .PHP_EOL);
$this->clabeInterbancariaBanamexID = $attribute['id'];
} }
public function registerPaymentFromIntent(array $data): void {
$piId = $data['id'] ?? null;
if (!$piId) return;
if (($data['status'] ?? '') !== 'succeeded') {
$this->logger->warning("PaymentIntent $piId no está succeeded (status: " . ($data['status']??'unknown') . ")");
return;
} }
// Buscar clientId en metadata (prioridad: clientId > ucrm_client_id)
$clientId = $data['metadata']['clientId'] ?? $data['metadata']['ucrm_client_id'] ?? null;
// Fallback: Buscar por Stripe Customer ID si no hay metadata
if (!$clientId && !empty($data['customer'])) {
$clientId = $this->findClientIdByStripeCustomer($data['customer']);
if ($clientId) {
$this->logger->info("Cliente encontrado por Stripe ID ({$data['customer']}): $clientId");
}
}
if (!$clientId) {
$this->logger->warning("PaymentIntent $piId no tiene clientId en metadata y no se encontró por Customer ID ({$data['customer']}).");
return;
}
try {
// Intentar detectar Payment Method name basado en tipo
$type = $data['payment_method_types'][0] ?? 'card';
$methodSearchName = ($type === 'oxxo') ? 'OXXO' : 'Stripe';
// Buscar ID de metodo en UCRM
$methodId = $this->findPaymentMethodId($methodSearchName);
if (!$methodId && $methodSearchName === 'OXXO') {
$methodId = $this->findPaymentMethodId('Stripe'); // Fallback
}
if ($methodId) {
$checkAmount = ($data['amount_received'] ?? $data['amount']) / 100;
$this->ucrmApi->post('payments', [
'clientId' => (int)$clientId,
'amount' => $checkAmount,
'currencyCode' => strtoupper($data['currency'] ?? 'MXN'),
'methodId' => $methodId,
'note' => "Stripe ($methodSearchName) - PI: $piId",
'createdDate' => date('c'),
]);
$this->logger->info("Pago registrado en UCRM vía PI Succeeded: $piId, Cliente: $clientId, Monto: $checkAmount");
} else { } else {
$this->logger->info("Error al obtener los atributos personalizados." . PHP_EOL); $this->logger->warning("No se encontró método de pago para '$methodSearchName' en UCRM.");
}
} catch (\Exception $e) {
$this->logger->error("Error al registrar pago desde PaymentIntent: " . $e->getMessage());
}
} }
private function findClientIdByStripeCustomer(string $stripeCustomerId): ?int {
try {
// Nota: Esto puede ser lento si hay muchos clientes, pero es un fallback.
// Idealmente usaríamos $this->ucrmApi->get('clients', ['customAttributeKey' => 'stripeCustomerId', ...]) si existiera ese filtro.
// Como fallback, buscamos en los clientes que tenemos cacheados o hacemos un search.
// UCRM API permite filtrar por userIdent? No directamente por atributo custom en GET /clients sin plugin extentions.
// PERO podemos usar la API de 'clients' y filtrar en memoria si no son muchos, o confiar en que el usuario ya usó metadata en el futuro.
// MEJOR OPCION: Usar el endpoint de attributes si es posible, o iterar.
// Dado que no queremos matar el server, limitaremos la búsqueda o asumiremos que el FIX de metadata es el principal.
// Sin embargo, para este caso específico, vamos a intentar buscar en los clientes recientes o usar una búsqueda básica.
// UCRM API v1.0 GET /clients soporta ?customAttributeId&customAttributeValue
$attrId = $this->resolveAttributeId('stripeCustomerId');
if (!$attrId) return null;
$baseUri = 'https://' . $IPServer . '/crm/api/v1.0/'; //endpoint de la API REST del CRM $clients = $this->ucrmApi->get('clients', [
'customAttributeId' => $attrId,
$stripe = new \Stripe\StripeClient($StripeToken); //Token de clave privada en modo prueba para la API de Stripe 'customAttributeValue' => $stripeCustomerId
//$stripe = new \Stripe\StripeClient('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'); //Token de clave privada en modo prodcucción para la API de Stripe ]);
// Verificar si la solicitud fue exitosa (código de estado 200)
//https://172.16.5.120/crm/api/v1.0/payments?limit=1&clientId=1992&order=createdDate&direction=DESC
$notification_client_data = $notificationData->clientData; //array con los datos del cliente
$notification_client_data_export = json_encode($notification_client_data);
$this->logger->info("Valor de notification client data export: " . $notification_client_data_export . PHP_EOL);
$this->createCustomerStripe($notificationData, $stripe, $baseUri, $UCRMAPIToken);
if (!empty($clients) && isset($clients[0]['id'])) {
return (int)$clients[0]['id'];
}
} catch (\Exception $e) {
$this->logger->error("Error buscando cliente por Stripe ID: " . $e->getMessage());
}
return null;
} }
private function findPaymentMethodId(string $name): ?int {
try {
$methods = $this->ucrmApi->get('payment-methods');
foreach ($methods as $m) {
if (stripos($m['name'], $name) !== false) {
return $m['id'];
}
}
} catch(\Exception $e) {}
return null;
}
public function createStripeClient(NotificationData $notificationData, string $tagName, bool $generateSpei = true): void {
$clientId = $notificationData->clientId;
if (!$clientId) return;
$config = PluginConfigManager::create()->loadConfig();
$stripe = new StripeClient($config['tokenstripe']);
try {
$clientCRM = $this->ucrmApi->get("clients/$clientId", []);
// /** // Si intenta crear CLABE pero NO tiene stripeCustomerId, cancelamos
// * implement in subclass with the specific messaging provider if ($tagName === 'CREAR CLABE STRIPE') {
// * @see TwilioNotifierFacade::sendWhatsApp() $hasStripeId = false;
// */ foreach ($clientCRM['attributes'] as $attr) {
abstract protected function sendWhatsApp( if ($attr['key'] === 'stripeCustomerId' && !empty($attr['value'])) {
string $message $hasStripeId = true;
): void;
function createCustomerStripe($notificationData, $stripe, $baseUri, $token)
{
$this->logger->info("Creando el Customer Stripe" . PHP_EOL);
$ucrm_client_id = $notificationData->clientData['id'];
$clientCRMContacts = $notificationData->clientData['contacts'];
$firstName = $notificationData->clientData['firstName']; //obtenemos nombre del cliente y lo almacenamos en una variable
$lastName = $notificationData->clientData['lastName']; //obtenemos apellidos del cliente y lo almacenamos en una variable
$this->logger->info('El cliente a procesar es : ' . $firstName . ' ' . $lastName . PHP_EOL); //impresión de control para ver el nombre del cliente a procesar en consola
$cadenaNotificationData = json_encode($notificationData);
$this->logger->info("Datos notificationData: " . $cadenaNotificationData . PHP_EOL);
foreach ($clientCRMContacts as $contact) { //aquí revisamos los datos de contacto del cliente, como pueden ser uno o varios se hace uso del foreach
$this->logger->info('Ya dentro del FOREACH!!! ' . PHP_EOL);
$phone = ''; //variable para almacenar el número de teléfono del cliente que se mandará a su cuenta de Stripe
foreach ($contact['types'] as $type) { //revisamos el tipo de contacto
$this->logger->info('REVISANDO EL PRIMER CONTACTO!!! ' . PHP_EOL);
if ($type['name'] === "WhatsApp") { //si es de tipo whatsapp..
//print_r("Encontré un tipo de Contacto para WhatsAapp" . PHP_EOL);
$phone = $contact['phone']; //se asigna como número de teléfono
break; break;
}
}
if (!$hasStripeId) {
$this->logger->warning("Cliente $clientId no tiene stripeCustomerId. No se puede crear CLABE.");
return;
}
}
$customer = $this->createCustomerStripe($stripe, $clientCRM, $generateSpei);
if ($customer) {
$this->logger->info("Cliente Stripe procesado para ID: $clientId (Tag: $tagName, SPEI: " . ($generateSpei ? 'SI' : 'NO') . ")");
}
} catch (\Exception $e) {
$this->logger->error("Error en createStripeClient para cliente $clientId: " . $e->getMessage());
} finally {
// Garantizamos quitar la etiqueta siempre para evitar re-ejecuciones accidentales
$this->removeTagFromClient($clientId, $tagName);
}
}
protected function createCustomerStripe(StripeClient $stripe, array $clientCRM, bool $generateSpei): ?\Stripe\Customer {
$clientId = $clientCRM['id'];
// Extraer email de contactos (prioridad) o username
$email = $clientCRM['username'] ?? null;
foreach ($clientCRM['contacts'] ?? [] as $contact) {
if ($contact['isBilling'] || $contact['isContact']) {
$email = $contact['email'] ?? $email;
if ($email) break;
}
}
$name = trim(($clientCRM['firstName'] ?? '') . ' ' . ($clientCRM['lastName'] ?? ''));
if (empty($name) && !empty($clientCRM['companyName'])) {
$name = $clientCRM['companyName'];
}
// Obtener IDs de atributos dinámicamente desde el sistema
$cidAttrId = $this->resolveAttributeId('stripeCustomerId');
$clabeAttrId = $this->resolveAttributeId('clabeInterbancaria');
$this->logger->debug("IDs de atributos resueltos: Stripe=$cidAttrId, CLABE=$clabeAttrId");
// Buscar cliente existente por metadata
$customers = $stripe->customers->search([
'query' => "metadata['ucrm_client_id']:'$clientId'",
]);
if ($customers->count() > 0) {
$customer = $customers->data[0];
// Sincronizar datos básicos
$stripe->customers->update($customer->id, [
'email' => $email,
'name' => $name,
]);
$this->logger->info("Datos básicos de Cliente Stripe sincronizados para ID: $clientId");
} else { } else {
$phone = $contact['phone']; //Si no encuentra un tipo de contacto como Whatsapp entonces el último número de celular obtenido es el que se envía $params = [
} 'email' => $email,
} 'name' => $name,
$email = $this->validarEmail($contact['email']); //validamos el email del cliente mediante la función validarEmail para que en caso de que no esté bien formado lo ponga en blanco 'metadata' => ['ucrm_client_id' => $clientId]
];
$customer = $stripe->customers->create($params);
$this->logger->info("Nuevo Cliente Stripe creado para ID: $clientId. CID: {$customer->id}");
// Guardar CID en UCRM
$this->patchClientCustomAttribute($clientId, (int)$cidAttrId, $customer->id);
} }
$this->logger->info('ahora se procede a validar el teléfono!!! ' . PHP_EOL); // Si se requiere SPEI, generamos las instrucciones de fondeo para obtener la CLABE
if ($generateSpei) {
$phone = $this->validarNumeroTelefono($phone); //validamos y procesamos el número de celular del cliente para que se vaya a 10 dígitos ya que Stripe por si mismo les agrega el +52 try {
//******************************************** */ $this->logger->info("Solicitando instrucciones de fondeo (CLABE) para cliente: {$customer->id}");
$fundingInstructions = $stripe->customers->createFundingInstructions(
$this->logger->info('AHORA SE MANDA A CREAR EL CLIENTE A STRIPE!!! ' . PHP_EOL); $customer->id,
$result = $stripe->customers->create([
"description" => "Cliente SIIP CRM con client_id: " . $ucrm_client_id,
"name" => $firstName . ' ' . $lastName,
"phone" => $phone,
"email" => $email,
'preferred_locales' => ['es-419']
]); //aquí se contruye la petición de creación de un customer en Stripe y se consume la API
$this->logger->info(json_encode($result) . PHP_EOL); //imprimir respuesta de creación del cliente
$stripe_customer_id = $result['id']; //obtenemos el customer id de Stripe recibido por medio del consumo del API y lo asignamos a una variable $stripe_customer_id
sleep(2);
$result2 = $stripe->customers->update(
$stripe_customer_id,
['metadata' => ['ucrm_client_id' => '' . $ucrm_client_id]]
);//aquí se contruye la petición de actualización de un customer en Stripe para agregarle los metadatos y se consume la API, requiere el ID del Customer, por eso antes lo almacenamos en la variable $stripe_customer_id
$this->logger->info(json_encode($result2) . PHP_EOL); // imprimir respuesta de actualización del metadata del cliente
sleep(2);
$result3 = $stripe->customers->createFundingInstructions(
$stripe_customer_id,
[ [
'currency' => 'mxn', 'currency' => 'mxn',
'funding_type' => 'bank_transfer', 'funding_type' => 'bank_transfer',
'bank_transfer' => ['type' => 'mx_bank_transfer'], 'bank_transfer' => ['type' => 'mx_bank_transfer'],
] ]
); //aquí se contruye la petición de creación de Instrucciones de Fondeo de un customer en Stripe (O su metodo de pago como cuenta bancaria para transferencias) y se consume la API
$this->logger->info(json_encode($result3) . PHP_EOL); //imprimir respuesta de asignación de cuenta bancaria de transferencia
// Acceder al valor de "clabe" para BANORTE
$clabeInterbancaria = $result3['bank_transfer']['financial_addresses'][0]['spei']['clabe']; //Asignamos la clabe obtenida con la API de Stripe con la solicitud anterior a la variable $clabe
$stripeID = $this->stripeCustomAttributeID;
$clabeInterbancariaID = $this->clabeInterbancariaBanamexID;
$customer = $stripe->customers->update(
$stripe_customer_id,
[
'metadata' => [
'clabe' => $clabeInterbancaria, // Nueva clabe
],
]
); );
$this->logger->info("CLABE guardada en metadata: " . $customer->metadata->clabe . PHP_EOL); $clabe = $fundingInstructions['bank_transfer']['financial_addresses'][0]['spei']['clabe'] ?? null;
if ($clabe) {
$json_data_patch = '{ $this->logger->info("CLABE obtenida via Funding Instructions para cliente $clientId: $clabe");
"attributes": [ $this->patchClientCustomAttribute($clientId, (int)$clabeAttrId, $clabe);
{ } else {
"value": "' . $stripe_customer_id . '", $this->logger->warning("Stripe no devolvió una CLABE en las instrucciones de fondeo para el cliente $clientId.");
"customAttributeId":' . $stripeID . ' }
}, } catch (\Exception $e) {
{ $this->logger->error("Error al crear instrucciones de fondeo para cliente $clientId: " . $e->getMessage());
"value": "' . $clabeInterbancaria . '", }
"customAttributeId":' . $clabeInterbancariaID . '
} }
]
}'; //JSON para hacer patch de los custom fields del cliente en el UISCP CRM, Campo para el Stripe Customer ID y la Clabe interbancaria return $customer;
// $json_data_patch = '{ }
// "attributes": [
// {
// "value": "' . $stripe_customer_id . '",
// "customAttributeId": 29
// },
// {
// "value": "' . $clabe . '",
// "customAttributeId": 30
// }
// ]
// }'; //JSON para hacer patch de los custom fields del cliente en el UISCP CRM, Campo para el Stripe Customer ID y la Clabe interbancaria protected function getVaultCredentialsByClientId($clientId): string {
$config = PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? '';
$clientguzz = new Client(); //instancia de cliente GuzzleHttp para consumir API UISP CRM
try { try {
$responseCRM = $clientguzz->patch($baseUri . 'clients/' . $ucrm_client_id, [ // OPT: Lazy Check - Si ya tiene pass válido en CRM, no hace falta procesar nada
'json' => json_decode($json_data_patch, true), $clientData = $this->ucrmApi->get("clients/$clientId");
'headers' => [ $passCRM = '';
'X-Auth-App-Key' => $token, // Cambia el nombre de la cabecera de autorización if (isset($clientData['attributes'])) {
'Accept' => 'application/json', // Indica que esperamos una respuesta en formato JSON foreach ($clientData['attributes'] as $attr) {
if ($attr['key'] === 'passwordAntenaCliente') {
$passCRM = $attr['value'] ?? '';
break;
}
}
}
// Si el campo no está vacío y no tiene advertencias, usamos el actual para ahorrar recursos
if (!empty($passCRM) && strpos($passCRM, '⚠️') === false) {
return $passCRM;
}
// 1. Obtener los servicios del cliente
$svcs = $this->ucrmApi->get('clients/services', ['clientId' => $clientId]);
if (empty($svcs)) {
$msg = '⚠️ Cliente sin servicios/antenas';
$this->syncPasswordWithCrm((int)$clientId, $msg);
return $msg;
}
$unms = new Client(['base_uri' => "https://{$ipServer}/nms/api/v2.1/", 'verify' => false, 'headers' => ['X-Auth-Token' => $config['apitoken']]]);
$allServicePasswords = [];
$isTestEnv = ($ipServer === '172.16.5.134' || $ipServer === 'pruebas.internet.mx' || $ipServer === 'venus.siip.mx');
$numServices = count($svcs);
foreach ($svcs as $index => $svc) {
$label = ($numServices > 1) ? "Servicio " . ($index + 1) . ":" : "";
$siteId = $svc['unmsClientSiteId'] ?? null;
$passwordValue = "";
if (!$siteId) {
$passwordValue = "⚠️ Sin sitio";
} else {
if ($isTestEnv) {
// Lógica de bypass: intentar recuperar de la cadena existente
$foundInCRM = false;
if (!empty($passCRM)) {
if ($numServices > 1) {
if (preg_match('/Servicio ' . ($index + 1) . ':\s*([^⚠️\s]+)/', $passCRM, $matches)) {
$passwordValue = $matches[1];
$foundInCRM = true;
}
} else {
// Caso de un solo servicio: si no tiene advertencias ni etiquetas, asumimos que es el pass
if (strpos($passCRM, '⚠️') === false && strpos($passCRM, 'Servicio') === false) {
$passwordValue = trim($passCRM);
$foundInCRM = true;
}
}
}
if (!$foundInCRM) {
$passwordValue = $this->generateStrongPassword(16);
}
} else {
// Lógica de producción
try {
$respDev = $unms->get("devices?siteId=$siteId", [
'headers' => ['X-Auth-Token' => $config['unmsApiToken']]
]);
$devs = json_decode($respDev->getBody()->getContents(), true);
if (empty($devs)) {
$passwordValue = "⚠️ Sin antena";
} else {
$passVault = null;
$firstDeviceId = null;
foreach ($devs as $dev) {
$deviceId = $dev['identification']['id'] ?? null;
if (!$deviceId) continue;
if (!$firstDeviceId) $firstDeviceId = $deviceId;
try {
$respVault = $unms->get("vault/$deviceId/credentials", [
'headers' => ['X-Auth-Token' => $config['unmsApiToken']]
]);
$vault = json_decode($respVault->getBody()->getContents(), true);
if (isset($vault['credentials'][0]['password'])) {
$passVault = $vault['credentials'][0]['password'];
break;
}
} catch (\Exception $e) { continue; }
}
if ($passVault) {
$passwordValue = $passVault;
} else if ($firstDeviceId) {
// Regenerar
$newPass = $this->generateStrongPassword(16);
try {
$unms->post("vault/$firstDeviceId/credentials/regenerate", [
'headers' => ['X-Auth-Token' => $config['unmsApiToken']],
'json' => [['username' => 'ubnt', 'password' => $newPass, 'readOnly' => true]]
]);
$passwordValue = $newPass;
} catch (\Exception $e) { $passwordValue = $newPass; }
} else {
$passwordValue = "⚠️ Sin antena";
}
}
} catch (\Exception $e) {
$passwordValue = "⚠️ Error API";
}
}
}
$allServicePasswords[] = trim("$label $passwordValue");
}
$finalValue = implode(' ', $allServicePasswords);
// Evitar sincronización redundante si el valor es idéntico al actual (anti-bucle)
if ($finalValue === $passCRM) {
return $finalValue;
}
$this->syncPasswordWithCrm((int)$clientId, $finalValue);
return $finalValue;
} catch (\Exception $e) {
$this->logger->error("Excepción en getVaultCredentialsByClientId (Cliente: $clientId): " . $e->getMessage());
return 'Error: ' . $e->getMessage();
}
}
private function syncPasswordWithCrm(int $clientId, string $passVault): void {
try {
$clientData = $this->ucrmApi->get("clients/$clientId");
$passCRM = '';
$attributeId = 17; // ID real para 'passwordAntenaCliente'
if (isset($clientData['attributes'])) {
foreach ($clientData['attributes'] as $attr) {
if ($attr['key'] === 'passwordAntenaCliente') {
$passCRM = $attr['value'] ?? '';
$attributeId = $attr['customAttributeId'];
break;
}
}
}
if (empty($passCRM) || $passCRM !== $passVault) {
$this->logger->info("Sincronizando contraseña en CRM para cliente $clientId. [" . ($passCRM ?: 'VACIO') . "] -> [$passVault]");
$this->patchClientCustomAttribute($clientId, (int)$attributeId, $passVault);
}
} catch (\Exception $e) {
$this->logger->warning("Fallo al sincronizar contraseña con CRM para cliente $clientId: " . $e->getMessage());
}
}
protected function generateStrongPassword(int $length = 16): string {
$lower = 'abcdefghijkmnopqrstuvwxyz'; // Eliminamos 'l'
$upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; // Eliminamos 'I', 'O'
$digits = '23456789'; // Eliminamos '1', '0'
$symbols = '@#'; // Solo símbolos amigables para impresoras térmicas
$all = $lower . $upper . $digits . $symbols;
$pwChars = [];
// Asegurar que tenga al menos uno de cada tipo si es posible
$pwChars[] = $lower[random_int(0, strlen($lower) - 1)];
$pwChars[] = $upper[random_int(0, strlen($upper) - 1)];
$pwChars[] = $digits[random_int(0, strlen($digits) - 1)];
$pwChars[] = $symbols[random_int(0, strlen($symbols) - 1)];
for ($i = count($pwChars); $i < $length; $i++) {
$pwChars[] = $all[random_int(0, strlen($all) - 1)];
}
// Mezclar Fisher-Yates
$n = count($pwChars);
for ($i = $n - 1; $i > 0; $i--) {
$j = random_int(0, $i);
$tmp = $pwChars[$i];
$pwChars[$i] = $pwChars[$j];
$pwChars[$j] = $tmp;
}
return implode('', $pwChars);
}
protected function patchClientCustomAttribute(int $clientId, int $attributeId, string $value): bool {
if ($attributeId <= 0) {
$this->logger->error("Intento de patchAttribute con ID inválido ($attributeId) para cliente $clientId");
return false;
}
try {
$this->logger->debug("Intentando PATCH en clients/$clientId para atributo ID: $attributeId con valor: $value");
$this->ucrmApi->patch("clients/$clientId", [
'attributes' => [
[
'customAttributeId' => $attributeId,
'value' => $value,
], ],
'verify' => false, ],
]); //aquí se contruye la petición para hacer patch hacia el cliente en sus custom fields con la API del UISP UCRM ]);
return true;
} catch (\Exception $e) {
} catch (GuzzleException $error) { $this->logger->error("Error patching custom attribute for client $clientId: " . $e->getMessage());
$this->logger->info("Error al hacer el patch al CRM: " . $error->getMessage() . PHP_EOL); return false;
//exit();
} }
$this->logger->info(json_encode($responseCRM) . PHP_EOL); //imprimir respuesta del patch de CRM con la clabe y Customer ID Stripe
} }
function validarNumeroTelefono($telefono) private function resolveAttributeId(string $key): int {
{ if ($this->systemAttributesCache === null) {
// Eliminar espacios y guiones try {
$telefono = preg_replace('/\s+|-/', '', $telefono); $this->systemAttributesCache = $this->ucrmApi->get('custom-attributes', ['attributeType' => 'client']);
} catch (\Exception $e) {
$this->logger->error("No se pudieron cargar los atributos del sistema: " . $e->getMessage());
return 0;
}
}
// Eliminar caracteres no numéricos foreach ($this->systemAttributesCache as $attr) {
$telefono = preg_replace('/\D/', '', $telefono); if ($attr['key'] === $key) {
return (int)$attr['id'];
}
}
// Verificar si quedan exactamente 10 dígitos return 0;
if (strlen($telefono) === 10) { }
// Retornar el número de teléfono correctamente formateado
return $telefono; protected function comparePasswords(?string $crm, ?string $vault): string {
} elseif (strlen($telefono) > 10) { if ($crm && strpos($crm, 'Error') !== 0) return $crm;
// Si el número tiene más de 10 dígitos, quitar los primeros if ($vault && strpos($vault, 'Error') !== 0) return $vault;
return substr($telefono, -10); return '⚠️ Probar pass conocida.';
}
public function syncStripeCustomerData(int $clientId, string $name, ?string $email): void {
$config = PluginConfigManager::create()->loadConfig();
$stripe = new StripeClient($config['tokenstripe']);
try {
$customers = $stripe->customers->search([
'query' => "metadata['ucrm_client_id']:'$clientId'",
]);
if ($customers->count() > 0) {
$customer = $customers->data[0];
$stripe->customers->update($customer->id, [
'name' => $name,
'email' => $email,
]);
$this->logger->info("Sincronización automática a Stripe exitosa para cliente $clientId.");
}
} catch (\Exception $e) {
$this->logger->error("Error sincronizando cliente $clientId a Stripe: " . $e->getMessage());
}
}
protected function removeTagFromClient(int $clientId, string $tagName): void {
try {
$client = $this->ucrmApi->get("clients/$clientId");
$targetTagId = null;
foreach ($client['tags'] as $tag) {
if ($tag['name'] === $tagName) {
$targetTagId = $tag['id'];
break;
}
}
if ($targetTagId) {
$this->ucrmApi->patch("clients/$clientId/remove-tag/$targetTagId", []);
$this->logger->info("Etiqueta '$tagName' (ID: $targetTagId) removida del cliente $clientId via endpoint especializado.");
} else { } else {
// Si el número tiene menos de 10 dígitos, retornar cadena vacía $this->logger->debug("Etiqueta '$tagName' no encontrada en el cliente $clientId, nada que remover.");
return ''; }
} catch (\Exception $e) {
$this->logger->error("Error al remover etiqueta '$tagName' del cliente $clientId: " . $e->getMessage());
} }
} }
function validarEmail($email) protected function validarNumeroTelefono($n): string {
{ if (!$n) return '';
$this->logger->info('SE VALIDA EL EMAIL!!! ' . PHP_EOL); $n = preg_replace('/\D/', '', (string)$n);
// Utilizar la función filter_var con el filtro FILTER_VALIDATE_EMAIL para validar el email return (strlen($n) === 10) ? '52' . $n : $n;
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Si el email es válido, devolver el email
return $email;
} else {
// Si el email no es válido, devolver una cadena vacía
return '';
}
} }
abstract protected function sendWhatsApp(NotificationData $notificationData, string $clientPhoneNumber): void;
} }

File diff suppressed because it is too large Load Diff

View File

@ -11,6 +11,9 @@ use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager; use SmsNotifier\Service\OptionsManager;
use SmsNotifier\Service\SmsNumberProvider; use SmsNotifier\Service\SmsNumberProvider;
use Twilio\Rest\Client; use Twilio\Rest\Client;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\GuzzleException;
class PluginNotifierFacade extends AbstractStripeOperationsFacade class PluginNotifierFacade extends AbstractStripeOperationsFacade
@ -36,16 +39,22 @@ class PluginNotifierFacade extends AbstractStripeOperationsFacade
$this->pluginData = $optionsManager->load(); $this->pluginData = $optionsManager->load();
} }
public function updatePasswordAntenaIfNeeded(int $clientId, array $jsonData): void
{
$this->logger->info("Iniciando verificación/sincronización de contraseña para el cliente ID: $clientId");
// El método base getVaultCredentialsByClientId ya incluye la lógica para:
// 1. Obtener la contraseña desde el Vault de UISP (iterando sobre dispositivos).
// 2. Compararla con el atributo 'passwordAntenaCliente' del CRM.
// 3. Actualizar el CRM si está vacío o si es diferente.
$this->getVaultCredentialsByClientId($clientId);
}
/* /*
* Send WhatsApp through the CallBell API * Implementation of abstract method from AbstractStripeOperationsFacade
*/ */
protected function sendWhatsApp( protected function sendWhatsApp(NotificationData $notificationData, string $clientPhoneNumber): void
string $message, {
): void { $this->logger->info("PluginNotifierFacade: Enviando WhatsApp (Mock): " . $clientPhoneNumber);
$this->logger->debug('Enviando mensaje desde twilio notifier facade: '.$message);
} }
/* /*
@ -53,6 +62,6 @@ class PluginNotifierFacade extends AbstractStripeOperationsFacade
*/ */
private function getSenderNumber(): string private function getSenderNumber(): string
{ {
return $this->pluginData->twilioSmsNumber; return $this->pluginData->twilioSmsNumber ?? '';
} }
} }

View File

@ -29,9 +29,10 @@ class PluginOxxoNotifierFacade extends AbstractOxxoOperationsFacade
Logger $logger, Logger $logger,
MessageTextFactory $messageTextFactory, MessageTextFactory $messageTextFactory,
SmsNumberProvider $smsNumberProvider, SmsNumberProvider $smsNumberProvider,
OptionsManager $optionsManager OptionsManager $optionsManager,
\SmsNotifier\Service\MinioStorageService $minioStorage
) { ) {
parent::__construct($logger, $messageTextFactory, $smsNumberProvider); parent::__construct($logger, $messageTextFactory, $smsNumberProvider, $minioStorage);
// load config data // load config data
$this->pluginData = $optionsManager->load(); $this->pluginData = $optionsManager->load();
} }

View File

@ -11,18 +11,10 @@ use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager; use SmsNotifier\Service\OptionsManager;
use SmsNotifier\Service\SmsNumberProvider; use SmsNotifier\Service\SmsNumberProvider;
use Twilio\Rest\Client; use Twilio\Rest\Client;
use SmsNotifier\Facade\ClientCallBellAPI;
class TwilioNotifierFacade extends AbstractMessageNotifierFacade class TwilioNotifierFacade extends AbstractMessageNotifierFacade
{ {
/**
* @var Client
*/
private $twilioClient; private $twilioClient;
/**
* @var PluginData
*/
private $pluginData; private $pluginData;
public function __construct( public function __construct(
@ -32,62 +24,41 @@ class TwilioNotifierFacade extends AbstractMessageNotifierFacade
OptionsManager $optionsManager OptionsManager $optionsManager
) { ) {
parent::__construct($logger, $messageTextFactory, $smsNumberProvider); parent::__construct($logger, $messageTextFactory, $smsNumberProvider);
// load config data
$this->pluginData = $optionsManager->load(); $this->pluginData = $optionsManager->load();
} }
/*
* Get Twilio SMS API object (unless it's already initialized)
*/
public function getTwilioClient(): Client public function getTwilioClient(): Client
{ {
if (!$this->twilioClient) { if (!$this->twilioClient) {
$this->twilioClient = new Client( $this->twilioClient = new Client(
$this->pluginData->token_callbell $this->pluginData->twilioAccountSid ?? '',
$this->pluginData->twilioAuthToken ?? ''
); );
} }
return $this->twilioClient; return $this->twilioClient;
} }
/*
* Send WhatsApp through the CallBell API
*/
protected function sendWhatsApp(
string $message,
): void {
$this->logger->debug('Enviando mensaje desde twilio notifier facade: '.$message);
protected function sendWhatsApp(NotificationData $notificationData, string $clientSmsNumber): void
{
$this->logger->info("TwilioNotifierFacade: Enviando WhatsApp a $clientSmsNumber (Mock)");
} }
/*
* Send message through the Twilio client
*/
protected function sendMessage( protected function sendMessage(
NotificationData $notificationData, NotificationData $notificationData,
string $clientSmsNumber, string $clientSmsNumber,
string $messageBody string $messageBody
): void { ): void {
$this->logger->debug(sprintf('Sending: %s', $messageBody)); try {
$message = $this->getTwilioClient()->messages->create(
$messageInstance = $this->getTwilioClient()->messages->create(
$clientSmsNumber, $clientSmsNumber,
[ [
'from' => $this->getSenderNumber(), 'from' => $this->pluginData->twilioSmsNumber ?? '',
'body' => $messageBody, 'body' => $messageBody,
] ]
); );
$this->logger->info(sprintf('Twilio status: %s, ID: %s', $message->status, $message->sid));
$this->logger->debug((string) $messageInstance); } catch (\Exception $e) {
$this->logger->info(sprintf('Twilio status: %s, message id: %s', $messageInstance->status, $messageInstance->sid)); $this->logger->error("Error en Twilio: " . $e->getMessage());
if ($messageInstance->errorCode) {
$this->logger->warning(sprintf('Twilio error: %s %s', $messageInstance->errorCode, $messageInstance->errorMessage));
} }
} }
/*
* Phone number of sender - required by Twilio. In this plugin, we only load it from config.
*/
private function getSenderNumber(): string
{
return $this->pluginData->twilioSmsNumber;
}
} }

View File

@ -37,8 +37,10 @@ class NotificationDataFactory
$notificationData->eventName = $jsonData['eventName']; $notificationData->eventName = $jsonData['eventName'];
$notificationData->message = $jsonData['extraData']['message'] ?? null; $notificationData->message = $jsonData['extraData']['message'] ?? null;
// Check if the given webhook exists. // Check if the given webhook exists. Skip for manual triggers.
if ($notificationData->uuid !== 'manual-trigger') {
$this->ucrmApi->query('webhook-events/' . $notificationData->uuid); $this->ucrmApi->query('webhook-events/' . $notificationData->uuid);
}
$this->resolveUcrmData($notificationData); $this->resolveUcrmData($notificationData);

View File

@ -1,19 +1,19 @@
<?php <?php
declare(strict_types=1); declare (strict_types = 1);
namespace SmsNotifier; namespace SmsNotifier;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use SmsNotifier\Facade\TwilioNotifierFacade;
use SmsNotifier\Facade\PluginNotifierFacade; use SmsNotifier\Facade\PluginNotifierFacade;
use SmsNotifier\Facade\PluginOxxoNotifierFacade; use SmsNotifier\Facade\PluginOxxoNotifierFacade;
use SmsNotifier\Facade\TwilioNotifierFacade;
use SmsNotifier\Factory\NotificationDataFactory; use SmsNotifier\Factory\NotificationDataFactory;
use SmsNotifier\Service\Logger; use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager; use SmsNotifier\Service\OptionsManager;
use SmsNotifier\Service\PluginDataValidator; use SmsNotifier\Service\PluginDataValidator;
use Twilio\Exceptions\TwilioException; use Twilio\Exceptions\TwilioException;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
class Plugin class Plugin
{ {
@ -50,6 +50,11 @@ class Plugin
*/ */
private $notificationDataFactory; private $notificationDataFactory;
/**
* @var UcrmApi
*/
protected $ucrmApi;
public function __construct( public function __construct(
Logger $logger, Logger $logger,
OptionsManager $optionsManager, OptionsManager $optionsManager,
@ -66,24 +71,26 @@ class Plugin
$this->pluginNotifierFacade = $pluginNotifierFacade; $this->pluginNotifierFacade = $pluginNotifierFacade;
$this->pluginOxxoNotifierFacade = $pluginOxxoNotifierFacade; $this->pluginOxxoNotifierFacade = $pluginOxxoNotifierFacade;
$this->notificationDataFactory = $notificationDataFactory; $this->notificationDataFactory = $notificationDataFactory;
$config = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create()->loadConfig();
$ipServer = $config['ipserver'] ?? 'localhost';
$apiUrl = "https://$ipServer/crm/api/v1.0/";
$client = new \GuzzleHttp\Client([
'base_uri' => $apiUrl,
'verify' => false,
]);
$this->ucrmApi = new UcrmApi($client, $config['apitoken'] ?? '');
} }
public function run(): void public function run(): void
{ {
// $hola = PHP_SAPI; if (PHP_SAPI === 'fpm-fcgi' || PHP_SAPI === 'cgi-fcgi' || PHP_SAPI === 'apache2handler') {
// $this->logger->info('valor de PHP_SAPI: ' . $hola);
if (PHP_SAPI === 'fpm-fcgi') {
$this->logger->debug('Whatsapp over HTTP started');
$this->processHttpRequest(); $this->processHttpRequest();
$this->logger->debug('HTTP request processing ended.');
} elseif (PHP_SAPI === 'cli') { } elseif (PHP_SAPI === 'cli') {
$this->logger->debug('Whatsapp over CLI started');
$this->processCli(); $this->processCli();
$this->logger->debug('CLI process ended.');
} else { } else {
throw new \UnexpectedValueException('Unknown PHP_SAPI type: ' . PHP_SAPI); $this->logger->error('SAPI desconocido: ' . PHP_SAPI . '. Intentando procesar como HTTP.');
$this->processHttpRequest();
} }
} }
private function processCli(): void private function processCli(): void
@ -97,97 +104,189 @@ class Plugin
private function processHttpRequest(): void private function processHttpRequest(): void
{ {
$pluginData = $this->optionsManager->load(); $pluginData = $this->optionsManager->load();
if ($pluginData->logging_level) { if ($pluginData->logging_level || $pluginData->debugMode) {
$this->logger->setLogLevelThreshold(LogLevel::DEBUG); $this->logger->setLogLevelThreshold(LogLevel::DEBUG);
} }
$userInput = file_get_contents('php://input'); $userInput = file_get_contents('php://input');
$this->logger->debug('Payload recibido: ' . $userInput . PHP_EOL);
if (! $userInput) {
$this->logger->warning('No se recibió input en la petición HTTP.');
if (!$userInput) {
$this->logger->warning('no input');
return; return;
} }
$event_json = json_decode($userInput);
$webhook_string = json_encode($event_json); $jsonData = @json_decode((string)$userInput, true, 50);
$this->logger->debug("El valor del evento recibio en json: " . $webhook_string . PHP_EOL);
// Maneja el evento del webhook if (! isset($jsonData['uuid'])) {
if ($event_json) { $this->logger->info('No UUID found in the webhook data');
switch ($event_json->type) { //$this->logger->error('JSON error: ' . json_last_error_msg());
//return;
// Maneja el evento del webhook externo
if ($jsonData) {
switch ($jsonData['type']) {
case 'customer_cash_balance_transaction.created': case 'customer_cash_balance_transaction.created':
$this->logger->info('Evento de transfencia al cliente encontrado'); if ($jsonData['data']['object']['type'] === 'funded') {
$this->logger->info('Valor del EventJSON: ' . json_encode($event_json) . PHP_EOL); $this->logger->info('Evento de transferencia de un cliente recibido: ' . json_encode($jsonData) . PHP_EOL);
$this->pluginNotifierFacade->createPaymentIntent($event_json); $this->pluginNotifierFacade->createPaymentIntent($jsonData);
}
if ($jsonData['data']['object']['type'] === 'applied_to_payment') {
$this->logger->info('Se aplicó el saldo en Stripe de un pago: ' . json_encode($jsonData) . PHP_EOL);
$this->pluginNotifierFacade->registerPaymentFromWebhook($jsonData);
}elseif ($jsonData['data']['object']['type'] === 'unapplied_from_payment'){
//ejemplo de json para transferencia de dinero cancelada: {"id":"evt_1RlEGgEFY1WEUtgR6Bp2DzDP","object":"event","api_version":"2023-10-16","created":1752606717,"data":{"object":{"id":"ccsbtxn_1RlEGfEFY1WEUtgRv8jAUGmE","object":"customer_cash_balance_transaction","created":1752606717,"currency":"mxn","customer":"cus_PetN1dhr4rx0kX","ending_balance":18000,"livemode":false,"net_amount":18000,"type":"unapplied_from_payment","unapplied_from_payment":{"payment_intent":"pi_3RlDPdEFY1WEUtgR1JBgNhTQ"}}},"livemode":false,"pending_webhooks":2,"request":{"id":"req_954mskVBfAI0jn","idempotency_key":"749518f6-baa0-4ae9-99e4-8029a35719aa"},"type":"customer_cash_balance_transaction.created"}
$paymentIntentId = $jsonData['data']['object']['unapplied_from_payment']['payment_intent'];
//Se canceló una transferencia de dinero, imprimir que se canceló y además el monto neto
$this->logger->warning('Evento de transferencia cancelada para el pago: ' . $paymentIntentId . PHP_EOL);
$this->logger->warning('Monto neto de la transferencia cancelada: ' . $jsonData['data']['object']['net_amount'] . PHP_EOL);
}
break;
case 'payout.failed':
$this->logger->info('Evento de transferencia fallida encontrado: ' . json_encode($jsonData) . PHP_EOL);
//imprimir detalles del fallo
$this->logger->info('Detalles del fallo: ' . json_encode($jsonData));
break;
case 'payment_intent.partially_funded':
$this->logger->info('Evento de pago parcialmente financiado encontrado: ' . json_encode($jsonData) . PHP_EOL);
//imprimir detalles del evento o pago
$this->logger->info('Detalles del evento: ' . json_encode($jsonData));
break; break;
case 'inbound_payment.payment_attempt': case 'inbound_payment.payment_attempt':
$this->logger->info('Evento de Pagode OXXO recibido'); //$this->logger->info('Evento de Pago de OXXO recibido: ' . json_encode($jsonData) . PHP_EOL);
$this->logger->info('Valor del EventJSON: ' . json_encode($event_json) . PHP_EOL);
break; break;
case 'energy.alert': case 'cash_balance.funds_available':
$this->logger->info('Evento de Energía recibido: ' . $event_json->message . PHP_EOL); $this->logger->info('Evento de Pago de fondos disponibles recibido: ' . json_encode($jsonData) . PHP_EOL);
break;
case 'payment_intent.succeeded':
$this->logger->info('Evento de pago exitoso (Stripe PI) recibido.');
if (isset($jsonData['data']['object'])) {
$this->pluginNotifierFacade->registerPaymentFromIntent($jsonData['data']['object']);
}
break;
case 'oxxo.retrieve':
$this->logger->info('Evento de recuperación de orden OXXO recibido');
$orderId = $jsonData['order_id'] ?? null;
if ($orderId) {
$status = $this->pluginOxxoNotifierFacade->getOxxoOrderStatus($orderId);
$this->logger->debug("Estado recuperado para Orden #$orderId: " . json_encode($status));
header('Content-Type: application/json');
echo json_encode($status);
} else {
$this->logger->warning('Solicitud de oxxo.retrieve sin order_id');
echo json_encode(['error' => 'missing_order_id']);
}
return; // Terminar ejecución aquí
break; break;
case 'oxxo.request': case 'oxxo.request':
$this->logger->info('Evento de referencia de oxxo recibido: ' . PHP_EOL); $this->logger->info('Evento de solicitud de referencia de OXXO recibido (Async Flow)');
// Construir la URL basada en el "client_id" // 1. Obtener datos de Stripe (OXXO Reference, URL, etc.)
// $url = "https://siip.mx/wp/wp-content/uploads/img/voucher.png"; $stripeResult = $this->pluginOxxoNotifierFacade->createStripeReference($jsonData, $jsonData['amount'] ?? null);
$url = $this->pluginOxxoNotifierFacade->createOxxoPaymentIntent($event_json);
// Crear una respuesta en formato JSON
// $response = [
// 'event' => 'response.siip',
// 'status' => 'success',
// 'url' => $url
// ];
$response = '{' . if ($stripeResult['hasError'] ?? false) {
'"url": "' . $url . '"' . $this->logger->error('Error generando referencia Stripe: ' . json_encode($stripeResult));
'}';
$this->logger->debug('Este ese el reponse que se envía a CallBell: ' . $response);
// $json_codificado = json_encode($response);
// if (json_last_error() !== JSON_ERROR_NONE) {
// $this->logger->error('Error en la codificación JSON: ' . json_last_error_msg() . PHP_EOL);
// }
//$this->logger->info('Se está enviando esta respuesta: ' . json_encode($json_codificado) . PHP_EOL);
// Enviar el encabezado de respuesta como JSON
header('Content-Type: application/json'); header('Content-Type: application/json');
echo json_encode([
'oxxo_reference' => '',
'url' => '',
'error' => $stripeResult['data']['error'] ?? 'stripe_error',
'status' => 'failed'
]);
exit;
}
// Enviar la respuesta en formato JSON $oxxoData = $stripeResult['data'];
//echo json_encode($response);
echo $response;
// 2. Crear Orden (Sync) para obtener ID
// Ahora pasamos $oxxoData que SI tiene clientID, clientFullName, etc.
$responseOxxo = $this->pluginOxxoNotifierFacade->createOxxoOrder($oxxoData);
$orderId = $responseOxxo['order_id'] ?? null;
// 3. Preparar respuesta inmediata (Pending)
$responseArray = [
'oxxo_reference' => $responseOxxo['oxxo_reference'] ?? '',
'url' => '', // No hay URL de imagen todavía
'stripe_url' => $responseOxxo['url'] ?? '',
'voucher_image_url' => '',
'order_id' => $orderId,
'clientFullName' => $responseOxxo['clientFullName'] ?? '',
'clientID' => $responseOxxo['clientID'] ?? '',
'amount' => $responseOxxo['amount'] ?? '',
'error' => $responseOxxo['error'] ?? '',
'status' => 'generating' // Estado esperado por el bot para iniciar polling
];
// 4. Enviar Respuesta y CERRAR Conexión
// Limpiamos buffers
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Content-Type: application/json');
header('Connection: close');
ignore_user_abort(true); // Permitir que el script siga corriendo
echo json_encode($responseArray);
// Forzar envío al cliente
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
} else {
// Fallback para servidores no FastCGI
header('Content-Length: ' . strlen(json_encode($responseArray)));
flush();
}
// 5. Trabajo en Pesado (Background)
if ($orderId) {
$this->logger->info("Iniciando generación background para orden #$orderId");
set_time_limit(180); // 3 minutos para Puppeteer
sleep(1); // Pequeña pausa para asegurar liberación del socket
$this->pluginOxxoNotifierFacade->generateOxxoVoucher($responseOxxo, true);
$this->logger->info("Generación background finalizada para orden #$orderId");
} else {
$this->logger->error("No se pudo iniciar background job: Falta order_id");
}
// Terminar proceso hijo
exit;
break; break;
// Otros eventos relevantes
} }
} }
$jsonData = @json_decode($userInput, true, 10);
if (!isset($jsonData['uuid'])) {
$this->logger->error('JSON error: ' . json_last_error_msg());
return; return;
} }
$notification = $this->notificationDataFactory->getObject($jsonData); $notification = $this->notificationDataFactory->getObject($jsonData);
$this->logger->debug('valor el evento recibido por webhook: ' . $notification->eventName . PHP_EOL); $this->logger->debug('Evento recibido: ' . $notification->eventName);
if ($notification->changeType === 'test') { if ($notification->changeType === 'test') {
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
$this->logger->info('Webhook test successful.'); $this->logger->info('Webhook test successful.');
return; return;
} else if ($notification->changeType === 'paperless.update') {
//imprimir el webhook json
$this->logger->info('Webhook de paperless update: ' . json_encode($jsonData) . PHP_EOL);
} }
if (!$notification->clientId) { // if (!$notification->clientId) {
$this->logger->warning('No client specified, cannot notify them.'); // $this->logger->warning('No client specified, cannot notify them.');
return; // return;
} // }
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create(); $configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig(); $config = $configManager->loadConfig();
@ -198,100 +297,191 @@ class Plugin
if ($notification->eventName === 'payment.add') { if ($notification->eventName === 'payment.add') {
$result = json_encode($notification); $result = json_encode($notification);
$this->logger->debug('datos del notification para el invoice add:' . $result . PHP_EOL); $this->logger->debug('Notification encodificado en JSON:' . $result . PHP_EOL);
$datos_payment = $notification->paymentData;
$this->logger->debug('valor del payment data: ' . json_encode($datos_payment) . PHP_EOL);
$payment_method_id = $notification->paymentData['methodId']; $payment_method_id = $notification->paymentData['methodId'];
//$this->logger->debug('Metodo de pago: ' . $notification->paymentData['methodId'] . PHP_EOL);
$payment_method = ''; $payment_method = '';
switch ($payment_method_id) { switch ($payment_method_id) {
case '11721cdf-a498-48be-903e-daa67552e4f6': case '11721cdf-a498-48be-903e-daa67552e4f6':
$payment_method = 'Cheque'; $payment_method = 'Cheque';
if ($config['checkPaymentMethodId']) { if ($config['checkPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case '6efe0fa8-36b2-4dd1-b049-427bffc7d369': case '6efe0fa8-36b2-4dd1-b049-427bffc7d369':
$payment_method = 'Efectivo'; $payment_method = 'Efectivo';
if ($config['cashPaymentMethodId']) { if ($config['cashPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case '4145b5f5-3bbc-45e3-8fc5-9cda970c62fb': case '4145b5f5-3bbc-45e3-8fc5-9cda970c62fb':
$payment_method = 'Transferencia bancaria'; $payment_method = 'Transferencia bancaria';
if ($config['bankTransferPaymentMethodId']) { if ($config['bankTransferPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case '78e84000-9b5b-44a4-8367-da43df86ce34': case '78e84000-9b5b-44a4-8367-da43df86ce34':
$payment_method = 'PayPal'; $payment_method = 'PayPal';
if ($config['paypalPaymentMethodId']) { if ($config['paypalPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case '6da98bb9-6df7-4c41-8608-5cdd7fde7d5d': case '6da98bb9-6df7-4c41-8608-5cdd7fde7d5d':
$payment_method = 'Tarjeta de crédito PayPal'; $payment_method = 'Tarjeta de crédito PayPal';
if ($config['creditCardPaypalPaymentMethodId']) { if ($config['creditCardPaypalPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case '1dd098fa-5d63-4c8d-88b7-3c27ffbbb6ae': case '1dd098fa-5d63-4c8d-88b7-3c27ffbbb6ae':
$payment_method = 'Tarjeta de crédito Stripe'; $payment_method = 'Tarjeta de crédito Stripe';
if ($config['creditCardStripePaymentMethodId']) { if ($config['creditCardStripePaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case 'b9e1e9d1-5c7b-41d2-b6b2-3e568d700290': case 'b9e1e9d1-5c7b-41d2-b6b2-3e568d700290':
$payment_method = 'Suscripción de Stripe (tarjeta de crédito)'; $payment_method = 'Suscripción de Stripe (tarjeta de crédito)';
if ($config['stripeSubscriptionCreditCardPaymentMethodId']) { if ($config['stripeSubscriptionCreditCardPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case '939f7701-00b7-4676-9b1e-17afb268c8ba': case '939f7701-00b7-4676-9b1e-17afb268c8ba':
$payment_method = 'Suscripción de PayPal'; $payment_method = 'Suscripción de PayPal';
if ($config['paypalSubscriptionPaymentMethodId']) { if ($config['paypalSubscriptionPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case '1c963e35-df24-444d-95d2-12592d5107e8': case '1c963e35-df24-444d-95d2-12592d5107e8':
$payment_method = 'MercadoPago'; $payment_method = 'MercadoPago';
if ($config['mercadopagoPaymentMethodId']) { if ($config['mercadopagoPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case 'd8c1eae9-d41d-479f-aeaf-38497975d7b3': case 'd8c1eae9-d41d-479f-aeaf-38497975d7b3':
$payment_method = 'Personalizado'; $payment_method = 'Personalizado';
if ($config['customPaymentMethodId']) { if ($config['customPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
case '72271b72-5c0a-45e2-94d1-cdf4d7cf10e2': case '72271b72-5c0a-45e2-94d1-cdf4d7cf10e2':
$payment_method = 'Cortesía'; $payment_method = 'Cortesía';
if ($config['courtesyPaymentMethodId']) { if ($config['courtesyPaymentMethodId'] ?? false) {
$this->notifierFacade->verifyPaymentActionToDo($notification); $this->notifierFacade->verifyPaymentActionToDo($notification);
} }
break; break;
default: default:
$payment_method = 'Desconocido, revisar metodos de pago no contemplados'; $payment_method = 'Desconocido';
break; break;
} }
} else if ($notification->eventName === 'client.edit') { } else if ($notification->eventName === 'client.edit') {
$this->logger->debug('Se actualiza a un cliente' . PHP_EOL); $this->logger->info('Procesando evento client.edit para entityId: ' . ($jsonData['entityId'] ?? 'unknown'));
$this->logger->debug('Payload completo client.edit: ' . json_encode($jsonData));
try {
$clientID = $jsonData['entityId'];
if (!$this->pluginNotifierFacade) {
$this->logger->error('Falla crítica: pluginNotifierFacade no está inicializado.');
} else {
$this->logger->info('Llamando a updatePasswordAntenaIfNeeded para cliente: ' . $clientID);
$this->pluginNotifierFacade->updatePasswordAntenaIfNeeded((int)$clientID, $jsonData);
$this->logger->info('Llamada finalizada exitosamente.');
}
} catch (\Throwable $e) {
$this->logger->error('ERROR FATAL procesando client.edit: ' . $e->getMessage());
$this->logger->error('Trace: ' . $e->getTraceAsString());
}
//ejemplo de json_data: {"uuid":"17e043a7-03b5-4312-ab81-a7818124a77e","changeType":"edit","entity":"client","entityId":"158","eventName":"client.edit","extraData":{"entity":{"id":158,"userIdent":null,"previousIsp":null,"isLead":false,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":"2025-02-09T03:15:49-0600","companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false},"entityBeforeEdit":{"id":158,"userIdent":null,"previousIsp":null,"isLead":true,"clientType":1,"companyName":null,"companyRegistrationNumber":null,"companyTaxId":null,"companyWebsite":null,"street1":"23 San Luis","street2":null,"city":"Dolores Hidalgo Cuna de la Independencia Nacional","countryId":173,"stateId":null,"zipCode":"37804","fullAddress":"San Luis 23, Guadalupe, Dolores Hidalgo Cuna de la Independencia Nacional, Gto., M\u00e9xico","invoiceStreet1":null,"invoiceStreet2":null,"invoiceCity":null,"invoiceStateId":null,"invoiceCountryId":null,"invoiceZipCode":null,"invoiceAddressSameAsContact":true,"note":null,"sendInvoiceByPost":null,"invoiceMaturityDays":null,"stopServiceDue":null,"stopServiceDueDays":null,"organizationId":1,"tax1Id":null,"tax2Id":null,"tax3Id":null,"registrationDate":"2025-01-06T00:00:00-0600","leadConvertedAt":null,"companyContactFirstName":null,"companyContactLastName":null,"isActive":false,"firstName":"Luis","lastName":"Guti\u00e9rrez","username":null,"contacts":[{"id":162,"clientId":158,"email":null,"phone":null,"name":null,"isBilling":true,"isContact":true,"types":[{"id":1,"name":"Billing"},{"id":2,"name":"General"}]}],"attributes":[],"accountBalance":0,"accountCredit":0,"accountOutstanding":0,"currencyCode":"MXN","organizationName":"SIIP Pruebas","bankAccounts":[],"tags":[],"invitationEmailSentDate":null,"avatarColor":"#2196f3","addressGpsLat":21.153272,"addressGpsLon":-100.9134508,"isArchived":false,"generateProformaInvoices":null,"usesProforma":false,"hasOverdueInvoice":false,"hasOutage":false,"hasSuspendedService":false,"hasServiceWithoutDevices":false,"referral":null,"hasPaymentSubscription":false,"hasAutopayCreditCard":false}}}
if (isset($jsonData['extraData']['entityBeforeEdit'], $jsonData['extraData']['entity'])) {
$entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit'];
$entity = $jsonData['extraData']['entity'];
if (isset($entityBeforeEdit['isLead'], $entity['isLead'])) {
$isLeadBefore = $entityBeforeEdit['isLead'];
$isLeadAfter = $entity['isLead'];
if ($isLeadBefore === true && $isLeadAfter === false) {
$this->logger->info("El cliente $clientID cambió de potencial a cliente. Iniciando creación automática en Stripe...");
$this->pluginNotifierFacade->createStripeClient($notification, 'CREAR CLIENTE STRIPE', false);
}
}
if (isset($entity['tags'], $entityBeforeEdit['tags'])) {
$tags = $entity['tags'];
$tagsBefore = $entityBeforeEdit['tags'];
$clabeTagExistsBefore = false;
$stripeTagExistsBefore = false;
$clabeTagExists = false;
$stripeTagExists = false;
foreach ($tagsBefore as $tag) {
if ($tag['name'] === 'CREAR CLABE STRIPE') $clabeTagExistsBefore = true;
if ($tag['name'] === 'CREAR CLIENTE STRIPE') $stripeTagExistsBefore = true;
}
foreach ($tags as $tag) {
if ($tag['name'] === 'CREAR CLABE STRIPE') $clabeTagExists = true;
if ($tag['name'] === 'CREAR CLIENTE STRIPE') $stripeTagExists = true;
}
if ($clabeTagExists && !$clabeTagExistsBefore) {
$this->logger->debug('La etiqueta CREAR CLABE STRIPE se agregó al cliente');
$this->pluginNotifierFacade->createStripeClient($notification, 'CREAR CLABE STRIPE', true);
}
if ($stripeTagExists && !$stripeTagExistsBefore) {
$this->logger->debug('La etiqueta CREAR CLIENTE STRIPE se agregó al cliente');
$this->pluginNotifierFacade->createStripeClient($notification, 'CREAR CLIENTE STRIPE', false);
}
}
// Automatización: Sincronizar cambios de Nombre o Email con Stripe
$nameBefore = trim(($entityBeforeEdit['firstName'] ?? '') . ' ' . ($entityBeforeEdit['lastName'] ?? ''));
if (empty($nameBefore)) $nameBefore = $entityBeforeEdit['companyName'] ?? '';
$nameAfter = trim(($entity['firstName'] ?? '') . ' ' . ($entity['lastName'] ?? ''));
if (empty($nameAfter)) $nameAfter = $entity['companyName'] ?? '';
$emailBefore = null;
foreach ($entityBeforeEdit['contacts'] ?? [] as $contact) {
if ($contact['isBilling'] || $contact['isContact']) {
$emailBefore = $contact['email'] ?? null;
if ($emailBefore) break;
}
}
$emailAfter = null;
foreach ($entity['contacts'] ?? [] as $contact) {
if ($contact['isBilling'] || $contact['isContact']) {
$emailAfter = $contact['email'] ?? null;
if ($emailAfter) break;
}
}
if ($nameBefore !== $nameAfter || $emailBefore !== $emailAfter) {
$this->logger->info("Detectado cambio en datos básicos del cliente $clientID. Sincronizando con Stripe...");
$this->pluginNotifierFacade->syncStripeCustomerData((int)$clientID, $nameAfter, $emailAfter);
}
} else {
$this->logger->warning('Los datos entityBeforeEdit o entity no están presentes en extraData');
}
$this->notifierFacade->verifyClientActionToDo($notification); $this->notifierFacade->verifyClientActionToDo($notification);
} else if ($notification->eventName === 'client.add') { } else if ($notification->eventName === 'client.add') {
$this->logger->debug('Se agregó un nuevo cliente' . PHP_EOL); $this->logger->debug('Se agregó un nuevo cliente');
$this->pluginNotifierFacade->createStripeClient($notification); $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
} else if ($notification->eventName === 'service.edit') {
$this->logger->debug('Se editó el servicio a un cliente' . PHP_EOL);
$this->notifierFacade->verifyServiceActionToDo($notification);
//ejemplo de json_data: {"uuid":"06d281ca-d78e-4f0a-a282-3a6b77d25da0","changeType":"edit","entity":"service","entityId":"155","eventName":"service.edit","extraData":{"entity":{"id":155,"prepaid":false,"clientId":171,"status":1,"name":"Basico 300","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","note":null,"addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"servicePlanId":6,"servicePlanPeriodId":26,"price":300,"hasIndividualPrice":false,"totalPrice":300,"currencyCode":"MXN","invoiceLabel":null,"contractId":null,"contractLengthType":1,"minimumContractLengthMonths":null,"activeFrom":"2025-05-21T00:00:00-0600","activeTo":null,"contractEndDate":null,"discountType":0,"discountValue":null,"discountInvoiceLabel":"Descuento","discountFrom":null,"discountTo":null,"tax1Id":null,"tax2Id":null,"tax3Id":null,"invoicingStart":"2025-05-21T00:00:00-0600","invoicingPeriodType":1,"invoicingPeriodStartDay":1,"nextInvoicingDayAdjustment":10,"invoicingProratedSeparately":true,"invoicingSeparately":false,"sendEmailsAutomatically":null,"useCreditAutomatically":true,"servicePlanName":"Basico 300","servicePlanPrice":300,"servicePlanPeriod":1,"servicePlanType":"Internet","downloadSpeed":8,"uploadSpeed":8,"hasOutage":false,"unmsClientSiteStatus":null,"fccBlockId":null,"lastInvoicedDate":null,"unmsClientSiteId":"359cb58d-e64f-453a-890e-23d5abb4f116","attributes":[],"addressData":null,"suspensionReasonId":null,"serviceChangeRequestId":null,"setupFeePrice":null,"earlyTerminationFeePrice":null,"downloadSpeedOverride":null,"uploadSpeedOverride":null,"trafficShapingOverrideEnd":null,"trafficShapingOverrideEnabled":false,"servicePlanGroupId":null,"suspensionPeriods":[],"surcharges":[]},"entityBeforeEdit":{"id":155,"prepaid":false,"clientId":171,"status":1,"name":"Basico 300","fullAddress":"Campeche 56, Dolores Hidalgo, 37800","street1":"Campeche 56","street2":null,"city":"Dolores Hidalgo","countryId":173,"stateId":null,"zipCode":"37800","note":null,"addressGpsLat":21.1572461,"addressGpsLon":-100.9377137,"servicePlanId":6,"servicePlanPeriodId":26,"price":300,"hasIndividualPrice":false,"totalPrice":300,"currencyCode":"MXN","invoiceLabel":null,"contractId":null,"contractLengthType":1,"minimumContractLengthMonths":null,"activeFrom":"2025-05-21T00:00:00-0600","activeTo":null,"contractEndDate":null,"discountType":0,"discountValue":null,"discountInvoiceLabel":"Descuento","discountFrom":null,"discountTo":null,"tax1Id":null,"tax2Id":null,"tax3Id":null,"invoicingStart":"2025-05-21T00:00:00-0600","invoicingPeriodType":1,"invoicingPeriodStartDay":1,"nextInvoicingDayAdjustment":10,"invoicingProratedSeparately":true,"invoicingSeparately":false,"sendEmailsAutomatically":null,"useCreditAutomatically":true,"servicePlanName":"Basico 300","servicePlanPrice":300,"servicePlanPeriod":1,"servicePlanType":"Internet","downloadSpeed":8,"uploadSpeed":8,"hasOutage":false,"unmsClientSiteStatus":null,"fccBlockId":null,"lastInvoicedDate":null,"unmsClientSiteId":"359cb58d-e64f-453a-890e-23d5abb4f116","attributes":[],"addressData":null,"suspensionReasonId":null,"serviceChangeRequestId":null,"setupFeePrice":null,"earlyTerminationFeePrice":null,"downloadSpeedOverride":null,"uploadSpeedOverride":null,"trafficShapingOverrideEnd":null,"trafficShapingOverrideEnabled":false,"servicePlanGroupId":null,"suspensionPeriods":[],"surcharges":[]}}}
$clientID = $jsonData['extraData']['entity']['clientId'];
$this->pluginNotifierFacade->updatePasswordAntenaIfNeeded($clientID, $jsonData);
} else if ($notification->eventName === 'service.suspend') { } else if ($notification->eventName === 'service.suspend') {
$this->logger->debug('Se suspendió el servicio a un cliente' . PHP_EOL); $this->logger->debug('Se suspendió el servicio a un cliente' . PHP_EOL);
$this->notifierFacade->verifyServiceActionToDo($notification); $this->notifierFacade->verifyServiceActionToDo($notification);
@ -301,7 +491,7 @@ class Plugin
} else if ($notification->eventName === 'service.postpone') { } else if ($notification->eventName === 'service.postpone') {
$this->logger->debug('Se pospuso la suspención del servicio a un cliente' . PHP_EOL); $this->logger->debug('Se pospuso la suspención del servicio a un cliente' . PHP_EOL);
$this->notifierFacade->verifyServiceActionToDo($notification); $this->notifierFacade->verifyServiceActionToDo($notification);
}else if ($notification->eventName === 'invoice.near_due') { } else if ($notification->eventName === 'invoice.near_due') {
$this->logger->debug('Factura casi por vencer' . PHP_EOL); $this->logger->debug('Factura casi por vencer' . PHP_EOL);
$this->notifierFacade->notifyOverDue($notification); $this->notifierFacade->notifyOverDue($notification);
} else if ($notification->eventName === 'invoice.overdue') { } else if ($notification->eventName === 'invoice.overdue') {
@ -315,16 +505,96 @@ class Plugin
$this->logger->debug('datos del notification para el invoice add:' . $result . PHP_EOL); $this->logger->debug('datos del notification para el invoice add:' . $result . PHP_EOL);
$accountBalance = $notification->clientData['accountBalance']; $accountBalance = $notification->clientData['accountBalance'];
$invoiceAmountPaid = $notification->invoiceData['amountPaid']; //$invoiceAmountPaid = $notification->invoiceData['amountPaid'];
$this->logger->debug("Account Balance: " . $accountBalance . PHP_EOL); $this->logger->debug("Account Balance: " . $accountBalance . PHP_EOL);
$this->logger->debug("Pago hecho con la factura: " . $invoiceAmountPaid . PHP_EOL); // $this->logger->debug("Pago hecho con la factura: " . $invoiceAmountPaid . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification); $this->notifierFacade->verifyInvoiceActionToDo($notification);
}else if($notification->eventName === 'invoice.edit'){ } else if ($notification->eventName === 'invoice.edit') {
$this->logger->debug('Edición de Factura' . PHP_EOL); $this->logger->debug('Edición de Factura' . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification); $this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'invoice.add_draft') {
$this->logger->debug('Adición de borrador de Factura' . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'invoice.draft_approved') {
$this->logger->debug('Aprobación de Factura' . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'invoice.delete') {
$this->logger->debug('Eliminación de Factura' . PHP_EOL);
$this->notifierFacade->verifyInvoiceActionToDo($notification);
} else if ($notification->eventName === 'job.add') {
$this->logger->debug('Se ha agregado un nuevo trabajo');
$title = $jsonData['extraData']['entity']['title'] ?? '';
$title = '[NOTIFICACION-PENDIENTE]' . $title;
$responsePatch = $this->ucrmApi->patch('scheduling/jobs/' . $jsonData['entityId'], [
'title' => $title,
]);
$this->logger->debug('Respuesta de la API al agregar el trabajo: ' . json_encode($responsePatch));
} else if ($notification->eventName === 'job.edit') {
$this->logger->debug('Se actualiza un trabajo' . PHP_EOL);
// $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
// Validar que 'extraData' existe y contiene las claves necesarias
if (
isset($jsonData['extraData']['entityBeforeEdit']) &&
isset($jsonData['extraData']['entity'])
) {
$entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit'];
$entity = $jsonData['extraData']['entity'];
$this->logger->debug('Validando claves dentro de entityBeforeEdit y entity');
// Validar que 'assignedUserId' existe en ambas entidades
if (array_key_exists('assignedUserId', $entityBeforeEdit) && array_key_exists('assignedUserId', $entity)) {
// $this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo assignedUserId');
$assignedUserIdBefore = $entityBeforeEdit['assignedUserId'];
$assignedUserIdAfter = $entity['assignedUserId'];
$dateBefore = $entityBeforeEdit['date'];
$dateAfter = $entity['date'];
$statusBefore = $entityBeforeEdit['status'];
$statusAfter = $entity['status'];
$title = $entityBeforeEdit['title'];
$pendingPrefix = '[NOTIFICACION-PENDIENTE]'; // Prefijo para trabajos pendientes de notificación
$currentTitle = $entity['title'] ?? ''; // Obtener el título actual
//Valores de status y su significado: 0 = abierto, 1= En curso, 2 = Cerrado
if ($statusAfter == 1) {
$isNewActivation = ($statusBefore == 0 && $statusAfter == 1);
$isTechChange = ($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore && $dateBefore === $dateAfter);
$isReprogramming = ($assignedUserIdBefore != null && $assignedUserIdBefore === $assignedUserIdAfter && $dateBefore != $dateAfter);
$isBothChange = ($assignedUserIdBefore != null && $assignedUserIdAfter != $assignedUserIdBefore && $dateBefore != $dateAfter);
$isDeassignment = ($assignedUserIdBefore != null && $assignedUserIdAfter === null);
if ($isNewActivation) {
$this->logger->debug('Trabajo iniciado o asignado: Notificando...');
$this->notifierFacade->verifyJobActionToDo($jsonData, false, false);
} else if ($isTechChange) {
$this->logger->debug('Cambio de técnico sin reprogramación');
$this->notifierFacade->verifyJobActionToDo($jsonData, false, true);
} else if ($isReprogramming) {
$this->logger->debug('Reprogramación sin cambio de técnico');
$this->notifierFacade->verifyJobActionToDo($jsonData, true, false);
} else if ($isBothChange) {
$this->logger->debug('Reprogramación y cambio de técnico');
$this->notifierFacade->verifyJobActionToDo($jsonData, true, true);
} else if ($isDeassignment) {
$this->logger->debug('Técnico desasignado');
$this->notifierFacade->verifyJobActionToDo($jsonData, null, true);
} else {
$this->logger->debug('Edición de trabajo "En curso" sin cambios de fecha o técnico relevantes para notificación');
}
} }
} else {
$this->logger->warning('El campo assignedUserId no existe en entityBeforeEdit o entity');
}
} else {
$this->logger->warning('Los datos entityBeforeEdit o entity no están presentes en extraData');
}
}
//$this->notifierFacade->update($notification); //$this->notifierFacade->update($notification);
} catch (TwilioException $exception) { } catch (TwilioException $exception) {

View File

@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace SmsNotifier\Service;
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
class MinioStorageService
{
/**
* @var S3Client
*/
private $s3Client;
/**
* @var string
*/
private $bucket;
/**
* @var string
*/
private $publicUrl;
/**
* @var Logger
*/
private $logger;
public function __construct(Logger $logger)
{
$this->logger = $logger;
$this->initializeClient();
}
private function initializeClient(): void
{
$config = PluginConfigManager::create()->loadConfig();
$endpoint = $config['minioEndpoint'] ?? 'http://localhost:9002';
$key = $config['minioAccessKey'] ?? 'minioadmin';
$secret = $config['minioSecretKey'] ?? 'minioadmin';
$this->bucket = $config['minioBucket'] ?? 'vouchers-oxxo';
$this->publicUrl = rtrim($config['minioPublicUrl'] ?? 'http://localhost:9002', '/');
try {
$this->s3Client = new S3Client([
'version' => 'latest',
'region' => 'us-east-1', // MinIO doesn't really care about region, but SDK requires it
'endpoint' => $endpoint,
'use_path_style_endpoint' => true,
'credentials' => [
'key' => $key,
'secret' => $secret,
],
]);
} catch (\Exception $e) {
$this->logger->error("Error initializing S3 Client: " . $e->getMessage());
}
}
public function uploadFile(string $sourcePath, string $filename): string
{
if (!$this->s3Client) {
$this->logger->error("S3 Client not initialized. Cannot upload.");
return '';
}
try {
$result = $this->s3Client->putObject([
'Bucket' => $this->bucket,
'Key' => $filename,
'SourceFile' => $sourcePath,
]);
// Construct Public URL
// We do NOT use $result['ObjectURL'] because that might point to the internal container IP/Port
// We specifically want to use the public domain provided in config.
$finalUrl = $this->publicUrl . '/' . $this->bucket . '/' . $filename;
$this->logger->info("Archivo subido exitosamente a MinIO: $finalUrl");
return $finalUrl;
} catch (AwsException $e) {
$this->logger->error("AWS S3 Error uploading file $filename: " . $e->getMessage());
return '';
} catch (\Exception $e) {
$this->logger->error("General Error uploading file $filename: " . $e->getMessage());
return '';
}
}
}

View File

@ -0,0 +1,171 @@
<?php
namespace SmsNotifier\Service;
use GuzzleHttp\Client;
use Stripe\StripeClient;
use Stripe\Exception\ApiErrorException;
class PaymentIntentService
{
private $ucrmApiUrl;
private $ucrmApiKey;
private $stripeApiKey;
private $httpClient;
private $stripeClient;
private $logger;
public function __construct($ucrmApiUrl, $ucrmApiKey, $stripeApiKey, $logger = null)
{
$this->ucrmApiUrl = rtrim($ucrmApiUrl, '/');
$this->ucrmApiKey = $ucrmApiKey;
$this->stripeApiKey = $stripeApiKey;
$this->logger = $logger;
$this->httpClient = new Client([
'base_uri' => $this->ucrmApiUrl . '/api/v1.0/',
'headers' => [
'X-Auth-App-Key' => $this->ucrmApiKey,
'Accept' => 'application/json',
],
'verify' => false,
'timeout' => 10,
]);
$this->stripeClient = new StripeClient($this->stripeApiKey);
}
public function searchClients($query)
{
try {
$response = $this->httpClient->get('clients', [
'query' => [
'query' => $query,
'limit' => 5
]
]);
$clients = json_decode($response->getBody(), true);
return array_map(function ($client) {
return [
'id' => $client['id'],
'firstName' => $client['firstName'],
'lastName' => $client['lastName'],
'username' => $client['username'],
'fullAddress' => $client['fullAddress'] ?? '',
'companyName' => $client['companyName'],
'clientType' => $client['clientType'], // 1 = residential, 2 = company
];
}, $clients);
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function getClientDetails($clientId)
{
try {
$response = $this->httpClient->get("clients/{$clientId}");
$client = json_decode($response->getBody(), true);
$stripeCustomerId = null;
$clabeInterbancaria = null;
if (isset($client['attributes'])) {
foreach ($client['attributes'] as $attribute) {
if ($attribute['key'] === 'stripeCustomerId' || $attribute['name'] === 'Stripe Customer ID') {
$stripeCustomerId = $attribute['value'];
}
if ($attribute['key'] === 'clabeInterbancaria' || $attribute['name'] === 'Clabe Interbancaria') {
$clabeInterbancaria = $attribute['value'];
}
}
}
return [
'id' => $client['id'],
'fullName' => ($client['clientType'] == 1)
? $client['firstName'] . ' ' . $client['lastName']
: $client['companyName'],
'stripeCustomerId' => $stripeCustomerId,
'clabeInterbancaria' => $clabeInterbancaria,
'email' => $this->getClientEmail($client),
'accountOutstanding' => $client['accountOutstanding'] ?? 0
];
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
private function getClientEmail($clientData)
{
if (!empty($clientData['contacts'])) {
foreach ($clientData['contacts'] as $contact) {
if (!empty($contact['email'])) {
return $contact['email'];
}
}
}
return $clientData['username'] ?? ''; // Fallback, though username might not be email
}
public function createPaymentIntent($clientId, $amount, $stripeCustomerId, $adminId = null)
{
if ($amount < 10) {
throw new \Exception("El monto debe ser mayor a 10 MXN");
}
try {
$amountCentavos = intval($amount * 100);
$paymentIntent = $this->stripeClient->paymentIntents->create([
'amount' => $amountCentavos,
'currency' => 'mxn',
'customer' => $stripeCustomerId,
'payment_method_types' => ['customer_balance'],
'payment_method_data' => ['type' => 'customer_balance'],
'confirm' => true,
'payment_method_options' => [
'customer_balance' => [
'funding_type' => 'bank_transfer',
'bank_transfer' => ['type' => 'mx_bank_transfer']
],
],
'metadata' => [
'clientId' => $clientId,
'createdBy' => 'UCRM',
'paymentType' => 'card.one_time',
'signedInAdminId' => $adminId,
'tipoPago' => 'Transferencia Bancaria'
],
]);
$this->log("PaymentIntent created: " . $paymentIntent->id . " Status: " . $paymentIntent->status);
return [
'success' => true,
'id' => $paymentIntent->id,
'status' => $paymentIntent->status,
'amount' => $paymentIntent->amount / 100,
'currency' => $paymentIntent->currency,
'next_action' => $paymentIntent->next_action
];
} catch (ApiErrorException $e) {
return ['success' => false, 'error' => $e->getMessage()];
} catch (\Exception $e) {
return ['success' => false, 'error' => $e->getMessage()];
}
}
private function log($message)
{
if ($this->logger) {
$this->logger->debug($message);
} else {
error_log($message);
}
}
}

View File

@ -31,13 +31,18 @@ class PluginDataValidator
{ {
$pluginData = $this->optionsManager->load(); $pluginData = $this->optionsManager->load();
$valid = true; $valid = true;
if (empty($pluginData->twilioAccountSid)) { if (empty($pluginData->tokencallbell)) {
$this->errors[] = 'Not valid configuration: Twilio Account SID must be configured'; $this->errors[] = 'Configuración inválida: Token de CallBell es requerido';
$valid = false; $valid = false;
} }
if (empty($pluginData->twilioAuthToken)) { if (empty($pluginData->apitoken)) {
$this->errors[] = 'Not valid configuration: Twilio Auth Token must be configured'; $this->errors[] = 'Configuración inválida: Token de API de UCRM es requerido';
$valid = false;
}
if (empty($pluginData->ipserver)) {
$this->errors[] = 'Configuración inválida: IP del Servidor es requerida';
$valid = false; $valid = false;
} }

View File

@ -33,27 +33,74 @@ class SmsNumberProvider
/* /*
* go through client's contacts and find an applicable one, if any * go through client's contacts and find an applicable one, if any
*/ */
public function getUcrmClientNumbers(NotificationData $notificationData) public function getUcrmClientNumbers(NotificationData $notificationData = null, $arrayClientCRM = null)
{
$log = PluginLogManager::create(); //Initialize Logger
$arrayPhones = [];
if ($arrayClientCRM != null) {
foreach ($arrayClientCRM['contacts'] as $contact) {
if (!empty($contact['phone'])) {
if (isset($contact['types']) && is_array($contact['types'])) {
foreach ($contact['types'] as $type) {
$typeNameLower = trim(strtolower($type['name']));
if (in_array($typeNameLower, ['whatsapp', 'whatsnotifica'])) {
// Almacena varios números bajo el mismo tipo normalizado
$arrayPhones[$type['name']][] = $contact['phone'];
}
}
}
}
}
} else {
foreach ($notificationData->clientData['contacts'] as $contact) {
if (!empty($contact['phone'])) {
if (isset($contact['types']) && is_array($contact['types'])) {
foreach ($contact['types'] as $type) {
$typeNameLower = trim(strtolower($type['name']));
if (in_array($typeNameLower, ['whatsapp', 'whatsnotifica', 'whatsactualiza'])) {
// Almacena varios números bajo el mismo tipo normalizado
$arrayPhones[$type['name']][] = $contact['phone'];
}
}
}
}
}
}
return $arrayPhones; // Devolver el arreglo de teléfonos por tipo
}
/*
* go through client's contacts and find an applicable one, if any
*/
public function getAllUcrmClientNumbers($arrayClientCRM = null)
{ {
$log = PluginLogManager::create(); //Initialize Logger
//$log->appendLog("Ejecutando metodo getUcrmClientNumbers: " . json_encode($arrayClientCRM) . PHP_EOL);
// Array asociativo donde almacenarás los números de teléfono con sus tipos correspondientes // Array asociativo donde almacenarás los números de teléfono con sus tipos correspondientes
$arrayPhones = []; $arrayPhones = [];
//$log->appendLog("Entrando al if del método getUcrmClientNumbers: " . $arrayClientCRM . PHP_EOL);
//$jsonNotificationData = json_decode($jsonNotificationData, true);
// Recorrer los contactos del cliente para encontrar los teléfonos con sus tipos // Recorrer los contactos del cliente para encontrar los teléfonos con sus tipos
foreach ($notificationData->clientData['contacts'] as $contact) { foreach ($arrayClientCRM['contacts'] as $contact) {
if (!empty($contact['phone'])) { // Verificar que el teléfono no esté vacío if (!empty($contact['phone'])) { // Verificar que el teléfono no esté vacío
if (isset($contact['types']) && is_array($contact['types'])) { // Verificar que 'types' exista y sea un array // agregamos al array asociativo
foreach ($contact['types'] as $type) { $arrayPhones[] = $contact['phone'];
if (in_array($type['name'], ['WhatsApp', 'WhatsNotifica', 'WhatsActualiza'])) {
// Si el tipo de contacto es uno de los deseados, agregamos al array asociativo
$arrayPhones[$type['name']] = $contact['phone'];
}
}
}
} }
} }
return $arrayPhones; // Devolver el arreglo de teléfonos por tipo return $arrayPhones; // Devolver el arreglo de teléfonos por tipo
} }
/* /*
* not every contact has a phone; also check if the type of notification is applicable to contact * not every contact has a phone; also check if the type of notification is applicable to contact
*/ */
@ -76,7 +123,7 @@ class SmsNumberProvider
$types = $contact['types'] ?? []; $types = $contact['types'] ?? [];
foreach ($types as $type) { foreach ($types as $type) {
//$log->appendLog("Entrando al case client del switch: " . json_encode($type)); //$log->appendLog("Entrando al case client del switch: " . json_encode($type));
if ($type['name'] == 'WhatsApp') { if (trim(strtolower($type['name'])) == 'whatsapp') {
return true; return true;
} }
} }
@ -88,19 +135,18 @@ class SmsNumberProvider
$types = $contact['types'] ?? []; $types = $contact['types'] ?? [];
foreach ($types as $type) { foreach ($types as $type) {
//$log->appendLog("Entrando al case client del switch: " . json_encode($type)); //$log->appendLog("Entrando al case client del switch: " . json_encode($type));
if ($type['name'] == 'WhatsApp') { if (trim(strtolower($type['name'])) == 'whatsapp') {
return true; return true;
} }
} }
return false; return false;
} }
case 'service': case 'service': {
{
$types = $contact['types'] ?? []; $types = $contact['types'] ?? [];
foreach ($types as $type) { foreach ($types as $type) {
//$log->appendLog("Entrando al case client del switch: " . json_encode($type)); //$log->appendLog("Entrando al case client del switch: " . json_encode($type));
if ($type['name'] == 'WhatsApp') { if (trim(strtolower($type['name'])) == 'whatsapp') {
return true; return true;
} }
} }

View File

@ -1 +1 @@
{"ucrmPublicUrl":"https://venus.siip.mx/crm/","ucrmLocalUrl":"http://localhost/crm/","unmsLocalUrl":"http://unms:8081/nms/","pluginPublicUrl":"https://venus.siip.mx/crm/_plugins/siip-whatsapp-notifications/public.php","pluginAppKey":"5dVI22XIa9NSK0tiDeiQ3SLDBa1UZVT7g5s/tJzi944Bygx89WIHH7I2/niVPiBK","pluginId":16} {"ucrmPublicUrl":"https://venus.siip.mx/crm/","ucrmLocalUrl":"http://localhost/crm/","unmsLocalUrl":"http://unms-api:8081/nms/","pluginPublicUrl":"https://venus.siip.mx/crm/_plugins/siip-whatsapp-notifications/public.php","pluginAppKey":"5dVI22XIa9NSK0tiDeiQ3SLDBa1UZVT7g5s/tJzi944Bygx89WIHH7I2/niVPiBK","pluginId":16}

90014
unms-swagger.json Normal file

File diff suppressed because it is too large Load Diff

6591
unms.yaml Normal file

File diff suppressed because it is too large Load Diff

8392
unmscrm.apib Normal file

File diff suppressed because it is too large Load Diff

18
vendor/autoload.php vendored
View File

@ -2,6 +2,24 @@
// autoload.php @generated by Composer // autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php'; require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitd6442a7ec79f2f43fc97d16bdcdd18ee::getLoader(); return ComposerAutoloaderInitd6442a7ec79f2f43fc97d16bdcdd18ee::getLoader();

View File

@ -0,0 +1,4 @@
## Code of Conduct
This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
opensource-codeofconduct@amazon.com with any additional questions or comments.

175
vendor/aws/aws-crt-php/LICENSE vendored Normal file
View File

@ -0,0 +1,175 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

1
vendor/aws/aws-crt-php/NOTICE vendored Normal file
View File

@ -0,0 +1 @@
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

117
vendor/aws/aws-crt-php/README.md vendored Normal file
View File

@ -0,0 +1,117 @@
# AWS Common Runtime PHP bindings
## Requirements
* PHP 5.5+ on UNIX platforms, 7.2+ on Windows
* CMake 3.x
* GCC 4.4+, clang 3.8+ on UNIX, Visual Studio build tools on Windows
* Tests require [Composer](https://getcomposer.org)
## Installing with Composer and PECL
The package has two different package published to [composer](https://packagist.org/packages/aws/aws-crt-php) and [PECL](https://pecl.php.net/package/awscrt).
On UNIX, you can get the package from package manager or build from source:
```
pecl install awscrt
composer require aws/aws-crt-php
```
On Windows, you need to build from source as instruction written below for the native extension `php_awscrt.dll` . And, follow https://www.php.net/manual/en/install.pecl.windows.php#install.pecl.windows.loading to load extension. After that:
```
composer require aws/aws-crt-php
```
## Building from Github source
```sh
$ git clone --recursive https://github.com/awslabs/aws-crt-php.git
$ cd aws-crt-php
$ phpize
$ ./configure
$ make
$ ./dev-scripts/run_tests.sh
```
## Building on Windows
### Requirements for Windows
* Ensure you have the [windows PHP SDK](https://github.com/microsoft/php-sdk-binary-tools) (this example assumes installation of the SDK to C:\php-sdk and that you've checked out the PHP source to php-src within the build directory) and it works well on your machine.
* Ensure you have "Development package (SDK to develop PHP extensions)" and PHP available from your system path. You can download them from https://windows.php.net/download/. You can check if they are available by running `phpize -v` and `php -v`
### Instructions
From Command Prompt (not powershell). The instruction is based on Visual Studio 2019 on 64bit Windows.
```bat
> git clone --recursive https://github.com/awslabs/aws-crt-php.git
> git clone https://github.com/microsoft/php-sdk-binary-tools.git C:\php-sdk
> C:\php-sdk\phpsdk-vs16-x64.bat
C:\php-sdk\
$ cd <your-path-to-aws-crt-php>
<your-path-to-aws-crt-php>\
$ phpize
# --with-prefix only required when your php runtime in system path is different than the runtime you wish to use.
<your-path-to-aws-crt-php>\
$ configure --enable-awscrt=shared --with-prefix=<your-path-to-php-prefix>
<your-path-to-aws-crt-php>\
$ nmake
<your-path-to-aws-crt-php>\
$ nmake generate-php-ini
# check .\php-win.ini, it now has the full path to php_awscrt.dll that you can manually load to your php runtime, or you can run the following command to run tests and load the required native extension for awscrt.
<your-path-to-aws-crt-php>\
$ .\dev-scripts\run_tests.bat <your-path-to-php-binary>
```
Note: for VS2017, Cmake will default to build for Win32, refer to [here](https://cmake.org/cmake/help/latest/generator/Visual%20Studio%2015%202017.html). If you are building for x64 php, you can set environment variable as follow to let cmake pick x64 compiler.
```bat
set CMAKE_GENERATOR=Visual Studio 15 2017
set CMAKE_GENERATOR_PLATFORM=x64
```
## Debugging
Using [PHPBrew](https://github.com/phpbrew/phpbrew) to build/manage multiple versions of PHP is helpful.
Note: You must use a debug build of PHP to debug native extensions.
See the [PHP Internals Book](https://www.phpinternalsbook.com/php7/build_system/building_php.html) for more info
```shell
# PHP 8 example
$ phpbrew install --stdout -j 8 8.0 +default -- CFLAGS=-Wno-error --disable-cgi --enable-debug
# PHP 5.5 example
$ phpbrew install --stdout -j 8 5.5 +default -openssl -mbstring -- CFLAGS="-w -Wno-error" --enable-debug --with-zlib=/usr/local/opt/zlib
$ phpbrew switch php-8.0.6 # or whatever version is current, it'll be at the end of the build output
$ phpize
$ ./configure
$ make CMAKE_BUILD_TYPE=Debug
```
Ensure that the php you launch from your debugger is the result of `which php` , not just
the system default php.
## Security
See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
## Known OpenSSL related issue (Unix only)
* When your php loads a different version of openssl than your system openssl version, awscrt may fail to load or weirdly crash. You can find the openssl version php linked via: `php -i | grep 'OpenSSL'`, and awscrt linked from the build log, which will be `Found OpenSSL: * (found version *)`
The easiest workaround to those issue is to build from source and get aws-lc for awscrt to depend on instead.
TO do that, same instructions as [here](#building-from-github-source), but use `USE_OPENSSL=OFF make` instead of `make`
## License
This project is licensed under the Apache-2.0 License.

35
vendor/aws/aws-crt-php/composer.json vendored Normal file
View File

@ -0,0 +1,35 @@
{
"name": "aws/aws-crt-php",
"homepage": "https://github.com/awslabs/aws-crt-php",
"description": "AWS Common Runtime for PHP",
"keywords": ["aws","amazon","sdk","crt"],
"type": "library",
"authors": [
{
"name": "AWS SDK Common Runtime Team",
"email": "aws-sdk-common-runtime@amazon.com"
}
],
"minimum-stability": "alpha",
"require": {
"php": ">=5.5"
},
"require-dev": {
"phpunit/phpunit":"^4.8.35||^5.6.3||^9.5",
"yoast/phpunit-polyfills": "^1.0"
},
"autoload": {
"classmap": [
"src/"
]
},
"suggest": {
"ext-awscrt": "Make sure you install awscrt native extension to use any of the functionality."
},
"scripts": {
"test": "./dev-scripts/run_tests.sh",
"test-extension": "@test",
"test-win": ".\\dev-scripts\\run_tests.bat"
},
"license": "Apache-2.0"
}

46
vendor/aws/aws-crt-php/format-check.py vendored Executable file
View File

@ -0,0 +1,46 @@
#!/usr/bin/env python3
import argparse
import os
from pathlib import Path
import re
from subprocess import list2cmdline, run
from tempfile import NamedTemporaryFile
CLANG_FORMAT_VERSION = '18.1.6'
INCLUDE_REGEX = re.compile(r'^ext/.*\.(c|h|inl)$')
EXCLUDE_REGEX = re.compile(r'^$')
arg_parser = argparse.ArgumentParser(description="Check with clang-format")
arg_parser.add_argument('-i', '--inplace-edit', action='store_true',
help="Edit files inplace")
args = arg_parser.parse_args()
os.chdir(Path(__file__).parent)
# create file containing list of all files to format
filepaths_file = NamedTemporaryFile(delete=False)
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
# our regexes expect filepath to use forward slash
filepath = Path(dirpath, filename).as_posix()
if not INCLUDE_REGEX.match(filepath):
continue
if EXCLUDE_REGEX.match(filepath):
continue
filepaths_file.write(f"{filepath}\n".encode())
filepaths_file.close()
# use pipx to run clang-format from PyPI
# this is a simple way to run the same clang-format version regardless of OS
cmd = ['pipx', 'run', f'clang-format=={CLANG_FORMAT_VERSION}',
f'--files={filepaths_file.name}']
if args.inplace_edit:
cmd += ['-i']
else:
cmd += ['--Werror', '--dry-run']
print(f"{Path.cwd()}$ {list2cmdline(cmd)}")
if run(cmd).returncode:
exit(1)

View File

@ -0,0 +1,69 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
use AWS\CRT\NativeResource as NativeResource;
use AWS\CRT\Options as Options;
/**
* Represents a set of AWS credentials
*
* @param array options:
* - string access_key_id - AWS Access Key Id
* - string secret_access_key - AWS Secret Access Key
* - string session_token - Optional STS session token
* - int expiration_timepoint_seconds - Optional time to expire these credentials
*/
final class AwsCredentials extends NativeResource {
static function defaults() {
return [
'access_key_id' => '',
'secret_access_key' => '',
'session_token' => '',
'expiration_timepoint_seconds' => 0,
];
}
private $access_key_id;
private $secret_access_key;
private $session_token;
private $expiration_timepoint_seconds = 0;
public function __get($name) {
return $this->$name;
}
function __construct(array $options = []) {
parent::__construct();
$options = new Options($options, self::defaults());
$this->access_key_id = $options->access_key_id->asString();
$this->secret_access_key = $options->secret_access_key->asString();
$this->session_token = $options->session_token ? $options->session_token->asString() : null;
$this->expiration_timepoint_seconds = $options->expiration_timepoint_seconds->asInt();
if (strlen($this->access_key_id) == 0) {
throw new \InvalidArgumentException("access_key_id must be provided");
}
if (strlen($this->secret_access_key) == 0) {
throw new \InvalidArgumentException("secret_access_key must be provided");
}
$creds_options = self::$crt->aws_credentials_options_new();
self::$crt->aws_credentials_options_set_access_key_id($creds_options, $this->access_key_id);
self::$crt->aws_credentials_options_set_secret_access_key($creds_options, $this->secret_access_key);
self::$crt->aws_credentials_options_set_session_token($creds_options, $this->session_token);
self::$crt->aws_credentials_options_set_expiration_timepoint_seconds($creds_options, $this->expiration_timepoint_seconds);
$this->acquire(self::$crt->aws_credentials_new($creds_options));
self::$crt->aws_credentials_options_release($creds_options);
}
function __destruct() {
self::$crt->aws_credentials_release($this->release());
parent::__destruct();
}
}

View File

@ -0,0 +1,23 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
use AWS\CRT\NativeResource as NativeResource;
/**
* Base class for credentials providers
*/
abstract class CredentialsProvider extends NativeResource {
function __construct(array $options = []) {
parent::__construct();
}
function __destruct() {
self::$crt->credentials_provider_release($this->release());
parent::__destruct();
}
}

View File

@ -0,0 +1,43 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
use AWS\CRT\IO\InputStream;
use AWS\CRT\NativeResource as NativeResource;
class Signable extends NativeResource {
public static function fromHttpRequest($http_message) {
return new Signable(function() use ($http_message) {
return self::$crt->signable_new_from_http_request($http_message->native);
});
}
public static function fromChunk($chunk_stream, $previous_signature="") {
if (!($chunk_stream instanceof InputStream)) {
$chunk_stream = new InputStream($chunk_stream);
}
return new Signable(function() use($chunk_stream, $previous_signature) {
return self::$crt->signable_new_from_chunk($chunk_stream->native, $previous_signature);
});
}
public static function fromCanonicalRequest($canonical_request) {
return new Signable(function() use($canonical_request) {
return self::$crt->signable_new_from_canonical_request($canonical_request);
});
}
protected function __construct($ctor) {
parent::__construct();
$this->acquire($ctor());
}
function __destruct() {
self::$crt->signable_release($this->release());
parent::__destruct();
}
}

View File

@ -0,0 +1,15 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
class SignatureType {
const HTTP_REQUEST_HEADERS = 0;
const HTTP_REQUEST_QUERY_PARAMS = 1;
const HTTP_REQUEST_CHUNK = 2;
const HTTP_REQUEST_EVENT = 3;
const CANONICAL_REQUEST_HEADERS = 4;
const CANONICAL_REQUEST_QUERY_PARAMS = 5;
}

View File

@ -0,0 +1,11 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
class SignedBodyHeaderType {
const NONE = 0;
const X_AMZ_CONTENT_SHA256 = 1;
}

View File

@ -0,0 +1,22 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
use AWS\CRT\NativeResource;
abstract class Signing extends NativeResource {
static function signRequestAws($signable, $signing_config, $on_complete) {
return self::$crt->sign_request_aws($signable->native, $signing_config->native,
function($result, $error_code) use ($on_complete) {
$signing_result = SigningResult::fromNative($result);
$on_complete($signing_result, $error_code);
}, null);
}
static function testVerifySigV4ASigning($signable, $signing_config, $expected_canonical_request, $signature, $ecc_key_pub_x, $ecc_key_pub_y) {
return self::$crt->test_verify_sigv4a_signing($signable, $signing_config, $expected_canonical_request, $signature, $ecc_key_pub_x, $ecc_key_pub_y);
}
}

View File

@ -0,0 +1,11 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
class SigningAlgorithm {
const SIGv4 = 0;
const SIGv4_ASYMMETRIC = 1;
}

View File

@ -0,0 +1,75 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
use AWS\CRT\NativeResource as NativeResource;
use AWS\CRT\Options as Options;
class SigningConfigAWS extends NativeResource {
public static function defaults() {
return [
'algorithm' => SigningAlgorithm::SIGv4,
'signature_type' => SignatureType::HTTP_REQUEST_HEADERS,
'credentials_provider' => null,
'region' => null,
'service' => null,
'use_double_uri_encode' => false,
'should_normalize_uri_path' => false,
'omit_session_token' => false,
'signed_body_value' => null,
'signed_body_header_type' => SignedBodyHeaderType::NONE,
'expiration_in_seconds' => 0,
'date' => time(),
'should_sign_header' => null,
];
}
private $options;
public function __construct(array $options = []) {
parent::__construct();
$this->options = $options = new Options($options, self::defaults());
$sc = $this->acquire(self::$crt->signing_config_aws_new());
self::$crt->signing_config_aws_set_algorithm($sc, $options->algorithm->asInt());
self::$crt->signing_config_aws_set_signature_type($sc, $options->signature_type->asInt());
if ($credentials_provider = $options->credentials_provider->asObject()) {
self::$crt->signing_config_aws_set_credentials_provider(
$sc,
$credentials_provider->native);
}
self::$crt->signing_config_aws_set_region(
$sc, $options->region->asString());
self::$crt->signing_config_aws_set_service(
$sc, $options->service->asString());
self::$crt->signing_config_aws_set_use_double_uri_encode(
$sc, $options->use_double_uri_encode->asBool());
self::$crt->signing_config_aws_set_should_normalize_uri_path(
$sc, $options->should_normalize_uri_path->asBool());
self::$crt->signing_config_aws_set_omit_session_token(
$sc, $options->omit_session_token->asBool());
self::$crt->signing_config_aws_set_signed_body_value(
$sc, $options->signed_body_value->asString());
self::$crt->signing_config_aws_set_signed_body_header_type(
$sc, $options->signed_body_header_type->asInt());
self::$crt->signing_config_aws_set_expiration_in_seconds(
$sc, $options->expiration_in_seconds->asInt());
self::$crt->signing_config_aws_set_date($sc, $options->date->asInt());
if ($should_sign_header = $options->should_sign_header->asCallable()) {
self::$crt->signing_config_aws_set_should_sign_header_fn($sc, $should_sign_header);
}
}
function __destruct()
{
self::$crt->signing_config_aws_release($this->release());
parent::__destruct();
}
public function __get($name) {
return $this->options->get($name);
}
}

View File

@ -0,0 +1,33 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
use AWS\CRT\NativeResource;
use AWS\CRT\HTTP\Request;
class SigningResult extends NativeResource {
protected function __construct($native) {
parent::__construct();
$this->acquire($native);
}
function __destruct() {
// No destruction necessary, SigningResults are transient, just release
$this->release();
parent::__destruct();
}
public static function fromNative($ptr) {
return new SigningResult($ptr);
}
public function applyToHttpRequest(&$http_request) {
self::$crt->signing_result_apply_to_http_request($this->native, $http_request->native);
// Update http_request from native
$http_request = Request::unmarshall($http_request->toBlob());
}
}

View File

@ -0,0 +1,35 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Auth;
/**
* Provides a static set of AWS credentials
*
* @param array options:
* - string access_key_id - AWS Access Key Id
* - string secret_access_key - AWS Secret Access Key
* - string session_token - Optional STS session token
*/
final class StaticCredentialsProvider extends CredentialsProvider {
private $credentials;
public function __get($name) {
return $this->$name;
}
function __construct(array $options = []) {
parent::__construct();
$this->credentials = new AwsCredentials($options);
$provider_options = self::$crt->credentials_provider_static_options_new();
self::$crt->credentials_provider_static_options_set_access_key_id($provider_options, $this->credentials->access_key_id);
self::$crt->credentials_provider_static_options_set_secret_access_key($provider_options, $this->credentials->secret_access_key);
self::$crt->credentials_provider_static_options_set_session_token($provider_options, $this->credentials->session_token);
$this->acquire(self::$crt->credentials_provider_static_new($provider_options));
self::$crt->credentials_provider_static_options_release($provider_options);
}
}

View File

@ -0,0 +1,358 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT;
use AWS\CRT\Internal\Extension;
use \RuntimeException;
/**
* Wrapper for the interface to the CRT. There only ever needs to be one of these, but
* additional instances won't cost anything other than their memory.
* Creating an instance of any NativeResource will activate the CRT binding. User code
* should only need to create one of these if they are only accessing CRT:: static functions.
*/
final class CRT {
private static $impl = null;
private static $refcount = 0;
function __construct() {
if (is_null(self::$impl)) {
try {
self::$impl = new Extension();
} catch (RuntimeException $rex) {
throw new RuntimeException("Unable to initialize AWS CRT via awscrt extension: \n$rex", -1);
}
}
++self::$refcount;
}
function __destruct() {
if (--self::$refcount == 0) {
self::$impl = null;
}
}
/**
* @return bool whether or not the CRT is currently loaded
*/
public static function isLoaded() {
return !is_null(self::$impl);
}
/**
* @return bool whether or not the CRT is available via one of the possible backends
*/
public static function isAvailable() {
try {
new CRT();
return true;
} catch (RuntimeException $ex) {
return false;
}
}
/**
* @return integer last error code reported within the CRT
*/
public static function last_error() {
return self::$impl->aws_crt_last_error();
}
/**
* @param integer $error Error code from the CRT, usually delivered via callback or {@see last_error}
* @return string Human-readable description of the provided error code
*/
public static function error_str($error) {
return self::$impl->aws_crt_error_str((int) $error);
}
/**
* @param integer $error Error code from the CRT, usually delivered via callback or {@see last_error}
* @return string Name/enum identifier for the provided error code
*/
public static function error_name($error) {
return self::$impl->aws_crt_error_name((int) $error);
}
public static function log_to_stdout() {
return self::$impl->aws_crt_log_to_stdout();
}
public static function log_to_stderr() {
return self::$impl->aws_crt_log_to_stderr();
}
public static function log_to_file($filename) {
return self::$impl->aws_crt_log_to_file($filename);
}
public static function log_to_stream($stream) {
return self::$impl->aws_crt_log_to_stream($stream);
}
public static function log_set_level($level) {
return self::$impl->aws_crt_log_set_level($level);
}
public static function log_stop() {
return self::$impl->aws_crt_log_stop();
}
public static function log_message($level, $message) {
return self::$impl->aws_crt_log_message($level, $message);
}
/**
* @return object Pointer to native event_loop_group_options
*/
function event_loop_group_options_new() {
return self::$impl->aws_crt_event_loop_group_options_new();
}
/**
* @param object $elg_options Pointer to native event_loop_group_options
*/
function event_loop_group_options_release($elg_options) {
self::$impl->aws_crt_event_loop_group_options_release($elg_options);
}
/**
* @param object $elg_options Pointer to native event_loop_group_options
* @param integer $max_threads Maximum number of threads to allow the event loop group to use, default: 0/1 per CPU core
*/
function event_loop_group_options_set_max_threads($elg_options, $max_threads) {
self::$impl->aws_crt_event_loop_group_options_set_max_threads($elg_options, (int)$max_threads);
}
/**
* @param object Pointer to event_loop_group_options, {@see event_loop_group_options_new}
* @return object Pointer to the new event loop group
*/
function event_loop_group_new($options) {
return self::$impl->aws_crt_event_loop_group_new($options);
}
/**
* @param object $elg Pointer to the event loop group to release
*/
function event_loop_group_release($elg) {
self::$impl->aws_crt_event_loop_group_release($elg);
}
/**
* return object Pointer to native AWS credentials options
*/
function aws_credentials_options_new() {
return self::$impl->aws_crt_credentials_options_new();
}
function aws_credentials_options_release($options) {
self::$impl->aws_crt_credentials_options_release($options);
}
function aws_credentials_options_set_access_key_id($options, $access_key_id) {
self::$impl->aws_crt_credentials_options_set_access_key_id($options, $access_key_id);
}
function aws_credentials_options_set_secret_access_key($options, $secret_access_key) {
self::$impl->aws_crt_credentials_options_set_secret_access_key($options, $secret_access_key);
}
function aws_credentials_options_set_session_token($options, $session_token) {
self::$impl->aws_crt_credentials_options_set_session_token($options, $session_token);
}
function aws_credentials_options_set_expiration_timepoint_seconds($options, $expiration_timepoint_seconds) {
self::$impl->aws_crt_credentials_options_set_expiration_timepoint_seconds($options, $expiration_timepoint_seconds);
}
function aws_credentials_new($options) {
return self::$impl->aws_crt_credentials_new($options);
}
function aws_credentials_release($credentials) {
self::$impl->aws_crt_credentials_release($credentials);
}
function credentials_provider_release($provider) {
self::$impl->aws_crt_credentials_provider_release($provider);
}
function credentials_provider_static_options_new() {
return self::$impl->aws_crt_credentials_provider_static_options_new();
}
function credentials_provider_static_options_release($options) {
self::$impl->aws_crt_credentials_provider_static_options_release($options);
}
function credentials_provider_static_options_set_access_key_id($options, $access_key_id) {
self::$impl->aws_crt_credentials_provider_static_options_set_access_key_id($options, $access_key_id);
}
function credentials_provider_static_options_set_secret_access_key($options, $secret_access_key) {
self::$impl->aws_crt_credentials_provider_static_options_set_secret_access_key($options, $secret_access_key);
}
function credentials_provider_static_options_set_session_token($options, $session_token) {
self::$impl->aws_crt_credentials_provider_static_options_set_session_token($options, $session_token);
}
function credentials_provider_static_new($options) {
return self::$impl->aws_crt_credentials_provider_static_new($options);
}
function input_stream_options_new() {
return self::$impl->aws_crt_input_stream_options_new();
}
function input_stream_options_release($options) {
self::$impl->aws_crt_input_stream_options_release($options);
}
function input_stream_options_set_user_data($options, $user_data) {
self::$impl->aws_crt_input_stream_options_set_user_data($options, $user_data);
}
function input_stream_new($options) {
return self::$impl->aws_crt_input_stream_new($options);
}
function input_stream_release($stream) {
self::$impl->aws_crt_input_stream_release($stream);
}
function input_stream_seek($stream, $offset, $basis) {
return self::$impl->aws_crt_input_stream_seek($stream, $offset, $basis);
}
function input_stream_read($stream, $length) {
return self::$impl->aws_crt_input_stream_read($stream, $length);
}
function input_stream_eof($stream) {
return self::$impl->aws_crt_input_stream_eof($stream);
}
function input_stream_get_length($stream) {
return self::$impl->aws_crt_input_stream_get_length($stream);
}
function http_message_new_from_blob($blob) {
return self::$impl->aws_crt_http_message_new_from_blob($blob);
}
function http_message_to_blob($message) {
return self::$impl->aws_crt_http_message_to_blob($message);
}
function http_message_release($message) {
self::$impl->aws_crt_http_message_release($message);
}
function signing_config_aws_new() {
return self::$impl->aws_crt_signing_config_aws_new();
}
function signing_config_aws_release($signing_config) {
return self::$impl->aws_crt_signing_config_aws_release($signing_config);
}
function signing_config_aws_set_algorithm($signing_config, $algorithm) {
self::$impl->aws_crt_signing_config_aws_set_algorithm($signing_config, (int)$algorithm);
}
function signing_config_aws_set_signature_type($signing_config, $signature_type) {
self::$impl->aws_crt_signing_config_aws_set_signature_type($signing_config, (int)$signature_type);
}
function signing_config_aws_set_credentials_provider($signing_config, $credentials_provider) {
self::$impl->aws_crt_signing_config_aws_set_credentials_provider($signing_config, $credentials_provider);
}
function signing_config_aws_set_region($signing_config, $region) {
self::$impl->aws_crt_signing_config_aws_set_region($signing_config, $region);
}
function signing_config_aws_set_service($signing_config, $service) {
self::$impl->aws_crt_signing_config_aws_set_service($signing_config, $service);
}
function signing_config_aws_set_use_double_uri_encode($signing_config, $use_double_uri_encode) {
self::$impl->aws_crt_signing_config_aws_set_use_double_uri_encode($signing_config, $use_double_uri_encode);
}
function signing_config_aws_set_should_normalize_uri_path($signing_config, $should_normalize_uri_path) {
self::$impl->aws_crt_signing_config_aws_set_should_normalize_uri_path($signing_config, $should_normalize_uri_path);
}
function signing_config_aws_set_omit_session_token($signing_config, $omit_session_token) {
self::$impl->aws_crt_signing_config_aws_set_omit_session_token($signing_config, $omit_session_token);
}
function signing_config_aws_set_signed_body_value($signing_config, $signed_body_value) {
self::$impl->aws_crt_signing_config_aws_set_signed_body_value($signing_config, $signed_body_value);
}
function signing_config_aws_set_signed_body_header_type($signing_config, $signed_body_header_type) {
self::$impl->aws_crt_signing_config_aws_set_signed_body_header_type($signing_config, $signed_body_header_type);
}
function signing_config_aws_set_expiration_in_seconds($signing_config, $expiration_in_seconds) {
self::$impl->aws_crt_signing_config_aws_set_expiration_in_seconds($signing_config, $expiration_in_seconds);
}
function signing_config_aws_set_date($signing_config, $timestamp) {
self::$impl->aws_crt_signing_config_aws_set_date($signing_config, $timestamp);
}
function signing_config_aws_set_should_sign_header_fn($signing_config, $should_sign_header_fn) {
self::$impl->aws_crt_signing_config_aws_set_should_sign_header_fn($signing_config, $should_sign_header_fn);
}
function signable_new_from_http_request($http_message) {
return self::$impl->aws_crt_signable_new_from_http_request($http_message);
}
function signable_new_from_chunk($chunk_stream, $previous_signature) {
return self::$impl->aws_crt_signable_new_from_chunk($chunk_stream, $previous_signature);
}
function signable_new_from_canonical_request($canonical_request) {
return self::$impl->aws_crt_signable_new_from_canonical_request($canonical_request);
}
function signable_release($signable) {
self::$impl->aws_crt_signable_release($signable);
}
function signing_result_release($signing_result) {
self::$impl->aws_crt_signing_result_release($signing_result);
}
function signing_result_apply_to_http_request($signing_result, $http_message) {
return self::$impl->aws_crt_signing_result_apply_to_http_request(
$signing_result, $http_message);
}
function sign_request_aws($signable, $signing_config, $on_complete, $user_data) {
return self::$impl->aws_crt_sign_request_aws($signable, $signing_config, $on_complete, $user_data);
}
function test_verify_sigv4a_signing($signable, $signing_config, $expected_canonical_request, $signature, $ecc_key_pub_x, $ecc_key_pub_y) {
return self::$impl->aws_crt_test_verify_sigv4a_signing($signable, $signing_config, $expected_canonical_request, $signature, $ecc_key_pub_x, $ecc_key_pub_y);
}
public static function crc32($input, $previous = 0) {
return self::$impl->aws_crt_crc32($input, $previous);
}
public static function crc32c($input, $previous = 0) {
return self::$impl->aws_crt_crc32c($input, $previous);
}
}

View File

@ -0,0 +1,50 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\HTTP;
use AWS\CRT\Internal\Encoding;
final class Headers {
private $headers;
public function __construct($headers = []) {
$this->headers = $headers;
}
public static function marshall($headers) {
$buf = "";
foreach ($headers->headers as $header => $value) {
$buf .= Encoding::encodeString($header);
$buf .= Encoding::encodeString($value);
}
return $buf;
}
public static function unmarshall($buf) {
$strings = Encoding::readStrings($buf);
$headers = [];
for ($idx = 0; $idx < count($strings);) {
$headers[$strings[$idx++]] = $strings[$idx++];
}
return new Headers($headers);
}
public function count() {
return count($this->headers);
}
public function get($header) {
return isset($this->headers[$header]) ? $this->headers[$header] : null;
}
public function set($header, $value) {
$this->headers[$header] = $value;
}
public function toArray() {
return $this->headers;
}
}

View File

@ -0,0 +1,95 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\HTTP;
use AWS\CRT\NativeResource;
use AWS\CRT\Internal\Encoding;
abstract class Message extends NativeResource {
private $method;
private $path;
private $query;
private $headers;
public function __construct($method, $path, $query = [], $headers = []) {
parent::__construct();
$this->method = $method;
$this->path = $path;
$this->query = $query;
$this->headers = new Headers($headers);
$this->acquire(self::$crt->http_message_new_from_blob(self::marshall($this)));
}
public function __destruct() {
self::$crt->http_message_release($this->release());
parent::__destruct();
}
public function toBlob() {
return self::$crt->http_message_to_blob($this->native);
}
protected static function marshall($msg) {
$buf = "";
$buf .= Encoding::encodeString($msg->method);
$buf .= Encoding::encodeString($msg->pathAndQuery());
$buf .= Headers::marshall($msg->headers);
return $buf;
}
protected static function _unmarshall($buf, $class=Message::class) {
$method = Encoding::readString($buf);
$path_and_query = Encoding::readString($buf);
$parts = explode("?", $path_and_query, 2);
$path = isset($parts[0]) ? $parts[0] : "";
$query = isset($parts[1]) ? $parts[1] : "";
$headers = Headers::unmarshall($buf);
// Turn query params back into a dictionary
if (strlen($query)) {
$query = rawurldecode($query);
$query = explode("&", $query);
$query = array_reduce($query, function($params, $pair) {
list($param, $value) = explode("=", $pair, 2);
$params[$param] = $value;
return $params;
}, []);
} else {
$query = [];
}
return new $class($method, $path, $query, $headers->toArray());
}
public function pathAndQuery() {
$path = $this->path;
$queries = [];
foreach ($this->query as $param => $value) {
$queries []= urlencode($param) . "=" . urlencode($value);
}
$query = implode("&", $queries);
if (strlen($query)) {
$path = implode("?", [$path, $query]);
}
return $path;
}
public function method() {
return $this->method;
}
public function path() {
return $this->path;
}
public function query() {
return $this->query;
}
public function headers() {
return $this->headers;
}
}

View File

@ -0,0 +1,32 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\HTTP;
use AWS\CRT\IO\InputStream;
class Request extends Message {
private $body_stream = null;
public function __construct($method, $path, $query = [], $headers = [], $body_stream = null) {
parent::__construct($method, $path, $query, $headers);
if (!is_null($body_stream) && !($body_stream instanceof InputStream)) {
throw new \InvalidArgumentException('body_stream must be an instance of ' . InputStream::class);
}
$this->body_stream = $body_stream;
}
public static function marshall($request) {
return parent::marshall($request);
}
public static function unmarshall($buf) {
return parent::_unmarshall($buf, Request::class);
}
public function body_stream() {
return $this->body_stream;
}
}

View File

@ -0,0 +1,27 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\HTTP;
class Response extends Message {
private $status_code;
public function __construct($method, $path, $query, $headers, $status_code) {
parent::__construct($method, $path, $query, $headers);
$this->status_code = $status_code;
}
public static function marshall($response) {
return parent::marshall($response);
}
public static function unmarshall($buf) {
return parent::_unmarshall($buf, Response::class);
}
public function status_code() {
return $this->status_code;
}
}

View File

@ -0,0 +1,39 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\IO;
use AWS\CRT\NativeResource as NativeResource;
use AWS\CRT\Options as Options;
/**
* Represents 1 or more event loops (1 per thread) for doing I/O and background tasks.
* Typically, every application has one EventLoopGroup.
*
* @param array options:
* - int num_threads - Number of worker threads in the EventLoopGroup. Defaults to 0/1 per logical core.
*/
final class EventLoopGroup extends NativeResource {
static function defaults() {
return [
'max_threads' => 0,
];
}
function __construct(array $options = []) {
parent::__construct();
$options = new Options($options, self::defaults());
$elg_options = self::$crt->event_loop_group_options_new();
self::$crt->event_loop_group_options_set_max_threads($elg_options, $options->getInt('max_threads'));
$this->acquire(self::$crt->event_loop_group_new($elg_options));
self::$crt->event_loop_group_options_release($elg_options);
}
function __destruct() {
self::$crt->event_loop_group_release($this->release());
parent::__destruct();
}
}

View File

@ -0,0 +1,50 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\IO;
use AWS\CRT\NativeResource as NativeResource;
final class InputStream extends NativeResource {
private $stream = null;
const SEEK_BEGIN = 0;
const SEEK_END = 2;
public function __construct($stream) {
parent::__construct();
$this->stream = $stream;
$options = self::$crt->input_stream_options_new();
// The stream implementation in native just converts the PHP stream into
// a native php_stream* and executes operations entirely in native
self::$crt->input_stream_options_set_user_data($options, $stream);
$this->acquire(self::$crt->input_stream_new($options));
self::$crt->input_stream_options_release($options);
}
public function __destruct() {
$this->release();
parent::__destruct();
}
public function eof() {
return self::$crt->input_stream_eof($this->native);
}
public function length() {
return self::$crt->input_stream_get_length($this->native);
}
public function read($length = 0) {
if ($length == 0) {
$length = $this->length();
}
return self::$crt->input_stream_read($this->native, $length);
}
public function seek($offset, $basis) {
return self::$crt->input_stream_seek($this->native, $offset, $basis);
}
}

View File

@ -0,0 +1,37 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Internal;
final class Encoding {
public static function readString(&$buffer) {
list($len, $str) = self::decodeString($buffer);
// Advance by sizeof(length) + strlen(str)
$buffer = substr($buffer, 4 + $len);
return $str;
}
public static function readStrings($buffer) {
$strings = [];
while (strlen($buffer)) {
$strings []= self::readString($buffer);
}
return $strings;
}
public static function decodeString($buffer) {
$len = unpack("N", $buffer)[1];
$buffer = substr($buffer, 4);
$str = unpack("a{$len}", $buffer)[1];
return [$len, $str];
}
public static function encodeString($str) {
if (is_array($str)) {
$str = $str[0];
}
return pack("Na*", strlen($str), $str);
}
}

View File

@ -0,0 +1,29 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT\Internal;
use \RuntimeException;
/**
* @internal
* Forwards calls on to awscrt PHP extension functions
*/
final class Extension {
function __construct() {
if (!extension_loaded('awscrt')) {
throw new RuntimeException('awscrt extension is not loaded');
}
}
/**
* Forwards any call made on this object to the extension function of the
* same name with the supplied arguments. Argument type hinting and checking
* occurs at the CRT wrapper.
*/
function __call($name, $args) {
return call_user_func_array($name, $args);
}
}

View File

@ -0,0 +1,47 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT;
use AWS\CRT\CRT;
final class Log {
const NONE = 0;
const FATAL = 1;
const ERROR = 2;
const WARN = 3;
const INFO = 4;
const DEBUG = 5;
const TRACE = 6;
public static function toStdout() {
CRT::log_to_stdout();
}
public static function toStderr() {
CRT::log_to_stderr();
}
public static function toFile($filename) {
CRT::log_to_file($filename);
}
public static function toStream($stream) {
assert(get_resource_type($stream) == "stream");
CRT::log_to_stream($stream);
}
public static function stop() {
CRT::log_stop();
}
public static function setLogLevel($level) {
assert($level >= self::NONE && $level <= self::TRACE);
CRT::log_set_level($level);
}
public static function log($level, $message) {
CRT::log_message($level, $message);
}
}

View File

@ -0,0 +1,42 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT;
use AWS\CRT\CRT as CRT;
/**
* Base class for all native resources, tracks all outstanding resources
* and provides basic leak checking
*/
abstract class NativeResource {
protected static $crt = null;
protected static $resources = [];
protected $native = null;
protected function __construct() {
if (is_null(self::$crt)) {
self::$crt = new CRT();
}
self::$resources[spl_object_hash($this)] = 1;
}
protected function acquire($handle) {
return $this->native = $handle;
}
protected function release() {
$native = $this->native;
$this->native = null;
return $native;
}
function __destruct() {
// Should have been destroyed and released by derived resource
assert($this->native == null);
unset(self::$resources[spl_object_hash($this)]);
}
}

View File

@ -0,0 +1,77 @@
<?php
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
namespace AWS\CRT;
final class OptionValue {
private $value;
function __construct($value) {
$this->value = $value;
}
public function asObject() {
return $this->value;
}
public function asMixed() {
return $this->value;
}
public function asInt() {
return empty($this->value) ? 0 : (int)$this->value;
}
public function asBool() {
return boolval($this->value);
}
public function asString() {
return !empty($this->value) ? strval($this->value) : "";
}
public function asArray() {
return is_array($this->value) ? $this->value : (!empty($this->value) ? [$this->value] : []);
}
public function asCallable() {
return is_callable($this->value) ? $this->value : null;
}
}
final class Options {
private $options;
public function __construct($opts = [], $defaults = []) {
$this->options = array_replace($defaults, empty($opts) ? [] : $opts);
}
public function __get($name) {
return $this->get($name);
}
public function asArray() {
return $this->options;
}
public function toArray() {
return array_merge_recursive([], $this->options);
}
public function get($name) {
return new OptionValue($this->options[$name]);
}
public function getInt($name) {
return $this->get($name)->asInt();
}
public function getString($name) {
return $this->get($name)->asString();
}
public function getBool($name) {
return $this->get($name)->asBool();
}
}

View File

@ -0,0 +1,4 @@
## Code of Conduct
This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
opensource-codeofconduct@amazon.com with any additional questions or comments.

View File

@ -0,0 +1,4 @@
## Building and enabling the Common Run Time
1. **Follow instructions on crt repo** Clone and build the repo as shown [here][https://github.com/awslabs/aws-crt-php].
1. **Enable the CRT** add the following line to your php.ini file `extension=path/to/aws-crt-php/modules/awscrt.so`

141
vendor/aws/aws-sdk-php/LICENSE vendored Normal file
View File

@ -0,0 +1,141 @@
# Apache License
Version 2.0, January 2004
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
## 1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1
through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the
License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled
by, or are under common control with that entity. For the purposes of this definition, "control" means
(i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract
or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software
source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form,
including but not limited to compiled object code, generated documentation, and conversions to other media
types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License,
as indicated by a copyright notice that is included in or attached to the work (an example is provided in the
Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from)
the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent,
as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not
include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work
and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any
modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to
Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to
submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of
electronic, verbal, or written communication sent to the Licensor or its representatives, including but not
limited to communication on electronic mailing lists, source code control systems, and issue tracking systems
that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been
received by Licensor and subsequently incorporated within the Work.
## 2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare
Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
## 3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent
license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such
license applies only to those patent claims licensable by such Contributor that are necessarily infringed by
their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such
Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim
or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work
constitutes direct or contributory patent infringement, then any patent licenses granted to You under this
License for that Work shall terminate as of the date such litigation is filed.
## 4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You meet the following conditions:
1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
2. You must cause any modified files to carry prominent notices stating that You changed the files; and
3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent,
trademark, and attribution notices from the Source form of the Work, excluding those notices that do
not pertain to any part of the Derivative Works; and
4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that
You distribute must include a readable copy of the attribution notices contained within such NOTICE
file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed as part of the Derivative Works; within
the Source form or documentation, if provided along with the Derivative Works; or, within a display
generated by the Derivative Works, if and wherever such third-party notices normally appear. The
contents of the NOTICE file are for informational purposes only and do not modify the License. You may
add Your own attribution notices within Derivative Works that You distribute, alongside or as an
addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be
construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license
terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative
Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the
conditions stated in this License.
## 5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by
You to the Licensor shall be under the terms and conditions of this License, without any additional terms or
conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate
license agreement you may have executed with Licensor regarding such Contributions.
## 6. Trademarks.
This License does not grant permission to use the trade names, trademarks, service marks, or product names of
the Licensor, except as required for reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
## 7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor
provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
## 8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless
required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any
Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential
damages of any character arising as a result of this License or out of the use or inability to use the Work
(including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has been advised of the possibility
of such damages.
## 9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole
responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold
each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

17
vendor/aws/aws-sdk-php/NOTICE vendored Normal file
View File

@ -0,0 +1,17 @@
# AWS SDK for PHP
<http://aws.amazon.com/php>
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,84 @@
The AWS SDK for PHP includes the following third-party software/licensing:
** Guzzle - https://github.com/guzzle/guzzle
Copyright (c) 2014 Michael Dowling, https://github.com/mtdowling
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
----------------
** jmespath.php - https://github.com/mtdowling/jmespath.php
Copyright (c) 2014 Michael Dowling, https://github.com/mtdowling
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
----------------
** phpunit-mock-objects -- https://github.com/sebastianbergmann/phpunit-mock-objects
Copyright (c) 2002-2018, Sebastian Bergmann <sebastian@phpunit.de>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Sebastian Bergmann nor the names of his
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

73
vendor/aws/aws-sdk-php/composer.json vendored Normal file
View File

@ -0,0 +1,73 @@
{
"name": "aws/aws-sdk-php",
"homepage": "http://aws.amazon.com/sdkforphp",
"description": "AWS SDK for PHP - Use Amazon Web Services in your PHP project",
"keywords": ["aws","amazon","sdk","s3","ec2","dynamodb","cloud","glacier"],
"type": "library",
"license": "Apache-2.0",
"authors": [
{
"name": "Amazon Web Services",
"homepage": "http://aws.amazon.com"
}
],
"support": {
"forum": "https://github.com/aws/aws-sdk-php/discussions",
"issues": "https://github.com/aws/aws-sdk-php/issues"
},
"require": {
"php": ">=8.1",
"guzzlehttp/guzzle": "^7.4.5",
"guzzlehttp/psr7": "^2.4.5",
"guzzlehttp/promises": "^2.0",
"mtdowling/jmespath.php": "^2.8.0",
"ext-pcre": "*",
"ext-json": "*",
"ext-simplexml": "*",
"aws/aws-crt-php": "^1.2.3",
"psr/http-message": "^1.0 || ^2.0",
"symfony/filesystem": "^v5.4.45 || ^v6.4.3 || ^v7.1.0 || ^v8.0.0"
},
"require-dev": {
"composer/composer" : "^2.7.8",
"ext-openssl": "*",
"ext-dom": "*",
"ext-sockets": "*",
"phpunit/phpunit": "^9.6",
"behat/behat": "~3.0",
"doctrine/cache": "~1.4",
"aws/aws-php-sns-message-validator": "~1.0",
"andrewsville/php-token-reflection": "^1.4",
"psr/cache": "^2.0 || ^3.0",
"psr/simple-cache": "^2.0 || ^3.0",
"sebastian/comparator": "^1.2.3 || ^4.0 || ^5.0",
"yoast/phpunit-polyfills": "^2.0",
"dms/phpunit-arraysubset-asserts": "^0.4.0"
},
"suggest": {
"ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages",
"ext-curl": "To send requests using cURL",
"ext-sockets": "To use client-side monitoring",
"ext-pcntl": "To use client-side monitoring",
"doctrine/cache": "To use the DoctrineCacheAdapter",
"aws/aws-php-sns-message-validator": "To validate incoming SNS notifications"
},
"autoload": {
"psr-4": {
"Aws\\": "src/"
},
"files": ["src/functions.php"],
"exclude-from-classmap": ["src/data/"]
},
"autoload-dev": {
"psr-4": {
"Aws\\Test\\": "tests/"
},
"classmap": ["build/"]
},
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
}
}

View File

@ -0,0 +1,55 @@
<?php
namespace Aws\ACMPCA;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS Certificate Manager Private Certificate Authority** service.
* @method \Aws\Result createCertificateAuthority(array $args = [])
* @method \GuzzleHttp\Promise\Promise createCertificateAuthorityAsync(array $args = [])
* @method \Aws\Result createCertificateAuthorityAuditReport(array $args = [])
* @method \GuzzleHttp\Promise\Promise createCertificateAuthorityAuditReportAsync(array $args = [])
* @method \Aws\Result createPermission(array $args = [])
* @method \GuzzleHttp\Promise\Promise createPermissionAsync(array $args = [])
* @method \Aws\Result deleteCertificateAuthority(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteCertificateAuthorityAsync(array $args = [])
* @method \Aws\Result deletePermission(array $args = [])
* @method \GuzzleHttp\Promise\Promise deletePermissionAsync(array $args = [])
* @method \Aws\Result deletePolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise deletePolicyAsync(array $args = [])
* @method \Aws\Result describeCertificateAuthority(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeCertificateAuthorityAsync(array $args = [])
* @method \Aws\Result describeCertificateAuthorityAuditReport(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeCertificateAuthorityAuditReportAsync(array $args = [])
* @method \Aws\Result getCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCertificateAsync(array $args = [])
* @method \Aws\Result getCertificateAuthorityCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCertificateAuthorityCertificateAsync(array $args = [])
* @method \Aws\Result getCertificateAuthorityCsr(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCertificateAuthorityCsrAsync(array $args = [])
* @method \Aws\Result getPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPolicyAsync(array $args = [])
* @method \Aws\Result importCertificateAuthorityCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise importCertificateAuthorityCertificateAsync(array $args = [])
* @method \Aws\Result issueCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise issueCertificateAsync(array $args = [])
* @method \Aws\Result listCertificateAuthorities(array $args = [])
* @method \GuzzleHttp\Promise\Promise listCertificateAuthoritiesAsync(array $args = [])
* @method \Aws\Result listPermissions(array $args = [])
* @method \GuzzleHttp\Promise\Promise listPermissionsAsync(array $args = [])
* @method \Aws\Result listTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsAsync(array $args = [])
* @method \Aws\Result putPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putPolicyAsync(array $args = [])
* @method \Aws\Result restoreCertificateAuthority(array $args = [])
* @method \GuzzleHttp\Promise\Promise restoreCertificateAuthorityAsync(array $args = [])
* @method \Aws\Result revokeCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise revokeCertificateAsync(array $args = [])
* @method \Aws\Result tagCertificateAuthority(array $args = [])
* @method \GuzzleHttp\Promise\Promise tagCertificateAuthorityAsync(array $args = [])
* @method \Aws\Result untagCertificateAuthority(array $args = [])
* @method \GuzzleHttp\Promise\Promise untagCertificateAuthorityAsync(array $args = [])
* @method \Aws\Result updateCertificateAuthority(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateCertificateAuthorityAsync(array $args = [])
*/
class ACMPCAClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\ACMPCA\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS Certificate Manager Private Certificate Authority** service.
*/
class ACMPCAException extends AwsException {}

View File

@ -0,0 +1,31 @@
<?php
namespace Aws\AIOps;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS AI Ops** service.
* @method \Aws\Result createInvestigationGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise createInvestigationGroupAsync(array $args = [])
* @method \Aws\Result deleteInvestigationGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteInvestigationGroupAsync(array $args = [])
* @method \Aws\Result deleteInvestigationGroupPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteInvestigationGroupPolicyAsync(array $args = [])
* @method \Aws\Result getInvestigationGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise getInvestigationGroupAsync(array $args = [])
* @method \Aws\Result getInvestigationGroupPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise getInvestigationGroupPolicyAsync(array $args = [])
* @method \Aws\Result listInvestigationGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise listInvestigationGroupsAsync(array $args = [])
* @method \Aws\Result listTagsForResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsForResourceAsync(array $args = [])
* @method \Aws\Result putInvestigationGroupPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putInvestigationGroupPolicyAsync(array $args = [])
* @method \Aws\Result tagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise tagResourceAsync(array $args = [])
* @method \Aws\Result untagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise untagResourceAsync(array $args = [])
* @method \Aws\Result updateInvestigationGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateInvestigationGroupAsync(array $args = [])
*/
class AIOpsClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\AIOps\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS AI Ops** service.
*/
class AIOpsException extends AwsException {}

View File

@ -0,0 +1,51 @@
<?php
namespace Aws\ARCRegionSwitch;
use Aws\AwsClient;
/**
* This client is used to interact with the **ARC - Region switch** service.
* @method \Aws\Result approvePlanExecutionStep(array $args = [])
* @method \GuzzleHttp\Promise\Promise approvePlanExecutionStepAsync(array $args = [])
* @method \Aws\Result cancelPlanExecution(array $args = [])
* @method \GuzzleHttp\Promise\Promise cancelPlanExecutionAsync(array $args = [])
* @method \Aws\Result createPlan(array $args = [])
* @method \GuzzleHttp\Promise\Promise createPlanAsync(array $args = [])
* @method \Aws\Result deletePlan(array $args = [])
* @method \GuzzleHttp\Promise\Promise deletePlanAsync(array $args = [])
* @method \Aws\Result getPlan(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPlanAsync(array $args = [])
* @method \Aws\Result getPlanEvaluationStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPlanEvaluationStatusAsync(array $args = [])
* @method \Aws\Result getPlanExecution(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPlanExecutionAsync(array $args = [])
* @method \Aws\Result getPlanInRegion(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPlanInRegionAsync(array $args = [])
* @method \Aws\Result listPlanExecutionEvents(array $args = [])
* @method \GuzzleHttp\Promise\Promise listPlanExecutionEventsAsync(array $args = [])
* @method \Aws\Result listPlanExecutions(array $args = [])
* @method \GuzzleHttp\Promise\Promise listPlanExecutionsAsync(array $args = [])
* @method \Aws\Result listPlans(array $args = [])
* @method \GuzzleHttp\Promise\Promise listPlansAsync(array $args = [])
* @method \Aws\Result listPlansInRegion(array $args = [])
* @method \GuzzleHttp\Promise\Promise listPlansInRegionAsync(array $args = [])
* @method \Aws\Result listRoute53HealthChecks(array $args = [])
* @method \GuzzleHttp\Promise\Promise listRoute53HealthChecksAsync(array $args = [])
* @method \Aws\Result listRoute53HealthChecksInRegion(array $args = [])
* @method \GuzzleHttp\Promise\Promise listRoute53HealthChecksInRegionAsync(array $args = [])
* @method \Aws\Result listTagsForResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsForResourceAsync(array $args = [])
* @method \Aws\Result startPlanExecution(array $args = [])
* @method \GuzzleHttp\Promise\Promise startPlanExecutionAsync(array $args = [])
* @method \Aws\Result tagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise tagResourceAsync(array $args = [])
* @method \Aws\Result untagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise untagResourceAsync(array $args = [])
* @method \Aws\Result updatePlan(array $args = [])
* @method \GuzzleHttp\Promise\Promise updatePlanAsync(array $args = [])
* @method \Aws\Result updatePlanExecution(array $args = [])
* @method \GuzzleHttp\Promise\Promise updatePlanExecutionAsync(array $args = [])
* @method \Aws\Result updatePlanExecutionStep(array $args = [])
* @method \GuzzleHttp\Promise\Promise updatePlanExecutionStepAsync(array $args = [])
*/
class ARCRegionSwitchClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\ARCRegionSwitch\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **ARC - Region switch** service.
*/
class ARCRegionSwitchException extends AwsException {}

View File

@ -0,0 +1,39 @@
<?php
namespace Aws\ARCZonalShift;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS ARC - Zonal Shift** service.
* @method \Aws\Result cancelPracticeRun(array $args = [])
* @method \GuzzleHttp\Promise\Promise cancelPracticeRunAsync(array $args = [])
* @method \Aws\Result cancelZonalShift(array $args = [])
* @method \GuzzleHttp\Promise\Promise cancelZonalShiftAsync(array $args = [])
* @method \Aws\Result createPracticeRunConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise createPracticeRunConfigurationAsync(array $args = [])
* @method \Aws\Result deletePracticeRunConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise deletePracticeRunConfigurationAsync(array $args = [])
* @method \Aws\Result getAutoshiftObserverNotificationStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAutoshiftObserverNotificationStatusAsync(array $args = [])
* @method \Aws\Result getManagedResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise getManagedResourceAsync(array $args = [])
* @method \Aws\Result listAutoshifts(array $args = [])
* @method \GuzzleHttp\Promise\Promise listAutoshiftsAsync(array $args = [])
* @method \Aws\Result listManagedResources(array $args = [])
* @method \GuzzleHttp\Promise\Promise listManagedResourcesAsync(array $args = [])
* @method \Aws\Result listZonalShifts(array $args = [])
* @method \GuzzleHttp\Promise\Promise listZonalShiftsAsync(array $args = [])
* @method \Aws\Result startPracticeRun(array $args = [])
* @method \GuzzleHttp\Promise\Promise startPracticeRunAsync(array $args = [])
* @method \Aws\Result startZonalShift(array $args = [])
* @method \GuzzleHttp\Promise\Promise startZonalShiftAsync(array $args = [])
* @method \Aws\Result updateAutoshiftObserverNotificationStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateAutoshiftObserverNotificationStatusAsync(array $args = [])
* @method \Aws\Result updatePracticeRunConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise updatePracticeRunConfigurationAsync(array $args = [])
* @method \Aws\Result updateZonalAutoshiftConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateZonalAutoshiftConfigurationAsync(array $args = [])
* @method \Aws\Result updateZonalShift(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateZonalShiftAsync(array $args = [])
*/
class ARCZonalShiftClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\ARCZonalShift\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS ARC - Zonal Shift** service.
*/
class ARCZonalShiftException extends AwsException {}

View File

@ -0,0 +1,157 @@
<?php
namespace Aws;
use GuzzleHttp\Promise;
/**
* A configuration provider is a function that returns a promise that is
* fulfilled with a configuration object. This class provides base functionality
* usable by specific configuration provider implementations
*/
abstract class AbstractConfigurationProvider
{
const ENV_PROFILE = 'AWS_PROFILE';
const ENV_CONFIG_FILE = 'AWS_CONFIG_FILE';
public static $cacheKey;
protected static $interfaceClass;
protected static $exceptionClass;
/**
* Wraps a config provider and saves provided configuration in an
* instance of Aws\CacheInterface. Forwards calls when no config found
* in cache and updates cache with the results.
*
* @param callable $provider Configuration provider function to wrap
* @param CacheInterface $cache Cache to store configuration
* @param string|null $cacheKey (optional) Cache key to use
*
* @return callable
*/
public static function cache(
callable $provider,
CacheInterface $cache,
$cacheKey = null
) {
$cacheKey = $cacheKey ?: static::$cacheKey;
return function () use ($provider, $cache, $cacheKey) {
$found = $cache->get($cacheKey);
if ($found instanceof static::$interfaceClass) {
return Promise\Create::promiseFor($found);
}
return $provider()
->then(function ($config) use (
$cache,
$cacheKey
) {
$cache->set($cacheKey, $config);
return $config;
});
};
}
/**
* Creates an aggregate configuration provider that invokes the provided
* variadic providers one after the other until a provider returns
* configuration.
*
* @return callable
*/
public static function chain()
{
$links = func_get_args();
if (empty($links)) {
throw new \InvalidArgumentException('No providers in chain');
}
return function () use ($links) {
/** @var callable $parent */
$parent = array_shift($links);
$promise = $parent();
while ($next = array_shift($links)) {
$promise = $promise->otherwise($next);
}
return $promise;
};
}
/**
* Gets the environment's HOME directory if available.
*
* @return null|string
*/
protected static function getHomeDir()
{
// On Linux/Unix-like systems, use the HOME environment variable
if ($homeDir = getenv('HOME')) {
return $homeDir;
}
// Get the HOMEDRIVE and HOMEPATH values for Windows hosts
$homeDrive = getenv('HOMEDRIVE');
$homePath = getenv('HOMEPATH');
return ($homeDrive && $homePath) ? $homeDrive . $homePath : null;
}
/**
* Gets default config file location from environment, falling back to aws
* default location
*
* @return string
*/
protected static function getDefaultConfigFilename()
{
if ($filename = getenv(self::ENV_CONFIG_FILE)) {
return $filename;
}
return self::getHomeDir() . '/.aws/config';
}
/**
* Wraps a config provider and caches previously provided configuration.
*
* @param callable $provider Config provider function to wrap.
*
* @return callable
*/
public static function memoize(callable $provider)
{
return function () use ($provider) {
static $result;
static $isConstant;
// Constant config will be returned constantly.
if ($isConstant) {
return $result;
}
// Create the initial promise that will be used as the cached value
if (null === $result) {
$result = $provider();
}
// Return config and set flag that provider is already set
return $result
->then(function ($config) use (&$isConstant) {
$isConstant = true;
return $config;
});
};
}
/**
* Reject promise with standardized exception.
*
* @param $msg
* @return Promise\RejectedPromise
*/
protected static function reject($msg)
{
$exceptionClass = static::$exceptionClass;
return new Promise\RejectedPromise(new $exceptionClass($msg));
}
}

View File

@ -0,0 +1,83 @@
<?php
namespace Aws\AccessAnalyzer;
use Aws\AwsClient;
/**
* This client is used to interact with the **Access Analyzer** service.
* @method \Aws\Result applyArchiveRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise applyArchiveRuleAsync(array $args = [])
* @method \Aws\Result cancelPolicyGeneration(array $args = [])
* @method \GuzzleHttp\Promise\Promise cancelPolicyGenerationAsync(array $args = [])
* @method \Aws\Result checkAccessNotGranted(array $args = [])
* @method \GuzzleHttp\Promise\Promise checkAccessNotGrantedAsync(array $args = [])
* @method \Aws\Result checkNoNewAccess(array $args = [])
* @method \GuzzleHttp\Promise\Promise checkNoNewAccessAsync(array $args = [])
* @method \Aws\Result checkNoPublicAccess(array $args = [])
* @method \GuzzleHttp\Promise\Promise checkNoPublicAccessAsync(array $args = [])
* @method \Aws\Result createAccessPreview(array $args = [])
* @method \GuzzleHttp\Promise\Promise createAccessPreviewAsync(array $args = [])
* @method \Aws\Result createAnalyzer(array $args = [])
* @method \GuzzleHttp\Promise\Promise createAnalyzerAsync(array $args = [])
* @method \Aws\Result createArchiveRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise createArchiveRuleAsync(array $args = [])
* @method \Aws\Result deleteAnalyzer(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAnalyzerAsync(array $args = [])
* @method \Aws\Result deleteArchiveRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteArchiveRuleAsync(array $args = [])
* @method \Aws\Result generateFindingRecommendation(array $args = [])
* @method \GuzzleHttp\Promise\Promise generateFindingRecommendationAsync(array $args = [])
* @method \Aws\Result getAccessPreview(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccessPreviewAsync(array $args = [])
* @method \Aws\Result getAnalyzedResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAnalyzedResourceAsync(array $args = [])
* @method \Aws\Result getAnalyzer(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAnalyzerAsync(array $args = [])
* @method \Aws\Result getArchiveRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise getArchiveRuleAsync(array $args = [])
* @method \Aws\Result getFinding(array $args = [])
* @method \GuzzleHttp\Promise\Promise getFindingAsync(array $args = [])
* @method \Aws\Result getFindingRecommendation(array $args = [])
* @method \GuzzleHttp\Promise\Promise getFindingRecommendationAsync(array $args = [])
* @method \Aws\Result getFindingV2(array $args = [])
* @method \GuzzleHttp\Promise\Promise getFindingV2Async(array $args = [])
* @method \Aws\Result getFindingsStatistics(array $args = [])
* @method \GuzzleHttp\Promise\Promise getFindingsStatisticsAsync(array $args = [])
* @method \Aws\Result getGeneratedPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise getGeneratedPolicyAsync(array $args = [])
* @method \Aws\Result listAccessPreviewFindings(array $args = [])
* @method \GuzzleHttp\Promise\Promise listAccessPreviewFindingsAsync(array $args = [])
* @method \Aws\Result listAccessPreviews(array $args = [])
* @method \GuzzleHttp\Promise\Promise listAccessPreviewsAsync(array $args = [])
* @method \Aws\Result listAnalyzedResources(array $args = [])
* @method \GuzzleHttp\Promise\Promise listAnalyzedResourcesAsync(array $args = [])
* @method \Aws\Result listAnalyzers(array $args = [])
* @method \GuzzleHttp\Promise\Promise listAnalyzersAsync(array $args = [])
* @method \Aws\Result listArchiveRules(array $args = [])
* @method \GuzzleHttp\Promise\Promise listArchiveRulesAsync(array $args = [])
* @method \Aws\Result listFindings(array $args = [])
* @method \GuzzleHttp\Promise\Promise listFindingsAsync(array $args = [])
* @method \Aws\Result listFindingsV2(array $args = [])
* @method \GuzzleHttp\Promise\Promise listFindingsV2Async(array $args = [])
* @method \Aws\Result listPolicyGenerations(array $args = [])
* @method \GuzzleHttp\Promise\Promise listPolicyGenerationsAsync(array $args = [])
* @method \Aws\Result listTagsForResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsForResourceAsync(array $args = [])
* @method \Aws\Result startPolicyGeneration(array $args = [])
* @method \GuzzleHttp\Promise\Promise startPolicyGenerationAsync(array $args = [])
* @method \Aws\Result startResourceScan(array $args = [])
* @method \GuzzleHttp\Promise\Promise startResourceScanAsync(array $args = [])
* @method \Aws\Result tagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise tagResourceAsync(array $args = [])
* @method \Aws\Result untagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise untagResourceAsync(array $args = [])
* @method \Aws\Result updateAnalyzer(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateAnalyzerAsync(array $args = [])
* @method \Aws\Result updateArchiveRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateArchiveRuleAsync(array $args = [])
* @method \Aws\Result updateFindings(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateFindingsAsync(array $args = [])
* @method \Aws\Result validatePolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise validatePolicyAsync(array $args = [])
*/
class AccessAnalyzerClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\AccessAnalyzer\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **Access Analyzer** service.
*/
class AccessAnalyzerException extends AwsException {}

View File

@ -0,0 +1,39 @@
<?php
namespace Aws\Account;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS Account** service.
* @method \Aws\Result acceptPrimaryEmailUpdate(array $args = [])
* @method \GuzzleHttp\Promise\Promise acceptPrimaryEmailUpdateAsync(array $args = [])
* @method \Aws\Result deleteAlternateContact(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAlternateContactAsync(array $args = [])
* @method \Aws\Result disableRegion(array $args = [])
* @method \GuzzleHttp\Promise\Promise disableRegionAsync(array $args = [])
* @method \Aws\Result enableRegion(array $args = [])
* @method \GuzzleHttp\Promise\Promise enableRegionAsync(array $args = [])
* @method \Aws\Result getAccountInformation(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccountInformationAsync(array $args = [])
* @method \Aws\Result getAlternateContact(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAlternateContactAsync(array $args = [])
* @method \Aws\Result getContactInformation(array $args = [])
* @method \GuzzleHttp\Promise\Promise getContactInformationAsync(array $args = [])
* @method \Aws\Result getGovCloudAccountInformation(array $args = [])
* @method \GuzzleHttp\Promise\Promise getGovCloudAccountInformationAsync(array $args = [])
* @method \Aws\Result getPrimaryEmail(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPrimaryEmailAsync(array $args = [])
* @method \Aws\Result getRegionOptStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise getRegionOptStatusAsync(array $args = [])
* @method \Aws\Result listRegions(array $args = [])
* @method \GuzzleHttp\Promise\Promise listRegionsAsync(array $args = [])
* @method \Aws\Result putAccountName(array $args = [])
* @method \GuzzleHttp\Promise\Promise putAccountNameAsync(array $args = [])
* @method \Aws\Result putAlternateContact(array $args = [])
* @method \GuzzleHttp\Promise\Promise putAlternateContactAsync(array $args = [])
* @method \Aws\Result putContactInformation(array $args = [])
* @method \GuzzleHttp\Promise\Promise putContactInformationAsync(array $args = [])
* @method \Aws\Result startPrimaryEmailUpdate(array $args = [])
* @method \GuzzleHttp\Promise\Promise startPrimaryEmailUpdateAsync(array $args = [])
*/
class AccountClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\Account\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS Account** service.
*/
class AccountException extends AwsException {}

View File

@ -0,0 +1,42 @@
<?php
namespace Aws\Acm;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS Certificate Manager** service.
*
* @method \Aws\Result addTagsToCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise addTagsToCertificateAsync(array $args = [])
* @method \Aws\Result deleteCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteCertificateAsync(array $args = [])
* @method \Aws\Result describeCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeCertificateAsync(array $args = [])
* @method \Aws\Result exportCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise exportCertificateAsync(array $args = [])
* @method \Aws\Result getAccountConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccountConfigurationAsync(array $args = [])
* @method \Aws\Result getCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCertificateAsync(array $args = [])
* @method \Aws\Result importCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise importCertificateAsync(array $args = [])
* @method \Aws\Result listCertificates(array $args = [])
* @method \GuzzleHttp\Promise\Promise listCertificatesAsync(array $args = [])
* @method \Aws\Result listTagsForCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsForCertificateAsync(array $args = [])
* @method \Aws\Result putAccountConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise putAccountConfigurationAsync(array $args = [])
* @method \Aws\Result removeTagsFromCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise removeTagsFromCertificateAsync(array $args = [])
* @method \Aws\Result renewCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise renewCertificateAsync(array $args = [])
* @method \Aws\Result requestCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise requestCertificateAsync(array $args = [])
* @method \Aws\Result resendValidationEmail(array $args = [])
* @method \GuzzleHttp\Promise\Promise resendValidationEmailAsync(array $args = [])
* @method \Aws\Result revokeCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise revokeCertificateAsync(array $args = [])
* @method \Aws\Result updateCertificateOptions(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateCertificateOptionsAsync(array $args = [])
*/
class AcmClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\Acm\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS Certificate Manager** service.
*/
class AcmException extends AwsException {}

View File

@ -0,0 +1,83 @@
<?php
namespace Aws\Amplify;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS Amplify** service.
* @method \Aws\Result createApp(array $args = [])
* @method \GuzzleHttp\Promise\Promise createAppAsync(array $args = [])
* @method \Aws\Result createBackendEnvironment(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBackendEnvironmentAsync(array $args = [])
* @method \Aws\Result createBranch(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBranchAsync(array $args = [])
* @method \Aws\Result createDeployment(array $args = [])
* @method \GuzzleHttp\Promise\Promise createDeploymentAsync(array $args = [])
* @method \Aws\Result createDomainAssociation(array $args = [])
* @method \GuzzleHttp\Promise\Promise createDomainAssociationAsync(array $args = [])
* @method \Aws\Result createWebhook(array $args = [])
* @method \GuzzleHttp\Promise\Promise createWebhookAsync(array $args = [])
* @method \Aws\Result deleteApp(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAppAsync(array $args = [])
* @method \Aws\Result deleteBackendEnvironment(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBackendEnvironmentAsync(array $args = [])
* @method \Aws\Result deleteBranch(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBranchAsync(array $args = [])
* @method \Aws\Result deleteDomainAssociation(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDomainAssociationAsync(array $args = [])
* @method \Aws\Result deleteJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteJobAsync(array $args = [])
* @method \Aws\Result deleteWebhook(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteWebhookAsync(array $args = [])
* @method \Aws\Result generateAccessLogs(array $args = [])
* @method \GuzzleHttp\Promise\Promise generateAccessLogsAsync(array $args = [])
* @method \Aws\Result getApp(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAppAsync(array $args = [])
* @method \Aws\Result getArtifactUrl(array $args = [])
* @method \GuzzleHttp\Promise\Promise getArtifactUrlAsync(array $args = [])
* @method \Aws\Result getBackendEnvironment(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBackendEnvironmentAsync(array $args = [])
* @method \Aws\Result getBranch(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBranchAsync(array $args = [])
* @method \Aws\Result getDomainAssociation(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDomainAssociationAsync(array $args = [])
* @method \Aws\Result getJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise getJobAsync(array $args = [])
* @method \Aws\Result getWebhook(array $args = [])
* @method \GuzzleHttp\Promise\Promise getWebhookAsync(array $args = [])
* @method \Aws\Result listApps(array $args = [])
* @method \GuzzleHttp\Promise\Promise listAppsAsync(array $args = [])
* @method \Aws\Result listArtifacts(array $args = [])
* @method \GuzzleHttp\Promise\Promise listArtifactsAsync(array $args = [])
* @method \Aws\Result listBackendEnvironments(array $args = [])
* @method \GuzzleHttp\Promise\Promise listBackendEnvironmentsAsync(array $args = [])
* @method \Aws\Result listBranches(array $args = [])
* @method \GuzzleHttp\Promise\Promise listBranchesAsync(array $args = [])
* @method \Aws\Result listDomainAssociations(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDomainAssociationsAsync(array $args = [])
* @method \Aws\Result listJobs(array $args = [])
* @method \GuzzleHttp\Promise\Promise listJobsAsync(array $args = [])
* @method \Aws\Result listTagsForResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsForResourceAsync(array $args = [])
* @method \Aws\Result listWebhooks(array $args = [])
* @method \GuzzleHttp\Promise\Promise listWebhooksAsync(array $args = [])
* @method \Aws\Result startDeployment(array $args = [])
* @method \GuzzleHttp\Promise\Promise startDeploymentAsync(array $args = [])
* @method \Aws\Result startJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise startJobAsync(array $args = [])
* @method \Aws\Result stopJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise stopJobAsync(array $args = [])
* @method \Aws\Result tagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise tagResourceAsync(array $args = [])
* @method \Aws\Result untagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise untagResourceAsync(array $args = [])
* @method \Aws\Result updateApp(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateAppAsync(array $args = [])
* @method \Aws\Result updateBranch(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateBranchAsync(array $args = [])
* @method \Aws\Result updateDomainAssociation(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateDomainAssociationAsync(array $args = [])
* @method \Aws\Result updateWebhook(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateWebhookAsync(array $args = [])
*/
class AmplifyClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\Amplify\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS Amplify** service.
*/
class AmplifyException extends AwsException {}

View File

@ -0,0 +1,71 @@
<?php
namespace Aws\AmplifyBackend;
use Aws\AwsClient;
/**
* This client is used to interact with the **AmplifyBackend** service.
* @method \Aws\Result cloneBackend(array $args = [])
* @method \GuzzleHttp\Promise\Promise cloneBackendAsync(array $args = [])
* @method \Aws\Result createBackend(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBackendAsync(array $args = [])
* @method \Aws\Result createBackendAPI(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBackendAPIAsync(array $args = [])
* @method \Aws\Result createBackendAuth(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBackendAuthAsync(array $args = [])
* @method \Aws\Result createBackendConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBackendConfigAsync(array $args = [])
* @method \Aws\Result createBackendStorage(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBackendStorageAsync(array $args = [])
* @method \Aws\Result createToken(array $args = [])
* @method \GuzzleHttp\Promise\Promise createTokenAsync(array $args = [])
* @method \Aws\Result deleteBackend(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBackendAsync(array $args = [])
* @method \Aws\Result deleteBackendAPI(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBackendAPIAsync(array $args = [])
* @method \Aws\Result deleteBackendAuth(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBackendAuthAsync(array $args = [])
* @method \Aws\Result deleteBackendStorage(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBackendStorageAsync(array $args = [])
* @method \Aws\Result deleteToken(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteTokenAsync(array $args = [])
* @method \Aws\Result generateBackendAPIModels(array $args = [])
* @method \GuzzleHttp\Promise\Promise generateBackendAPIModelsAsync(array $args = [])
* @method \Aws\Result getBackend(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBackendAsync(array $args = [])
* @method \Aws\Result getBackendAPI(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBackendAPIAsync(array $args = [])
* @method \Aws\Result getBackendAPIModels(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBackendAPIModelsAsync(array $args = [])
* @method \Aws\Result getBackendAuth(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBackendAuthAsync(array $args = [])
* @method \Aws\Result getBackendJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBackendJobAsync(array $args = [])
* @method \Aws\Result getBackendStorage(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBackendStorageAsync(array $args = [])
* @method \Aws\Result getChallengeToken(array $args = [])
* @method \GuzzleHttp\Promise\Promise getChallengeTokenAsync(array $args = [])
* @method \Aws\Result importBackendAuth(array $args = [])
* @method \GuzzleHttp\Promise\Promise importBackendAuthAsync(array $args = [])
* @method \Aws\Result importBackendStorage(array $args = [])
* @method \GuzzleHttp\Promise\Promise importBackendStorageAsync(array $args = [])
* @method \Aws\Result listBackendJobs(array $args = [])
* @method \GuzzleHttp\Promise\Promise listBackendJobsAsync(array $args = [])
* @method \Aws\Result listS3Buckets(array $args = [])
* @method \GuzzleHttp\Promise\Promise listS3BucketsAsync(array $args = [])
* @method \Aws\Result removeAllBackends(array $args = [])
* @method \GuzzleHttp\Promise\Promise removeAllBackendsAsync(array $args = [])
* @method \Aws\Result removeBackendConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise removeBackendConfigAsync(array $args = [])
* @method \Aws\Result updateBackendAPI(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateBackendAPIAsync(array $args = [])
* @method \Aws\Result updateBackendAuth(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateBackendAuthAsync(array $args = [])
* @method \Aws\Result updateBackendConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateBackendConfigAsync(array $args = [])
* @method \Aws\Result updateBackendJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateBackendJobAsync(array $args = [])
* @method \Aws\Result updateBackendStorage(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateBackendStorageAsync(array $args = [])
*/
class AmplifyBackendClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\AmplifyBackend\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AmplifyBackend** service.
*/
class AmplifyBackendException extends AwsException {}

View File

@ -0,0 +1,65 @@
<?php
namespace Aws\AmplifyUIBuilder;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS Amplify UI Builder** service.
* @method \Aws\Result createComponent(array $args = [])
* @method \GuzzleHttp\Promise\Promise createComponentAsync(array $args = [])
* @method \Aws\Result createForm(array $args = [])
* @method \GuzzleHttp\Promise\Promise createFormAsync(array $args = [])
* @method \Aws\Result createTheme(array $args = [])
* @method \GuzzleHttp\Promise\Promise createThemeAsync(array $args = [])
* @method \Aws\Result deleteComponent(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteComponentAsync(array $args = [])
* @method \Aws\Result deleteForm(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteFormAsync(array $args = [])
* @method \Aws\Result deleteTheme(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteThemeAsync(array $args = [])
* @method \Aws\Result exchangeCodeForToken(array $args = [])
* @method \GuzzleHttp\Promise\Promise exchangeCodeForTokenAsync(array $args = [])
* @method \Aws\Result exportComponents(array $args = [])
* @method \GuzzleHttp\Promise\Promise exportComponentsAsync(array $args = [])
* @method \Aws\Result exportForms(array $args = [])
* @method \GuzzleHttp\Promise\Promise exportFormsAsync(array $args = [])
* @method \Aws\Result exportThemes(array $args = [])
* @method \GuzzleHttp\Promise\Promise exportThemesAsync(array $args = [])
* @method \Aws\Result getCodegenJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCodegenJobAsync(array $args = [])
* @method \Aws\Result getComponent(array $args = [])
* @method \GuzzleHttp\Promise\Promise getComponentAsync(array $args = [])
* @method \Aws\Result getForm(array $args = [])
* @method \GuzzleHttp\Promise\Promise getFormAsync(array $args = [])
* @method \Aws\Result getMetadata(array $args = [])
* @method \GuzzleHttp\Promise\Promise getMetadataAsync(array $args = [])
* @method \Aws\Result getTheme(array $args = [])
* @method \GuzzleHttp\Promise\Promise getThemeAsync(array $args = [])
* @method \Aws\Result listCodegenJobs(array $args = [])
* @method \GuzzleHttp\Promise\Promise listCodegenJobsAsync(array $args = [])
* @method \Aws\Result listComponents(array $args = [])
* @method \GuzzleHttp\Promise\Promise listComponentsAsync(array $args = [])
* @method \Aws\Result listForms(array $args = [])
* @method \GuzzleHttp\Promise\Promise listFormsAsync(array $args = [])
* @method \Aws\Result listTagsForResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsForResourceAsync(array $args = [])
* @method \Aws\Result listThemes(array $args = [])
* @method \GuzzleHttp\Promise\Promise listThemesAsync(array $args = [])
* @method \Aws\Result putMetadataFlag(array $args = [])
* @method \GuzzleHttp\Promise\Promise putMetadataFlagAsync(array $args = [])
* @method \Aws\Result refreshToken(array $args = [])
* @method \GuzzleHttp\Promise\Promise refreshTokenAsync(array $args = [])
* @method \Aws\Result startCodegenJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise startCodegenJobAsync(array $args = [])
* @method \Aws\Result tagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise tagResourceAsync(array $args = [])
* @method \Aws\Result untagResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise untagResourceAsync(array $args = [])
* @method \Aws\Result updateComponent(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateComponentAsync(array $args = [])
* @method \Aws\Result updateForm(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateFormAsync(array $args = [])
* @method \Aws\Result updateTheme(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateThemeAsync(array $args = [])
*/
class AmplifyUIBuilderClient extends AwsClient {}

View File

@ -0,0 +1,9 @@
<?php
namespace Aws\AmplifyUIBuilder\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS Amplify UI Builder** service.
*/
class AmplifyUIBuilderException extends AwsException {}

View File

@ -0,0 +1,89 @@
<?php
namespace Aws\Api;
/**
* Base class that is used by most API shapes
*/
abstract class AbstractModel implements \ArrayAccess
{
/** @var array */
protected $definition;
/** @var ShapeMap */
protected $shapeMap;
/** @var array */
protected $contextParam;
/**
* @param array $definition Service description
* @param ShapeMap $shapeMap Shapemap used for creating shapes
*/
public function __construct(array $definition, ShapeMap $shapeMap)
{
$this->definition = $definition;
$this->shapeMap = $shapeMap;
if (isset($definition['contextParam'])) {
$this->contextParam = $definition['contextParam'];
}
}
public function toArray()
{
return $this->definition;
}
/**
* @return mixed|null
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return isset($this->definition[$offset])
? $this->definition[$offset] : null;
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
$this->definition[$offset] = $value;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return isset($this->definition[$offset]);
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
unset($this->definition[$offset]);
}
protected function shapeAt($key)
{
if (!isset($this->definition[$key])) {
throw new \InvalidArgumentException('Expected shape definition at '
. $key);
}
return $this->shapeFor($this->definition[$key]);
}
protected function shapeFor(array $definition)
{
return isset($definition['shape'])
? $this->shapeMap->resolve($definition)
: Shape::create($definition, $this->shapeMap);
}
}

View File

@ -0,0 +1,244 @@
<?php
namespace Aws\Api;
use Aws\Exception\UnresolvedApiException;
/**
* API providers.
*
* An API provider is a function that accepts a type, service, and version and
* returns an array of API data on success or NULL if no API data can be created
* for the provided arguments.
*
* You can wrap your calls to an API provider with the
* {@see ApiProvider::resolve} method to ensure that API data is created. If the
* API data is not created, then the resolve() method will throw a
* {@see Aws\Exception\UnresolvedApiException}.
*
* use Aws\Api\ApiProvider;
* $provider = ApiProvider::defaultProvider();
* // Returns an array or NULL.
* $data = $provider('api', 's3', '2006-03-01');
* // Returns an array or throws.
* $data = ApiProvider::resolve($provider, 'api', 'elasticfood', '2020-01-01');
*
* You can compose multiple providers into a single provider using
* {@see Aws\or_chain}. This method accepts providers as arguments and
* returns a new function that will invoke each provider until a non-null value
* is returned.
*
* $a = ApiProvider::filesystem(sys_get_temp_dir() . '/aws-beta-models');
* $b = ApiProvider::manifest();
*
* $c = \Aws\or_chain($a, $b);
* $data = $c('api', 'betaservice', '2015-08-08'); // $a handles this.
* $data = $c('api', 's3', '2006-03-01'); // $b handles this.
* $data = $c('api', 'invalid', '2014-12-15'); // Neither handles this.
*/
class ApiProvider
{
/** @var array A map of public API type names to their file suffix. */
private static $typeMap = [
'api' => 'api-2',
'paginator' => 'paginators-1',
'waiter' => 'waiters-2',
'docs' => 'docs-2',
];
/** @var array API manifest */
private $manifest;
/** @var string The directory containing service models. */
private $modelsDir;
/**
* Resolves an API provider and ensures a non-null return value.
*
* @param callable $provider Provider function to invoke.
* @param string $type Type of data ('api', 'waiter', 'paginator').
* @param string $service Service name.
* @param string $version API version.
*
* @return array
* @throws UnresolvedApiException
*/
public static function resolve(callable $provider, $type, $service, $version)
{
// Execute the provider and return the result, if there is one.
$result = $provider($type, $service, $version);
if (is_array($result)) {
if (!isset($result['metadata']['serviceIdentifier'])) {
$result['metadata']['serviceIdentifier'] = $service;
}
return $result;
}
// Throw an exception with a message depending on the inputs.
if (!isset(self::$typeMap[$type])) {
$msg = "The type must be one of: " . implode(', ', self::$typeMap);
} elseif ($service) {
$msg = "The {$service} service does not have version: {$version}.";
} else {
$msg = "You must specify a service name to retrieve its API data.";
}
throw new UnresolvedApiException($msg);
}
/**
* Default SDK API provider.
*
* This provider loads pre-built manifest data from the `data` directory.
*
* @return self
*/
public static function defaultProvider()
{
return new self(__DIR__ . '/../data', \Aws\manifest());
}
/**
* Loads API data after resolving the version to the latest, compatible,
* available version based on the provided manifest data.
*
* Manifest data is essentially an associative array of service names to
* associative arrays of API version aliases.
*
* [
* ...
* 'ec2' => [
* 'latest' => '2014-10-01',
* '2014-10-01' => '2014-10-01',
* '2014-09-01' => '2014-10-01',
* '2014-06-15' => '2014-10-01',
* ...
* ],
* 'ecs' => [...],
* 'elasticache' => [...],
* ...
* ]
*
* @param string $dir Directory containing service models.
* @param array $manifest The API version manifest data.
*
* @return self
*/
public static function manifest($dir, array $manifest)
{
return new self($dir, $manifest);
}
/**
* Loads API data from the specified directory.
*
* If "latest" is specified as the version, this provider must glob the
* directory to find which is the latest available version.
*
* @param string $dir Directory containing service models.
*
* @return self
* @throws \InvalidArgumentException if the provided `$dir` is invalid.
*/
public static function filesystem($dir)
{
return new self($dir);
}
/**
* Retrieves a list of valid versions for the specified service.
*
* @param string $service Service name
*
* @return array
*/
public function getVersions($service)
{
if (!isset($this->manifest)) {
$this->buildVersionsList($service);
}
if (!isset($this->manifest[$service]['versions'])) {
return [];
}
return array_values(array_unique($this->manifest[$service]['versions']));
}
/**
* Execute the provider.
*
* @param string $type Type of data ('api', 'waiter', 'paginator').
* @param string $service Service name.
* @param string $version API version.
*
* @return array|null
*/
public function __invoke($type, $service, $version)
{
// Resolve the type or return null.
if (isset(self::$typeMap[$type])) {
$type = self::$typeMap[$type];
} else {
return null;
}
// Resolve the version or return null.
if (!isset($this->manifest)) {
$this->buildVersionsList($service);
}
if (!isset($this->manifest[$service]['versions'][$version])) {
return null;
}
$version = $this->manifest[$service]['versions'][$version];
$path = "{$this->modelsDir}/{$service}/{$version}/{$type}.json";
try {
return \Aws\load_compiled_json($path);
} catch (\InvalidArgumentException $e) {
return null;
}
}
/**
* @param string $modelsDir Directory containing service models.
* @param array $manifest The API version manifest data.
*/
private function __construct($modelsDir, ?array $manifest = null)
{
$this->manifest = $manifest;
$this->modelsDir = rtrim($modelsDir, '/');
if (!is_dir($this->modelsDir)) {
throw new \InvalidArgumentException(
"The specified models directory, {$modelsDir}, was not found."
);
}
}
/**
* Build the versions list for the specified service by globbing the dir.
*/
private function buildVersionsList($service)
{
$dir = "{$this->modelsDir}/{$service}/";
if (!is_dir($dir)) {
return;
}
// Get versions, remove . and .., and sort in descending order.
$results = array_diff(scandir($dir, SCANDIR_SORT_DESCENDING), ['..', '.']);
if (!$results) {
$this->manifest[$service] = ['versions' => []];
} else {
$this->manifest[$service] = [
'versions' => [
'latest' => $results[0]
]
];
$this->manifest[$service]['versions'] += array_combine($results, $results);
}
}
}

View File

@ -0,0 +1,134 @@
<?php
namespace Aws\Api;
use Aws\Api\Parser\Exception\ParserException;
use DateTime;
use DateTimeZone;
use Exception;
/**
* DateTime overrides that make DateTime work more seamlessly as a string,
* with JSON documents, and with JMESPath.
*/
class DateTimeResult extends \DateTime implements \JsonSerializable
{
private const ISO8601_NANOSECOND_REGEX = '/^(.*\.\d{6})(\d{1,3})(Z|[+-]\d{2}:\d{2})?$/';
/**
* Create a new DateTimeResult from a unix timestamp.
* The Unix epoch (or Unix time or POSIX time or Unix
* timestamp) is the number of seconds that have elapsed since
* January 1, 1970 (midnight UTC/GMT).
*
* @return DateTimeResult
* @throws Exception
*/
public static function fromEpoch($unixTimestamp)
{
if (!is_numeric($unixTimestamp)) {
throw new ParserException('Invalid timestamp value passed to DateTimeResult::fromEpoch');
}
// PHP 5.5 does not support sub-second precision
if (\PHP_VERSION_ID < 56000) {
return new self(gmdate('c', $unixTimestamp));
}
$decimalSeparator = isset(localeconv()['decimal_point']) ? localeconv()['decimal_point'] : ".";
$formatString = "U" . $decimalSeparator . "u";
$dateTime = DateTime::createFromFormat(
$formatString,
sprintf('%0.6f', $unixTimestamp),
new DateTimeZone('UTC')
);
if (false === $dateTime) {
throw new ParserException('Invalid timestamp value passed to DateTimeResult::fromEpoch');
}
return new self(
$dateTime->format('Y-m-d H:i:s.u'),
new DateTimeZone('UTC')
);
}
/**
* @return DateTimeResult
*/
public static function fromISO8601($iso8601Timestamp)
{
if (is_numeric($iso8601Timestamp) || !is_string($iso8601Timestamp)) {
throw new ParserException('Invalid timestamp value passed to DateTimeResult::fromISO8601');
}
// Prior to 8.0.10, nanosecond precision is not supported
// Reduces to microsecond precision if nanosecond precision is detected
if (PHP_VERSION_ID < 80010
&& preg_match(self::ISO8601_NANOSECOND_REGEX, $iso8601Timestamp, $matches)
) {
$iso8601Timestamp = $matches[1] . ($matches[3] ?? '');
}
return new DateTimeResult($iso8601Timestamp);
}
/**
* Create a new DateTimeResult from an unknown timestamp.
*
* @return DateTimeResult
* @throws Exception
*/
public static function fromTimestamp($timestamp, $expectedFormat = null)
{
if (empty($timestamp)) {
return self::fromEpoch(0);
}
if (!(is_string($timestamp) || is_numeric($timestamp))) {
throw new ParserException('Invalid timestamp value passed to DateTimeResult::fromTimestamp');
}
try {
if ($expectedFormat == 'iso8601') {
try {
return self::fromISO8601($timestamp);
} catch (Exception $exception) {
return self::fromEpoch($timestamp);
}
} else if ($expectedFormat == 'unixTimestamp') {
try {
return self::fromEpoch($timestamp);
} catch (Exception $exception) {
return self::fromISO8601($timestamp);
}
} else if (\Aws\is_valid_epoch($timestamp)) {
return self::fromEpoch($timestamp);
}
return self::fromISO8601($timestamp);
} catch (Exception $exception) {
throw new ParserException('Invalid timestamp value passed to DateTimeResult::fromTimestamp');
}
}
/**
* Serialize the DateTimeResult as an ISO 8601 date string.
*
* @return string
*/
public function __toString()
{
return $this->format('c');
}
/**
* Serialize the date as an ISO 8601 date when serializing as JSON.
*
* @return string
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return (string) $this;
}
}

View File

@ -0,0 +1,139 @@
<?php
namespace Aws\Api;
/**
* Encapsulates the documentation strings for a given service-version and
* provides methods for extracting the desired parts related to a service,
* operation, error, or shape (i.e., parameter).
*/
class DocModel
{
/** @var array */
private $docs;
/**
* @param array $docs
*
* @throws \RuntimeException
*/
public function __construct(array $docs)
{
if (!extension_loaded('tidy')) {
throw new \RuntimeException('The "tidy" PHP extension is required.');
}
$this->docs = $docs;
}
/**
* Convert the doc model to an array.
*
* @return array
*/
public function toArray()
{
return $this->docs;
}
/**
* Retrieves documentation about the service.
*
* @return null|string
*/
public function getServiceDocs()
{
return isset($this->docs['service']) ? $this->docs['service'] : null;
}
/**
* Retrieves documentation about an operation.
*
* @param string $operation Name of the operation
*
* @return null|string
*/
public function getOperationDocs($operation)
{
return isset($this->docs['operations'][$operation])
? $this->docs['operations'][$operation]
: null;
}
/**
* Retrieves documentation about an error.
*
* @param string $error Name of the error
*
* @return null|string
*/
public function getErrorDocs($error)
{
return isset($this->docs['shapes'][$error]['base'])
? $this->docs['shapes'][$error]['base']
: null;
}
/**
* Retrieves documentation about a shape, specific to the context.
*
* @param string $shapeName Name of the shape.
* @param string $parentName Name of the parent/context shape.
* @param string $ref Name used by the context to reference the shape.
*
* @return null|string
*/
public function getShapeDocs($shapeName, $parentName, $ref)
{
if (!isset($this->docs['shapes'][$shapeName])) {
return '';
}
$result = '';
$d = $this->docs['shapes'][$shapeName];
if (isset($d['refs']["{$parentName}\${$ref}"])) {
$result = $d['refs']["{$parentName}\${$ref}"];
} elseif (isset($d['base'])) {
$result = $d['base'];
}
if (isset($d['append'])) {
if (!isset($d['excludeAppend'])
|| !in_array($parentName, $d['excludeAppend'])
) {
$result .= $d['append'];
}
}
if (isset($d['appendOnly'])
&& in_array($parentName, $d['appendOnly']['shapes'])
) {
$result .= $d['appendOnly']['message'];
}
return $this->clean($result);
}
private function clean($content)
{
if (!$content) {
return '';
}
$tidy = new \tidy();
$tidy->parseString($content, [
'indent' => true,
'doctype' => 'omit',
'output-html' => true,
'show-body-only' => true,
'drop-empty-paras' => true,
'clean' => true,
'drop-proprietary-attributes' => true,
'hide-comments' => true,
'logical-emphasis' => true
]);
$tidy->cleanRepair();
return (string) $content;
}
}

View File

@ -0,0 +1,99 @@
<?php
namespace Aws\Api\ErrorParser;
use Aws\Api\Parser\MetadataParserTrait;
use Aws\Api\Parser\PayloadParserTrait;
use Aws\Api\Service;
use Aws\Api\StructureShape;
use Aws\CommandInterface;
use Psr\Http\Message\ResponseInterface;
abstract class AbstractErrorParser
{
use MetadataParserTrait;
use PayloadParserTrait;
/**
* @var Service
*/
protected $api;
/**
* @param Service $api
*/
public function __construct(?Service $api = null)
{
$this->api = $api;
}
abstract protected function payload(
ResponseInterface $response,
StructureShape $member
);
protected function extractPayload(
StructureShape $member,
ResponseInterface $response
) {
if ($member instanceof StructureShape) {
// Structure members parse top-level data into a specific key.
return $this->payload($response, $member);
} else {
// Streaming data is just the stream from the response body.
return $response->getBody();
}
}
protected function populateShape(
array &$data,
ResponseInterface $response,
?CommandInterface $command = null
) {
$data['body'] = [];
if (!empty($command) && !empty($this->api)) {
// If modeled error code is indicated, check for known error shape
if (!empty($data['code'])) {
$errors = $this->api->getOperation($command->getName())->getErrors();
foreach ($errors as $key => $error) {
// If error code matches a known error shape, populate the body
if ($this->errorCodeMatches($data, $error)) {
$modeledError = $error;
$data['body'] = $this->extractPayload(
$modeledError,
$response
);
$data['error_shape'] = $modeledError;
foreach ($error->getMembers() as $name => $member) {
switch ($member['location']) {
case 'header':
$this->extractHeader($name, $member, $response, $data['body']);
break;
case 'headers':
$this->extractHeaders($name, $member, $response, $data['body']);
break;
case 'statusCode':
$this->extractStatus($name, $response, $data['body']);
break;
}
}
break;
}
}
}
}
return $data;
}
private function errorCodeMatches(array $data, $error): bool
{
return $data['code'] == $error['name']
|| (isset($error['error']['code']) && $data['code'] === $error['error']['code']);
}
}

View File

@ -0,0 +1,144 @@
<?php
namespace Aws\Api\ErrorParser;
use Aws\Api\Parser\PayloadParserTrait;
use Aws\Api\StructureShape;
use Psr\Http\Message\ResponseInterface;
/**
* Provides basic JSON error parsing functionality.
*/
trait JsonParserTrait
{
use PayloadParserTrait;
private function genericHandler(ResponseInterface $response): array
{
$code = (string) $response->getStatusCode();
$error_code = null;
$error_type = null;
// Parse error code and type for query compatible services
if ($this->api
&& !is_null($this->api->getMetadata('awsQueryCompatible'))
&& $response->hasHeader('x-amzn-query-error')
) {
$awsQueryError = $this->parseAwsQueryCompatibleHeader($response);
if ($awsQueryError) {
$error_code = $awsQueryError['code'];
$error_type = $awsQueryError['type'];
}
}
// Parse error code from X-Amzn-Errortype header
if (!$error_code && $response->hasHeader('X-Amzn-Errortype')) {
$error_code = $this->extractErrorCode(
$response->getHeaderLine('X-Amzn-Errortype')
);
}
$parsedBody = null;
$body = $response->getBody();
if (!$body->isSeekable() || $body->getSize()) {
$parsedBody = $this->parseJson((string) $body, $response);
}
// Parse error code from response body
if (!$error_code && $parsedBody) {
$error_code = $this->parseErrorFromBody($parsedBody);
}
if (!isset($error_type)) {
$error_type = $code[0] == '4' ? 'client' : 'server';
}
return [
'request_id' => $response->getHeaderLine('x-amzn-requestid'),
'code' => $error_code ?? null,
'message' => null,
'type' => $error_type,
'parsed' => $parsedBody
];
}
/**
* Parse AWS Query Compatible error from header
*
* @param ResponseInterface $response
* @return array|null Returns ['code' => string, 'type' => string] or null
*/
private function parseAwsQueryCompatibleHeader(ResponseInterface $response): ?array
{
$queryError = $response->getHeaderLine('x-amzn-query-error');
$parts = explode(';', $queryError);
if (count($parts) === 2 && $parts[0] && $parts[1]) {
return [
'code' => $parts[0],
'type' => $parts[1]
];
}
return null;
}
/**
* Parse error code from response body
*
* @param array|null $parsedBody
* @return string|null
*/
private function parseErrorFromBody(?array $parsedBody): ?string
{
if (!$parsedBody
|| (!isset($parsedBody['code']) && !isset($parsedBody['__type']))
) {
return null;
}
$error_code = $parsedBody['code'] ?? $parsedBody['__type'];
return $this->extractErrorCode($error_code);
}
/**
* Extract error code from raw error string containing # and/or : delimiters
*
* @param string $rawErrorCode
* @return string
*/
private function extractErrorCode(string $rawErrorCode): string
{
// Handle format with both # and uri (e.g., "namespace#http://foo-bar")
if (str_contains($rawErrorCode, ':') && str_contains($rawErrorCode, '#')) {
$start = strpos($rawErrorCode, '#') + 1;
$end = strpos($rawErrorCode, ':', $start);
return substr($rawErrorCode, $start, $end - $start);
}
// Handle format with uri only : (e.g., "ErrorCode:http://foo-bar.com/baz")
if (str_contains($rawErrorCode, ':')) {
return substr($rawErrorCode, 0, strpos($rawErrorCode, ':'));
}
// Handle format with only # (e.g., "namespace#ErrorCode")
if (str_contains($rawErrorCode, '#')) {
return substr($rawErrorCode, strpos($rawErrorCode, '#') + 1);
}
return $rawErrorCode;
}
protected function payload(
ResponseInterface $response,
StructureShape $member
) {
$body = $response->getBody();
if (!$body->isSeekable() || $body->getSize()) {
$jsonBody = $this->parseJson($body, $response);
} else {
$jsonBody = (string) $body;
}
return $this->parser->parse($member, $jsonBody);
}
}

Some files were not shown because too many files have changed in this diff Show More