diff --git a/api/paymentmethods/response.php b/api/paymentmethods/response.php index fc8b69e5..aaf696de 100644 --- a/api/paymentmethods/response.php +++ b/api/paymentmethods/response.php @@ -17,6 +17,7 @@ require_once dirname(__FILE__) . '/../../library/logger.php'; require_once dirname(__FILE__) . '/../abstract.php'; require_once _PS_ROOT_DIR_ . '/modules/buckaroo3/vendor/autoload.php'; + use Buckaroo\BuckarooClient; use Buckaroo\Handlers\Reply\ReplyHandler; use Buckaroo\Transaction\Response\TransactionResponse; @@ -27,15 +28,11 @@ abstract class Response extends BuckarooAbstract { - // false if not received response private $received = false; - // true if validated and securety checked private $validated = false; - // request is test? private $test = true; private $signature; private $isPush; - // payment key public $payment; public $payment_method; public $statuscode; @@ -53,43 +50,36 @@ abstract class Response extends BuckarooAbstract public $brq_transaction_type; public $brq_relatedtransaction_partialpayment; public $brq_relatedtransaction_refund; - // transaction key public $transactions; - // if is errors, othervise = null public $parameterError; - protected ?TransactionResponse $response = null; + protected $logger; public function __construct(TransactionResponse $response = null) { + $this->logger = new Logger(Logger::INFO, 'response'); + $this->logger->logInfo("\n\n\n\n***************** Response start ***********************"); + if ($response) { $this->response = $response; + $this->logger->logInfo('Response object provided directly'); } else { $this->isPush = $this->isPushRequest(); $this->received = true; + $this->logger->logInfo('Response determined to be a push request'); $this->parsePushRequest(); } } - /** - * Get code required for payment - * - * @param string $configCode - * - * @return string - */ protected function getPaymentCode(string $configCode): string { - if ($configCode === 'Capayable') { - return 'in3'; - } - - return $configCode; + return $configCode === 'Capayable' ? 'in3' : $configCode; } private function parsePushRequest() { if (!$this->isPushRequest()) { + $this->logger->logInfo('Not a push request'); return false; } @@ -99,7 +89,6 @@ private function parsePushRequest() } elseif (Tools::getValue('brq_transaction_method')) { $this->payment_method = $this->getPaymentCode(Tools::getValue('brq_transaction_method')); } - $this->statuscode = $this->setPostVariable('brq_statuscode'); $this->statusmessage = $this->setPostVariable('brq_statusmessage'); $this->statuscode_detail = $this->setPostVariable('brq_statuscode_detail'); @@ -109,87 +98,66 @@ private function parsePushRequest() $this->invoice = $this->setPostVariable('brq_invoicenumber'); $this->invoicenumber = $this->setPostVariable('brq_invoicenumber'); $this->amount = $this->setPostVariable('brq_amount'); - if (Tools::getValue('brq_amount_credit')) { - $this->amount_credit = Tools::getValue('brq_amount_credit'); - } - + $this->amount_credit = $this->setPostVariable('brq_amount_credit'); $this->currency = $this->setPostVariable('brq_currency'); $this->test = $this->setPostVariable('brq_test'); $this->timestamp = $this->setPostVariable('brq_timestamp'); $this->transactions = $this->setPostVariable('brq_transactions'); $this->signature = $this->setPostVariable('brq_signature'); + $this->logger->logInfo('Parsed push request', [ + 'statuscode' => $this->statuscode, + 'statusmessage' => $this->statusmessage, + 'amount' => $this->amount, + 'currency' => $this->currency, + 'timestamp' => $this->timestamp + ]); + if (!empty($this->statuscode)) { - $responseArray = $this->responseCodes[(int) $this->statuscode]; + $responseArray = $this->responseCodes[(int)$this->statuscode]; $this->status = $responseArray['status']; $this->message = $responseArray['message']; } } - /** - * @return bool - */ public function isSuccess(): bool { return $this->response->isSuccess(); } - /** - * @return bool - */ public function isFailed(): bool { return $this->response->isFailed(); } - /** - * @return bool - */ public function isCanceled(): bool { return $this->response->isCanceled(); } - /** - * @return bool - */ public function isAwaitingConsumer(): bool { return $this->response->isAwaitingConsumer(); } - /** - * @return bool - */ public function isPendingProcessing(): bool { return $this->response->isPendingProcessing(); } - /** - * @return bool - */ public function isWaitingOnUserInput(): bool { return $this->response->isWaitingOnUserInput(); } - /** - * @return bool - */ public function isRejected(): bool { return $this->response->isRejected(); } - // Determine if is buckaroo response or push - private function isPushRequest() + private function isPushRequest(): bool { - if (Tools::getValue('brq_statuscode')) { - return true; - } - - return false; + return (bool)Tools::getValue('brq_statuscode'); } public function getServiceParameters() @@ -197,7 +165,27 @@ public function getServiceParameters() return $this->response->getServiceParameters(); } - public function hasSomeError() + public function getStatuscode() + { + return $this->response->statuscode; + } + + public function getStatusmessage() + { + return $this->response->statusmessage; + } + + public function getAmount() + { + return $this->response->amount; + } + + public function getBrqRelatedtransactionPartialpayment() + { + return $this->brq_relatedtransaction_partialpayment; + } + + public function hasSomeError(): bool { return $this->response->hasSomeError(); } @@ -207,12 +195,12 @@ public function getSomeError() return $this->response->getSomeError(); } - public function isTest() + public function isTest(): bool { return $this->response->get('IsTest') === true; } - public function isValid() + public function isValid(): bool { if (!$this->validated) { if ($this->isPush) { @@ -220,58 +208,60 @@ public function isValid() try { $reply_handler = new ReplyHandler($buckaroo->client()->config(), $_POST); $reply_handler->validate(); - - return $this->validated = $reply_handler->isValid(); + $this->validated = $reply_handler->isValid(); + $this->logger->logInfo('Push request validated successfully'); } catch (Exception $e) { + $this->logger->logError('Push request validation failed', ['exception' => $e->getMessage()]); } } elseif ($this->response) { - $this->validated = (!$this->response->isValidationFailure()); + $this->validated = !$this->response->isValidationFailure(); + $this->logger->logInfo('Response validation status', ['validated' => $this->validated]); } } return $this->validated; } - public function hasSucceeded() + public function hasSucceeded(): bool { if (isset($this->response)) { try { if ($this->isValid()) { if ($this->isPendingProcessing() || $this->isAwaitingConsumer() || $this->isWaitingOnUserInput() || $this->isSuccess()) { + $this->logger->logInfo('Response has succeeded'); return true; } } } catch (Exception $e) { + $this->logger->logError('Exception while checking success', ['exception' => $e->getMessage()]); } } elseif (in_array($this->status, [self::BUCKAROO_PENDING_PAYMENT, self::BUCKAROO_SUCCESS])) { + $this->logger->logInfo('Response status indicates success'); return true; } + $this->logger->logInfo('Response has not succeeded'); return false; } - public function isRedirectRequired() + public function isRedirectRequired(): bool { return $this->response->hasRedirect(); } - public function getRedirectUrl() + public function getRedirectUrl(): string { return $this->response->getRedirectUrl(); } - public function getResponse() + public function getResponse(): ?TransactionResponse { return $this->response; } private function setPostVariable($key) { - if (Tools::getValue($key)) { - return Tools::getValue($key); - } else { - return null; - } + return Tools::getValue($key) ?? null; } public function getCartIdAndReferenceId($show = false) @@ -283,14 +273,10 @@ public function getCartIdAndReferenceId($show = false) $cartId = 0; $reference = $this->invoicenumber; } - if ($show == 'cartId') { - return (int) $cartId; - } - - return $reference; + return $show == 'cartId' ? (int)$cartId : $reference; } - public function getCartId() + public function getCartId(): int { return $this->getCartIdAndReferenceId('cartId'); } @@ -299,4 +285,35 @@ public function getReferenceId() { return $this->getCartIdAndReferenceId('reference'); } + + public function isPartialPayment(): bool + { + return !empty($this->getGroupTransaction()); + } + + public function getRemainingAmount(): float + { + return $this->response->remaining_amount ?? 0; + } + + public function getGroupTransaction() + { + $data = $this->response->data(); + if (isset($data['RequiredAction']['PayRemainderDetails']['GroupTransaction'])) { + return $data['RequiredAction']['PayRemainderDetails']['GroupTransaction']; + } + return null; + } + + public function getRemainderAmount() + { + $data = $this->response->data(); + if (!isset($data['RequiredAction']['PayRemainderDetails']['RemainderAmount']) || + !is_scalar($data['RequiredAction']['PayRemainderDetails']['RemainderAmount']) + ) { + return 0; + } + return (float) $data['RequiredAction']['PayRemainderDetails']['RemainderAmount']; + } + } diff --git a/buckaroo3.php b/buckaroo3.php index 0720b057..a0ec7be5 100644 --- a/buckaroo3.php +++ b/buckaroo3.php @@ -449,6 +449,7 @@ public function hookPaymentOptions($params) 'methodsWithFinancialWarning' => $buckarooPaymentService->paymentMethodsWithFinancialWarning(), 'creditcardIssuers' => $buckarooConfigService->getActiveCreditCards(), 'creditCardDisplayMode' => $buckarooConfigService->getConfigValue('creditcard', 'display_type'), + 'giftCardDisplayMode' => $buckarooConfigService->getConfigValue('giftcard', 'display_in_checkout'), 'in3Method' => $this->get('buckaroo.classes.issuers.capayableIn3')->getMethod(), 'showIdealIssuers' => $buckarooConfigService->getConfigValue('ideal', 'show_issuers') ?? true, 'buckaroo_idin_test' => $buckarooConfigService->getConfigValue('idin', 'mode'), diff --git a/controllers/front/common.php b/controllers/front/common.php index 94ca17eb..8b3d2fd0 100644 --- a/controllers/front/common.php +++ b/controllers/front/common.php @@ -23,6 +23,10 @@ class BuckarooCommonController extends ModuleFrontController { + public function __construct() + { + parent::__construct(); + } private $id_order; protected function displayConfirmationTransfer($response) @@ -86,4 +90,12 @@ protected function displayError($invoicenumber = null, $error_message = null) $this->setTemplate('module:buckaroo3/views/templates/front/error.tpl'); } + + /** + * Method to initialize content, should be overridden in child classes + */ + public function initContent() + { + parent::initContent(); + } } diff --git a/controllers/front/request.php b/controllers/front/request.php index 487ac2dc..2252fb5d 100644 --- a/controllers/front/request.php +++ b/controllers/front/request.php @@ -28,84 +28,111 @@ class Buckaroo3RequestModuleFrontController extends BuckarooCommonController { - /* @var $checkout Checkout */ public $checkout; public $display_column_left = false; - /** @var bool */ public $display_column_right = false; + protected $logger; + + public function __construct() + { + parent::__construct(); + $this->logger = new Logger(Logger::INFO, 'request'); + } - /** - * @throws Exception - * - * @see FrontController::postProcess() - */ public function postProcess() { - $logger = new \Logger(CoreLogger::INFO, ''); - $logger->logInfo("\n\n\n\n***************** Request start ***********************"); + $this->logger->logInfo("\n\n\n\n***************** Request start ***********************"); + + if (!$this->context || !$this->context->cart) { + $this->logger->logError('Context or cart is not properly initialized.'); + Tools::redirect('index.php?controller=order&step=1'); + return; + } $cart = $this->context->cart; - $logger->logDebug('Get cart', $cart->id); if (!$this->isValidCart($cart)) { - $this->handleInvalidCart($logger, $cart); + $this->handleInvalidCart($cart); return; } - if (!$this->isValidConfiguration($logger)) { + if (!$this->isValidConfiguration()) { return; } - if (!$this->isAuthorized($logger)) { + if (!$this->isAuthorized()) { return; } $customer = new Customer($cart->id_customer); - if (!$this->isValidCustomer($logger, $customer)) { + if (!$this->isValidCustomer($customer)) { return; } $currency = $this->context->currency; + if (!$currency) { + $this->logger->logError('Currency is not set in context.'); + Tools::redirect('index.php?controller=order&step=1'); + return; + } + $total = (float)$cart->getOrderTotal(true, Cart::BOTH); $payment_method = Tools::getValue('method'); if (empty($payment_method)) { - $logger->logError('Load a method', 'Failed to load the method'); + $this->logger->logError('Load a method', 'Failed to load the method'); Tools::redirect('index.php?controller=order&step=1'); return; } $total = $this->applyBuckarooFee($payment_method, $total); - if (!$this->isValidService($logger)) { + if (!$this->isValidService()) { return; } $debug = 'Currency: ' . $currency->name . "\nTotal Amount: " . $total . "\nPayment Method: " . $payment_method; - $logger->logInfo('Checkout info', $debug); + $this->logger->logInfo('Checkout info', $debug); - $this->initializeCheckout($logger, $cart, $payment_method, $currency, $total, $customer); + $this->initializeCheckout($cart, $payment_method, $currency, $total, $customer); if ($this->checkout->isRequestSucceeded()) { - $this->handleSuccessfulRequest($logger, $cart->id, $customer); + $this->handleSuccessfulRequest($cart->id, $customer); } else { - $this->handleFailedRequest($logger, $cart->id); + $this->handleFailedRequest($cart->id); } } private function isValidCart($cart) { - return $cart->id_customer != 0 && $cart->id_address_delivery != 0 && $cart->id_address_invoice != 0 && $this->module->active; + if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) { + return false; + } + + if (Order::getOrderByCartId($cart->id)) { + $oldCart = new Cart($cart->id); + $duplication = $oldCart->duplicate(); + if ($duplication && Validate::isLoadedObject($duplication['cart']) && $duplication['success']) { + $this->context->cookie->id_cart = $duplication['cart']->id; + $this->context->cart = $duplication['cart']; + $this->context->cookie->write(); + return true; + } else { + return false; + } + } + + return true; } - private function handleInvalidCart($logger, $cart) + private function handleInvalidCart($cart) { $debug = 'Customer Id: ' . $cart->id_customer . "\nDelivery Address ID: " . $cart->id_address_delivery . 'Invoice Address ID: ' . $cart->id_address_invoice . "\nModule Active: " . $this->module->active; - $logger->logError('Validation Error', $debug); + $this->logger->logError('Validation Error', $debug); Tools::redirect('index.php?controller=order&step=1'); } - private function isValidConfiguration($logger) + private function isValidConfiguration() { $merchantKey = Configuration::get('BUCKAROO_MERCHANT_KEY'); $secretKey = Configuration::get('BUCKAROO_SECRET_KEY'); @@ -117,21 +144,21 @@ private function isValidConfiguration($logger) return true; } - private function isAuthorized($logger) + private function isAuthorized() { foreach (PaymentModule::getInstalledPaymentModules() as $module) { if ($module['name'] == 'buckaroo3') { return true; } } - $logger->logError('Authorization Error', 'This payment method is not available.'); + $this->logger->logError('Authorization Error', 'This payment method is not available.'); exit($this->module->l('This payment method is not available.', 'validation')); } - private function isValidCustomer($logger, $customer) + private function isValidCustomer($customer) { if (!Validate::isLoadedObject($customer)) { - $logger->logError('Load a customer', 'Failed to load the customer with ID: ' . $cart->id_customer); + $this->logger->logError('Load a customer', 'Failed to load the customer with ID: ' . $customer->id); Tools::redirect('index.php?controller=order&step=1'); return false; } @@ -150,62 +177,70 @@ private function applyBuckarooFee($payment_method, $total) return $total; } - private function isValidService($logger) + private function isValidService() { if (Tools::getValue('service') && Tools::getValue('service') != 'digi' && Tools::getValue('service') != 'sepa') { - $logger->logError('Load a method', 'Failed to load the method'); + $this->logger->logError('Load a method', 'Failed to load the method'); Tools::redirect('index.php?controller=order&step=1'); return false; } return true; } - private function initializeCheckout($logger, $cart, $payment_method, $currency, $total, $customer) + private function initializeCheckout($cart, $payment_method, $currency, $total, $customer) { try { $this->checkout = Checkout::getInstance($payment_method, $cart, $this->context); $this->setCheckoutProperties(); $this->setCheckoutUrls(); } catch (Exception $e) { - $logger->logError('Set checkout info: ', $e->getMessage()); + $this->logger->logError('Set checkout info: ', $e->getMessage()); $this->displayError(null, $e->getMessage()); return; } - $logger->logDebug('Get checkout class: '); $pending = Configuration::get('BUCKAROO_ORDER_STATE_DEFAULT'); $payment_method_tr = (new RawPaymentMethodRepository())->getPaymentMethodsLabel($payment_method); - if (!$this->checkout->isVerifyRequired()) { - $this->module->validateOrder( - (int) $cart->id, - $pending, - (float) $total, - $payment_method_tr, - null, - null, - (int) $currency->id, - false, - $customer->secure_key - ); + $id_order_cart = Order::getIdByCartId($cart->id); + if (!$id_order_cart) { + if (!$this->checkout->isVerifyRequired()) { + try { + $this->module->validateOrder( + (int) $cart->id, + $pending, + (float) $total, + $payment_method_tr, + null, + null, + (int) $currency->id, + false, + $customer->secure_key + ); + } catch (Exception $e) { + $this->logger->logError('Order validation failed: ', $e->getMessage()); + $this->displayError(null, $e->getMessage()); + return; + } + } + } else { + $this->module->currentOrder = $id_order_cart; } - $id_order_cart = Order::getIdByCartId($cart->id); - $order = new Order($id_order_cart); + $order = new Order($this->module->currentOrder); $this->checkout->setReference($order->reference); try { $this->checkout->setCheckout(); - $logger->logDebug('Set checkout info: '); if ($this->checkout->isVerifyRequired()) { - $logger->logInfo('Start verify process'); + $this->logger->logInfo('Start verify process'); $this->checkout->startVerify(['cid' => $cart->id_customer]); } else { - $logger->logInfo('Start the payment process'); + $this->logger->logInfo('Start the payment process'); $this->checkout->startPayment(); } } catch (Exception $e) { - $logger->logError('Set checkout info: ', $e->getMessage()); + $this->logger->logError('Set checkout info: ', $e->getMessage()); $this->displayError(null, $e->getMessage()); return; } @@ -222,34 +257,32 @@ private function setCheckoutProperties() private function setCheckoutUrls() { - $this->checkout->returnUrl = 'http' . ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . __PS_BASE_URI__ . 'index.php?fc=module&module=buckaroo3&controller=userreturn'; // phpcs:ignore + $this->checkout->returnUrl = 'http' . ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . __PS_BASE_URI__ . 'index.php?fc=module&module=buckaroo3&controller=userreturn'; $this->checkout->pushUrl = 'http' . ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . __PS_BASE_URI__ . 'index.php?fc=module&module=buckaroo3&controller=return'; } - private function handleSuccessfulRequest($logger, $cartId, $customer) + private function handleSuccessfulRequest($cartId, $customer) { $response = $this->checkout->getResponse(); - $logger->logInfo('Request succeeded'); + $this->logger->logInfo('Request succeeded'); if ($this->checkout->isRedirectRequired()) { $this->setCartCookie($cartId); - $logger->logInfo('Redirecting ... '); + $this->logger->logInfo('Redirecting ... '); $this->checkout->doRedirect(); exit; } - $logger->logDebug('Checkout response', $response); - if ($response->hasSucceeded()) { - $this->processSuccessfulPayment($logger, $cartId, $customer, $response); + $this->processSuccessfulPayment($cartId, $customer, $response); } else { - $this->processFailedPayment($logger, $cartId, $response); + $this->processFailedPayment($cartId, $response); } } - private function processSuccessfulPayment($logger, $cartId, $customer, $response) + private function processSuccessfulPayment($cartId, $customer, $response) { - $logger->logInfo('Payment request succeeded. Wait push message!'); + $this->logger->logInfo('Payment request succeeded. Wait push message!'); $id_order = $this->module->currentOrder; $responseData = $response->getResponse(); @@ -263,9 +296,14 @@ private function processSuccessfulPayment($logger, $cartId, $customer, $response $this->context->cookie->__set('HtmlText', $response->consumerMessage['HtmlText']); } - Tools::redirect( - 'index.php?controller=order-confirmation&id_cart=' . $cartId . '&id_module=' . $this->module->id . '&id_order=' . $id_order . '&key=' . $customer->secure_key . '&success=true&response_received=' . $response->payment_method // phpcs:ignore - ); + Tools::redirect($this->context->link->getPageLink('order-confirmation', true, null, [ + 'id_cart' => $cartId, + 'id_module' => $this->module->id, + 'id_order' => $id_order, + 'key' => $customer->secure_key, + 'success' => 'true', + 'response_received' => $response->payment_method + ])); } private function processSepaDirectDebit($id_order, $responseData) @@ -279,15 +317,15 @@ private function processSepaDirectDebit($id_order, $responseData) } } - private function processFailedPayment($logger, $cartId, $response) + private function processFailedPayment($cartId, $response) { - $logger->logInfo('Payment request failed/canceled'); + $this->logger->logInfo('Payment request failed/canceled'); $this->setCartCookie($cartId); if ($response->isValid()) { - $this->updateOrderHistory($logger, $response); + $this->updateOrderHistory($response); } else { - $logger->logInfo('Payment request not valid'); + $this->logger->logInfo('Payment request not valid'); } $error = null; @@ -297,21 +335,21 @@ private function processFailedPayment($logger, $cartId, $response) $this->displayError(null, $error); } - private function updateOrderHistory($logger, $response) + private function updateOrderHistory($response) { - $logger->logInfo('Payment request valid'); + $this->logger->logInfo('Payment request valid'); $id_order = Order::getOrderByCartId($response->getCartId()); if ($id_order) { - $this->updateOrderStatus($logger, $response, $id_order); + $this->updateOrderStatus($response, $id_order); } else { - $logger->logInfo('Find order by cart ID', 'Order not found.'); + $this->logger->logInfo('Find order by cart ID', 'Order not found.'); } } - private function updateOrderStatus($logger, $response, $id_order) + private function updateOrderStatus($response, $id_order) { - $logger->logInfo('Find order by cart ID', 'Order found. ID: ' . $id_order); - $logger->logInfo('Update order history with status: ' . Buckaroo3::resolveStatusCode($response->status)); + $this->logger->logInfo('Find order by cart ID', 'Order found. ID: ' . $id_order); + $this->logger->logInfo('Update order history with status: ' . Buckaroo3::resolveStatusCode($response->status)); $order = new Order($id_order); $new_status_code = Buckaroo3::resolveStatusCode($response->status); @@ -327,10 +365,10 @@ private function updateOrderStatus($logger, $response, $id_order) } } - private function handleFailedRequest($logger, $cartId) + private function handleFailedRequest($cartId) { $response = $this->checkout->getResponse(); - $logger->logInfo('Request not succeeded'); + $this->logger->logInfo('Request not succeeded'); $this->setCartCookie($cartId); @@ -361,6 +399,8 @@ private function setCartCookie($cartId) if ($duplication && Validate::isLoadedObject($duplication['cart']) && $duplication['success']) { $this->context->cookie->id_cart = $duplication['cart']->id; $this->context->cookie->write(); + } else { + $this->logger->logError('Cart duplication failed'); } } -} +} \ No newline at end of file diff --git a/controllers/front/return.php b/controllers/front/return.php index 3851b00a..516aff37 100644 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -28,13 +28,14 @@ class Buckaroo3ReturnModuleFrontController extends BuckarooCommonController { public $ssl = true; - private $symContainer; + protected $logger; public function __construct() { parent::__construct(); $this->setContainer(); + $this->logger = new Logger(Logger::INFO, 'return'); } /** @@ -44,8 +45,7 @@ public function initContent() { $this->display_column_left = false; $this->display_column_right = false; - $logger = new Logger(Logger::INFO, 'return'); - $logger->logInfo("\n\n\n\n***************** Return start ***********************"); + $this->logger->logInfo("\n\n\n\n***************** Return start ***********************"); parent::initContent(); @@ -54,11 +54,12 @@ public function initContent() foreach ($tmp as $stat) { $statuses[$stat['id_order_state']] = $stat['name']; } + $response = ResponseFactory::getResponse(); - $logger->logInfo('Parse response', $response); + $this->logger->logInfo('Parse response', $response); if ($response->isValid()) { - $logger->logInfo('Response valid'); + $this->logger->logInfo('Response valid'); if (!empty($response->payment_method) && ($response->payment_method == 'paypal') && !empty($response->statuscode) @@ -75,9 +76,11 @@ public function initContent() $row = get_object_vars($order); $references[] = $row['reference']; } - $logger->logInfo('Get order by cart id', 'Order ID: ' . $id_order); + + $this->logger->logInfo('Get order by cart id', 'Order ID: ' . $id_order); + if ($response->brq_relatedtransaction_partialpayment != null) { - $logger->logInfo('PUSH', 'Partial payment PUSH received ' . $response->status); + $this->logger->logInfo('PUSH', 'Partial payment PUSH received ' . $response->status); if ($id_order && $response->hasSucceeded()) { $order = new Order($id_order); $order->setInvoice(false); @@ -87,26 +90,19 @@ public function initContent() $payment->transaction_id = $response->transactions; $payment->amount = urldecode($response->amount); $payment->payment_method = $response->payment_method; - if ($payment->id_currency == $order->id_currency) { - $order->total_paid_real += $response->amount; - } else { - $order->total_paid_real += Tools::ps_round( - Tools::convertPrice($response->amount, $payment->id_currency, false), - 2 - ); - } + $order->total_paid_real += $response->amount; $order->save(); $payment->conversion_rate = 1; $payment->save(); Db::getInstance()->execute( ' - INSERT INTO `' . _DB_PREFIX_ . 'order_invoice_payment` - VALUES(' . (int) $order->invoice_number . ', ' . (int) $payment->id . ', ' . (int) $order->id . ')' + INSERT INTO `' . _DB_PREFIX_ . 'order_invoice_payment` + VALUES(' . (int)$order->invoice_number . ', ' . (int)$payment->id . ', ' . (int)$order->id . ')' ); $message = new Message(); $message->id_order = $id_order; - $message->message = 'Buckaroo partial payment message (' . $response->transactions . '): ' . $response->statusmessage; // phpcs:ignore + $message->message = 'Buckaroo partial payment message (' . $response->transactions . '): ' . $response->statusmessage; $message->add(); } exit; @@ -122,42 +118,43 @@ public function initContent() 'Buckaroo refund message (' . $response->transactions . '): ' . $response->statusmessage ); } catch (\Throwable $th) { - $logger->logInfo('PUSH', (string) $th); + $this->logger->logInfo('PUSH', (string)$th); } exit; } + if (!$id_order) { header('HTTP/1.1 503 Service Unavailable'); - echo 'Order do not exists'; - $logger->logInfo('PUSH', 'Order do not exists'); + echo 'Order does not exist'; + $this->logger->logError('PUSH', 'Order does not exist'); exit; } else { - $logger->logInfo('Update the order', 'Order ID: ' . $id_order); + $this->logger->logInfo('Update the order', 'Order ID: ' . $id_order); $new_status_code = Buckaroo3::resolveStatusCode($response->status, $id_order); - $order = new Order($id_order); if (!in_array($order->reference, $references)) { header('HTTP/1.1 503 Service Unavailable'); - $logger->logInfo('Order not in reference ' . $order->reference); + $this->logger->logError('Order not in reference ' . $order->reference); echo 'Order not in reference: ' . $order->reference; exit; } - $logger->logInfo( - 'Old order status code: ' . $order->getCurrentState( - ) . '; new order status code: ' . $new_status_code + $this->logger->logInfo( + 'Old order status code: ' . $order->getCurrentState() . '; new order status code: ' . $new_status_code ); + $pending = Configuration::get('BUCKAROO_ORDER_STATE_DEFAULT'); $canceled = Configuration::get('BUCKAROO_ORDER_STATE_FAILED'); $error = Configuration::get('PS_OS_ERROR'); $outofstock_unpaid = Configuration::get('PS_OS_OUTOFSTOCK_UNPAID'); + if ($new_status_code != $order->getCurrentState() - && ($pending == $order->getCurrentState() || $canceled == $order->getCurrentState( - ) || $error == $order->getCurrentState() || $outofstock_unpaid == $order->getCurrentState()) + && ($pending == $order->getCurrentState() || $canceled == $order->getCurrentState() + || $error == $order->getCurrentState() || $outofstock_unpaid == $order->getCurrentState()) ) { - $logger->logInfo('Update order status'); + $this->logger->logInfo('Update order status'); $history = new OrderHistory(); $history->id_order = $id_order; $history->date_add = date('Y-m-d H:i:s'); @@ -171,23 +168,25 @@ public function initContent() $payment->amount = 0; $payment->update(); } - /* @var $payment OrderPaymentCore */ if ($payment->amount == $response->amount && $payment->transaction_id == '') { $payment->transaction_id = $response->transactions; $payment->update(); } } } else { - $logger->logInfo('Order status not updated'); + $this->logger->logInfo('Order status not updated'); } + $statusCodeName = $new_status_code; if (!empty($statuses[$new_status_code])) { $statusCodeName = $statuses[$new_status_code]; } + $message = new Message(); $message->id_order = $id_order; - $message->message = 'Push message recieved. Buckaroo status: ' . $statusCodeName . '. Transaction key: ' . $response->transactions; // phpcs:ignore + $message->message = 'Push message received. Buckaroo status: ' . $statusCodeName . '. Transaction key: ' . $response->transactions; $message->add(); + if ($response->statusmessage) { $message = new Message(); $message->id_order = $id_order; @@ -197,7 +196,7 @@ public function initContent() } } else { header('HTTP/1.1 503 Service Unavailable'); - $logger->logError('Payment response not valid', $response); + $this->logger->logError('Payment response not valid', $response); echo 'Payment response not valid'; exit; } @@ -233,4 +232,4 @@ private function setContainer() } $this->symContainer = $kernel->getContainer(); } -} +} \ No newline at end of file diff --git a/controllers/front/userreturn.php b/controllers/front/userreturn.php index 535d9850..e25ebd90 100644 --- a/controllers/front/userreturn.php +++ b/controllers/front/userreturn.php @@ -25,6 +25,13 @@ class Buckaroo3UserreturnModuleFrontController extends BuckarooCommonController { public $ssl = true; + protected $logger; + + public function __construct() + { + parent::__construct(); + $this->logger = new Logger(Logger::INFO, 'userreturn'); + } /** * @see FrontController::initContent() @@ -32,12 +39,12 @@ class Buckaroo3UserreturnModuleFrontController extends BuckarooCommonController public function initContent() { $cookie = new Cookie('ps'); - $logger = new Logger(Logger::INFO, 'return'); + $this->logger->logInfo("\n\n\n\n***************** User return start ***********************"); $response = ResponseFactory::getResponse(); - $logger->logDebug('Checkout response', $response); + if ($response->isValid()) { - $logger->logInfo('Payment request succeeded'); + $this->logger->logInfo('Payment request succeeded'); if (!empty($response->payment_method) && ($response->payment_method == 'paypal') @@ -49,12 +56,14 @@ public function initContent() } $id_order = Order::getOrderByCartId($response->getCartId()); - $logger->logInfo('Update the order', 'Order ID: ' . $id_order); + $this->logger->logInfo('Update the order', 'Order ID: ' . $id_order); + if ($response->hasSucceeded()) { $cart = new Cart($response->getCartId()); $customer = new Customer($cart->id_customer); + if (!Validate::isLoadedObject($customer)) { - $logger->logError('Load a customer', 'Failed to load the customer with ID: ' . $cart->id_customer); + $this->logger->logError('Load a customer', 'Failed to load the customer with ID: ' . $cart->id_customer); Tools::redirect('index.php?controller=order&step=1'); exit; } @@ -67,19 +76,22 @@ public function initContent() 'key' => $customer->secure_key, 'success' => 'true', ]); + $this->logger->logInfo('Redirecting to order confirmation', ['url' => $redirectUrl]); Tools::redirect($redirectUrl); } else { $cookie->statusMessage = ''; if (($response->payment_method == 'afterpayacceptgiro' - || $response->payment_method == 'afterpaydigiaccept') + || $response->payment_method == 'afterpaydigiaccept') && $response->statusmessage) { $cookie->statusMessage = $response->statusmessage; } + $this->logger->logError('Payment failed', ['statusMessage' => $cookie->statusMessage]); Tools::redirect('index.php?fc=module&module=buckaroo3&controller=error'); exit; } } else { $cookie->statusMessage = 'Not valid response'; + $this->logger->logError('Invalid payment response'); Tools::redirect('index.php?fc=module&module=buckaroo3&controller=error'); } exit; diff --git a/dev/src/components/payments/CreditCardPaymentConfig.vue b/dev/src/components/payments/CreditCardPaymentConfig.vue index 63ac0227..f274d4b9 100644 --- a/dev/src/components/payments/CreditCardPaymentConfig.vue +++ b/dev/src/components/payments/CreditCardPaymentConfig.vue @@ -76,11 +76,11 @@ export default { }) - return { - config, - displayInCheckout, - displayOptions - } + return { + config, + displayInCheckout, + displayOptions + } } } diff --git a/dev/src/components/payments/GiftcardPaymentConfig.vue b/dev/src/components/payments/GiftcardPaymentConfig.vue index 0d02f68c..2b9e4a3b 100644 --- a/dev/src/components/payments/GiftcardPaymentConfig.vue +++ b/dev/src/components/payments/GiftcardPaymentConfig.vue @@ -1,13 +1,31 @@