Hot fix para nuevos clientes potenciales, se evitara hacer un Stripe customer ID

This commit is contained in:
server 2025-01-05 20:25:12 +00:00
parent 3b3cd70ece
commit ef7156fad2
7 changed files with 301 additions and 1022 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 427 KiB

After

Width:  |  Height:  |  Size: 432 KiB

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.5.1",
"version": "2.5.3",
"unmsVersionCompliancy": {
"min": "2.1.0",
"max": null

View File

@ -37,7 +37,7 @@ abstract class AbstractOxxoOperationsFacade
* @var UcrmApi
*/
protected $ucrmApi;
protected $stripeCustomAttributeID;
protected $clabeInterbancariaBanamexID;
@ -52,138 +52,110 @@ abstract class AbstractOxxoOperationsFacade
}
/*
* Creates a PaymentIntent for OXXO in Stripe for a Customer
*/
* 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);
$configManager = \Ubnt\UcrmPluginSdk\Service\PluginConfigManager::create();
$config = $configManager->loadConfig();
$StripeToken = $config['tokenstripe'];
$IPServer = $config['ipserver'];
$tokenCRM = $config['apitoken'];
{
$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'];
$baseUri = 'https://' . $IPServer . '/crm/api/v1.0/';
$stripe = new \Stripe\StripeClient($StripeToken);
$this->ucrmApi = UcrmApi::create();
$currentUserAdmin = $this->ucrmApi->get('users/admins', []);
$clientID = $event_json->client_id;
$baseUri = 'https://' . $IPServer . '/crm/api/v1.0/';
$stripe = new \Stripe\StripeClient($StripeToken);
$this->ucrmApi = UcrmApi::create();
$currentUserAdmin = $this->ucrmApi->get('users/admins', []);
$clientID = $event_json->client_id;
$stripeCustomerId = null;
$clientEmail = '';
$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,
'Accept' => 'application/json',
],
'verify' => false,
]);
$response = $clientGuzzleHttp->request('GET', "clients/" . $clientID);
$arrayClientCRM = json_decode($response->getBody()->getContents(), true);
$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;
}
// Obtener stripeCustomerId
foreach ($arrayClientCRM['attributes'] as $attribute) {
if ($attribute['key'] === 'stripeCustomerId') {
$stripeCustomerId = $attribute['value'];
break;
}
$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 ';
}
// Obtener email del cliente
foreach ($arrayClientCRM['contacts'] as $contact) {
if (!empty($contact['email'])) {
$clientEmail = $contact['email'];
break;
}
}
// Validar y procesar el monto proporcionado
if ($amount !== null) {
// Extraer solo dígitos numéricos del monto
$numericAmount = preg_replace('/\D/', '', $amount);
// Verificar si $amount es null para determinar si es necesario consultar la API
if ($amount === null) {
try {
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
}
// Obtener el monto pendiente del cliente en centavos
$amount = abs($arrayClientCRM['accountOutstanding']) * 100;
// Convertir el valor limpio a entero
$amount = (int) $numericAmount;
$this->logger->info("Monto proporcionado directamente (procesado): $amount " . PHP_EOL);
} else {
try {
// 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
}
$this->logger->info("Se obtuvieron los datos del cliente y Stripe Customer ID: " . $stripeCustomerId . PHP_EOL);
} catch (RequestException $e) {
$this->logger->error("Error al obtener atributos personalizados del cliente: " . $e->getMessage() . PHP_EOL);
return 'errorGetClientAttributes';
}
} else {
$this->logger->info("Monto proporcionado directamente: $amount " . PHP_EOL);
}
// Validar que el monto sea mayor a 0 antes de proceder
if ($amount > 10) {
$amount = intval($amount * 100);
try {
$paymentIntent = $stripe->paymentIntents->create([
'amount' => $amount,
'currency' => 'mxn',
'payment_method_types' => ['customer_balance', 'card', 'oxxo'],
'description' => 'Pago de servicio de SIIP Internet',
'customer' => $stripeCustomerId,
'metadata' => [
'clientId' => $clientID,
'createdBy' => 'UCRM',
'paymentType' => 'card.one_time',
'signedInAdminId' => $currentUserAdmin[0]['id']
// Validar que el monto sea mayor a 0 antes de proceder
if ($amount > 10) {
$amount = intval($amount * 100);
try {
$this->logger->info("Creando referencia en Stripe por: $amount " . PHP_EOL);
$paymentIntent = $stripe->paymentIntents->create([
'amount' => $amount,
'currency' => 'mxn',
'payment_method_types' => ['customer_balance', 'card', 'oxxo'],
'description' => 'Pago de servicio de SIIP Internet',
'customer' => $stripeCustomerId,
'metadata' => [
'clientId' => $clientID,
'createdBy' => 'UCRM',
'paymentType' => 'card.one_time',
'signedInAdminId' => $currentUserAdmin[0]['id']
],
'payment_method_options' => [
'oxxo' => [
'expires_after_days' => 3,
],
'payment_method_options' => [
'oxxo' => [
'expires_after_days' => 3,
],
],
]);
} 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'],
'email' => $clientEmail,
],
]);
} 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]
);
} catch (Exception $e) {
$this->logger->error('Error al confirmar el payment intent: ' . $e->getMessage() . PHP_EOL);
return 'errorConfirmPaymentIntent'; // Error al confirmar el payment intent
}
],
]);
$this->logger->info("Creando payment methods del voucher" . PHP_EOL);
$paymentMethod = $stripe->paymentMethods->create([
'type' => 'oxxo',
'billing_details' => [
'name' => $arrayClientCRM['firstName'] . ' ' . $arrayClientCRM['lastName'],
'email' => $clientEmail,
],
]);
$this->logger->info("Confirmando el paymentIntent" . PHP_EOL);
$paymentIntent = $stripe->paymentIntents->confirm(
$paymentIntent->id,
['payment_method' => $paymentMethod->id]
);
$this->logger->info("Se terminó de confirmar el paymentIntent" . 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;
@ -197,13 +169,17 @@ abstract class AbstractOxxoOperationsFacade
$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';
} catch (Exception $e) {
$this->logger->error('Error al crear el payment intent: ' . $e->getMessage() . PHP_EOL);
return 'errorCreatePaymentIntent';
}
} else {
$this->logger->info("Este cliente no tiene adeudos por lo tanto no se puede generar su referencia de OXXO. " . PHP_EOL);
return 'errorsinadeudo';
}
}
@ -220,7 +196,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

@ -155,9 +155,27 @@ abstract class AbstractStripeOperationsFacade
$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);
// Asegúrate de trabajar con un objeto PHP
$dataObject = json_decode(json_encode($notification_client_data)); // Convertir a JSON y luego decodificar como objeto
if (!is_object($dataObject)) {
$this->logger->info("Error: Los datos del cliente no pudieron ser procesados." . PHP_EOL);
return;
}
// Acceder a "isLead" de forma segura
$isLead = $dataObject->isLead ?? null;
$this->logger->info("El valor de 'isLead' es: " . ($isLead ? "true" : "false") . PHP_EOL);
if ($isLead === true) {
$this->logger->info("El cliente es un lead, no se procesará" . PHP_EOL);
return;
} else {
$this->logger->info("El cliente NO es un lead, se procesará" . PHP_EOL);
$this->createCustomerStripe($notificationData, $stripe, $baseUri, $UCRMAPIToken);
}
}
@ -260,7 +278,7 @@ abstract class AbstractStripeOperationsFacade
],
]
);
$this->logger->info("CLABE guardada en metadata: " . $customer->metadata->clabe . PHP_EOL);

View File

@ -136,7 +136,7 @@ class Plugin
// Construir la URL basada en el "client_id"
// $url = "https://siip.mx/wp/wp-content/uploads/img/voucher.png";
if (!empty($event_json->amount )) {
$this->logger->info('Valor del monto: ' . $event_json->amount . PHP_EOL);
$this->logger->info('Referencia persnoalizada, Valor del monto: ' . $event_json->amount . PHP_EOL);
$intentos = 0;
do {
if($intentos>1){
@ -167,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);

View File

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