Compare commits

...

5 Commits
main ... beta

9 changed files with 180 additions and 1125 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 383 KiB

After

Width:  |  Height:  |  Size: 427 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 411 KiB

After

Width:  |  Height:  |  Size: 429 KiB

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":"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,"dataInstallersWhatsApp":"{ \"instaladores\": [{\"ID\": 1015, \"nombre\": \"Daniel Peña, \"whatsapp\": 4181878106}, {\"ID\": 1020, \"nombre\": \"Angel Arvizu\", \"whatsapp\": 4123456789}, {\"ID\": 1035,\"nombre\": \"Juan Rostro, \"whatsapp\": 4198765432}] }","debugMode":true,"logging_level":true}

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,7 @@
"displayName": "SIIP - Procesador de Pagos en línea con Stripe, 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",
"url": "https://siip.mx/",
"version": "2.4.7",
"version": "2.5.2",
"unmsVersionCompliancy": {
"min": "2.1.0",
"max": null

Binary file not shown.

View File

@ -37,7 +37,7 @@ abstract class AbstractOxxoOperationsFacade
* @var UcrmApi
*/
protected $ucrmApi;
protected $stripeCustomAttributeID;
protected $clabeInterbancariaBanamexID;
@ -52,162 +52,166 @@ abstract class AbstractOxxoOperationsFacade
}
/*
* Creates a PaymentIntent for OXXO in Stripe for a Customer
*/
public function createOxxoPaymentIntent($event_json):string
* Creates a PaymentIntent for OXXO in Stripe for a Customer
*/
public function createOxxoPaymentIntent($event_json, $amount = null): string
{
$this->logger->info("Creando referencia del cliente para oxxo: ".PHP_EOL);
$this->logger->info("Creando referencia del cliente para OXXO: " . PHP_EOL);
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
$StripeToken = $config['tokenstripe'];
$IPServer = $config['ipserver'];
$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
//$stripe = new \Stripe\StripeClient('sk_test_51OkG0REFY1WEUtgRH6UxBK5pu80Aq5Iy8EcdPnf0cOWzuVLQTpyLCd7CbPzqMsWMafZOHElCxhEHF7g8boURjWlJ00tBwE0W1M'); //Token de clave privada para la API de Stripe modo pruebas
$baseUri = 'https://' . $IPServer . '/crm/api/v1.0/';
$stripe = new \Stripe\StripeClient($StripeToken);
$this->ucrmApi = UcrmApi::create();
$currentUserAdmin = $this->ucrmApi->get('users/admins',[]);
$currentUserAdmin = $this->ucrmApi->get('users/admins', []);
$clientID = $event_json->client_id;
try {
$stripeCustomerId = null;
$clientEmail = '';
$clientGuzzleHttp = new Client([
'base_uri' => $baseUri,
'headers' => [
'X-Auth-App-Key' => $tokenCRM,
'Accept' => 'application/json',
],
'verify' => false,
]);
$clientGuzzleHttp = new Client([
'base_uri' => $baseUri,
'headers' => [
'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,
]);
// Hacer la solicitud GET para obtener los datos del cliente
$response = $clientGuzzleHttp->request('GET', "clients/".$clientID);
// Obtener el cuerpo de la respuesta como JSON
$arrayClientCRM = json_decode($response->getBody()->getContents(), true);
// 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;
}
$response = $clientGuzzleHttp->request('GET', "clients/" . $clientID);
$arrayClientCRM = json_decode($response->getBody()->getContents(), true);
// Obtener stripeCustomerId
foreach ($arrayClientCRM['attributes'] as $attribute) {
if ($attribute['key'] === 'stripeCustomerId') {
$stripeCustomerId = $attribute['value'];
break;
}
// Recorrer los contactos
foreach ($arrayClientCRM['contacts'] as $contact) {
if ($contact['email'] != '') {
$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);
} catch (RequestException $e) {
// Manejo de errores en la petición
$this->logger->error("Error al obtener atributos personalizados del cliente: " . $e->getMessage().PHP_EOL);
}
$amount = abs($arrayClientCRM['accountOutstanding']) * 100;
//$this->logger->info("User Admin ID: " . json_encode($currentUserAdmin) . PHP_EOL);
if($amount>0){
$this->logger->info("Se obtuvo el Stripe Customer ID: " . $stripeCustomerId . PHP_EOL);
// Obtener email del cliente
foreach ($arrayClientCRM['contacts'] as $contact) {
if (!empty($contact['email'])) {
$clientEmail = $contact['email'];
break;
} else {
$clientEmail = 'siip8873@gmail.com ';
}
}
$this->logger->info("Se analizó el email: " . $clientEmail . PHP_EOL);
// Validar y procesar el monto proporcionado
if ($amount === null) {
$this->logger->info("Se obtiene el monto de los cargos pendientes del cliente" . PHP_EOL);
try {
// Crear el PaymentIntent vinculado al cliente
// Obtener el monto pendiente del cliente en centavos
$amount = abs($arrayClientCRM['accountOutstanding']);
$this->logger->info("Monto pendiente del cliente (procesado): $amount " . PHP_EOL);
} catch (RequestException $e) {
$this->logger->error('Error al obtener el monto pendiente del cliente: ' . $e->getMessage() . PHP_EOL);
return 'errorobtenermontopendiente'; // Error al obtener el monto pendiente
}
} else {
// Extraer solo dígitos numéricos del monto
$numericAmount = preg_replace('/\D/', '', (string) $amount); // Cast $amount to string
$this->logger->info("Se extrajeron los digitos" . PHP_EOL);
if (empty($numericAmount)) {
$this->logger->error("Cantidad no válida proporcionada: " . $amount . PHP_EOL);
return 'cantidadnovalida'; // Retornar error si no se obtiene un valor válido
}
// Convertir el valor limpio a entero
$amount = (int) $numericAmount;
$this->logger->info("Monto proporcionado directamente (procesado): $amount " . PHP_EOL);
}
// Validar que el monto sea mayor a 0 antes de proceder
if ($amount > 10 && $amount !== null) {
$amount = intval($amount * 100);
try {
$paymentIntent = $stripe->paymentIntents->create([
'amount' => $amount, // Monto en centavos (300 MXN)
'amount' => $amount,
'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, // Vincular al cliente existente
'customer' => $stripeCustomerId,
'metadata' => [
'clientId' => $clientID, // ID del cliente en UISP
'createdBy' => 'UCRM',
'clientId' => $clientID,
'createdBy' => 'UCRM',
'paymentType' => 'card.one_time',
'signedInAdminId' => $currentUserAdmin[0]['id']
],
'payment_method_options' => [
'oxxo' => [
'expires_after_days' => 3, // El voucher expira en 3 días
'expires_after_days' => 3,
],
],
]);
// Crear un método de pago OXXO con detalles de facturación
} catch (Exception $e) {
$this->logger->error('Error al crear el payment intent: ' . $e->getMessage() . PHP_EOL);
return 'errorCreatePaymentIntent'; // Error al crear el payment intent
}
try {
$this->logger->info("Creando payment methods del voucher" . PHP_EOL);
$paymentMethod = $stripe->paymentMethods->create([
'type' => 'oxxo',
'billing_details' => [
'name' => $arrayClientCRM['firstName'].' '.$arrayClientCRM['lastName'], // Proporciona el nombre del cliente
'email' => $clientEmail, // Proporciona el correo del cliente
'name' => $arrayClientCRM['firstName'] . ' ' . $arrayClientCRM['lastName'],
'email' => $clientEmail,
],
]);
// Confirmar el PaymentIntent con el método de pago OXXO
} catch (Exception $e) {
$this->logger->error('Error al crear el payment method: ' . $e->getMessage() . PHP_EOL);
return 'errorCreatePaymentMethod'; // Error al crear el payment method
}
try {
$paymentIntent = $stripe->paymentIntents->confirm(
$paymentIntent->id,
['payment_method' => $paymentMethod->id]
);
// 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) {
// Manejar cualquier error
//echo 'Error: ' . $e->getMessage();
$this->logger->error('Error al crear el payment intent: ' . $e->getMessage().PHP_EOL);
return 'error';
$this->logger->error('Error al confirmar el payment intent: ' . $e->getMessage() . PHP_EOL);
return 'errorConfirmPaymentIntent'; // Error al confirmar el payment intent
}
}else{
$this->logger->info("Este cliente no tiene adeudos por lo tanto no se puede genear su referencia de oxxo. " .PHP_EOL);
if (!empty($paymentIntent->next_action) && isset($paymentIntent->next_action->oxxo_display_details)) {
$oxxoPayment = $paymentIntent->next_action->oxxo_display_details;
$oxxo_reference = $oxxoPayment->number;
$oxxo_receipt_url = $oxxoPayment->hosted_voucher_url;
$this->logger->info("Referencia OXXO: " . $oxxo_reference . PHP_EOL);
$this->logger->info("URL del recibo: " . $oxxo_receipt_url . PHP_EOL);
return $oxxo_receipt_url;
} else {
$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 'errorPyamentIntentWithoutOxxoDetails';
}
} else {
$this->logger->info("Este cliente no tiene adeudos por lo tanto no se puede generar su referencia de OXXO. " . PHP_EOL);
return 'errorsinadeudo';
}
}
// /**
// * implement in subclass with the specific messaging provider
// * @see TwilioNotifierFacade::sendWhatsApp()
@ -221,7 +225,7 @@ abstract class AbstractOxxoOperationsFacade
function validarEmail($email)
{
$this->logger->info('SE VALIDA EL EMAIL!!! '.PHP_EOL);
$this->logger->info('SE VALIDA EL EMAIL!!! ' . PHP_EOL);
// Utilizar la función filter_var con el filtro FILTER_VALIDATE_EMAIL para validar el email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Si el email es válido, devolver el email

View File

@ -130,11 +130,32 @@ class Plugin
$this->logger->info('Evento de Energía recibido: ' . $event_json->message . PHP_EOL);
break;
case 'oxxo.request':
$this->logger->info('Evento de referencia de oxxo recibido: ' . PHP_EOL);
$this->logger->info('Evento de referencia de oxxo recibido' . PHP_EOL);
// Construir la URL basada en el "client_id"
// $url = "https://siip.mx/wp/wp-content/uploads/img/voucher.png";
$url = $this->pluginOxxoNotifierFacade->createOxxoPaymentIntent($event_json);
if (!empty($event_json->amount )) {
$this->logger->info('Referencia persnoalizada, Valor del monto: ' . $event_json->amount . PHP_EOL);
$intentos = 0;
do {
if($intentos>1){
sleep(2);
}
$url = $this->pluginOxxoNotifierFacade->createOxxoPaymentIntent($event_json, $event_json->amount );
$intentos++;
} while (strpos($url, 'https') !== 0 && $intentos < 5);
} else {
$intentos = 0;
do {
if($intentos>1){
sleep(2);
}
$url = $this->pluginOxxoNotifierFacade->createOxxoPaymentIntent($event_json);
$intentos++;
} while (strpos($url, 'https') !== 0 && $intentos < 5);
}
// Crear una respuesta en formato JSON
// $response = [
// 'event' => 'response.siip',
@ -146,7 +167,7 @@ class Plugin
'"url": "' . $url . '"' .
'}';
$this->logger->debug('Este ese el reponse que se envía a CallBell: ' . $response);
$this->logger->debug('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);
@ -205,7 +226,7 @@ class Plugin
$payment_method_id = $notification->paymentData['methodId'];
//$this->logger->debug('Metodo de pago: ' . $notification->paymentData['methodId'] . PHP_EOL);
$payment_method = '';
@ -301,7 +322,7 @@ class Plugin
} else if ($notification->eventName === 'service.postpone') {
$this->logger->debug('Se pospuso la suspención del servicio a un cliente' . PHP_EOL);
$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->notifierFacade->notifyOverDue($notification);
} else if ($notification->eventName === 'invoice.overdue') {
@ -319,7 +340,7 @@ class Plugin
$this->logger->debug("Account Balance: " . $accountBalance . PHP_EOL);
$this->logger->debug("Pago hecho con la factura: " . $invoiceAmountPaid . PHP_EOL);
$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->notifierFacade->verifyInvoiceActionToDo($notification);
}

View File

@ -1,11 +1,11 @@
<?php return array(
'root' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => NULL,
'reference' => '3b3cd70eced76670e2aad8fbe97b422f516ab7eb',
'name' => 'ucrm-plugins/sms-twilio',
'dev' => false,
),
@ -302,12 +302,12 @@
'dev_requirement' => false,
),
'ucrm-plugins/sms-twilio' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => NULL,
'reference' => '3b3cd70eced76670e2aad8fbe97b422f516ab7eb',
'dev_requirement' => false,
),
),