1281 lines
57 KiB
PHP
Executable File
1281 lines
57 KiB
PHP
Executable File
<?php
|
|
|
|
namespace SmsNotifier\Facade;
|
|
|
|
use CURLFile;
|
|
use DateTime;
|
|
use GuzzleHttp\Client;
|
|
use GuzzleHttp\Exception\GuzzleException;
|
|
use Imagick;
|
|
use Ubnt\UcrmPluginSdk\Service\PluginLogManager;
|
|
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
|
|
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
|
|
use Ubnt\UcrmPluginSdk\Service\UcrmOptionsManager;
|
|
|
|
//use SmsNotifier\Service\Logger;
|
|
|
|
class ClientCallBellAPI
|
|
{
|
|
|
|
/**
|
|
* @var
|
|
*/
|
|
private $CallBellAPIToken;
|
|
/**
|
|
* @var
|
|
*/
|
|
private $IPServer;
|
|
/**
|
|
* @var
|
|
*/
|
|
private $UCRMAPIToken;
|
|
/**
|
|
* @var UcrmApi
|
|
*/
|
|
private $ucrmApi;
|
|
|
|
/**
|
|
* @var pluginConfigManager
|
|
*/
|
|
|
|
private $pluginConfigManager;
|
|
|
|
/**
|
|
* @var Logger
|
|
*/
|
|
private $logger;
|
|
|
|
private $ucrmUri;
|
|
private $printsites;
|
|
|
|
/**
|
|
* @var UnmsApi
|
|
*/
|
|
private $unmsApi; //Enable only for UNMS v1
|
|
|
|
public $ucrmVersion;
|
|
|
|
|
|
public function __construct(
|
|
$UCRMAPIToken,
|
|
$IPServer,
|
|
$CallBellAPIToken
|
|
) {
|
|
$this->UCRMAPIToken = $UCRMAPIToken;
|
|
$this->IPServer = $IPServer;
|
|
$this->CallBellAPIToken = $CallBellAPIToken;
|
|
}
|
|
|
|
public function updateContact($client_uuid)
|
|
{
|
|
}
|
|
|
|
public function printPrueba($clientWhatsAppNumber, $notificationData)
|
|
{
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
$log->appendLog("Ejecutando metodo print prueba: " . $clientWhatsAppNumber);
|
|
// $logger = new Logger();
|
|
// $logger->debug('Ejecutando metodo print prueba con Logger');
|
|
}
|
|
|
|
public function sendMessageWhatsApp($clientWhatsAppNumber, $notificationData)
|
|
{
|
|
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
$log->appendLog("Entrando al metodo sendMessageWhatsApp" . PHP_EOL);
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer g8thcZkXGd3xBj2g3TtYNYFMH1fuesbJ.b6a940ea7d78cf6c9e42f067b21c8ddf96e9fa2a9e307bfd0c7c7c4d7fa38f79',
|
|
'Content-Type: application/json',
|
|
]);
|
|
|
|
// $jsonString = json_encode($notificationData);
|
|
// $log->appendLog($jsonString);
|
|
|
|
$campo1 = sprintf("😀 *%s %s*", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
|
|
$log->appendLog("Valor del campo1: " . $campo1);
|
|
$estado_service = ($notificationData->clientData['hasSuspendedService']) ? 'Suspendido 🔴' : 'Activo 🟢';
|
|
$log->appendLog("Valor del estado_service: " . $estado_service);
|
|
$domicilio = ($notificationData->clientData['fullAddress'] == null) ? 'Sin domicilio' : $notificationData->clientData['fullAddress'];
|
|
$log->appendLog("Valor del domicilio: " . $domicilio);
|
|
$campo2 = sprintf("📡 Su servicio está: %s 📍Su dirección es: *%s* ", $estado_service, $domicilio);
|
|
$log->appendLog("Valor del campo2 " . $campo2);
|
|
|
|
|
|
|
|
|
|
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }";
|
|
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
|
|
|
|
$response = curl_exec($ch);
|
|
$log->appendLog("Response del CallBell: " . $response);
|
|
|
|
curl_close($ch);
|
|
}
|
|
|
|
public function sendPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool
|
|
{
|
|
|
|
|
|
|
|
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
|
|
$log->appendLog("Eviando comprobante de pago al cliente: " . $notificationData->clientData['id'] . ' con número: ' . $clientWhatsAppNumber . PHP_EOL);
|
|
|
|
// URL base de la API
|
|
$baseUri = 'https://' . $this->IPServer . '/crm/api/v1.0/';
|
|
// Token de autenticación
|
|
$token = $this->UCRMAPIToken;
|
|
//Path base del comprobante de pago
|
|
$pdf_payment_path = '';
|
|
|
|
|
|
$this->ucrmApi = UcrmApi::create();
|
|
$payments = $this->ucrmApi->get(
|
|
'payments/',
|
|
[
|
|
'clientId' => $notificationData->clientData['id'],
|
|
'limit' => 1,
|
|
'direction' => 'DESC'
|
|
|
|
]
|
|
);
|
|
|
|
//$datos_payment_array = json_decode($payments,true);
|
|
$datos_payment = json_encode($payments);
|
|
|
|
//$log->appendLog("Datos traidos con payment api: " . $datos_payment . PHP_EOL);
|
|
//$log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos: " . $notificationData->paymentData[0]['createdDate']. PHP_EOL);
|
|
// $log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos opcion 2: " . $payments[0]['createdDate'] . PHP_EOL);
|
|
|
|
$payment_id = $payments[0]['id'];
|
|
$payment_amount = '$' . $payments[0]['amount'];
|
|
//$saldo = '$' . $notificationData->clientData['accountBalance'];
|
|
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
|
|
|
|
$accountBalance = $notificationData->clientData['accountBalance'];
|
|
$saldoTexto = '';
|
|
|
|
if ($accountBalance < 0) {
|
|
// Si el saldo es negativo, quitar el signo y poner "Pendientes"
|
|
$saldoTexto = '$' . abs($accountBalance) . ' pendientes';
|
|
} elseif ($accountBalance > 0) {
|
|
// Si el saldo es positivo, poner "a favor"
|
|
$saldoTexto = '$' . $accountBalance . ' a favor';
|
|
} else {
|
|
// Si el saldo es 0, poner "está al corriente"
|
|
$saldoTexto = '$' . $accountBalance . ' está al corriente';
|
|
}
|
|
|
|
// Configuración del cliente GuzzleHttp
|
|
$clientGuzzleHttp = new Client([
|
|
'base_uri' => $baseUri,
|
|
'headers' => [
|
|
'X-Auth-App-Key' => $token, // Cambia el nombre de la cabecera de autorización
|
|
'Accept' => 'application/pdf', // Indica que esperamos una respuesta en formato JSON
|
|
],
|
|
'verify' => false,
|
|
]);
|
|
|
|
|
|
|
|
try {
|
|
|
|
// Hacer la solicitud GET
|
|
$response = $clientGuzzleHttp->request('GET', "payments/$payment_id/pdf");
|
|
|
|
// Realizar la solicitud a la API y guardar el contenido en un archivo local
|
|
$contenidoArchivo = $response->getBody()->getContents();
|
|
|
|
// Reemplazar nombre del cliente espacios por guiones bajos y concatenar la extensión ".pdf" para construir el nombre del archivo
|
|
//$fileNameComprobante = 'Comprobante_' . str_replace(' ', '_', $nombre_cliente) . '.pdf';
|
|
$fileNameComprobante = 'Comprobante_' . str_replace(' ', '_', $nombre_cliente) . '.png';
|
|
|
|
|
|
// Guardar el contenido en un archivo local
|
|
$resultado = file_put_contents(__DIR__ . '/../../comprobantes/' . $fileNameComprobante, $contenidoArchivo);
|
|
|
|
if ($resultado !== false) {
|
|
$log->appendLog("El archivo se ha descargado correctamente y se ha guardado en: " . __DIR__ . '/../../comprobantes/' . $fileNameComprobante . PHP_EOL);
|
|
} else {
|
|
$log->appendLog("Se produjo un error al descargar y guardar el archivo." . PHP_EOL);
|
|
}
|
|
|
|
// Obtener el cuerpo de la respuesta (contenido binario)
|
|
$binaryData = $response->getBody()->getContents();
|
|
|
|
|
|
|
|
// Abrir un recurso de flujo de datos en memoria
|
|
$fileHandle = fopen('php://temp', 'r+');
|
|
|
|
// Escribir los datos binarios en el recurso de flujo de datos en memoria
|
|
fwrite($fileHandle, $binaryData);
|
|
|
|
// Rebobinar el puntero del flujo de datos para leer desde el principio
|
|
rewind($fileHandle);
|
|
|
|
if (!isset($fileHandle)) {
|
|
$log->appendLog("viene vacia la variable filehandle" . PHP_EOL);
|
|
}
|
|
} catch (\Exception $e) {
|
|
$log->appendLog("Error con un problema al generar y comprobante de pago: " . $e->getMessage() . PHP_EOL);
|
|
return false;
|
|
}
|
|
|
|
|
|
try {
|
|
// Obtener el nombre del archivo del encabezado Content-Disposition si está presente
|
|
$serverFilename = null;
|
|
$content_disposition = $response->getHeaderLine('Content-Disposition');
|
|
|
|
if (!empty($content_disposition)) {
|
|
preg_match('/filename=([^;]+)/', $content_disposition, $matches);
|
|
if (isset($matches[1])) {
|
|
$serverFilename = trim($matches[1], '"');
|
|
$pdf_payment_path = '/home/unms/data/ucrm/ucrm/data/payment_receipts/' . $serverFilename;
|
|
}
|
|
}
|
|
|
|
// Si no se encontró un nombre de archivo, usar un nombre predeterminado
|
|
if (empty((($serverFilename)))) {
|
|
$pdf_payment_path = '/home/unms/data/ucrm/ucrm/data/payment_receipts/comprobante.pdf';
|
|
}
|
|
|
|
//imprimir el nombre del archivo
|
|
$log->appendLog("El nombre del archivo PDF es: $pdf_payment_path" . PHP_EOL);
|
|
|
|
} catch (\Exception $exception) {
|
|
$log->appendLog("Error con un problema al generar y comprobante de pago: " . $exception->getMessage() . PHP_EOL);
|
|
return false;
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
//******************
|
|
|
|
// Ruta del archivo PDF
|
|
//$pdfFilePath = dirname(dirname(dirname(dirname(__DIR__)))) . '//payment_receipts/' . $serverFilename;
|
|
// Instanciar Imagick con la ruta del archivo PDF
|
|
$image = new Imagick();
|
|
$log->appendLog("se creó la instancia de Imagick" . PHP_EOL);
|
|
|
|
|
|
$image->setResolution(1024, 1024); // Establecer la resolución (opcional)
|
|
|
|
// Leer el archivo PDF
|
|
$image->readImage(__DIR__ . '/../../comprobantes/' . $fileNameComprobante);
|
|
|
|
$image->resizeImage(1024, 1024, Imagick::FILTER_LANCZOS, 1, true);
|
|
// Obtener las dimensiones originales de la imagen
|
|
$ancho_original = $image->getImageWidth();
|
|
$altura_original = $image->getImageHeight();
|
|
$log->appendLog("Ancho original de la imagen:" . $ancho_original . " Altura original de la imagen: " . $altura_original . PHP_EOL);
|
|
|
|
// Calcular las coordenadas de inicio del área a recortar
|
|
$inicio_x = $ancho_original * 0.14; // 14% del ancho
|
|
$inicio_y = $altura_original * 0.05; // 5% de la altura
|
|
$log->appendLog("Inicio x:" . $inicio_x . " Inicio y: " . $inicio_y . PHP_EOL);
|
|
|
|
// Calcular el ancho y la altura del área a recortar
|
|
$nuevo_ancho = $ancho_original * 0.7; // 70% del ancho del comprbante final
|
|
$nueva_altura = $altura_original * 0.55; // 60% de la altura del comprobante final
|
|
//$log->appendLog("Nuevo ancho:".$nuevo_ancho ." Nuevo alto: ".$nueva_altura. PHP_EOL);
|
|
|
|
// Recortar la imagen
|
|
$image->cropImage($nuevo_ancho, $nueva_altura, $inicio_x, $inicio_y);
|
|
|
|
// Convertir la primera página del PDF a imagen
|
|
$image->setImageFormat('png');
|
|
$image->writeImage(__DIR__ . '/../../comprobantes/' . $fileNameComprobante);
|
|
|
|
// Liberar recursos
|
|
$image->destroy();
|
|
$log->appendLog("Terminó de crear la imagen del comprobante" . PHP_EOL);
|
|
|
|
//******************
|
|
|
|
} catch (\Exception $exception) {
|
|
$log->appendLog("Error al crear la imagen: " . $exception . PHP_EOL);
|
|
return false;
|
|
}
|
|
|
|
|
|
|
|
$url_file = $this->UploadReceiptToWordpressByImageFileName($fileNameComprobante);//Carga del comprobante PDF a Wordpress para su posterior envío
|
|
//$url_file = $this->UploadReceiptToWordpressByServerFileName($serverFilename, $fileNameComprobante);//Carga del comprobante PDF a Wordpress para su posterior envío
|
|
//$url_file = $this->UploadReceiptToWordpressByCustomLocalFileName($fileNameComprobante);//Carga del comprobante PDF a Wordpress para su posterior envío
|
|
|
|
$log->appendLog("Se terminó de subir comprobante a wordpress " . PHP_EOL);
|
|
|
|
// if (empty($notificationData->clientData['contacts'][0]['email'])) {
|
|
// $log->appendLog("El cliente no tiene correo" . PHP_EOL);
|
|
// } else {
|
|
// // $log->appendLog("El cliente SI tiene correo y es: ".$notificationData->clientData['contacts'][0]['email'] . PHP_EOL);
|
|
// // Hacer la solicitud PATCH para enviar correo electronico con el comprobante de pago
|
|
// $response = $clientGuzzleHttp->request('PATCH', "payments/$payment_id/send-receipt");
|
|
|
|
// }
|
|
|
|
|
|
//$log->appendLog("Entrando al metodo sendPaymentNotificationWhatsAp" . PHP_EOL);
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $this->CallBellAPIToken,
|
|
'Content-Type: application/json',
|
|
]);
|
|
|
|
// Verificar si la ruta es válida
|
|
// if ($realPath = realpath('/data/ucrm/data/plugins/siip-whatsapp-notifications/src/Facade/Comprobante.pdf')) {
|
|
// $log->appendLog("La ruta es válida: $realPath" . PHP_EOL);
|
|
// $log->appendLog(var_export($realPath,true) . PHP_EOL);
|
|
|
|
// } else {
|
|
// $log->appendLog("La ruta no es válida o no existe" . PHP_EOL);
|
|
// }
|
|
|
|
|
|
|
|
|
|
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldoTexto\"],\n \"template_uuid\": \"57ead79cebd14902921477922403093b\",\n \"optin_contact\": true\n }";
|
|
|
|
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"6c0df98317b44f7b8666375a6cc8454c\",\n \"optin_contact\": true\n }";
|
|
|
|
// $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }";
|
|
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
|
|
|
|
$response = curl_exec($ch);
|
|
$log->appendLog("Response del CallBell: " . $response);
|
|
|
|
//Enviar notificación adicional si es transferencia
|
|
// if($transferNotify){
|
|
// curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_uuid\": \"41783c020cd84881bc27cb9e7e1da348\",\n \"optin_contact\": true\n }");
|
|
// $response2 = curl_exec($ch);
|
|
// $log->appendLog("Response del CallBell aviso adicional: " . $response2);
|
|
// }
|
|
|
|
curl_close($ch);
|
|
$this->deleteFilesExceptLastFifty();
|
|
//return $fileNameComprobante;
|
|
return true;
|
|
}
|
|
public function sendTextPaymentNotificationWhatsApp($clientWhatsAppNumber, $notificationData): bool
|
|
{
|
|
|
|
|
|
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
|
|
$folio = $notificationData->paymentData['id'];
|
|
$client_id = $notificationData->clientData['id'];
|
|
$fecha_pago = null;
|
|
$cantidad_pagada = $notificationData->paymentData['amount'];
|
|
$metodo_pago = '';
|
|
//$invoice_id= null;
|
|
$total_factura = null;
|
|
$pago_factura = $notificationData->paymentData['amount'];
|
|
// $saldoTexto= null;
|
|
$creditoPorPago = $notificationData->paymentData['creditAmount'];
|
|
$texto_credito = null;
|
|
$creditoClienteBase = $notificationData->clientData['accountCredit'];
|
|
|
|
|
|
|
|
|
|
switch ($notificationData->paymentData['methodId']) {
|
|
case '11721cdf-a498-48be-903e-daa67552e4f6':
|
|
$metodo_pago = 'Cheque 📄';
|
|
break;
|
|
case '6efe0fa8-36b2-4dd1-b049-427bffc7d369':
|
|
$metodo_pago = 'Efectivo 💵';
|
|
break;
|
|
case '4145b5f5-3bbc-45e3-8fc5-9cda970c62fb':
|
|
$metodo_pago = 'Transferencia bancaria 📱🏦';
|
|
break;
|
|
case '78e84000-9b5b-44a4-8367-da43df86ce34':
|
|
$metodo_pago = 'PayPal 🌐💳';
|
|
break;
|
|
case '6da98bb9-6df7-4c41-8608-5cdd7fde7d5d':
|
|
$metodo_pago = 'Tarjeta de crédito PayPal 💳';
|
|
break;
|
|
case '1dd098fa-5d63-4c8d-88b7-3c27ffbbb6ae':
|
|
$metodo_pago = 'Tarjeta de crédito Stripe 💳';
|
|
break;
|
|
case 'b9e1e9d1-5c7b-41d2-b6b2-3e568d700290':
|
|
$metodo_pago = 'Suscripción de Stripe (tarjeta de crédito) 🌐💳';
|
|
break;
|
|
case '939f7701-00b7-4676-9b1e-17afb268c8ba':
|
|
$metodo_pago = 'Suscripción de PayPal 🌐💳';
|
|
break;
|
|
case '1c963e35-df24-444d-95d2-12592d5107e8':
|
|
$metodo_pago = 'MercadoPago 🌐💳';
|
|
break;
|
|
case 'd8c1eae9-d41d-479f-aeaf-38497975d7b3':
|
|
$metodo_pago = 'Personalizado 📝💸';
|
|
break;
|
|
default:
|
|
$metodo_pago = 'Desconocido, revisar metodos de pago no contemplados';
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
|
|
$log->appendLog("Eviando comprobante de pago al cliente: " . $notificationData->clientData['id'] . ' con número: ' . $clientWhatsAppNumber . PHP_EOL);
|
|
|
|
// URL base de la API
|
|
$baseUri = 'https://' . $this->IPServer . '/crm/api/v1.0/';
|
|
// Token de autenticación
|
|
$token = $this->UCRMAPIToken;
|
|
//Path base del comprobante de pago
|
|
$pdf_payment_path = '';
|
|
|
|
|
|
$this->ucrmApi = UcrmApi::create();
|
|
$payments = $this->ucrmApi->get(
|
|
'payments/',
|
|
[
|
|
'clientId' => $notificationData->clientData['id'],
|
|
'limit' => 1,
|
|
'direction' => 'DESC'
|
|
|
|
]
|
|
);
|
|
|
|
//$datos_payment_array = json_decode($response->getBody()->getContents(), true);
|
|
$datos_paymentJsonText = json_encode($payments, true);
|
|
$log->appendLog("Datos traidos con payment api: " . $datos_paymentJsonText . PHP_EOL);
|
|
|
|
|
|
// $log->appendLog("Check 1" . PHP_EOL);
|
|
$paymentDate = new DateTime($fecha_pago);
|
|
|
|
// Restar 6 horas
|
|
$paymentDate->modify('-6 hours');
|
|
|
|
// Formatear la fecha como "d/m/Y g:ia" (día/mes/año hora:minutos am/pm)
|
|
$fecha_pago = $paymentDate->format('d/m/Y g:ia');
|
|
|
|
|
|
$accountBalance = $notificationData->clientData['accountBalance'];
|
|
$saldoTexto = '';
|
|
|
|
if ($accountBalance < 0) {
|
|
// Si el saldo es negativo, quitar el signo y poner "Pendientes"
|
|
$saldoTexto = '$' . abs($accountBalance) . ' pendientes';
|
|
} elseif ($accountBalance > 0) {
|
|
// Si el saldo es positivo, poner "a favor"
|
|
$saldoTexto = '$' . $accountBalance . ' a favor';
|
|
} else {
|
|
// Si el saldo es 0, poner "está al corriente"
|
|
$saldoTexto = '$' . $accountBalance . ' está al corriente';
|
|
}
|
|
|
|
$log->appendLog("Datos client data credit amount: " . $notificationData->paymentData['creditAmount'] . PHP_EOL);
|
|
|
|
$cantidad_pagadaFormateada = '$' . number_format($cantidad_pagada, 2, ',', '.') . ' MXN';
|
|
$creditoPorPagoFormateado = '$' . number_format($creditoPorPago, 2, ',', '.') . ' MXN';
|
|
|
|
if ($creditoClienteBase > 0 && empty($notificationData->paymentData['paymentCovers'])) {
|
|
|
|
|
|
$texto_credito = "La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito";
|
|
$log->appendLog("La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito" . PHP_EOL);
|
|
|
|
|
|
|
|
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$folio\", \"$client_id\", \"$fecha_pago\", \"$cantidad_pagadaFormateada\", \"$metodo_pago\", \"$saldoTexto\", \"$texto_credito\"],\n \"template_uuid\": \"4ac9dc060cf746b6ad7f2e8acad355e0\",\n \"optin_contact\": true\n }";
|
|
|
|
|
|
} else {
|
|
|
|
if ($creditoPorPago > 0) {
|
|
$texto_credito = "La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito";
|
|
$log->appendLog("La cantidad que sobra de $creditoPorPagoFormateado se ha convertido a crédito" . PHP_EOL);
|
|
|
|
}else{
|
|
$texto_credito = '_________________________';
|
|
}
|
|
|
|
// Configuración del cliente GuzzleHttp
|
|
$clientGuzzleHttp = new Client([
|
|
'base_uri' => $baseUri,
|
|
'headers' => [
|
|
'X-Auth-App-Key' => $token, // Cambia el nombre de la cabecera de autorización
|
|
'Accept' => 'application/pdf', // Indica que esperamos una respuesta en formato JSON
|
|
],
|
|
'verify' => false,
|
|
]);
|
|
|
|
$log->appendLog("Verificar paymentCovers " . PHP_EOL);
|
|
|
|
|
|
$log->appendLog("payment covers" . json_encode($notificationData->paymentData['paymentCovers']) . PHP_EOL);
|
|
|
|
|
|
if (!empty($notificationData->paymentData['paymentCovers'])) {
|
|
$log->appendLog('Datos del payment covers:' . PHP_EOL);
|
|
|
|
$invoiceIds = ''; // Variable para almacenar los invoiceId
|
|
$amounts = ''; // Variable para almacenar los amounts formateados
|
|
|
|
foreach ($notificationData->paymentData['paymentCovers'] as $paymentCover) {
|
|
$log->appendLog('Invoice ID pagado: ' . $paymentCover['invoiceId'] . ' de esta cantidad: ' . $paymentCover['amount'] . PHP_EOL);
|
|
|
|
// Concatenar cada invoiceId seguido de una coma
|
|
$invoiceIds .= $paymentCover['invoiceId'] . ', ';
|
|
|
|
// Formatear el amount con punto para miles y coma para decimales
|
|
$formattedAmount = number_format($paymentCover['amount'], 2, ',', '.');
|
|
|
|
// Concatenar el amount formateado seguido de una coma
|
|
$amounts .= $formattedAmount . ', ';
|
|
}
|
|
|
|
// Eliminar la última coma y el espacio extra usando substr
|
|
$invoiceIds = substr($invoiceIds, 0, -2); // Elimina los últimos dos caracteres (coma y espacio)
|
|
$amounts = substr($amounts, 0, -2); // Elimina los últimos dos caracteres (coma y espacio)
|
|
|
|
// Mostrar las cadenas finales
|
|
$log->appendLog('Todos los Invoice IDs: ' . $invoiceIds . PHP_EOL);
|
|
$log->appendLog('Todas las cantidades: ' . $amounts . PHP_EOL);
|
|
|
|
try {
|
|
|
|
// Hacer la solicitud GET
|
|
$response = $clientGuzzleHttp->request('GET', "invoices/$invoiceIds");
|
|
|
|
// Realizar la solicitud a la API y guardar el contenido en un archivo local
|
|
$responseInvoices = $response->getBody()->getContents();
|
|
$responseInvoicesJSON = json_decode($responseInvoices, true);
|
|
$log->appendLog('Numero de factura: ' . $responseInvoicesJSON['number'] . PHP_EOL);
|
|
$log->appendLog('TOTAL de factura: ' . $responseInvoicesJSON['total'] . PHP_EOL);
|
|
$total_factura = $responseInvoicesJSON['total'];
|
|
|
|
|
|
|
|
} catch (\Exception $e) {
|
|
$log->appendLog("Error con un problema al obtener alguna factura del cliente: " . $e->getMessage() . PHP_EOL);
|
|
return false;
|
|
}
|
|
|
|
} else {
|
|
$log->appendLog("no hay datos en payment covers" . PHP_EOL);
|
|
$invoiceIds = $notificationData->paymentData['id'];
|
|
$amounts = $notificationData->paymentData['amount'];
|
|
$total_factura = 0;
|
|
}
|
|
//$cantidad_pagadaFormateada = '$' . number_format($cantidad_pagada, 2, ',', '.') . ' MXN';
|
|
$log->appendLog("Se terminó de verificar payment covers" . PHP_EOL);
|
|
$total_facturaFormateada = '$' . number_format($total_factura, 2, ',', '.') . ' MXN';
|
|
$pagoFacturaFormateado = '$' . $amounts. ' MXN';
|
|
|
|
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$folio\", \"$client_id\", \"$fecha_pago\", \"$cantidad_pagadaFormateada\", \"$metodo_pago\", \"$invoiceIds\", \"$total_facturaFormateada\", \"$pagoFacturaFormateado\", \"$saldoTexto\", \"$texto_credito\"],\n \"template_uuid\": \"c1396a6ad3cb4192916d4ac2bfb782a5\",\n \"optin_contact\": true\n }";
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//$log->appendLog("Entrando al metodo sendPaymentNotificationWhatsAp" . PHP_EOL);
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $this->CallBellAPIToken,
|
|
'Content-Type: application/json',
|
|
]);
|
|
|
|
|
|
|
|
|
|
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"6c0df98317b44f7b8666375a6cc8454c\",\n \"optin_contact\": true\n }";
|
|
|
|
// $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }";
|
|
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
|
//curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
|
|
$response = curl_exec($ch);
|
|
$log->appendLog("Response del CallBell: " . $response);
|
|
|
|
//Enviar notificación adicional si es transferencia
|
|
// if($transferNotify){
|
|
// curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"John Doe\"\n },\n \"template_uuid\": \"41783c020cd84881bc27cb9e7e1da348\",\n \"optin_contact\": true\n }");
|
|
// $response2 = curl_exec($ch);
|
|
// $log->appendLog("Response del CallBell aviso adicional: " . $response2);
|
|
// }
|
|
|
|
curl_close($ch);
|
|
//$this->deleteFilesExceptLastFifty();
|
|
//return $fileNameComprobante;
|
|
return true;
|
|
}
|
|
|
|
public function sendOverdueNotificationWhatsApp($clientWhatsAppNumber, $notificationData): void
|
|
{
|
|
|
|
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
|
|
// URL base de la API
|
|
//$baseUri = 'https://' . $this->IPServer . '/crm/api/v1.0/';
|
|
// Token de autenticación
|
|
//$token = $this->UCRMAPIToken;
|
|
//Path base del comprobante de pago
|
|
//$pdf_payment_path = '';
|
|
|
|
|
|
// $this->ucrmApi = UcrmApi::create();
|
|
// $invoices = $this->ucrmApi->get(
|
|
// 'invoices/',
|
|
// [
|
|
// 'clientId' => $notificationData->clientData['id'],
|
|
// 'limit' => 1,
|
|
// 'direction' => 'DESC'
|
|
|
|
// ]
|
|
// );
|
|
|
|
//$datos_payment_array = json_decode($payments,true);
|
|
//$datos_invoices = json_encode($invoices);
|
|
|
|
//$log->appendLog("Datos traidos con invoices api: " . $datos_invoices . PHP_EOL);
|
|
//$log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos: " . $notificationData->paymentData[0]['createdDate']. PHP_EOL);
|
|
// $log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos opcion 2: " . $payments[0]['createdDate'] . PHP_EOL);
|
|
|
|
// $invoice_id = $invoices[0]['id'];
|
|
// $invoices_amount = '$' . $invoices[0]['amount'];
|
|
$saldo = '$' . $notificationData->clientData['accountBalance'];
|
|
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
|
|
|
|
// Configuración del cliente GuzzleHttp
|
|
// $clientGuzzleHttp = new Client([
|
|
// 'base_uri' => $baseUri,
|
|
// 'headers' => [
|
|
// 'X-Auth-App-Key' => $token, // Cambia el nombre de la cabecera de autorización
|
|
// 'Accept' => 'application/pdf', // Indica que esperamos una respuesta en formato JSON
|
|
// ],
|
|
// 'verify' => false,
|
|
// ]);
|
|
|
|
|
|
|
|
// if (empty($notificationData->clientData['contacts'][0]['email'])) {
|
|
// $log->appendLog("El cliente no tiene correo" . PHP_EOL);
|
|
// } else {
|
|
// // $log->appendLog("El cliente SI tiene correo y es: ".$notificationData->clientData['contacts'][0]['email'] . PHP_EOL);
|
|
// // Hacer la solicitud PATCH para enviar correo electronico con el comprobante de pago
|
|
// $response = $clientGuzzleHttp->request('PATCH', "invoices/$invoice_id/send");
|
|
|
|
// }
|
|
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, 'https://api.callbell.eu/v1/messages/send');
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $this->CallBellAPIToken,
|
|
'Content-Type: application/json',
|
|
]);
|
|
|
|
// Verificar si la ruta es válida
|
|
// if ($realPath = realpath('/data/ucrm/data/plugins/siip-whatsapp-notifications/src/Facade/Comprobante.pdf')) {
|
|
// $log->appendLog("La ruta es válida: $realPath" . PHP_EOL);
|
|
// $log->appendLog(var_export($realPath,true) . PHP_EOL);
|
|
|
|
// } else {
|
|
// $log->appendLog("La ruta no es válida o no existe" . PHP_EOL);
|
|
// }
|
|
|
|
|
|
|
|
|
|
$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"SIIP INTERNET\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\",\n },\n \"template_values\": [\"$nombre_cliente\", \"$saldo\"],\n \"template_uuid\": \"9e7024c0a61a4c49b382150d26888dc2\",\n \"optin_contact\": true\n }";
|
|
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"57ead79cebd14902921477922403093b\",\n \"optin_contact\": true\n }";
|
|
//$curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"document\",\n \"content\": {\n \"text\": \"S/M\",\n \"url\": \"$url_file\"\n },\n \"template_values\": [\"$nombre_cliente\", \"$payment_amount\", \"$saldo\"],\n \"template_uuid\": \"6c0df98317b44f7b8666375a6cc8454c\",\n \"optin_contact\": true\n }";
|
|
|
|
// $curl_string = "{\n \"to\": \"$clientWhatsAppNumber\",\n \"from\": \"whatsapp\",\n \"type\": \"text\",\n \"content\": {\n \"text\": \"S/M\"\n },\n \"template_values\": [\"$campo1\", \"$campo2\"],\n \"template_uuid\": \"55705f1fe4e24bab80104dc2643fe11c\",\n \"optin_contact\": true\n }";
|
|
$log->appendLog("La cadena CURL que se envia es: " . $curl_string);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_string);
|
|
|
|
$response = curl_exec($ch);
|
|
$log->appendLog("Response del CallBell: " . $response);
|
|
|
|
curl_close($ch);
|
|
|
|
}
|
|
|
|
|
|
public function getContactWhatsapp($cellphone_number): string
|
|
{
|
|
// URL de la API REST
|
|
$apiUrl = 'https://api.callbell.eu/v1/contacts/phone/' . $cellphone_number;
|
|
|
|
// Inicializar cURL
|
|
$ch = curl_init();
|
|
|
|
// Configurar las opciones de cURL
|
|
curl_setopt($ch, CURLOPT_URL, $apiUrl);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $this->CallBellAPIToken,
|
|
'Content-Type: application/json'
|
|
]);
|
|
|
|
// Ejecutar la solicitud y obtener la respuesta
|
|
$response = curl_exec($ch);
|
|
|
|
// Verificar si hay errores en la solicitud cURL
|
|
if (curl_errno($ch)) {
|
|
return 'Error al realizar la solicitud cURL: ' . curl_error($ch);
|
|
} else {
|
|
// Cerrar la sesión cURL
|
|
curl_close($ch);
|
|
return $response;
|
|
}
|
|
}
|
|
|
|
public function patchWhatsapp($response_getContactCallBell, $notificationData, $clabeInterbancaria = null)
|
|
{
|
|
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
|
|
// $IPSERVIDOR = $this->IPServer;
|
|
// $log->appendLog("Valor de la IP del Servidor: " . $IPSERVIDOR . PHP_EOL);
|
|
// $UCRMTOKEN= $this->UCRMAPIToken;
|
|
// $log->appendLog("Valor del Token del UCRM: " . $UCRMTOKEN . PHP_EOL);
|
|
// $CALLBELLTOKEN = $this->CallBellAPIToken;
|
|
// $log->appendLog("Valor del Token de Call Bell: " . $CALLBELLTOKEN . PHP_EOL);
|
|
|
|
//$notification_payment = $notificationData->paymentData; //array con los datos del pago
|
|
|
|
// $notification_payment_export = json_encode($notification_payment);
|
|
// $this->logger->info("Valor de notification payment export: " . $notification_payment_export . PHP_EOL);
|
|
|
|
//$payment_id = $notification_payment['id'];
|
|
|
|
|
|
$log->appendLog("Dentro del proceso del patch: " . PHP_EOL);
|
|
$this->ucrmApi = UcrmApi::create();
|
|
$payments = $this->ucrmApi->get(
|
|
'payments/',
|
|
[
|
|
'clientId' => $notificationData->clientData['id'],
|
|
'limit' => 1,
|
|
'direction' => 'DESC'
|
|
|
|
]
|
|
);
|
|
|
|
//$datos_payment_array = json_decode($payments,true);
|
|
$datos_payment = json_encode($payments);
|
|
|
|
$log->appendLog("Datos traidos con payment api: " . $datos_payment . PHP_EOL);
|
|
//$log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos: " . $notificationData->paymentData[0]['createdDate']. PHP_EOL);
|
|
// $log->appendLog("Esto es lo que trae la fecha mas reciente de los pagos opcion 2: " . $payments[0]['createdDate'] . PHP_EOL);
|
|
|
|
|
|
|
|
|
|
|
|
$uuid = $response_getContactCallBell['contact']['uuid'];
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $this->CallBellAPIToken,
|
|
'Content-Type: application/json',
|
|
]);
|
|
$UrlChatCallBell = 'https://api.callbell.eu/v1/contacts/' . $uuid;
|
|
curl_setopt($ch, CURLOPT_URL, $UrlChatCallBell);
|
|
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
|
|
$log->appendLog("Nombre del cliente que se va a actualizar: " . $nombre_cliente . PHP_EOL);
|
|
$log->appendLog("UUID: " . $uuid . PHP_EOL);
|
|
|
|
$payment_method_id = $payments[0]['methodId'];
|
|
$payment_method = '';
|
|
|
|
switch ($payment_method_id) {
|
|
case '11721cdf-a498-48be-903e-daa67552e4f6':
|
|
$payment_method = 'Cheque 📄';
|
|
break;
|
|
case '6efe0fa8-36b2-4dd1-b049-427bffc7d369':
|
|
$payment_method = 'Efectivo 💵';
|
|
break;
|
|
case '4145b5f5-3bbc-45e3-8fc5-9cda970c62fb':
|
|
$payment_method = 'Transferencia bancaria 📱🏦';
|
|
break;
|
|
case '78e84000-9b5b-44a4-8367-da43df86ce34':
|
|
$payment_method = 'PayPal 🌐💳';
|
|
break;
|
|
case '6da98bb9-6df7-4c41-8608-5cdd7fde7d5d':
|
|
$payment_method = 'Tarjeta de crédito PayPal 💳';
|
|
break;
|
|
case '1dd098fa-5d63-4c8d-88b7-3c27ffbbb6ae':
|
|
$payment_method = 'Tarjeta de crédito Stripe 💳';
|
|
break;
|
|
case 'b9e1e9d1-5c7b-41d2-b6b2-3e568d700290':
|
|
$payment_method = 'Suscripción de Stripe (tarjeta de crédito) 🌐💳';
|
|
break;
|
|
case '939f7701-00b7-4676-9b1e-17afb268c8ba':
|
|
$payment_method = 'Suscripción de PayPal 🌐💳';
|
|
break;
|
|
case '1c963e35-df24-444d-95d2-12592d5107e8':
|
|
$payment_method = 'MercadoPago 🌐💳';
|
|
break;
|
|
case 'd8c1eae9-d41d-479f-aeaf-38497975d7b3':
|
|
$payment_method = 'Personalizado 📝💸';
|
|
break;
|
|
default:
|
|
$payment_method = 'Desconocido, revisar metodos de pago no contemplados';
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
$fecha_actual = new DateTime();
|
|
$fecha_actual->modify('-6 hours');
|
|
$fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i");
|
|
|
|
$fecha_ultimoPago = new DateTime($payments[0]['createdDate']);
|
|
//$fecha_ultimoPago = $fecha_ultimoPago->modify('-6 hours');
|
|
$fecha_ultimoPago_ajustada = $fecha_ultimoPago->format("d/m/Y H:i");
|
|
|
|
//$log->appendLog("las dos fechas ajustadas : " . $fecha_actual_ajustada.' aqui la otra: '.$fecha_ultimoPago_ajustada. PHP_EOL);
|
|
|
|
// $attributes = $notificationData->clientData['attributes']; //Obtener los atributos del cliente
|
|
|
|
// // Variable para almacenar los valores de los atributos que comienzan con "clabe"
|
|
// $clabeInterbancaria = '';
|
|
|
|
// // Iterar sobre los atributoss
|
|
// foreach ($attributes as $attribute) {
|
|
// // Verificar si la "key" comienza con "clabe"
|
|
// if (strpos($attribute['key'], 'clabe') === 0) {
|
|
// // Agregar el valor al array $clabeValues
|
|
// $clabeInterbancaria = $attribute['value'];
|
|
// }
|
|
// }
|
|
|
|
$accountBalance = $notificationData->clientData['accountBalance'];
|
|
$saldoTexto = '';
|
|
|
|
if ($accountBalance < 0) {
|
|
// Si el saldo es negativo, quitar el signo y poner "Pendientes"
|
|
$saldoTexto = '💲' . abs($accountBalance) . ' pendientes';
|
|
} elseif ($accountBalance > 0) {
|
|
// Si el saldo es positivo, poner "a favor"
|
|
$saldoTexto = '💲' . $accountBalance . ' a favor';
|
|
} else {
|
|
// Si el saldo es 0, poner "está al corriente"
|
|
$saldoTexto = '💲' . $accountBalance . ' está al corriente';
|
|
}
|
|
|
|
$resumenClienteJSON = '{' .
|
|
'"Cliente": "' . $notificationData->clientData['id'] . '",' .
|
|
'"Domicilio": "' .
|
|
(($notificationData->clientData['fullAddress'] == null) ? '📍❌ Sin domicilio' : '📍 ' . $notificationData->clientData['fullAddress']) . '",' .
|
|
'"Nombre": "' . sprintf("👤 %s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']) . '",' .
|
|
'"URL": "🌐 https://172.16.5.120/crm/client/' . $notificationData->clientId . '",' .
|
|
'"Saldo Actual": "' . $saldoTexto . '",' .
|
|
'"Monto Ultimo Pago": "💲 ' . $payments[0]['amount'] . '",' .
|
|
'"Estado": "' .
|
|
(($notificationData->clientData['hasSuspendedService']) ? '🔴 Suspendido' : '🟢 Activo') . '",' .
|
|
'"Fecha Ultimo Pago": "📆💰 ' . $fecha_ultimoPago_ajustada . ' con ' . $payment_method . '",' .
|
|
'"Fecha Ultima Actualizacion": "📆🔄️ ' . $fecha_actual_ajustada . '",' .
|
|
'"Clabe Transferencia Banamex": "' . $clabeInterbancaria . '"' .
|
|
'}';
|
|
|
|
|
|
|
|
|
|
|
|
$data_CRM = array(
|
|
//"uuid" => $json_responseAPI->contact->uuid,
|
|
"name" => sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']),
|
|
|
|
"custom_fields" => array(
|
|
"Cliente" => $notificationData->clientData['id'],
|
|
"Domicilio" => ($notificationData->clientData['fullAddress'] == null) ? '📍❌ Sin domicilio' : '📍 ' . $notificationData->clientData['fullAddress'],
|
|
"Nombre" => sprintf("👤 %s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']),
|
|
"URL" => '🌐 https://172.16.5.120/crm/client/' . $notificationData->clientId,
|
|
"Saldo Actual" => $saldoTexto,
|
|
"Monto Ultimo Pago" => '💲 ' . $payments[0]['amount'],
|
|
"Estado" => ($notificationData->clientData['hasSuspendedService']) ? '🔴 Suspendido' : '🟢 Activo ',
|
|
"Resumen" => $resumenClienteJSON,
|
|
"Fecha Ultimo Pago" => '📆💸 ' . $fecha_ultimoPago_ajustada . ' con ' . $payment_method,
|
|
"Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada,
|
|
"Clabe Transferencia Banamex" => $clabeInterbancaria
|
|
)
|
|
);
|
|
$log->appendLog("JSON con los datos a actualizar: " . json_encode($data_CRM) . PHP_EOL);
|
|
if (
|
|
$response_getContactCallBell['custom_fields']['Cliente'] != $data_CRM['custom_fields']['Cliente']
|
|
|| $response_getContactCallBell['custom_fields']['Domicilio'] != $data_CRM['custom_fields']['Domicilio']
|
|
|| $response_getContactCallBell['custom_fields']['Nombre'] != $data_CRM['custom_fields']['Nombre']
|
|
|| $response_getContactCallBell['custom_fields']['URL'] != $data_CRM['custom_fields']['URL']
|
|
|| $response_getContactCallBell['custom_fields']['Saldo'] != $data_CRM['custom_fields']['Saldo']
|
|
|| $response_getContactCallBell['custom_fields']['Estado'] != $data_CRM['custom_fields']['Estado']
|
|
|| $response_getContactCallBell['custom_fields']['Fecha Ultimo Pago'] != $data_CRM['custom_fields']['Fecha Ultimo Pago']
|
|
|| $response_getContactCallBell['custom_fields']['Monto Ultimo Pago'] != $data_CRM['custom_fields']['Monto Ultimo Pago']
|
|
|| $response_getContactCallBell['name'] != $data_CRM['name']
|
|
) {
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data_CRM));
|
|
$response = curl_exec($ch);
|
|
$log->appendLog("Response Patch CallBell: " . $response . PHP_EOL);
|
|
curl_close($ch);
|
|
|
|
// if($fileNameComprobante != null){
|
|
// sleep(3);
|
|
// $this->deleteFileWordPressAndLocal($fileNameComprobante);
|
|
// }
|
|
|
|
|
|
// $json_data_patch = '{
|
|
// "attributes": [
|
|
// {
|
|
// "value": "' . $UrlChatCallBell . '",
|
|
// "customAttributeId": 21
|
|
// }
|
|
// ]
|
|
|
|
// }'; //JSON para hacer patch de los custom fields del cliente en el UISCP CRM, Campo para el Stripe Customer ID y la Clabe interbancaria
|
|
|
|
// $clientguzz = new Client(); //instancia de cliente GuzzleHttp para consumir API UISP CRM
|
|
// try {
|
|
// $responseCRM = $clientguzz->patch($baseUri . 'clients/' . $notificationData->clientData['id'], [
|
|
// 'json' => json_decode($json_data_patch, true),
|
|
// 'headers' => [
|
|
// 'X-Auth-App-Key' => $token, // Cambia el nombre de la cabecera de autorización
|
|
// 'Accept' => 'application/json', // Indica que esperamos una respuesta en formato JSON
|
|
// ],
|
|
// 'verify' => false,
|
|
// ]); //aquí se contruye la petición para hacer patch hacia el cliente en sus custom fields con la API del UISP UCRM
|
|
|
|
|
|
// } catch (GuzzleException $error) {
|
|
// echo "Error al hacer el patch al CRM: " . $error->getMessage() . PHP_EOL;
|
|
// //exit();
|
|
// }
|
|
// $log->appendLog(json_encode($responseCRM) . PHP_EOL); //imprimir respuesta del patch de CRM con la clabe y Customer ID Stripe
|
|
|
|
} else {
|
|
$log->appendLog("No hay cambios que actualizar " . PHP_EOL);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public function patchServiceStatusWhatsApp($response_getContactCallBell, $notificationData)
|
|
{
|
|
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
|
|
|
|
$log->appendLog("Actualizando estado del servicio " . PHP_EOL);
|
|
|
|
|
|
$uuid = $response_getContactCallBell['contact']['uuid'];
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $this->CallBellAPIToken,
|
|
'Content-Type: application/json',
|
|
]);
|
|
$UrlChatCallBell = 'https://api.callbell.eu/v1/contacts/' . $uuid;
|
|
curl_setopt($ch, CURLOPT_URL, $UrlChatCallBell);
|
|
$nombre_cliente = sprintf("%s %s", $notificationData->clientData['firstName'], $notificationData->clientData['lastName']);
|
|
$log->appendLog("Nombre del cliente al que se va a actualizar el estado del servicio: " . $nombre_cliente . PHP_EOL);
|
|
$log->appendLog("UUID: " . $uuid . PHP_EOL);
|
|
|
|
|
|
|
|
|
|
$fecha_actual = new DateTime();
|
|
$fecha_actual->modify('-6 hours');
|
|
$fecha_actual_ajustada = $fecha_actual->format("d/m/Y H:i");
|
|
|
|
|
|
|
|
$data_CRM = array(
|
|
"custom_fields" => array(
|
|
"Estado" => (
|
|
isset($notificationData->serviceData['status'])
|
|
&& $notificationData->serviceData['status'] == 3
|
|
) ? '🟠 Suspendido' : (
|
|
(isset($notificationData->serviceData['status'])
|
|
&& $notificationData->serviceData['status'] == 1)
|
|
? '🟢 Activo' : '🚫 Finalizado'),
|
|
"Fecha Ultima Actualizacion" => '📆🔄️ ' . $fecha_actual_ajustada
|
|
)
|
|
);
|
|
|
|
|
|
|
|
$log->appendLog("JSON con los datos a actualizar: " . json_encode($data_CRM) . PHP_EOL);
|
|
|
|
if ($response_getContactCallBell['custom_fields']['Estado'] != $data_CRM['custom_fields']['Estado']) {
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data_CRM));
|
|
$response = curl_exec($ch);
|
|
$log->appendLog("Response Patch CallBell: " . $response . PHP_EOL);
|
|
curl_close($ch);
|
|
|
|
|
|
} else {
|
|
$log->appendLog("No hay cambios en el estado del servicio que actualizar " . PHP_EOL);
|
|
}
|
|
}
|
|
|
|
|
|
function UploadFileWordpress($fileHandle): string
|
|
{
|
|
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
|
|
// Configuración de conexión FTP
|
|
$ftp_server = "siip.mx";
|
|
$ftp_username = "siip0001";
|
|
$ftp_password = '$spGiT,[wa)n';
|
|
//$fileName = $fileNameComprobantePDF;
|
|
$remote_file = "/public_html/wp/wp-content/uploads/pdf/Comprobante_de_pago.pdf";
|
|
//$file_to_upload = '/home/unms/data/ucrm/ucrm/data/payment_receipts/' . $fileName;
|
|
$url = 'http://siip.mx/wp/wp-content/uploads/pdf/Comprobante_de_pago.pdf';
|
|
|
|
|
|
|
|
// 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_fput($ftp_conn, $remote_file, $fileHandle, FTP_BINARY)) {
|
|
$log->appendLog("El archivo ha sido cargado exitosamente." . PHP_EOL);
|
|
$log->appendLog("La URL es: " . $url . PHP_EOL);
|
|
// Cerrar conexión FTP
|
|
ftp_close($ftp_conn);
|
|
return $url;
|
|
|
|
} else {
|
|
$log->appendLog("Error al cargar el archivo " . PHP_EOL);
|
|
}
|
|
|
|
// Cerrar conexión FTP
|
|
ftp_close($ftp_conn);
|
|
return '';
|
|
} else {
|
|
$log->appendLog("No se pudo conectar o iniciar sesión en el servidor FTP." . PHP_EOL);
|
|
return '';
|
|
}
|
|
|
|
}
|
|
|
|
|
|
function UploadReceiptToWordpressByServerFileName($fileNamePaymentReceiptServer, $newCustomFileName): string
|
|
{
|
|
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
|
|
|
|
|
|
// 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/pdf/" . $newCustomFileName;
|
|
$file_to_upload = __DIR__ . '/../../../../payment_receipts/' . $fileNamePaymentReceiptServer;
|
|
$url = 'https://siip.mx/wp/wp-content/uploads/pdf/' . $newCustomFileName;
|
|
|
|
|
|
|
|
// 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);
|
|
// Cerrar conexión FTP
|
|
ftp_close($ftp_conn);
|
|
return $url;
|
|
|
|
} else {
|
|
$log->appendLog("Error al cargar el archivo " . PHP_EOL);
|
|
}
|
|
|
|
// Cerrar conexión FTP
|
|
ftp_close($ftp_conn);
|
|
return '';
|
|
} else {
|
|
$log->appendLog("No se pudo conectar o iniciar sesión en el servidor FTP." . PHP_EOL);
|
|
return '';
|
|
}
|
|
|
|
}
|
|
|
|
function UploadReceiptToWordpressByImageFileName($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/img/";
|
|
|
|
$log->appendLog("Subiendo comprobante a worpdpress " . PHP_EOL);
|
|
// 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;
|
|
$file_to_upload = __DIR__ . '/../../comprobantes/' . $imageFileName;
|
|
$url = 'https://siip.mx/wp/wp-content/uploads/img/' . $imageFileName;
|
|
|
|
|
|
|
|
// 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);
|
|
// Cerrar conexión FTP
|
|
//ftp_close($ftp_conn);
|
|
//return $url;
|
|
|
|
} else {
|
|
$log->appendLog("Error al cargar el archivo " . PHP_EOL);
|
|
ftp_close($ftp_conn);
|
|
return '';
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
|
|
// Cerrar conexión FTP
|
|
//ftp_close($ftp_conn);
|
|
//return '';
|
|
} else {
|
|
$log->appendLog("No se pudo conectar o iniciar sesión en el servidor FTP." . PHP_EOL);
|
|
return '';
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
* /Elimina los archivos del directorio de comprobantes de pago a excepción de los últimos 30 para evitar errores de envío
|
|
* @return void
|
|
*/
|
|
function deleteFilesExceptLastFifty()
|
|
{
|
|
$log = PluginLogManager::create(); //Initialize Logger
|
|
$directory = __DIR__ . '/../../comprobantes/';
|
|
// Verificar si el directorio existe
|
|
if (!is_dir($directory)) {
|
|
$log->appendLog('El directorio no existe.');
|
|
die("El directorio no existe.");
|
|
|
|
}
|
|
|
|
// Obtener la lista de archivos en el directorio
|
|
$files = glob($directory . '/*');
|
|
|
|
// Ordenar los archivos por fecha de modificación, de más reciente a más antiguo
|
|
usort($files, function ($a, $b) {
|
|
return filemtime($b) - filemtime($a);
|
|
});
|
|
|
|
// Verificar que haya más de 30 archivos
|
|
if (count($files) > 50) {
|
|
// Obtener los archivos que deben ser eliminados (todos menos los 50 más recientes)
|
|
$filesToDelete = array_slice($files, 50);
|
|
|
|
// Eliminar los archivos
|
|
foreach ($filesToDelete as $file) {
|
|
if (is_file($file)) {
|
|
unlink($file);
|
|
$log->appendLog("Archivo eliminado: $file" . PHP_EOL);
|
|
}
|
|
}
|
|
} else {
|
|
$log->appendLog("Hay menos de 50 archivos en el directorio. No se eliminarán archivos." . PHP_EOL);
|
|
}
|
|
}
|
|
|
|
} |