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.

This commit is contained in:
server 2025-05-10 11:21:43 -06:00
parent 9a3af1f3d4
commit 7cb26fe735
8 changed files with 15910 additions and 128 deletions

File diff suppressed because one or more lines are too long

View File

@ -5,7 +5,7 @@
"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", "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 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", "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.7.1", "version": "2.7.5",
"unmsVersionCompliancy": { "unmsVersionCompliancy": {
"min": "2.1.0", "min": "2.1.0",
"max": null "max": null

View File

@ -13,6 +13,7 @@ use SmsNotifier\Facade\ClientCallBellAPI;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use Ubnt\UcrmPluginSdk\Service\UcrmApi; use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use \DateTime; use \DateTime;
use GuzzleHttp\Exception\RequestException;
/* /*
@ -461,13 +462,6 @@ abstract class AbstractMessageNotifierFacade
} }
} }
//$installerWhatsApp = $this->validarNumeroTelefono((string)$installerWhatsApp); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp" //$installerWhatsApp = $this->validarNumeroTelefono((string)$installerWhatsApp); //Obtiene el número de celular del cliente que sea del tipo de contacto "WhatsApp"
$this->logger->debug('Valor de $installerWhatsApp en verifyJobActionToDo: ' . $installerWhatsApp . PHP_EOL); $this->logger->debug('Valor de $installerWhatsApp en verifyJobActionToDo: ' . $installerWhatsApp . PHP_EOL);
@ -513,7 +507,8 @@ abstract class AbstractMessageNotifierFacade
$this->validarNumeroTelefono((string) $previousInstallerWhatsApp), $this->validarNumeroTelefono((string) $previousInstallerWhatsApp),
$jsonPreviousInstallerJobNotificationData, $jsonPreviousInstallerJobNotificationData,
false, false,
true true, $this->getVaultCredentials($arrayClientCRM['id'])
); );
@ -896,7 +891,7 @@ abstract class AbstractMessageNotifierFacade
/* /*
* Update the client's data at CallBell * Update the client's data at CallBell
*/ */
public function onlyUpdate(NotificationData $notificationData, $phoneToUpdate = null, $updateEmail=false): void public function onlyUpdate(NotificationData $notificationData, $phoneToUpdate = null, $updateEmail = false): void
{ {
//$this->logger->info("Se enviará una actualización a Callbell " . PHP_EOL); //$this->logger->info("Se enviará una actualización a Callbell " . PHP_EOL);
@ -1066,7 +1061,6 @@ abstract class AbstractMessageNotifierFacade
// string $clientSmsNumber // string $clientSmsNumber
// ): void; // ): void;
function validarNumeroTelefono($telefono) function validarNumeroTelefono($telefono)
{ {
// Eliminar espacios y guiones // Eliminar espacios y guiones
@ -1102,4 +1096,482 @@ abstract class AbstractMessageNotifierFacade
return ''; return '';
} }
function getVaultCredentials($dataToSearch): string
{
$logger = \Ubnt\UcrmPluginSdk\Service\PluginLogManager::create();
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
$ucrmBaseUri = $config['ipserver'];
$authToken = $config['apitoken'];
$unmsBaseUri = 'https://' . $ucrmBaseUri . '/nms/api/v2.1/';
$ucrmBaseUri = 'https://' . $ucrmBaseUri . '/crm/api/v1.0/';
//$authToken = '7adc9198-50b1-41d0-9bfa-d4946902ed89';
// Crear una instancia del cliente Guzzle
$clientUnms = new Client([
'base_uri' => $unmsBaseUri,
'verify' => false // Deshabilitar la verificación del certificado SSL
]);
$clientUcrm = new Client([
'base_uri' => $ucrmBaseUri,
'verify' => false // Deshabilitar la verificación del certificado SSL
]);
//validar si dataToSearch es una dirección IP o una dirección MAC
if (filter_var($dataToSearch, FILTER_VALIDATE_IP)) {
// La variable es una dirección IP válida
// $logger->appendLog('Consulta por dirección IP: ' . $dataToSearch);
print ('Consulta por dirección IP: ' . $dataToSearch . PHP_EOL);
$IpAddressClientId = filter_var($dataToSearch, FILTER_VALIDATE_IP);
try {
$responseSitesByIP = $clientUnms->request('GET', 'sites/search?query=' . $dataToSearch . '&count=1&page=1', [
'headers' => [
'X-Auth-Token' => $authToken
]
]);
if ($responseSitesByIP->getStatusCode() === 200) {
$datasSitesByIP = json_decode($responseSitesByIP->getBody(), true);
$jsonDevicesBySite = json_encode($datasSitesByIP, JSON_PRETTY_PRINT);
//print_r($jsonDevicesBySite . PHP_EOL); //Devices por ID del sitio
if (isset($datasSitesByIP[0])) {
$siteId = $datasSitesByIP[0]['id'];
// print_r('ID DEL SITIO: ' . $siteId . PHP_EOL); // ID del sitio
} else {
// $logger->appendLog('No se encontró ningún sitio para la IP proporcionada: ' . $dataToSearch);
print_r('No se encontró ningún sitio para la IP proporcionada: ' . $dataToSearch . PHP_EOL);
return 'Error: No se encontró ningún sitio para la IP proporcionada: ' . $dataToSearch; // Return early if no site is found
}
} else {
//echo "Error en la solicitud. Código de estado HTTP: " . $responseSitesByIP->getStatusCode() . PHP_EOL;
// $logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responseSitesByIP->getStatusCode());
print_r('Error en la solicitud. Código de estado HTTP: ' . $responseSitesByIP->getStatusCode() . PHP_EOL);
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responseSitesByIP->getStatusCode(); // Return early if the request fails
}
$devicesBySiteId = $clientUnms->request('GET', 'devices?siteId=' . $siteId, [
'headers' => [
'X-Auth-Token' => $authToken
]
]);
if ($devicesBySiteId->getStatusCode() === 200) {
$dataDevicesBySite = json_decode($devicesBySiteId->getBody(), true);
$jsonDevicesBySite = json_encode($dataDevicesBySite, JSON_PRETTY_PRINT);
//print_r($jsonDevicesBySite . PHP_EOL); //Devices por ID del sitio
$deviceID = null;
foreach ($dataDevicesBySite as $device) {
if (isset($device['ipAddress'])) {
$ipAddress = explode('/', $device['ipAddress'])[0]; // Obtener solo la IP sin la máscara
if ($ipAddress === $IpAddressClientId) {
$deviceID = $device['identification']['id'];
break; // Salir del ciclo si se encuentra la IP
}
} else {
// $logger->appendLog('No se encontró la IP del dispositivo en la respuesta de la API.');
print_r('No se encontró la IP del dispositivo en la respuesta de la API.' . PHP_EOL);
return 'Error: No se encontró la IP del dispositivo en la respuesta de la API.'; // Return early if the IP is not found
}
}
if ($deviceID == null) {
//echo "No se encontró el dispositivo con la IP proporcionada." . PHP_EOL;
// $logger->appendLog('No se encontró el dispositivo con la IP proporcionada: ' . $IpAddressClientId);
print_r('No se encontró el dispositivo con la IP proporcionada: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el dispositivo con la IP proporcionada: ' . $IpAddressClientId; // Return early if no device is found
}
} else {
// echo "Error en la solicitud. Código de estado HTTP: " . $devicesBySiteId->getStatusCode() . PHP_EOL;
// $logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $devicesBySiteId->getStatusCode());
print_r('Error en la solicitud. Código de estado HTTP: ' . $devicesBySiteId->getStatusCode() . PHP_EOL);
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $devicesBySiteId->getStatusCode(); // Return early if the request fails
}
$responsePasswordVault = $clientUnms->request('GET', 'vault/' . $deviceID . '/credentials', [
'headers' => [
'X-Auth-Token' => $authToken
]
]);
if ($responsePasswordVault->getStatusCode() === 200) {
$dataPasswordVault = json_decode($responsePasswordVault->getBody(), true);
// $jsonPasswordVault = json_encode($dataPasswordVault, JSON_PRETTY_PRINT);
//print_r($jsonPasswordVault . PHP_EOL); //Credenciales del dispositivo
if (isset($dataPasswordVault['credentials']['password'])) {
$dataPasswordVault = $dataPasswordVault['credentials']['password'];
} else {
// echo "No se encontró la contraseña en la respuesta de la API." . PHP_EOL;
// $logger->appendLog('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.');
print_r('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.' . PHP_EOL);
return "Error: No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida."; // Return early if the password is not found
}
return $dataPasswordVault;
} else {
// echo "Error en la solicitud. Código de estado HTTP: " . $responsePasswordVault->getStatusCode() . PHP_EOL;
// $logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode());
print_r('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode() . PHP_EOL);
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode(); // Return early if the request fails
}
} catch (RequestException $requestException) {
// Manejar errores de la solicitud, si hay error 404 entonces responder que no se encontró niguna IP asociada a alguna antena o dispositivo de red
if ($requestException->hasResponse()) {
$response = $requestException->getResponse();
$statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase();
// echo "Error: {$statusCode} - {$reason}" . PHP_EOL;
// echo $response->getBody();
if ($statusCode == 404) {
// echo "No se encontró el cliente con la dirección IP proporcionada." . PHP_EOL;
// $logger->appendLog('No se encontró el cliente con la dirección IP proporcionada: ' . $IpAddressClientId);
print_r('No se encontró el cliente con la dirección IP proporcionada: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el cliente con la dirección IP proporcionada: ' . $IpAddressClientId; // Return early if the client is not found
}
return 'Error: ' . $reason; // Return early if the request fails
} else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL;
// $logger->appendLog('Error: ' . $requestException->getMessage());
print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
}
}
} else if (preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $dataToSearch)) {
// La variable es una dirección MAC válida
// $logger->appendLog('Consulta por dirección MAC: ' . $dataToSearch);
print ('Consulta por dirección MAC: ' . $dataToSearch . PHP_EOL);
try {
// //para mandarla al endpoint de dispositivos por MAC se necesita convertir la cadena de la direccion mac en un formato como el siguiente ejemplo: para la dirección mac 60:22:32:c8:b2:c3 quedaría como 60%3A22%3A32%3Ac8%3Ab2%3Ac3
// $dataToSearch = str_replace(':', '%3A', $dataToSearch);
// $logger->appendLog('Consulta por dirección MAC: ' . $dataToSearch );
$responseDeviceByMAC = $clientUnms->request('GET', 'devices/mac/' . $dataToSearch, [
'headers' => [
'X-Auth-Token' => $authToken
]
]);
if ($responseDeviceByMAC->getStatusCode() === 200) {
$dataDeviceByMAC = json_decode($responseDeviceByMAC->getBody(), true);
$jsonDeviceByMac = json_encode($dataDeviceByMAC, JSON_PRETTY_PRINT);
// print_r($jsonDeviceByMac . PHP_EOL); //Devices por ID del sitio
//$logger->appendLog($jsonDeviceByMac.PHP_EOL);
//Ejemplo de $responseDeviceByMac en json: {"id":"84c8a581-154c-41db-81d5-a1b1c9ede411","type":"airMax","series":"AC"}
//obtener el id del dispositivo y si no existe el id del dispositivo entonces devolver un mensaje de error
if (isset($dataDeviceByMAC['id'])) {
$deviceId = $dataDeviceByMAC['id'];
// print_r('ID DEL DISPOSITIVO: ' . $deviceId . PHP_EOL); // ID del dispositivo
} else {
// echo "No se encontró el dispositivo con la dirección MAC proporcionada." . PHP_EOL;
// $logger->appendLog('No se encontró el dispositivo con la dirección MAC proporcionada: ' . $dataToSearch);
print_r('No se encontró el dispositivo con la dirección MAC proporcionada: ' . $dataToSearch . PHP_EOL);
return 'Error: No se encontró el dispositivo con la dirección MAC proporcionada: ' . $dataToSearch; // Return early if no device is found
}
}
$responsePasswordVault = $clientUnms->request('GET', 'vault/' . $deviceId . '/credentials', [
'headers' => [
'X-Auth-Token' => $authToken
]
]);
if ($responsePasswordVault->getStatusCode() === 200) {
$dataPasswordVault = json_decode($responsePasswordVault->getBody(), true);
// $jsonPasswordVault = json_encode($dataPasswordVault, JSON_PRETTY_PRINT);
//print_r($jsonPasswordVault . PHP_EOL); //Credenciales del dispositivo
if (isset($dataPasswordVault['credentials']['password'])) {
$dataPasswordVault = $dataPasswordVault['credentials']['password'];
} else {
// echo "No se encontró la contraseña en la respuesta de la API." . PHP_EOL;
// $logger->appendLog('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.');
print_r('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.' . PHP_EOL);
return "Error: No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida."; // Return early if the password is not found
}
return $dataPasswordVault;
} else {
// echo "Error en la solicitud. Código de estado HTTP: " . $responsePasswordVault->getStatusCode() . PHP_EOL;
// $logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode());
print_r('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode() . PHP_EOL);
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode(); // Return early if the request fails
}
} catch (RequestException $requestException) {
// Manejar errores de la solicitud, si hay error 404 entonces responder que no se encontró niguna MAC asociada a alguna antena o dispositivo de red
if ($requestException->hasResponse()) {
$response = $requestException->getResponse();
$statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase();
// echo "Error: {$statusCode} - {$reason}" . PHP_EOL;
// echo $response->getBody();
if ($statusCode == 404) {
// echo "No se encontró el cliente con la dirección MAC proporcionada." . PHP_EOL;
// $logger->appendLog('No se encontró ninguna antena de cliente o dispositivo en la red con la dirección MAC proporcionada: ' . $dataToSearch);
print_r('No se encontró ninguna antena de cliente o dispositivo en la red con la dirección MAC proporcionada: ' . $dataToSearch . PHP_EOL);
return 'Error: No se encontró ninguna antena de cliente o dispositivo en la red con la dirección MAC proporcionada: ' . $dataToSearch; // Return early if the client is not found
}
return 'Error: ' . $reason; // Return early if the request fails
} else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL;
// $logger->appendLog('Error: ' . $requestException->getMessage());
print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
}
}
} else {
// La variable no es una dirección IP válida, se asume que es un ID
$IpAddressClientId = filter_var($dataToSearch, FILTER_SANITIZE_NUMBER_INT);
//print ('Consulta por ID: ' . $dataToSearch . PHP_EOL);
try {
//Obtener id del sitio por medio del servicio
$responseServices = $clientUcrm->get('clients/services?clientId=' . $IpAddressClientId, [
'headers' => [
'X-Auth-Token' => $authToken,
'Content-Type: application/json'
]
]);
} catch (RequestException $requestException) {
// Manejar errores de la solicitud
if ($requestException->hasResponse()) {
$response = $requestException->getResponse();
$statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase();
//si el statusCode es 404 significa que no se encontró el cliente
if ($statusCode == 404) {
echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL;
$logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId);
// print_r('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found
}
return 'Error: ' . $reason; // Return early if the request fails
} else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL;
$logger->appendLog('Error: ' . $requestException->getMessage());
// print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
}
}
if ($responseServices->getStatusCode() === 200) {
$dataServices = json_decode($responseServices->getBody(), true);
// $jsonServices = json_encode($dataServices, JSON_PRETTY_PRINT);
// print_r($jsonServices . PHP_EOL);
if (isset($dataServices[0])) {
$unmsSiteID = $dataServices[0]['unmsClientSiteId']; // Example: 9c6798f3-0254-4e5b-bc3b-9da82fe16e46
} else {
// echo "No se encontraron servicios para el cliente proporcionado." . PHP_EOL;
$logger->appendLog('No se encontraron servicios para el cliente proporcionado: ' . $IpAddressClientId);
// print_r('No se encontraron servicios para el cliente proporcionado: ' . $IpAddressClientId . PHP_EOL);
return "Error: No se encontraron servicios para el cliente proporcionado: " . $IpAddressClientId; // Return early if no services are found
}
} else {
// echo "Error en la solicitud. Código de estado HTTP: " . $responseServices->getStatusCode() . PHP_EOL;
$logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responseServices->getStatusCode());
// print_r('Error en la solicitud. Código de estado HTTP: ' . $responseServices->getStatusCode() . PHP_EOL);
return "Error: En la solicitud. Código de estado HTTP: " . $responseServices->getStatusCode();
}
try {
$responseDevicesBySite = $clientUnms->request('GET', 'devices?siteId=' . $unmsSiteID, [
'headers' => [
'X-Auth-Token' => $authToken
]
]);
} catch (RequestException $requestException) {
// Manejar errores de la solicitud
if ($requestException->hasResponse()) {
$response = $requestException->getResponse();
$statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase();
//si el statusCode es 404 significa que no se encontró el cliente
if ($statusCode == 404) {
// echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL;
$logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId);
// print_r('No se encontró el devicie con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el devicie con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found
}
return 'Error: ' . $reason; // Return early if the request fails
} else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL;
$logger->appendLog('Error: ' . $requestException->getMessage());
// print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
}
}
if ($responseDevicesBySite->getStatusCode() === 200) {
$dataDevicesBySite = json_decode($responseDevicesBySite->getBody(), true);
$jsonDevicesBySite = json_encode($dataDevicesBySite, JSON_PRETTY_PRINT);
//print_r($jsonDevicesBySite . PHP_EOL); //Devices por ID del sitio
//id del device al que está conectado el cliente
if (isset($dataDevicesBySite[0])) {
//verificar con iiset si existe la clave 'identification' y 'apDevice' en el primer elemento del array
if (isset($dataDevicesBySite[0]['identification']) && isset($dataDevicesBySite[0]['attributes']['apDevice'])) {
$idClientDevice = $dataDevicesBySite[0]['identification']['id'];
$deviceID = $dataDevicesBySite[0]['attributes']['apDevice']['id'];
} else {
// echo "No se encontró la clave 'identification' o 'apDevice' en la respuesta." . PHP_EOL;
$logger->appendLog('No se encontró la clave \'identification\' o \'apDevice\' en la respuesta.');
// print_r('Este cliente es un repetidor.' . PHP_EOL);
return "Este cliente es un repetidor."; // Return early if the key is not found
}
} else {
// echo "No se encontraron dispositivos para el sitio proporcionado." . PHP_EOL;
$logger->appendLog('No se encontraron dispositivos para el sitio proporcionado: ' . $unmsSiteID);
// print_r('No se encontraron dispositivos para el sitio proporcionado: ' . $unmsSiteID . PHP_EOL);
return "Error: No se encontraron dispositivos para el sitio proporcionado."; // Return early if no devices are found
}
} else {
// echo "Error en la solicitud. Código de estado HTTP: " . $responseDevicesBySite->getStatusCode() . PHP_EOL;
$logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode());
// print_r('Error en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode() . PHP_EOL);
return "Error: Falla en la solicitud. Código de estado HTTP: " . $responseDevicesBySite->getStatusCode();
}
try {
$responseDevicesBySite = $clientUnms->request('GET', 'devices/' . $deviceID, [
'headers' => [
'X-Auth-Token' => $authToken
]
]);
} catch (RequestException $requestException) {
// Manejar errores de la solicitud
if ($requestException->hasResponse()) {
$response = $requestException->getResponse();
$statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase();
//si el statusCode es 404 significa que no se encontró el cliente
if ($statusCode == 404) {
// echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL;
$logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId);
// print_r('No se encontró el device con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el device con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found
}
return 'Error: ' . $reason; // Return early if the request fails
} else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL;
$logger->appendLog('Error: ' . $requestException->getMessage());
// print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
}
}
if ($responseDevicesBySite->getStatusCode() === 200) {
$dataDevices = json_decode($responseDevicesBySite->getBody(), true);
$jsonDevices = json_encode($dataDevices, JSON_PRETTY_PRINT);
//print_r($jsonDevices . PHP_EOL);
try {
//print_r('ID del device al que está conectado el cliente: ' . $idDevice . PHP_EOL);
$responsePasswordVault = $clientUnms->request('GET', 'vault/' . $idClientDevice . '/credentials', [
'headers' => [
'X-Auth-Token' => $authToken
]
]);
} catch (RequestException $requestException) {
// Manejar errores de la solicitud
if ($requestException->hasResponse()) {
$response = $requestException->getResponse();
$statusCode = $response->getStatusCode();
$reason = $response->getReasonPhrase();
//si el statusCode es 404 significa que no se encontró el cliente
if ($statusCode == 404) {
// echo "No se encontró el cliente con el ID proporcionado." . PHP_EOL;
$logger->appendLog('No se encontró el cliente con el ID proporcionado: ' . $IpAddressClientId);
// print_r('No se encontró el device con el ID proporcionado: ' . $IpAddressClientId . PHP_EOL);
return 'Error: No se encontró el device con el ID proporcionado: ' . $IpAddressClientId; // Return early if the client is not found
}
return 'Error: ' . $reason; // Return early if the request fails
} else {
// echo "Error: " . $requestException->getMessage() . PHP_EOL;
$logger->appendLog('Error: ' . $requestException->getMessage());
// print_r('Error: ' . $requestException->getMessage() . PHP_EOL);
return 'Error: ' . $requestException->getMessage(); // Return early if the request fails
}
}
if ($responsePasswordVault->getStatusCode() === 200) {
$dataPasswordVault = json_decode($responsePasswordVault->getBody(), true);
$jsonPasswordVault = json_encode($dataPasswordVault, JSON_PRETTY_PRINT);
if (isset($dataPasswordVault['credentials']['password'])) {
$passwordVault = $dataPasswordVault['credentials']['password'];
return $passwordVault;
} else {
// echo "No se encontró la contraseña en la respuesta de la API." . PHP_EOL;
$logger->appendLog('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.');
// print_r('No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida.' . PHP_EOL);
return "Error: No se encontró una contraseña en la bóveda para la antena de este cliente, es altamente probable que conserve una contraseña conocida."; // Return early if the password is not found
}
} else {
// echo "Error en la solicitud. Código de estado HTTP: " . $responsePasswordVault->getStatusCode() . PHP_EOL;
$logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode());
// print_r('Error en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode() . PHP_EOL);
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responsePasswordVault->getStatusCode(); // Return early if the request fails
}
} else {
// echo "Error en la solicitud. Código de estado HTTP: " . $responseDevicesBySite->getStatusCode() . PHP_EOL;
$logger->appendLog('Error en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode());
// print_r('Error en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode() . PHP_EOL);
return 'Error: Falla en la solicitud. Código de estado HTTP: ' . $responseDevicesBySite->getStatusCode(); // Return early if the request fails
}
}
}
} }

View File

@ -80,6 +80,7 @@ abstract class AbstractOxxoOperationsFacade
$stripeCustomerId = null; $stripeCustomerId = null;
$clientEmail = ''; $clientEmail = '';
$clientFullName = '';
$clientGuzzleHttp = new Client([ $clientGuzzleHttp = new Client([
'base_uri' => $baseUri, 'base_uri' => $baseUri,
@ -116,6 +117,7 @@ abstract class AbstractOxxoOperationsFacade
$this->logger->error("Timeout al obtener el cliente en CRM: " . $clientID . PHP_EOL); $this->logger->error("Timeout al obtener el cliente en CRM: " . $clientID . PHP_EOL);
//devolver un array con los campos del codigo error, descripción de la falla, clientID y amount //devolver un array con los campos del codigo error, descripción de la falla, clientID y amount
$arrayOxxoPayment['oxxo_reference'] = ''; $arrayOxxoPayment['oxxo_reference'] = '';
$arrayOxxoPayment['url'] = '';
$arrayOxxoPayment['error'] = 'errorTimeoutGetClient'; $arrayOxxoPayment['error'] = 'errorTimeoutGetClient';
$arrayOxxoPayment['failDescription'] = 'Timeout al obtener el cliente en CRM: ' . $clientID; $arrayOxxoPayment['failDescription'] = 'Timeout al obtener el cliente en CRM: ' . $clientID;
$arrayOxxoPayment['clientID'] = $clientID; $arrayOxxoPayment['clientID'] = $clientID;
@ -126,6 +128,7 @@ abstract class AbstractOxxoOperationsFacade
$this->logger->error("Error al obtener el cliente en CRM (Error {$e->getCode()}): " . $e->getMessage() . PHP_EOL); $this->logger->error("Error al obtener el cliente en CRM (Error {$e->getCode()}): " . $e->getMessage() . PHP_EOL);
//devolver un array con los campos del codigo error, descripción de la falla, clientID y amount //devolver un array con los campos del codigo error, descripción de la falla, clientID y amount
$arrayOxxoPayment['oxxo_reference'] = ''; $arrayOxxoPayment['oxxo_reference'] = '';
$arrayOxxoPayment['url'] = '';
$arrayOxxoPayment['error'] = 'errorGetClient'; $arrayOxxoPayment['error'] = 'errorGetClient';
$arrayOxxoPayment['failDescription'] = 'Error al obtener el cliente en CRM: ' . $clientID; $arrayOxxoPayment['failDescription'] = 'Error al obtener el cliente en CRM: ' . $clientID;
$arrayOxxoPayment['clientID'] = $clientID; $arrayOxxoPayment['clientID'] = $clientID;
@ -233,11 +236,18 @@ abstract class AbstractOxxoOperationsFacade
} catch (Exception $e) { } catch (Exception $e) {
$this->logger->error("Error inesperado al crear PaymentIntent (Error {$e->getCode()}): " . $e->getMessage() . PHP_EOL); $this->logger->error("Error inesperado al crear PaymentIntent (Error {$e->getCode()}): " . $e->getMessage() . PHP_EOL);
//si e->getMessage incluye el mensaje: You must provide a customer when creating or updating a PaymentIntent with a `customer_ba (truncated...) declarar una variable y ahi poner "Este cliente no tiene cuenta de Stripe"
if($e->getMessage() == 'You must provide a customer when creating or updating a PaymentIntent with a `customer_ba (truncated...)'){
$this->logger->error("Este cliente no tiene cuenta de Stripe" . PHP_EOL);
$arrayOxxoPayment['failDescription'] = 'Este cliente no tiene cuenta de Stripe: ' . $clientID;
}else{
$this->logger->error("Error inesperado al crear PaymentIntent: " . $e->getMessage() . PHP_EOL);
$arrayOxxoPayment['failDescription'] = 'Error inesperado al crear PaymentIntent: ' . $clientID;
}
//devolver un array con los campos del codigo error, descripción de la falla, clientID y amount //devolver un array con los campos del codigo error, descripción de la falla, clientID y amount
$arrayOxxoPayment['oxxo_reference'] = ''; $arrayOxxoPayment['oxxo_reference'] = '';
$arrayOxxoPayment['url'] = ''; $arrayOxxoPayment['url'] = '';
$arrayOxxoPayment['error'] = 'errorCreatePaymentIntent'; $arrayOxxoPayment['error'] = 'errorCreatePaymentIntent';
$arrayOxxoPayment['failDescription'] = 'Error inesperado al crear PaymentIntent: ' . $clientID;
$arrayOxxoPayment['clientID'] = $clientID; $arrayOxxoPayment['clientID'] = $clientID;
$arrayOxxoPayment['amount'] = $integerAmount; $arrayOxxoPayment['amount'] = $integerAmount;
$arrayOxxoPayment['clientFullName'] = $clientFullName; $arrayOxxoPayment['clientFullName'] = $clientFullName;
@ -305,7 +315,7 @@ abstract class AbstractOxxoOperationsFacade
$this->logger->info("Referencia OXXO: " . $oxxo_reference . PHP_EOL); $this->logger->info("Referencia OXXO: " . $oxxo_reference . PHP_EOL);
$this->logger->info("URL del recibo: " . $oxxo_receipt_url . PHP_EOL); $this->logger->info("URL del recibo: " . $oxxo_receipt_url . PHP_EOL);
$this->captureScreenshot($oxxo_receipt_url); //$this->captureScreenshot($oxxo_receipt_url);
//devolver un array con los campos de url de oxxo, descripción de la falla, clientID y amount //devolver un array con los campos de url de oxxo, descripción de la falla, clientID y amount
$arrayOxxoPayment['oxxo_reference'] = $oxxo_reference; $arrayOxxoPayment['oxxo_reference'] = $oxxo_reference;
$arrayOxxoPayment['url'] = $oxxo_receipt_url; $arrayOxxoPayment['url'] = $oxxo_receipt_url;

View File

@ -58,7 +58,10 @@ abstract class AbstractStripeOperationsFacade
*/ */
public function createPaymentIntent($event_json) public function createPaymentIntent($event_json)
{ {
$this->logger->info("Evento recibido: " . json_encode($event_json) . PHP_EOL); // if ($event_json['data']['object']['type'] != 'funded') {
// return;
// }
// $this->logger->info("Evento recibido: " . json_encode($event_json) . PHP_EOL);
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create(); $configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig(); $config = $configManager->loadConfig();
@ -192,19 +195,19 @@ abstract class AbstractStripeOperationsFacade
//obtener el ID de la etiqueta o tag llamada "CREARCLABESTRIPE" y asiganarla a una variable $tagCrearClabeStripe basandose en el ejemplo de respuesta anterior //obtener el ID de la etiqueta o tag llamada "CREARCLABESTRIPE" y asiganarla a una variable $tagCrearClabeStripe basandose en el ejemplo de respuesta anterior
$tagCrearClabeStripe = null; $tagCrearClabeStripe = null;
foreach ($tagsIds as $tag) { foreach ($tagsIds as $tag) {
if ($tag['name'] === 'CREARCLABESTRIPE') { if ($tag['name'] === 'CREAR CLABE STRIPE') {
$tagCrearClabeStripe = $tag['id']; $tagCrearClabeStripe = $tag['id'];
$this->logger->info("ID de la etiqueta 'CREARCLABESTRIPE': " . $tagCrearClabeStripe . PHP_EOL); $this->logger->info("ID de la etiqueta 'CREAR CLABE STRIPE': " . $tagCrearClabeStripe . PHP_EOL);
break; break;
} }
} }
if (!$tagCrearClabeStripe) { if (!$tagCrearClabeStripe) {
$this->logger->info("No se encontró la etiqueta 'CREARCLABESTRIPE'." . PHP_EOL); $this->logger->info("No se encontró la etiqueta 'CREAR CLABE STRIPE'." . PHP_EOL);
return; return;
} }
$this->ucrmApi->patch("clients/$clientId/remove-tag/" . $tagCrearClabeStripe); $this->ucrmApi->patch("clients/$clientId/remove-tag/" . $tagCrearClabeStripe);
$this->logger->info("Se eliminó la etiqueta 'CREARCLABESTRIPE' del cliente." . PHP_EOL); $this->logger->info("Se eliminó la etiqueta 'CREAR CLABE STRIPE' del cliente." . PHP_EOL);
} }
return; return;
@ -236,7 +239,7 @@ abstract class AbstractStripeOperationsFacade
$this->logger->info("Se eliminó la etiqueta 'CREARCLABESTRIPE' del cliente." . PHP_EOL); $this->logger->info("Se eliminó la etiqueta 'CREARCLABESTRIPE' del cliente." . PHP_EOL);
return; return;
} }
@ -258,10 +261,6 @@ abstract class AbstractStripeOperationsFacade
$this->createCustomerStripe($notificationData, $stripe, $baseUri, $UCRMAPIToken); $this->createCustomerStripe($notificationData, $stripe, $baseUri, $UCRMAPIToken);
} }
// /** // /**
// * implement in subclass with the specific messaging provider // * implement in subclass with the specific messaging provider
// * @see TwilioNotifierFacade::sendWhatsApp() // * @see TwilioNotifierFacade::sendWhatsApp()
@ -398,7 +397,7 @@ abstract class AbstractStripeOperationsFacade
}'; //JSON para hacer patch de los custom fields del cliente en el UISCP CRM, Campo para el Stripe Customer ID y la Clabe interbancaria }'; //JSON para hacer patch de los custom fields del cliente en el UISCP CRM, Campo para el Stripe Customer ID y la Clabe interbancaria
//valor de $json_data_patch en json //valor de $json_data_patch en json
//$this->logger->info("Valor de json_data_patch: " . $json_data_patch . PHP_EOL); //$this->logger->info("Valor de json_data_patch: " . $json_data_patch . PHP_EOL);
// try{ // try{
// $responsepatchCRM= $this->ucrmApi->patch("clients/$ucrm_client_id", [ // $responsepatchCRM= $this->ucrmApi->patch("clients/$ucrm_client_id", [
@ -419,7 +418,7 @@ abstract class AbstractStripeOperationsFacade
// $this->logger->info("Error al hacer el patch al cliente en UCRM: " . $e->getMessage() . PHP_EOL); // $this->logger->info("Error al hacer el patch al cliente en UCRM: " . $e->getMessage() . PHP_EOL);
// return false; // Return false if patch fails // return false; // Return false if patch fails
// } // }
$clientguzz = new Client(); //instancia de cliente GuzzleHttp para consumir API UISP CRM $clientguzz = new Client(); //instancia de cliente GuzzleHttp para consumir API UISP CRM
try { try {
@ -431,7 +430,7 @@ abstract class AbstractStripeOperationsFacade
'Accept' => 'application/json', // Indica que esperamos una respuesta en formato JSON 'Accept' => 'application/json', // Indica que esperamos una respuesta en formato JSON
], ],
'verify' => false, 'verify' => false,
]); ]);
} catch (GuzzleException $error) { } catch (GuzzleException $error) {
@ -477,4 +476,6 @@ abstract class AbstractStripeOperationsFacade
} }
} }
} }

View File

@ -118,7 +118,7 @@ class ClientCallBellAPI
curl_close($ch); curl_close($ch);
} }
public function sendJobNotificationWhatsAppToClient($clientWhatsAppNumber, $jobNotificationData, $reprogramming = false, $changeInstaller = false): bool public function sendJobNotificationWhatsAppToClient($clientWhatsAppNumber, $jobNotificationData, $passwordVault, $reprogramming = false, $changeInstaller = false): bool
{ {
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
@ -190,7 +190,7 @@ class ClientCallBellAPI
$log->appendLog("Ruta no prevista en la función." . PHP_EOL); $log->appendLog("Ruta no prevista en la función." . PHP_EOL);
return false; return false;
} }
public function sendJobNotificationWhatsAppToInstaller($installerWhatsAppNumber, $jobInstallerNotificationData, $reprogramming = false, $changeInstaller = false): bool public function sendJobNotificationWhatsAppToInstaller($installerWhatsAppNumber, $jobInstallerNotificationData, $reprogramming = false, $changeInstaller = false, $passwordAntenaCliente): bool
{ {
$log = PluginLogManager::create(); //Initialize Logger $log = PluginLogManager::create(); //Initialize Logger
@ -217,11 +217,12 @@ class ClientCallBellAPI
} else { } else {
$campo2 = sprintf("*#%s*", $jobInstallerNotificationData['jobId']); $campo2 = sprintf("*#%s*", $jobInstallerNotificationData['jobId']);
$campo3 = $jobInstallerNotificationData['clientFullName']; $campo3 = $jobInstallerNotificationData['clientFullName'];
$campo4 = $jobInstallerNotificationData['clientAddress']; // $campo4 = $jobInstallerNotificationData['clientAddress'];
$campo5 = $jobInstallerNotificationData['clientWhatsApp']; $campo4 = $jobInstallerNotificationData['clientWhatsApp'];
$campo6 = $jobInstallerNotificationData['date']; $campo5 = $jobInstallerNotificationData['date'];
$campo7 = $jobInstallerNotificationData['jobDescription']; $campo6 = $jobInstallerNotificationData['jobDescription'];
$campo8 = $jobInstallerNotificationData['gmapsLocation']; $campo7 = $jobInstallerNotificationData['gmapsLocation'];
$campo8 = $passwordAntenaCliente;
} }
@ -230,7 +231,7 @@ class ClientCallBellAPI
//Enviar notificación de reprogramación //Enviar notificación de reprogramación
$log->appendLog("Enviando notificación de reprogramación al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL); $log->appendLog("Enviando notificación de reprogramación al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"42152c07c67b468ba68e581c0283e22e\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"7eb4d8e27cf740779dd6777fad7ffaf4\",\n \"optin_contact\": true\n }";
} else if ($changeInstaller) { } else if ($changeInstaller) {
//Enviar notificación de cambio de instalador //Enviar notificación de cambio de instalador
@ -240,7 +241,7 @@ class ClientCallBellAPI
} else { } else {
//Enviar notificación normal de asignación de tarea //Enviar notificación normal de asignación de tarea
$log->appendLog("Enviando notificación normal de asignación de tarea al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL); $log->appendLog("Enviando notificación normal de asignación de tarea al instalador, valor de reprogramming $reprogramming y valor de changeInstaller $changeInstaller " . PHP_EOL);
$curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"b6663394265e4bcdb215369aa9ba0f21\",\n \"optin_contact\": true\n }"; $curl_string = "{\n \"to\": \"$installerWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\", \"$campo3\", \"$campo4\", \"$campo5\", \"$campo6\", \"$campo7\", \"$campo8\"],\n \"template_uuid\": \"fa7f3f8e25934e159a9203eb1cd7f7a6\",\n \"optin_contact\": true\n }";
} }
$log->appendLog("La cadena CURL que se envia es: " . $curl_string); $log->appendLog("La cadena CURL que se envia es: " . $curl_string);

View File

@ -80,13 +80,13 @@ class Plugin
// $hola = PHP_SAPI; // $hola = PHP_SAPI;
// $this->logger->info('valor de PHP_SAPI: ' . $hola); // $this->logger->info('valor de PHP_SAPI: ' . $hola);
if (PHP_SAPI === 'fpm-fcgi') { if (PHP_SAPI === 'fpm-fcgi') {
//$this->logger->debug('Whatsapp over HTTP started'); // $this->logger->debug('Whatsapp over HTTP started');
$this->processHttpRequest(); $this->processHttpRequest();
//$this->logger->debug('HTTP request processing ended.'); // $this->logger->debug('HTTP request processing ended.');
} elseif (PHP_SAPI === 'cli') { } elseif (PHP_SAPI === 'cli') {
//$this->logger->debug('Whatsapp over CLI started'); // $this->logger->debug('Whatsapp over CLI started');
$this->processCli(); $this->processCli();
//$this->logger->debug('CLI process ended.'); // $this->logger->debug('CLI process ended.');
} else { } else {
throw new \UnexpectedValueException('Unknown PHP_SAPI type: ' . PHP_SAPI); throw new \UnexpectedValueException('Unknown PHP_SAPI type: ' . PHP_SAPI);
} }
@ -109,7 +109,9 @@ class Plugin
} }
$userInput = file_get_contents('php://input'); $userInput = file_get_contents('php://input'); //se recibe el json del webhook
//imprimir el json del webhook
$this->logger->debug('valor del webhook: ' . $userInput . PHP_EOL);
@ -119,6 +121,7 @@ class Plugin
return; return;
} }
$jsonData = @json_decode($userInput, true, 50); $jsonData = @json_decode($userInput, true, 50);
if (!isset($jsonData['uuid'])) { if (!isset($jsonData['uuid'])) {
@ -131,19 +134,29 @@ class Plugin
if ($jsonData) { if ($jsonData) {
switch ($jsonData['type']) { switch ($jsonData['type']) {
case 'customer_cash_balance_transaction.created': case 'customer_cash_balance_transaction.created':
$this->logger->info('Evento de transfencia al cliente encontrado'); $this->logger->info('Evento de transfencia al cliente encontrado: '. json_encode($jsonData) . PHP_EOL);
$this->logger->info('Valor del EventJSON: ' . json_encode($jsonData) . PHP_EOL); if ($jsonData['data']['object']['type'] === 'funded') {
$this->pluginNotifierFacade->createPaymentIntent($jsonData); $this->pluginNotifierFacade->createPaymentIntent($jsonData);
}
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 Pago de OXXO recibido'); //$this->logger->info('Evento de Pago de OXXO recibido: '. json_encode($jsonData) . PHP_EOL);
$this->logger->info('Valor del EventJSON: ' . json_encode($jsonData) . PHP_EOL);
break; break;
case 'energy.alert': case 'energy.alert':
$this->logger->info('Evento de Energía recibido: ' . $jsonData['message'] . PHP_EOL); $this->logger->info('Evento de Energía recibido: ' . $jsonData['message'] . PHP_EOL);
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' . PHP_EOL);
// Construir la URL basada en el "client_id" // Construir la URL basada en el "client_id"
@ -178,12 +191,12 @@ class Plugin
//this->logger->error('Error al crear la referencia de OXXO: ' . $responseOxxo); //this->logger->error('Error al crear la referencia de OXXO: ' . $responseOxxo);
//crear un json con variable $response que contenga las claves y valores del array $responseOxxo los cuales son: oxxo_reference, error, failDescription, clientID, clientFullName amount //crear un json con variable $response que contenga las claves y valores del array $responseOxxo los cuales son: oxxo_reference, error, failDescription, clientID, clientFullName amount
$response = '{' . $response = '{' .
'"url":' . $responseOxxo['url'] . ',' . '"url": "' . $responseOxxo['url'] . '",' .
'"error": "' . $responseOxxo['error'] . '",' . '"error": "' . $responseOxxo['error'] . '",' .
'"failDescription": "' . $responseOxxo['failDescription'] . '",' . '"failDescription": "' . $responseOxxo['failDescription'] . '",' .
'"clientID": "' . $responseOxxo['clientID'] . '",' . '"clientID": "' . $responseOxxo['clientID'] . '",' .
'"clientFullName": "' . $responseOxxo['clientFullName'] . '",' . '"clientFullName": "' . $responseOxxo['clientFullName'] . '",' .
'"amount": "' . $responseOxxo['amount'] . '",' . '"amount": "' . $responseOxxo['amount'] . '"' .
'}'; '}';
header('Content-Type: application/json'); header('Content-Type: application/json');
@ -240,6 +253,9 @@ class Plugin
$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.');
@ -348,7 +364,7 @@ class Plugin
$this->logger->debug('Se actualiza a un cliente'); $this->logger->debug('Se actualiza a un cliente');
$this->logger->debug('Valor de json_data: ' . json_encode($jsonData)); $this->logger->debug('Valor de json_data: ' . json_encode($jsonData));
//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}}} //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}}}
// Validar que 'extraData' existe y contiene las claves necesarias // Validar que 'extraData' existe y contiene las claves necesarias
if ( if (
@ -358,11 +374,11 @@ class Plugin
$entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit']; $entityBeforeEdit = $jsonData['extraData']['entityBeforeEdit'];
$entity = $jsonData['extraData']['entity']; $entity = $jsonData['extraData']['entity'];
$this->logger->debug('Validando claves dentro de entityBeforeEdit y entity'); //$this->logger->debug('Validando claves dentro de entityBeforeEdit y entity');
// Validar si 'isLead' esta en true en entityBeforeEdit y en false en entity // Validar si 'isLead' esta en true en entityBeforeEdit y en false en entity
if (array_key_exists('isLead', $entityBeforeEdit) && array_key_exists('isLead', $entity)) { if (array_key_exists('isLead', $entityBeforeEdit) && array_key_exists('isLead', $entity)) {
$this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo isLead'); //$this->logger->debug('Los datos entityBeforeEdit y entity contienen el campo isLead');
$isLeadBefore = $entityBeforeEdit['isLead']; $isLeadBefore = $entityBeforeEdit['isLead'];
$isLeadAfter = $entity['isLead']; $isLeadAfter = $entity['isLead'];
@ -377,7 +393,7 @@ class Plugin
} else { } else {
$this->logger->warning('El campo isLead no existe en entityBeforeEdit o entity'); $this->logger->warning('El campo isLead no existe en entityBeforeEdit o entity');
} }
// buscar si existe la etiqueta 'STRIPE' en entity pero no en entityBeforeEdit // buscar si existe la etiqueta 'STRIPE' en entity pero no en entityBeforeEdit
$tags = $jsonData['extraData']['entity']['tags']; $tags = $jsonData['extraData']['entity']['tags'];
@ -394,17 +410,17 @@ class Plugin
$this->logger->debug('Validando si la etiqueta STRIPE existe en entity pero no en entityBeforeEdit'); $this->logger->debug('Validando si la etiqueta STRIPE existe en entity pero no en entityBeforeEdit');
// Comprobar si la etiqueta 'STRIPE' existe en 'tags' pero no en 'tagsBefore' // Comprobar si la etiqueta 'CREAR CLABE STRIPE' existe en 'tags' pero no en 'tagsBefore'
$stripeTagExists = false; $stripeTagExists = false;
$stripeTagExistsBefore = false; $stripeTagExistsBefore = false;
foreach ($tags as $tag) { foreach ($tags as $tag) {
if ($tag['name'] === 'CREARCLABESTRIPE') { if ($tag['name'] === 'CREAR CLABE STRIPE') {
$stripeTagExists = true; $stripeTagExists = true;
break; break;
} }
} }
foreach ($tagsBefore as $tag) { foreach ($tagsBefore as $tag) {
if ($tag['name'] === 'CREARCLABESTRIPE') { if ($tag['name'] === 'CREAR CLABE STRIPE') {
$stripeTagExistsBefore = true; $stripeTagExistsBefore = true;
break; break;
} }
@ -412,9 +428,9 @@ class Plugin
// Comprobar si la etiqueta 'STRIPE' existe en 'tags' pero no en 'tagsBefore' // Comprobar si la etiqueta 'STRIPE' existe en 'tags' pero no en 'tagsBefore'
if ($stripeTagExists && !$stripeTagExistsBefore) { if ($stripeTagExists && !$stripeTagExistsBefore) {
$this->logger->debug('La etiqueta CREARCLABESTRIPE se agregará al cliente'); $this->logger->debug('La etiqueta CREAR CLABE STRIPE se agregará al cliente');
$this->pluginNotifierFacade->createStripeClient($notification, true); $this->pluginNotifierFacade->createStripeClient($notification, true);
} }
} else { } else {
$this->logger->warning('El campo tags no existe en entity o entityBeforeEdit'); $this->logger->warning('El campo tags no existe en entity o entityBeforeEdit');
} }

View File

@ -5,7 +5,7 @@
'type' => 'library', 'type' => 'library',
'install_path' => __DIR__ . '/../../', 'install_path' => __DIR__ . '/../../',
'aliases' => array(), 'aliases' => array(),
'reference' => '96d7fe6b27798f5bb1deaa200ae416315d270a02', 'reference' => '9a3af1f3d453e226100a2c8ff4c62b4929373492',
'name' => 'ucrm-plugins/sms-twilio', 'name' => 'ucrm-plugins/sms-twilio',
'dev' => false, 'dev' => false,
), ),
@ -307,7 +307,7 @@
'type' => 'library', 'type' => 'library',
'install_path' => __DIR__ . '/../../', 'install_path' => __DIR__ . '/../../',
'aliases' => array(), 'aliases' => array(),
'reference' => '96d7fe6b27798f5bb1deaa200ae416315d270a02', 'reference' => '9a3af1f3d453e226100a2c8ff4c62b4929373492',
'dev_requirement' => false, 'dev_requirement' => false,
), ),
), ),