From 0d73a06562e3770db43ef16ad9e47909f193d66a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 24 Jan 2024 18:45:45 -0300 Subject: [PATCH 001/159] feat: add new class to restore quote when payment is cancelled or failed --- Helper/RestoreQuoteWebpay.php | 94 +++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Helper/RestoreQuoteWebpay.php diff --git a/Helper/RestoreQuoteWebpay.php b/Helper/RestoreQuoteWebpay.php new file mode 100644 index 0000000..d05f3f8 --- /dev/null +++ b/Helper/RestoreQuoteWebpay.php @@ -0,0 +1,94 @@ +quoteFactory = $quoteFactory; + $this->quoteRepository = $quoteRepository; + $this->checkoutSession = $checkoutSession; + $this->customerFactory = $customerFactory; + $this->customerRepository = $customerRepository; + } + + public function replaceQuoteAfterRedirection($quote) + { + + $this->quoteRepository->get($this->checkoutSession->getQuoteId())->setIsActive(false)->save(); + + $newQuote = $this->quoteFactory->create(); + $newQuote->merge($quote); + $newQuote->setIsActive(true)->collectTotals(); + $this->quoteRepository->save($newQuote); + $this->checkoutSession->replaceQuote($newQuote); + $this->setGuestData($quote); + } + + protected function restoreShippingInformation($oldQuote, $newQuote) + { + /* + * Restore shipping information for guest customer + */ + $oldAddress = $oldQuote->getShippingAddress(); + $newAddress = $newQuote->getShippingAddress(); + + $newAddress->setEmail($oldAddress->getEmail()); + $newAddress->setFirstname($oldAddress->getFirstname()); + $newAddress->setLastname($oldAddress->getLastname()); + $newAddress->setCompany($oldAddress->getCompany()); + $newAddress->setStreetFull($oldAddress->getStreetFull()); + $newAddress->setCountryId($oldAddress->getCountryId()); + $newAddress->setCity($oldAddress->getCity()); + $newAddress->setRegion($oldAddress->getRegion()); + $newAddress->setRegionId($oldAddress->getRegionId()); + $newAddress->setTelephone($oldAddress->getTelephone()); + $newAddress->setPostcode($oldAddress->getPostcode()); + + $this->quoteRepository->save($newQuote); + } + + public function setGuestData($oldQuote) + { + + $customerId = $oldQuote->getCustomerId(); + $isGuest = $oldQuote->getCustomerIsGuest(); + + if ($customerId && $isGuest == 1) { + $oldQuote->setCustomerIsGuest(false); + $oldQuote->save(); + } + + $newQuote = $this->checkoutSession->getQuote(); + + if ($isGuest == 1) { + $this->restoreShippingInformation($oldQuote, $newQuote); + } else { + $customer = $this->customerRepository->getById($customerId); + $newQuote->assignCustomer($customer)->save(); + } + } +} From 9aaeade037a03d1c70cf012163fae0b571bd6bc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 24 Jan 2024 19:01:10 -0300 Subject: [PATCH 002/159] fix: replace use of restore quote magento function by restore quote webpay method on create transaction flow --- Controller/Transaction/CreateWebpayM22.php | 41 ++++++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/Controller/Transaction/CreateWebpayM22.php b/Controller/Transaction/CreateWebpayM22.php index 99b5696..50fa340 100644 --- a/Controller/Transaction/CreateWebpayM22.php +++ b/Controller/Transaction/CreateWebpayM22.php @@ -7,6 +7,8 @@ use Transbank\Webpay\Model\Webpay; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\InteractsWithFullLog; +use Transbank\Webpay\Helper\RestoreQuoteWebpay; +use Magento\Quote\Model\QuoteRepository; /** * Controller for create transaction Webpay. @@ -22,6 +24,8 @@ class CreateWebpayM22 extends \Magento\Framework\App\Action\Action protected $webpayOrderDataFactory; protected $log; protected $interactsWithFullLog; + protected $quoteFactory; + protected $quoteRepository; /** * CreateWebpayM22 constructor. @@ -34,6 +38,8 @@ class CreateWebpayM22 extends \Magento\Framework\App\Action\Action * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Transbank\Webpay\Model\Config\ConfigProvider $configProvider * @param \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory + * @param \Magento\Quote\Model\QuoteRepository $quoteRepository, + * @param \Transbank\Webpay\Helper\RestoreQuoteWebpay $restoreQuoteWebpay */ public function __construct( \Magento\Framework\App\Action\Context $context, @@ -44,7 +50,9 @@ public function __construct( \Magento\Store\Model\StoreManagerInterface $storeManager, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, - InteractsWithFullLog $InteractsWithFullLog + InteractsWithFullLog $InteractsWithFullLog, + \Magento\Quote\Model\QuoteRepository $quoteRepository, + \Transbank\Webpay\Helper\RestoreQuoteWebpay $restoreQuoteWebpay ) { parent::__construct($context); @@ -57,6 +65,8 @@ public function __construct( $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->log = new LogHandler(); $this->interactsWithFullLog = $InteractsWithFullLog; + $this->quoteRepository = $quoteRepository; + $this->restoreQuoteWebpay = $restoreQuoteWebpay; } /** @@ -80,8 +90,33 @@ public function execute() $config = $this->configProvider->getPluginConfig(); + $lastRealOrder = $this->checkoutSession->getLastRealOrder(); + + if($lastRealOrder->getId() && $lastRealOrder->getState() != \Magento\Sales\Model\Order::STATE_CANCELED ){ + try { + $quote = $this->quoteRepository->get($lastRealOrder->getQuoteId()); + $quote->setIsActive(1)->setReservedOrderId(null); + $this->quoteRepository->save($quote); + $this->checkoutSession->replaceQuote($quote)->unsLastRealOrderId(); + if($lastRealOrder->getCustomerId()){ + $this->restoreQuoteWebpay->setGuestData($quote); + } + } catch (\Exception $e) { + $message = 'Error al recuperar el carrito: '.$e->getMessage(); + $this->log->logError($message); + } + }else{ + try { + $this->quoteRepository->get($lastRealOrder->getQuoteId())->setIsActive(false)->save(); + $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($this->checkoutSession->getQuote()); + }catch (\Exception $e) { + $message = 'Error al recuperar el carrito: '.$e->getMessage(); + $this->log->logError($message); + } + + } + $tmpOrder = $this->getOrder(); - $this->checkoutSession->restoreQuote(); $quote = $this->cart->getQuote(); @@ -128,7 +163,7 @@ public function execute() $orderId, $quoteId ); - + $this->interactsWithFullLog->logWebpayPlusDespuesCrearTx($response); // Logs $order->setStatus($orderStatusPendingPayment); From 13f16def0c6ec8c0a06e8c174b79822866fd3ef5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 24 Jan 2024 19:11:34 -0300 Subject: [PATCH 003/159] fix: replace use of restore quote magento by restore quote webpay method on commit webpay --- Controller/Transaction/CommitWebpayM22.php | 28 ++++++++++------------ 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/Controller/Transaction/CommitWebpayM22.php b/Controller/Transaction/CommitWebpayM22.php index e4b16ab..da9c039 100755 --- a/Controller/Transaction/CommitWebpayM22.php +++ b/Controller/Transaction/CommitWebpayM22.php @@ -7,6 +7,7 @@ use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\InteractsWithFullLog; +use Transbank\Webpay\Helper\RestoreQuoteWebpay; /** * Controller for commit transaction Webpay. @@ -31,6 +32,7 @@ class CommitWebpayM22 extends \Magento\Framework\App\Action\Action protected $webpayOrderDataFactory; protected $log; protected $interactsWithFullLog; + protected $restoreQuoteWebpay; public function __construct( \Magento\Framework\App\Action\Context $context, @@ -41,7 +43,8 @@ public function __construct( \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, - InteractsWithFullLog $InteractsWithFullLog + InteractsWithFullLog $InteractsWithFullLog, + \Transbank\Webpay\Helper\RestoreQuoteWebpay $restoreQuoteWebpay ) { parent::__construct($context); @@ -55,6 +58,7 @@ public function __construct( $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->log = new LogHandler(); $this->interactsWithFullLog = $InteractsWithFullLog; + $this->restoreQuoteWebpay = $restoreQuoteWebpay; } /** @@ -139,7 +143,8 @@ public function execute() $order->addStatusToHistory($order->getStatus(), json_encode($transactionResult)); $order->save(); - $this->checkoutSession->restoreQuote(); + $quote = $this->quoteRepository->get($order->getQuoteId()); + $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($quote); $message = $this->getRejectMessage($transactionResult); $this->messageManager->addError(__($message)); @@ -161,7 +166,8 @@ public function execute() return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); } elseif ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_FAILED) { - $this->checkoutSession->restoreQuote(); + $quote = $this->quoteRepository->get($order->getQuoteId()); + $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($quote); $message = $this->getRejectMessage($transactionResult); $this->messageManager->addError(__($message)); @@ -287,21 +293,11 @@ protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) list($webpayOrderData, $order) = $this->getOrderByToken($token); if ($order->getStatus() == $orderStatusCanceled){ + $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($this->checkoutSession->getQuote()); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } - $this->checkoutSession->restoreQuote(); - $getQuoteById = $this->quoteRepository->get($quoteId); - - if ($getQuoteById) { - $customerId = $getQuoteById->getCustomerId(); - $isGuest = $getQuoteById->getCustomerIsGuest(); - - if ($customerId && $isGuest == 1) { - $getQuoteById->setCustomerIsGuest(false); - $getQuoteById->save(); - } - } + $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($this->checkoutSession->getQuote()); if ($order != null) { $order->cancel(); @@ -382,9 +378,9 @@ private function errorOnConfirmation(\Exception $e, $order, $orderStatusCanceled { $message = 'Error al confirmar transacción: '.$e->getMessage(); $this->log->logError($message); - $this->checkoutSession->restoreQuote(); $this->messageManager->addError(__($message)); if ($order != null && $order->getState() != Order::STATE_PROCESSING) { + $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($this->quoteRepository->get($order->getQuoteId())); $order->cancel(); $order->save(); $order->setStatus($orderStatusCanceled); From 29c8cbdb53ebc17327ef615ddbb51d71aa86b817 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 25 Jan 2024 00:17:45 -0300 Subject: [PATCH 004/159] fix: add quote repository variable on createwebpay class --- Controller/Transaction/CreateWebpayM22.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Controller/Transaction/CreateWebpayM22.php b/Controller/Transaction/CreateWebpayM22.php index 50fa340..b84b9b4 100644 --- a/Controller/Transaction/CreateWebpayM22.php +++ b/Controller/Transaction/CreateWebpayM22.php @@ -26,6 +26,7 @@ class CreateWebpayM22 extends \Magento\Framework\App\Action\Action protected $interactsWithFullLog; protected $quoteFactory; protected $quoteRepository; + protected $restoreQuoteWebpay; /** * CreateWebpayM22 constructor. From ee1cde19e7d1ed40317eff1ada15c38f9ef51753 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 25 Jan 2024 00:31:05 -0300 Subject: [PATCH 005/159] fix: parse commit response to array when transaction is rejected --- Controller/Transaction/CommitWebpayM22.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/CommitWebpayM22.php b/Controller/Transaction/CommitWebpayM22.php index da9c039..9f1115f 100755 --- a/Controller/Transaction/CommitWebpayM22.php +++ b/Controller/Transaction/CommitWebpayM22.php @@ -146,7 +146,7 @@ public function execute() $quote = $this->quoteRepository->get($order->getQuoteId()); $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($quote); - $message = $this->getRejectMessage($transactionResult); + $message = $this->getRejectMessage($this->commitResponseToArray($transactionResult)); $this->messageManager->addError(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); @@ -168,7 +168,7 @@ public function execute() } elseif ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_FAILED) { $quote = $this->quoteRepository->get($order->getQuoteId()); $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($quote); - $message = $this->getRejectMessage($transactionResult); + $message = $this->getRejectMessage($this->commitResponseToArray($transactionResult)); $this->messageManager->addError(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); From f27dd652a416970dce23a67672e7cf484684b828 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 31 Jan 2024 13:10:03 -0300 Subject: [PATCH 006/159] fix: add error message when user is logged in and transaction is rejected or cancelled --- Controller/Transaction/CommitWebpayM22.php | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpayM22.php b/Controller/Transaction/CommitWebpayM22.php index 9f1115f..8afb8a3 100755 --- a/Controller/Transaction/CommitWebpayM22.php +++ b/Controller/Transaction/CommitWebpayM22.php @@ -148,6 +148,9 @@ public function execute() $message = $this->getRejectMessage($this->commitResponseToArray($transactionResult)); $this->messageManager->addError(__($message)); + if($quote->getCustomerId()){ + $this->messageManager->addError(__('Para reintentar el pago debe actualizar el carrito.')); + } return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } @@ -170,6 +173,9 @@ public function execute() $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($quote); $message = $this->getRejectMessage($this->commitResponseToArray($transactionResult)); $this->messageManager->addError(__($message)); + if($quote->getCustomerId()){ + $this->messageManager->addError(__('Para reintentar el pago debe actualizar el carrito.')); + } return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } @@ -289,9 +295,15 @@ protected function getSuccessMessage(array $transactionResult) protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) { $message = 'Orden cancelada por el usuario'; - $this->messageManager->addError(__($message)); + list($webpayOrderData, $order) = $this->getOrderByToken($token); + if($order->getCustomerId()){ + $message = 'Orden cancelada por el usuario. Para reintentar el pago debe actualizar el carrito.' + } + + $this->messageManager->addError(__($message)); + if ($order->getStatus() == $orderStatusCanceled){ $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($this->checkoutSession->getQuote()); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); @@ -377,6 +389,11 @@ private function getOrderByToken($tokenWs) private function errorOnConfirmation(\Exception $e, $order, $orderStatusCanceled) { $message = 'Error al confirmar transacción: '.$e->getMessage(); + + if($order->getCustomerId()){ + $message = "Error al confirmar transacción: {$e->getMessage()}. Para reintentar el pago debe actualizar el carrito."; + } + $this->log->logError($message); $this->messageManager->addError(__($message)); if ($order != null && $order->getState() != Order::STATE_PROCESSING) { From 0cec6c35494db97ca2b10a53c8333025d83d90fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 31 Jan 2024 13:12:58 -0300 Subject: [PATCH 007/159] fix: add semicolon expected in message --- Controller/Transaction/CommitWebpayM22.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpayM22.php b/Controller/Transaction/CommitWebpayM22.php index 8afb8a3..a53747f 100755 --- a/Controller/Transaction/CommitWebpayM22.php +++ b/Controller/Transaction/CommitWebpayM22.php @@ -299,7 +299,7 @@ protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) list($webpayOrderData, $order) = $this->getOrderByToken($token); if($order->getCustomerId()){ - $message = 'Orden cancelada por el usuario. Para reintentar el pago debe actualizar el carrito.' + $message = 'Orden cancelada por el usuario. Para reintentar el pago debe actualizar el carrito.'; } $this->messageManager->addError(__($message)); From 7a62ad00ec60f166da35b70573bdcfd268bdb9db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Tue, 7 May 2024 11:57:16 -0400 Subject: [PATCH 008/159] refactor: add tbkresponse class to handle approved and rejected transaction message --- Helper/TbkResponseHelper.php | 195 +++++++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 Helper/TbkResponseHelper.php diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php new file mode 100644 index 0000000..14e9a19 --- /dev/null +++ b/Helper/TbkResponseHelper.php @@ -0,0 +1,195 @@ + 'Venta Debito', + 'VN' => 'Venta Normal', + 'VC' => 'Venta en cuotas', + 'SI' => '3 cuotas sin interés', + 'S2' => '2 cuotas sin interés', + 'NC' => 'N cuotas sin interés', + 'VP' => 'Venta Prepago' + ]; + + /** + * @param string $utcDate representation of date in UTC format + * + * @return string|null date string in localtime representation, `null` if input cannot be transformed + */ + public static function utcToLocalDate($utcDate): string { + try { + $scopeConfig = ObjectManagerHelper::get(ScopeConfigInterface::class); + $timezone = $scopeConfig->getValue('general/locale/timezone'); + + $utcDate = new DateTime($utcDate, new DateTimeZone('UTC')); + $utcDate->setTimezone(new DateTimeZone($timezone)); + + return $utcDate->format('d-m-Y H:i:s P'); + } + catch (\Exception $e) { + return $e; + } + } + + /** + * Retrieve success message for a transaction + * + * @param object|array $transactionResult + * @param string $product + * @param $paymentTypeCodearray + * @return string success message + */ + public static function getSuccessMessage($transactionResult, string $product) + { + + if (strpos($product, 'click')) { + $transactionResult = self::getOneclickDetails($transactionResult); + } + + if ( in_array($transactionResult->paymentTypeCode, ['SI', 'S2', 'NC', 'VC']) ) { + $tipoCuotas = self::$paymentTypeCodearray[$transactionResult->paymentTypeCode]; + } else { + $tipoCuotas = 'Sin cuotas'; + } + + if ($transactionResult->responseCode == 0) { + $transactionResponse = 'Transacción Aprobada'; + } else { + $transactionResponse = 'Transacción Rechazada'; + } + + if ($transactionResult->paymentTypeCode == 'VD') { + $paymentType = 'Débito'; + } elseif ($transactionResult->paymentTypeCode == 'VP') { + $paymentType = 'Prepago'; + } else { + $paymentType = 'Crédito'; + } + $installmentsString = ''; + if ($tipoCuotas != 'Sin cuotas') { + $installmentsString = " +
+ • Número de cuotas: {$transactionResult->installmentsNumber} +
+
+ • Monto Cuota: {$transactionResult->installmentsNumber} +
+ "; + } + + $message = " + Detalles del pago con {$product} +
+ • Respuesta de la Transacción: {$transactionResponse} +
+
+ • Código de la Transacción: {$transactionResult->responseCode} +
+
+ • Monto: $ {$transactionResult->amount} +
+
+ • Order de Compra: $ {$transactionResult->buyOrder} +
+
+ • Fecha de la Transacción: ".date('d-m-Y', strtotime($transactionResult->transactionDate)).' +
+
+ • Hora de la Transacción: '.date('H:i:s', strtotime($transactionResult->transactionDate))." +
+
+ • Tarjeta: **** **** **** {$transactionResult->cardNumber} +
+
+ • Código de autorizacion: {$transactionResult->authorizationCode} +
+
+ • Tipo de Pago: {$paymentType} +
+
+ • Tipo de Cuotas: {$tipoCuotas} +
+ {$installmentsString} + "; + + return $message; + } + + public static function getRejectMessage($transactionResult, $product) + { + if (strpos($product, 'click')) { + $transactionResult = self::getOneclickDetails($transactionResult); + } + + if (isset($transactionResult)) { + $message = "

Autorización de transacción rechazada con {$product}

+
+ • Respuesta de la Transacción: {$transactionResult->responseCode} +
+
+ • Monto:$ {$transactionResult->amount} +
+
+ • Order de Compra: {$transactionResult->buyOrder} +
+
+ • Fecha de la Transacción: " . date('d-m-Y', strtotime($transactionResult->transactionDate)) ." +
+
+ • Hora de la Transacción: " . date('H:i:s', strtotime($transactionResult->transactionDate)) ." +
+
+ • Tarjeta: **** **** **** {$transactionResult->cardNumber} +
+ "; + return $message; + + } else { + if ($transactionResult->status == 'ERROR') { + $error = $transactionResult->status; + $detail = isset($transactionResult->details[0]) ? $transactionResult->details[0] : 'Sin detalles'; + $message = "

Transacción fallida con {$product}

+
+ • Respuesta de la Transacción: {$error} +
+
+ • Mensaje: {$detail} +
"; + + return $message; + } else { + $message = '

Transacción Fallida

'; + + return $message; + } + } + } + + + public static function getOneclickDetails($transactionResult){ + $details = $transactionResult->details; + foreach ($details as $detail) { + $transactionResult->amount = $detail->amount; + $transactionResult->authorizationCode = $detail->authorizationCode; + $transactionResult->buyOrder = $detail->buyOrder; + $transactionResult->installmentsNumber = $detail->installmentsNumber; + $transactionResult->paymentTypeCode = $detail->paymentTypeCode; + $transactionResult->responseCode = $detail->responseCode; + $transactionResult->status = $detail->status; + } + $transactionResult->authorizationCode; + $transactionResult->cardNumber; + $transactionResult->transactionDate; + $transactionResult->installmentsNumber; + + return $transactionResult; + } + +} From 7567ee59b151c84b2969a0fba3d71ca19d481296 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Tue, 7 May 2024 16:54:00 -0400 Subject: [PATCH 009/159] fix: change installmentsAmount value on success message --- Helper/TbkResponseHelper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 14e9a19..36ac565 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -79,7 +79,7 @@ public static function getSuccessMessage($transactionResult, string $product) • Número de cuotas: {$transactionResult->installmentsNumber}
- • Monto Cuota: {$transactionResult->installmentsNumber} + • Monto Cuota: {$transactionResult->installmentsAmount}
"; } From 544c2103e87dba5a817dbce880d07303336a46a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 10:29:15 -0400 Subject: [PATCH 010/159] refactor: remove reject and success message function on commit webpay --- Controller/Transaction/CommitWebpay.php | 116 ------------------------ 1 file changed, 116 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 79eecc8..b43cf79 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -218,75 +218,6 @@ protected function commitResponseToArray($response) ]; } - protected function getSuccessMessage(array $transactionResult) - { - if ( in_array($transactionResult['paymentTypeCode'], ['SI', 'S2', 'NC', 'VC']) ) { - $tipoCuotas = $this->paymentTypeCodearray[$transactionResult['paymentTypeCode']]; - } else { - $tipoCuotas = 'Sin cuotas'; - } - - if ($transactionResult['responseCode'] == 0) { - $transactionResponse = 'Transacción Aprobada'; - } else { - $transactionResponse = 'Transacción Rechazada'; - } - - if ($transactionResult['paymentTypeCode'] == 'VD') { - $paymentType = 'Débito'; - } elseif ($transactionResult['paymentTypeCode'] == 'VP') { - $paymentType = 'Prepago'; - } else { - $paymentType = 'Crédito'; - } - $installmentsString = ''; - if ($tipoCuotas != 'Sin cuotas') { - $installmentsString = " -
- • Número de cuotas: {$transactionResult['installmentsNumber']} -
-
- • Monto Cuota: {$transactionResult['installmentsAmount']} -
- "; - } - - return " - Detalles del pago con Webpay -
- • Respuesta de la Transacción: {$transactionResponse} -
-
- • Código de la Transacción: {$transactionResult['responseCode']} -
-
- • Monto: $ {$transactionResult['amount']} -
-
- • Order de Compra: $ {$transactionResult['buyOrder']} -
-
- • Fecha de la Transacción: ".date('d-m-Y', strtotime($transactionResult['transactionDate'])).' -
-
- • Hora de la Transacción: '.date('H:i:s', strtotime($transactionResult['transactionDate']))." -
-
- • Tarjeta: **** **** **** {$transactionResult['cardDetail']['card_number']} -
-
- • Código de autorizacion: {$transactionResult['authorizationCode']} -
-
- • Tipo de Pago: {$paymentType} -
-
- • Tipo de Cuotas: {$tipoCuotas} -
- {$installmentsString} - "; - } - protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) { $message = 'Orden cancelada por el usuario'; @@ -321,53 +252,6 @@ protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } - /** - * @param array|TransactionCommitResponse $transactionResult - * @return string - */ - protected function getRejectMessage( $transactionResult ): string - { - if (isset($transactionResult) && $transactionResult instanceof TransactionCommitResponse) { - return "Transacción rechazada por Webpay -
- • Respuesta de la Transacción: {$transactionResult->getResponseCode()} -
-
- • Monto: $ {$transactionResult->getAmount()} -
-
- • Orden de Compra: {$transactionResult->getBuyOrder()} -
-
- • Fecha de la Transacción: " - . date('d-m-Y', strtotime($transactionResult->getTransactionDate())) ." -
-
- • Hora de la Transacción: " - . date('H:i:s', strtotime($transactionResult->getTransactionDate())) ." -
-
- • Tarjeta: **** **** **** {$transactionResult->getCardNumber()} -
"; - - } - - if (isset($transactionResult['error'])) { - $error = $transactionResult['error']; - $detail = isset($transactionResult['detail']) ? $transactionResult['detail'] : 'Sin detalles'; - return "Transacción fallida con Webpay -
- • Respuesta de la Transacción: {$error} -
-
- • Mensaje: {$detail} -
"; - } - - return '

Transacción Fallida

'; - - } - protected function getOrder($orderId) { $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); From 8e359c53f72593b09ce8592c73d14a75d72adc20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 10:30:10 -0400 Subject: [PATCH 011/159] refactor: remove reject and success message function on authorization oneclick --- Controller/Transaction/AuthorizeOneclick.php | 85 -------------------- 1 file changed, 85 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index d71190d..e925bc1 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -292,89 +292,4 @@ protected function saveWebpayData($authorizeResponse, $amount, $payment_status, return $webpayOrderData; } - protected function getSuccessMessage($transactionResult, $oneclickTitle) - { - if ($transactionResult->details[0]->responseCode == 0) { - $transactionResponse = 'Transacción Aprobada'; - } else { - $transactionResponse = 'Transacción Rechazada'; - } - - if ($transactionResult->details[0]->paymentTypeCode == 'VD') { - $paymentType = 'Débito'; - } elseif ($transactionResult->details[0]->paymentTypeCode == 'VP') { - $paymentType = 'Prepago'; - } else { - $paymentType = 'Crédito'; - } - - - $message = " - Detalles del pago {$oneclickTitle} -
- • Respuesta de la Transacción: {$transactionResponse} -
-
- • Código de la Transacción: {$transactionResult->details[0]->responseCode} -
-
- • Monto: $ {$transactionResult->details[0]->amount} -
-
- • Order de Compra: {$transactionResult->details[0]->buyOrder} -
-
- • Fecha de la Transacción: " . date('d-m-Y', strtotime($transactionResult->transactionDate)) . ' -
-
- • Hora de la Transacción: ' . date('H:i:s', strtotime($transactionResult->transactionDate)) . " -
-
- • Tarjeta: **** **** **** {$transactionResult->cardNumber} -
-
- • Código de autorizacion: {$transactionResult->details[0]->authorizationCode} -
-
- • Tipo de Pago: {$paymentType} -
- "; - - return $message; - } - - protected function getRejectMessage($transactionResult, $oneclickTitle) - { - if (isset($transactionResult)) { - $message = "

Autorización de transacción rechazada con {$oneclickTitle}

-

-
- Respuesta de la Transacción: {$this->responseCodeArray[$transactionResult->details[0]->responseCode]}
- Monto: $ {$transactionResult->details[0]->amount}
- Order de Compra: {$transactionResult->details[0]->buyOrder}
- Fecha de la Transacción: " . date('d-m-Y', strtotime($transactionResult->transactionDate)) . '
- Hora de la Transacción: ' . date('H:i:s', strtotime($transactionResult->transactionDate)) . "
- Tarjeta: **** **** **** {$transactionResult->cardNumber}
-

"; - - return $message; - } else { - if ($transactionResult->details[0]->status == 'ERROR') { - $error = $transactionResult->details[0]->status; - $detail = isset($transactionResult->details[0]) ? $transactionResult->details[0] : 'Sin detalles'; - $message = "

Transacción fallida con Oneclick

-

-
- Respuesta de la Transacción: {$error}
- Mensaje: {$detail} -

"; - - return $message; - } else { - $message = '

Transacción Fallida

'; - - return $message; - } - } - } } From bd2f16571cb87fb40a2b3d0b09fd736b6ce0e2e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 10:38:00 -0400 Subject: [PATCH 012/159] refactor: change called function for show reject message on oneclick authorization --- Controller/Transaction/AuthorizeOneclick.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index e925bc1..e3bcbaa 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -9,6 +9,7 @@ use Magento\Framework\App\Action\Context; use Magento\Framework\App\ObjectManager; use Transbank\Webpay\Helper\PluginLogger; +use Transbank\Webpay\Helper\TbkResponseHelper; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Controller\Result\Json; use Transbank\Webpay\Model\Config\ConfigProvider; @@ -187,7 +188,7 @@ public function execute() ); $order->setStatus($orderStatusCanceled); - $message = '

Error en Inscripción con Oneclick


' . json_encode($response); + $message = '

Error en autorización con Oneclick Mall


' . json_encode($response); $order->addStatusToHistory($order->getStatus(), $message); $order->cancel(); @@ -195,11 +196,11 @@ public function execute() $this->checkoutSession->restoreQuote(); - $message = $this->getRejectMessage($response, $oneclickTitle); + $message = TbkResponseHelper::getRejectMessage($response, "Oneclick Mall"); $this->messageManager->addErrorMessage(__($message)); - // return $this->resultRedirectFactory->create()->setPath('checkout/cart'); - return $resultJson->setData(['status' => 'error', 'response' => $response, 'flag' => 1]); + return $this->resultRedirectFactory->create()->setPath('checkout/cart'); + } } catch (\Exception $e) { $message = 'Error al crear transacción: ' . $e->getMessage(); From bb3729fafe03055aa4702cee1a1f4f2207c22ce4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 10:42:50 -0400 Subject: [PATCH 013/159] fix: replace commerce code by response to save correctly transaction on transbank table --- Controller/Transaction/AuthorizeOneclick.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index e3bcbaa..ad0c573 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -180,7 +180,7 @@ public function execute() return $resultJson->setData(['status' => 'success', 'response' => $response, '$webpayOrderData' => $webpayOrderData]); } else { $webpayOrderData = $this->saveWebpayData( - $this->oneclickConfig['CHILD_COMMERCE_CODE'], + $response, $grandTotal, OneclickInscriptionData::PAYMENT_STATUS_FAILED, $orderId, From dc278ac7d37b30d4bf8bab20be94a3c0adeef284 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 10:48:18 -0400 Subject: [PATCH 014/159] refactor: change called function for show success message on oneclick authorization --- Controller/Transaction/AuthorizeOneclick.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index ad0c573..c8e9624 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -170,14 +170,16 @@ public function execute() $this->checkoutSession->getQuote()->setIsActive(false)->save(); - $message = $this->getSuccessMessage($response, $oneclickTitle); + $message = TbkResponseHelper::getSuccessMessage($response, "Oneclick Mall"); + $this->messageManager->addComplexSuccessMessage( 'successMessage', [ 'message' => $message ] ); - return $resultJson->setData(['status' => 'success', 'response' => $response, '$webpayOrderData' => $webpayOrderData]); + + return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); } else { $webpayOrderData = $this->saveWebpayData( $response, From 8981932130ef5202acc0ffb8c85a83e9153b1d0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 10:52:55 -0400 Subject: [PATCH 015/159] fix: replace redirect method when transaction is failed on oneclick --- Controller/Transaction/AuthorizeOneclick.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index c8e9624..b8765a5 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -218,7 +218,7 @@ public function execute() } $this->messageManager->addErrorMessage($e->getMessage()); - return $resultJson->setData(['status' => 'error', 'response' => $response, 'flag' => 2]); + return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } } From 539eeb246c95e62ddc5a323b254fd0d9e240a67a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 10:53:44 -0400 Subject: [PATCH 016/159] refactor: remove unused message variable --- Controller/Transaction/AuthorizeOneclick.php | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index b8765a5..1e96e80 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -30,13 +30,6 @@ class AuthorizeOneclick extends Action { protected $configProvider; - protected $responseCodeArray = [ - '-96' => 'Cancelaste la inscripción durante el formulario de Oneclick.', - '-97' => 'La transacción ha sido rechazada porque se superó el monto máximo diario de pago.', - '-98' => 'La transacción ha sido rechazada porque se superó el monto máximo de pago.', - '-99' => 'La transacción ha sido rechazada porque se superó la cantidad máxima de pagos diarios.', - ]; - private $cart; private $checkoutSession; private $resultJsonFactory; From 228950a2d43b355b4136256a39ae4e5a4806ccfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 10:55:38 -0400 Subject: [PATCH 017/159] refactor: remove unused payment type code variable --- Controller/Transaction/CommitWebpay.php | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index b43cf79..d746f37 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -14,14 +14,6 @@ */ class CommitWebpay extends \Magento\Framework\App\Action\Action { - protected $paymentTypeCodearray = [ - 'VD' => 'Venta Debito', - 'VN' => 'Venta Normal', - 'VC' => 'Venta en cuotas', - 'SI' => '3 cuotas sin interés', - 'S2' => '2 cuotas sin interés', - 'NC' => 'N cuotas sin interés', - ]; protected $configProvider; protected $quoteRepository; From ef894d3692623d046c74922568eae306b4915907 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 10:58:56 -0400 Subject: [PATCH 018/159] refactor: replace success message method on commit webpay --- Controller/Transaction/CommitWebpay.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index d746f37..02c7aec 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -6,6 +6,7 @@ use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\PluginLogger; +use Transbank\Webpay\Helper\TbkResponseHelper; use Transbank\Webpay\Helper\DateHelper; use Transbank\Webpay\WebpayPlus\Responses\TransactionCommitResponse; @@ -15,7 +16,6 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action { protected $configProvider; - protected $quoteRepository; protected $cart; protected $checkoutSession; @@ -115,7 +115,7 @@ public function execute() $this->checkoutSession->getQuote()->setIsActive(false)->save(); - $message = $this->getSuccessMessage($this->commitResponseToArray($transactionResult)); + $message = TbkResponseHelper::getSuccessMessage($transactionResult, "Webpay Plus"); $this->messageManager->addComplexSuccessMessage( 'successMessage', @@ -148,10 +148,10 @@ public function execute() return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } } else { - $transactionResult = json_decode($webpayOrderData->getMetadata(), true); + $transactionResult = json_decode($webpayOrderData->getMetadata()); if ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_SUCCESS) { - $message = $this->getSuccessMessage($transactionResult); + $message = TbkResponseHelper::getSuccessMessage($transactionResult, "Webpay Plus"); $this->messageManager->addComplexSuccessMessage( 'successMessage', From b243a4becb1618265593ead4ffda5203b7967e54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 11:03:59 -0400 Subject: [PATCH 019/159] refactor: replace function called to format date on commit webpay --- Controller/Transaction/CommitWebpay.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 02c7aec..52383a4 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -292,7 +292,7 @@ private function errorOnConfirmation(\Exception $e, $order, $orderStatusCanceled private function createCommitHistoryComment($commitResponse): string { if ( $commitResponse instanceof TransactionCommitResponse ) { - $transactionLocalDate = DateHelper::utcToLocalDate($commitResponse->getTransactionDate()); + $transactionLocalDate = TbkResponseHelper::utcToLocalDate($commitResponse->getTransactionDate()); $commitStatus = $commitResponse->getResponseCode() == 0 ? 'Aprobada' : 'Rechazada'; $installmentsAmount = $commitResponse->getInstallmentsAmount(); $balance = $commitResponse->getBalance(); From 8db5cdb46cb4590b201ef6a8115fc5731ba822ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 11:05:48 -0400 Subject: [PATCH 020/159] refactor: replace function called to format date on refund observer --- Observer/RefundObserver.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Observer/RefundObserver.php b/Observer/RefundObserver.php index 189deec..465193f 100644 --- a/Observer/RefundObserver.php +++ b/Observer/RefundObserver.php @@ -8,7 +8,7 @@ use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderDataFactory; use Transbank\Webpay\Model\Config\ConfigProvider; -use Transbank\Webpay\Helper\DateHelper; +use Transbank\Webpay\Helper\TbkResponseHelper; use Transbank\Webpay\Helper\PluginLogger; class RefundObserver implements ObserverInterface @@ -164,7 +164,7 @@ private function createHistoryComment(string $refundType, object $refundResponse 'Monto: $' . $amount; if ($refundType == 'NULLIFIED'){ - $transactionLocalDate = DateHelper::utcToLocalDate($refundResponse->getAuthorizationDate()); + $transactionLocalDate = TbkResponseHelper::utcToLocalDate($refundResponse->getAuthorizationDate()); $message .= '
Saldo: $' . $refundResponse->getBalance() . '
Fecha: ' . $transactionLocalDate . '
From 4f01232ca4170c66ea0ae38fa84ac46bf09c2ef4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 11:10:25 -0400 Subject: [PATCH 021/159] refactor: remove unused import on commit webpay --- Controller/Transaction/CommitWebpay.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 52383a4..459483f 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -7,7 +7,6 @@ use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\PluginLogger; use Transbank\Webpay\Helper\TbkResponseHelper; -use Transbank\Webpay\Helper\DateHelper; use Transbank\Webpay\WebpayPlus\Responses\TransactionCommitResponse; /** From 3f0b54e8673a7daaf735623f7792813c75831b9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 11:13:26 -0400 Subject: [PATCH 022/159] refactor: remove unused date helper --- Helper/DateHelper.php | 30 ------------------------------ 1 file changed, 30 deletions(-) delete mode 100644 Helper/DateHelper.php diff --git a/Helper/DateHelper.php b/Helper/DateHelper.php deleted file mode 100644 index be63c63..0000000 --- a/Helper/DateHelper.php +++ /dev/null @@ -1,30 +0,0 @@ -getValue('general/locale/timezone'); - - $utcDate = new DateTime($utcDate, new DateTimeZone('UTC')); - $utcDate->setTimezone(new DateTimeZone($timezone)); - - return $utcDate->format('d-m-Y H:i:s P'); - } - catch (\Exception $e) { - return null; - } - } -} From a19b7638c4f6556d15c2e384ecd8bbefdd9a39b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 11:18:15 -0400 Subject: [PATCH 023/159] refactor: change title of reject message on tbkresponse --- Helper/TbkResponseHelper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 36ac565..d4af6b3 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -129,7 +129,7 @@ public static function getRejectMessage($transactionResult, $product) } if (isset($transactionResult)) { - $message = "

Autorización de transacción rechazada con {$product}

+ $message = "

Transacción rechazada con {$product}

• Respuesta de la Transacción: {$transactionResult->responseCode}
From c39fcdb095cd34267000916989aefd41c4034d94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 13:03:48 -0400 Subject: [PATCH 024/159] refactor: change called function for show reject message on commit webpay --- Controller/Transaction/CommitWebpay.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 459483f..296a6ed 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -141,7 +141,7 @@ public function execute() $order->save(); $this->checkoutSession->restoreQuote(); - $message = $this->getRejectMessage($transactionResult); + $message = TbkResponseHelper::getRejectMessage($transactionResult, "Webpay Plus"); $this->messageManager->addError(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); @@ -162,7 +162,7 @@ public function execute() return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); } elseif ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_FAILED) { $this->checkoutSession->restoreQuote(); - $message = $this->getRejectMessage($transactionResult); + $message = TbkResponseHelper::getRejectMessage($transactionResult, "Webpay Plus"); $this->messageManager->addError(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); From 19b381c43807623cf3f9cfe972d16b8641b14c28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 16:17:24 -0400 Subject: [PATCH 025/159] fix: change location ref to cart on oneclickmethod.js --- .../web/js/view/payment/method-renderer/oneclick-method.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js index 79f30a8..29c6acd 100644 --- a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js +++ b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js @@ -92,7 +92,7 @@ function authorizeTransaction(selected_inscription) { inscription: selected_inscription }, function (result) { console.log(result); - window.location.href = 'onepage/success'; + window.location.href = 'cart'; }); } From 82cf80def6114fb37f28194586d5b05fb1e927b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Wed, 8 May 2024 16:18:08 -0400 Subject: [PATCH 026/159] fix: change reject message to oneclick products --- Helper/TbkResponseHelper.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index d4af6b3..b810561 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -126,6 +126,14 @@ public static function getRejectMessage($transactionResult, $product) { if (strpos($product, 'click')) { $transactionResult = self::getOneclickDetails($transactionResult); + $message = 'Transacción rechazada con Oneclick Mall' . + nl2br('• Respuesta de la Transacción: ' . $transactionResult->responseCode . ' ') . + nl2br('• Monto:$ ' . $transactionResult->amount . ' ') . + nl2br('• Order de Compra: ' . $transactionResult->buyOrder . ' ') . + nl2br('• Fecha de la Transacción: ' . date('d-m-Y', strtotime($transactionResult->transactionDate)) . ' ') . + nl2br('• Hora de la Transacción: ' . date('H:i:s', strtotime($transactionResult->transactionDate)) . ' ') . + nl2br('• Tarjeta: **** **** **** ' . $transactionResult->cardNumber . ''); + return $message; } if (isset($transactionResult)) { From e12f47e385d597ccdb51adcb325c009ac783f3c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 9 May 2024 09:01:01 -0400 Subject: [PATCH 027/159] fix: report sonarcloud bugs when return temporary variable message --- Helper/TbkResponseHelper.php | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index b810561..d1cfff8 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -84,7 +84,7 @@ public static function getSuccessMessage($transactionResult, string $product) "; } - $message = " + return " Detalles del pago con {$product}
• Respuesta de la Transacción: {$transactionResponse} @@ -118,26 +118,23 @@ public static function getSuccessMessage($transactionResult, string $product)
{$installmentsString} "; - - return $message; } public static function getRejectMessage($transactionResult, $product) { if (strpos($product, 'click')) { $transactionResult = self::getOneclickDetails($transactionResult); - $message = 'Transacción rechazada con Oneclick Mall' . + return 'Transacción rechazada con Oneclick Mall' . nl2br('• Respuesta de la Transacción: ' . $transactionResult->responseCode . ' ') . nl2br('• Monto:$ ' . $transactionResult->amount . ' ') . nl2br('• Order de Compra: ' . $transactionResult->buyOrder . ' ') . nl2br('• Fecha de la Transacción: ' . date('d-m-Y', strtotime($transactionResult->transactionDate)) . ' ') . nl2br('• Hora de la Transacción: ' . date('H:i:s', strtotime($transactionResult->transactionDate)) . ' ') . nl2br('• Tarjeta: **** **** **** ' . $transactionResult->cardNumber . ''); - return $message; } if (isset($transactionResult)) { - $message = "

Transacción rechazada con {$product}

+ return "

Transacción rechazada con {$product}

• Respuesta de la Transacción: {$transactionResult->responseCode}
@@ -157,25 +154,20 @@ public static function getRejectMessage($transactionResult, $product) • Tarjeta: **** **** **** {$transactionResult->cardNumber} "; - return $message; } else { if ($transactionResult->status == 'ERROR') { $error = $transactionResult->status; $detail = isset($transactionResult->details[0]) ? $transactionResult->details[0] : 'Sin detalles'; - $message = "

Transacción fallida con {$product}

+ return "

Transacción fallida con {$product}

• Respuesta de la Transacción: {$error}
• Mensaje: {$detail}
"; - - return $message; } else { - $message = '

Transacción Fallida

'; - - return $message; + return '

Transacción Fallida

'; } } } From 13859ea111a5b888450e50a78402ff1daf749e1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 9 May 2024 09:12:35 -0400 Subject: [PATCH 028/159] fix: create var for product on commitwebpay --- Controller/Transaction/CommitWebpay.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 296a6ed..b544d47 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -54,6 +54,7 @@ public function execute() $config = $this->configProvider->getPluginConfig(); $orderStatusCanceled = $this->configProvider->getOrderErrorStatus(); $transactionResult = []; + $product = 'Webpay Plus'; try { $tokenWs = $_POST['token_ws'] ?? $_GET['token_ws'] ?? null; @@ -114,7 +115,7 @@ public function execute() $this->checkoutSession->getQuote()->setIsActive(false)->save(); - $message = TbkResponseHelper::getSuccessMessage($transactionResult, "Webpay Plus"); + $message = TbkResponseHelper::getSuccessMessage($transactionResult, $product); $this->messageManager->addComplexSuccessMessage( 'successMessage', @@ -141,7 +142,7 @@ public function execute() $order->save(); $this->checkoutSession->restoreQuote(); - $message = TbkResponseHelper::getRejectMessage($transactionResult, "Webpay Plus"); + $message = TbkResponseHelper::getRejectMessage($transactionResult, $product); $this->messageManager->addError(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); @@ -150,7 +151,7 @@ public function execute() $transactionResult = json_decode($webpayOrderData->getMetadata()); if ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_SUCCESS) { - $message = TbkResponseHelper::getSuccessMessage($transactionResult, "Webpay Plus"); + $message = TbkResponseHelper::getSuccessMessage($transactionResult, $product); $this->messageManager->addComplexSuccessMessage( 'successMessage', @@ -162,7 +163,7 @@ public function execute() return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); } elseif ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_FAILED) { $this->checkoutSession->restoreQuote(); - $message = TbkResponseHelper::getRejectMessage($transactionResult, "Webpay Plus"); + $message = TbkResponseHelper::getRejectMessage($transactionResult, $product); $this->messageManager->addError(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); From 20c286dbb2532b364ebdf5ee7afae1bccbbc257a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 9 May 2024 09:41:28 -0400 Subject: [PATCH 029/159] refactor: replace date by utctolocaldate function on message transaction --- Helper/TbkResponseHelper.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index d1cfff8..c993e87 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -99,10 +99,10 @@ public static function getSuccessMessage($transactionResult, string $product) • Order de Compra: $ {$transactionResult->buyOrder}
- • Fecha de la Transacción: ".date('d-m-Y', strtotime($transactionResult->transactionDate)).' + • Fecha de la Transacción: ".substr(self::utcToLocalDate($transactionResult->transactionDate), 0,10).'
- • Hora de la Transacción: '.date('H:i:s', strtotime($transactionResult->transactionDate))." + • Hora de la Transacción: '.substr(self::utcToLocalDate($transactionResult->transactionDate),11, 8)."
• Tarjeta: **** **** **** {$transactionResult->cardNumber} @@ -128,8 +128,8 @@ public static function getRejectMessage($transactionResult, $product) nl2br('• Respuesta de la Transacción: ' . $transactionResult->responseCode . ' ') . nl2br('• Monto:$ ' . $transactionResult->amount . ' ') . nl2br('• Order de Compra: ' . $transactionResult->buyOrder . ' ') . - nl2br('• Fecha de la Transacción: ' . date('d-m-Y', strtotime($transactionResult->transactionDate)) . ' ') . - nl2br('• Hora de la Transacción: ' . date('H:i:s', strtotime($transactionResult->transactionDate)) . ' ') . + nl2br('• Fecha de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate), 0,10) . ' ') . + nl2br('• Hora de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate),11, 8). ' ') . nl2br('• Tarjeta: **** **** **** ' . $transactionResult->cardNumber . ''); } @@ -145,10 +145,10 @@ public static function getRejectMessage($transactionResult, $product) • Order de Compra: {$transactionResult->buyOrder}
- • Fecha de la Transacción: " . date('d-m-Y', strtotime($transactionResult->transactionDate)) ." + • Fecha de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate), 0,10)."
- • Hora de la Transacción: " . date('H:i:s', strtotime($transactionResult->transactionDate)) ." + • Hora de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate),11, 8)."
• Tarjeta: **** **** **** {$transactionResult->cardNumber} From 1f7c0e2f2771fced626c21189ecd3ec1581ec07e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 9 May 2024 11:30:11 -0400 Subject: [PATCH 030/159] fix: report sonarcloud bug many return in function --- Helper/TbkResponseHelper.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index c993e87..c9c37ce 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -134,7 +134,7 @@ public static function getRejectMessage($transactionResult, $product) } if (isset($transactionResult)) { - return "

Transacción rechazada con {$product}

+ $message = "

Transacción rechazada con {$product}

• Respuesta de la Transacción: {$transactionResult->responseCode}
@@ -159,7 +159,7 @@ public static function getRejectMessage($transactionResult, $product) if ($transactionResult->status == 'ERROR') { $error = $transactionResult->status; $detail = isset($transactionResult->details[0]) ? $transactionResult->details[0] : 'Sin detalles'; - return "

Transacción fallida con {$product}

+ $message = "

Transacción fallida con {$product}

• Respuesta de la Transacción: {$error}
@@ -167,9 +167,11 @@ public static function getRejectMessage($transactionResult, $product) • Mensaje: {$detail}
"; } else { - return '

Transacción Fallida

'; + $message = '

Transacción Fallida

'; } } + + return $message; } From 426f4dce67d540ebc88f41e7135d58905abd0559 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 9 May 2024 15:09:22 -0400 Subject: [PATCH 031/159] fix: return exception on utclocaltodate --- Helper/TbkResponseHelper.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index c9c37ce..dd735df 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -34,7 +34,7 @@ public static function utcToLocalDate($utcDate): string { return $utcDate->format('d-m-Y H:i:s P'); } catch (\Exception $e) { - return $e; + return null; } } @@ -43,7 +43,6 @@ public static function utcToLocalDate($utcDate): string { * * @param object|array $transactionResult * @param string $product - * @param $paymentTypeCodearray * @return string success message */ public static function getSuccessMessage($transactionResult, string $product) From b8e6668a1ebb1d88c322d5113bc6db43590ca102 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 9 May 2024 15:10:43 -0400 Subject: [PATCH 032/159] fix: remove unnecesary prefix $ to buy order --- Helper/TbkResponseHelper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index dd735df..e7f088d 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -95,7 +95,7 @@ public static function getSuccessMessage($transactionResult, string $product) • Monto: $ {$transactionResult->amount}
- • Order de Compra: $ {$transactionResult->buyOrder} + • Order de Compra: {$transactionResult->buyOrder}
• Fecha de la Transacción: ".substr(self::utcToLocalDate($transactionResult->transactionDate), 0,10).' From 8cee8e0fe86921fee9b9eab236b2a5ffb720882b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 9 May 2024 15:21:55 -0400 Subject: [PATCH 033/159] fix: typo in 'Orden de compra' value --- Helper/TbkResponseHelper.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index e7f088d..0da1ada 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -126,7 +126,7 @@ public static function getRejectMessage($transactionResult, $product) return 'Transacción rechazada con Oneclick Mall' . nl2br('• Respuesta de la Transacción: ' . $transactionResult->responseCode . ' ') . nl2br('• Monto:$ ' . $transactionResult->amount . ' ') . - nl2br('• Order de Compra: ' . $transactionResult->buyOrder . ' ') . + nl2br('• Orden de Compra: ' . $transactionResult->buyOrder . ' ') . nl2br('• Fecha de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate), 0,10) . ' ') . nl2br('• Hora de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate),11, 8). ' ') . nl2br('• Tarjeta: **** **** **** ' . $transactionResult->cardNumber . ''); @@ -141,7 +141,7 @@ public static function getRejectMessage($transactionResult, $product) • Monto:$ {$transactionResult->amount}
- • Order de Compra: {$transactionResult->buyOrder} + • Orden de Compra: {$transactionResult->buyOrder}
• Fecha de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate), 0,10)." From d4da3eb1aca5b8e74c7d32f51dac5886d49506ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabel=20Anabal=C3=B3n=20Fuentes?= Date: Thu, 9 May 2024 15:33:43 -0400 Subject: [PATCH 034/159] refactor: remove expression result is not used anywhere --- Helper/TbkResponseHelper.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 0da1ada..bed9baf 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -185,10 +185,6 @@ public static function getOneclickDetails($transactionResult){ $transactionResult->responseCode = $detail->responseCode; $transactionResult->status = $detail->status; } - $transactionResult->authorizationCode; - $transactionResult->cardNumber; - $transactionResult->transactionDate; - $transactionResult->installmentsNumber; return $transactionResult; } From b0e2c1980890043490caef1f0ff0ab370d10fd4e Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 13 May 2024 12:14:21 -0400 Subject: [PATCH 035/159] style: format file --- Helper/TbkResponseHelper.php | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index bed9baf..10de869 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -1,4 +1,5 @@ 'Venta Debito', @@ -23,7 +25,8 @@ class TbkResponseHelper { * * @return string|null date string in localtime representation, `null` if input cannot be transformed */ - public static function utcToLocalDate($utcDate): string { + public static function utcToLocalDate($utcDate): string + { try { $scopeConfig = ObjectManagerHelper::get(ScopeConfigInterface::class); $timezone = $scopeConfig->getValue('general/locale/timezone'); @@ -32,8 +35,7 @@ public static function utcToLocalDate($utcDate): string { $utcDate->setTimezone(new DateTimeZone($timezone)); return $utcDate->format('d-m-Y H:i:s P'); - } - catch (\Exception $e) { + } catch (\Exception $e) { return null; } } @@ -52,7 +54,7 @@ public static function getSuccessMessage($transactionResult, string $product) $transactionResult = self::getOneclickDetails($transactionResult); } - if ( in_array($transactionResult->paymentTypeCode, ['SI', 'S2', 'NC', 'VC']) ) { + if (in_array($transactionResult->paymentTypeCode, ['SI', 'S2', 'NC', 'VC'])) { $tipoCuotas = self::$paymentTypeCodearray[$transactionResult->paymentTypeCode]; } else { $tipoCuotas = 'Sin cuotas'; @@ -98,10 +100,10 @@ public static function getSuccessMessage($transactionResult, string $product) • Order de Compra: {$transactionResult->buyOrder}
- • Fecha de la Transacción: ".substr(self::utcToLocalDate($transactionResult->transactionDate), 0,10).' + • Fecha de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate), 0, 10) . '
- • Hora de la Transacción: '.substr(self::utcToLocalDate($transactionResult->transactionDate),11, 8)." + • Hora de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate), 11, 8) . "
• Tarjeta: **** **** **** {$transactionResult->cardNumber} @@ -127,8 +129,8 @@ public static function getRejectMessage($transactionResult, $product) nl2br('• Respuesta de la Transacción: ' . $transactionResult->responseCode . ' ') . nl2br('• Monto:$ ' . $transactionResult->amount . ' ') . nl2br('• Orden de Compra: ' . $transactionResult->buyOrder . ' ') . - nl2br('• Fecha de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate), 0,10) . ' ') . - nl2br('• Hora de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate),11, 8). ' ') . + nl2br('• Fecha de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate), 0, 10) . ' ') . + nl2br('• Hora de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate), 11, 8) . ' ') . nl2br('• Tarjeta: **** **** **** ' . $transactionResult->cardNumber . ''); } @@ -144,16 +146,15 @@ public static function getRejectMessage($transactionResult, $product) • Orden de Compra: {$transactionResult->buyOrder}
- • Fecha de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate), 0,10)." + • Fecha de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate), 0, 10) . "
- • Hora de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate),11, 8)." + • Hora de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate), 11, 8) . "
• Tarjeta: **** **** **** {$transactionResult->cardNumber}
"; - } else { if ($transactionResult->status == 'ERROR') { $error = $transactionResult->status; @@ -174,7 +175,8 @@ public static function getRejectMessage($transactionResult, $product) } - public static function getOneclickDetails($transactionResult){ + public static function getOneclickDetails($transactionResult) + { $details = $transactionResult->details; foreach ($details as $detail) { $transactionResult->amount = $detail->amount; From 57a019e6713284ee3af7a05d62858f3a145f148d Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 13 May 2024 23:01:41 -0400 Subject: [PATCH 036/159] refactor: change variable paymentTypeCode to constant --- Helper/TbkResponseHelper.php | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 10de869..f40c51d 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -9,15 +9,14 @@ class TbkResponseHelper { - - protected static $paymentTypeCodearray = [ - 'VD' => 'Venta Debito', - 'VN' => 'Venta Normal', - 'VC' => 'Venta en cuotas', - 'SI' => '3 cuotas sin interés', - 'S2' => '2 cuotas sin interés', - 'NC' => 'N cuotas sin interés', - 'VP' => 'Venta Prepago' + const PAYMENT_TYPE_CODE = [ + "VD" => "Venta Débito", + "VN" => "Venta Normal", + "VC" => "Venta en cuotas", + "SI" => "3 cuotas sin interés", + "S2" => "2 cuotas sin interés", + "NC" => "N cuotas sin interés", + "VP" => "Venta Prepago" ]; /** From 90a1fc5154bb95c9e6233523a2c10d7a3e5a50e3 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 13 May 2024 23:03:27 -0400 Subject: [PATCH 037/159] feat: add constants for payment types --- Helper/TbkResponseHelper.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index f40c51d..004ecad 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -9,6 +9,20 @@ class TbkResponseHelper { + const PAYMENT_TYPE_CREDIT = "Crédito"; + const PAYMENT_TYPE_DEBIT = "Débito"; + const PAYMENT_TYPE_PREPAID = "Prepago"; + + const PAYMENT_TYPE = [ + "VD" => self::PAYMENT_TYPE_DEBIT, + "VN" => self::PAYMENT_TYPE_CREDIT, + "VC" => self::PAYMENT_TYPE_CREDIT, + "SI" => self::PAYMENT_TYPE_CREDIT, + "S2" => self::PAYMENT_TYPE_CREDIT, + "NC" => self::PAYMENT_TYPE_CREDIT, + "VP" => self::PAYMENT_TYPE_PREPAID + ]; + const PAYMENT_TYPE_CODE = [ "VD" => "Venta Débito", "VN" => "Venta Normal", From 89fea89cc6f4321b026e4581d7389982caec7c2f Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 13 May 2024 23:03:57 -0400 Subject: [PATCH 038/159] feat: add method getPaymentType --- Helper/TbkResponseHelper.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 004ecad..e5a9353 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -33,6 +33,17 @@ class TbkResponseHelper "VP" => "Venta Prepago" ]; + /** + * Get the payment type from its code. + * + * @param string $paymentType The code of the payment type. + * @return string The corresponding payment type. + */ + public static function getPaymentType(string $paymentType): string + { + return self::PAYMENT_TYPE[$paymentType] ?? $paymentType; + } + /** * @param string $utcDate representation of date in UTC format * From fd4f61ce6b532f79b43b813a25c20c3b0c5db0f1 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 13 May 2024 23:05:05 -0400 Subject: [PATCH 039/159] feat: add method getInstallmentType --- Helper/TbkResponseHelper.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index e5a9353..bc5aed9 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -44,6 +44,18 @@ public static function getPaymentType(string $paymentType): string return self::PAYMENT_TYPE[$paymentType] ?? $paymentType; } + /** + * Get the installment type from the payment type response. + * + * @param string $paymentType The code of the installment type. + * @return string The corresponding installment type. + */ + public static function getInstallmentType(string $paymentType): string + { + return self::PAYMENT_TYPE_CODE[$paymentType] ?? $paymentType; + } + + /** * @param string $utcDate representation of date in UTC format * From cff8c01c05c89ada2b319bba7fc5ea648c6ceb1f Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 13 May 2024 23:05:49 -0400 Subject: [PATCH 040/159] feat: add constants for status descriptions --- Helper/TbkResponseHelper.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index bc5aed9..e112c1d 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -33,6 +33,16 @@ class TbkResponseHelper "VP" => "Venta Prepago" ]; + const STATUS_DESCRIPTION = [ + 'INITIALIZED' => 'Inicializada', + 'AUTHORIZED' => 'Autorizada', + 'REVERSED' => 'Reversada', + 'FAILED' => 'Fallida', + 'NULLIFIED' => 'Anulada', + 'PARTIALLY_NULLIFIED' => 'Parcialmente anulada', + 'CAPTURED' => 'Capturada', + ]; + /** * Get the payment type from its code. * From 294aa57bd4fcec7bb05da3ad09d245a6d4dfec66 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 13 May 2024 23:06:34 -0400 Subject: [PATCH 041/159] feat: add method getStatus --- Helper/TbkResponseHelper.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index e112c1d..6cf70d3 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -65,6 +65,17 @@ public static function getInstallmentType(string $paymentType): string return self::PAYMENT_TYPE_CODE[$paymentType] ?? $paymentType; } + /** + * Get the transaction status description from response status. + * + * @param string $status The code of the transaction status. + * @return string The description of the corresponding transaction status. + */ + public static function getStatus(string $status): string + { + return self::STATUS_DESCRIPTION[$status] ?? $status; + } + /** * @param string $utcDate representation of date in UTC format From 2a5f911bbba4a86686cb5a8466c7efd13ec6a796 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 13 May 2024 23:10:04 -0400 Subject: [PATCH 042/159] feat: add method getAccountingDate --- Helper/TbkResponseHelper.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 6cf70d3..059e5ec 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -97,6 +97,23 @@ public static function utcToLocalDate($utcDate): string } } + /** + * Get the formatted accounting date from response. + * + * @param string $accountingDate The accounting date in 'md' format. + * @return string The accounting date in 'mm-dd' format. + */ + public static function getAccountingDate(string $accountingDate): string + { + $date = DateTime::createFromFormat('md', $accountingDate); + + if (!$date) { + return $accountingDate; + } + + return $date->format('m-d'); + } + /** * Retrieve success message for a transaction * From ec969329dd189b95117096242a784d6f0ddf7541 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 13 May 2024 23:11:17 -0400 Subject: [PATCH 043/159] feat: add method getAmountFormatted --- Helper/TbkResponseHelper.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 059e5ec..8b5cf76 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -114,6 +114,17 @@ public static function getAccountingDate(string $accountingDate): string return $date->format('m-d'); } + /** + * Get the CLP formatted amount from an integer value. + * + * @param int $amount The integer amount to be formatted. + * @return string The formatted amount as a string. + */ + public static function getAmountFormatted(int $amount): string + { + return '$' . number_format($amount, 0, ',', '.'); + } + /** * Retrieve success message for a transaction * From 4b1c1f9deb01b00b496e3518d4400bafc948552e Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 14 May 2024 10:47:57 -0400 Subject: [PATCH 044/159] feat: add methods to format response --- Helper/TbkResponseHelper.php | 81 ++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 8b5cf76..a53b7ad 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -276,4 +276,85 @@ public static function getOneclickDetails($transactionResult) return $transactionResult; } + /** + * Get the common fields formatted for sale receipt. + * + * @param object $transactionResponse The transaction response. + * @return array The formatted common fields. + */ + private static function getCommonFieldsFormatted(object $transactionResponse): array + { + $scopeConfig = ObjectManagerHelper::get(ScopeConfigInterface::class); + $timezone = $scopeConfig->getValue('general/locale/timezone'); + + $utcDate = new DateTime($transactionResponse->transactionDate, new DateTimeZone('UTC')); + $utcDate->setTimezone(new DateTimeZone($timezone)); + + $buyOrder = $transactionResponse->buyOrder; + $cardNumber = "**** **** **** {$transactionResponse->cardNumber}"; + $transactionDate = $utcDate->format('d-m-Y'); + $transactionTime = $utcDate->format('H:i:s'); + + return [ + 'buyOrder' => $buyOrder, + 'cardNumber' => $cardNumber, + 'transactionDate' => $transactionDate, + 'transactionTime' => $transactionTime + ]; + } + + /** + * Get the formatted response for Webpay transactions. + * + * @param object $transactionResponse The response object for Webpay transactions. + * @return array The formatted response fields. + */ + public static function getWebpayFormattedResponse(object $transactionResponse): array + { + $commonFields = self::getCommonFieldsFormatted($transactionResponse); + + $amount = self::getAmountFormatted($transactionResponse->amount); + $paymentType = self::getPaymentType($transactionResponse->paymentTypeCode); + $installmentType = self::getInstallmentType($transactionResponse->paymentTypeCode); + $installmentAmount = self::getAmountFormatted($transactionResponse->installmentsAmount ?? 0); + + $webpayFields = [ + 'amount' => $amount, + 'authorizationCode' => $transactionResponse->authorizationCode, + 'paymentType' => $paymentType, + 'installmentType' => $installmentType, + 'installmentNumber' => $transactionResponse->installmentsNumber, + 'installmentAmount' => $installmentAmount + ]; + + return array_merge($commonFields, $webpayFields); + } + + /** + * Get the formatted response for Oneclick transactions. + * + * @param object $transactionResponse The response object for Oneclick transactions. + * @return array The formatted response fields. + */ + public static function getOneclickFormattedResponse(object $transactionResponse): array + { + $commonFields = self::getCommonFieldsFormatted($transactionResponse); + $detail = $transactionResponse->details[0]; + + $amount = self::getAmountFormatted($detail->amount); + $paymentType = self::getPaymentType($detail->paymentTypeCode); + $installmentType = self::getInstallmentType($detail->paymentTypeCode); + $installmentAmount = self::getAmountFormatted($detail->installmentsAmount ?? 0); + + $oneclickFields = [ + 'amount' => $amount, + 'authorizationCode' => $detail->authorizationCode, + 'paymentType' => $paymentType, + 'installmentType' => $installmentType, + 'installmentNumber' => $detail->installmentsNumber, + 'installmentAmount' => $installmentAmount + ]; + + return array_merge($commonFields, $oneclickFields); + } } From 5745502a9a3948e2fd521bc661bf76cde0d49fc7 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 14 May 2024 10:57:38 -0400 Subject: [PATCH 045/159] refactor: remove unused methods --- Controller/Transaction/CommitWebpay.php | 4 +- Helper/TbkResponseHelper.php | 151 ------------------------ 2 files changed, 2 insertions(+), 153 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index b544d47..1aa2a0e 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -142,7 +142,7 @@ public function execute() $order->save(); $this->checkoutSession->restoreQuote(); - $message = TbkResponseHelper::getRejectMessage($transactionResult, $product); + $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; $this->messageManager->addError(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); @@ -163,7 +163,7 @@ public function execute() return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); } elseif ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_FAILED) { $this->checkoutSession->restoreQuote(); - $message = TbkResponseHelper::getRejectMessage($transactionResult, $product); + $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; $this->messageManager->addError(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index a53b7ad..d92a5ef 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -125,157 +125,6 @@ public static function getAmountFormatted(int $amount): string return '$' . number_format($amount, 0, ',', '.'); } - /** - * Retrieve success message for a transaction - * - * @param object|array $transactionResult - * @param string $product - * @return string success message - */ - public static function getSuccessMessage($transactionResult, string $product) - { - - if (strpos($product, 'click')) { - $transactionResult = self::getOneclickDetails($transactionResult); - } - - if (in_array($transactionResult->paymentTypeCode, ['SI', 'S2', 'NC', 'VC'])) { - $tipoCuotas = self::$paymentTypeCodearray[$transactionResult->paymentTypeCode]; - } else { - $tipoCuotas = 'Sin cuotas'; - } - - if ($transactionResult->responseCode == 0) { - $transactionResponse = 'Transacción Aprobada'; - } else { - $transactionResponse = 'Transacción Rechazada'; - } - - if ($transactionResult->paymentTypeCode == 'VD') { - $paymentType = 'Débito'; - } elseif ($transactionResult->paymentTypeCode == 'VP') { - $paymentType = 'Prepago'; - } else { - $paymentType = 'Crédito'; - } - $installmentsString = ''; - if ($tipoCuotas != 'Sin cuotas') { - $installmentsString = " -
- • Número de cuotas: {$transactionResult->installmentsNumber} -
-
- • Monto Cuota: {$transactionResult->installmentsAmount} -
- "; - } - - return " - Detalles del pago con {$product} -
- • Respuesta de la Transacción: {$transactionResponse} -
-
- • Código de la Transacción: {$transactionResult->responseCode} -
-
- • Monto: $ {$transactionResult->amount} -
-
- • Order de Compra: {$transactionResult->buyOrder} -
-
- • Fecha de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate), 0, 10) . ' -
-
- • Hora de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate), 11, 8) . " -
-
- • Tarjeta: **** **** **** {$transactionResult->cardNumber} -
-
- • Código de autorizacion: {$transactionResult->authorizationCode} -
-
- • Tipo de Pago: {$paymentType} -
-
- • Tipo de Cuotas: {$tipoCuotas} -
- {$installmentsString} - "; - } - - public static function getRejectMessage($transactionResult, $product) - { - if (strpos($product, 'click')) { - $transactionResult = self::getOneclickDetails($transactionResult); - return 'Transacción rechazada con Oneclick Mall' . - nl2br('• Respuesta de la Transacción: ' . $transactionResult->responseCode . ' ') . - nl2br('• Monto:$ ' . $transactionResult->amount . ' ') . - nl2br('• Orden de Compra: ' . $transactionResult->buyOrder . ' ') . - nl2br('• Fecha de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate), 0, 10) . ' ') . - nl2br('• Hora de la Transacción: ' . substr(self::utcToLocalDate($transactionResult->transactionDate), 11, 8) . ' ') . - nl2br('• Tarjeta: **** **** **** ' . $transactionResult->cardNumber . ''); - } - - if (isset($transactionResult)) { - $message = "

Transacción rechazada con {$product}

-
- • Respuesta de la Transacción: {$transactionResult->responseCode} -
-
- • Monto:$ {$transactionResult->amount} -
-
- • Orden de Compra: {$transactionResult->buyOrder} -
-
- • Fecha de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate), 0, 10) . " -
-
- • Hora de la Transacción: " . substr(self::utcToLocalDate($transactionResult->transactionDate), 11, 8) . " -
-
- • Tarjeta: **** **** **** {$transactionResult->cardNumber} -
- "; - } else { - if ($transactionResult->status == 'ERROR') { - $error = $transactionResult->status; - $detail = isset($transactionResult->details[0]) ? $transactionResult->details[0] : 'Sin detalles'; - $message = "

Transacción fallida con {$product}

-
- • Respuesta de la Transacción: {$error} -
-
- • Mensaje: {$detail} -
"; - } else { - $message = '

Transacción Fallida

'; - } - } - - return $message; - } - - - public static function getOneclickDetails($transactionResult) - { - $details = $transactionResult->details; - foreach ($details as $detail) { - $transactionResult->amount = $detail->amount; - $transactionResult->authorizationCode = $detail->authorizationCode; - $transactionResult->buyOrder = $detail->buyOrder; - $transactionResult->installmentsNumber = $detail->installmentsNumber; - $transactionResult->paymentTypeCode = $detail->paymentTypeCode; - $transactionResult->responseCode = $detail->responseCode; - $transactionResult->status = $detail->status; - } - - return $transactionResult; - } - /** * Get the common fields formatted for sale receipt. * From c0a8ce1e17314df04776bf0634fd85500e79ae70 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 14 May 2024 10:59:30 -0400 Subject: [PATCH 046/159] feat: add new voucher layout --- .../layout/checkout_onepage_success.xml | 11 ++++ .../templates/checkout/success_voucher.phtml | 56 +++++++++++++++++++ view/frontend/web/css/transbank.css | 38 +++++++++++++ 3 files changed, 105 insertions(+) create mode 100644 view/frontend/layout/checkout_onepage_success.xml create mode 100644 view/frontend/templates/checkout/success_voucher.phtml create mode 100644 view/frontend/web/css/transbank.css diff --git a/view/frontend/layout/checkout_onepage_success.xml b/view/frontend/layout/checkout_onepage_success.xml new file mode 100644 index 0000000..5798fdb --- /dev/null +++ b/view/frontend/layout/checkout_onepage_success.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/view/frontend/templates/checkout/success_voucher.phtml b/view/frontend/templates/checkout/success_voucher.phtml new file mode 100644 index 0000000..0ce1abc --- /dev/null +++ b/view/frontend/templates/checkout/success_voucher.phtml @@ -0,0 +1,56 @@ +getResponse(); + +if (is_null($responseData)) return; + +?> + +
+
+

Detalles del pago

+
+
+
+

Orden de compra:

+

#

+
+
+

Código de autorización:

+

+
+
+

Fecha transacción:

+

+
+
+

Hora transacción:

+

+
+
+

Número de tarjeta:

+

+
+
+

Tipo de pago:

+

+
+
+

Tipo de cuota:

+

+
+
+

Número de cuotas:

+

+
+ 0) { ?> +
+

Monto de cada cuota:

+

+
+ +
+

Monto compra:

+

+
+
+
diff --git a/view/frontend/web/css/transbank.css b/view/frontend/web/css/transbank.css new file mode 100644 index 0000000..973c231 --- /dev/null +++ b/view/frontend/web/css/transbank.css @@ -0,0 +1,38 @@ +.tbk_voucher { + display: flex; + flex-direction: column; + border: 1px solid #ddd; + border-radius: 18px; + width: 400px; + margin-top: 60px; +} + +.tbk_voucher>.tbk_voucher-header { + border-bottom: 1px solid #ddd; + width: 100%; + text-align: center; +} + +.tbk_voucher>.tbk_voucher-body { + padding: 10px 20px; + gap: 10px; + display: flex; + flex-direction: column; +} + +.tbk_voucher-body>.tbk_voucher-field { + display: flex; + justify-content: space-between; +} + +.tbk_voucher-body>.tbk_voucher-field:last-child { + border-top: 1px dashed #ddd; +} + +.tbk_voucher-body>.tbk_voucher-field>p { + margin: 0px; +} + +.tbk_voucher-body>.tbk_voucher-field>p:first-child { + font-weight: bold; +} From b52b40cfab5cfc4ddafc67b6bd349390db02dde4 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 14 May 2024 11:04:58 -0400 Subject: [PATCH 047/159] feat: add SuccessVoucher block --- Block/Checkout/SuccessVoucher.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Block/Checkout/SuccessVoucher.php diff --git a/Block/Checkout/SuccessVoucher.php b/Block/Checkout/SuccessVoucher.php new file mode 100644 index 0000000..099d3d8 --- /dev/null +++ b/Block/Checkout/SuccessVoucher.php @@ -0,0 +1,20 @@ +response = $response; + } + + public function getResponse(): array + { + return $this->response; + } +} From b58234fff2928a74014a5fb4d334d9a2c43981bc Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 14 May 2024 11:08:18 -0400 Subject: [PATCH 048/159] feat: implement new voucher in webpay --- Controller/Transaction/CommitWebpay.php | 39 +++++++++++++------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 1aa2a0e..66f30d5 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -3,6 +3,7 @@ namespace Transbank\Webpay\Controller\Transaction; use Magento\Sales\Model\Order; +use Transbank\Webpay\Block\Checkout\SuccessVoucher; use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\PluginLogger; @@ -20,7 +21,9 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action protected $checkoutSession; protected $resultJsonFactory; protected $resultRawFactory; + protected $resultPageFactory; protected $webpayOrderDataFactory; + protected $successVoucherBlock; protected $log; public function __construct( @@ -30,8 +33,10 @@ public function __construct( \Magento\Quote\Model\QuoteRepository $quoteRepository, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, + \Magento\Framework\View\Result\PageFactory $resultPageFactory, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, - \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory + \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, + SuccessVoucher $successVoucherBlock ) { parent::__construct($context); @@ -40,9 +45,11 @@ public function __construct( $this->quoteRepository = $quoteRepository; $this->resultJsonFactory = $resultJsonFactory; $this->resultRawFactory = $resultRawFactory; + $this->resultPageFactory = $resultPageFactory; $this->messageManager = $context->getMessageManager(); $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; + $this->successVoucherBlock = $successVoucherBlock; $this->log = new PluginLogger(); } @@ -115,20 +122,18 @@ public function execute() $this->checkoutSession->getQuote()->setIsActive(false)->save(); - $message = TbkResponseHelper::getSuccessMessage($transactionResult, $product); - - $this->messageManager->addComplexSuccessMessage( - 'successMessage', - [ - 'message' => $message - ] - ); + $formattedResponse = TbkResponseHelper::getWebpayFormattedResponse($transactionResult); $this->log->logInfo('TRANSACCION VALIDADA POR MAGENTO Y POR TBK EN ESTADO STATUS_APPROVED => TOKEN: ' .$tokenWs); $this->log->logInfo(json_encode($transactionResult)); - return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); + $resultPage = $this->resultPageFactory->create(); + $resultPage->addHandle('checkout_onepage_success'); + $block = $resultPage->getLayout()->getBlock('transbank_success'); + $block->setResponse($formattedResponse); + return $resultPage; + } else { $this->log->logError('C.5. Respuesta de tbk commit fallido => token: '.$tokenWs); $this->log->logError(json_encode($transactionResult)); @@ -151,16 +156,14 @@ public function execute() $transactionResult = json_decode($webpayOrderData->getMetadata()); if ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_SUCCESS) { - $message = TbkResponseHelper::getSuccessMessage($transactionResult, $product); + $formattedResponse = TbkResponseHelper::getWebpayFormattedResponse($transactionResult); - $this->messageManager->addComplexSuccessMessage( - 'successMessage', - [ - 'message' => $message - ] - ); + $resultPage = $this->resultPageFactory->create(); + $resultPage->addHandle('checkout_onepage_success'); + $block = $resultPage->getLayout()->getBlock('transbank_success'); + $block->setResponse($formattedResponse); - return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); + return $resultPage; } elseif ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_FAILED) { $this->checkoutSession->restoreQuote(); $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; From 4dfbb7aabb4781619f179c080b17c8085346592d Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 14 May 2024 14:47:02 -0400 Subject: [PATCH 049/159] refactor: remove unused import --- Controller/Transaction/CommitWebpay.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 66f30d5..8a5f171 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -3,7 +3,6 @@ namespace Transbank\Webpay\Controller\Transaction; use Magento\Sales\Model\Order; -use Transbank\Webpay\Block\Checkout\SuccessVoucher; use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\PluginLogger; @@ -23,7 +22,6 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action protected $resultRawFactory; protected $resultPageFactory; protected $webpayOrderDataFactory; - protected $successVoucherBlock; protected $log; public function __construct( @@ -35,8 +33,7 @@ public function __construct( \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, \Magento\Framework\View\Result\PageFactory $resultPageFactory, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, - \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, - SuccessVoucher $successVoucherBlock + \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory ) { parent::__construct($context); @@ -49,7 +46,6 @@ public function __construct( $this->messageManager = $context->getMessageManager(); $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; - $this->successVoucherBlock = $successVoucherBlock; $this->log = new PluginLogger(); } From df8e87a1853db1ac64c6f6039ecc16fa722807cb Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:01:40 -0400 Subject: [PATCH 050/159] fix: render only when injected from controller --- Controller/Transaction/CommitWebpay.php | 4 ++-- ...out_onepage_success.xml => transbank_checkout_success.xml} | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) rename view/frontend/layout/{checkout_onepage_success.xml => transbank_checkout_success.xml} (91%) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 8a5f171..4f58e5c 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -125,7 +125,7 @@ public function execute() $this->log->logInfo(json_encode($transactionResult)); $resultPage = $this->resultPageFactory->create(); - $resultPage->addHandle('checkout_onepage_success'); + $resultPage->addHandle('transbank_checkout_success'); $block = $resultPage->getLayout()->getBlock('transbank_success'); $block->setResponse($formattedResponse); return $resultPage; @@ -155,7 +155,7 @@ public function execute() $formattedResponse = TbkResponseHelper::getWebpayFormattedResponse($transactionResult); $resultPage = $this->resultPageFactory->create(); - $resultPage->addHandle('checkout_onepage_success'); + $resultPage->addHandle('transbank_checkout_success'); $block = $resultPage->getLayout()->getBlock('transbank_success'); $block->setResponse($formattedResponse); diff --git a/view/frontend/layout/checkout_onepage_success.xml b/view/frontend/layout/transbank_checkout_success.xml similarity index 91% rename from view/frontend/layout/checkout_onepage_success.xml rename to view/frontend/layout/transbank_checkout_success.xml index 5798fdb..83651e9 100644 --- a/view/frontend/layout/checkout_onepage_success.xml +++ b/view/frontend/layout/transbank_checkout_success.xml @@ -3,7 +3,9 @@ + + From 5659aaf59c2dba0cc49e962837554ae64d62785b Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:12:08 -0400 Subject: [PATCH 051/159] feat: implement new voucher in oneclick --- Controller/Transaction/AuthorizeOneclick.php | 21 +++++++++---------- .../method-renderer/oneclick-method.js | 11 +++++----- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 1e96e80..852eab1 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -20,6 +20,7 @@ use Magento\Sales\Model\Order\Payment\Transaction; use Transbank\Webpay\Model\OneclickInscriptionData; use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\View\Result\PageFactory; use Transbank\Webpay\Model\OneclickInscriptionDataFactory; @@ -36,6 +37,7 @@ class AuthorizeOneclick extends Action private $oneclickInscriptionDataFactory; private $log; private $webpayOrderDataFactory; + private $resultPageFactory; protected $messageManager; private $oneclickConfig; @@ -56,6 +58,7 @@ public function __construct( Cart $cart, Session $checkoutSession, JsonFactory $resultJsonFactory, + PageFactory $resultPageFactory, ConfigProvider $configProvider, OneclickInscriptionDataFactory $oneclickInscriptionDataFactory, WebpayOrderDataFactory $webpayOrderDataFactory, @@ -70,6 +73,7 @@ public function __construct( $this->messageManager = $messageManager; $this->oneclickInscriptionDataFactory = $oneclickInscriptionDataFactory; $this->webpayOrderDataFactory = $webpayOrderDataFactory; + $this->resultPageFactory = $resultPageFactory; $this->log = new PluginLogger(); $this->oneclickConfig = $configProvider->getPluginConfigOneclick(); } @@ -163,16 +167,13 @@ public function execute() $this->checkoutSession->getQuote()->setIsActive(false)->save(); - $message = TbkResponseHelper::getSuccessMessage($response, "Oneclick Mall"); + $formattedResponse = TbkResponseHelper::getOneclickFormattedResponse($response); - $this->messageManager->addComplexSuccessMessage( - 'successMessage', - [ - 'message' => $message - ] - ); - - return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); + $resultPage = $this->resultPageFactory->create(); + $resultPage->addHandle('transbank_checkout_success'); + $block = $resultPage->getLayout()->getBlock('transbank_success'); + $block->setResponse($formattedResponse); + return $resultPage; } else { $webpayOrderData = $this->saveWebpayData( $response, @@ -195,7 +196,6 @@ public function execute() $this->messageManager->addErrorMessage(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); - } } catch (\Exception $e) { $message = 'Error al crear transacción: ' . $e->getMessage(); @@ -287,5 +287,4 @@ protected function saveWebpayData($authorizeResponse, $amount, $payment_status, return $webpayOrderData; } - } diff --git a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js index 29c6acd..df157da 100644 --- a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js +++ b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js @@ -88,12 +88,11 @@ function checkTransaction(result) { function authorizeTransaction(selected_inscription) { let url = window.checkoutConfig.pluginConfigOneclick.authorizeTransactionUrl; - jQuery.post(url, { - inscription: selected_inscription - }, function (result) { - console.log(result); - window.location.href = 'cart'; - }); + let form = jQuery('
' + + '' + + '
'); + jQuery('body').append(form); + form.submit(); } function handleOneclickTransaction(self, selectedInscription) { From d6b1558546e6ac92d59928891157138db5b64ba6 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:12:39 -0400 Subject: [PATCH 052/159] style: format file --- .../method-renderer/oneclick-method.js | 209 +++++++++--------- 1 file changed, 110 insertions(+), 99 deletions(-) diff --git a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js index df157da..db75319 100644 --- a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js +++ b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js @@ -1,104 +1,119 @@ -define( - [ - 'jquery', - 'Magento_Checkout/js/view/payment/default', - 'Magento_Checkout/js/action/place-order', - 'Magento_Checkout/js/action/select-payment-method', - 'Magento_Customer/js/model/customer', - 'Magento_Checkout/js/checkout-data', - 'Magento_Checkout/js/model/payment/additional-validators', - 'mage/url', - 'Magento_Checkout/js/model/quote', - 'Magento_Checkout/js/action/set-payment-information' - ], - function ($, - Component, - placeOrderAction, - selectPaymentMethodAction, - customer, - checkoutData, - additionalValidators, - urlBuilder, - quote, - setPaymentInformationAction) { - 'use strict'; - - return Component.extend({ - defaults: { - template: 'Transbank_Webpay/payment/oneclick' - }, - - getCode: function () { - return 'transbank_oneclick'; - }, - - placeOrder: function (data, event) { - placeOneclickOrderFunction(event, additionalValidators, this); - }, - - getPlaceOrderDeferredObject: function () { - return $.when( - placeOrderAction(this.getData(), this.messageContainer) +define([ + "jquery", + "Magento_Checkout/js/view/payment/default", + "Magento_Checkout/js/action/place-order", + "Magento_Checkout/js/action/select-payment-method", + "Magento_Customer/js/model/customer", + "Magento_Checkout/js/checkout-data", + "Magento_Checkout/js/model/payment/additional-validators", + "mage/url", + "Magento_Checkout/js/model/quote", + "Magento_Checkout/js/action/set-payment-information", +], function ( + $, + Component, + placeOrderAction, + selectPaymentMethodAction, + customer, + checkoutData, + additionalValidators, + urlBuilder, + quote, + setPaymentInformationAction +) { + "use strict"; + + return Component.extend({ + defaults: { + template: "Transbank_Webpay/payment/oneclick", + }, + + getCode: function () { + return "transbank_oneclick"; + }, + + placeOrder: function (data, event) { + placeOneclickOrderFunction(event, additionalValidators, this); + }, + + getPlaceOrderDeferredObject: function () { + return $.when( + placeOrderAction(this.getData(), this.messageContainer) + ); + }, + + getCardList: function () { + const storedInscriptions = + window.checkoutConfig.oneclick_inscriptions; + let inscriptions = []; + + inscriptions = storedInscriptions.map((inscription) => { + let last_digits = inscription.card_number.substr( + inscription.card_number.length - 4 ); - }, - getCardList: function() { - const storedInscriptions = window.checkoutConfig.oneclick_inscriptions; - let inscriptions = []; + return { + key: `${inscription.card_type} terminada en ${last_digits}`, + value: inscription.id, + }; + }); - inscriptions = storedInscriptions.map(inscription => { - let last_digits = inscription.card_number.substr(inscription.card_number.length - 4); + return inscriptions; + }, - return { - key: `${inscription.card_type} terminada en ${last_digits}`, - value: inscription.id - } - }); + getOneclickConfig: function () { + const grandTotal = window.checkoutConfig.totalsData.grand_total; + const oneclickMaxAmount = + window.checkoutConfig.totalsData.oneclick_max_amount; - return inscriptions; - }, - - getOneclickConfig: function() { - const grandTotal = window.checkoutConfig.totalsData.grand_total; - const oneclickMaxAmount = window.checkoutConfig.totalsData.oneclick_max_amount; - - if (oneclickMaxAmount < grandTotal) { - return true; - } else { - return false; - } + if (oneclickMaxAmount < grandTotal) { + return true; + } else { + return false; } - - - }); - } -); + }, + }); +}); function checkTransaction(result) { if (result != undefined && result.token != undefined) { - let form = jQuery('
' + - '
'); - jQuery('body').append(form); + let form = jQuery( + '
' + + "
" + ); + jQuery("body").append(form); form.submit(); } else { - alert('Error al crear transacción'); + alert("Error al crear transacción"); } } function authorizeTransaction(selected_inscription) { - let url = window.checkoutConfig.pluginConfigOneclick.authorizeTransactionUrl; - - let form = jQuery('
' + - '' + - '
'); - jQuery('body').append(form); + let url = + window.checkoutConfig.pluginConfigOneclick.authorizeTransactionUrl; + + let form = jQuery( + '
' + + '' + + "
" + ); + jQuery("body").append(form); form.submit(); } function handleOneclickTransaction(self, selectedInscription) { self.afterPlaceOrder(); if (!selectedInscription) { - let url = window.checkoutConfig.pluginConfigOneclick.createTransactionUrl; + let url = + window.checkoutConfig.pluginConfigOneclick.createTransactionUrl; console.log(url); jQuery.getJSON(url, checkTransaction); } else { @@ -109,7 +124,9 @@ function handleOneclickTransaction(self, selectedInscription) { function placeOneclickOrderFunction(event, additionalValidators, context) { let self = context; - const selected_inscription = jQuery('#'+context.getCode()+'_payment_profile_id').val(); + const selected_inscription = jQuery( + "#" + context.getCode() + "_payment_profile_id" + ).val(); if (event) { event.preventDefault(); @@ -120,23 +137,17 @@ function placeOneclickOrderFunction(event, additionalValidators, context) { } context.isPlaceOrderActionAllowed(false); - context.getPlaceOrderDeferredObject() - .fail( - function () { - self.isPlaceOrderActionAllowed(true); - } - ) - .done( - function () { - handleOneclickTransaction(self, selected_inscription) - } - - ) - .always( - function () { - self.isPlaceOrderActionAllowed(true); - jQuery('body').loader('show'); - } - ); + context + .getPlaceOrderDeferredObject() + .fail(function () { + self.isPlaceOrderActionAllowed(true); + }) + .done(function () { + handleOneclickTransaction(self, selected_inscription); + }) + .always(function () { + self.isPlaceOrderActionAllowed(true); + jQuery("body").loader("show"); + }); return true; } From f896f1f19f36e4e3f6c1c48b86b2295fea643bd3 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:27:48 -0400 Subject: [PATCH 053/159] refactor: improve param name in getPaymentType method --- Helper/TbkResponseHelper.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index d92a5ef..0385ea1 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -46,12 +46,12 @@ class TbkResponseHelper /** * Get the payment type from its code. * - * @param string $paymentType The code of the payment type. + * @param string $paymentTypeCode The code of the payment type. * @return string The corresponding payment type. */ - public static function getPaymentType(string $paymentType): string + public static function getPaymentType(string $paymentTypeCode): string { - return self::PAYMENT_TYPE[$paymentType] ?? $paymentType; + return self::PAYMENT_TYPE[$paymentTypeCode] ?? $paymentTypeCode; } /** From 5ffda3e8b9beb8d44b0729dcfdbd597aec6b47c7 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:32:14 -0400 Subject: [PATCH 054/159] refactor: improve const name for installment types --- Helper/TbkResponseHelper.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 0385ea1..522b2bd 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -23,7 +23,7 @@ class TbkResponseHelper "VP" => self::PAYMENT_TYPE_PREPAID ]; - const PAYMENT_TYPE_CODE = [ + const INSTALLMENT_TYPES = [ "VD" => "Venta Débito", "VN" => "Venta Normal", "VC" => "Venta en cuotas", @@ -57,12 +57,12 @@ public static function getPaymentType(string $paymentTypeCode): string /** * Get the installment type from the payment type response. * - * @param string $paymentType The code of the installment type. + * @param string $paymentTypeCode The code of the installment type. * @return string The corresponding installment type. */ - public static function getInstallmentType(string $paymentType): string + public static function getInstallmentType(string $paymentTypeCode): string { - return self::PAYMENT_TYPE_CODE[$paymentType] ?? $paymentType; + return self::INSTALLMENT_TYPES[$paymentTypeCode] ?? $paymentTypeCode; } /** From f337e4c3fba31e88d228f99681d0157075cf67d6 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:33:41 -0400 Subject: [PATCH 055/159] fix: typos --- Helper/TbkResponseHelper.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Helper/TbkResponseHelper.php b/Helper/TbkResponseHelper.php index 522b2bd..2390c8a 100644 --- a/Helper/TbkResponseHelper.php +++ b/Helper/TbkResponseHelper.php @@ -13,7 +13,7 @@ class TbkResponseHelper const PAYMENT_TYPE_DEBIT = "Débito"; const PAYMENT_TYPE_PREPAID = "Prepago"; - const PAYMENT_TYPE = [ + const PAYMENT_TYPES = [ "VD" => self::PAYMENT_TYPE_DEBIT, "VN" => self::PAYMENT_TYPE_CREDIT, "VC" => self::PAYMENT_TYPE_CREDIT, @@ -33,7 +33,7 @@ class TbkResponseHelper "VP" => "Venta Prepago" ]; - const STATUS_DESCRIPTION = [ + const STATUS_DESCRIPTIONS = [ 'INITIALIZED' => 'Inicializada', 'AUTHORIZED' => 'Autorizada', 'REVERSED' => 'Reversada', @@ -51,7 +51,7 @@ class TbkResponseHelper */ public static function getPaymentType(string $paymentTypeCode): string { - return self::PAYMENT_TYPE[$paymentTypeCode] ?? $paymentTypeCode; + return self::PAYMENT_TYPES[$paymentTypeCode] ?? $paymentTypeCode; } /** @@ -73,7 +73,7 @@ public static function getInstallmentType(string $paymentTypeCode): string */ public static function getStatus(string $status): string { - return self::STATUS_DESCRIPTION[$status] ?? $status; + return self::STATUS_DESCRIPTIONS[$status] ?? $status; } From b8f796b2be7c0fd08ac7797ee14a4712d93e6776 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:37:59 -0400 Subject: [PATCH 056/159] fix: view installment amount field when installmentNumber > 0 --- view/frontend/templates/checkout/success_voucher.phtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/view/frontend/templates/checkout/success_voucher.phtml b/view/frontend/templates/checkout/success_voucher.phtml index 0ce1abc..524af0b 100644 --- a/view/frontend/templates/checkout/success_voucher.phtml +++ b/view/frontend/templates/checkout/success_voucher.phtml @@ -42,7 +42,7 @@ if (is_null($responseData)) return;

Número de cuotas:

- 0) { ?> + 0) { ?>

Monto de cada cuota:

From 6e294c9fe1362cef8e5c0eb829f0ac5aef2f9a6a Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:41:06 -0400 Subject: [PATCH 057/159] refactor: add curly braces --- view/frontend/templates/checkout/success_voucher.phtml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/view/frontend/templates/checkout/success_voucher.phtml b/view/frontend/templates/checkout/success_voucher.phtml index 524af0b..af27d7c 100644 --- a/view/frontend/templates/checkout/success_voucher.phtml +++ b/view/frontend/templates/checkout/success_voucher.phtml @@ -1,7 +1,9 @@ getResponse(); -if (is_null($responseData)) return; +if (is_null($responseData)) { + return; +} ?> From ad8c61f4ccb77c9c9f8669308edb30e38bc47633 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:41:34 -0400 Subject: [PATCH 058/159] refactor: remove unused variable --- Controller/Transaction/CommitWebpay.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 4f58e5c..5bde1a0 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -57,7 +57,6 @@ public function execute() $config = $this->configProvider->getPluginConfig(); $orderStatusCanceled = $this->configProvider->getOrderErrorStatus(); $transactionResult = []; - $product = 'Webpay Plus'; try { $tokenWs = $_POST['token_ws'] ?? $_GET['token_ws'] ?? null; From 6a5c229964de525aa8c01a8d02bebdcfdd9ebd9f Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 13:54:39 -0400 Subject: [PATCH 059/159] refactor: use return directly --- .../web/js/view/payment/method-renderer/oneclick-method.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js index db75319..884b8fb 100644 --- a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js +++ b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js @@ -66,11 +66,7 @@ define([ const oneclickMaxAmount = window.checkoutConfig.totalsData.oneclick_max_amount; - if (oneclickMaxAmount < grandTotal) { - return true; - } else { - return false; - } + return oneclickMaxAmount < grandTotal; }, }); }); From e062a9e95b03997e1d4bec4fb22eb37341432743 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 7 May 2024 12:25:49 -0400 Subject: [PATCH 060/159] style: format file --- Controller/Transaction/CommitWebpay.php | 37 +++++++++++++------------ 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 5bde1a0..cf3a471 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -68,7 +68,7 @@ public function execute() return $this->orderCanceledByUser($_POST['TBK_TOKEN'], $_POST['TBK_ID_SESION'], $orderStatusCanceled); } if (isset($_GET['TBK_TOKEN'])) { - $this->log->logError('C.2. Error tipo Flujo 2: El pago fue anulado por tiempo de espera => tbkIdSesion: '. + $this->log->logError('C.2. Error tipo Flujo 2: El pago fue anulado por tiempo de espera => tbkIdSesion: ' . $_GET['TBK_ID_SESION']); // Logs return $this->orderCanceledByUser($_GET['TBK_TOKEN'], $_GET['TBK_ID_SESION'], $orderStatusCanceled); } @@ -77,26 +77,27 @@ public function execute() throw new \Exception('Token no encontrado'); } $this->log->logInfo('C.1. Iniciando validación luego de redirección desde tbk => method: ' - .$_SERVER['REQUEST_METHOD']); + . $_SERVER['REQUEST_METHOD']); $this->log->logInfo(json_encode($params)); list($webpayOrderData, $order) = $this->getOrderByToken($tokenWs); $paymentStatus = $webpayOrderData->getPaymentStatus(); if ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_WATING) { - $this->log->logInfo('C.3. Transaccion antes del commit => token: '.$tokenWs); + $this->log->logInfo('C.3. Transaccion antes del commit => token: ' . $tokenWs); $this->log->logInfo(json_encode($webpayOrderData)); $transbankSdkWebpay = new TransbankSdkWebpayRest($config); $transactionResult = $transbankSdkWebpay->commitTransaction($tokenWs); // Commit $webpayOrderData->setMetadata(json_encode($transactionResult)); - $this->log->logInfo('C.2. Tx obtenido desde la tabla webpay_transactions => token: '.$tokenWs); + $this->log->logInfo('C.2. Tx obtenido desde la tabla webpay_transactions => token: ' . $tokenWs); $this->log->logInfo(json_encode($webpayOrderData)); - if (isset($transactionResult->buyOrder) && + if ( + isset($transactionResult->buyOrder) && isset($transactionResult->responseCode) && $transactionResult->responseCode == 0 - ) { + ) { $webpayOrderData->setPaymentStatus(WebpayOrderData::PAYMENT_STATUS_SUCCESS); $webpayOrderData->save(); @@ -105,7 +106,8 @@ public function execute() $payment->setLastTransId($authorizationCode); $payment->setTransactionId($authorizationCode); $payment->setAdditionalInformation( - [\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS => (array) $transactionResult]); + [\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS => (array) $transactionResult] + ); $orderStatus = $this->configProvider->getOrderSuccessStatus(); $order->setState($orderStatus)->setStatus($orderStatus); @@ -113,14 +115,14 @@ public function execute() $order->save(); $this->log->logInfo('C.5. Transacción con commit exitoso en Transbank y guardado => token: ' - .$tokenWs); + . $tokenWs); $this->checkoutSession->getQuote()->setIsActive(false)->save(); $formattedResponse = TbkResponseHelper::getWebpayFormattedResponse($transactionResult); $this->log->logInfo('TRANSACCION VALIDADA POR MAGENTO Y POR TBK EN ESTADO STATUS_APPROVED => TOKEN: ' - .$tokenWs); + . $tokenWs); $this->log->logInfo(json_encode($transactionResult)); $resultPage = $this->resultPageFactory->create(); @@ -130,7 +132,7 @@ public function execute() return $resultPage; } else { - $this->log->logError('C.5. Respuesta de tbk commit fallido => token: '.$tokenWs); + $this->log->logError('C.5. Respuesta de tbk commit fallido => token: ' . $tokenWs); $this->log->logError(json_encode($transactionResult)); $webpayOrderData->setPaymentStatus(WebpayOrderData::PAYMENT_STATUS_FAILED); @@ -179,7 +181,7 @@ protected function toRedirect($url, $data) $response = $this->resultRawFactory->create(); $content = "
"; foreach ($data as $name => $value) { - $content .= ""; + $content .= ""; } $content .= '
'; $content .= ""; @@ -214,7 +216,7 @@ protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) $this->messageManager->addError(__($message)); list($webpayOrderData, $order) = $this->getOrderByToken($token); - if ($order->getStatus() == $orderStatusCanceled){ + if ($order->getStatus() == $orderStatusCanceled) { return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } @@ -273,7 +275,7 @@ private function getOrderByToken($tokenWs) */ private function errorOnConfirmation(\Exception $e, $order, $orderStatusCanceled) { - $message = 'Error al confirmar transacción: '.$e->getMessage(); + $message = 'Error al confirmar transacción: ' . $e->getMessage(); $this->log->logError($message); $this->checkoutSession->restoreQuote(); $this->messageManager->addError(__($message)); @@ -288,8 +290,9 @@ private function errorOnConfirmation(\Exception $e, $order, $orderStatusCanceled return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } - private function createCommitHistoryComment($commitResponse): string { - if ( $commitResponse instanceof TransactionCommitResponse ) { + private function createCommitHistoryComment($commitResponse): string + { + if ($commitResponse instanceof TransactionCommitResponse) { $transactionLocalDate = TbkResponseHelper::utcToLocalDate($commitResponse->getTransactionDate()); $commitStatus = $commitResponse->getResponseCode() == 0 ? 'Aprobada' : 'Rechazada'; $installmentsAmount = $commitResponse->getInstallmentsAmount(); @@ -320,8 +323,8 @@ private function createCommitHistoryComment($commitResponse): string { if (isset($commitResponse['error'])) { $detail = isset($commitResponse['detail']) ? $commitResponse['detail'] : 'Sin detalles'; $message .= '

' . - 'Respuesta: ' . $commitResponse['error'] . '
' . - 'Mensaje: ' . $detail . '
'; + 'Respuesta: ' . $commitResponse['error'] . '
' . + 'Mensaje: ' . $detail . '
'; } return $message; } From cf3bae38df80a628de41bb822739872025cd6475 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 7 May 2024 12:38:53 -0400 Subject: [PATCH 061/159] refactor: improve the use of request variables --- Controller/Transaction/CommitWebpay.php | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index cf3a471..39ebe6e 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -59,18 +59,13 @@ public function execute() $transactionResult = []; try { - $tokenWs = $_POST['token_ws'] ?? $_GET['token_ws'] ?? null; - $params = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET; - if (isset($_POST['TBK_TOKEN'])) { + $tokenWs = $params['token_ws'] ?? null; + + if (isset($params['TBK_TOKEN'])) { $this->log->logError('C.2. Error tipo Flujo 2: El pago fue anulado por tiempo de espera => tbkIdSesion: ' - . $_POST['TBK_ID_SESION']); - return $this->orderCanceledByUser($_POST['TBK_TOKEN'], $_POST['TBK_ID_SESION'], $orderStatusCanceled); - } - if (isset($_GET['TBK_TOKEN'])) { - $this->log->logError('C.2. Error tipo Flujo 2: El pago fue anulado por tiempo de espera => tbkIdSesion: ' . - $_GET['TBK_ID_SESION']); // Logs - return $this->orderCanceledByUser($_GET['TBK_TOKEN'], $_GET['TBK_ID_SESION'], $orderStatusCanceled); + . $params['TBK_ID_SESION']); + return $this->orderCanceledByUser($params['TBK_TOKEN'], $params['TBK_ID_SESION'], $orderStatusCanceled); } if (is_null($tokenWs)) { From a19408fd6804bb3fb9fd86a2c574a4cd5f1e21ae Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 7 May 2024 12:45:52 -0400 Subject: [PATCH 062/159] refactor: add variables for request params --- Controller/Transaction/CommitWebpay.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 39ebe6e..e987262 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -61,11 +61,13 @@ public function execute() try { $params = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET; $tokenWs = $params['token_ws'] ?? null; + $tbkToken = $params['TBK_TOKEN'] ?? null; + $tbkIdSession = $params['TBK_ID_SESION'] ?? null; - if (isset($params['TBK_TOKEN'])) { + if (isset($tbkToken)) { $this->log->logError('C.2. Error tipo Flujo 2: El pago fue anulado por tiempo de espera => tbkIdSesion: ' - . $params['TBK_ID_SESION']); - return $this->orderCanceledByUser($params['TBK_TOKEN'], $params['TBK_ID_SESION'], $orderStatusCanceled); + . $tbkIdSession); + return $this->orderCanceledByUser($tbkToken, $tbkIdSession, $orderStatusCanceled); } if (is_null($tokenWs)) { From 6941e648b07b7bd0944a8caa7d9bb191b8a56e3b Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 7 May 2024 15:58:21 -0400 Subject: [PATCH 063/159] refactor: add method redirectWithErrorMEssage --- Controller/Transaction/CommitWebpay.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index e987262..e42a1f6 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -144,7 +144,7 @@ public function execute() $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; $this->messageManager->addError(__($message)); - return $this->resultRedirectFactory->create()->setPath('checkout/cart'); + return $this->redirectWithErrorMessage($message); } } else { $transactionResult = json_decode($webpayOrderData->getMetadata()); @@ -163,7 +163,7 @@ public function execute() $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; $this->messageManager->addError(__($message)); - return $this->resultRedirectFactory->create()->setPath('checkout/cart'); + return $this->redirectWithErrorMessage($message); } } } catch (\Exception $e) { @@ -187,6 +187,13 @@ protected function toRedirect($url, $data) return $response; } + private function redirectWithErrorMessage(string $message) + { + $this->checkoutSession->restoreQuote(); + $this->messageManager->addErrorMessage(__($message)); + return $this->resultRedirectFactory->create()->setPath('checkout/cart'); + } + protected function commitResponseToArray($response) { return [ From 95cdc11884e05850c3af920e38e58f2c1034fd42 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 7 May 2024 16:00:42 -0400 Subject: [PATCH 064/159] refactor: add method redirectToSuccess --- Controller/Transaction/CommitWebpay.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index e42a1f6..d3cf105 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -187,6 +187,16 @@ protected function toRedirect($url, $data) return $response; } + private function redirectToSuccess(string $message) + { + $this->checkoutSession->getQuote()->setIsActive(false)->save(); + $this->messageManager->addComplexSuccessMessage( + 'successMessage', + ['message' => $message] + ); + return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); + } + private function redirectWithErrorMessage(string $message) { $this->checkoutSession->restoreQuote(); From 5c7e8b6edfd4586392ab63532230dcb71952c534 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 7 May 2024 16:42:03 -0400 Subject: [PATCH 065/159] refactor: split the logic of obtaining WebpayOrderData from the order --- Controller/Transaction/CommitWebpay.php | 26 +++++++++++-------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index d3cf105..34716c5 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -77,7 +77,10 @@ public function execute() . $_SERVER['REQUEST_METHOD']); $this->log->logInfo(json_encode($params)); - list($webpayOrderData, $order) = $this->getOrderByToken($tokenWs); + $webpayOrderData = $this->getWebpayOrderData($tokenWs); + $orderId = $webpayOrderData->getOrderId(); + $order = $this->getOrder($orderId); + $paymentStatus = $webpayOrderData->getPaymentStatus(); if ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_WATING) { $this->log->logInfo('C.3. Transaccion antes del commit => token: ' . $tokenWs); @@ -227,14 +230,11 @@ protected function commitResponseToArray($response) protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) { $message = 'Orden cancelada por el usuario'; - $this->messageManager->addError(__($message)); - list($webpayOrderData, $order) = $this->getOrderByToken($token); - if ($order->getStatus() == $orderStatusCanceled) { - return $this->resultRedirectFactory->create()->setPath('checkout/cart'); - } + $webpayOrderData = $this->getWebpayOrderData($token); + $orderId = $webpayOrderData->getOrderId(); + $order = $this->getOrder($orderId); - $this->checkoutSession->restoreQuote(); $getQuoteById = $this->quoteRepository->get($quoteId); if ($getQuoteById) { @@ -255,7 +255,7 @@ protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) $order->save(); } - return $this->resultRedirectFactory->create()->setPath('checkout/cart'); + return $this->redirectWithErrorMessage($message); } protected function getOrder($orderId) @@ -268,16 +268,12 @@ protected function getOrder($orderId) /** * @param $tokenWs * - * @return array + * @return WebpayOrderData */ - private function getOrderByToken($tokenWs) + private function getWebpayOrderData($tokenWs): WebpayOrderData { $webpayOrderDataModel = $this->webpayOrderDataFactory->create(); - $webpayOrderData = $webpayOrderDataModel->load($tokenWs, 'token'); - $orderId = $webpayOrderData->getOrderId(); - $order = $this->getOrder($orderId); - - return [$webpayOrderData, $order]; + return $webpayOrderDataModel->load($tokenWs, 'token'); } /** From a15c1775d374a291790c42e3a2deea0d84a621a9 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 7 May 2024 17:10:15 -0400 Subject: [PATCH 066/159] refactor: use ObjectManagerHelper instead ObjectManager class --- Controller/Transaction/CommitWebpay.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 34716c5..7ee9767 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -3,6 +3,7 @@ namespace Transbank\Webpay\Controller\Transaction; use Magento\Sales\Model\Order; +use Transbank\Webpay\Helper\ObjectManagerHelper; use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\PluginLogger; @@ -260,9 +261,8 @@ protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) protected function getOrder($orderId) { - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - - return $objectManager->create('\Magento\Sales\Model\Order')->loadByIncrementId($orderId); + $order = ObjectManagerHelper::get(Order::class); + return $order->loadByIncrementId($orderId); } /** From 318396f26a2d47082bd1ed118893cac8e6d2b410 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 7 May 2024 17:11:33 -0400 Subject: [PATCH 067/159] refactor: add method cancelOrder --- Controller/Transaction/CommitWebpay.php | 28 ++++++++++++------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 7ee9767..5c75ffd 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -137,12 +137,9 @@ public function execute() $this->log->logError(json_encode($transactionResult)); $webpayOrderData->setPaymentStatus(WebpayOrderData::PAYMENT_STATUS_FAILED); - $order->cancel(); - $order->save(); - $order->setStatus($orderStatusCanceled); $commitHistoryComment = $this->createCommitHistoryComment($transactionResult); - $order->addStatusToHistory($order->getStatus(), $commitHistoryComment); - $order->save(); + + $this->cancelOrder($order, $commitHistoryComment); $this->checkoutSession->restoreQuote(); $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; @@ -208,6 +205,15 @@ private function redirectWithErrorMessage(string $message) return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } + private function cancelOrder(Order $order, string $message) + { + $orderStatusCanceled = $this->configProvider->getOrderErrorStatus(); + $order->cancel(); + $order->setStatus($orderStatusCanceled); + $order->addStatusToHistory($order->getStatus(), $message); + $order->save(); + } + protected function commitResponseToArray($response) { return [ @@ -249,11 +255,7 @@ protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) } if ($order != null) { - $order->cancel(); - $order->save(); - $order->setStatus($orderStatusCanceled); - $order->addStatusToHistory($order->getStatus(), $message); - $order->save(); + $this->cancelOrder($order, $message); } return $this->redirectWithErrorMessage($message); @@ -290,11 +292,7 @@ private function errorOnConfirmation(\Exception $e, $order, $orderStatusCanceled $this->checkoutSession->restoreQuote(); $this->messageManager->addError(__($message)); if ($order != null && $order->getState() != Order::STATE_PROCESSING) { - $order->cancel(); - $order->save(); - $order->setStatus($orderStatusCanceled); - $order->addStatusToHistory($order->getStatus(), $message); - $order->save(); + $this->cancelOrder($order, $message); } return $this->resultRedirectFactory->create()->setPath('checkout/cart'); From 847aa5c5732b95829f6e8274e98fa0839a5ada5f Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 7 May 2024 17:12:00 -0400 Subject: [PATCH 068/159] refactor: add return type to getOrder method --- Controller/Transaction/CommitWebpay.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 5c75ffd..354bf36 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -261,7 +261,7 @@ protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) return $this->redirectWithErrorMessage($message); } - protected function getOrder($orderId) + protected function getOrder($orderId): Order { $order = ObjectManagerHelper::get(Order::class); return $order->loadByIncrementId($orderId); From 86f53e57f0b6b88c7fddf808c86a83357f57caf3 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 9 May 2024 10:15:37 -0400 Subject: [PATCH 069/159] refactor: implement new flow for transaction processing --- Controller/Transaction/CommitWebpay.php | 312 ++++++++++++++---------- 1 file changed, 179 insertions(+), 133 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 354bf36..be76a3b 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -3,6 +3,7 @@ namespace Transbank\Webpay\Controller\Transaction; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Payment\Transaction; use Transbank\Webpay\Helper\ObjectManagerHelper; use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderData; @@ -15,6 +16,19 @@ */ class CommitWebpay extends \Magento\Framework\App\Action\Action { + const WEBPAY_NORMAL_FLOW = 'normal'; + const WEBPAY_FLOW_TIMEOUT = 'timeout'; + const WEBPAY_FLOW_ABORTED = 'aborted'; + const WEBPAY_FLOW_ERROR = 'error'; + + protected $paymentTypeCodearray = [ + 'VD' => 'Venta Debito', + 'VN' => 'Venta Normal', + 'VC' => 'Venta en cuotas', + 'SI' => '3 cuotas sin interés', + 'S2' => '2 cuotas sin interés', + 'NC' => 'N cuotas sin interés', + ]; protected $configProvider; protected $quoteRepository; protected $cart; @@ -55,122 +69,12 @@ public function __construct( */ public function execute() { - $config = $this->configProvider->getPluginConfig(); - $orderStatusCanceled = $this->configProvider->getOrderErrorStatus(); - $transactionResult = []; - try { - $params = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET; - $tokenWs = $params['token_ws'] ?? null; - $tbkToken = $params['TBK_TOKEN'] ?? null; - $tbkIdSession = $params['TBK_ID_SESION'] ?? null; - - if (isset($tbkToken)) { - $this->log->logError('C.2. Error tipo Flujo 2: El pago fue anulado por tiempo de espera => tbkIdSesion: ' - . $tbkIdSession); - return $this->orderCanceledByUser($tbkToken, $tbkIdSession, $orderStatusCanceled); - } + $request = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET; - if (is_null($tokenWs)) { - throw new \Exception('Token no encontrado'); - } - $this->log->logInfo('C.1. Iniciando validación luego de redirección desde tbk => method: ' - . $_SERVER['REQUEST_METHOD']); - $this->log->logInfo(json_encode($params)); - - $webpayOrderData = $this->getWebpayOrderData($tokenWs); - $orderId = $webpayOrderData->getOrderId(); - $order = $this->getOrder($orderId); - - $paymentStatus = $webpayOrderData->getPaymentStatus(); - if ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_WATING) { - $this->log->logInfo('C.3. Transaccion antes del commit => token: ' . $tokenWs); - $this->log->logInfo(json_encode($webpayOrderData)); - - $transbankSdkWebpay = new TransbankSdkWebpayRest($config); - $transactionResult = $transbankSdkWebpay->commitTransaction($tokenWs); // Commit - $webpayOrderData->setMetadata(json_encode($transactionResult)); - - $this->log->logInfo('C.2. Tx obtenido desde la tabla webpay_transactions => token: ' . $tokenWs); - $this->log->logInfo(json_encode($webpayOrderData)); - - if ( - isset($transactionResult->buyOrder) && - isset($transactionResult->responseCode) && - $transactionResult->responseCode == 0 - ) { - $webpayOrderData->setPaymentStatus(WebpayOrderData::PAYMENT_STATUS_SUCCESS); - $webpayOrderData->save(); - - $authorizationCode = $transactionResult->authorizationCode; - $payment = $order->getPayment(); - $payment->setLastTransId($authorizationCode); - $payment->setTransactionId($authorizationCode); - $payment->setAdditionalInformation( - [\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS => (array) $transactionResult] - ); - - $orderStatus = $this->configProvider->getOrderSuccessStatus(); - $order->setState($orderStatus)->setStatus($orderStatus); - $order->addStatusToHistory($order->getStatus(), json_encode($transactionResult)); - $order->save(); - - $this->log->logInfo('C.5. Transacción con commit exitoso en Transbank y guardado => token: ' - . $tokenWs); - - $this->checkoutSession->getQuote()->setIsActive(false)->save(); - - $formattedResponse = TbkResponseHelper::getWebpayFormattedResponse($transactionResult); - - $this->log->logInfo('TRANSACCION VALIDADA POR MAGENTO Y POR TBK EN ESTADO STATUS_APPROVED => TOKEN: ' - . $tokenWs); - $this->log->logInfo(json_encode($transactionResult)); - - $resultPage = $this->resultPageFactory->create(); - $resultPage->addHandle('transbank_checkout_success'); - $block = $resultPage->getLayout()->getBlock('transbank_success'); - $block->setResponse($formattedResponse); - return $resultPage; - - } else { - $this->log->logError('C.5. Respuesta de tbk commit fallido => token: ' . $tokenWs); - $this->log->logError(json_encode($transactionResult)); - - $webpayOrderData->setPaymentStatus(WebpayOrderData::PAYMENT_STATUS_FAILED); - $commitHistoryComment = $this->createCommitHistoryComment($transactionResult); - - $this->cancelOrder($order, $commitHistoryComment); - - $this->checkoutSession->restoreQuote(); - $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; - $this->messageManager->addError(__($message)); - - return $this->redirectWithErrorMessage($message); - } - } else { - $transactionResult = json_decode($webpayOrderData->getMetadata()); - - if ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_SUCCESS) { - $formattedResponse = TbkResponseHelper::getWebpayFormattedResponse($transactionResult); - - $resultPage = $this->resultPageFactory->create(); - $resultPage->addHandle('transbank_checkout_success'); - $block = $resultPage->getLayout()->getBlock('transbank_success'); - $block->setResponse($formattedResponse); - - return $resultPage; - } elseif ($paymentStatus == WebpayOrderData::PAYMENT_STATUS_FAILED) { - $this->checkoutSession->restoreQuote(); - $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; - $this->messageManager->addError(__($message)); - - return $this->redirectWithErrorMessage($message); - } - } + return $this->handleRequest($request); } catch (\Exception $e) { - $order = isset($order) ? $order : null; - - return $this->errorOnConfirmation($e, $order, $orderStatusCanceled); + return $this->handleException($e->getMessage()); } } @@ -188,6 +92,168 @@ protected function toRedirect($url, $data) return $response; } + private function handleRequest(array $request) + { + $webpayFlow = $this->getWebpayFlow($request); + + if ($webpayFlow == self::WEBPAY_NORMAL_FLOW) { + return $this->handleNormalFlow($request['token_ws']); + } + + if ($webpayFlow == self::WEBPAY_FLOW_TIMEOUT) { + return $this->handleFlowTimeout($request['TBK_ORDEN_COMPRA']); + } + + if ($webpayFlow == self::WEBPAY_FLOW_ABORTED) { + return $this->handleFlowAborted($request['TBK_TOKEN']); + } + + if ($webpayFlow == self::WEBPAY_FLOW_ERROR) { + return $this->handleFlowError($request['token_ws']); + } + } + + private function getWebpayFlow(array $request): string + { + $tokenWs = $request['token_ws'] ?? null; + $tbkToken = $request['TBK_TOKEN'] ?? null; + $tbkIdSession = $request['TBK_ID_SESION'] ?? null; + + if (isset($tokenWs) && isset($tbkToken)) { + return self::WEBPAY_FLOW_ERROR; + } + + if (isset($tbkIdSession) && isset($tbkToken) && !isset($tokenWs)) { + return self::WEBPAY_FLOW_ABORTED; + } + + if (isset($tbkIdSession) && !isset($tbkToken) && !isset($tokenWs)) { + return self::WEBPAY_FLOW_TIMEOUT; + } + + if (isset($tokenWs) && !isset($tbkToken) && !isset($tbkIdSession)) { + return self::WEBPAY_NORMAL_FLOW; + } + } + + private function handleNormalFlow(string $token) + { + $config = $this->configProvider->getPluginConfig(); + $webpayOrderData = $this->getWebpayOrderData($token); + $orderId = $webpayOrderData->getOrderId(); + $order = $this->getOrder($orderId); + + $transbankSdkWebpay = new TransbankSdkWebpayRest($config); + $commitResponse = $transbankSdkWebpay->commitTransaction($token); + + $webpayOrderData->setMetadata(json_encode($commitResponse)); + + if ($commitResponse->isApproved()) { + return $this->handleAuthorizedTransaction($order, $webpayOrderData, $commitResponse); + } + + return $this->handleUnauthorizedTransaction($order, $webpayOrderData, $commitResponse); + } + + private function handleFlowTimeout(string $buyOrder) + { + $message = 'Orden cancelada por inactividad del usuario en el formulario de pago'; + + $this->log->logInfo('Transacción con error => Orden de compra: ' . $buyOrder); + $this->log->logInfo('Detalle: ' . $message); + + return $this->redirectWithErrorMessage($message); + } + + private function handleFlowAborted(string $token) + { + $message = 'Orden cancelada por el usuario'; + + return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_CANCELED_BY_USER); + } + + private function handleFlowError(string $token) + { + $message = 'Orden cancelada por un error en el formulario de pago'; + + return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_ERROR); + } + + private function handleAuthorizedTransaction( + Order $order, + WebpayOrderData $webpayOrderData, + TransactionCommitResponse $commitResponse + ) { + $token = $webpayOrderData->getToken(); + $webpayOrderData->setPaymentStatus(WebpayOrderData::PAYMENT_STATUS_SUCCESS); + $webpayOrderData->save(); + + $authorizationCode = $commitResponse->getAuthorizationCode(); + $payment = $order->getPayment(); + $payment->setLastTransId($authorizationCode); + $payment->setTransactionId($authorizationCode); + $payment->setAdditionalInformation([ + Transaction::RAW_DETAILS => (array) $commitResponse + ]); + + $orderStatusSuccess = $this->configProvider->getOrderSuccessStatus(); + $order->setState($orderStatusSuccess)->setStatus($orderStatusSuccess); + $commitHistoryComment = $this->createCommitHistoryComment($commitResponse); + $order->addStatusToHistory($order->getStatus(), $commitHistoryComment); + $order->save(); + + $this->log->logInfo('Transacción aprobada => token: ' . $token); + + $message = $this->getSuccessMessage($this->commitResponseToArray($commitResponse)); + + return $this->redirectToSuccess($message); + } + + private function handleUnauthorizedTransaction( + Order $order, + WebpayOrderData $webpayOrderData, + TransactionCommitResponse $commitResponse + ) { + $this->log->logInfo('Transacción rechazada => token: ' . $webpayOrderData->getToken()); + + $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; + + $webpayOrderData->setPaymentStatus(WebpayOrderData::PAYMENT_STATUS_FAILED); + $webpayOrderData->save(); + + $commitHistoryComment = $this->createCommitHistoryComment($commitResponse); + $this->cancelOrder($order, $commitHistoryComment); + + return $this->redirectWithErrorMessage($message); + } + + private function handleAbortedTransaction(string $token, string $message, string $webpayStatus) + { + $this->log->logInfo('Transacción con error => token: ' . $token); + $this->log->logInfo('Detalle: ' . $message); + + $webpayOrderData = $this->getWebpayOrderData($token); + $webpayOrderData->setPaymentStatus($webpayStatus); + $webpayOrderData->save(); + + $orderId = $webpayOrderData->getOrderId(); + $order = $this->getOrder($orderId); + + if ($order != null) { + $this->cancelOrder($order, $message); + } + + return $this->redirectWithErrorMessage($message); + } + + private function handleException(string $exceptionMessage) + { + $message = 'No se pudo procesar el pago '; + $this->log->logError($message . $exceptionMessage); + + return $this->redirectWithErrorMessage($message); + } + private function redirectToSuccess(string $message) { $this->checkoutSession->getQuote()->setIsActive(false)->save(); @@ -278,26 +344,6 @@ private function getWebpayOrderData($tokenWs): WebpayOrderData return $webpayOrderDataModel->load($tokenWs, 'token'); } - /** - * @param \Exception $e - * @param $order - * @param $orderStatusCanceled - * - * @return \Magento\Framework\Controller\Result\Redirect - */ - private function errorOnConfirmation(\Exception $e, $order, $orderStatusCanceled) - { - $message = 'Error al confirmar transacción: ' . $e->getMessage(); - $this->log->logError($message); - $this->checkoutSession->restoreQuote(); - $this->messageManager->addError(__($message)); - if ($order != null && $order->getState() != Order::STATE_PROCESSING) { - $this->cancelOrder($order, $message); - } - - return $this->resultRedirectFactory->create()->setPath('checkout/cart'); - } - private function createCommitHistoryComment($commitResponse): string { if ($commitResponse instanceof TransactionCommitResponse) { From 8127612d96859f521340edfa96c7c526d74d75bc Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 9 May 2024 15:59:14 -0400 Subject: [PATCH 070/159] fix: assign correct value to constant --- Model/WebpayOrderData.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Model/WebpayOrderData.php b/Model/WebpayOrderData.php index 33e9d47..0d2ee20 100644 --- a/Model/WebpayOrderData.php +++ b/Model/WebpayOrderData.php @@ -10,7 +10,7 @@ class WebpayOrderData extends AbstractModel implements \Magento\Framework\DataOb const PAYMENT_STATUS_WATING = 'WAITING'; const PAYMENT_STATUS_SUCCESS = 'SUCCESS'; const PAYMENT_STATUS_FAILED = 'FAILED'; - const PAYMENT_STATUS_CANCELED_BY_USER = 'FAILED'; + const PAYMENT_STATUS_CANCELED_BY_USER = 'CANCELED_BY_USER'; const PAYMENT_STATUS_ERROR = 'ERROR'; /** From 0a00e6e4ac52d7f32b55231608e763a4b19732e6 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 9 May 2024 18:02:49 -0400 Subject: [PATCH 071/159] feat: add new logs for transaction flow --- Controller/Transaction/CommitWebpay.php | 36 ++++++++++++++++++------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index be76a3b..aa15f95 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -2,6 +2,7 @@ namespace Transbank\Webpay\Controller\Transaction; +use Exception; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment\Transaction; use Transbank\Webpay\Helper\ObjectManagerHelper; @@ -73,8 +74,8 @@ public function execute() $request = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET; return $this->handleRequest($request); - } catch (\Exception $e) { - return $this->handleException($e->getMessage()); + } catch (Exception $exception) { + return $this->handleException($exception); } } @@ -138,6 +139,8 @@ private function getWebpayFlow(array $request): string private function handleNormalFlow(string $token) { + $this->log->logInfo('Procesando transacción por flujo Normal => token: ' . $token); + $config = $this->configProvider->getPluginConfig(); $webpayOrderData = $this->getWebpayOrderData($token); $orderId = $webpayOrderData->getOrderId(); @@ -157,16 +160,17 @@ private function handleNormalFlow(string $token) private function handleFlowTimeout(string $buyOrder) { - $message = 'Orden cancelada por inactividad del usuario en el formulario de pago'; + $this->log->logInfo('Procesando transacción por flujo timeout => Orden de compra: ' . $buyOrder); - $this->log->logInfo('Transacción con error => Orden de compra: ' . $buyOrder); - $this->log->logInfo('Detalle: ' . $message); + $message = 'Orden cancelada por inactividad del usuario en el formulario de pago'; return $this->redirectWithErrorMessage($message); } private function handleFlowAborted(string $token) { + $this->log->logInfo('Procesando transacción por flujo de pago abortado => Token: ' . $token); + $message = 'Orden cancelada por el usuario'; return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_CANCELED_BY_USER); @@ -174,6 +178,8 @@ private function handleFlowAborted(string $token) private function handleFlowError(string $token) { + $this->log->logInfo('Procesando transacción por flujo de error en formulario de pago => Token: ' . $token); + $message = 'Orden cancelada por un error en el formulario de pago'; return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_ERROR); @@ -184,7 +190,10 @@ private function handleAuthorizedTransaction( WebpayOrderData $webpayOrderData, TransactionCommitResponse $commitResponse ) { + $token = $webpayOrderData->getToken(); + $this->log->logInfo('Transacción autorizada por Transbank, procesando orden => Token: ' . $token); + $webpayOrderData->setPaymentStatus(WebpayOrderData::PAYMENT_STATUS_SUCCESS); $webpayOrderData->save(); @@ -202,7 +211,7 @@ private function handleAuthorizedTransaction( $order->addStatusToHistory($order->getStatus(), $commitHistoryComment); $order->save(); - $this->log->logInfo('Transacción aprobada => token: ' . $token); + $this->log->logInfo('Orden aprobada => Token: ' . $token); $message = $this->getSuccessMessage($this->commitResponseToArray($commitResponse)); @@ -214,7 +223,8 @@ private function handleUnauthorizedTransaction( WebpayOrderData $webpayOrderData, TransactionCommitResponse $commitResponse ) { - $this->log->logInfo('Transacción rechazada => token: ' . $webpayOrderData->getToken()); + $token = $webpayOrderData->getToken(); + $this->log->logInfo('Transacción rechazada por Transbank, cancelando orden => token: ' . $token); $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; @@ -224,12 +234,14 @@ private function handleUnauthorizedTransaction( $commitHistoryComment = $this->createCommitHistoryComment($commitResponse); $this->cancelOrder($order, $commitHistoryComment); + $this->log->logInfo('Orden cancelada => Token: ' . $token); + return $this->redirectWithErrorMessage($message); } private function handleAbortedTransaction(string $token, string $message, string $webpayStatus) { - $this->log->logInfo('Transacción con error => token: ' . $token); + $this->log->logInfo('Error al procesar transacción por Transbank => token: ' . $token); $this->log->logInfo('Detalle: ' . $message); $webpayOrderData = $this->getWebpayOrderData($token); @@ -241,15 +253,19 @@ private function handleAbortedTransaction(string $token, string $message, string if ($order != null) { $this->cancelOrder($order, $message); + $this->log->logInfo('Orden cancelada => Token: ' . $token); } return $this->redirectWithErrorMessage($message); } - private function handleException(string $exceptionMessage) + private function handleException(Exception $exception) { $message = 'No se pudo procesar el pago '; - $this->log->logError($message . $exceptionMessage); + + $this->log->logError('Error al procesar el pago: '); + $this->log->logError($exception->getMessage()); + $this->log->logError($exception->getTraceAsString()); return $this->redirectWithErrorMessage($message); } From d2c03e309d31e6ec9e824739483f7a9fb4bce711 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 15:52:43 -0400 Subject: [PATCH 072/159] feat: use new success view --- Controller/Transaction/CommitWebpay.php | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index aa15f95..af8238f 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -213,9 +213,9 @@ private function handleAuthorizedTransaction( $this->log->logInfo('Orden aprobada => Token: ' . $token); - $message = $this->getSuccessMessage($this->commitResponseToArray($commitResponse)); + $responseData = TbkResponseHelper::getWebpayFormattedResponse($commitResponse); - return $this->redirectToSuccess($message); + return $this->redirectToSuccess($responseData); } private function handleUnauthorizedTransaction( @@ -270,14 +270,15 @@ private function handleException(Exception $exception) return $this->redirectWithErrorMessage($message); } - private function redirectToSuccess(string $message) + private function redirectToSuccess(array $responseData) { $this->checkoutSession->getQuote()->setIsActive(false)->save(); - $this->messageManager->addComplexSuccessMessage( - 'successMessage', - ['message' => $message] - ); - return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); + + $resultPage = $this->resultPageFactory->create(); + $resultPage->addHandle('transbank_checkout_success'); + $block = $resultPage->getLayout()->getBlock('transbank_success'); + $block->setResponse($responseData); + return $resultPage; } private function redirectWithErrorMessage(string $message) From cd9a6e7ec23e76d16679b2f84c6fa5188dddca00 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 17:29:12 -0400 Subject: [PATCH 073/159] refactor: remove unnecessary payment dictionary --- Controller/Transaction/CommitWebpay.php | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index af8238f..89e25a7 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -22,14 +22,6 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action const WEBPAY_FLOW_ABORTED = 'aborted'; const WEBPAY_FLOW_ERROR = 'error'; - protected $paymentTypeCodearray = [ - 'VD' => 'Venta Debito', - 'VN' => 'Venta Normal', - 'VC' => 'Venta en cuotas', - 'SI' => '3 cuotas sin interés', - 'S2' => '2 cuotas sin interés', - 'NC' => 'N cuotas sin interés', - ]; protected $configProvider; protected $quoteRepository; protected $cart; From 2cd40ed7c6d2c9802c97589f1ed8d961e8a7d500 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 17:32:57 -0400 Subject: [PATCH 074/159] refactor: remove unused methods --- Controller/Transaction/CommitWebpay.php | 47 ------------------------- 1 file changed, 47 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 89e25a7..5bd709e 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -289,53 +289,6 @@ private function cancelOrder(Order $order, string $message) $order->save(); } - protected function commitResponseToArray($response) - { - return [ - 'vci' => $response->getVci(), - 'amount' => $response->getAmount(), - 'status' => $response->getStatus(), - 'buyOrder' => $response->getBuyOrder(), - 'sessionId' => $response->getSessionId(), - 'cardDetail' => $response->getCardDetail(), - 'accountingDate' => $response->getAccountingDate(), - 'transactionDate' => $response->getTransactionDate(), - 'authorizationCode' => $response->getAuthorizationCode(), - 'paymentTypeCode' => $response->getPaymentTypeCode(), - 'responseCode' => $response->getResponseCode(), - 'installmentsAmount' => $response->getInstallmentsAmount(), - 'installmentsNumber' => $response->getInstallmentsNumber(), - 'balance' => $response->getBalance(), - ]; - } - - protected function orderCanceledByUser($token, $quoteId, $orderStatusCanceled) - { - $message = 'Orden cancelada por el usuario'; - - $webpayOrderData = $this->getWebpayOrderData($token); - $orderId = $webpayOrderData->getOrderId(); - $order = $this->getOrder($orderId); - - $getQuoteById = $this->quoteRepository->get($quoteId); - - if ($getQuoteById) { - $customerId = $getQuoteById->getCustomerId(); - $isGuest = $getQuoteById->getCustomerIsGuest(); - - if ($customerId && $isGuest == 1) { - $getQuoteById->setCustomerIsGuest(false); - $getQuoteById->save(); - } - } - - if ($order != null) { - $this->cancelOrder($order, $message); - } - - return $this->redirectWithErrorMessage($message); - } - protected function getOrder($orderId): Order { $order = ObjectManagerHelper::get(Order::class); From 7163a3bf85ec0b71336e3655eb769afd386e7963 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 18:02:00 -0400 Subject: [PATCH 075/159] feat: log the request --- Controller/Transaction/CommitWebpay.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 5bd709e..116a0c9 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -63,7 +63,11 @@ public function __construct( public function execute() { try { - $request = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET; + $requestMethod = $_SERVER['REQUEST_METHOD']; + $request = $requestMethod === 'POST' ? $_POST : $_GET; + + $this->log->logInfo('Request: method -> ' . $requestMethod); + $this->log->logInfo('Request: payload -> ' . json_encode($request)); return $this->handleRequest($request); } catch (Exception $exception) { From 9648416b7b91bf631cf5a1e58eda7e99bce09a49 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 18:37:57 -0400 Subject: [PATCH 076/159] feat: cancel order in timeout flow --- Controller/Transaction/CommitWebpay.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 116a0c9..6ea43d4 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -159,6 +159,11 @@ private function handleFlowTimeout(string $buyOrder) $this->log->logInfo('Procesando transacción por flujo timeout => Orden de compra: ' . $buyOrder); $message = 'Orden cancelada por inactividad del usuario en el formulario de pago'; + $order = $this->getOrder($buyOrder); + + if (!is_null($order->getId())) { + $this->cancelOrder($order, $message); + } return $this->redirectWithErrorMessage($message); } From 8d4c8e8bb86489c65e66d782db207f4c64e732fe Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 18:53:48 -0400 Subject: [PATCH 077/159] feat: add timeout payment status --- Model/WebpayOrderData.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Model/WebpayOrderData.php b/Model/WebpayOrderData.php index 0d2ee20..8647c20 100644 --- a/Model/WebpayOrderData.php +++ b/Model/WebpayOrderData.php @@ -12,6 +12,7 @@ class WebpayOrderData extends AbstractModel implements \Magento\Framework\DataOb const PAYMENT_STATUS_FAILED = 'FAILED'; const PAYMENT_STATUS_CANCELED_BY_USER = 'CANCELED_BY_USER'; const PAYMENT_STATUS_ERROR = 'ERROR'; + const PAYMENT_STATUS_TIMEOUT = 'TIMEOUT'; /** * @return void From bbdfba57dc71e7a80f1a8420b037a9ea810608f5 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 19:00:52 -0400 Subject: [PATCH 078/159] feat: add method getWebpayOrderDataByBuyOrder --- Controller/Transaction/CommitWebpay.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 6ea43d4..f04996e 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -315,6 +315,19 @@ private function getWebpayOrderData($tokenWs): WebpayOrderData return $webpayOrderDataModel->load($tokenWs, 'token'); } + /** + * Get the Webpay order data by buy order. + * + * @param string $buyOrder The buy order. + * + * @return WebpayOrderData + */ + private function getWebpayOrderDataByBuyOrder($buyOrder): WebpayOrderData + { + $webpayOrderDataModel = $this->webpayOrderDataFactory->create(); + return $webpayOrderDataModel->load($buyOrder, 'order_id'); + } + private function createCommitHistoryComment($commitResponse): string { if ($commitResponse instanceof TransactionCommitResponse) { From 5536957b98d008580410c7563af27c56cde3376a Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 15 May 2024 19:01:29 -0400 Subject: [PATCH 079/159] feat: use handleAbortedTransaction method in timeout flow --- Controller/Transaction/CommitWebpay.php | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index f04996e..6b22ca2 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -159,13 +159,11 @@ private function handleFlowTimeout(string $buyOrder) $this->log->logInfo('Procesando transacción por flujo timeout => Orden de compra: ' . $buyOrder); $message = 'Orden cancelada por inactividad del usuario en el formulario de pago'; - $order = $this->getOrder($buyOrder); - if (!is_null($order->getId())) { - $this->cancelOrder($order, $message); - } + $webpayOrderData = $this->getWebpayOrderDataByBuyOrder($buyOrder); + $token = $webpayOrderData->getToken(); - return $this->redirectWithErrorMessage($message); + return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_TIMEOUT); } private function handleFlowAborted(string $token) @@ -262,7 +260,7 @@ private function handleAbortedTransaction(string $token, string $message, string private function handleException(Exception $exception) { - $message = 'No se pudo procesar el pago '; + $message = 'No se pudo procesar el pago.'; $this->log->logError('Error al procesar el pago: '); $this->log->logError($exception->getMessage()); From afeb4ba651cf70a9816c21c4331586fc50253e3b Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Fri, 17 May 2024 16:41:40 -0400 Subject: [PATCH 080/159] feat: log when process starts a transaction --- Controller/Transaction/CommitWebpay.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 6b22ca2..40e75d2 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -66,6 +66,7 @@ public function execute() $requestMethod = $_SERVER['REQUEST_METHOD']; $request = $requestMethod === 'POST' ? $_POST : $_GET; + $this->log->logInfo('Procesando retorno desde formulario de Webpay.'); $this->log->logInfo('Request: method -> ' . $requestMethod); $this->log->logInfo('Request: payload -> ' . json_encode($request)); From 920d328a22813ea626ffe36377e0317977f7bf7c Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Fri, 17 May 2024 16:43:39 -0400 Subject: [PATCH 081/159] feat: add constant for transaction flow messages --- Controller/Transaction/CommitWebpay.php | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 40e75d2..24fde08 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -22,6 +22,12 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action const WEBPAY_FLOW_ABORTED = 'aborted'; const WEBPAY_FLOW_ERROR = 'error'; + const WEBPAY_FAILED_FLOW_MESSAGE = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; + const WEBPAY_CANCELED_BY_USER_FLOW_MESSAGE = 'Orden cancelada por el usuario.'; + const WEBPAY_TIMEOUT_FLOW_MESSAGE = 'Orden cancelada por inactividad del usuario en el formulario de pago.'; + const WEBPAY_ERROR_FLOW_MESSAGE = 'Orden cancelada por un error en el formulario de pago'; + const WEBPAY_EXCEPTION_FLOW_MESSAGE = 'No se pudo procesar el pago.'; + protected $configProvider; protected $quoteRepository; protected $cart; @@ -159,7 +165,7 @@ private function handleFlowTimeout(string $buyOrder) { $this->log->logInfo('Procesando transacción por flujo timeout => Orden de compra: ' . $buyOrder); - $message = 'Orden cancelada por inactividad del usuario en el formulario de pago'; + $message = self::WEBPAY_TIMEOUT_FLOW_MESSAGE; $webpayOrderData = $this->getWebpayOrderDataByBuyOrder($buyOrder); $token = $webpayOrderData->getToken(); @@ -171,7 +177,7 @@ private function handleFlowAborted(string $token) { $this->log->logInfo('Procesando transacción por flujo de pago abortado => Token: ' . $token); - $message = 'Orden cancelada por el usuario'; + $message = self::WEBPAY_CANCELED_BY_USER_FLOW_MESSAGE; return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_CANCELED_BY_USER); } @@ -180,7 +186,7 @@ private function handleFlowError(string $token) { $this->log->logInfo('Procesando transacción por flujo de error en formulario de pago => Token: ' . $token); - $message = 'Orden cancelada por un error en el formulario de pago'; + $message = self::WEBPAY_ERROR_FLOW_MESSAGE; return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_ERROR); } @@ -226,7 +232,7 @@ private function handleUnauthorizedTransaction( $token = $webpayOrderData->getToken(); $this->log->logInfo('Transacción rechazada por Transbank, cancelando orden => token: ' . $token); - $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; + $message = self::WEBPAY_FAILED_FLOW_MESSAGE; $webpayOrderData->setPaymentStatus(WebpayOrderData::PAYMENT_STATUS_FAILED); $webpayOrderData->save(); @@ -261,7 +267,7 @@ private function handleAbortedTransaction(string $token, string $message, string private function handleException(Exception $exception) { - $message = 'No se pudo procesar el pago.'; + $message = self::WEBPAY_EXCEPTION_FLOW_MESSAGE; $this->log->logError('Error al procesar el pago: '); $this->log->logError($exception->getMessage()); From 45a7f11ec90472160b4b5f5dfb9c7ccf75bd5b4c Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Fri, 17 May 2024 16:54:49 -0400 Subject: [PATCH 082/159] feat: add checkTransactionIsAlreadyProcessed method --- Controller/Transaction/CommitWebpay.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 24fde08..2a0fe00 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -303,6 +303,14 @@ private function cancelOrder(Order $order, string $message) $order->save(); } + private function checkTransactionIsAlreadyProcessed($token): bool + { + $webpayOrderData = $this->getWebpayOrderData($token); + $status = $webpayOrderData->getPaymentStatus(); + + return $status != WebpayOrderData::PAYMENT_STATUS_WATING; + } + protected function getOrder($orderId): Order { $order = ObjectManagerHelper::get(Order::class); From bd02c068cf87c2cafe15fbc4539e206bb8de6fed Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Fri, 17 May 2024 16:55:12 -0400 Subject: [PATCH 083/159] feat: add handleTransactionAlreadyProcessed method --- Controller/Transaction/CommitWebpay.php | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 2a0fe00..38f4289 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -276,6 +276,43 @@ private function handleException(Exception $exception) return $this->redirectWithErrorMessage($message); } + private function handleTransactionAlreadyProcessed(string $token) + { + $this->log->logInfo('Transacción ya se encontraba procesada.'); + + $webpayOrderData = $this->getWebpayOrderData($token); + $status = $webpayOrderData->getPaymentStatus(); + $message = self::WEBPAY_EXCEPTION_FLOW_MESSAGE; + + $this->log->logInfo('Estado de la transacción => ' . $status); + + if ($status == WebpayOrderData::PAYMENT_STATUS_SUCCESS) { + $metadata = $webpayOrderData->getMetadata(); + $response = json_decode($metadata); + $formattedResponse = TbkResponseHelper::getWebpayFormattedResponse($response); + + return $this->redirectToSuccess($formattedResponse); + } + + if ($status == WebpayOrderData::PAYMENT_STATUS_FAILED) { + $message = self::WEBPAY_FAILED_FLOW_MESSAGE; + } + + if ($status == WebpayOrderData::PAYMENT_STATUS_CANCELED_BY_USER) { + $message = self::WEBPAY_CANCELED_BY_USER_FLOW_MESSAGE; + } + + if ($status == WebpayOrderData::PAYMENT_STATUS_TIMEOUT) { + $message = self::WEBPAY_TIMEOUT_FLOW_MESSAGE; + } + + if ($status == WebpayOrderData::PAYMENT_STATUS_ERROR) { + $message = self::WEBPAY_ERROR_FLOW_MESSAGE; + } + + return $this->redirectWithErrorMessage($message); + } + private function redirectToSuccess(array $responseData) { $this->checkoutSession->getQuote()->setIsActive(false)->save(); From 44f05e8130ef624ef1f1ae668485801ad3fbb39f Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Fri, 17 May 2024 16:57:15 -0400 Subject: [PATCH 084/159] fix: validate transaction status first --- Controller/Transaction/CommitWebpay.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 38f4289..7aabdff 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -144,6 +144,10 @@ private function handleNormalFlow(string $token) { $this->log->logInfo('Procesando transacción por flujo Normal => token: ' . $token); + if ($this->checkTransactionIsAlreadyProcessed($token)) { + return $this->handleTransactionAlreadyProcessed($token); + } + $config = $this->configProvider->getPluginConfig(); $webpayOrderData = $this->getWebpayOrderData($token); $orderId = $webpayOrderData->getOrderId(); @@ -170,6 +174,10 @@ private function handleFlowTimeout(string $buyOrder) $webpayOrderData = $this->getWebpayOrderDataByBuyOrder($buyOrder); $token = $webpayOrderData->getToken(); + if ($this->checkTransactionIsAlreadyProcessed($token)) { + return $this->handleTransactionAlreadyProcessed($token); + } + return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_TIMEOUT); } @@ -177,6 +185,10 @@ private function handleFlowAborted(string $token) { $this->log->logInfo('Procesando transacción por flujo de pago abortado => Token: ' . $token); + if ($this->checkTransactionIsAlreadyProcessed($token)) { + return $this->handleTransactionAlreadyProcessed($token); + } + $message = self::WEBPAY_CANCELED_BY_USER_FLOW_MESSAGE; return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_CANCELED_BY_USER); @@ -186,6 +198,10 @@ private function handleFlowError(string $token) { $this->log->logInfo('Procesando transacción por flujo de error en formulario de pago => Token: ' . $token); + if ($this->checkTransactionIsAlreadyProcessed($token)) { + return $this->handleTransactionAlreadyProcessed($token); + } + $message = self::WEBPAY_ERROR_FLOW_MESSAGE; return $this->handleAbortedTransaction($token, $message, WebpayOrderData::PAYMENT_STATUS_ERROR); From 57731a4355fc89dd95ef769e973847f2b1b11baf Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Tue, 18 Jun 2024 10:54:21 -0400 Subject: [PATCH 085/159] refactor: improve cancel order flow on commit webpay --- Controller/Transaction/CommitWebpay.php | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 7aabdff..76bceab 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -11,6 +11,7 @@ use Transbank\Webpay\Helper\PluginLogger; use Transbank\Webpay\Helper\TbkResponseHelper; use Transbank\Webpay\WebpayPlus\Responses\TransactionCommitResponse; +use Transbank\Webpay\Helper\RestoreQuoteWebpay; /** * Controller for commit transaction Webpay. @@ -37,6 +38,7 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action protected $resultPageFactory; protected $webpayOrderDataFactory; protected $log; + protected $restoreQuoteWebpay; public function __construct( \Magento\Framework\App\Action\Context $context, @@ -47,7 +49,8 @@ public function __construct( \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, \Magento\Framework\View\Result\PageFactory $resultPageFactory, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, - \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory + \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, + \Transbank\Webpay\Helper\RestoreQuoteWebpay $restoreQuoteWebpay ) { parent::__construct($context); @@ -61,6 +64,7 @@ public function __construct( $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->log = new PluginLogger(); + $this->restoreQuoteWebpay = $restoreQuoteWebpay; } /** @@ -71,7 +75,7 @@ public function execute() try { $requestMethod = $_SERVER['REQUEST_METHOD']; $request = $requestMethod === 'POST' ? $_POST : $_GET; - + $this->log->logInfo('-------------------------------------------------------------------------------- Commit'); $this->log->logInfo('Procesando retorno desde formulario de Webpay.'); $this->log->logInfo('Request: method -> ' . $requestMethod); $this->log->logInfo('Request: payload -> ' . json_encode($request)); @@ -354,6 +358,12 @@ private function cancelOrder(Order $order, string $message) $order->setStatus($orderStatusCanceled); $order->addStatusToHistory($order->getStatus(), $message); $order->save(); + $quote = $this->checkoutSession->getQuote(); + $newQuote = $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($quote); + + $this->cart->setQuote($newQuote); + + return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } private function checkTransactionIsAlreadyProcessed($token): bool From 167ae60c0f3f6afc76bf1a947fe23bd58699a55c Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Tue, 18 Jun 2024 10:54:36 -0400 Subject: [PATCH 086/159] refactor: improve canceled order flow on create webpay --- Controller/Transaction/CreateWebpay.php | 55 ++++++++++++++++++++----- 1 file changed, 45 insertions(+), 10 deletions(-) diff --git a/Controller/Transaction/CreateWebpay.php b/Controller/Transaction/CreateWebpay.php index bd2d0e7..325852a 100644 --- a/Controller/Transaction/CreateWebpay.php +++ b/Controller/Transaction/CreateWebpay.php @@ -6,6 +6,8 @@ use Transbank\Webpay\Model\Webpay; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\PluginLogger; +use Transbank\Webpay\Helper\RestoreQuoteWebpay; +use Magento\Quote\Model\QuoteRepository; /** * Controller for create transaction Webpay. @@ -20,6 +22,8 @@ class CreateWebpay extends \Magento\Framework\App\Action\Action protected $storeManager; protected $webpayOrderDataFactory; protected $log; + protected $quoteRepository; + protected $restoreQuoteWebpay; /** * CreateWebpayM22 constructor. @@ -32,6 +36,8 @@ class CreateWebpay extends \Magento\Framework\App\Action\Action * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Transbank\Webpay\Model\Config\ConfigProvider $configProvider * @param \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory + * @param \Magento\Quote\Model\QuoteRepository $quoteRepository, + * @param \Transbank\Webpay\Helper\RestoreQuoteWebpay $restoreQuoteWebpay */ public function __construct( \Magento\Framework\App\Action\Context $context, @@ -41,7 +47,9 @@ public function __construct( \Magento\Quote\Model\QuoteManagement $quoteManagement, \Magento\Store\Model\StoreManagerInterface $storeManager, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, - \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory + \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, + \Magento\Quote\Model\QuoteRepository $quoteRepository, + \Transbank\Webpay\Helper\RestoreQuoteWebpay $restoreQuoteWebpay ) { parent::__construct($context); @@ -53,6 +61,8 @@ public function __construct( $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->log = new PluginLogger(); + $this->quoteRepository = $quoteRepository; + $this->restoreQuoteWebpay = $restoreQuoteWebpay; } /** @@ -62,7 +72,6 @@ public function __construct( */ public function execute() { - $this->log->logInfo('B.1. Iniciando medio de pago Webpay Plus'); $response = null; @@ -76,6 +85,8 @@ public function execute() $config = $this->configProvider->getPluginConfig(); + $this->restoreQuote(); + $tmpOrder = $this->getOrder(); $this->checkoutSession->restoreQuote(); @@ -102,7 +113,7 @@ public function execute() $baseUrl = $this->storeManager->getStore()->getBaseUrl(); - $returnUrl = $baseUrl.$config['URL_RETURN']; + $returnUrl = $baseUrl . $config['URL_RETURN']; $quoteId = $quote->getId(); $orderId = $this->getOrderId(); @@ -110,11 +121,11 @@ public function execute() $transbankSdkWebpay = new TransbankSdkWebpayRest($config); $this->log->logInfo('B.2. Preparando datos antes de crear la transacción en Transbank'); - $this->log->logInfo('amount: '.$grandTotal.', sessionId: '.$quoteId.', buyOrder: '.$orderId.', returnUrl: '.$returnUrl); + $this->log->logInfo('amount: ' . $grandTotal . ', sessionId: ' . $quoteId . ', buyOrder: ' . $orderId . ', returnUrl: ' . $returnUrl); $response = $transbankSdkWebpay->createTransaction($grandTotal, $quoteId, $orderId, $returnUrl); $dataLog = ['grandTotal' => $grandTotal, 'quoteId' => $quoteId, 'orderId' => $orderId]; - $message = '

Esperando pago con Webpay


'.json_encode($dataLog); + $message = '

Esperando pago con Webpay


' . json_encode($dataLog); if (isset($response['token_ws'])) { $this->saveWebpayData( @@ -133,18 +144,15 @@ public function execute() $order->cancel(); $order->save(); $order->setStatus($orderStatusCanceled); - $message = '

Error en pago con Webpay


'.json_encode($response); + $message = '

Error en pago con Webpay


' . json_encode($response); $this->log->logError('B.3. Transacción creada con error en Transbank'); $this->log->logError(json_encode($response)); } $order->addStatusToHistory($order->getStatus(), $message); $order->save(); - - $this->checkoutSession->getQuote()->setIsActive(true)->save(); - $this->cart->getQuote()->setIsActive(true)->save(); } catch (\Exception $e) { - $message = 'Error al crear transacción: '.$e->getMessage(); + $message = 'Error al crear transacción: ' . $e->getMessage(); $this->log->logError($message); $response = ['error' => $message]; if ($order != null) { @@ -162,6 +170,33 @@ public function execute() return $result; } + /** + * Restore quote. + */ + private function restoreQuote() + { + $lastRealOrder = $this->checkoutSession->getLastRealOrder(); + try { + $quote = $this->quoteRepository->get($lastRealOrder->getQuoteId()); + + if ($lastRealOrder->getId() && $lastRealOrder->getState() != \Magento\Sales\Model\Order::STATE_CANCELED) { + $quote->setIsActive(1)->setReservedOrderId(null); + $this->quoteRepository->save($quote); + $this->checkoutSession->replaceQuote($quote)->unsLastRealOrderId(); + if ($lastRealOrder->getCustomerId()) { + $this->restoreQuoteWebpay->setGuestData($quote); + } + } else { + $quote->setIsActive(0); + $this->quoteRepository->save($quote); + $this->checkoutSession->replaceQuote($this->checkoutSession->getQuote()); + } + } catch (\Exception $e) { + $message = 'Error al recuperar el carrito: ' . $e->getMessage(); + $this->log->logError($message); + } + } + /** * @return |null */ From c24b285b4f85939163b5f97412b413f02752f4c3 Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Tue, 18 Jun 2024 10:54:48 -0400 Subject: [PATCH 087/159] refactor: improve cancel order logic on restore quote helper --- Helper/RestoreQuoteWebpay.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Helper/RestoreQuoteWebpay.php b/Helper/RestoreQuoteWebpay.php index d05f3f8..d2800f0 100644 --- a/Helper/RestoreQuoteWebpay.php +++ b/Helper/RestoreQuoteWebpay.php @@ -37,15 +37,19 @@ public function __construct( public function replaceQuoteAfterRedirection($quote) { - - $this->quoteRepository->get($this->checkoutSession->getQuoteId())->setIsActive(false)->save(); + $quote->setIsActive(false)->save(); $newQuote = $this->quoteFactory->create(); $newQuote->merge($quote); + $newQuote->setStoreId($this->checkoutSession->getStoreId()); $newQuote->setIsActive(true)->collectTotals(); $this->quoteRepository->save($newQuote); + $this->checkoutSession->clearStorage(); $this->checkoutSession->replaceQuote($newQuote); + $this->checkoutSession->setQuoteId($newQuote->getId()); $this->setGuestData($quote); + + return $newQuote; } protected function restoreShippingInformation($oldQuote, $newQuote) From 47d90c7eae8ce3992ae555b502e0544586b523db Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Tue, 18 Jun 2024 11:03:31 -0400 Subject: [PATCH 088/159] refactor: remove debug log on commit webpay --- Controller/Transaction/CommitWebpay.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 76bceab..c78d28e 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -75,7 +75,6 @@ public function execute() try { $requestMethod = $_SERVER['REQUEST_METHOD']; $request = $requestMethod === 'POST' ? $_POST : $_GET; - $this->log->logInfo('-------------------------------------------------------------------------------- Commit'); $this->log->logInfo('Procesando retorno desde formulario de Webpay.'); $this->log->logInfo('Request: method -> ' . $requestMethod); $this->log->logInfo('Request: payload -> ' . json_encode($request)); From f303530136b2722b4a94c7ea3e201dd2b1b8654d Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 24 Jun 2024 16:35:39 -0400 Subject: [PATCH 089/159] fix: handle error when commit fails --- Controller/Transaction/CommitWebpay.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 7aabdff..524fefb 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -156,6 +156,10 @@ private function handleNormalFlow(string $token) $transbankSdkWebpay = new TransbankSdkWebpayRest($config); $commitResponse = $transbankSdkWebpay->commitTransaction($token); + if (is_array($commitResponse) && isset($commitResponse['error'])) { + $this->handleFlowError($token); + } + $webpayOrderData->setMetadata(json_encode($commitResponse)); if ($commitResponse->isApproved()) { From 5af15f35a751acf48f2698d139cf0bb189b16c65 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 24 Jun 2024 16:50:03 -0400 Subject: [PATCH 090/159] fix: dispatch event when transaction is approved in webpay --- Controller/Transaction/CommitWebpay.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 524fefb..437b4b5 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -35,6 +35,7 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action protected $resultJsonFactory; protected $resultRawFactory; protected $resultPageFactory; + protected $eventManager; protected $webpayOrderDataFactory; protected $log; @@ -46,6 +47,7 @@ public function __construct( \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, \Magento\Framework\View\Result\PageFactory $resultPageFactory, + \Magento\Framework\Event\ManagerInterface $eventManager, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory ) { @@ -57,6 +59,7 @@ public function __construct( $this->resultJsonFactory = $resultJsonFactory; $this->resultRawFactory = $resultRawFactory; $this->resultPageFactory = $resultPageFactory; + $this->eventManager = $eventManager; $this->messageManager = $context->getMessageManager(); $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; @@ -239,6 +242,11 @@ private function handleAuthorizedTransaction( $this->log->logInfo('Orden aprobada => Token: ' . $token); + $this->eventManager->dispatch( + 'checkout_onepage_controller_success_action', + ['order' => $order] + ); + $responseData = TbkResponseHelper::getWebpayFormattedResponse($commitResponse); return $this->redirectToSuccess($responseData); From 04a65b378c42cfa302a3b7fddf349b00272c791b Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 24 Jun 2024 17:47:35 -0400 Subject: [PATCH 091/159] fix: dispatch event when transaction is approved in oneclick --- Controller/Transaction/AuthorizeOneclick.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 852eab1..c3aa028 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -21,6 +21,7 @@ use Transbank\Webpay\Model\OneclickInscriptionData; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\View\Result\PageFactory; +use Magento\Framework\Event\ManagerInterface as EventManagerInterface; use Transbank\Webpay\Model\OneclickInscriptionDataFactory; @@ -38,6 +39,7 @@ class AuthorizeOneclick extends Action private $log; private $webpayOrderDataFactory; private $resultPageFactory; + protected $eventManager; protected $messageManager; private $oneclickConfig; @@ -60,6 +62,7 @@ public function __construct( JsonFactory $resultJsonFactory, PageFactory $resultPageFactory, ConfigProvider $configProvider, + EventManagerInterface $eventManager, OneclickInscriptionDataFactory $oneclickInscriptionDataFactory, WebpayOrderDataFactory $webpayOrderDataFactory, ManagerInterface $messageManager @@ -74,6 +77,7 @@ public function __construct( $this->oneclickInscriptionDataFactory = $oneclickInscriptionDataFactory; $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->resultPageFactory = $resultPageFactory; + $this->eventManager = $eventManager; $this->log = new PluginLogger(); $this->oneclickConfig = $configProvider->getPluginConfigOneclick(); } @@ -167,6 +171,11 @@ public function execute() $this->checkoutSession->getQuote()->setIsActive(false)->save(); + $this->eventManager->dispatch( + 'checkout_onepage_controller_success_action', + ['order' => $order] + ); + $formattedResponse = TbkResponseHelper::getOneclickFormattedResponse($response); $resultPage = $this->resultPageFactory->create(); From 2dcb4f8867b51e8d9a684d3fdd1ed0c26bbd9de3 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 25 Jun 2024 11:54:53 -0400 Subject: [PATCH 092/159] fix: remove unused variable --- Observer/EmailObserver.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Observer/EmailObserver.php b/Observer/EmailObserver.php index 05e1406..c14679f 100644 --- a/Observer/EmailObserver.php +++ b/Observer/EmailObserver.php @@ -13,7 +13,6 @@ public function execute(\Magento\Framework\Event\Observer $observer) { $order = $observer->getEvent()->getOrder(); if ($emailSettings == 'transbank' || $oneclickEmailSettings == 'transbank') { - $this->_current_order = $order; $order->setCanSendNewEmailFlag(true); $order->save(); From b69140d38a02a54db0ede88ef06ff677daddebe2 Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Mon, 1 Jul 2024 16:15:32 -0400 Subject: [PATCH 093/159] refactor: simplify setGuestData and set logic for logged users on cancelOrder --- Helper/RestoreQuoteWebpay.php | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/Helper/RestoreQuoteWebpay.php b/Helper/RestoreQuoteWebpay.php index d2800f0..3dee435 100644 --- a/Helper/RestoreQuoteWebpay.php +++ b/Helper/RestoreQuoteWebpay.php @@ -35,19 +35,23 @@ public function __construct( $this->customerRepository = $customerRepository; } - public function replaceQuoteAfterRedirection($quote) + public function replaceQuoteAfterRedirection($quote, $isGuest, $storeId) { $quote->setIsActive(false)->save(); $newQuote = $this->quoteFactory->create(); $newQuote->merge($quote); - $newQuote->setStoreId($this->checkoutSession->getStoreId()); $newQuote->setIsActive(true)->collectTotals(); + + if (!$isGuest) { + $customer = $this->customerRepository->getById($quote->getCustomerId()); + $newQuote->assignCustomer($customer)->save(); + $newQuote->setStoreId($storeId); + } + $this->quoteRepository->save($newQuote); $this->checkoutSession->clearStorage(); $this->checkoutSession->replaceQuote($newQuote); - $this->checkoutSession->setQuoteId($newQuote->getId()); - $this->setGuestData($quote); return $newQuote; } @@ -77,20 +81,11 @@ protected function restoreShippingInformation($oldQuote, $newQuote) public function setGuestData($oldQuote) { - - $customerId = $oldQuote->getCustomerId(); $isGuest = $oldQuote->getCustomerIsGuest(); - if ($customerId && $isGuest == 1) { - $oldQuote->setCustomerIsGuest(false); - $oldQuote->save(); - } - - $newQuote = $this->checkoutSession->getQuote(); - - if ($isGuest == 1) { - $this->restoreShippingInformation($oldQuote, $newQuote); - } else { + if (!$isGuest) { + $customerId = $oldQuote->getCustomerId(); + $newQuote = $this->checkoutSession->getQuote(); $customer = $this->customerRepository->getById($customerId); $newQuote->assignCustomer($customer)->save(); } From 9b840650b556644896248a8156f6c2116f5588e9 Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Mon, 1 Jul 2024 16:16:02 -0400 Subject: [PATCH 094/159] refactor: simplify restoreQuote on createWebpay --- Controller/Transaction/CreateWebpay.php | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/Controller/Transaction/CreateWebpay.php b/Controller/Transaction/CreateWebpay.php index 325852a..665cf81 100644 --- a/Controller/Transaction/CreateWebpay.php +++ b/Controller/Transaction/CreateWebpay.php @@ -88,7 +88,6 @@ public function execute() $this->restoreQuote(); $tmpOrder = $this->getOrder(); - $this->checkoutSession->restoreQuote(); $quote = $this->cart->getQuote(); @@ -179,18 +178,12 @@ private function restoreQuote() try { $quote = $this->quoteRepository->get($lastRealOrder->getQuoteId()); - if ($lastRealOrder->getId() && $lastRealOrder->getState() != \Magento\Sales\Model\Order::STATE_CANCELED) { - $quote->setIsActive(1)->setReservedOrderId(null); - $this->quoteRepository->save($quote); - $this->checkoutSession->replaceQuote($quote)->unsLastRealOrderId(); - if ($lastRealOrder->getCustomerId()) { - $this->restoreQuoteWebpay->setGuestData($quote); - } - } else { - $quote->setIsActive(0); - $this->quoteRepository->save($quote); - $this->checkoutSession->replaceQuote($this->checkoutSession->getQuote()); - } + $quote->setIsActive(1)->setReservedOrderId(null); + $this->quoteRepository->save($quote); + $this->checkoutSession->replaceQuote($quote)->unsLastRealOrderId(); + $this->restoreQuoteWebpay->setGuestData($quote); + + $this->checkoutSession->restoreQuote(); } catch (\Exception $e) { $message = 'Error al recuperar el carrito: ' . $e->getMessage(); $this->log->logError($message); From 6ec39d9626de44e13d46c2dfc357acdd9b01ee11 Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Mon, 1 Jul 2024 16:16:24 -0400 Subject: [PATCH 095/159] refactor: improve cancelOrder method --- Controller/Transaction/CommitWebpay.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index c78d28e..2a76c07 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -345,7 +345,6 @@ private function redirectToSuccess(array $responseData) private function redirectWithErrorMessage(string $message) { - $this->checkoutSession->restoreQuote(); $this->messageManager->addErrorMessage(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } @@ -358,11 +357,14 @@ private function cancelOrder(Order $order, string $message) $order->addStatusToHistory($order->getStatus(), $message); $order->save(); $quote = $this->checkoutSession->getQuote(); - $newQuote = $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($quote); - $this->cart->setQuote($newQuote); + $isGuest = $quote->getCustomerIsGuest(); + $storeId = $order->getStoreId(); - return $this->resultRedirectFactory->create()->setPath('checkout/cart'); + $newQuote = $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($quote, $isGuest, $storeId); + + $this->checkoutSession->replaceQuote($newQuote); + $this->cart->setQuote($newQuote); } private function checkTransactionIsAlreadyProcessed($token): bool From b1900bf874bef0165c7f6d92d20cf7beb68c888a Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 2 Jul 2024 12:55:29 -0400 Subject: [PATCH 096/159] refactor: delete RestoreQuoteWebpay class --- Controller/Transaction/CommitWebpay.php | 13 ---- Controller/Transaction/CreateWebpay.php | 32 +-------- Helper/RestoreQuoteWebpay.php | 93 ------------------------- 3 files changed, 2 insertions(+), 136 deletions(-) delete mode 100644 Helper/RestoreQuoteWebpay.php diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 2a76c07..a088b3b 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -11,7 +11,6 @@ use Transbank\Webpay\Helper\PluginLogger; use Transbank\Webpay\Helper\TbkResponseHelper; use Transbank\Webpay\WebpayPlus\Responses\TransactionCommitResponse; -use Transbank\Webpay\Helper\RestoreQuoteWebpay; /** * Controller for commit transaction Webpay. @@ -38,7 +37,6 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action protected $resultPageFactory; protected $webpayOrderDataFactory; protected $log; - protected $restoreQuoteWebpay; public function __construct( \Magento\Framework\App\Action\Context $context, @@ -50,7 +48,6 @@ public function __construct( \Magento\Framework\View\Result\PageFactory $resultPageFactory, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, - \Transbank\Webpay\Helper\RestoreQuoteWebpay $restoreQuoteWebpay ) { parent::__construct($context); @@ -64,7 +61,6 @@ public function __construct( $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->log = new PluginLogger(); - $this->restoreQuoteWebpay = $restoreQuoteWebpay; } /** @@ -356,15 +352,6 @@ private function cancelOrder(Order $order, string $message) $order->setStatus($orderStatusCanceled); $order->addStatusToHistory($order->getStatus(), $message); $order->save(); - $quote = $this->checkoutSession->getQuote(); - - $isGuest = $quote->getCustomerIsGuest(); - $storeId = $order->getStoreId(); - - $newQuote = $this->restoreQuoteWebpay->replaceQuoteAfterRedirection($quote, $isGuest, $storeId); - - $this->checkoutSession->replaceQuote($newQuote); - $this->cart->setQuote($newQuote); } private function checkTransactionIsAlreadyProcessed($token): bool diff --git a/Controller/Transaction/CreateWebpay.php b/Controller/Transaction/CreateWebpay.php index 665cf81..27ad16c 100644 --- a/Controller/Transaction/CreateWebpay.php +++ b/Controller/Transaction/CreateWebpay.php @@ -6,7 +6,6 @@ use Transbank\Webpay\Model\Webpay; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\PluginLogger; -use Transbank\Webpay\Helper\RestoreQuoteWebpay; use Magento\Quote\Model\QuoteRepository; /** @@ -23,7 +22,6 @@ class CreateWebpay extends \Magento\Framework\App\Action\Action protected $webpayOrderDataFactory; protected $log; protected $quoteRepository; - protected $restoreQuoteWebpay; /** * CreateWebpayM22 constructor. @@ -34,10 +32,9 @@ class CreateWebpay extends \Magento\Framework\App\Action\Action * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory * @param \Magento\Quote\Model\QuoteManagement $quoteManagement * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Transbank\Webpay\Model\Config\ConfigProvider $configProvider + * @param \Transbank\Webpay\Model\Config\ConfigProvider $configProvider * @param \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory - * @param \Magento\Quote\Model\QuoteRepository $quoteRepository, - * @param \Transbank\Webpay\Helper\RestoreQuoteWebpay $restoreQuoteWebpay + * @param \Magento\Quote\Model\QuoteRepository $quoteRepository */ public function __construct( \Magento\Framework\App\Action\Context $context, @@ -49,7 +46,6 @@ public function __construct( \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, \Magento\Quote\Model\QuoteRepository $quoteRepository, - \Transbank\Webpay\Helper\RestoreQuoteWebpay $restoreQuoteWebpay ) { parent::__construct($context); @@ -62,7 +58,6 @@ public function __construct( $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->log = new PluginLogger(); $this->quoteRepository = $quoteRepository; - $this->restoreQuoteWebpay = $restoreQuoteWebpay; } /** @@ -85,8 +80,6 @@ public function execute() $config = $this->configProvider->getPluginConfig(); - $this->restoreQuote(); - $tmpOrder = $this->getOrder(); $quote = $this->cart->getQuote(); @@ -169,27 +162,6 @@ public function execute() return $result; } - /** - * Restore quote. - */ - private function restoreQuote() - { - $lastRealOrder = $this->checkoutSession->getLastRealOrder(); - try { - $quote = $this->quoteRepository->get($lastRealOrder->getQuoteId()); - - $quote->setIsActive(1)->setReservedOrderId(null); - $this->quoteRepository->save($quote); - $this->checkoutSession->replaceQuote($quote)->unsLastRealOrderId(); - $this->restoreQuoteWebpay->setGuestData($quote); - - $this->checkoutSession->restoreQuote(); - } catch (\Exception $e) { - $message = 'Error al recuperar el carrito: ' . $e->getMessage(); - $this->log->logError($message); - } - } - /** * @return |null */ diff --git a/Helper/RestoreQuoteWebpay.php b/Helper/RestoreQuoteWebpay.php deleted file mode 100644 index 3dee435..0000000 --- a/Helper/RestoreQuoteWebpay.php +++ /dev/null @@ -1,93 +0,0 @@ -quoteFactory = $quoteFactory; - $this->quoteRepository = $quoteRepository; - $this->checkoutSession = $checkoutSession; - $this->customerFactory = $customerFactory; - $this->customerRepository = $customerRepository; - } - - public function replaceQuoteAfterRedirection($quote, $isGuest, $storeId) - { - $quote->setIsActive(false)->save(); - - $newQuote = $this->quoteFactory->create(); - $newQuote->merge($quote); - $newQuote->setIsActive(true)->collectTotals(); - - if (!$isGuest) { - $customer = $this->customerRepository->getById($quote->getCustomerId()); - $newQuote->assignCustomer($customer)->save(); - $newQuote->setStoreId($storeId); - } - - $this->quoteRepository->save($newQuote); - $this->checkoutSession->clearStorage(); - $this->checkoutSession->replaceQuote($newQuote); - - return $newQuote; - } - - protected function restoreShippingInformation($oldQuote, $newQuote) - { - /* - * Restore shipping information for guest customer - */ - $oldAddress = $oldQuote->getShippingAddress(); - $newAddress = $newQuote->getShippingAddress(); - - $newAddress->setEmail($oldAddress->getEmail()); - $newAddress->setFirstname($oldAddress->getFirstname()); - $newAddress->setLastname($oldAddress->getLastname()); - $newAddress->setCompany($oldAddress->getCompany()); - $newAddress->setStreetFull($oldAddress->getStreetFull()); - $newAddress->setCountryId($oldAddress->getCountryId()); - $newAddress->setCity($oldAddress->getCity()); - $newAddress->setRegion($oldAddress->getRegion()); - $newAddress->setRegionId($oldAddress->getRegionId()); - $newAddress->setTelephone($oldAddress->getTelephone()); - $newAddress->setPostcode($oldAddress->getPostcode()); - - $this->quoteRepository->save($newQuote); - } - - public function setGuestData($oldQuote) - { - $isGuest = $oldQuote->getCustomerIsGuest(); - - if (!$isGuest) { - $customerId = $oldQuote->getCustomerId(); - $newQuote = $this->checkoutSession->getQuote(); - $customer = $this->customerRepository->getById($customerId); - $newQuote->assignCustomer($customer)->save(); - } - } -} From 2aa2231c192199e3802086ce215d3f7e5ab7ab7e Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 2 Jul 2024 12:57:13 -0400 Subject: [PATCH 097/159] fix: restore quote for canceled payments in webpay --- Controller/Transaction/CommitWebpay.php | 29 ++++++++++++++++++++++++- Controller/Transaction/CreateWebpay.php | 6 ++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index a088b3b..6ed488f 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -35,6 +35,7 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action protected $resultJsonFactory; protected $resultRawFactory; protected $resultPageFactory; + protected $quoteFactory; protected $webpayOrderDataFactory; protected $log; @@ -46,6 +47,7 @@ public function __construct( \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, \Magento\Framework\View\Result\PageFactory $resultPageFactory, + \Magento\Quote\Model\QuoteFactory $quoteFactory, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, ) { @@ -57,6 +59,7 @@ public function __construct( $this->resultJsonFactory = $resultJsonFactory; $this->resultRawFactory = $resultRawFactory; $this->resultPageFactory = $resultPageFactory; + $this->quoteFactory = $quoteFactory; $this->messageManager = $context->getMessageManager(); $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; @@ -254,9 +257,10 @@ private function handleUnauthorizedTransaction( $commitHistoryComment = $this->createCommitHistoryComment($commitResponse); $this->cancelOrder($order, $commitHistoryComment); - $this->log->logInfo('Orden cancelada => Token: ' . $token); + $this->processQuoteForCancelOrder($order); + return $this->redirectWithErrorMessage($message); } @@ -275,6 +279,8 @@ private function handleAbortedTransaction(string $token, string $message, string if ($order != null) { $this->cancelOrder($order, $message); $this->log->logInfo('Orden cancelada => Token: ' . $token); + + $this->processQuoteForCancelOrder($order); } return $this->redirectWithErrorMessage($message); @@ -354,6 +360,27 @@ private function cancelOrder(Order $order, string $message) $order->save(); } + public function processQuoteForCancelOrder(Order $order) + { + $quote = $this->quoteFactory->create()->load($order->getQuoteId()); + if ($quote->getId()) { + $quote->setIsActive(false); + $quote->setReservedOrderId(null); + $quote->save(); + + $newQuote = $this->quoteFactory->create(); + $newQuote->merge($quote) + ->setIsActive(true) + ->setStoreId($quote->getStoreId()) + ->setCustomer($quote->getCustomer()) + ->save(); + + $this->checkoutSession->replaceQuote($newQuote); + $this->cart->setQuote($newQuote); + $this->cart->saveQuote(); + } + } + private function checkTransactionIsAlreadyProcessed($token): bool { $webpayOrderData = $this->getWebpayOrderData($token); diff --git a/Controller/Transaction/CreateWebpay.php b/Controller/Transaction/CreateWebpay.php index 27ad16c..9f2832a 100644 --- a/Controller/Transaction/CreateWebpay.php +++ b/Controller/Transaction/CreateWebpay.php @@ -82,7 +82,11 @@ public function execute() $tmpOrder = $this->getOrder(); - $quote = $this->cart->getQuote(); + $quote = $this->checkoutSession->getQuote(); + if (!$quote->getId()) { + $this->checkoutSession->restoreQuote(); + $quote = $this->checkoutSession->getQuote(); + } if ($guestEmail != null) { $this->setQuoteData($quote, $guestEmail); From 1890c718703c8aa9a2d287d8bc7d09ac50752fb4 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 2 Jul 2024 12:59:48 -0400 Subject: [PATCH 098/159] refactor: remove unused import --- Controller/Transaction/CreateWebpay.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Controller/Transaction/CreateWebpay.php b/Controller/Transaction/CreateWebpay.php index 9f2832a..4cc05ab 100644 --- a/Controller/Transaction/CreateWebpay.php +++ b/Controller/Transaction/CreateWebpay.php @@ -6,7 +6,6 @@ use Transbank\Webpay\Model\Webpay; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\PluginLogger; -use Magento\Quote\Model\QuoteRepository; /** * Controller for create transaction Webpay. @@ -34,7 +33,6 @@ class CreateWebpay extends \Magento\Framework\App\Action\Action * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Transbank\Webpay\Model\Config\ConfigProvider $configProvider * @param \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory - * @param \Magento\Quote\Model\QuoteRepository $quoteRepository */ public function __construct( \Magento\Framework\App\Action\Context $context, @@ -45,7 +43,6 @@ public function __construct( \Magento\Store\Model\StoreManagerInterface $storeManager, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, - \Magento\Quote\Model\QuoteRepository $quoteRepository, ) { parent::__construct($context); @@ -57,7 +54,6 @@ public function __construct( $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->log = new PluginLogger(); - $this->quoteRepository = $quoteRepository; } /** From ec50678679e032e07ba21bd2de4094f66f7bfa71 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 8 Jul 2024 11:07:48 -0400 Subject: [PATCH 099/159] fix: remove unnecessary quote from constructor parameters --- Controller/Transaction/CommitWebpay.php | 2 +- Controller/Transaction/CreateWebpay.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 6ed488f..690cfde 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -49,7 +49,7 @@ public function __construct( \Magento\Framework\View\Result\PageFactory $resultPageFactory, \Magento\Quote\Model\QuoteFactory $quoteFactory, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, - \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, + \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory ) { parent::__construct($context); diff --git a/Controller/Transaction/CreateWebpay.php b/Controller/Transaction/CreateWebpay.php index 4cc05ab..783bbbc 100644 --- a/Controller/Transaction/CreateWebpay.php +++ b/Controller/Transaction/CreateWebpay.php @@ -42,7 +42,7 @@ public function __construct( \Magento\Quote\Model\QuoteManagement $quoteManagement, \Magento\Store\Model\StoreManagerInterface $storeManager, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, - \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, + \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory ) { parent::__construct($context); From ac31d028ed35eee1cf8bee488281c1a609c3dcba Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 8 Jul 2024 13:24:52 -0400 Subject: [PATCH 100/159] refactor: add messageManager property --- Controller/Transaction/CommitOneclick.php | 1 + Controller/Transaction/CommitWebpay.php | 1 + 2 files changed, 2 insertions(+) diff --git a/Controller/Transaction/CommitOneclick.php b/Controller/Transaction/CommitOneclick.php index 5079310..5fca6c0 100755 --- a/Controller/Transaction/CommitOneclick.php +++ b/Controller/Transaction/CommitOneclick.php @@ -43,6 +43,7 @@ class CommitOneclick extends \Magento\Framework\App\Action\Action protected $resultRawFactory; protected $oneclickInscriptionDataFactory; protected $log; + protected $messageManager; public function __construct( \Magento\Framework\App\Action\Context $context, diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 690cfde..50f672e 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -38,6 +38,7 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action protected $quoteFactory; protected $webpayOrderDataFactory; protected $log; + protected $messageManager; public function __construct( \Magento\Framework\App\Action\Context $context, From a87a99dfe7b60d3f85253eedc04f79c0e6f04bc7 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 8 Jul 2024 14:21:30 -0400 Subject: [PATCH 101/159] feat: add class QuoteHelper --- Helper/QuoteHelper.php | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Helper/QuoteHelper.php diff --git a/Helper/QuoteHelper.php b/Helper/QuoteHelper.php new file mode 100644 index 0000000..661daf2 --- /dev/null +++ b/Helper/QuoteHelper.php @@ -0,0 +1,40 @@ +cart = $cart; + $this->checkoutSession = $session; + $this->quoteFactory = $quoteFactory; + } + + public function processQuoteForCancelOrder(int $quoteId) + { + $quote = $this->quoteFactory->create()->load($quoteId); + if ($quote->getId()) { + $quote->setIsActive(false); + $quote->setReservedOrderId(null); + $quote->save(); + + $newQuote = $this->quoteFactory->create(); + $newQuote->merge($quote) + ->setIsActive(true) + ->setStoreId($quote->getStoreId()) + ->setCustomer($quote->getCustomer()) + ->save(); + + $this->checkoutSession->replaceQuote($newQuote); + $this->cart->setQuote($newQuote); + $this->cart->saveQuote(); + } + } +} From 04167766843cd8c1d3a813b3311099a887dcfade Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 8 Jul 2024 14:22:39 -0400 Subject: [PATCH 102/159] feat: implement class QuoteHelper --- Controller/Transaction/AuthorizeOneclick.php | 9 ++++- Controller/Transaction/CommitOneclick.php | 21 +++++----- Controller/Transaction/CommitWebpay.php | 40 ++++---------------- 3 files changed, 23 insertions(+), 47 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 852eab1..e57f832 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -21,6 +21,7 @@ use Transbank\Webpay\Model\OneclickInscriptionData; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\View\Result\PageFactory; +use Transbank\Webpay\Helper\QuoteHelper; use Transbank\Webpay\Model\OneclickInscriptionDataFactory; @@ -40,6 +41,7 @@ class AuthorizeOneclick extends Action private $resultPageFactory; protected $messageManager; private $oneclickConfig; + private $quoteHelper; /** * AuthorizeOneclick constructor. @@ -62,7 +64,8 @@ public function __construct( ConfigProvider $configProvider, OneclickInscriptionDataFactory $oneclickInscriptionDataFactory, WebpayOrderDataFactory $webpayOrderDataFactory, - ManagerInterface $messageManager + ManagerInterface $messageManager, + QuoteHelper $quoteHelper ) { parent::__construct($context); @@ -76,6 +79,7 @@ public function __construct( $this->resultPageFactory = $resultPageFactory; $this->log = new PluginLogger(); $this->oneclickConfig = $configProvider->getPluginConfigOneclick(); + $this->quoteHelper = $quoteHelper; } /** @@ -190,7 +194,7 @@ public function execute() $order->cancel(); $order->save(); - $this->checkoutSession->restoreQuote(); + $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); $message = TbkResponseHelper::getRejectMessage($response, "Oneclick Mall"); $this->messageManager->addErrorMessage(__($message)); @@ -208,6 +212,7 @@ public function execute() $order->setStatus($orderStatusCanceled); $order->addStatusToHistory($order->getStatus(), $message); $order->save(); + $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); } $this->messageManager->addErrorMessage($e->getMessage()); diff --git a/Controller/Transaction/CommitOneclick.php b/Controller/Transaction/CommitOneclick.php index 5fca6c0..17db629 100755 --- a/Controller/Transaction/CommitOneclick.php +++ b/Controller/Transaction/CommitOneclick.php @@ -3,6 +3,7 @@ namespace Transbank\Webpay\Controller\Transaction; use Magento\Sales\Model\Order; +use Transbank\Webpay\Helper\QuoteHelper; use Transbank\Webpay\Helper\PluginLogger; use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\OneclickInscriptionData; @@ -35,37 +36,33 @@ class CommitOneclick extends \Magento\Framework\App\Action\Action ]; protected $configProvider; - - protected $quoteRepository; - protected $cart; protected $checkoutSession; protected $resultJsonFactory; protected $resultRawFactory; protected $oneclickInscriptionDataFactory; protected $log; protected $messageManager; + private $quoteHelper; public function __construct( \Magento\Framework\App\Action\Context $context, - \Magento\Checkout\Model\Cart $cart, \Magento\Checkout\Model\Session $checkoutSession, - \Magento\Quote\Model\QuoteRepository $quoteRepository, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, - \Transbank\Webpay\Model\OneclickInscriptionDataFactory $oneclickInscriptionDataFactory + \Transbank\Webpay\Model\OneclickInscriptionDataFactory $oneclickInscriptionDataFactory, + QuoteHelper $quoteHelper ) { parent::__construct($context); - $this->cart = $cart; $this->checkoutSession = $checkoutSession; - $this->quoteRepository = $quoteRepository; $this->resultJsonFactory = $resultJsonFactory; $this->resultRawFactory = $resultRawFactory; $this->messageManager = $context->getMessageManager(); $this->configProvider = $configProvider; $this->oneclickInscriptionDataFactory = $oneclickInscriptionDataFactory; $this->log = new PluginLogger(); + $this->quoteHelper = $quoteHelper; } /** @@ -123,6 +120,8 @@ public function execute() $order->save(); $order->setStatus($orderStatusCanceled); + $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); + $statusFields = $this->getInscriptionResponseFields($inscriptionResult); $historyComment = $this->createHistoryComment( 'Inscripción rechazada', @@ -133,8 +132,6 @@ public function execute() $order->addStatusToHistory($order->getStatus(), $historyComment); $order->save(); - $this->checkoutSession->restoreQuote(); - return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } } else { @@ -144,12 +141,12 @@ public function execute() $message = "¡Tarjeta inscrita exitosamente!"; $this->messageManager->addSuccess(__($message)); - return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success'); + return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } elseif ($status == OneclickInscriptionData::PAYMENT_STATUS_FAILED) { $OneclickInscriptionData->setStatus(OneclickInscriptionData::PAYMENT_STATUS_FAILED); $OneclickInscriptionData->save(); - $this->checkoutSession->restoreQuote(); + $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); $message = $this->getRejectMessage($inscriptionResult, $oneclickTitle); $this->messageManager->addError(__($message)); diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 50f672e..87bee62 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -9,6 +9,7 @@ use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderData; use Transbank\Webpay\Helper\PluginLogger; +use Transbank\Webpay\Helper\QuoteHelper; use Transbank\Webpay\Helper\TbkResponseHelper; use Transbank\Webpay\WebpayPlus\Responses\TransactionCommitResponse; @@ -29,42 +30,36 @@ class CommitWebpay extends \Magento\Framework\App\Action\Action const WEBPAY_EXCEPTION_FLOW_MESSAGE = 'No se pudo procesar el pago.'; protected $configProvider; - protected $quoteRepository; - protected $cart; protected $checkoutSession; protected $resultJsonFactory; protected $resultRawFactory; protected $resultPageFactory; - protected $quoteFactory; protected $webpayOrderDataFactory; protected $log; protected $messageManager; + private $quoteHelper; public function __construct( \Magento\Framework\App\Action\Context $context, - \Magento\Checkout\Model\Cart $cart, \Magento\Checkout\Model\Session $checkoutSession, - \Magento\Quote\Model\QuoteRepository $quoteRepository, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, \Magento\Framework\View\Result\PageFactory $resultPageFactory, - \Magento\Quote\Model\QuoteFactory $quoteFactory, \Transbank\Webpay\Model\Config\ConfigProvider $configProvider, - \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory + \Transbank\Webpay\Model\WebpayOrderDataFactory $webpayOrderDataFactory, + QuoteHelper $quoteHelper ) { parent::__construct($context); - $this->cart = $cart; $this->checkoutSession = $checkoutSession; - $this->quoteRepository = $quoteRepository; $this->resultJsonFactory = $resultJsonFactory; $this->resultRawFactory = $resultRawFactory; $this->resultPageFactory = $resultPageFactory; - $this->quoteFactory = $quoteFactory; $this->messageManager = $context->getMessageManager(); $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->log = new PluginLogger(); + $this->quoteHelper = $quoteHelper; } /** @@ -260,7 +255,7 @@ private function handleUnauthorizedTransaction( $this->cancelOrder($order, $commitHistoryComment); $this->log->logInfo('Orden cancelada => Token: ' . $token); - $this->processQuoteForCancelOrder($order); + $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); return $this->redirectWithErrorMessage($message); } @@ -281,7 +276,7 @@ private function handleAbortedTransaction(string $token, string $message, string $this->cancelOrder($order, $message); $this->log->logInfo('Orden cancelada => Token: ' . $token); - $this->processQuoteForCancelOrder($order); + $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); } return $this->redirectWithErrorMessage($message); @@ -361,27 +356,6 @@ private function cancelOrder(Order $order, string $message) $order->save(); } - public function processQuoteForCancelOrder(Order $order) - { - $quote = $this->quoteFactory->create()->load($order->getQuoteId()); - if ($quote->getId()) { - $quote->setIsActive(false); - $quote->setReservedOrderId(null); - $quote->save(); - - $newQuote = $this->quoteFactory->create(); - $newQuote->merge($quote) - ->setIsActive(true) - ->setStoreId($quote->getStoreId()) - ->setCustomer($quote->getCustomer()) - ->save(); - - $this->checkoutSession->replaceQuote($newQuote); - $this->cart->setQuote($newQuote); - $this->cart->saveQuote(); - } - } - private function checkTransactionIsAlreadyProcessed($token): bool { $webpayOrderData = $this->getWebpayOrderData($token); From 018d15148e4be3720e4a085547286c81f7971fec Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 8 Jul 2024 14:24:01 -0400 Subject: [PATCH 103/159] fix: use rejected message --- Controller/Transaction/AuthorizeOneclick.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index e57f832..f2595d2 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -196,7 +196,7 @@ public function execute() $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); - $message = TbkResponseHelper::getRejectMessage($response, "Oneclick Mall"); + $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; $this->messageManager->addErrorMessage(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); From 78545c0e9d7705ad357a64583ac11099dc426d0e Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 8 Jul 2024 14:32:29 -0400 Subject: [PATCH 104/159] refactor: simplify restore quote process --- Controller/Transaction/CreateWebpay.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Controller/Transaction/CreateWebpay.php b/Controller/Transaction/CreateWebpay.php index 783bbbc..a47c9b4 100644 --- a/Controller/Transaction/CreateWebpay.php +++ b/Controller/Transaction/CreateWebpay.php @@ -78,11 +78,8 @@ public function execute() $tmpOrder = $this->getOrder(); + $this->checkoutSession->restoreQuote(); $quote = $this->checkoutSession->getQuote(); - if (!$quote->getId()) { - $this->checkoutSession->restoreQuote(); - $quote = $this->checkoutSession->getQuote(); - } if ($guestEmail != null) { $this->setQuoteData($quote, $guestEmail); From 492fa39420cc67fcefa1ba4acfadf04fed43a561 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 8 Jul 2024 15:59:37 -0400 Subject: [PATCH 105/159] feat: process quote in exception flow --- Controller/Transaction/CommitWebpay.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 87bee62..c878e02 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -290,6 +290,11 @@ private function handleException(Exception $exception) $this->log->logError($exception->getMessage()); $this->log->logError($exception->getTraceAsString()); + $order = $this->checkoutSession->getLastRealOrder(); + if($order->getId()) { + $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); + } + return $this->redirectWithErrorMessage($message); } From d6e763092aea452bfe291aa34bc727aba5158eae Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 8 Jul 2024 16:00:08 -0400 Subject: [PATCH 106/159] style: format file --- Controller/Transaction/CommitWebpay.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index c878e02..fc1c14e 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -291,7 +291,7 @@ private function handleException(Exception $exception) $this->log->logError($exception->getTraceAsString()); $order = $this->checkoutSession->getLastRealOrder(); - if($order->getId()) { + if ($order->getId()) { $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); } From d9cff77e361d878fc988a821c05722c7a3f938eb Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Mon, 8 Jul 2024 16:39:08 -0400 Subject: [PATCH 107/159] refactor: remove unused import --- Helper/QuoteHelper.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Helper/QuoteHelper.php b/Helper/QuoteHelper.php index 661daf2..7ed4d8e 100644 --- a/Helper/QuoteHelper.php +++ b/Helper/QuoteHelper.php @@ -3,7 +3,6 @@ namespace Transbank\Webpay\Helper; use Magento\Checkout\Model\Cart; -use Magento\Sales\Model\Order; use Magento\Checkout\Model\Session; use Magento\Quote\Model\QuoteFactory; From 8ae49c07680e8f8daea9a19b632f454870aa0e35 Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Thu, 4 Jul 2024 09:57:07 -0400 Subject: [PATCH 108/159] refactor: add validation to ensure that no double authorization happens on oneclick --- Controller/Transaction/AuthorizeOneclick.php | 36 +++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 24bd475..4d89e0f 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -96,6 +96,8 @@ public function execute() $orderStatusCanceled = $this->configProvider->getOneclickOrderErrorStatus(); $orderStatusSuccess = $this->configProvider->getOneclickOrderSuccessStatus(); $oneclickTitle = $this->configProvider->getOneclickTitle(); + $cookieName = 'AUTHORIZE_TRANSACTION-BUY-ORDER:'; + $cookieIdForBuyOrder = ""; try { $resultJson = $this->resultJsonFactory->create(); @@ -113,14 +115,37 @@ public function execute() $this->checkoutSession->restoreQuote(); $quote = $this->cart->getQuote(); - - $quote->getPayment()->importData(['method' => Oneclick::CODE]); - $quote->collectTotals(); $order = $this->getOrder(); - $grandTotal = round($order->getGrandTotal()); $quoteId = $quote->getId(); $orderId = $order->getId(); + $orderStatus = $order->getStatus(); + + if ($orderStatus == $orderStatusCanceled) { + $this->log->logInfo('Cancelando flujo ya que la transaccion ya esta cancelada'); + $this->messageManager->addErrorMessage(__('Error al autorizar la transacción')); + return $resultJson->setData(['status' => 'error', 'message' => 'Esta transacción ha sido cancelada', 'flag' => 0]); + } + + if ($orderStatus == $orderStatusSuccess) { + $this->log->logInfo('Cancelando flujo ya que la transaccion ya esta autorizada'); + $this->messageManager->addErrorMessage(__('Error al autorizar la transacción')); + return $resultJson->setData(['status' => 'error', 'message' => 'Esta transacción ya ha sido autorizada', 'flag' => 0]); + } + + $cookieIdForBuyOrder = $cookieName . $orderId; + + if (isset($_COOKIE[$cookieIdForBuyOrder])) { + $this->log->logInfo('Cancelando flujo ya que la transaccion ya esta en proceso'); + $this->messageManager->addErrorMessage(__('Error al autorizar la transacción')); + return $resultJson->setData(['status' => 'error', 'message' => 'Error autorizando transacción', 'flag' => 0]); + } + + setcookie($cookieIdForBuyOrder, 'true', time() + 100, '/'); + + $quote->getPayment()->importData(['method' => Oneclick::CODE]); + $quote->collectTotals(); + $grandTotal = round($order->getGrandTotal()); $quote->save(); @@ -207,11 +232,14 @@ public function execute() $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; $this->messageManager->addErrorMessage(__($message)); + setcookie($cookieIdForBuyOrder, '', time() - 1000, '/'); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } } catch (\Exception $e) { $message = 'Error al crear transacción: ' . $e->getMessage(); + setcookie($cookieIdForBuyOrder, '', time() - 1000, '/'); + $this->log->logError($message); $response = ['error' => $message]; From faa4ee6927e44947945941cdb44991f856a3a208 Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Mon, 8 Jul 2024 10:00:01 -0400 Subject: [PATCH 109/159] refactor: add flag httpOnly to setcookie --- Controller/Transaction/AuthorizeOneclick.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 4d89e0f..5495d65 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -141,7 +141,7 @@ public function execute() return $resultJson->setData(['status' => 'error', 'message' => 'Error autorizando transacción', 'flag' => 0]); } - setcookie($cookieIdForBuyOrder, 'true', time() + 100, '/'); + setcookie($cookieIdForBuyOrder, 'true', time() + 100, '/', '', true, true); $quote->getPayment()->importData(['method' => Oneclick::CODE]); $quote->collectTotals(); @@ -232,13 +232,13 @@ public function execute() $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; $this->messageManager->addErrorMessage(__($message)); - setcookie($cookieIdForBuyOrder, '', time() - 1000, '/'); + setcookie($cookieIdForBuyOrder, '', time() - 1000, '/', true, true); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } } catch (\Exception $e) { $message = 'Error al crear transacción: ' . $e->getMessage(); - setcookie($cookieIdForBuyOrder, '', time() - 1000, '/'); + setcookie($cookieIdForBuyOrder, '', time() - 1000, '/', true, true); $this->log->logError($message); $response = ['error' => $message]; From 59c22ca33e48ffe511cf26c4789a033b63cad6cc Mon Sep 17 00:00:00 2001 From: Carlos Tribiec Date: Mon, 8 Jul 2024 10:17:53 -0400 Subject: [PATCH 110/159] refactor: add missing flag to setcookie --- Controller/Transaction/AuthorizeOneclick.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 5495d65..d87d254 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -232,13 +232,13 @@ public function execute() $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; $this->messageManager->addErrorMessage(__($message)); - setcookie($cookieIdForBuyOrder, '', time() - 1000, '/', true, true); + setcookie($cookieIdForBuyOrder, '', time() - 1000, '/', true, true, true); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } } catch (\Exception $e) { $message = 'Error al crear transacción: ' . $e->getMessage(); - setcookie($cookieIdForBuyOrder, '', time() - 1000, '/', true, true); + setcookie($cookieIdForBuyOrder, '', time() - 1000, '/', true, true, true); $this->log->logError($message); $response = ['error' => $message]; From 89815a7a4b0712c49c131a94563dc65e97c79260 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 18 Jul 2024 16:57:19 -0400 Subject: [PATCH 111/159] feat: remove use of cookies to manage status --- Controller/Transaction/AuthorizeOneclick.php | 36 +++----------------- 1 file changed, 4 insertions(+), 32 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index d87d254..24bd475 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -96,8 +96,6 @@ public function execute() $orderStatusCanceled = $this->configProvider->getOneclickOrderErrorStatus(); $orderStatusSuccess = $this->configProvider->getOneclickOrderSuccessStatus(); $oneclickTitle = $this->configProvider->getOneclickTitle(); - $cookieName = 'AUTHORIZE_TRANSACTION-BUY-ORDER:'; - $cookieIdForBuyOrder = ""; try { $resultJson = $this->resultJsonFactory->create(); @@ -115,38 +113,15 @@ public function execute() $this->checkoutSession->restoreQuote(); $quote = $this->cart->getQuote(); - $order = $this->getOrder(); - - $quoteId = $quote->getId(); - $orderId = $order->getId(); - $orderStatus = $order->getStatus(); - - if ($orderStatus == $orderStatusCanceled) { - $this->log->logInfo('Cancelando flujo ya que la transaccion ya esta cancelada'); - $this->messageManager->addErrorMessage(__('Error al autorizar la transacción')); - return $resultJson->setData(['status' => 'error', 'message' => 'Esta transacción ha sido cancelada', 'flag' => 0]); - } - - if ($orderStatus == $orderStatusSuccess) { - $this->log->logInfo('Cancelando flujo ya que la transaccion ya esta autorizada'); - $this->messageManager->addErrorMessage(__('Error al autorizar la transacción')); - return $resultJson->setData(['status' => 'error', 'message' => 'Esta transacción ya ha sido autorizada', 'flag' => 0]); - } - - $cookieIdForBuyOrder = $cookieName . $orderId; - - if (isset($_COOKIE[$cookieIdForBuyOrder])) { - $this->log->logInfo('Cancelando flujo ya que la transaccion ya esta en proceso'); - $this->messageManager->addErrorMessage(__('Error al autorizar la transacción')); - return $resultJson->setData(['status' => 'error', 'message' => 'Error autorizando transacción', 'flag' => 0]); - } - - setcookie($cookieIdForBuyOrder, 'true', time() + 100, '/', '', true, true); $quote->getPayment()->importData(['method' => Oneclick::CODE]); $quote->collectTotals(); + $order = $this->getOrder(); $grandTotal = round($order->getGrandTotal()); + $quoteId = $quote->getId(); + $orderId = $order->getId(); + $quote->save(); $transbankSdkWebpay = new TransbankSdkWebpayRest($this->oneclickConfig); @@ -232,14 +207,11 @@ public function execute() $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; $this->messageManager->addErrorMessage(__($message)); - setcookie($cookieIdForBuyOrder, '', time() - 1000, '/', true, true, true); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } } catch (\Exception $e) { $message = 'Error al crear transacción: ' . $e->getMessage(); - setcookie($cookieIdForBuyOrder, '', time() - 1000, '/', true, true, true); - $this->log->logError($message); $response = ['error' => $message]; From afeff5bb06fa4e6c793dbfe20cb3060ab3df4b6c Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 17 Jul 2024 13:13:44 -0400 Subject: [PATCH 112/159] fix: add missing import --- Controller/Transaction/AuthorizeOneclick.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 24bd475..28390d3 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -23,6 +23,7 @@ use Magento\Framework\View\Result\PageFactory; use Transbank\Webpay\Helper\QuoteHelper; use Transbank\Webpay\Model\OneclickInscriptionDataFactory; +use Magento\Framework\Event\ManagerInterface as EventManagerInterface; /** From f2aeb41ae7bea287b338f5d5059ae030544304d6 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 17 Jul 2024 14:01:25 -0400 Subject: [PATCH 113/159] refactor: add cancel order method --- Controller/Transaction/AuthorizeOneclick.php | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 28390d3..544a0b4 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -94,7 +94,6 @@ public function __construct( public function execute() { $response = null; - $orderStatusCanceled = $this->configProvider->getOneclickOrderErrorStatus(); $orderStatusSuccess = $this->configProvider->getOneclickOrderSuccessStatus(); $oneclickTitle = $this->configProvider->getOneclickTitle(); @@ -196,13 +195,9 @@ public function execute() $quoteId, ); - $order->setStatus($orderStatusCanceled); $message = '

Error en autorización con Oneclick Mall


' . json_encode($response); - $order->addStatusToHistory($order->getStatus(), $message); - $order->cancel(); - $order->save(); - + $this->cancelOrder($order, $message); $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; @@ -217,10 +212,7 @@ public function execute() $response = ['error' => $message]; if ($order != null) { - $order->cancel(); - $order->setStatus($orderStatusCanceled); - $order->addStatusToHistory($order->getStatus(), $message); - $order->save(); + $this->cancelOrder($order, $message); $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); } @@ -228,6 +220,14 @@ public function execute() return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } } + private function cancelOrder(Order $order, string $message) + { + $orderStatusCanceled = $this->configProvider->getOneclickOrderErrorStatus(); + $order->cancel(); + $order->setStatus($orderStatusCanceled); + $order->addStatusToHistory($order->getStatus(), $message); + $order->save(); + } /** * @return |null From 173efb180f122c8c6f3a90cdf041201ed2c3ab61 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 17 Jul 2024 14:03:41 -0400 Subject: [PATCH 114/159] refactor: add method redirectWithErrorMessage --- Controller/Transaction/AuthorizeOneclick.php | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 544a0b4..bfca606 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -201,9 +201,7 @@ public function execute() $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; - $this->messageManager->addErrorMessage(__($message)); - - return $this->resultRedirectFactory->create()->setPath('checkout/cart'); + return $this->redirectWithErrorMessage($message); } } catch (\Exception $e) { $message = 'Error al crear transacción: ' . $e->getMessage(); @@ -216,10 +214,15 @@ public function execute() $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); } - $this->messageManager->addErrorMessage($e->getMessage()); - return $this->resultRedirectFactory->create()->setPath('checkout/cart'); + return $this->redirectWithErrorMessage($e->getMessage()); } } + private function redirectWithErrorMessage(string $message) + { + $this->messageManager->addErrorMessage(__($message)); + return $this->resultRedirectFactory->create()->setPath('checkout/cart'); + } + private function cancelOrder(Order $order, string $message) { $orderStatusCanceled = $this->configProvider->getOneclickOrderErrorStatus(); From d2ad3e6213ed7f70df99d1c6c29a0522312f66e7 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 17 Jul 2024 14:09:55 -0400 Subject: [PATCH 115/159] refactor: add method handleException --- Controller/Transaction/AuthorizeOneclick.php | 30 +++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index bfca606..2e6e78c 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -1,7 +1,7 @@ redirectWithErrorMessage($message); } - } catch (\Exception $e) { - $message = 'Error al crear transacción: ' . $e->getMessage(); + } catch (Exception $e) { + return $this->handleException($e); + } + } - $this->log->logError($message); - $response = ['error' => $message]; + private function handleException(Exception $exception) + { + $message = self::ONECLICK_EXCEPTION_FLOW_MESSAGE; - if ($order != null) { - $this->cancelOrder($order, $message); - $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); - } + $this->log->logError('Error al procesar el pago: '); + $this->log->logError($exception->getMessage()); + $this->log->logError($exception->getTraceAsString()); + + $order = $this->checkoutSession->getLastRealOrder(); - return $this->redirectWithErrorMessage($e->getMessage()); + if ($order->getId()) { + $this->cancelOrder($order, $message); + $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); } + + return $this->redirectWithErrorMessage($message); } + private function redirectWithErrorMessage(string $message) { $this->messageManager->addErrorMessage(__($message)); From 02fcd4f641fbce2abc3250ee9d4d4e4de820d1e9 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 17 Jul 2024 14:14:22 -0400 Subject: [PATCH 116/159] refactor: rename method saveWebpayData to saveOneclickData --- Controller/Transaction/AuthorizeOneclick.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 2e6e78c..f97f080 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -1,6 +1,7 @@ details) && $response->details[0]->responseCode == 0) { - $webpayOrderData = $this->saveWebpayData( + $webpayOrderData = $this->saveOneclickData( $response, $grandTotal, OneclickInscriptionData::PAYMENT_STATUS_SUCCESS, @@ -188,7 +189,7 @@ public function execute() $block->setResponse($formattedResponse); return $resultPage; } else { - $webpayOrderData = $this->saveWebpayData( + $webpayOrderData = $this->saveOneclickData( $response, $grandTotal, OneclickInscriptionData::PAYMENT_STATUS_FAILED, @@ -294,7 +295,7 @@ protected function getOrderId() * * @return WebpayOrderData */ - protected function saveWebpayData($authorizeResponse, $amount, $payment_status, $order_id, $quote_id) + protected function saveOneclickData($authorizeResponse, $amount, $payment_status, $order_id, $quote_id) { $webpayOrderData = $this->webpayOrderDataFactory->create(); $webpayOrderData->setData([ From be4ed9b1a6ecad750801bf44125d85eaa2843e0c Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 18 Jul 2024 12:58:26 -0400 Subject: [PATCH 117/159] refactor: add method handleUnauthorizedTransaction --- Controller/Transaction/AuthorizeOneclick.php | 41 ++++++++++++-------- Model/TransbankSdkWebpayRest.php | 3 +- 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index f97f080..0ba6803 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -3,6 +3,7 @@ namespace Transbank\Webpay\Controller\Transaction; use Exception; +use Magento\Sales\Model\Order; use Magento\Checkout\Model\Cart; use Magento\Checkout\Model\Session; use Transbank\Webpay\Model\Oneclick; @@ -25,7 +26,7 @@ use Transbank\Webpay\Helper\QuoteHelper; use Transbank\Webpay\Model\OneclickInscriptionDataFactory; use Magento\Framework\Event\ManagerInterface as EventManagerInterface; - +use Transbank\Webpay\Oneclick\Responses\MallTransactionAuthorizeResponse; /** * Controller for create Oneclick Inscription. @@ -189,27 +190,35 @@ public function execute() $block->setResponse($formattedResponse); return $resultPage; } else { - $webpayOrderData = $this->saveOneclickData( - $response, - $grandTotal, - OneclickInscriptionData::PAYMENT_STATUS_FAILED, - $orderId, - $quoteId, - ); - - $message = '

Error en autorización con Oneclick Mall


' . json_encode($response); - - $this->cancelOrder($order, $message); - $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); - - $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; - return $this->redirectWithErrorMessage($message); + return $this->handleUnauthorizedTransaction($order, $response, $grandTotal); } } catch (Exception $e) { return $this->handleException($e); } } + private function handleUnauthorizedTransaction( + Order $order, + MallTransactionAuthorizeResponse $authorizeResponse, + float $totalAmount + ) { + $this->saveOneclickData( + $authorizeResponse, + $totalAmount, + OneclickInscriptionData::PAYMENT_STATUS_FAILED, + $order->getId(), + $order->getQuoteId(), + ); + + $message = '

Error en autorización con Oneclick Mall


' . json_encode($authorizeResponse); + + $this->cancelOrder($order, $message); + $this->quoteHelper->processQuoteForCancelOrder($order->getQuoteId()); + + $message = 'Tu transacción no pudo ser autorizada. Ningún cobro fue realizado.'; + return $this->redirectWithErrorMessage($message); + } + private function handleException(Exception $exception) { $message = self::ONECLICK_EXCEPTION_FLOW_MESSAGE; diff --git a/Model/TransbankSdkWebpayRest.php b/Model/TransbankSdkWebpayRest.php index 50a7943..5385f20 100755 --- a/Model/TransbankSdkWebpayRest.php +++ b/Model/TransbankSdkWebpayRest.php @@ -12,6 +12,7 @@ use Transbank\Webpay\Oneclick; use Transbank\Webpay\Oneclick\Exceptions\InscriptionStartException; use Transbank\Webpay\Oneclick\Exceptions\InscriptionFinishException; +use Transbank\Webpay\Oneclick\Responses\MallTransactionAuthorizeResponse; /** * Class TransbankSdkWebpayRest. @@ -213,7 +214,7 @@ public function finishInscription($tbkToken) * * @throws MissingArgumentException * - * @return array + * @return array|MallTransactionAuthorizeResponse */ public function authorizeTransaction($username, $tbkUser, $buyOrder, $details) { From c02b18a32af8b8c238f7344e696f7edd8b7eb6e0 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 18 Jul 2024 16:27:45 -0400 Subject: [PATCH 118/159] refactor: add method redirectToSuccess --- Controller/Transaction/AuthorizeOneclick.php | 21 ++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 0ba6803..5266165 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -175,20 +175,14 @@ public function execute() $order->addStatusToHistory($order->getStatus(), $orderLogs); $order->save(); - $this->checkoutSession->getQuote()->setIsActive(false)->save(); - $this->eventManager->dispatch( 'checkout_onepage_controller_success_action', ['order' => $order] ); - $formattedResponse = TbkResponseHelper::getOneclickFormattedResponse($response); + $responseData = TbkResponseHelper::getOneclickFormattedResponse($response); - $resultPage = $this->resultPageFactory->create(); - $resultPage->addHandle('transbank_checkout_success'); - $block = $resultPage->getLayout()->getBlock('transbank_success'); - $block->setResponse($formattedResponse); - return $resultPage; + return $this->redirectToSuccess($responseData); } else { return $this->handleUnauthorizedTransaction($order, $response, $grandTotal); } @@ -237,6 +231,17 @@ private function handleException(Exception $exception) return $this->redirectWithErrorMessage($message); } + private function redirectToSuccess(array $responseData) + { + $this->checkoutSession->getQuote()->setIsActive(false)->save(); + + $resultPage = $this->resultPageFactory->create(); + $resultPage->addHandle('transbank_checkout_success'); + $block = $resultPage->getLayout()->getBlock('transbank_success'); + $block->setResponse($responseData); + return $resultPage; + } + private function redirectWithErrorMessage(string $message) { $this->messageManager->addErrorMessage(__($message)); From 16ec0e544e3bdcdec6669e07e01b69864c817c26 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 18 Jul 2024 16:40:34 -0400 Subject: [PATCH 119/159] refactor: add method handleAuthorizedTransaction --- Controller/Transaction/AuthorizeOneclick.php | 83 +++++++++++--------- 1 file changed, 46 insertions(+), 37 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 5266165..166149c 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -142,53 +142,62 @@ public function execute() ]; $response = $transbankSdkWebpay->authorizeTransaction($username, $tbkUser, $buyOrder, $details); - $dataLog = ['customerId' => $username, 'orderId' => $orderId]; if (isset($response->details) && $response->details[0]->responseCode == 0) { + return $this->handleAuthorizedTransaction($order, $response, $grandTotal); + } else { + return $this->handleUnauthorizedTransaction($order, $response, $grandTotal); + } + } catch (Exception $e) { + return $this->handleException($e); + } + } - $webpayOrderData = $this->saveOneclickData( - $response, - $grandTotal, - OneclickInscriptionData::PAYMENT_STATUS_SUCCESS, - $orderId, - $quoteId - ); + private function handleAuthorizedTransaction( + Order $order, + MallTransactionAuthorizeResponse $authorizeResponse, + float $totalAmount + ) { + $quoteId = $order->getQuoteId(); + + $this->saveOneclickData( + $authorizeResponse, + $totalAmount, + OneclickInscriptionData::PAYMENT_STATUS_SUCCESS, + $order->getId(), + $quoteId + ); - $this->checkoutSession->setLastQuoteId($quote->getId()); - $this->checkoutSession->setLastSuccessQuoteId($quote->getId()); - $this->checkoutSession->setLastOrderId($order->getId()); - $this->checkoutSession->setLastRealOrderId($order->getIncrementId()); - $this->checkoutSession->setLastOrderStatus($order->getStatus()); - $this->checkoutSession->setGrandTotal($grandTotal); - $this->checkoutSession->getQuote()->setIsActive(true)->save(); - $this->cart->getQuote()->setIsActive(true)->save(); + $this->checkoutSession->setLastQuoteId($quoteId); + $this->checkoutSession->setLastSuccessQuoteId($quoteId); + $this->checkoutSession->setLastOrderId($order->getId()); + $this->checkoutSession->setLastRealOrderId($order->getIncrementId()); + $this->checkoutSession->setLastOrderStatus($order->getStatus()); + $this->checkoutSession->setGrandTotal($totalAmount); + $this->checkoutSession->getQuote()->setIsActive(true)->save(); + $this->cart->getQuote()->setIsActive(true)->save(); - $orderLogs = '

Pago autorizado exitosamente con ' . $oneclickTitle . '


' . json_encode($dataLog); - $payment = $order->getPayment(); + $orderLogs = '

Pago autorizado exitosamente con Oneclick Mall


' . json_encode($authorizeResponse); + $payment = $order->getPayment(); - $payment->setLastTransId($response->details[0]->authorizationCode); - $payment->setTransactionId($response->details[0]->authorizationCode); - $payment->setAdditionalInformation([Transaction::RAW_DETAILS => (array) $response->details[0]]); + $payment->setLastTransId($authorizeResponse->details[0]->authorizationCode); + $payment->setTransactionId($authorizeResponse->details[0]->authorizationCode); + $payment->setAdditionalInformation([Transaction::RAW_DETAILS => (array) $authorizeResponse->details[0]]); - $order->setState($orderStatusSuccess)->setStatus($orderStatusSuccess); - $order->addStatusToHistory($order->getStatus(), $orderLogs); - $order->save(); + $orderStatusSuccess = $this->configProvider->getOneclickOrderSuccessStatus(); + $order->setState($orderStatusSuccess)->setStatus($orderStatusSuccess); + $order->addStatusToHistory($order->getStatus(), $orderLogs); + $order->save(); - $this->eventManager->dispatch( - 'checkout_onepage_controller_success_action', - ['order' => $order] - ); + $this->eventManager->dispatch( + 'checkout_onepage_controller_success_action', + ['order' => $order] + ); - $responseData = TbkResponseHelper::getOneclickFormattedResponse($response); + $responseData = TbkResponseHelper::getOneclickFormattedResponse($authorizeResponse); - return $this->redirectToSuccess($responseData); - } else { - return $this->handleUnauthorizedTransaction($order, $response, $grandTotal); - } - } catch (Exception $e) { - return $this->handleException($e); - } + return $this->redirectToSuccess($responseData); } private function handleUnauthorizedTransaction( @@ -201,7 +210,7 @@ private function handleUnauthorizedTransaction( $totalAmount, OneclickInscriptionData::PAYMENT_STATUS_FAILED, $order->getId(), - $order->getQuoteId(), + $order->getQuoteId() ); $message = '

Error en autorización con Oneclick Mall


' . json_encode($authorizeResponse); From 738d898bce1963a7340cae7539881fdf7ad8cc73 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 18 Jul 2024 16:47:59 -0400 Subject: [PATCH 120/159] refactor: add handleOneclickRequest --- Controller/Transaction/AuthorizeOneclick.php | 83 ++++++++++---------- 1 file changed, 40 insertions(+), 43 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 166149c..acd5daa 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -96,10 +96,6 @@ public function __construct( */ public function execute() { - $response = null; - $orderStatusSuccess = $this->configProvider->getOneclickOrderSuccessStatus(); - $oneclickTitle = $this->configProvider->getOneclickTitle(); - try { $resultJson = $this->resultJsonFactory->create(); @@ -109,50 +105,51 @@ public function execute() return $resultJson->setData(['status' => 'error', 'message' => 'Error autorizando transacción', 'flag' => 0]); } - $inscription = $this->getOneclickInscriptionData($inscriptionId); - $username = $inscription->getUsername(); - $tbkUser = $inscription->getTbkUser(); - - $this->checkoutSession->restoreQuote(); - - $quote = $this->cart->getQuote(); - - $quote->getPayment()->importData(['method' => Oneclick::CODE]); - $quote->collectTotals(); - $order = $this->getOrder(); - $grandTotal = round($order->getGrandTotal()); - - $quoteId = $quote->getId(); - $orderId = $order->getId(); - - $quote->save(); - - $transbankSdkWebpay = new TransbankSdkWebpayRest($this->oneclickConfig); - - $buyOrder = "100000" . $orderId; - $childBuyOrder = "200000" . $orderId; - - $details = [ - [ - "commerce_code" => $this->oneclickConfig['CHILD_COMMERCE_CODE'], - "buy_order" => $childBuyOrder, - "amount" => $grandTotal, - "installments_number" => 1 - ] - ]; - - $response = $transbankSdkWebpay->authorizeTransaction($username, $tbkUser, $buyOrder, $details); - - if (isset($response->details) && $response->details[0]->responseCode == 0) { - return $this->handleAuthorizedTransaction($order, $response, $grandTotal); - } else { - return $this->handleUnauthorizedTransaction($order, $response, $grandTotal); - } + return $this->handleOneclickRequest($inscriptionId); } catch (Exception $e) { return $this->handleException($e); } } + private function handleOneclickRequest(int $inscriptionId) + { + $inscription = $this->getOneclickInscriptionData($inscriptionId); + $username = $inscription->getUsername(); + $tbkUser = $inscription->getTbkUser(); + + $this->checkoutSession->restoreQuote(); + $quote = $this->cart->getQuote(); + $quote->getPayment()->importData(['method' => Oneclick::CODE]); + $quote->collectTotals(); + $quote->save(); + + $order = $this->getOrder(); + $orderId = $order->getId(); + $grandTotal = round($order->getGrandTotal()); + + $transbankSdkWebpay = new TransbankSdkWebpayRest($this->oneclickConfig); + + $buyOrder = "100000" . $orderId; + $childBuyOrder = "200000" . $orderId; + + $details = [ + [ + "commerce_code" => $this->oneclickConfig['CHILD_COMMERCE_CODE'], + "buy_order" => $childBuyOrder, + "amount" => $grandTotal, + "installments_number" => 1 + ] + ]; + + $authorizeResponse = $transbankSdkWebpay->authorizeTransaction($username, $tbkUser, $buyOrder, $details); + + if (isset($authorizeResponse->details) && $authorizeResponse->details[0]->responseCode == 0) { + return $this->handleAuthorizedTransaction($order, $authorizeResponse, $grandTotal); + } else { + return $this->handleUnauthorizedTransaction($order, $authorizeResponse, $grandTotal); + } + } + private function handleAuthorizedTransaction( Order $order, MallTransactionAuthorizeResponse $authorizeResponse, From 3d7db9758f5a67a10887cbab56a7ca82e8ec96f3 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 18 Jul 2024 16:49:24 -0400 Subject: [PATCH 121/159] feat: add InvalidRequestException --- Exceptions/InvalidRequestException.php | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Exceptions/InvalidRequestException.php diff --git a/Exceptions/InvalidRequestException.php b/Exceptions/InvalidRequestException.php new file mode 100644 index 0000000..5b195cc --- /dev/null +++ b/Exceptions/InvalidRequestException.php @@ -0,0 +1,8 @@ + Date: Thu, 18 Jul 2024 16:50:20 -0400 Subject: [PATCH 122/159] feat: implement InvalidRequestException --- Controller/Transaction/AuthorizeOneclick.php | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index acd5daa..4001b30 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -27,6 +27,7 @@ use Transbank\Webpay\Model\OneclickInscriptionDataFactory; use Magento\Framework\Event\ManagerInterface as EventManagerInterface; use Transbank\Webpay\Oneclick\Responses\MallTransactionAuthorizeResponse; +use Transbank\Webpay\Exceptions\InvalidRequestException; /** * Controller for create Oneclick Inscription. @@ -97,14 +98,19 @@ public function __construct( public function execute() { try { - $resultJson = $this->resultJsonFactory->create(); - - if (isset($_POST['inscription'])) { - $inscriptionId = intval($_POST['inscription']); - } else { - return $resultJson->setData(['status' => 'error', 'message' => 'Error autorizando transacción', 'flag' => 0]); + if (!isset($_POST['inscription'])) { + throw new InvalidRequestException('Petición invalida: Falta el campo inscription'); } + $requestMethod = $_SERVER['REQUEST_METHOD']; + $request = $requestMethod === 'POST' ? $_POST : $_GET; + + $inscriptionId = intval($request['inscription']); + + $this->log->logInfo('Autorizando transacción Oneclick.'); + $this->log->logInfo('Request: method -> ' . $requestMethod); + $this->log->logInfo('Request: payload -> ' . json_encode($request)); + return $this->handleOneclickRequest($inscriptionId); } catch (Exception $e) { return $this->handleException($e); From 2c0077cf2aeeeb08d656030b09cee28e99775764 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Fri, 19 Jul 2024 13:20:07 -0400 Subject: [PATCH 123/159] refactor: remove unused method getOrderId --- Controller/Transaction/AuthorizeOneclick.php | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 4001b30..5603c62 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -301,14 +301,6 @@ protected function getOneclickInscriptionData($inscriptionId): OneclickInscripti return $oneclickInscriptionDataModel->load($inscriptionId, 'id'); } - /** - * @return string - */ - protected function getOrderId() - { - return $this->checkoutSession->getLastRealOrderId(); - } - /** * @param $buyOrder * @param $childBuyOrder From 9868b098cbd9d2ea6f63f3eb7c91ea382a3a3673 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Fri, 19 Jul 2024 13:22:22 -0400 Subject: [PATCH 124/159] refactor: improve getOrder method logic --- Controller/Transaction/AuthorizeOneclick.php | 24 ++++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 5603c62..b81bae5 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -9,9 +9,9 @@ use Transbank\Webpay\Model\Oneclick; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; -use Magento\Framework\App\ObjectManager; use Transbank\Webpay\Helper\PluginLogger; use Transbank\Webpay\Helper\TbkResponseHelper; +use Transbank\Webpay\Helper\ObjectManagerHelper; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Controller\Result\Json; use Transbank\Webpay\Model\Config\ConfigProvider; @@ -129,7 +129,7 @@ private function handleOneclickRequest(int $inscriptionId) $quote->collectTotals(); $quote->save(); - $order = $this->getOrder(); + $order = $this->getOrder($this->checkoutSession->getLastOrderId()); $orderId = $order->getId(); $grandTotal = round($order->getGrandTotal()); @@ -270,22 +270,16 @@ private function cancelOrder(Order $order, string $message) } /** - * @return |null + * @return Order */ - private function getOrder() + private function getOrder($orderId): Order { - try { - $orderId = $this->checkoutSession->getLastOrderId(); - if ($orderId == null) { - return null; - } + /** + * @var Order + */ + $order = ObjectManagerHelper::get(Order::class); - $objectManager = ObjectManager::getInstance(); - - return $objectManager->create('\Magento\Sales\Model\Order')->load($orderId); - } catch (\Exception $e) { - return null; - } + return $order->load($orderId); } /** From 590f88bf81237c9e8c5e9f061eef6c8ced6a8176 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Sat, 20 Jul 2024 00:06:29 -0400 Subject: [PATCH 125/159] feat: create factory repository for WebpayOrderData --- .../WebpayOrderData/Collection.php | 25 ++++++++++ .../WebpayOrderData/CollectionFactory.php | 20 ++++++++ Model/WebpayOrderDataFactory.php | 36 ++++++++++++++ Model/WebpayOrderDataRepository.php | 47 +++++++++++++++++++ etc/frontend/di.xml | 12 ++++- 5 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 Model/ResourceModel/WebpayOrderData/Collection.php create mode 100644 Model/ResourceModel/WebpayOrderData/CollectionFactory.php create mode 100644 Model/WebpayOrderDataFactory.php create mode 100644 Model/WebpayOrderDataRepository.php diff --git a/Model/ResourceModel/WebpayOrderData/Collection.php b/Model/ResourceModel/WebpayOrderData/Collection.php new file mode 100644 index 0000000..f16f64a --- /dev/null +++ b/Model/ResourceModel/WebpayOrderData/Collection.php @@ -0,0 +1,25 @@ +_init( + 'Transbank\Webpay\Model\WebpayOrderData', + 'Transbank\Webpay\Model\ResourceModel\WebpayOrderData' + ); + } +} diff --git a/Model/ResourceModel/WebpayOrderData/CollectionFactory.php b/Model/ResourceModel/WebpayOrderData/CollectionFactory.php new file mode 100644 index 0000000..d68fca3 --- /dev/null +++ b/Model/ResourceModel/WebpayOrderData/CollectionFactory.php @@ -0,0 +1,20 @@ +objectManager = $objectManager; + } + + public function create(array $data = []) + { + return $this->objectManager->create(Collection::class, $data); + } +} diff --git a/Model/WebpayOrderDataFactory.php b/Model/WebpayOrderDataFactory.php new file mode 100644 index 0000000..64b8abf --- /dev/null +++ b/Model/WebpayOrderDataFactory.php @@ -0,0 +1,36 @@ +objectManager = $objectManager; + } + + /** + * Create a new instance of WebpayOrderData + * + * @param array $data Data to initialize the model + * + * @return WebpayOrderData + */ + public function create(array $data = []) + { + return $this->objectManager->create(WebpayOrderData::class, $data); + } +} diff --git a/Model/WebpayOrderDataRepository.php b/Model/WebpayOrderDataRepository.php new file mode 100644 index 0000000..0260678 --- /dev/null +++ b/Model/WebpayOrderDataRepository.php @@ -0,0 +1,47 @@ +webpayOrderDataFactory = $webpayOrderDataFactory; + $this->collectionFactory = $collectionFactory; + } + + /** + * Get WebpayOrderData by order ID and quote ID + * + * @param string $orderId The order ID + * @param string $quoteId The quote ID + * + * @return WebpayOrderData + */ + public function getByOrderIdAndQuoteId($orderId, $quoteId) + { + $collection = $this->collectionFactory->create(); + $collection->addFieldToFilter('order_id', $orderId) + ->addFieldToFilter('quote_id', $quoteId); + + return $collection->getFirstItem(); + } +} diff --git a/etc/frontend/di.xml b/etc/frontend/di.xml index 1ac528d..a33d0a8 100644 --- a/etc/frontend/di.xml +++ b/etc/frontend/di.xml @@ -20,4 +20,14 @@ - \ No newline at end of file + + + Magento\Framework\ObjectManagerInterface + + + + + Magento\Framework\ObjectManagerInterface + + + From 4c694446be2f085927cc363e39721749492678fe Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Sat, 20 Jul 2024 00:07:05 -0400 Subject: [PATCH 126/159] feat: add refund status constants to model WebpayOrderData --- Model/WebpayOrderData.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Model/WebpayOrderData.php b/Model/WebpayOrderData.php index 8647c20..99e8d72 100644 --- a/Model/WebpayOrderData.php +++ b/Model/WebpayOrderData.php @@ -13,6 +13,8 @@ class WebpayOrderData extends AbstractModel implements \Magento\Framework\DataOb const PAYMENT_STATUS_CANCELED_BY_USER = 'CANCELED_BY_USER'; const PAYMENT_STATUS_ERROR = 'ERROR'; const PAYMENT_STATUS_TIMEOUT = 'TIMEOUT'; + const PAYMENT_STATUS_NULLIFIED = 'NULLIFIED'; + const PAYMENT_STATUS_REVERSED = 'REVERSED'; /** * @return void From 345bbc040b72190a36836f2ee59a4bbe2997b7f1 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Sat, 20 Jul 2024 00:09:14 -0400 Subject: [PATCH 127/159] refactor: use import for IdentityInterface --- Model/WebpayOrderData.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Model/WebpayOrderData.php b/Model/WebpayOrderData.php index 99e8d72..6eb5d4d 100644 --- a/Model/WebpayOrderData.php +++ b/Model/WebpayOrderData.php @@ -3,8 +3,9 @@ namespace Transbank\Webpay\Model; use Magento\Framework\Model\AbstractModel; +use Magento\Framework\DataObject\IdentityInterface; -class WebpayOrderData extends AbstractModel implements \Magento\Framework\DataObject\IdentityInterface +class WebpayOrderData extends AbstractModel implements IdentityInterface { const CACHE_TAG = 'webpay_order_data'; const PAYMENT_STATUS_WATING = 'WAITING'; From fede480eb617468280f43b07d2e51791d988001a Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Sat, 20 Jul 2024 00:11:00 -0400 Subject: [PATCH 128/159] feat: check if transaction is already processed --- Controller/Transaction/AuthorizeOneclick.php | 45 ++++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index b81bae5..16a7e58 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -19,6 +19,7 @@ use Magento\Framework\Controller\ResultInterface; use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderDataFactory; +use Transbank\Webpay\Model\WebpayOrderDataRepository; use Magento\Sales\Model\Order\Payment\Transaction; use Transbank\Webpay\Model\OneclickInscriptionData; use Magento\Framework\Controller\Result\JsonFactory; @@ -28,6 +29,7 @@ use Magento\Framework\Event\ManagerInterface as EventManagerInterface; use Transbank\Webpay\Oneclick\Responses\MallTransactionAuthorizeResponse; use Transbank\Webpay\Exceptions\InvalidRequestException; +use Transbank\Webpay\Model\WebpayOrderData; /** * Controller for create Oneclick Inscription. @@ -43,6 +45,7 @@ class AuthorizeOneclick extends Action private $oneclickInscriptionDataFactory; private $log; private $webpayOrderDataFactory; + protected $webpayOrderDataRepository; private $resultPageFactory; protected $eventManager; protected $messageManager; @@ -71,6 +74,7 @@ public function __construct( EventManagerInterface $eventManager, OneclickInscriptionDataFactory $oneclickInscriptionDataFactory, WebpayOrderDataFactory $webpayOrderDataFactory, + WebpayOrderDataRepository $webpayOrderDataRepository, ManagerInterface $messageManager, QuoteHelper $quoteHelper ) { @@ -83,6 +87,7 @@ public function __construct( $this->messageManager = $messageManager; $this->oneclickInscriptionDataFactory = $oneclickInscriptionDataFactory; $this->webpayOrderDataFactory = $webpayOrderDataFactory; + $this->webpayOrderDataRepository = $webpayOrderDataRepository; $this->resultPageFactory = $resultPageFactory; $this->eventManager = $eventManager; $this->log = new PluginLogger(); @@ -133,6 +138,10 @@ private function handleOneclickRequest(int $inscriptionId) $orderId = $order->getId(); $grandTotal = round($order->getGrandTotal()); + if ($this->checkTransactionIsAlreadyProcessed($orderId, $quote->getId())) { + return $this->handleTransactionAlreadyProcessed($orderId, $quote->getId()); + } + $transbankSdkWebpay = new TransbankSdkWebpayRest($this->oneclickConfig); $buyOrder = "100000" . $orderId; @@ -171,7 +180,6 @@ private function handleAuthorizedTransaction( $quoteId ); - $this->checkoutSession->setLastQuoteId($quoteId); $this->checkoutSession->setLastSuccessQuoteId($quoteId); $this->checkoutSession->setLastOrderId($order->getId()); @@ -200,6 +208,8 @@ private function handleAuthorizedTransaction( $responseData = TbkResponseHelper::getOneclickFormattedResponse($authorizeResponse); + $this->checkoutSession->getQuote()->setIsActive(false)->save(); + return $this->redirectToSuccess($responseData); } @@ -225,6 +235,22 @@ private function handleUnauthorizedTransaction( return $this->redirectWithErrorMessage($message); } + private function handleTransactionAlreadyProcessed($orderId, $quoteId) + { + $webpayOrderData = $this->getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId); + $status = $webpayOrderData->getPaymentStatus(); + + if ($status == WebpayOrderData::PAYMENT_STATUS_SUCCESS) { + $metadata = $webpayOrderData->getMetadata(); + $response = json_decode($metadata); + $formattedResponse = TbkResponseHelper::getOneclickFormattedResponse($response); + + return $this->redirectToSuccess($formattedResponse); + } + + return $this->redirectWithErrorMessage("La orden ya fue procesada."); + } + private function handleException(Exception $exception) { $message = self::ONECLICK_EXCEPTION_FLOW_MESSAGE; @@ -245,8 +271,6 @@ private function handleException(Exception $exception) private function redirectToSuccess(array $responseData) { - $this->checkoutSession->getQuote()->setIsActive(false)->save(); - $resultPage = $this->resultPageFactory->create(); $resultPage->addHandle('transbank_checkout_success'); $block = $resultPage->getLayout()->getBlock('transbank_success'); @@ -269,6 +293,16 @@ private function cancelOrder(Order $order, string $message) $order->save(); } + private function checkTransactionIsAlreadyProcessed($orderId, $quoteId): bool + { + $webpayOrderData = $this->getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId); + $status = $webpayOrderData->getPaymentStatus(); + + return $status == WebpayOrderData::PAYMENT_STATUS_SUCCESS || + $status == WebpayOrderData::PAYMENT_STATUS_NULLIFIED || + $status == WebpayOrderData::PAYMENT_STATUS_REVERSED; + } + /** * @return Order */ @@ -282,6 +316,11 @@ private function getOrder($orderId): Order return $order->load($orderId); } + private function getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId) + { + return $this->webpayOrderDataRepository->getByOrderIdAndQuoteId($orderId, $quoteId); + } + /** * @param $inscriptionId * From 6d551039f3a8ac546b6f351c843e49b05d139a17 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 16:02:05 -0400 Subject: [PATCH 129/159] refactor: add types for all methods --- Controller/Transaction/AuthorizeOneclick.php | 33 ++++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 16a7e58..a244f2b 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -7,6 +7,7 @@ use Magento\Checkout\Model\Cart; use Magento\Checkout\Model\Session; use Transbank\Webpay\Model\Oneclick; +use Magento\Framework\View\Result\Page; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Transbank\Webpay\Helper\PluginLogger; @@ -17,6 +18,7 @@ use Transbank\Webpay\Model\Config\ConfigProvider; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Controller\ResultInterface; +use Magento\Framework\Controller\Result\Redirect; use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderDataFactory; use Transbank\Webpay\Model\WebpayOrderDataRepository; @@ -169,7 +171,7 @@ private function handleAuthorizedTransaction( Order $order, MallTransactionAuthorizeResponse $authorizeResponse, float $totalAmount - ) { + ): Page { $quoteId = $order->getQuoteId(); $this->saveOneclickData( @@ -217,7 +219,7 @@ private function handleUnauthorizedTransaction( Order $order, MallTransactionAuthorizeResponse $authorizeResponse, float $totalAmount - ) { + ): Redirect { $this->saveOneclickData( $authorizeResponse, $totalAmount, @@ -235,7 +237,7 @@ private function handleUnauthorizedTransaction( return $this->redirectWithErrorMessage($message); } - private function handleTransactionAlreadyProcessed($orderId, $quoteId) + private function handleTransactionAlreadyProcessed(int $orderId, int $quoteId) { $webpayOrderData = $this->getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId); $status = $webpayOrderData->getPaymentStatus(); @@ -251,7 +253,7 @@ private function handleTransactionAlreadyProcessed($orderId, $quoteId) return $this->redirectWithErrorMessage("La orden ya fue procesada."); } - private function handleException(Exception $exception) + private function handleException(Exception $exception): Redirect { $message = self::ONECLICK_EXCEPTION_FLOW_MESSAGE; @@ -269,7 +271,7 @@ private function handleException(Exception $exception) return $this->redirectWithErrorMessage($message); } - private function redirectToSuccess(array $responseData) + private function redirectToSuccess(array $responseData): Page { $resultPage = $this->resultPageFactory->create(); $resultPage->addHandle('transbank_checkout_success'); @@ -278,13 +280,13 @@ private function redirectToSuccess(array $responseData) return $resultPage; } - private function redirectWithErrorMessage(string $message) + private function redirectWithErrorMessage(string $message): Redirect { $this->messageManager->addErrorMessage(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } - private function cancelOrder(Order $order, string $message) + private function cancelOrder(Order $order, string $message): void { $orderStatusCanceled = $this->configProvider->getOneclickOrderErrorStatus(); $order->cancel(); @@ -293,7 +295,7 @@ private function cancelOrder(Order $order, string $message) $order->save(); } - private function checkTransactionIsAlreadyProcessed($orderId, $quoteId): bool + private function checkTransactionIsAlreadyProcessed(int $orderId, int $quoteId): bool { $webpayOrderData = $this->getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId); $status = $webpayOrderData->getPaymentStatus(); @@ -306,7 +308,7 @@ private function checkTransactionIsAlreadyProcessed($orderId, $quoteId): bool /** * @return Order */ - private function getOrder($orderId): Order + private function getOrder(int $orderId): Order { /** * @var Order @@ -316,7 +318,7 @@ private function getOrder($orderId): Order return $order->load($orderId); } - private function getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId) + private function getWebpayOrderDataByOrderIdAndQuoteId(int $orderId, int $quoteId): WebpayOrderData { return $this->webpayOrderDataRepository->getByOrderIdAndQuoteId($orderId, $quoteId); } @@ -328,7 +330,7 @@ private function getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId) * * @return OneclickInscriptionData */ - protected function getOneclickInscriptionData($inscriptionId): OneclickInscriptionData + protected function getOneclickInscriptionData(int $inscriptionId): OneclickInscriptionData { $oneclickInscriptionDataModel = $this->oneclickInscriptionDataFactory->create(); return $oneclickInscriptionDataModel->load($inscriptionId, 'id'); @@ -346,8 +348,13 @@ protected function getOneclickInscriptionData($inscriptionId): OneclickInscripti * * @return WebpayOrderData */ - protected function saveOneclickData($authorizeResponse, $amount, $payment_status, $order_id, $quote_id) - { + protected function saveOneclickData( + MallTransactionAuthorizeResponse $authorizeResponse, + float $amount, + string $payment_status, + int $order_id, + int $quote_id + ): WebpayOrderData { $webpayOrderData = $this->webpayOrderDataFactory->create(); $webpayOrderData->setData([ 'buy_order' => $authorizeResponse->getBuyOrder(), From a0717b14675785b759b0938fae4b520ae52f5f6e Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 16:04:00 -0400 Subject: [PATCH 130/159] docs: update docs for all methods --- Controller/Transaction/AuthorizeOneclick.php | 110 ++++++++++++++++--- 1 file changed, 96 insertions(+), 14 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index a244f2b..ce50440 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -98,9 +98,9 @@ public function __construct( } /** - * @throws \Exception + * This method handle the controller request. * - * @return ResponseInterface|Json|ResultInterface + * @return Page|Redirect The result of handling the request. */ public function execute() { @@ -124,6 +124,13 @@ public function execute() } } + /** + * This method handle Oneclick Request + * + * @param int $inscriptionId The Id for the inscription. + * + * @return Page|Redirect The result of handling Oneclick the request. + */ private function handleOneclickRequest(int $inscriptionId) { $inscription = $this->getOneclickInscriptionData($inscriptionId); @@ -167,6 +174,15 @@ private function handleOneclickRequest(int $inscriptionId) } } + /** + * This method handle de authorized transaction flow. + * + * @param Order $order The Magento order. + * @param MallTransactionAuthorizeResponse $authorizeResponse The Oneclick authorization response. + * @param float $totalAmount The total amount of the order. + * + * @return Page The success result page. + */ private function handleAuthorizedTransaction( Order $order, MallTransactionAuthorizeResponse $authorizeResponse, @@ -215,6 +231,16 @@ private function handleAuthorizedTransaction( return $this->redirectToSuccess($responseData); } + + /** + * This method handle de unauthorized transaction flow. + * + * @param Order $order The Magento order. + * @param MallTransactionAuthorizeResponse $authorizeResponse The Oneclick authorization response. + * @param float $totalAmount The total amount of the order. + * + * @return Redirect Redirect to cart page. + */ private function handleUnauthorizedTransaction( Order $order, MallTransactionAuthorizeResponse $authorizeResponse, @@ -237,6 +263,14 @@ private function handleUnauthorizedTransaction( return $this->redirectWithErrorMessage($message); } + /** + * This method handle the flow for orders already processed. + * + * @param int $orderId The order id. + * @param int $quoteId The quote id. + * + * @return Page|Redirect The result of handling Oneclick the request. + */ private function handleTransactionAlreadyProcessed(int $orderId, int $quoteId) { $webpayOrderData = $this->getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId); @@ -253,6 +287,13 @@ private function handleTransactionAlreadyProcessed(int $orderId, int $quoteId) return $this->redirectWithErrorMessage("La orden ya fue procesada."); } + /** + * This method will handle the flow when an exception is thrown. + * + * @param Exception $exception The exception object. + * + * @return Redirect Redirect to cart page. + */ private function handleException(Exception $exception): Redirect { $message = self::ONECLICK_EXCEPTION_FLOW_MESSAGE; @@ -271,6 +312,13 @@ private function handleException(Exception $exception): Redirect return $this->redirectWithErrorMessage($message); } + /** + * This method show the success result page. + * + * @param array $responseData The formatted response. + * + * @return Page The success result page. + */ private function redirectToSuccess(array $responseData): Page { $resultPage = $this->resultPageFactory->create(); @@ -280,12 +328,28 @@ private function redirectToSuccess(array $responseData): Page return $resultPage; } + /** + * This method redirect to the cart page. + * + * @param string $message The error message to show in the page. + * + * @return Redirect Redirect to cart page. + */ private function redirectWithErrorMessage(string $message): Redirect { $this->messageManager->addErrorMessage(__($message)); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } + + /** + * This method cancels the order and updates its status. + * + * @param Order $order The Magento order. + * @param string $message The message to show in order resume. + * + * @return void + */ private function cancelOrder(Order $order, string $message): void { $orderStatusCanceled = $this->configProvider->getOneclickOrderErrorStatus(); @@ -295,6 +359,14 @@ private function cancelOrder(Order $order, string $message): void $order->save(); } + /** + * This method check if the order already process. + * + * @param int $orderId The order id. + * @param int $quoteId The quote id. + * + * @return bool True if the order is already processed, false if it is not processed. + */ private function checkTransactionIsAlreadyProcessed(int $orderId, int $quoteId): bool { $webpayOrderData = $this->getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId); @@ -306,7 +378,11 @@ private function checkTransactionIsAlreadyProcessed(int $orderId, int $quoteId): } /** - * @return Order + * This method return the order object based on the id. + * + * @param int $orderId The order id. + * + * @return Order The Magento order. */ private function getOrder(int $orderId): Order { @@ -318,17 +394,24 @@ private function getOrder(int $orderId): Order return $order->load($orderId); } + /** + * This method return the WebpayOrderData base on the order id and quote id. + * + * @param int $orderId The order id. + * @param int $quoteId The quite id. + * + * @return WebpayOrderData The Webpay order data object. + */ private function getWebpayOrderDataByOrderIdAndQuoteId(int $orderId, int $quoteId): WebpayOrderData { return $this->webpayOrderDataRepository->getByOrderIdAndQuoteId($orderId, $quoteId); } /** - * @param $inscriptionId - * - * @throws \Exception + * This method return the OneclickInscriptionData based on the id. + * @param $inscriptionId The OneclickInscriptionData id. * - * @return OneclickInscriptionData + * @return OneclickInscriptionData The Oneclick inscription data object. */ protected function getOneclickInscriptionData(int $inscriptionId): OneclickInscriptionData { @@ -337,14 +420,13 @@ protected function getOneclickInscriptionData(int $inscriptionId): OneclickInscr } /** - * @param $buyOrder - * @param $childBuyOrder - * @param $commerceCode - * @param $payment_status - * @param $order_id - * @param $quote_id + * This method update the WebpayOrderData. * - * @throws \Exception + * @param MallTransactionAuthorizeResponse $authorizeResponse The authorization response. + * @param float $amount The amount of the order. + * @param string $payment_status The payment status. + * @param int $order_id The order id. + * @param int $quote_id The quote id. * * @return WebpayOrderData */ From 996fd3685bd75d815c856d51557cf8db16e315ce Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 16:04:12 -0400 Subject: [PATCH 131/159] style: format file --- Controller/Transaction/AuthorizeOneclick.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index ce50440..f9e4d33 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -274,17 +274,17 @@ private function handleUnauthorizedTransaction( private function handleTransactionAlreadyProcessed(int $orderId, int $quoteId) { $webpayOrderData = $this->getWebpayOrderDataByOrderIdAndQuoteId($orderId, $quoteId); - $status = $webpayOrderData->getPaymentStatus(); + $status = $webpayOrderData->getPaymentStatus(); - if ($status == WebpayOrderData::PAYMENT_STATUS_SUCCESS) { - $metadata = $webpayOrderData->getMetadata(); - $response = json_decode($metadata); - $formattedResponse = TbkResponseHelper::getOneclickFormattedResponse($response); + if ($status == WebpayOrderData::PAYMENT_STATUS_SUCCESS) { + $metadata = $webpayOrderData->getMetadata(); + $response = json_decode($metadata); + $formattedResponse = TbkResponseHelper::getOneclickFormattedResponse($response); - return $this->redirectToSuccess($formattedResponse); - } + return $this->redirectToSuccess($formattedResponse); + } - return $this->redirectWithErrorMessage("La orden ya fue procesada."); + return $this->redirectWithErrorMessage("La orden ya fue procesada."); } /** From 0c2b7fc413d9ab8f7826b5132c48c3804679b025 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 16:06:55 -0400 Subject: [PATCH 132/159] refactor: add types for the getByOrderIdAndQuoteId method --- Model/WebpayOrderDataRepository.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Model/WebpayOrderDataRepository.php b/Model/WebpayOrderDataRepository.php index 0260678..a7deef7 100644 --- a/Model/WebpayOrderDataRepository.php +++ b/Model/WebpayOrderDataRepository.php @@ -36,7 +36,7 @@ public function __construct( * * @return WebpayOrderData */ - public function getByOrderIdAndQuoteId($orderId, $quoteId) + public function getByOrderIdAndQuoteId(int $orderId, int $quoteId): WebpayOrderData { $collection = $this->collectionFactory->create(); $collection->addFieldToFilter('order_id', $orderId) From 52b74fc17b6ccad7061f2973aa8af672de451fab Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 16:12:03 -0400 Subject: [PATCH 133/159] refactor: use constant instead of a magic number --- Controller/Transaction/AuthorizeOneclick.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index f9e4d33..42dcace 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -39,6 +39,7 @@ class AuthorizeOneclick extends Action { const ONECLICK_EXCEPTION_FLOW_MESSAGE = 'No se pudo procesar el pago.'; + const AUTHORIZED_RESPONSE_CODE = 0; protected $configProvider; private $cart; @@ -167,7 +168,10 @@ private function handleOneclickRequest(int $inscriptionId) $authorizeResponse = $transbankSdkWebpay->authorizeTransaction($username, $tbkUser, $buyOrder, $details); - if (isset($authorizeResponse->details) && $authorizeResponse->details[0]->responseCode == 0) { + if ( + isset($authorizeResponse->details) && + $authorizeResponse->details[0]->responseCode == self::AUTHORIZED_RESPONSE_CODE + ) { return $this->handleAuthorizedTransaction($order, $authorizeResponse, $grandTotal); } else { return $this->handleUnauthorizedTransaction($order, $authorizeResponse, $grandTotal); From 7ebf810946854074a24455c956876716b46f4fd5 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 16:16:18 -0400 Subject: [PATCH 134/159] refactor: return always a MallTransactionAuthorizeResponse --- Model/TransbankSdkWebpayRest.php | 35 ++++++++++++++------------------ 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/Model/TransbankSdkWebpayRest.php b/Model/TransbankSdkWebpayRest.php index 5385f20..d4f7f19 100755 --- a/Model/TransbankSdkWebpayRest.php +++ b/Model/TransbankSdkWebpayRest.php @@ -208,35 +208,30 @@ public function finishInscription($tbkToken) } /** + * This method authorize a Oneclick transaction. + * * @param $username * @param $tbkUser * @param $total * * @throws MissingArgumentException * - * @return array|MallTransactionAuthorizeResponse + * @return MallTransactionAuthorizeResponse */ - public function authorizeTransaction($username, $tbkUser, $buyOrder, $details) - { - try { - if ($username == null || $tbkUser == null) { - throw new MissingArgumentException('El token tbkUser y el username son requerido'); - } - - $transaction = $this->mallTransaction->authorize($username, $tbkUser, $buyOrder, $details); - $this->log->logInfo('authorizeTransaction: '.json_encode($transaction)); - - return $transaction; - - } catch (InscriptionFinishException $e) { - $result = [ - 'error' => 'Error al autorizar la transacción', - 'detail' => $e->getMessage(), - ]; - $this->log->logError(json_encode($result)); + public function authorizeTransaction( + string $username, + string $tbkUser, + string $buyOrder, + array $details + ): MallTransactionAuthorizeResponse { + if ($username == null || $tbkUser == null) { + throw new MissingArgumentException('El token tbkUser y el username son requerido'); } - return $result; + $transaction = $this->mallTransaction->authorize($username, $tbkUser, $buyOrder, $details); + $this->log->logInfo('authorizeTransaction: ' . json_encode($transaction)); + + return $transaction; } /** From 6ee3b0084aba3eb24710dab61ac273323ec08f4d Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 16:16:34 -0400 Subject: [PATCH 135/159] style: format file --- Model/TransbankSdkWebpayRest.php | 36 +++++++++++++------------------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/Model/TransbankSdkWebpayRest.php b/Model/TransbankSdkWebpayRest.php index d4f7f19..2d7621c 100755 --- a/Model/TransbankSdkWebpayRest.php +++ b/Model/TransbankSdkWebpayRest.php @@ -56,14 +56,13 @@ public function __construct($config) $this->mallInscription = new Oneclick\MallInscription(); $this->mallTransaction = new Oneclick\MallTransaction(); - $this->log->logInfo('Environment: '.json_encode($environment)); + $this->log->logInfo('Environment: ' . json_encode($environment)); if ($environment != 'TEST') { $this->transaction->configureForProduction($config['COMMERCE_CODE'], $config['API_KEY']); $this->mallInscription->configureForProduction($config['COMMERCE_CODE'], $config['API_KEY']); $this->mallTransaction->configureForProduction($config['COMMERCE_CODE'], $config['API_KEY']); } - } } @@ -84,19 +83,19 @@ public function createTransaction($amount, $sessionId, $buyOrder, $returnUrl) try { $txDate = date('d-m-Y'); $txTime = date('H:i:s'); - $this->log->logInfo('createTransaction - amount: '.$amount.', sessionId: '.$sessionId. - ', buyOrder: '.$buyOrder.', txDate: '.$txDate.', txTime: '.$txTime); + $this->log->logInfo('createTransaction - amount: ' . $amount . ', sessionId: ' . $sessionId . + ', buyOrder: ' . $buyOrder . ', txDate: ' . $txDate . ', txTime: ' . $txTime); $createResult = $this->transaction->create($buyOrder, $sessionId, $amount, $returnUrl); - $this->log->logInfo('createTransaction - createResult: '.json_encode($createResult)); + $this->log->logInfo('createTransaction - createResult: ' . json_encode($createResult)); if (isset($createResult) && isset($createResult->url) && isset($createResult->token)) { $result = [ 'url' => $createResult->url, 'token_ws' => $createResult->token, ]; } else { - throw new TransbankCreateException('No se ha creado la transacción para, amount: '.$amount.', sessionId: '.$sessionId.', buyOrder: '.$buyOrder); + throw new TransbankCreateException('No se ha creado la transacción para, amount: ' . $amount . ', sessionId: ' . $sessionId . ', buyOrder: ' . $buyOrder); } } catch (TransactionCreateException $e) { $result = [ @@ -125,7 +124,7 @@ public function commitTransaction($tokenWs) $transaction = $this->transaction->commit($tokenWs); - $this->log->logInfo('commitTransaction: '.json_encode($transaction)); + $this->log->logInfo('commitTransaction: ' . json_encode($transaction)); return $transaction; } catch (TransactionCommitException $e) { $result = [ @@ -152,19 +151,19 @@ public function createInscription($username, $email, $responseUrl) $result = []; try { - $this->log->logInfo('initInscription - Username: '.$username.', email: '.$email. - ', responseUrl: '.$responseUrl); + $this->log->logInfo('initInscription - Username: ' . $username . ', email: ' . $email . + ', responseUrl: ' . $responseUrl); $initResult = $this->mallInscription->start($username, $email, $responseUrl); - $this->log->logInfo('createInscription - initResult: '.json_encode($initResult)); + $this->log->logInfo('createInscription - initResult: ' . json_encode($initResult)); if (isset($initResult) && isset($initResult->token) && isset($initResult->urlWebpay)) { $result = [ 'token' => $initResult->token, 'urlWebpay' => $initResult->urlWebpay, ]; } else { - throw new TransbankCreateException('No se ha creado la inscripción para, username: '.$username.', email: '.$email.', responseUrl: '.$responseUrl); + throw new TransbankCreateException('No se ha creado la inscripción para, username: ' . $username . ', email: ' . $email . ', responseUrl: ' . $responseUrl); } } catch (InscriptionStartException $e) { $result = [ @@ -187,13 +186,13 @@ public function createInscription($username, $email, $responseUrl) public function finishInscription($tbkToken) { try { - $this->log->logInfo('getInscriptonResult - tokenWs: '.$tbkToken); + $this->log->logInfo('getInscriptonResult - tokenWs: ' . $tbkToken); if ($tbkToken == null) { throw new MissingArgumentException('El token tokenWs es requerido'); } $inscription = $this->mallInscription->finish($tbkToken); - $this->log->logInfo('finishInscription: '.json_encode($inscription)); + $this->log->logInfo('finishInscription: ' . json_encode($inscription)); return $inscription; } catch (InscriptionFinishException $e) { @@ -250,10 +249,9 @@ public function deleteInscription($username, $tbkUser) } $delInscription = $this->mallInscription->delete($tbkUser, $username); - $this->log->logInfo('deleteInscription: '.json_encode($delInscription)); + $this->log->logInfo('deleteInscription: ' . json_encode($delInscription)); return $delInscription; - } catch (InscriptionFinishException $e) { $result = [ 'error' => 'Error al eliminar una inscripción', @@ -280,10 +278,8 @@ public function refundOneClickTransaction( string $childCommerceCode, string $childBuyOrder, int $amount - ): \Transbank\Webpay\Oneclick\Responses\MallTransactionRefundResponse - { + ): \Transbank\Webpay\Oneclick\Responses\MallTransactionRefundResponse { return $this->mallTransaction->refund($buyOrder, $childCommerceCode, $childBuyOrder, $amount); - } /** @@ -298,9 +294,7 @@ public function refundOneClickTransaction( public function refundWebpayPlusTransaction( string $token, int $amount - ): \Transbank\Webpay\WebpayPlus\Responses\TransactionRefundResponse - { + ): \Transbank\Webpay\WebpayPlus\Responses\TransactionRefundResponse { return $this->transaction->refund($token, $amount); - } } From 0ef86b1d4256d31d6c1f7376b0264e38e24a4e63 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 16:35:34 -0400 Subject: [PATCH 136/159] refactor: fix typo --- Model/TransbankSdkWebpayRest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Model/TransbankSdkWebpayRest.php b/Model/TransbankSdkWebpayRest.php index 2d7621c..6df853d 100755 --- a/Model/TransbankSdkWebpayRest.php +++ b/Model/TransbankSdkWebpayRest.php @@ -224,7 +224,7 @@ public function authorizeTransaction( array $details ): MallTransactionAuthorizeResponse { if ($username == null || $tbkUser == null) { - throw new MissingArgumentException('El token tbkUser y el username son requerido'); + throw new MissingArgumentException('El token tbkUser y el username son requeridos'); } $transaction = $this->mallTransaction->authorize($username, $tbkUser, $buyOrder, $details); From e7eabd10b2cc46582604cbb1afa1739567a96636 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 16:40:11 -0400 Subject: [PATCH 137/159] docs: update docs for the method authorizeTransaction --- Model/TransbankSdkWebpayRest.php | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Model/TransbankSdkWebpayRest.php b/Model/TransbankSdkWebpayRest.php index 6df853d..54106fe 100755 --- a/Model/TransbankSdkWebpayRest.php +++ b/Model/TransbankSdkWebpayRest.php @@ -209,13 +209,14 @@ public function finishInscription($tbkToken) /** * This method authorize a Oneclick transaction. * - * @param $username - * @param $tbkUser - * @param $total + * @param string $username The username of the inscription. + * @param string $tbkUser The tbk_user of the inscription. + * @param string $buyOrder The buy order. + * @param array $details The transactions details. * - * @throws MissingArgumentException + * @throws MissingArgumentException Thrown when username or tbk_user is null. * - * @return MallTransactionAuthorizeResponse + * @return MallTransactionAuthorizeResponse The authorization response. */ public function authorizeTransaction( string $username, From ee72144aefba1f2d02ca2cdeec163bf0b39e38f5 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 17:51:43 -0400 Subject: [PATCH 138/159] refactor: remove unused variable --- Controller/Transaction/AuthorizeOneclick.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 42dcace..c154a63 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -24,7 +24,6 @@ use Transbank\Webpay\Model\WebpayOrderDataRepository; use Magento\Sales\Model\Order\Payment\Transaction; use Transbank\Webpay\Model\OneclickInscriptionData; -use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\View\Result\PageFactory; use Transbank\Webpay\Helper\QuoteHelper; use Transbank\Webpay\Model\OneclickInscriptionDataFactory; @@ -44,7 +43,6 @@ class AuthorizeOneclick extends Action private $cart; private $checkoutSession; - private $resultJsonFactory; private $oneclickInscriptionDataFactory; private $log; private $webpayOrderDataFactory; @@ -61,7 +59,6 @@ class AuthorizeOneclick extends Action * @param Context $context * @param Cart $cart * @param Session $checkoutSession - * @param JsonFactory $resultJsonFactory * @param ConfigProvider $configProvider * @param OneclickInscriptionDataFactory $oneclickInscriptionDataFactory * @param WebpayOrderDataFactory $webpayOrderDataFactory @@ -71,7 +68,6 @@ public function __construct( Context $context, Cart $cart, Session $checkoutSession, - JsonFactory $resultJsonFactory, PageFactory $resultPageFactory, ConfigProvider $configProvider, EventManagerInterface $eventManager, @@ -85,7 +81,6 @@ public function __construct( $this->cart = $cart; $this->checkoutSession = $checkoutSession; - $this->resultJsonFactory = $resultJsonFactory; $this->configProvider = $configProvider; $this->messageManager = $messageManager; $this->oneclickInscriptionDataFactory = $oneclickInscriptionDataFactory; From e1d502d61d09d7e800b22cb41d512936cd2c9a97 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 17:51:57 -0400 Subject: [PATCH 139/159] refactor: remove unused imports --- Controller/Transaction/AuthorizeOneclick.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index c154a63..9c3f092 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -13,11 +13,8 @@ use Transbank\Webpay\Helper\PluginLogger; use Transbank\Webpay\Helper\TbkResponseHelper; use Transbank\Webpay\Helper\ObjectManagerHelper; -use Magento\Framework\App\ResponseInterface; -use Magento\Framework\Controller\Result\Json; use Transbank\Webpay\Model\Config\ConfigProvider; use Magento\Framework\Message\ManagerInterface; -use Magento\Framework\Controller\ResultInterface; use Magento\Framework\Controller\Result\Redirect; use Transbank\Webpay\Model\TransbankSdkWebpayRest; use Transbank\Webpay\Model\WebpayOrderDataFactory; From fc1df138bfce1c140a325e608beab7e79b6a9df5 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 22:24:42 -0400 Subject: [PATCH 140/159] feat: validate if customer is logged in --- Controller/Transaction/AuthorizeOneclick.php | 31 ++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 9c3f092..4a92e72 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -28,6 +28,7 @@ use Transbank\Webpay\Oneclick\Responses\MallTransactionAuthorizeResponse; use Transbank\Webpay\Exceptions\InvalidRequestException; use Transbank\Webpay\Model\WebpayOrderData; +use Magento\Customer\Model\Session as CustomerSession; /** * Controller for create Oneclick Inscription. @@ -49,6 +50,7 @@ class AuthorizeOneclick extends Action protected $messageManager; private $oneclickConfig; private $quoteHelper; + protected $customerSession; /** * AuthorizeOneclick constructor. @@ -56,9 +58,12 @@ class AuthorizeOneclick extends Action * @param Context $context * @param Cart $cart * @param Session $checkoutSession + * @param PageFactory $resultPageFactory * @param ConfigProvider $configProvider + * @param EventManagerInterface $eventManager * @param OneclickInscriptionDataFactory $oneclickInscriptionDataFactory * @param WebpayOrderDataFactory $webpayOrderDataFactory + * @param WebpayOrderDataRepository $webpayOrderDataRepository * @param ManagerInterface $messageManager */ public function __construct( @@ -72,7 +77,8 @@ public function __construct( WebpayOrderDataFactory $webpayOrderDataFactory, WebpayOrderDataRepository $webpayOrderDataRepository, ManagerInterface $messageManager, - QuoteHelper $quoteHelper + QuoteHelper $quoteHelper, + CustomerSession $customerSession ) { parent::__construct($context); @@ -88,6 +94,7 @@ public function __construct( $this->log = new PluginLogger(); $this->oneclickConfig = $configProvider->getPluginConfigOneclick(); $this->quoteHelper = $quoteHelper; + $this->customerSession = $customerSession; } /** @@ -126,10 +133,6 @@ public function execute() */ private function handleOneclickRequest(int $inscriptionId) { - $inscription = $this->getOneclickInscriptionData($inscriptionId); - $username = $inscription->getUsername(); - $tbkUser = $inscription->getTbkUser(); - $this->checkoutSession->restoreQuote(); $quote = $this->cart->getQuote(); $quote->getPayment()->importData(['method' => Oneclick::CODE]); @@ -144,8 +147,17 @@ private function handleOneclickRequest(int $inscriptionId) return $this->handleTransactionAlreadyProcessed($orderId, $quote->getId()); } + if (!$this->isCustomerLoggedIn()) { + throw new InvalidRequestException("No se ha iniciado sesión de usuario."); + } + + $inscription = $this->getOneclickInscriptionData($inscriptionId); + $transbankSdkWebpay = new TransbankSdkWebpayRest($this->oneclickConfig); + $username = $inscription->getUsername(); + $tbkUser = $inscription->getTbkUser(); + $buyOrder = "100000" . $orderId; $childBuyOrder = "200000" . $orderId; @@ -415,6 +427,15 @@ protected function getOneclickInscriptionData(int $inscriptionId): OneclickInscr return $oneclickInscriptionDataModel->load($inscriptionId, 'id'); } + /** + * This method check if customer is logged in. + * + * @return bool True if customer is logged in, otherwise false. + */ + private function isCustomerLoggedIn(): bool { + return $this->customerSession->isLoggedIn(); + } + /** * This method update the WebpayOrderData. * From 8b57957f9278b27f4f2b1b3965136a65235da025 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 22:27:03 -0400 Subject: [PATCH 141/159] feat: Validate that the user who pays the order is the same one who registered the card --- Controller/Transaction/AuthorizeOneclick.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 4a92e72..556d85e 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -153,6 +153,10 @@ private function handleOneclickRequest(int $inscriptionId) $inscription = $this->getOneclickInscriptionData($inscriptionId); + if (!$this->validatePayerMatchesCardInscription($inscription)) { + throw new InvalidRequestException("Datos incorrectos para autorizar la transacción."); + } + $transbankSdkWebpay = new TransbankSdkWebpayRest($this->oneclickConfig); $username = $inscription->getUsername(); @@ -427,6 +431,22 @@ protected function getOneclickInscriptionData(int $inscriptionId): OneclickInscr return $oneclickInscriptionDataModel->load($inscriptionId, 'id'); } + /** + * Validate that the user paying for the order is the same as the one who registered the card. + * + * @param OneclickInscriptionData $inscriptionData The card inscription data. + * + * @return bool True if the payer matches the card inscription, false otherwise. + */ + private function validatePayerMatchesCardInscription(OneclickInscriptionData $inscriptionData) + { + $customerData = $this->customerSession->getCustomerData(); + $customerEmail = $customerData->getEmail(); + $inscriptionEmail = $inscriptionData->getEmail(); + + return $customerEmail == $inscriptionEmail; + } + /** * This method check if customer is logged in. * From b32bc71976a063364923be9267db6a5be2e7bee2 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 22:33:14 -0400 Subject: [PATCH 142/159] feat: log always the request information --- Controller/Transaction/AuthorizeOneclick.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 556d85e..32f906b 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -105,19 +105,19 @@ public function __construct( public function execute() { try { - if (!isset($_POST['inscription'])) { - throw new InvalidRequestException('Petición invalida: Falta el campo inscription'); - } - $requestMethod = $_SERVER['REQUEST_METHOD']; $request = $requestMethod === 'POST' ? $_POST : $_GET; - $inscriptionId = intval($request['inscription']); - $this->log->logInfo('Autorizando transacción Oneclick.'); $this->log->logInfo('Request: method -> ' . $requestMethod); $this->log->logInfo('Request: payload -> ' . json_encode($request)); + if (!isset($_POST['inscription'])) { + throw new InvalidRequestException('Petición invalida: Falta el campo inscription'); + } + + $inscriptionId = intval($request['inscription']); + return $this->handleOneclickRequest($inscriptionId); } catch (Exception $e) { return $this->handleException($e); From 48765ac29e9e6286fed3f9bd8cbd5f94ae42ad13 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 22:34:03 -0400 Subject: [PATCH 143/159] feat: log the exception name --- Controller/Transaction/AuthorizeOneclick.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 32f906b..528e601 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -113,7 +113,7 @@ public function execute() $this->log->logInfo('Request: payload -> ' . json_encode($request)); if (!isset($_POST['inscription'])) { - throw new InvalidRequestException('Petición invalida: Falta el campo inscription'); + throw new InvalidRequestException('Falta el campo inscription'); } $inscriptionId = intval($request['inscription']); @@ -309,9 +309,10 @@ private function handleTransactionAlreadyProcessed(int $orderId, int $quoteId) private function handleException(Exception $exception): Redirect { $message = self::ONECLICK_EXCEPTION_FLOW_MESSAGE; + $exceptionName = get_class($exception); $this->log->logError('Error al procesar el pago: '); - $this->log->logError($exception->getMessage()); + $this->log->logError($exceptionName . ": " .$exception->getMessage()); $this->log->logError($exception->getTraceAsString()); $order = $this->checkoutSession->getLastRealOrder(); From c8800fb0e91737885b155c79ab842b72c5470b1d Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 23 Jul 2024 22:38:22 -0400 Subject: [PATCH 144/159] docs: add InvalidRequestException exception in methods --- Controller/Transaction/AuthorizeOneclick.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 528e601..954e245 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -100,6 +100,8 @@ public function __construct( /** * This method handle the controller request. * + * @throws InvalidRequestException When inscription is not defined. + * * @return Page|Redirect The result of handling the request. */ public function execute() @@ -129,6 +131,8 @@ public function execute() * * @param int $inscriptionId The Id for the inscription. * + * @throws InvalidRequestException When the user is not logged in or when the user pays with a card that is not registered + * * @return Page|Redirect The result of handling Oneclick the request. */ private function handleOneclickRequest(int $inscriptionId) From aeb883ff581e3fd852ea2d4ab1bc29168eb25e95 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 30 Jul 2024 13:29:07 -0400 Subject: [PATCH 145/159] feat: add webpay environment transaction info --- Controller/Transaction/CreateWebpay.php | 12 +++++++----- Model/Webpay.php | 1 + 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/Controller/Transaction/CreateWebpay.php b/Controller/Transaction/CreateWebpay.php index a47c9b4..2e1777e 100644 --- a/Controller/Transaction/CreateWebpay.php +++ b/Controller/Transaction/CreateWebpay.php @@ -21,6 +21,7 @@ class CreateWebpay extends \Magento\Framework\App\Action\Action protected $webpayOrderDataFactory; protected $log; protected $quoteRepository; + protected $webpayConfig; /** * CreateWebpayM22 constructor. @@ -54,6 +55,7 @@ public function __construct( $this->configProvider = $configProvider; $this->webpayOrderDataFactory = $webpayOrderDataFactory; $this->log = new PluginLogger(); + $this->webpayConfig = $configProvider->getPluginConfig(); } /** @@ -67,15 +69,12 @@ public function execute() $response = null; $order = null; - $config = $this->configProvider->getPluginConfig(); $orderStatusCanceled = $this->configProvider->getOrderErrorStatus(); $orderStatusPendingPayment = $this->configProvider->getOrderPendingStatus(); try { $guestEmail = isset($_GET['guestEmail']) ? $_GET['guestEmail'] : null; - $config = $this->configProvider->getPluginConfig(); - $tmpOrder = $this->getOrder(); $this->checkoutSession->restoreQuote(); @@ -102,13 +101,13 @@ public function execute() $baseUrl = $this->storeManager->getStore()->getBaseUrl(); - $returnUrl = $baseUrl . $config['URL_RETURN']; + $returnUrl = $baseUrl . $this->webpayConfig['URL_RETURN']; $quoteId = $quote->getId(); $orderId = $this->getOrderId(); $quote->save(); - $transbankSdkWebpay = new TransbankSdkWebpayRest($config); + $transbankSdkWebpay = new TransbankSdkWebpayRest($this->webpayConfig); $this->log->logInfo('B.2. Preparando datos antes de crear la transacción en Transbank'); $this->log->logInfo('amount: ' . $grandTotal . ', sessionId: ' . $quoteId . ', buyOrder: ' . $orderId . ', returnUrl: ' . $returnUrl); $response = $transbankSdkWebpay->createTransaction($grandTotal, $quoteId, $orderId, $returnUrl); @@ -195,6 +194,9 @@ protected function saveWebpayData($token_ws, $payment_status, $order_id, $quote_ 'order_id' => $order_id, 'quote_id' => $quote_id, 'metadata' => json_encode($this->checkoutSession->getData()), + 'commerce_code' => $this->webpayConfig['COMMERCE_CODE'], + 'environment' => $this->webpayConfig['ENVIRONMENT'], + 'product' => Webpay::PRODUCT_NAME ]); $webpayOrderData->save(); } diff --git a/Model/Webpay.php b/Model/Webpay.php index 61eff8a..c4e9e26 100755 --- a/Model/Webpay.php +++ b/Model/Webpay.php @@ -5,6 +5,7 @@ class Webpay extends \Magento\Payment\Model\Method\AbstractMethod { const CODE = 'transbank_webpay'; + const PRODUCT_NAME = 'webpay_plus'; /** * Payment code. From 986df2e9668fbaf01dcb248ae74fb7d12b644194 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 20 Aug 2024 10:57:25 -0400 Subject: [PATCH 146/159] feat: use user id instead of the email --- Controller/Transaction/AuthorizeOneclick.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 954e245..ba63684 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -446,10 +446,10 @@ protected function getOneclickInscriptionData(int $inscriptionId): OneclickInscr private function validatePayerMatchesCardInscription(OneclickInscriptionData $inscriptionData) { $customerData = $this->customerSession->getCustomerData(); - $customerEmail = $customerData->getEmail(); - $inscriptionEmail = $inscriptionData->getEmail(); + $customerId = $customerData->getId(); + $inscriptionUserId = $inscriptionData->getUserId(); - return $customerEmail == $inscriptionEmail; + return $customerId == $inscriptionUserId; } /** From fc4c1d5c850ac08af4afc17aafb1193d0c1f1cac Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 11 Sep 2024 16:20:45 -0300 Subject: [PATCH 147/159] feat: sanitize webpay forms --- .../method-renderer/oneclick-method.js | 49 +++++++++++-------- .../payment/method-renderer/webpay-method.js | 16 ++++-- 2 files changed, 41 insertions(+), 24 deletions(-) diff --git a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js index 884b8fb..cd34935 100644 --- a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js +++ b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js @@ -73,15 +73,16 @@ define([ function checkTransaction(result) { if (result != undefined && result.token != undefined) { - let form = jQuery( - '
' + - "
" - ); - jQuery("body").append(form); + const url = new URL(result.urlWebpay); + const params = new URLSearchParams(); + params.append("TBK_TOKEN", result.token); + + const form = document.createElement("form"); + form.setAttribute("action", `${url}?${params.toString()}`); + form.setAttribute("method", "post"); + + document.body.appendChild(form); + form.submit(); } else { alert("Error al crear transacción"); @@ -89,19 +90,27 @@ function checkTransaction(result) { } function authorizeTransaction(selected_inscription) { - let url = + const url = window.checkoutConfig.pluginConfigOneclick.authorizeTransactionUrl; - let form = jQuery( - '
' + - '' + - "
" - ); - jQuery("body").append(form); + const form = document.createElement("form"); + form.setAttribute("action", url); + form.setAttribute("method", "post"); + + const input = document.createElement("input"); + input.setAttribute("type", "hidden"); + input.setAttribute("name", "inscription"); + input.setAttribute("value", selected_inscription); + + const formKeyInput = document.createElement("input"); + formKeyInput.setAttribute("type", "hidden"); + formKeyInput.setAttribute("name", "form_key"); + formKeyInput.setAttribute("value", jQuery.cookie("form_key")); + + form.appendChild(input); + form.appendChild(formKeyInput); + document.body.appendChild(form); + form.submit(); } diff --git a/view/frontend/web/js/view/payment/method-renderer/webpay-method.js b/view/frontend/web/js/view/payment/method-renderer/webpay-method.js index 9388379..3a06e8c 100644 --- a/view/frontend/web/js/view/payment/method-renderer/webpay-method.js +++ b/view/frontend/web/js/view/payment/method-renderer/webpay-method.js @@ -48,10 +48,18 @@ define( function submitForm (result) { if (result != undefined && result.token_ws != undefined) { - let form = jQuery('
' + - '' + - '
'); - jQuery('body').append(form); + const form = document.createElement('form'); + form.setAttribute('action', result.url); + form.setAttribute('method', 'post'); + + const input = document.createElement('input'); + input.setAttribute('type', 'hidden'); + input.setAttribute('name', 'token_ws'); + input.setAttribute('value', result.token_ws); + + form.appendChild(input); + document.body.appendChild(form); + form.submit(); } else { alert('Error al crear transacción'); From c35c00ce89366f0d6733118f16b1d58ddd80d9cd Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 11 Sep 2024 16:55:21 -0300 Subject: [PATCH 148/159] feat: improve information exposure --- Controller/Adminhtml/Request/Index.php | 2 +- Observer/EmailObserver.php | 2 +- Observer/SubmitObserver.php | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Controller/Adminhtml/Request/Index.php b/Controller/Adminhtml/Request/Index.php index bf11738..8abf931 100755 --- a/Controller/Adminhtml/Request/Index.php +++ b/Controller/Adminhtml/Request/Index.php @@ -30,7 +30,7 @@ public function execute() echo json_encode(['success' => true, 'msg' => $response]); } catch (TransbankCreateException $e) { - echo json_encode(['success' => false, 'msg' => $e->getMessage()]); + echo json_encode(['success' => false, 'msg' => 'No se puedo crear la transacción de pruebas.']); } } } diff --git a/Observer/EmailObserver.php b/Observer/EmailObserver.php index c14679f..25edd3a 100644 --- a/Observer/EmailObserver.php +++ b/Observer/EmailObserver.php @@ -19,7 +19,7 @@ public function execute(\Magento\Framework\Event\Observer $observer) { try { $this->orderSender->send($order); } catch (\Exception $e) { - $this->logger->critical($e); + $this->logger->critical($e->getMessage()); } } diff --git a/Observer/SubmitObserver.php b/Observer/SubmitObserver.php index 22c2c41..a723bc9 100644 --- a/Observer/SubmitObserver.php +++ b/Observer/SubmitObserver.php @@ -26,7 +26,7 @@ public function __construct ( public function execute(\Magento\Framework\Event\Observer $observer) { try { - + $emailSettings = $this->configProvider->getEmailSettings(); $oneclickEmailSettings = $this->configProvider->getOneclickEmailSettings(); $this->_logger->debug($emailSettings); @@ -40,8 +40,8 @@ public function execute(\Magento\Framework\Event\Observer $observer) } } catch (\ErrorException $e) { - $this->_logger->critical($e); + $this->_logger->critical($e->getMessage()); } } - + } From cfcb532a3fad8fe81db41528eadba36582c6235e Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 11 Sep 2024 17:03:39 -0300 Subject: [PATCH 149/159] fix: typo --- Controller/Adminhtml/Request/Index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Controller/Adminhtml/Request/Index.php b/Controller/Adminhtml/Request/Index.php index 8abf931..d419f2c 100755 --- a/Controller/Adminhtml/Request/Index.php +++ b/Controller/Adminhtml/Request/Index.php @@ -30,7 +30,7 @@ public function execute() echo json_encode(['success' => true, 'msg' => $response]); } catch (TransbankCreateException $e) { - echo json_encode(['success' => false, 'msg' => 'No se puedo crear la transacción de pruebas.']); + echo json_encode(['success' => false, 'msg' => 'No se pudo crear la transacción de pruebas.']); } } } From c21c2a4bc20e7d2385dba91fc1ba804b2f456d69 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 24 Sep 2024 15:25:00 -0300 Subject: [PATCH 150/159] feat: add protection to multiples clicks --- view/adminhtml/templates/system/config/button.phtml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/view/adminhtml/templates/system/config/button.phtml b/view/adminhtml/templates/system/config/button.phtml index 5fa483e..0eb2090 100755 --- a/view/adminhtml/templates/system/config/button.phtml +++ b/view/adminhtml/templates/system/config/button.phtml @@ -272,6 +272,8 @@ $(".check_conn").click(function() { + $(".check_conn").prop('disabled', true); + $(".btn_status").hide(); $(".check_conn").text("Verificando ..."); $("#row_response_url").hide(); @@ -322,7 +324,11 @@ $("#row_error_message").show(); $("#row_error_detail").show(); } - },'json'); + + $(".check_conn").prop('disabled', false); + },'json').fail(function() { + $(".check_conn").prop('disabled', false); + }); }); }); From 1440a2eee558281ca5a2cbb13cedfcedcbb7fdb6 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 24 Sep 2024 15:28:03 -0300 Subject: [PATCH 151/159] feat: set status text in case of error --- view/adminhtml/templates/system/config/button.phtml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/view/adminhtml/templates/system/config/button.phtml b/view/adminhtml/templates/system/config/button.phtml index 0eb2090..f5e6207 100755 --- a/view/adminhtml/templates/system/config/button.phtml +++ b/view/adminhtml/templates/system/config/button.phtml @@ -319,7 +319,7 @@ $(".status-label").removeClass("tbk-label-success"); $(".status-label").removeClass("tbk-label-danger"); $(".status-label").addClass("tbk-label-danger"); - $(".status-label").append("ERROR"); + $(".status-label").text("ERROR"); $(".error_detail_content").append('
'+response.msg+'
'); $("#row_error_message").show(); $("#row_error_detail").show(); @@ -327,6 +327,11 @@ $(".check_conn").prop('disabled', false); },'json').fail(function() { + $(".status-label").removeClass("tbk-label-success"); + $(".status-label").removeClass("tbk-label-danger"); + $(".status-label").addClass("tbk-label-danger"); + $(".status-label").text("ERROR"); + $(".check_conn").prop('disabled', false); }); }); From e9891c50c28228cc986c0568da1680b9d7d3c6b8 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Tue, 24 Sep 2024 16:03:20 -0300 Subject: [PATCH 152/159] feat: add error message --- view/adminhtml/templates/system/config/button.phtml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/view/adminhtml/templates/system/config/button.phtml b/view/adminhtml/templates/system/config/button.phtml index f5e6207..457b69e 100755 --- a/view/adminhtml/templates/system/config/button.phtml +++ b/view/adminhtml/templates/system/config/button.phtml @@ -312,7 +312,7 @@ $(".status-label").text("ERROR"); $("#row_error_message").show(); $("#row_error_detail").show(); - $(".error-content").append(response.msg.response.error); + $(".error_content").append(response.msg.response.error); $(".error_detail_content").append('
'+response.msg.response.detail+'
'); } } else { @@ -320,6 +320,7 @@ $(".status-label").removeClass("tbk-label-danger"); $(".status-label").addClass("tbk-label-danger"); $(".status-label").text("ERROR"); + $(".error_content").append(response.msg.response.error); $(".error_detail_content").append('
'+response.msg+'
'); $("#row_error_message").show(); $("#row_error_detail").show(); From 5aac7a8d29a3b8b949419c0cf9f551b6a7fe9d61 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 25 Sep 2024 16:57:36 -0300 Subject: [PATCH 153/159] fix: remove comma at the end of the last element --- .../js/view/payment/method-renderer/oneclick-method.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js index cd34935..042cf26 100644 --- a/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js +++ b/view/frontend/web/js/view/payment/method-renderer/oneclick-method.js @@ -8,7 +8,7 @@ define([ "Magento_Checkout/js/model/payment/additional-validators", "mage/url", "Magento_Checkout/js/model/quote", - "Magento_Checkout/js/action/set-payment-information", + "Magento_Checkout/js/action/set-payment-information" ], function ( $, Component, @@ -25,7 +25,7 @@ define([ return Component.extend({ defaults: { - template: "Transbank_Webpay/payment/oneclick", + template: "Transbank_Webpay/payment/oneclick" }, getCode: function () { @@ -54,7 +54,7 @@ define([ return { key: `${inscription.card_type} terminada en ${last_digits}`, - value: inscription.id, + value: inscription.id }; }); @@ -67,7 +67,7 @@ define([ window.checkoutConfig.totalsData.oneclick_max_amount; return oneclickMaxAmount < grandTotal; - }, + } }); }); From e04d76192b5c431f19d7c130e02f534c0a2c43c7 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 25 Sep 2024 17:01:30 -0300 Subject: [PATCH 154/159] fix: remove unused return value --- Controller/Transaction/AuthorizeOneclick.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index ba63684..3b900cc 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -478,7 +478,7 @@ protected function saveOneclickData( string $payment_status, int $order_id, int $quote_id - ): WebpayOrderData { + ): void { $webpayOrderData = $this->webpayOrderDataFactory->create(); $webpayOrderData->setData([ 'buy_order' => $authorizeResponse->getBuyOrder(), @@ -494,7 +494,5 @@ protected function saveOneclickData( 'product' => Oneclick::PRODUCT_NAME ]); $webpayOrderData->save(); - - return $webpayOrderData; } } From a7f5f5f5f78abaa3f9ae767a0f595a69e6858d9c Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 25 Sep 2024 17:02:40 -0300 Subject: [PATCH 155/159] fix: add missing return --- Controller/Transaction/CommitWebpay.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index bceb8e8..fad84a8 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -158,7 +158,7 @@ private function handleNormalFlow(string $token) $commitResponse = $transbankSdkWebpay->commitTransaction($token); if (is_array($commitResponse) && isset($commitResponse['error'])) { - $this->handleFlowError($token); + return $this->handleFlowError($token); } $webpayOrderData->setMetadata(json_encode($commitResponse)); From 159056ed07c0a54ff43165a97d57986e084b10c4 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 25 Sep 2024 17:10:33 -0300 Subject: [PATCH 156/159] refactor: reduce return number to three --- Controller/Transaction/CommitWebpay.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index fad84a8..945e0a5 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -163,11 +163,15 @@ private function handleNormalFlow(string $token) $webpayOrderData->setMetadata(json_encode($commitResponse)); + $responseHandled = null; + if ($commitResponse->isApproved()) { - return $this->handleAuthorizedTransaction($order, $webpayOrderData, $commitResponse); + $responseHandled = $this->handleAuthorizedTransaction($order, $webpayOrderData, $commitResponse); + } else { + $responseHandled = $this->handleUnauthorizedTransaction($order, $webpayOrderData, $commitResponse); } - return $this->handleUnauthorizedTransaction($order, $webpayOrderData, $commitResponse); + return $responseHandled; } private function handleFlowTimeout(string $buyOrder) From c2f2233baaa13e00530d4ef3730cf4bf36f9d5ff Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Wed, 25 Sep 2024 17:31:56 -0300 Subject: [PATCH 157/159] fix: use specific exceptions instead of base exception --- Controller/Transaction/AuthorizeOneclick.php | 4 +++- Controller/Transaction/CommitWebpay.php | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 3b900cc..1cea8f8 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -26,7 +26,9 @@ use Transbank\Webpay\Model\OneclickInscriptionDataFactory; use Magento\Framework\Event\ManagerInterface as EventManagerInterface; use Transbank\Webpay\Oneclick\Responses\MallTransactionAuthorizeResponse; +use Transbank\Webpay\Oneclick\Exceptions\MallTransactionAuthorizeException; use Transbank\Webpay\Exceptions\InvalidRequestException; +use Transbank\Webpay\Exceptions\MissingArgumentException; use Transbank\Webpay\Model\WebpayOrderData; use Magento\Customer\Model\Session as CustomerSession; @@ -121,7 +123,7 @@ public function execute() $inscriptionId = intval($request['inscription']); return $this->handleOneclickRequest($inscriptionId); - } catch (Exception $e) { + } catch (InvalidRequestException | MissingArgumentException | MallTransactionAuthorizeException $e) { return $this->handleException($e); } } diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index 945e0a5..e27ba2b 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -11,7 +11,9 @@ use Transbank\Webpay\Helper\PluginLogger; use Transbank\Webpay\Helper\QuoteHelper; use Transbank\Webpay\Helper\TbkResponseHelper; +use Transbank\Webpay\Exceptions\MissingArgumentException; use Transbank\Webpay\WebpayPlus\Responses\TransactionCommitResponse; +use Transbank\Webpay\WebpayPlus\Exceptions\TransactionCommitException; /** * Controller for commit transaction Webpay. @@ -78,7 +80,7 @@ public function execute() $this->log->logInfo('Request: payload -> ' . json_encode($request)); return $this->handleRequest($request); - } catch (Exception $exception) { + } catch (MissingArgumentException | TransactionCommitException $exception) { return $this->handleException($exception); } } From b15c267812666c016f3def2504830d3816f6cd08 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Thu, 26 Sep 2024 15:28:59 -0300 Subject: [PATCH 158/159] feat: add guzzle exception in catch block --- Controller/Transaction/AuthorizeOneclick.php | 3 ++- Controller/Transaction/CommitWebpay.php | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Controller/Transaction/AuthorizeOneclick.php b/Controller/Transaction/AuthorizeOneclick.php index 1cea8f8..2e75041 100644 --- a/Controller/Transaction/AuthorizeOneclick.php +++ b/Controller/Transaction/AuthorizeOneclick.php @@ -3,6 +3,7 @@ namespace Transbank\Webpay\Controller\Transaction; use Exception; +use GuzzleHttp\Exception\GuzzleException; use Magento\Sales\Model\Order; use Magento\Checkout\Model\Cart; use Magento\Checkout\Model\Session; @@ -123,7 +124,7 @@ public function execute() $inscriptionId = intval($request['inscription']); return $this->handleOneclickRequest($inscriptionId); - } catch (InvalidRequestException | MissingArgumentException | MallTransactionAuthorizeException $e) { + } catch (InvalidRequestException | MissingArgumentException | MallTransactionAuthorizeException | GuzzleException $e) { return $this->handleException($e); } } diff --git a/Controller/Transaction/CommitWebpay.php b/Controller/Transaction/CommitWebpay.php index e27ba2b..38ed9de 100755 --- a/Controller/Transaction/CommitWebpay.php +++ b/Controller/Transaction/CommitWebpay.php @@ -3,6 +3,7 @@ namespace Transbank\Webpay\Controller\Transaction; use Exception; +use GuzzleHttp\Exception\GuzzleException; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment\Transaction; use Transbank\Webpay\Helper\ObjectManagerHelper; @@ -13,7 +14,6 @@ use Transbank\Webpay\Helper\TbkResponseHelper; use Transbank\Webpay\Exceptions\MissingArgumentException; use Transbank\Webpay\WebpayPlus\Responses\TransactionCommitResponse; -use Transbank\Webpay\WebpayPlus\Exceptions\TransactionCommitException; /** * Controller for commit transaction Webpay. @@ -80,7 +80,7 @@ public function execute() $this->log->logInfo('Request: payload -> ' . json_encode($request)); return $this->handleRequest($request); - } catch (MissingArgumentException | TransactionCommitException $exception) { + } catch (MissingArgumentException | GuzzleException $exception) { return $this->handleException($exception); } } From bbb687feb80600d2a59f56e869d89b2258dee9e5 Mon Sep 17 00:00:00 2001 From: Mauricio Astudillo Toledo Date: Fri, 4 Oct 2024 11:15:41 -0300 Subject: [PATCH 159/159] chore: prepare release 2.3.0 --- CHANGELOG.md | 16 ++++++++++++++++ etc/module.xml | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8d3b26..80a9828 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ Todos los cambios notables a este proyecto serán documentados en este archivo. El formato está basado en [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) y este proyecto adhiere a [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +# [2.3.0] - 2024-10-04 + +Esta versión no tiene cambios en el comportamiento de las operaciones de la API. + +## Agrega: +- Se agrega la información de entorno para las transacciones de Webpay en la tabla de transacciones. + +## Actualiza: +- Se refina el flujo de pago de Webpay y Onelick. +- Se refina el flujo de envío de correo. +- Se homologan los comprobantes de pago de Oneclick y Webpay. +- Se aclara la información en caso de que de error la transacción de prueba en la pantalla de diagnóstico. + +## Borra: +- Se elimina la creación de variables dinámicas para eliminar advertencias en PHP 8. + # [2.2.1] - 2024-04-22 ## Fixed - Se corrige el valor de path_config para que sea aceptado desde las versiones 2.4.6 en adelante. diff --git a/etc/module.xml b/etc/module.xml index 9d5188d..d60cb89 100644 --- a/etc/module.xml +++ b/etc/module.xml @@ -1,6 +1,6 @@ - +