From dd7e5fd94ca0ffc2bf8dffa923cfebf45129dae0 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Tue, 12 Dec 2023 10:00:57 +0200 Subject: [PATCH 01/18] feat: added option in back office and upgrade method --- changelog.md | 3 ++ ...dminSaferPayOfficialSettingsController.php | 11 ++++++ saferpayofficial.php | 2 +- src/Config/SaferPayConfig.php | 3 ++ upgrade/install-1.2.0.php | 35 +++++++++++++++++++ 5 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 upgrade/install-1.2.0.php diff --git a/changelog.md b/changelog.md index 2f93b3c2..e710fd77 100755 --- a/changelog.md +++ b/changelog.md @@ -144,3 +144,6 @@ ## [1.1.7] - * - BO : Added PrestaShop module security validations - FO : Added PrestaShop module security validations +- +- ## [1.2.0] - * +- BO : TODO diff --git a/controllers/admin/AdminSaferPayOfficialSettingsController.php b/controllers/admin/AdminSaferPayOfficialSettingsController.php index 7eaad21a..793348dc 100755 --- a/controllers/admin/AdminSaferPayOfficialSettingsController.php +++ b/controllers/admin/AdminSaferPayOfficialSettingsController.php @@ -267,6 +267,17 @@ public function initOptions() 'desc' => $this->l('If set to true, the refund will be rejected if the sum of authorized refunds exceeds the capture value.'), 'form_group_class' => 'thumbs_chose', ], + SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION => [ + 'type' => 'radio', + 'title' => $this->l('Order creation rule'), + 'validation' => 'isInt', + 'choices' => [ + 1 => $this->l('After authorization'), + 0 => $this->l('Before authorization'), + ], + 'desc' => $this->l('If set to true, the refund will be rejected if the sum of authorized refunds exceeds the capture value.'), + 'form_group_class' => 'thumbs_chose', + ], ], 'buttons' => [ 'save_and_connect' => [ diff --git a/saferpayofficial.php b/saferpayofficial.php index a3d5fb1e..4aa213ad 100755 --- a/saferpayofficial.php +++ b/saferpayofficial.php @@ -40,7 +40,7 @@ public function __construct($name = null) { $this->name = 'saferpayofficial'; $this->author = 'Invertus'; - $this->version = '1.1.7'; + $this->version = '1.2.0'; $this->module_key = '3d3506c3e184a1fe63b936b82bda1bdf'; $this->displayName = 'SaferpayOfficial'; $this->description = 'Saferpay Payment module'; diff --git a/src/Config/SaferPayConfig.php b/src/Config/SaferPayConfig.php index 3aef29da..a317be2a 100755 --- a/src/Config/SaferPayConfig.php +++ b/src/Config/SaferPayConfig.php @@ -221,6 +221,7 @@ class SaferPayConfig const SAFERPAY_PAYMENT_AUTHORIZATION_FAILED = 'SAFERPAY_PAYMENT_AUTHORIZATION_FAILED'; const SAFERPAY_SEND_ORDER_CONFIRMATION = 'SAFERPAY_SEND_ORDER_CONFIRMATION'; const SAFERPAY_SEND_NEW_ORDER_MAIL = 'SAFERPAY_SEND_NEW_ORDER_MAIL'; + const SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION = 'SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION'; const STATUS_PS_OS_OUTOFSTOCK_PAID = 'PS_OS_OUTOFSTOCK_PAID'; @@ -338,6 +339,7 @@ public static function getDefaultConfiguration() SaferPayConfig::SAFERPAY_SEND_ORDER_CONFIRMATION => 1, SaferPayConfig::FIELDS_LIBRARY => self::FIELDS_LIBRARY_DEFAULT_VALUE, SaferPayConfig::FIELDS_LIBRARY . SaferPayConfig::TEST_SUFFIX => self::FIELDS_LIBRARY_TEST_DEFAULT_VALUE, + self::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION => 0, self::TEST_MODE => 1, self::HOSTED_FIELDS_TEMPLATE => self::HOSTED_FIELDS_TEMPLATE_DEFAULT, self::SAFERPAY_ORDER_STATE_CHOICE_AWAITING_PAYMENT => Configuration::get( @@ -374,6 +376,7 @@ public static function getUninstallConfiguration() self::FIELDS_ACCESS_TOKEN . self::TEST_SUFFIX, self::FIELDS_LIBRARY, self::FIELDS_LIBRARY . self::TEST_SUFFIX, + self::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION ]; } diff --git a/upgrade/install-1.2.0.php b/upgrade/install-1.2.0.php new file mode 100644 index 00000000..972d3a50 --- /dev/null +++ b/upgrade/install-1.2.0.php @@ -0,0 +1,35 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +use Invertus\SaferPay\Config\SaferPayConfig; +use Invertus\SaferPay\DTO\Request\RequestHeader; + +if (!defined('_PS_VERSION_')) { + exit; +} +function upgrade_module_1_2_0($module) +{ + Configuration::updateValue(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION, 0); + return true; +} + From b54232427d36b4f392435a38ba535e68f8393f00 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Wed, 13 Dec 2023 14:12:09 +0200 Subject: [PATCH 02/18] initial changes for new functionality --- ...dminSaferPayOfficialSettingsController.php | 2 +- controllers/front/ajax.php | 10 ++++---- controllers/front/iframe.php | 1 + controllers/front/notify.php | 1 + controllers/front/return.php | 12 ++++++---- controllers/front/validation.php | 24 ++++++++++--------- src/Service/Request/RequestObjectCreator.php | 7 ++++-- src/Service/SaferPayInitialize.php | 6 +++-- 8 files changed, 39 insertions(+), 24 deletions(-) diff --git a/controllers/admin/AdminSaferPayOfficialSettingsController.php b/controllers/admin/AdminSaferPayOfficialSettingsController.php index 793348dc..a28d6fc1 100755 --- a/controllers/admin/AdminSaferPayOfficialSettingsController.php +++ b/controllers/admin/AdminSaferPayOfficialSettingsController.php @@ -275,7 +275,7 @@ public function initOptions() 1 => $this->l('After authorization'), 0 => $this->l('Before authorization'), ], - 'desc' => $this->l('If set to true, the refund will be rejected if the sum of authorized refunds exceeds the capture value.'), + 'desc' => $this->l('TODO'), 'form_group_class' => 'thumbs_chose', ], ], diff --git a/controllers/front/ajax.php b/controllers/front/ajax.php index fc57d049..fb574610 100755 --- a/controllers/front/ajax.php +++ b/controllers/front/ajax.php @@ -41,12 +41,13 @@ public function postProcess() } } - private function submitHostedFields() + private function submitHostedFields(): void { try { - if (!Order::getOrderByCartId($this->context->cart->id)) { - $this->validateOrder(); - } + //todo do not create yet here if setting is true +// if (!Order::getOrderByCartId($this->context->cart->id)) { +// $this->validateOrder(); +// } /** @var SaferPayCardAliasRepository $cardAliasRep */ $cardAliasRep = $this->module->getService(SaferPayCardAliasRepository::class); @@ -71,6 +72,7 @@ private function submitHostedFields() $redirectUrl = $this->getRedirectionToControllerUrl('successHosted'); } + //todo create here an order if setting is true $this->ajaxDie(json_encode([ 'error' => false, 'url' => $redirectUrl, diff --git a/controllers/front/iframe.php b/controllers/front/iframe.php index 53a9659f..d5b0bbd3 100755 --- a/controllers/front/iframe.php +++ b/controllers/front/iframe.php @@ -80,6 +80,7 @@ public function postProcess() $orderId = Order::getOrderByCartId($cart->id); if (!$orderId) { $paymentMethod = Tools::getValue('saved_card_method'); + $this->module->validateOrder( $cart->id, Configuration::get(SaferPayConfig::SAFERPAY_ORDER_STATE_CHOICE_AWAITING_PAYMENT), diff --git a/controllers/front/notify.php b/controllers/front/notify.php index ce55cc26..9a5367ea 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -93,6 +93,7 @@ public function postProcess() ) { $orderStatusService->capture($order); } + } catch (Exception $e) { PrestaShopLogger::addLog( sprintf( diff --git a/controllers/front/return.php b/controllers/front/return.php index 80e18760..9d9b9398 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -45,8 +45,7 @@ public function postProcess() $fieldToken = Tools::getValue('fieldToken'); $moduleId = $this->module->id; $selectedCard = Tools::getValue('selectedCard'); - - $orderId = Order::getOrderByCartId($cartId); + $orderId = Tools::getValue('orderId'); $cart = new Cart($cartId); @@ -65,7 +64,12 @@ public function postProcess() } try { - $this->assertTransaction($orderId); + if ($orderId) { + $this->assertTransactionByOrderId($orderId); + } else { + $this->assertTransactionByCartId($cartId); + //todo if assertion is good create order + } Tools::redirect($this->context->link->getModuleLink( $this->module->name, @@ -106,7 +110,7 @@ public function postProcess() * @return AssertBody * @throws Exception */ - private function assertTransaction($orderId) + private function assertTransactionByOrderId($orderId) { /** @var SaferPayTransactionAssertion $transactionAssert */ $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); diff --git a/controllers/front/validation.php b/controllers/front/validation.php index 7a11958b..d4071b67 100755 --- a/controllers/front/validation.php +++ b/controllers/front/validation.php @@ -79,8 +79,7 @@ public function postProcess() $currency = $this->context->currency; $total = (float) $cart->getOrderTotal(); - $orderId = Order::getOrderByCartId($cart->id); - if (!$orderId) { + if (!(int) Configuration::get(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION)) { $this->module->validateOrder( $cart->id, Configuration::get(SaferPayConfig::SAFERPAY_ORDER_STATE_CHOICE_AWAITING_PAYMENT), @@ -116,15 +115,18 @@ public function postProcess() ); $this->redirectWithNotifications($redirectLink); } - /** @var Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder $saferPayOrderBuilder */ - $saferPayOrderBuilder = $this->module->getService(\Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder::class); - $saferPayOrderBuilder->create( - $initializeBody, - $this->context->cart, - $this->context->customer, - false, - $isBusinessLicence - ); + if (!(int) Configuration::get(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION)) { + /** @var Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder $saferPayOrderBuilder */ + $saferPayOrderBuilder = $this->module->getService(\Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder::class); + + $saferPayOrderBuilder->create( + $initializeBody, + $this->context->cart, + $this->context->customer, + false, + $isBusinessLicence + ); + } Tools::redirect($initializeBody->RedirectUrl); } diff --git a/src/Service/Request/RequestObjectCreator.php b/src/Service/Request/RequestObjectCreator.php index 72cb3d70..4c7a26e2 100755 --- a/src/Service/Request/RequestObjectCreator.php +++ b/src/Service/Request/RequestObjectCreator.php @@ -111,13 +111,16 @@ public function createPayment(Cart $cart, $totalPrice) /** @var \Order|null $order */ $order = $this->orderRepository->findOneByCartId($cart->id); - if (empty($order)) { + if (!(int) \Configuration::get(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION) && empty($order)) { return null; } + $payment = new Payment(); $payment->setValue($totalPrice); $payment->setCurrencyCode($currency['iso_code']); - $payment->setOrderReference($order->reference); + + //todo what is the reference ?? todo recommended + $payment->setOrderReference('random'); return $payment; } diff --git a/src/Service/SaferPayInitialize.php b/src/Service/SaferPayInitialize.php index bf6368d7..5dc94ae9 100755 --- a/src/Service/SaferPayInitialize.php +++ b/src/Service/SaferPayInitialize.php @@ -31,6 +31,7 @@ use Invertus\SaferPay\Exception\Api\SaferPayApiException; use Invertus\SaferPay\Factory\ModuleFactory; use Invertus\SaferPay\Service\Request\InitializeRequestObjectCreator; +use Invertus\SaferPay\Config\SaferPayConfig; use Order; use SaferPayOfficial; @@ -81,6 +82,7 @@ public function initialize( ) { $customerEmail = $this->context->customer->email; $cartId = $this->context->cart->id; + $createAfterAuthorization = (int) \Configuration::get(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION); $returnUrl = $this->context->link->getModuleLink( $this->module->name, @@ -88,7 +90,7 @@ public function initialize( [ 'cartId' => $cartId, 'secureKey' => $this->context->cart->secure_key, - 'orderId' => Order::getOrderByCartId($cartId), + 'orderId' => $createAfterAuthorization ? 0 : Order::getOrderByCartId($cartId), 'moduleId' => $this->module->id, 'selectedCard' => $selectedCard, 'isBusinessLicence' => $isBusinessLicence, @@ -103,7 +105,7 @@ public function initialize( [ 'success' => 1, 'cartId' => $this->context->cart->id, - 'orderId' => Order::getOrderByCartId($cartId), + 'orderId' => $createAfterAuthorization ? 0 : Order::getOrderByCartId($cartId), 'secureKey' => $this->context->cart->secure_key, ], true From 304870c66502aeb4478832f8d5731c7e5bde9406 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Thu, 14 Dec 2023 17:47:57 +0200 Subject: [PATCH 03/18] return controller fixed --- controllers/front/ajax.php | 99 ++++------------ controllers/front/fail.php | 1 + controllers/front/iframe.php | 61 ++++------ controllers/front/notify.php | 28 ++--- controllers/front/return.php | 31 ++--- controllers/front/validation.php | 63 ++++------ src/Adapter/Configuration.php | 109 ++++++++++++++++++ src/Adapter/LegacyContext.php | 5 + .../Front/PaymentFrontController.php | 99 ++++++++++++++++ src/Entity/SaferPayOrder.php | 5 +- src/EntityBuilder/SaferPayOrderBuilder.php | 10 +- src/Processor/CheckoutProcessor.php | 96 +++++++++++++++ src/Repository/SaferPayOrderRepository.php | 9 ++ .../Request/AssertRequestObjectCreator.php | 4 +- src/Service/Request/RequestObjectCreator.php | 8 +- src/Service/SaferPayInitialize.php | 85 +++++++++++--- .../SaferPayTransactionAssertion.php | 17 +-- upgrade/install-1.2.0.php | 17 +++ 18 files changed, 520 insertions(+), 227 deletions(-) create mode 100644 src/Adapter/Configuration.php create mode 100644 src/Controller/Front/PaymentFrontController.php create mode 100644 src/Processor/CheckoutProcessor.php diff --git a/controllers/front/ajax.php b/controllers/front/ajax.php index fb574610..0942d465 100755 --- a/controllers/front/ajax.php +++ b/controllers/front/ajax.php @@ -22,7 +22,7 @@ */ use Invertus\SaferPay\Config\SaferPayConfig; -use Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder; +use Invertus\SaferPay\Controller\Front\PaymentFrontController; use Invertus\SaferPay\Repository\SaferPayCardAliasRepository; use Invertus\SaferPay\Service\SaferPayInitialize; @@ -32,6 +32,11 @@ class SaferPayOfficialAjaxModuleFrontController extends ModuleFrontController { + const FILE_NAME = 'ajax'; + + /** @var SaferPayOfficial */ + public $module; + public function postProcess() { switch (Tools::getValue('action')) { @@ -44,35 +49,33 @@ public function postProcess() private function submitHostedFields(): void { try { - //todo do not create yet here if setting is true -// if (!Order::getOrderByCartId($this->context->cart->id)) { -// $this->validateOrder(); -// } - - /** @var SaferPayCardAliasRepository $cardAliasRep */ - $cardAliasRep = $this->module->getService(SaferPayCardAliasRepository::class); - - $selectedCard = Tools::getValue('selectedCard'); - - $alias = $cardAliasRep->getSavedCardAliasFromId($selectedCard); + /** @var PaymentFrontController $paymentFrontController */ + $paymentFrontController = $this->module->getService(PaymentFrontController::class); + + if (Order::getOrderByCartId($this->context->cart->id)) { + $this->ajaxDie(json_encode([ + 'error' => true, + 'message' => $this->module->l('Order already exists', self::FILE_NAME), + 'url' => $this->getRedirectionToControllerUrl('fail'), + ])); + } - /** @var SaferPayInitialize $initializeService */ - $initializeService = $this->module->getService(SaferPayInitialize::class); - $initializeBody = $initializeService->initialize( + $initializeResponse = $paymentFrontController->create( + $this->context->cart, Tools::getValue('paymentMethod'), (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE), - $selectedCard, - $alias, - Tools::getValue('fieldToken') + Tools::getValue('selectedCard'), + Tools::getValue('fieldToken'), + 'successHosted', + true ); - $this->createSaferPayOrder($initializeBody); - $redirectUrl = $this->getRedirectionUrl($initializeBody); + + $redirectUrl = $paymentFrontController->getRedirectionUrl($initializeResponse); if (empty($redirectUrl)) { $redirectUrl = $this->getRedirectionToControllerUrl('successHosted'); } - //todo create here an order if setting is true $this->ajaxDie(json_encode([ 'error' => false, 'url' => $redirectUrl, @@ -86,40 +89,6 @@ private function submitHostedFields(): void } } - /** - * @param object $initializeBody - * - * @return string - */ - private function getRedirectionUrl($initializeBody) - { - if (isset($initializeBody->RedirectUrl)) { - return $initializeBody->RedirectUrl; - } - - if (isset($initializeBody->Redirect->RedirectUrl)) { - return $initializeBody->Redirect->RedirectUrl; - } - - return ''; - } - - /** - * @param object $initializeBody - */ - private function createSaferPayOrder($initializeBody) - { - /** @var Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder $saferPayOrderBuilder */ - $saferPayOrderBuilder = $this->module->getService(SaferPayOrderBuilder::class); - $saferPayOrderBuilder->create( - $initializeBody, - $this->context->cart, - $this->context->customer, - true, - Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE) - ); - } - /** * @param string $controllerName * @@ -139,24 +108,4 @@ private function getRedirectionToControllerUrl($controllerName) true ); } - - /** - * @throws Exception - */ - private function validateOrder() - { - $customer = new Customer($this->context->cart->id_customer); - - $this->module->validateOrder( - $this->context->cart->id, - Configuration::get(SaferPayConfig::SAFERPAY_ORDER_STATE_CHOICE_AWAITING_PAYMENT), - (float) $this->context->cart->getOrderTotal(), - Tools::getValue('paymentMethod'), - null, - [], - (int) $this->context->currency->id, - false, - $customer->secure_key - ); - } } diff --git a/controllers/front/fail.php b/controllers/front/fail.php index b771c012..296a011d 100755 --- a/controllers/front/fail.php +++ b/controllers/front/fail.php @@ -67,6 +67,7 @@ public function init() if (!SaferPayConfig::isVersion17()) { return parent::init(); } + parent::init(); $this->id_cart = (int) Tools::getValue('cartId', 0); diff --git a/controllers/front/iframe.php b/controllers/front/iframe.php index d5b0bbd3..edc09641 100755 --- a/controllers/front/iframe.php +++ b/controllers/front/iframe.php @@ -23,7 +23,6 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; -use Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder; use Invertus\SaferPay\Enum\ControllerName; use Invertus\SaferPay\Repository\SaferPayCardAliasRepository; use Invertus\SaferPay\Service\SaferPayInitialize; @@ -73,49 +72,33 @@ public function postProcess() if (!Validate::isLoadedObject($customer)) { Tools::redirect($redirectLink); } - - $currency = $this->context->currency; - $total = (float) $cart->getOrderTotal(); - - $orderId = Order::getOrderByCartId($cart->id); - if (!$orderId) { - $paymentMethod = Tools::getValue('saved_card_method'); - - $this->module->validateOrder( - $cart->id, - Configuration::get(SaferPayConfig::SAFERPAY_ORDER_STATE_CHOICE_AWAITING_PAYMENT), - $total, - $paymentMethod, - null, - [], - (int) $currency->id, - false, - $customer->secure_key - ); - } } public function initContent() { parent::initContent(); + $paymentMethod = Tools::getValue('saved_card_method'); $selectedCard = Tools::getValue("selectedCreditCard_{$paymentMethod}"); + if (!SaferPayConfig::isVersion17()) { $selectedCard = Tools::getValue("saved_card_{$paymentMethod}"); } - /** @var SaferPayOrderBuilder $saferPayOrderBuilder */ - $saferPayOrderBuilder = $this->module->getService(SaferPayOrderBuilder::class); - $isBusinessLicence = Tools::getValue(\Invertus\SaferPay\Config\SaferPayConfig::IS_BUSINESS_LICENCE); - /** @var SaferPayInitialize $initializeService */ - $initializeService = $this->module->getService(SaferPayInitialize::class); try { - /** @var SaferPayCardAliasRepository $cardAliasRep */ - $cardAliasRep = $this->module->getService(SaferPayCardAliasRepository::class); - $alias = $cardAliasRep->getSavedCardAliasFromId($selectedCard); - $response = $initializeService->initialize($paymentMethod, $isBusinessLicence, $selectedCard, $alias); - } catch (Exception $e) { - $redirectLink = $this->context->link->getModuleLink( + /** @var \Invertus\SaferPay\Controller\Front\PaymentFrontController $paymentFrontController */ + $paymentFrontController = $this->module->getModuleContainer()->get(\Invertus\SaferPay\Controller\Front\PaymentFrontController::class); + + $initializeResponse = $paymentFrontController->create( + $this->context->cart, + $paymentMethod, + Tools::getValue(\Invertus\SaferPay\Config\SaferPayConfig::IS_BUSINESS_LICENCE), + $selectedCard + ); + + $redirectUrl = $paymentFrontController->getRedirectionUrl($initializeResponse); + } catch (\Exception $exception) { + $redirectUrl = $this->context->link->getModuleLink( $this->module->name, ControllerName::FAIL, [ @@ -126,22 +109,18 @@ public function initContent() ], true ); - $this->redirectWithNotifications($redirectLink); + $this->redirectWithNotifications($redirectUrl); } - $saferPayOrderBuilder->create( - $response, - $this->context->cart, - $this->context->customer, - true, - $isBusinessLicence - ); + $this->context->smarty->assign([ - 'redirect' => $response->Redirect->RedirectUrl, + 'redirect' => $redirectUrl, ]); + if (SaferPayConfig::isVersion17()) { $this->setTemplate(SaferPayConfig::SAFERPAY_TEMPLATE_LOCATION . '/front/saferpay_iframe.tpl'); return; } + $this->setTemplate('saferpay_iframe_16.tpl'); } diff --git a/controllers/front/notify.php b/controllers/front/notify.php index 9a5367ea..877924d2 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -65,18 +65,17 @@ public function postProcess() //TODO look into pipeline design pattern to use when object is modified in multiple places to avoid this issue. //NOTE must be left below assert action to get newest information. - $order = new Order($orderId); - - /** @var SaferPayOrderStatusService $orderStatusService */ - $orderStatusService = $this->module->getService(SaferPayOrderStatusService::class); - $paymentBehaviourWithout3DS = (int) Configuration::get(SaferPayConfig::PAYMENT_BEHAVIOR_WITHOUT_3D); + //todo we need to do it with cart and on cancel we need to cancel it + $order = new Order($orderId); + //todo check if cart can give as payment option - if ( - !$assertResponseBody->getLiability()->getLiabilityShift() && + if (!$assertResponseBody->getLiability()->getLiabilityShift() && in_array($order->payment, SaferPayConfig::SUPPORTED_3DS_PAYMENT_METHODS) && - $paymentBehaviourWithout3DS === SaferPayConfig::PAYMENT_BEHAVIOR_WITHOUT_3D_CANCEL + (int) Configuration::get(SaferPayConfig::PAYMENT_BEHAVIOR_WITHOUT_3D) === SaferPayConfig::PAYMENT_BEHAVIOR_WITHOUT_3D_CANCEL ) { + /** @var SaferPayOrderStatusService $orderStatusService */ + $orderStatusService = $this->module->getService(SaferPayOrderStatusService::class); $orderStatusService->cancel($order); die($this->module->l('Liability shift is false', self::FILENAME)); @@ -85,10 +84,7 @@ public function postProcess() //NOTE to get latest information possible and not override new information. $order = new Order($orderId); - $paymentBehaviour = (int) Configuration::get(SaferPayConfig::PAYMENT_BEHAVIOR); - - if ( - $paymentBehaviour === SaferPayConfig::DEFAULT_PAYMENT_BEHAVIOR_CAPTURE && + if ((int) Configuration::get(SaferPayConfig::PAYMENT_BEHAVIOR) === SaferPayConfig::DEFAULT_PAYMENT_BEHAVIOR_CAPTURE && $assertResponseBody->getTransaction()->getStatus() !== TransactionStatus::CAPTURED ) { $orderStatusService->capture($order); @@ -123,7 +119,13 @@ private function assertTransaction($cartId) { /** @var SaferPayTransactionAssertion $transactionAssert */ $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); - $assertionResponse = $transactionAssert->assert(Order::getOrderByCartId($cartId), true); + $assertionResponse = $transactionAssert->assert($cartId); //todo just a cart id + + $orderId = \Order::getOrderByCartId($cartId); + //todo repo to get saferpayOrder + /** @var SaferPayOrderStatusService $orderStatusService */ + $orderStatusService = $this->module->getService(SaferPayOrderStatusService::class); + $orderStatusService->assert($saferPayOrder, $assertionResponse->getTransaction()->getStatus()); return $assertionResponse; } diff --git a/controllers/front/return.php b/controllers/front/return.php index 9d9b9398..27ee03f7 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -25,6 +25,8 @@ use Invertus\SaferPay\Controller\AbstractSaferPayController; use Invertus\SaferPay\DTO\Response\Assert\AssertBody; use Invertus\SaferPay\Service\TransactionFlow\SaferPayTransactionAssertion; +use Invertus\SaferPay\Processor\CheckoutProcessor; + if (!defined('_PS_VERSION_')) { exit; @@ -64,13 +66,18 @@ public function postProcess() } try { - if ($orderId) { - $this->assertTransactionByOrderId($orderId); - } else { - $this->assertTransactionByCartId($cartId); - //todo if assertion is good create order + /** @var SaferPayTransactionAssertion $transactionAssert */ + $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); + $assertionResponse = $transactionAssert->assert($cartId); + + if (!$orderId) { // todo check config too + /** @var CheckoutProcessor $checkoutProcessor **/ + $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); + $checkoutProcessor->processCreateOrder(new \Cart($cartId), 'MASTERCARD'); // todo payment method if not in assertionResone then add to response } + $orderId = \Order::getOrderByCartId($cartId); + Tools::redirect($this->context->link->getModuleLink( $this->module->name, $this->getSuccessControllerName($isBusinessLicence, $fieldToken), @@ -105,20 +112,6 @@ public function postProcess() } } - /** - * @param $cartId - * @return AssertBody - * @throws Exception - */ - private function assertTransactionByOrderId($orderId) - { - /** @var SaferPayTransactionAssertion $transactionAssert */ - $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); - $assertionResponse = $transactionAssert->assert($orderId, false); - - return $assertionResponse; - } - private function getSuccessControllerName($isBusinessLicence, $fieldToken) { $successController = 'success'; diff --git a/controllers/front/validation.php b/controllers/front/validation.php index d4071b67..bb2b61e0 100755 --- a/controllers/front/validation.php +++ b/controllers/front/validation.php @@ -26,6 +26,7 @@ use Invertus\SaferPay\Exception\Api\SaferPayApiException; use Invertus\SaferPay\Service\SaferPayExceptionService; use Invertus\SaferPay\Service\SaferPayInitialize; +use Invertus\SaferPay\Controller\Front\PaymentFrontController; if (!defined('_PS_VERSION_')) { exit; @@ -35,6 +36,9 @@ class SaferPayOfficialValidationModuleFrontController extends AbstractSaferPayCo { const FILENAME = 'validation'; + /** @var SaferPayOfficial */ + public $module; + /** * @see FrontController::postProcess() */ @@ -66,42 +70,33 @@ public function postProcess() } } if (!$authorized) { - $this->errors[] = - $this->module->l('This payment method is not available.', self::FILENAME); + $this->errors[] = $this->module->l('This payment method is not available.', self::FILENAME); $this->redirectWithNotifications($redirectLink); } - $customer = new Customer($cart->id_customer); - if (!Validate::isLoadedObject($customer)) { - Tools::redirect($redirectLink); + if (Order::getOrderByCartId($this->context->cart->id)) { + $this->errors[] = $this->module->l('Order already exists.', self::FILENAME); + $this->redirectWithNotifications($redirectLink); } - $currency = $this->context->currency; - $total = (float) $cart->getOrderTotal(); + try { + /** @var PaymentFrontController $paymentFrontController */ + $paymentFrontController = $this->module->getService(PaymentFrontController::class); - if (!(int) Configuration::get(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION)) { - $this->module->validateOrder( - $cart->id, - Configuration::get(SaferPayConfig::SAFERPAY_ORDER_STATE_CHOICE_AWAITING_PAYMENT), - $total, - $paymentMethod, - null, - [], - (int) $currency->id, - false, - $customer->secure_key - ); - } + $initializeResponse = $paymentFrontController->create( + $this->context->cart, + $paymentMethod, + (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE) + ); - /** @var SaferPayInitialize $initializeService */ - $initializeService = $this->module->getService(SaferPayInitialize::class); - try { - $isBusinessLicence = Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE); - $initializeBody = $initializeService->initialize($paymentMethod, $isBusinessLicence); - } catch (SaferPayApiException $e) { + $redirectLink = $paymentFrontController->getRedirectionUrl($initializeResponse); + + Tools::redirect($redirectLink); + } catch (\Exception $exception) { /** @var SaferPayExceptionService $exceptionService */ $exceptionService = $this->module->getService(SaferPayExceptionService::class); - $this->errors[] = $exceptionService->getErrorMessageForException($e, $exceptionService->getErrorMessages()); + $this->errors[] = $exceptionService->getErrorMessageForException($exception, $exceptionService->getErrorMessages()); + $redirectLink = $this->context->link->getModuleLink( $this->module->name, 'fail', @@ -115,19 +110,5 @@ public function postProcess() ); $this->redirectWithNotifications($redirectLink); } - if (!(int) Configuration::get(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION)) { - /** @var Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder $saferPayOrderBuilder */ - $saferPayOrderBuilder = $this->module->getService(\Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder::class); - - $saferPayOrderBuilder->create( - $initializeBody, - $this->context->cart, - $this->context->customer, - false, - $isBusinessLicence - ); - } - - Tools::redirect($initializeBody->RedirectUrl); } } diff --git a/src/Adapter/Configuration.php b/src/Adapter/Configuration.php new file mode 100644 index 00000000..ab6f521c --- /dev/null +++ b/src/Adapter/Configuration.php @@ -0,0 +1,109 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Adapter; + +use Configuration as PrestaShopConfiguration; +use Invertus\SaferPay\Adapter\LegacyContext; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class Configuration +{ + + /** + * @var LegacyContext + */ + private $context; + + public function __construct(LegacyContext $context) + { + $this->context = $context; + } + + public function set(string $id, $value, ?int $shopId = null) + { + if (!$shopId) { + $shopId = $this->context->getShopId(); + } + + PrestaShopConfiguration::updateValue($id, $value, false, null, $shopId); + } + + public function get(string $id, ?int $shopId = null) + { + if (!$shopId) { + $shopId = $this->context->getShopId(); + } + + $result = PrestaShopConfiguration::get($id, null, null, $shopId); + + return $result ?: null; + } + + public function getAsBoolean(string $id, ?int $shopId = null) + { + $result = $this->get($id, $shopId); + + if (in_array($result, ['null', 'false', '0', null, false, 0], true)) { + return false; + } + + return (bool) $result; + } + + public function getAsInteger(string $id, ?int $shopId = null) + { + $result = $this->get($id, $shopId); + + if (in_array($result, ['null', 'false', '0', null, false, 0], true)) { + return 0; + } + + return (int) $result; + } + + /** + * Removes by specific shop id + * + * @param string $id + * @param int $shopId + */ + public function remove(string $id, ?int $shopId) + { + // making sure to set to null value only for single shop id + PrestaShopConfiguration::updateValue($id, null, false, null, $shopId); + } + + /** + * Drops configuration from all shops. + * + * @param string $id + */ + public function delete(string $id) + { + PrestaShopConfiguration::deleteByName($id); + } +} \ No newline at end of file diff --git a/src/Adapter/LegacyContext.php b/src/Adapter/LegacyContext.php index 2a5c8e01..618d21cf 100755 --- a/src/Adapter/LegacyContext.php +++ b/src/Adapter/LegacyContext.php @@ -36,6 +36,11 @@ public function getContext() return Context::getContext(); } + public function getShopId() + { + return $this->getContext()->shop->id; + } + public function getCurrencyIsoCode() { return $this->getContext()->currency->iso_code; diff --git a/src/Controller/Front/PaymentFrontController.php b/src/Controller/Front/PaymentFrontController.php new file mode 100644 index 00000000..9aa18c35 --- /dev/null +++ b/src/Controller/Front/PaymentFrontController.php @@ -0,0 +1,99 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Controller\Front; + +use Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder; +use Invertus\SaferPay\Processor\CheckoutProcessor; +use Invertus\SaferPay\Service\SaferPayInitialize; +use Invertus\SaferPay\Adapter\Configuration; +use Invertus\SaferPay\Config\SaferPayConfig; + +class PaymentFrontController +{ + + /** + * @var CheckoutProcessor + */ + private $checkoutProcessor; + + /** + * @var Configuration + */ + private $configuration; + + public function __construct( + CheckoutProcessor $checkoutProcessor, + Configuration $configuration + ) { + $this->checkoutProcessor = $checkoutProcessor; + $this->configuration = $configuration; + } + + public function create(\Cart $cart, $paymentMethod, $isBusinessLicense, $selectedCard = -1, $fieldToken = null, $successController = null, $isTransaction = false) + { + if (!$this->configuration->getAsBoolean(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION)) { + $this->checkoutProcessor->processCreateOrder( + $cart, + $paymentMethod + ); + } + + $response = $this->checkoutProcessor->initializePayment( + $paymentMethod, + $isBusinessLicense, + $selectedCard, + $fieldToken, + $successController + ); + + $this->checkoutProcessor->processCreateSaferPayOrder( + $response, + $cart->id, + $cart->id_customer, + $isTransaction + ); + + return $response; + } + + /** + * TODO Extract initializeBody to class and have method to get redirectionUrl + * + * @param object $initializeBody + * + * @return string + */ + public function getRedirectionUrl($initializeBody) + { + if (isset($initializeBody->RedirectUrl)) { + return $initializeBody->RedirectUrl; + } + + if (isset($initializeBody->Redirect->RedirectUrl)) { + return $initializeBody->Redirect->RedirectUrl; + } + + return ''; + } +} diff --git a/src/Entity/SaferPayOrder.php b/src/Entity/SaferPayOrder.php index 3930f6f3..64cd7331 100755 --- a/src/Entity/SaferPayOrder.php +++ b/src/Entity/SaferPayOrder.php @@ -31,7 +31,7 @@ class SaferPayOrder extends ObjectModel { /** - * @var Int + * @var Int|null */ public $id_order; @@ -92,7 +92,8 @@ class SaferPayOrder extends ObjectModel 'table' => 'saferpay_order', 'primary' => 'id_saferpay_order', 'fields' => [ - 'id_order' => ['type' => self::TYPE_INT, 'validate' => 'isInt'], + 'id_order' => ['type' => self::TYPE_INT, 'validate' => 'isInt', 'required' => false], + 'id_cart' => ['type' => self::TYPE_INT, 'validate' => 'isInt'], 'id_customer' => ['type' => self::TYPE_INT, 'validate' => 'isInt'], 'transaction_id' => ['type' => self::TYPE_STRING, 'validate' => 'isString'], 'refund_id' => ['type' => self::TYPE_STRING, 'validate' => 'isString'], diff --git a/src/EntityBuilder/SaferPayOrderBuilder.php b/src/EntityBuilder/SaferPayOrderBuilder.php index d3418dcb..cba006d9 100755 --- a/src/EntityBuilder/SaferPayOrderBuilder.php +++ b/src/EntityBuilder/SaferPayOrderBuilder.php @@ -35,13 +35,15 @@ class SaferPayOrderBuilder { //TODO to pass $body as InitializeBody. - public function create($body, Cart $cart, Customer $customer, $isTransaction, $isBusinessLicence) + public function create($body, $cartId, $customerId, $isTransaction) { - $orderId = Order::getOrderByCartId($cart->id); + $orderId = Order::getOrderByCartId($cartId); + $saferPayOrder = new SaferPayOrder(); $saferPayOrder->token = $body->Token; - $saferPayOrder->id_order = $orderId; - $saferPayOrder->id_customer = $customer->id; + $saferPayOrder->id_order = $orderId ? $orderId : null; + $saferPayOrder->id_cart = $cartId; + $saferPayOrder->id_customer = $customerId; $saferPayOrder->redirect_url = $this->getRedirectionUrl($body); $saferPayOrder->is_transaction = $isTransaction; $saferPayOrder->add(); diff --git a/src/Processor/CheckoutProcessor.php b/src/Processor/CheckoutProcessor.php new file mode 100644 index 00000000..7e9b85b2 --- /dev/null +++ b/src/Processor/CheckoutProcessor.php @@ -0,0 +1,96 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Processor; + +use Invertus\SaferPay\Config\SaferPayConfig; +use Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder; +use Invertus\SaferPay\Factory\ModuleFactory; +use Invertus\SaferPay\Service\SaferPayInitialize; + +class CheckoutProcessor +{ + /** @var \SaferPayOfficial */ + private $module; + + /** @var SaferPayOrderBuilder */ + private $saferPayOrderBuilder; + + /** @var SaferPayInitialize */ + private $saferPayInitialize; + + public function __construct( + ModuleFactory $module, + SaferPayOrderBuilder $saferPayOrderBuilder, + SaferPayInitialize $saferPayInitialize + ) { + $this->module = $module->getModule(); + $this->saferPayOrderBuilder = $saferPayOrderBuilder; + $this->saferPayInitialize = $saferPayInitialize; + } + + public function processCreateOrder(\Cart $cart, $paymentMethod) + { + $customer = new \Customer($cart->id_customer); + + $this->module->validateOrder( + $cart->id, + \Configuration::get(SaferPayConfig::SAFERPAY_ORDER_STATE_CHOICE_AWAITING_PAYMENT), + (float) $cart->getOrderTotal(), + $paymentMethod, + null, + [], + null, + false, + $customer->secure_key + ); + } + + public function initializePayment( + $paymentMethod, + $isBusinessLicense, + $selectedCard, + $fieldToken, + $successController + ) { + $request = $this->saferPayInitialize->buildRequest( + $paymentMethod, + $isBusinessLicense, + $selectedCard, + $fieldToken, + $successController + ); + + return $this->saferPayInitialize->initialize($request, $isBusinessLicense); + } + + public function processCreateSaferPayOrder($initializeBody, $cartId, $customerId, $isTransaction) + { + $this->saferPayOrderBuilder->create( + $initializeBody, + $cartId, + $customerId, + $isTransaction + ); + } +} diff --git a/src/Repository/SaferPayOrderRepository.php b/src/Repository/SaferPayOrderRepository.php index 0d511c14..1223aeaf 100755 --- a/src/Repository/SaferPayOrderRepository.php +++ b/src/Repository/SaferPayOrderRepository.php @@ -42,6 +42,15 @@ public function getIdByOrderId($orderId) return Db::getInstance()->getValue($query); } + public function getIdByCartId($cartId) + { + $query = new DbQuery(); + $query->select('`id_saferpay_order`'); + $query->from('saferpay_order'); + $query->where('id_cart = "' . (int) $cartId . '"'); + + return Db::getInstance()->getValue($query); + } public function getAssertIdBySaferPayOrderId($saferPayOrderId) { $query = new DbQuery(); diff --git a/src/Service/Request/AssertRequestObjectCreator.php b/src/Service/Request/AssertRequestObjectCreator.php index 5d8dde1f..662f17d8 100755 --- a/src/Service/Request/AssertRequestObjectCreator.php +++ b/src/Service/Request/AssertRequestObjectCreator.php @@ -51,11 +51,9 @@ public function __construct( $this->saferPayOrderRepository = $saferPayOrderRepository; } - public function create($orderId) + public function create($token) { $requestHeader = $this->requestObjectCreator->createRequestHeader(); - $saferPayOrderId = $this->saferPayOrderRepository->getIdByOrderId($orderId); - $saferPayOrder = new SaferPayOrder($saferPayOrderId); return new AssertRequest($requestHeader, $saferPayOrder->token); } diff --git a/src/Service/Request/RequestObjectCreator.php b/src/Service/Request/RequestObjectCreator.php index 4c7a26e2..abeb061e 100755 --- a/src/Service/Request/RequestObjectCreator.php +++ b/src/Service/Request/RequestObjectCreator.php @@ -119,8 +119,12 @@ public function createPayment(Cart $cart, $totalPrice) $payment->setValue($totalPrice); $payment->setCurrencyCode($currency['iso_code']); - //todo what is the reference ?? todo recommended - $payment->setOrderReference('random'); + if ((int) \Configuration::get(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION) && empty($order)) { + return $payment; + } + + /** This param is not mandatory, but recommended **/ + $payment->setOrderReference($order->reference); return $payment; } diff --git a/src/Service/SaferPayInitialize.php b/src/Service/SaferPayInitialize.php index 5dc94ae9..cab4e6d9 100755 --- a/src/Service/SaferPayInitialize.php +++ b/src/Service/SaferPayInitialize.php @@ -25,10 +25,13 @@ use Context; use Exception; +use Invertus\SaferPay\Adapter\Configuration; use Invertus\SaferPay\Adapter\LegacyContext; use Invertus\SaferPay\Api\Request\InitializeService; +use Invertus\SaferPay\DTO\Request\Initialize\InitializeRequest; use Invertus\SaferPay\Enum\ControllerName; use Invertus\SaferPay\Exception\Api\SaferPayApiException; +use Invertus\SaferPay\Repository\SaferPayCardAliasRepository; use Invertus\SaferPay\Factory\ModuleFactory; use Invertus\SaferPay\Service\Request\InitializeRequestObjectCreator; use Invertus\SaferPay\Config\SaferPayConfig; @@ -61,36 +64,60 @@ class SaferPayInitialize */ private $requestObjectCreator; + /** @var SaferPayCardAliasRepository */ + private $saferPayCardAliasRepository; + + /** + * @var Configuration + */ + private $configuration; + public function __construct( ModuleFactory $module, LegacyContext $context, InitializeService $initializeService, - InitializeRequestObjectCreator $requestObjectCreator + InitializeRequestObjectCreator $requestObjectCreator, + SaferPayCardAliasRepository $saferPayCardAliasRepository, + Configuration $configuration ) { $this->module = $module->getModule(); $this->context = $context->getContext(); $this->initializeService = $initializeService; $this->requestObjectCreator = $requestObjectCreator; + $this->saferPayCardAliasRepository = $saferPayCardAliasRepository; + $this->configuration = $configuration; + } + + public function initialize(InitializeRequest $initializeRequest, $isBusinessLicence) + { + try { + $initialize = $this->initializeService->initialize($initializeRequest, $isBusinessLicence); + } catch (Exception $e) { + throw new SaferPayApiException('Initialize API failed', SaferPayApiException::INITIALIZE); + } + + return $initialize; } - public function initialize( + public function buildRequest( $paymentMethod, $isBusinessLicence, $selectedCard = -1, - $alias = null, - $fieldToken = null + $fieldToken = null, + $successController = null ) { $customerEmail = $this->context->customer->email; $cartId = $this->context->cart->id; - $createAfterAuthorization = (int) \Configuration::get(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION); + $creationAfterInitialization = $this->configuration->getAsBoolean(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION); + $alias = $this->saferPayCardAliasRepository->getSavedCardAliasFromId($selectedCard); - $returnUrl = $this->context->link->getModuleLink( + $successUrl = $this->context->link->getModuleLink( $this->module->name, ControllerName::RETURN_URL, [ 'cartId' => $cartId, 'secureKey' => $this->context->cart->secure_key, - 'orderId' => $createAfterAuthorization ? 0 : Order::getOrderByCartId($cartId), + 'orderId' => $creationAfterInitialization ? 0 :Order::getOrderByCartId($cartId), 'moduleId' => $this->module->id, 'selectedCard' => $selectedCard, 'isBusinessLicence' => $isBusinessLicence, @@ -105,31 +132,57 @@ public function initialize( [ 'success' => 1, 'cartId' => $this->context->cart->id, - 'orderId' => $createAfterAuthorization ? 0 : Order::getOrderByCartId($cartId), + 'orderId' => $creationAfterInitialization ? 0 :Order::getOrderByCartId($cartId), 'secureKey' => $this->context->cart->secure_key, ], true ); + $failUrl = $this->context->link->getModuleLink( + $this->module->name, + 'failValidation', + [ + 'cartId' => $this->context->cart->id, + 'secureKey' => $this->context->cart->secure_key, + 'orderId' => $creationAfterInitialization ? 0 :Order::getOrderByCartId($cartId), + 'moduleId' => $this->module->id, + 'isBusinessLicence' => $isBusinessLicence, + ], + true + ); + $initializeRequest = $this->requestObjectCreator->create( $this->context->cart, $customerEmail, $paymentMethod, - $returnUrl, + $successUrl, $notifyUrl, + $failUrl, $this->context->cart->id_address_delivery, $this->context->cart->id_address_invoice, $this->context->cart->id_customer, - $isBusinessLicence, $alias, $fieldToken ); - try { - $initialize = $this->initializeService->initialize($initializeRequest, $isBusinessLicence); - } catch (Exception $e) { - throw new SaferPayApiException('Initialize API failed', SaferPayApiException::INITIALIZE); - } - return $initialize; + return $initializeRequest; + } + + /** + * @param int $isBusinessLicence + * @param string $fieldToken + * + * @return string + */ + private function getSuccessControllerName($isBusinessLicence, $fieldToken) + { + $successController = 'success'; + if ($isBusinessLicence) { + $successController = 'successIFrame'; + } + if ($fieldToken) { + $successController = 'successHosted'; + } + return $successController; } } diff --git a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php index eab50579..88730bc7 100755 --- a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php +++ b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php @@ -75,12 +75,11 @@ public function __construct( * @return AssertBody * @throws \Exception */ - public function assert($orderId, $changeOrderStatus) + public function assert($cartId) { - $saferPayOrder = $this->getSaferPayOrder($orderId); - $order = new Order($orderId); + $saferPayOrder = $this->getSaferPayOrder($cartId); - $assertRequest = $this->assertRequestCreator->create($orderId); + $assertRequest = $this->assertRequestCreator->create($saferPayOrder->token); $assertResponse = $this->assertionService->assert($assertRequest, $saferPayOrder->id); $assertBody = $this->assertionService->createObjectsFromAssertResponse( @@ -91,22 +90,18 @@ public function assert($orderId, $changeOrderStatus) $saferPayOrder->transaction_id = $assertBody->getTransaction()->getId(); $saferPayOrder->update(); - if ($changeOrderStatus) { - $this->orderStatusService->assert($order, $assertBody->getTransaction()->getStatus()); - } - return $assertBody; } /** - * @param $orderId + * @param $cartId * * @return false|SaferPayOrder * @throws \Exception */ - private function getSaferPayOrder($orderId) + private function getSaferPayOrder($cartId) { - $saferPayOrderId = $this->orderRepository->getIdByOrderId($orderId); + $saferPayOrderId = $this->orderRepository->getIdByCartId($orderId); return new SaferPayOrder($saferPayOrderId); } diff --git a/upgrade/install-1.2.0.php b/upgrade/install-1.2.0.php index 972d3a50..d667e728 100644 --- a/upgrade/install-1.2.0.php +++ b/upgrade/install-1.2.0.php @@ -23,13 +23,30 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\DTO\Request\RequestHeader; +use Configuration; if (!defined('_PS_VERSION_')) { exit; } + +//todo test it and todo upgrade method function upgrade_module_1_2_0($module) { + // Make id_order nullable + $sql = 'ALTER TABLE `' . bqSQL(_DB_PREFIX_ . 'saferpay_order') . '` MODIFY `id_order` INT NULL;'; + + if (!Db::getInstance()->execute($sql)) { + return false; + } + + // Add the new column id_cart after id_order + $sql = 'ALTER TABLE `' . bqSQL(_DB_PREFIX_ . 'saferpay_order') . '` ADD COLUMN `id_cart` INT AFTER `id_order`;'; + if (!Db::getInstance()->execute($sql)) { + return false; + } + Configuration::updateValue(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION, 0); + return true; } From 9133cc159289997d56e37e0c8ea2120da6b1f770 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Fri, 15 Dec 2023 16:12:41 +0200 Subject: [PATCH 04/18] feat: after and before authorization feature --- .../AdminSaferPayOfficialOrderController.php | 2 +- controllers/front/fail.php | 23 +++++------------- controllers/front/failIFrame.php | 3 ++- controllers/front/failValidation.php | 10 ++++++-- controllers/front/notify.php | 14 +++++------ controllers/front/return.php | 16 ++++++++----- controllers/front/validation.php | 4 +--- src/EntityBuilder/SaferPayOrderBuilder.php | 4 ++-- src/Processor/CheckoutProcessor.php | 24 +++++++++++++++++-- src/Repository/SaferPayOrderRepository.php | 14 +++++++++++ .../Request/AssertRequestObjectCreator.php | 7 +++++- .../SaferPayTransactionAssertion.php | 3 ++- 12 files changed, 81 insertions(+), 43 deletions(-) diff --git a/controllers/admin/AdminSaferPayOfficialOrderController.php b/controllers/admin/AdminSaferPayOfficialOrderController.php index 2facdb02..7d5fc098 100755 --- a/controllers/admin/AdminSaferPayOfficialOrderController.php +++ b/controllers/admin/AdminSaferPayOfficialOrderController.php @@ -50,7 +50,7 @@ public function postProcess() $orderStatusService->capture($order); $this->context->cookie->captured = true; } elseif (Tools::isSubmit('submitCancelOrder')) { - $orderStatusService->cancel($order); + $orderStatusService->cancel($order); //todo saferPayOrder $this->context->cookie->canceled = true; } elseif (Tools::isSubmit('submitRefundOrder')) { $refundAmount = Tools::getValue('saferpay_refund_amount'); diff --git a/controllers/front/fail.php b/controllers/front/fail.php index 296a011d..52300df8 100755 --- a/controllers/front/fail.php +++ b/controllers/front/fail.php @@ -34,13 +34,6 @@ class SaferPayOfficialFailModuleFrontController extends AbstractSaferPayControll { const FILENAME = 'fail'; - /** - * ID Order Variable Declaration. - * - * @var - */ - private $id_order; - /** * Security Key Variable Declaration. * @@ -74,25 +67,21 @@ public function init() $redirectLink = 'index.php?controller=history'; - $this->id_order = Order::getOrderByCartId((int) $this->id_cart); $this->secure_key = Tools::getValue('secureKey'); - $order = new Order((int) $this->id_order); - if (!$this->id_order || !$this->module->id || !$this->secure_key || empty($this->secure_key)) { + $cart = new Cart($this->id_cart); + + if (!$this->module->id || !$this->secure_key || empty($this->secure_key)) { Tools::redirect($redirectLink . (Tools::isSubmit('slowvalidation') ? '&slowvalidation' : '')); } - if ((string) $this->secure_key !== (string) $order->secure_key || - (int) $order->id_customer !== (int) $this->context->customer->id || - !Validate::isLoadedObject($order) + if ((string) $this->secure_key !== (string) $cart->secure_key || + (int) $cart->id_customer !== (int) $this->context->customer->id || + !Validate::isLoadedObject($cart) ) { Tools::redirect($redirectLink); } - if ($order->module !== $this->module->name) { - Tools::redirect($redirectLink); - } - /** @var CartDuplicationService $cartDuplicationService */ $cartDuplicationService = $this->module->getService(CartDuplicationService::class); $cartDuplicationService->restoreCart($this->id_cart); diff --git a/controllers/front/failIFrame.php b/controllers/front/failIFrame.php index 7752121a..c96b44a6 100755 --- a/controllers/front/failIFrame.php +++ b/controllers/front/failIFrame.php @@ -23,6 +23,7 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; +use Invertus\SaferPay\Enum\ControllerName; if (!defined('_PS_VERSION_')) { exit; @@ -76,7 +77,7 @@ public function setMedia() $failUrl = $this->context->link->getModuleLink( $this->module->name, - 'fail', + ControllerName::FAIL, [ 'cartId' => $cartId, 'secureKey' => $secureKey, diff --git a/controllers/front/failValidation.php b/controllers/front/failValidation.php index 991368c7..90951a60 100755 --- a/controllers/front/failValidation.php +++ b/controllers/front/failValidation.php @@ -52,14 +52,20 @@ public function postProcess() Tools::redirect($redirectLink); } + $order = new Order($orderId); - $order->setCurrentState(_SAFERPAY_PAYMENT_AUTHORIZATION_FAILED_); + + if (Validate::isLoadedObject($order)) { + $order->setCurrentState(_SAFERPAY_PAYMENT_AUTHORIZATION_FAILED_); + } + /** @var SaferPayOrderRepository $orderRepo */ $orderRepo = $this->module->getService(SaferPayOrderRepository::class); + /** @var CartDuplicationService $cartDuplicationService */ $cartDuplicationService = $this->module->getService(CartDuplicationService::class); - $saferPayOrderId = $orderRepo->getIdByOrderId($orderId); + $saferPayOrderId = $orderRepo->getIdByCartId($cartId); $saferPayOrder = new SaferPayOrder($saferPayOrderId); $saferPayOrder->canceled = 1; $saferPayOrder->update(); diff --git a/controllers/front/notify.php b/controllers/front/notify.php index 877924d2..45e46cc4 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -41,6 +41,7 @@ class SaferPayOfficialNotifyModuleFrontController extends AbstractSaferPayContro * # WILL NOT work for local development, to AUTHORIZE payment this must be called manually. # * Example manual request: https://saferpay.demo.com/en/module/saferpayofficial/notify?success=1&cartId=12&orderId=12&secureKey=9366c61b59e918b2cd96ed0567c82e90 */ +//http://localhost/ps17810/index.php?fc=module&module=saferpayofficial&controller=notify&success=1&cartId=179&orderId=93&secureKey=6780efac67f4422574332bf887249bd7 //todo add correct data public function postProcess() { $cartId = Tools::getValue('cartId'); @@ -65,10 +66,7 @@ public function postProcess() //TODO look into pipeline design pattern to use when object is modified in multiple places to avoid this issue. //NOTE must be left below assert action to get newest information. - - //todo we need to do it with cart and on cancel we need to cancel it $order = new Order($orderId); - //todo check if cart can give as payment option if (!$assertResponseBody->getLiability()->getLiabilityShift() && in_array($order->payment, SaferPayConfig::SUPPORTED_3DS_PAYMENT_METHODS) && @@ -76,7 +74,7 @@ public function postProcess() ) { /** @var SaferPayOrderStatusService $orderStatusService */ $orderStatusService = $this->module->getService(SaferPayOrderStatusService::class); - $orderStatusService->cancel($order); + $orderStatusService->cancel($cart); die($this->module->l('Liability shift is false', self::FILENAME)); } @@ -87,6 +85,8 @@ public function postProcess() if ((int) Configuration::get(SaferPayConfig::PAYMENT_BEHAVIOR) === SaferPayConfig::DEFAULT_PAYMENT_BEHAVIOR_CAPTURE && $assertResponseBody->getTransaction()->getStatus() !== TransactionStatus::CAPTURED ) { + /** @var SaferPayOrderStatusService $orderStatusService */ + $orderStatusService = $this->module->getService(SaferPayOrderStatusService::class); $orderStatusService->capture($order); } @@ -119,13 +119,13 @@ private function assertTransaction($cartId) { /** @var SaferPayTransactionAssertion $transactionAssert */ $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); - $assertionResponse = $transactionAssert->assert($cartId); //todo just a cart id + $assertionResponse = $transactionAssert->assert($cartId); $orderId = \Order::getOrderByCartId($cartId); - //todo repo to get saferpayOrder + /** @var SaferPayOrderStatusService $orderStatusService */ $orderStatusService = $this->module->getService(SaferPayOrderStatusService::class); - $orderStatusService->assert($saferPayOrder, $assertionResponse->getTransaction()->getStatus()); + $orderStatusService->assert(new Order($orderId), $assertionResponse->getTransaction()->getStatus()); return $assertionResponse; } diff --git a/controllers/front/return.php b/controllers/front/return.php index 27ee03f7..8fed3f93 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -24,6 +24,8 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; use Invertus\SaferPay\DTO\Response\Assert\AssertBody; +use Invertus\SaferPay\Enum\ControllerName; +use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\TransactionFlow\SaferPayTransactionAssertion; use Invertus\SaferPay\Processor\CheckoutProcessor; @@ -70,13 +72,15 @@ public function postProcess() $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); $assertionResponse = $transactionAssert->assert($cartId); - if (!$orderId) { // todo check config too + if (!$orderId) { + $paymentMethod = $assertionResponse->getPaymentMeans()->getBrand()->getPaymentMethod(); + /** @var CheckoutProcessor $checkoutProcessor **/ $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); - $checkoutProcessor->processCreateOrder(new \Cart($cartId), 'MASTERCARD'); // todo payment method if not in assertionResone then add to response + $checkoutProcessor->processCreateOrderAfterAuthorization(new \Cart($cartId), $paymentMethod); } - $orderId = \Order::getOrderByCartId($cartId); + $orderId = \Order::getIdByCartId($cartId); Tools::redirect($this->context->link->getModuleLink( $this->module->name, @@ -114,14 +118,14 @@ public function postProcess() private function getSuccessControllerName($isBusinessLicence, $fieldToken) { - $successController = 'success'; + $successController = ControllerName::SUCCESS; if ($isBusinessLicence) { - $successController = 'successIFrame'; + $successController = ControllerName::SUCCESS_IFRAME; } if ($fieldToken) { - $successController = 'successHosted'; + $successController = ControllerName::SUCCESS_HOSTED; } return $successController; diff --git a/controllers/front/validation.php b/controllers/front/validation.php index bb2b61e0..dbb211a6 100755 --- a/controllers/front/validation.php +++ b/controllers/front/validation.php @@ -23,9 +23,7 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; -use Invertus\SaferPay\Exception\Api\SaferPayApiException; use Invertus\SaferPay\Service\SaferPayExceptionService; -use Invertus\SaferPay\Service\SaferPayInitialize; use Invertus\SaferPay\Controller\Front\PaymentFrontController; if (!defined('_PS_VERSION_')) { @@ -102,7 +100,7 @@ public function postProcess() 'fail', [ 'cartId' => $this->context->cart->id, - 'orderId' => Order::getOrderByCartId($this->context->cart->id), + 'orderId' => Order::getIdByCartId($this->context->cart->id), 'secureKey' => $this->context->cart->secure_key, 'moduleId' => $this->module->id, ], diff --git a/src/EntityBuilder/SaferPayOrderBuilder.php b/src/EntityBuilder/SaferPayOrderBuilder.php index cba006d9..0ea782e4 100755 --- a/src/EntityBuilder/SaferPayOrderBuilder.php +++ b/src/EntityBuilder/SaferPayOrderBuilder.php @@ -37,11 +37,11 @@ class SaferPayOrderBuilder //TODO to pass $body as InitializeBody. public function create($body, $cartId, $customerId, $isTransaction) { - $orderId = Order::getOrderByCartId($cartId); + $orderId = Order::getIdByCartId($cartId); $saferPayOrder = new SaferPayOrder(); $saferPayOrder->token = $body->Token; - $saferPayOrder->id_order = $orderId ? $orderId : null; + $saferPayOrder->id_order = $orderId ?: null; $saferPayOrder->id_cart = $cartId; $saferPayOrder->id_customer = $customerId; $saferPayOrder->redirect_url = $this->getRedirectionUrl($body); diff --git a/src/Processor/CheckoutProcessor.php b/src/Processor/CheckoutProcessor.php index 7e9b85b2..e13777db 100644 --- a/src/Processor/CheckoutProcessor.php +++ b/src/Processor/CheckoutProcessor.php @@ -23,10 +23,14 @@ namespace Invertus\SaferPay\Processor; +use Cart; use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder; use Invertus\SaferPay\Factory\ModuleFactory; +use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\SaferPayInitialize; +use Order; +use SaferPayOrder; class CheckoutProcessor { @@ -39,17 +43,22 @@ class CheckoutProcessor /** @var SaferPayInitialize */ private $saferPayInitialize; + /** @var SaferPayOrderRepository */ + private $saferPayOrderRepository; + public function __construct( ModuleFactory $module, SaferPayOrderBuilder $saferPayOrderBuilder, - SaferPayInitialize $saferPayInitialize + SaferPayInitialize $saferPayInitialize, + SaferPayOrderRepository $saferPayOrderRepository ) { $this->module = $module->getModule(); $this->saferPayOrderBuilder = $saferPayOrderBuilder; $this->saferPayInitialize = $saferPayInitialize; + $this->saferPayOrderRepository = $saferPayOrderRepository; } - public function processCreateOrder(\Cart $cart, $paymentMethod) + public function processCreateOrder(Cart $cart, $paymentMethod) { $customer = new \Customer($cart->id_customer); @@ -93,4 +102,15 @@ public function processCreateSaferPayOrder($initializeBody, $cartId, $customerId $isTransaction ); } + + public function processCreateOrderAfterAuthorization(Cart $cart, $paymentMethod) + { + $this->processCreateOrder($cart, $paymentMethod); + + $saferPayOrderId = $this->saferPayOrderRepository->getIdByCartId($cart->id); + $saferPayOrder = new SaferPayOrder($saferPayOrderId); + $saferPayOrder->id_order = Order::getIdByCartId($cart->id); + + $saferPayOrder->update(); + } } diff --git a/src/Repository/SaferPayOrderRepository.php b/src/Repository/SaferPayOrderRepository.php index 1223aeaf..034ad98e 100755 --- a/src/Repository/SaferPayOrderRepository.php +++ b/src/Repository/SaferPayOrderRepository.php @@ -32,6 +32,20 @@ class SaferPayOrderRepository { + /** + * @param int $cartId + * @return false|string + */ + public function getOrderByCartId($cartId) + { + $query = new DbQuery(); + $query->select('`*`'); + $query->from('saferpay_order'); + $query->where('id_cart = "' . (int) $cartId . '"'); + + return Db::getInstance()->getValue($query); + } + public function getIdByOrderId($orderId) { $query = new DbQuery(); diff --git a/src/Service/Request/AssertRequestObjectCreator.php b/src/Service/Request/AssertRequestObjectCreator.php index 662f17d8..20288215 100755 --- a/src/Service/Request/AssertRequestObjectCreator.php +++ b/src/Service/Request/AssertRequestObjectCreator.php @@ -51,10 +51,15 @@ public function __construct( $this->saferPayOrderRepository = $saferPayOrderRepository; } + /** + * @param string $token + * + * @return AssertRequest + */ public function create($token) { $requestHeader = $this->requestObjectCreator->createRequestHeader(); - return new AssertRequest($requestHeader, $saferPayOrder->token); + return new AssertRequest($requestHeader, $token); } } diff --git a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php index 88730bc7..edf72538 100755 --- a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php +++ b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php @@ -94,6 +94,7 @@ public function assert($cartId) } /** + * TODO DO WE NEED IT OR WE CAN JUST INSERT REPO INTO CLASS * @param $cartId * * @return false|SaferPayOrder @@ -101,7 +102,7 @@ public function assert($cartId) */ private function getSaferPayOrder($cartId) { - $saferPayOrderId = $this->orderRepository->getIdByCartId($orderId); + $saferPayOrderId = $this->orderRepository->getIdByCartId($cartId); return new SaferPayOrder($saferPayOrderId); } From ec58fbbfd516d080edfc715db02d5eb606f53b67 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Fri, 15 Dec 2023 16:45:02 +0200 Subject: [PATCH 05/18] cs-fixer --- .../AdminSaferPayOfficialOrderController.php | 2 +- controllers/front/ajax.php | 7 ++--- controllers/front/iframe.php | 2 -- controllers/front/notify.php | 3 +- controllers/front/return.php | 3 -- controllers/front/validation.php | 12 ++++---- src/Adapter/Configuration.php | 3 +- src/Config/SaferPayConfig.php | 2 +- .../Front/PaymentFrontController.php | 5 ---- src/Repository/SaferPayOrderRepository.php | 14 ---------- .../Request/AssertRequestObjectCreator.php | 1 - src/Service/SaferPayInitialize.php | 28 +++---------------- .../SaferPayTransactionAssertion.php | 1 - upgrade/install-1.2.0.php | 2 -- 14 files changed, 17 insertions(+), 68 deletions(-) diff --git a/controllers/admin/AdminSaferPayOfficialOrderController.php b/controllers/admin/AdminSaferPayOfficialOrderController.php index 7d5fc098..2facdb02 100755 --- a/controllers/admin/AdminSaferPayOfficialOrderController.php +++ b/controllers/admin/AdminSaferPayOfficialOrderController.php @@ -50,7 +50,7 @@ public function postProcess() $orderStatusService->capture($order); $this->context->cookie->captured = true; } elseif (Tools::isSubmit('submitCancelOrder')) { - $orderStatusService->cancel($order); //todo saferPayOrder + $orderStatusService->cancel($order); $this->context->cookie->canceled = true; } elseif (Tools::isSubmit('submitRefundOrder')) { $refundAmount = Tools::getValue('saferpay_refund_amount'); diff --git a/controllers/front/ajax.php b/controllers/front/ajax.php index 0942d465..34a46087 100755 --- a/controllers/front/ajax.php +++ b/controllers/front/ajax.php @@ -23,8 +23,7 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\Front\PaymentFrontController; -use Invertus\SaferPay\Repository\SaferPayCardAliasRepository; -use Invertus\SaferPay\Service\SaferPayInitialize; +use Invertus\SaferPay\Enum\ControllerName; if (!defined('_PS_VERSION_')) { exit; @@ -46,7 +45,7 @@ public function postProcess() } } - private function submitHostedFields(): void + private function submitHostedFields() { try { /** @var PaymentFrontController $paymentFrontController */ @@ -66,7 +65,7 @@ private function submitHostedFields(): void (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE), Tools::getValue('selectedCard'), Tools::getValue('fieldToken'), - 'successHosted', + ControllerName::SUCCESS_HOSTED, true ); diff --git a/controllers/front/iframe.php b/controllers/front/iframe.php index edc09641..96bee23d 100755 --- a/controllers/front/iframe.php +++ b/controllers/front/iframe.php @@ -24,8 +24,6 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; use Invertus\SaferPay\Enum\ControllerName; -use Invertus\SaferPay\Repository\SaferPayCardAliasRepository; -use Invertus\SaferPay\Service\SaferPayInitialize; if (!defined('_PS_VERSION_')) { exit; diff --git a/controllers/front/notify.php b/controllers/front/notify.php index 45e46cc4..f37e8adf 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -41,7 +41,7 @@ class SaferPayOfficialNotifyModuleFrontController extends AbstractSaferPayContro * # WILL NOT work for local development, to AUTHORIZE payment this must be called manually. # * Example manual request: https://saferpay.demo.com/en/module/saferpayofficial/notify?success=1&cartId=12&orderId=12&secureKey=9366c61b59e918b2cd96ed0567c82e90 */ -//http://localhost/ps17810/index.php?fc=module&module=saferpayofficial&controller=notify&success=1&cartId=179&orderId=93&secureKey=6780efac67f4422574332bf887249bd7 //todo add correct data + //http://localhost/ps17810/index.php?fc=module&module=saferpayofficial&controller=notify&success=1&cartId=179&orderId=93&secureKey=6780efac67f4422574332bf887249bd7 //todo add correct data public function postProcess() { $cartId = Tools::getValue('cartId'); @@ -89,7 +89,6 @@ public function postProcess() $orderStatusService = $this->module->getService(SaferPayOrderStatusService::class); $orderStatusService->capture($order); } - } catch (Exception $e) { PrestaShopLogger::addLog( sprintf( diff --git a/controllers/front/return.php b/controllers/front/return.php index 8fed3f93..02ae7157 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -23,13 +23,10 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; -use Invertus\SaferPay\DTO\Response\Assert\AssertBody; use Invertus\SaferPay\Enum\ControllerName; -use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\TransactionFlow\SaferPayTransactionAssertion; use Invertus\SaferPay\Processor\CheckoutProcessor; - if (!defined('_PS_VERSION_')) { exit; } diff --git a/controllers/front/validation.php b/controllers/front/validation.php index dbb211a6..469b2acc 100755 --- a/controllers/front/validation.php +++ b/controllers/front/validation.php @@ -82,14 +82,14 @@ public function postProcess() $paymentFrontController = $this->module->getService(PaymentFrontController::class); $initializeResponse = $paymentFrontController->create( - $this->context->cart, - $paymentMethod, - (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE) - ); + $this->context->cart, + $paymentMethod, + (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE) + ); - $redirectLink = $paymentFrontController->getRedirectionUrl($initializeResponse); + $redirectLink = $paymentFrontController->getRedirectionUrl($initializeResponse); - Tools::redirect($redirectLink); + Tools::redirect($redirectLink); } catch (\Exception $exception) { /** @var SaferPayExceptionService $exceptionService */ $exceptionService = $this->module->getService(SaferPayExceptionService::class); diff --git a/src/Adapter/Configuration.php b/src/Adapter/Configuration.php index ab6f521c..d89f3203 100644 --- a/src/Adapter/Configuration.php +++ b/src/Adapter/Configuration.php @@ -24,7 +24,6 @@ namespace Invertus\SaferPay\Adapter; use Configuration as PrestaShopConfiguration; -use Invertus\SaferPay\Adapter\LegacyContext; if (!defined('_PS_VERSION_')) { exit; @@ -106,4 +105,4 @@ public function delete(string $id) { PrestaShopConfiguration::deleteByName($id); } -} \ No newline at end of file +} diff --git a/src/Config/SaferPayConfig.php b/src/Config/SaferPayConfig.php index a317be2a..f7279ff1 100755 --- a/src/Config/SaferPayConfig.php +++ b/src/Config/SaferPayConfig.php @@ -376,7 +376,7 @@ public static function getUninstallConfiguration() self::FIELDS_ACCESS_TOKEN . self::TEST_SUFFIX, self::FIELDS_LIBRARY, self::FIELDS_LIBRARY . self::TEST_SUFFIX, - self::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION + self::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION, ]; } diff --git a/src/Controller/Front/PaymentFrontController.php b/src/Controller/Front/PaymentFrontController.php index 9aa18c35..b6a7fbbb 100644 --- a/src/Controller/Front/PaymentFrontController.php +++ b/src/Controller/Front/PaymentFrontController.php @@ -23,15 +23,12 @@ namespace Invertus\SaferPay\Controller\Front; -use Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder; use Invertus\SaferPay\Processor\CheckoutProcessor; -use Invertus\SaferPay\Service\SaferPayInitialize; use Invertus\SaferPay\Adapter\Configuration; use Invertus\SaferPay\Config\SaferPayConfig; class PaymentFrontController { - /** * @var CheckoutProcessor */ @@ -78,8 +75,6 @@ public function create(\Cart $cart, $paymentMethod, $isBusinessLicense, $selecte } /** - * TODO Extract initializeBody to class and have method to get redirectionUrl - * * @param object $initializeBody * * @return string diff --git a/src/Repository/SaferPayOrderRepository.php b/src/Repository/SaferPayOrderRepository.php index 034ad98e..1223aeaf 100755 --- a/src/Repository/SaferPayOrderRepository.php +++ b/src/Repository/SaferPayOrderRepository.php @@ -32,20 +32,6 @@ class SaferPayOrderRepository { - /** - * @param int $cartId - * @return false|string - */ - public function getOrderByCartId($cartId) - { - $query = new DbQuery(); - $query->select('`*`'); - $query->from('saferpay_order'); - $query->where('id_cart = "' . (int) $cartId . '"'); - - return Db::getInstance()->getValue($query); - } - public function getIdByOrderId($orderId) { $query = new DbQuery(); diff --git a/src/Service/Request/AssertRequestObjectCreator.php b/src/Service/Request/AssertRequestObjectCreator.php index 20288215..34c1ef83 100755 --- a/src/Service/Request/AssertRequestObjectCreator.php +++ b/src/Service/Request/AssertRequestObjectCreator.php @@ -25,7 +25,6 @@ use Invertus\SaferPay\DTO\Request\Assert\AssertRequest; use Invertus\SaferPay\Repository\SaferPayOrderRepository; -use SaferPayOrder; if (!defined('_PS_VERSION_')) { exit; diff --git a/src/Service/SaferPayInitialize.php b/src/Service/SaferPayInitialize.php index cab4e6d9..ddc6e217 100755 --- a/src/Service/SaferPayInitialize.php +++ b/src/Service/SaferPayInitialize.php @@ -67,9 +67,7 @@ class SaferPayInitialize /** @var SaferPayCardAliasRepository */ private $saferPayCardAliasRepository; - /** - * @var Configuration - */ + /** @var Configuration */ private $configuration; public function __construct( @@ -117,7 +115,7 @@ public function buildRequest( [ 'cartId' => $cartId, 'secureKey' => $this->context->cart->secure_key, - 'orderId' => $creationAfterInitialization ? 0 :Order::getOrderByCartId($cartId), + 'orderId' => $creationAfterInitialization ? 0 : Order::getOrderByCartId($cartId), 'moduleId' => $this->module->id, 'selectedCard' => $selectedCard, 'isBusinessLicence' => $isBusinessLicence, @@ -132,7 +130,7 @@ public function buildRequest( [ 'success' => 1, 'cartId' => $this->context->cart->id, - 'orderId' => $creationAfterInitialization ? 0 :Order::getOrderByCartId($cartId), + 'orderId' => $creationAfterInitialization ? 0 : Order::getOrderByCartId($cartId), 'secureKey' => $this->context->cart->secure_key, ], true @@ -140,7 +138,7 @@ public function buildRequest( $failUrl = $this->context->link->getModuleLink( $this->module->name, - 'failValidation', + ControllerName::FAIL_VALIDATION, [ 'cartId' => $this->context->cart->id, 'secureKey' => $this->context->cart->secure_key, @@ -167,22 +165,4 @@ public function buildRequest( return $initializeRequest; } - - /** - * @param int $isBusinessLicence - * @param string $fieldToken - * - * @return string - */ - private function getSuccessControllerName($isBusinessLicence, $fieldToken) - { - $successController = 'success'; - if ($isBusinessLicence) { - $successController = 'successIFrame'; - } - if ($fieldToken) { - $successController = 'successHosted'; - } - return $successController; - } } diff --git a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php index edf72538..dcd3707a 100755 --- a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php +++ b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php @@ -28,7 +28,6 @@ use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\Request\AssertRequestObjectCreator; use Invertus\SaferPay\Service\SaferPayOrderStatusService; -use Order; use SaferPayOrder; if (!defined('_PS_VERSION_')) { diff --git a/upgrade/install-1.2.0.php b/upgrade/install-1.2.0.php index d667e728..4a7df724 100644 --- a/upgrade/install-1.2.0.php +++ b/upgrade/install-1.2.0.php @@ -22,7 +22,6 @@ */ use Invertus\SaferPay\Config\SaferPayConfig; -use Invertus\SaferPay\DTO\Request\RequestHeader; use Configuration; if (!defined('_PS_VERSION_')) { @@ -49,4 +48,3 @@ function upgrade_module_1_2_0($module) return true; } - From 3cfb616b0644d6749033296eedb7be76c11211b6 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Mon, 18 Dec 2023 15:41:12 +0200 Subject: [PATCH 06/18] feat: implemented logic into notify controller --- controllers/front/notify.php | 52 +++++++++++++++---- controllers/front/pendingNotify.php | 6 ++- .../Order/Action/UpdateOrderStatusAction.php | 50 ++++++++++++++++++ src/Entity/SaferPayOrder.php | 2 +- src/Service/SaferPayOrderStatusService.php | 23 -------- .../SaferPayTransactionAssertion.php | 13 +---- 6 files changed, 100 insertions(+), 46 deletions(-) create mode 100644 src/Core/Order/Action/UpdateOrderStatusAction.php diff --git a/controllers/front/notify.php b/controllers/front/notify.php index f37e8adf..5a4bcfb2 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -24,7 +24,10 @@ use Invertus\SaferPay\Api\Enum\TransactionStatus; use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; +use Invertus\SaferPay\Core\Order\Action\UpdateOrderStatusAction; use Invertus\SaferPay\DTO\Response\Assert\AssertBody; +use Invertus\SaferPay\Processor\CheckoutProcessor; +use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\SaferPayOrderStatusService; use Invertus\SaferPay\Service\TransactionFlow\SaferPayTransactionAssertion; @@ -41,11 +44,10 @@ class SaferPayOfficialNotifyModuleFrontController extends AbstractSaferPayContro * # WILL NOT work for local development, to AUTHORIZE payment this must be called manually. # * Example manual request: https://saferpay.demo.com/en/module/saferpayofficial/notify?success=1&cartId=12&orderId=12&secureKey=9366c61b59e918b2cd96ed0567c82e90 */ - //http://localhost/ps17810/index.php?fc=module&module=saferpayofficial&controller=notify&success=1&cartId=179&orderId=93&secureKey=6780efac67f4422574332bf887249bd7 //todo add correct data + //http://localhost/ps17810/index.php?fc=module&module=saferpayofficial&controller=notify&success=1&cartId=223&orderId=0&secureKey=26496a9004c1d081062e00bf2a1f9254 //todo add correct data public function postProcess() { $cartId = Tools::getValue('cartId'); - $orderId = Tools::getValue('orderId'); $secureKey = Tools::getValue('secureKey'); $cart = new Cart($cartId); @@ -63,18 +65,36 @@ public function postProcess() try { $assertResponseBody = $this->assertTransaction($cartId); + $this->authorizeSaferPayOrderEntity($cartId); + + // If order does not exist but assertion is valid that means order authorized or captured. + $orderId = Order::getIdByCartId($cartId); + + if (!$orderId) { + /** @var CheckoutProcessor $checkoutProcessor **/ + $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); + $checkoutProcessor + ->processCreateOrderAfterAuthorization( + $cart, + $assertResponseBody->getPaymentMeans()->getBrand()->getPaymentMethod() + ); + } //TODO look into pipeline design pattern to use when object is modified in multiple places to avoid this issue. //NOTE must be left below assert action to get newest information. $order = new Order($orderId); + /** @var UpdateOrderStatusAction $updateOrderStatusAction **/ + $updateOrderStatusAction = $this->module->getService(UpdateOrderStatusAction::class); + $updateOrderStatusAction->run($order, $assertResponseBody->getTransaction()->getStatus()); + if (!$assertResponseBody->getLiability()->getLiabilityShift() && in_array($order->payment, SaferPayConfig::SUPPORTED_3DS_PAYMENT_METHODS) && (int) Configuration::get(SaferPayConfig::PAYMENT_BEHAVIOR_WITHOUT_3D) === SaferPayConfig::PAYMENT_BEHAVIOR_WITHOUT_3D_CANCEL ) { /** @var SaferPayOrderStatusService $orderStatusService */ $orderStatusService = $this->module->getService(SaferPayOrderStatusService::class); - $orderStatusService->cancel($cart); + $orderStatusService->cancel($order); die($this->module->l('Liability shift is false', self::FILENAME)); } @@ -118,19 +138,33 @@ private function assertTransaction($cartId) { /** @var SaferPayTransactionAssertion $transactionAssert */ $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); - $assertionResponse = $transactionAssert->assert($cartId); + return $transactionAssert->assert($cartId); + } - $orderId = \Order::getOrderByCartId($cartId); + /** + * @param $cartId + * @return void + * @throws PrestaShopDatabaseException + * @throws PrestaShopException + */ + private function authorizeSaferPayOrderEntity($cartId) + { + /** @var SaferPayOrderRepository $saferPayOrderRepository */ + $saferPayOrderRepository = $this->module->getService(SaferPayOrderRepository::class); + $saferPayOrderId = $saferPayOrderRepository->getIdByCartId($cartId); + $saferPayOrder = new SaferPayOrder($saferPayOrderId); - /** @var SaferPayOrderStatusService $orderStatusService */ - $orderStatusService = $this->module->getService(SaferPayOrderStatusService::class); - $orderStatusService->assert(new Order($orderId), $assertionResponse->getTransaction()->getStatus()); + if ($saferPayOrder->authorized) { + return; + } - return $assertionResponse; + $saferPayOrder->authorized = 1; + $saferPayOrder->update(); } protected function displayMaintenancePage() { return true; } + } diff --git a/controllers/front/pendingNotify.php b/controllers/front/pendingNotify.php index 208aa062..43c6639a 100755 --- a/controllers/front/pendingNotify.php +++ b/controllers/front/pendingNotify.php @@ -43,22 +43,24 @@ class SaferPayOfficialPendingNotifyModuleFrontController extends AbstractSaferPa public function postProcess() { $cartId = Tools::getValue('cartId'); - $orderId = Tools::getValue('orderId'); $secureKey = Tools::getValue('secureKey'); $cart = new Cart($cartId); + if ($cart->secure_key !== $secureKey) { die($this->module->l('Error. Insecure cart', self::FILENAME)); } + /** @var SaferPayOrderRepository $saferPayOrderRepository */ $saferPayOrderRepository = $this->module->getService(SaferPayOrderRepository::class); - $saferPayOrderId = $saferPayOrderRepository->getIdByOrderId($orderId); + $saferPayOrderId = $saferPayOrderRepository->getIdByCartId($cartId); $orderRefunds = $saferPayOrderRepository->getOrderRefunds($saferPayOrderId); foreach ($orderRefunds as $orderRefund) { if ($orderRefund['status'] === SaferPayConfig::TRANSACTION_STATUS_CAPTURED) { continue; } + $assertRefundResponse = $this->assertRefundTransaction($orderRefund['transaction_id']); if ($assertRefundResponse->getStatus() === SaferPayConfig::TRANSACTION_STATUS_CAPTURED) { $this->handleCapturedRefund($orderRefund['id_saferpay_order_refund']); diff --git a/src/Core/Order/Action/UpdateOrderStatusAction.php b/src/Core/Order/Action/UpdateOrderStatusAction.php new file mode 100644 index 00000000..082daf68 --- /dev/null +++ b/src/Core/Order/Action/UpdateOrderStatusAction.php @@ -0,0 +1,50 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Core\Order\Action; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class UpdateOrderStatusAction +{ + const STATUS_AUTHORIZED = 'AUTHORIZED'; + const STATUS_CAPTURED = 'CAPTURED'; + + public function run(\Order $order, $orderStatus) + { + switch ($orderStatus) { + case self::STATUS_AUTHORIZED: + $order->setCurrentState(_SAFERPAY_PAYMENT_AUTHORIZED_); + break; + case self::STATUS_CAPTURED: + $order->setCurrentState(_SAFERPAY_PAYMENT_COMPLETED_); + break; + default: + die('Order status is invalid'); + } + + $order->update(); + } +} diff --git a/src/Entity/SaferPayOrder.php b/src/Entity/SaferPayOrder.php index 64cd7331..69240344 100755 --- a/src/Entity/SaferPayOrder.php +++ b/src/Entity/SaferPayOrder.php @@ -92,7 +92,7 @@ class SaferPayOrder extends ObjectModel 'table' => 'saferpay_order', 'primary' => 'id_saferpay_order', 'fields' => [ - 'id_order' => ['type' => self::TYPE_INT, 'validate' => 'isInt', 'required' => false], + 'id_order' => ['type' => self::TYPE_NOTHING, 'allow_null' => true], 'id_cart' => ['type' => self::TYPE_INT, 'validate' => 'isInt'], 'id_customer' => ['type' => self::TYPE_INT, 'validate' => 'isInt'], 'transaction_id' => ['type' => self::TYPE_STRING, 'validate' => 'isString'], diff --git a/src/Service/SaferPayOrderStatusService.php b/src/Service/SaferPayOrderStatusService.php index b3122096..0894beef 100755 --- a/src/Service/SaferPayOrderStatusService.php +++ b/src/Service/SaferPayOrderStatusService.php @@ -127,29 +127,6 @@ public function authorize(Order $order) $order->update(); } - /** - * @param Order $order - * - * @throws \Exception - */ - public function assert(Order $order, $status = 'AUTHORIZED') - { - $saferPayOrderId = $this->orderRepository->getIdByOrderId($order->id); - $saferPayOrder = new SaferPayOrder($saferPayOrderId); - if ($saferPayOrder->authorized) { - return; - } - $saferPayOrder->authorized = 1; - if ($status === 'AUTHORIZED') { - $order->setCurrentState(_SAFERPAY_PAYMENT_AUTHORIZED_); - } elseif ($status === 'CAPTURED') { - $order->setCurrentState(_SAFERPAY_PAYMENT_COMPLETED_); - } - - $saferPayOrder->update(); - $order->update(); - } - /** TODO extract capture api code to different service like Assert for readability */ public function capture(Order $order, $refundedAmount = 0, $isRefund = false) { diff --git a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php index dcd3707a..b53352a5 100755 --- a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php +++ b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php @@ -27,7 +27,6 @@ use Invertus\SaferPay\DTO\Response\Assert\AssertBody; use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\Request\AssertRequestObjectCreator; -use Invertus\SaferPay\Service\SaferPayOrderStatusService; use SaferPayOrder; if (!defined('_PS_VERSION_')) { @@ -51,25 +50,18 @@ class SaferPayTransactionAssertion */ private $assertionService; - /** - * @var SaferPayOrderStatusService - */ - private $orderStatusService; - public function __construct( AssertRequestObjectCreator $assertRequestCreator, SaferPayOrderRepository $orderRepository, - AssertService $assertionService, - SaferPayOrderStatusService $orderStatusService + AssertService $assertionService ) { $this->assertRequestCreator = $assertRequestCreator; $this->orderRepository = $orderRepository; $this->assertionService = $assertionService; - $this->orderStatusService = $orderStatusService; } /** - * @param int $orderId + * @param int $cartId * * @return AssertBody * @throws \Exception @@ -93,7 +85,6 @@ public function assert($cartId) } /** - * TODO DO WE NEED IT OR WE CAN JUST INSERT REPO INTO CLASS * @param $cartId * * @return false|SaferPayOrder From 2f9daa866c72256ee99e4e1bb5d86f8aec330b88 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Tue, 19 Dec 2023 09:27:45 +0200 Subject: [PATCH 07/18] removed not needed methods --- controllers/front/notify.php | 18 ++++-------------- src/Processor/CheckoutProcessor.php | 3 +-- .../SaferPayTransactionAssertion.php | 17 ++--------------- 3 files changed, 7 insertions(+), 31 deletions(-) diff --git a/controllers/front/notify.php b/controllers/front/notify.php index 5a4bcfb2..52dedc38 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -64,7 +64,10 @@ public function postProcess() } try { - $assertResponseBody = $this->assertTransaction($cartId); + /** @var SaferPayTransactionAssertion $transactionAssert */ + $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); + $assertResponseBody = $transactionAssert->assert($cartId); + $this->authorizeSaferPayOrderEntity($cartId); // If order does not exist but assertion is valid that means order authorized or captured. @@ -128,19 +131,6 @@ public function postProcess() die($this->module->l('Success', self::FILENAME)); } - /** - * @param int $cartId - * - * @return AssertBody - * @throws Exception - */ - private function assertTransaction($cartId) - { - /** @var SaferPayTransactionAssertion $transactionAssert */ - $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); - return $transactionAssert->assert($cartId); - } - /** * @param $cartId * @return void diff --git a/src/Processor/CheckoutProcessor.php b/src/Processor/CheckoutProcessor.php index e13777db..0903dd0c 100644 --- a/src/Processor/CheckoutProcessor.php +++ b/src/Processor/CheckoutProcessor.php @@ -107,8 +107,7 @@ public function processCreateOrderAfterAuthorization(Cart $cart, $paymentMethod) { $this->processCreateOrder($cart, $paymentMethod); - $saferPayOrderId = $this->saferPayOrderRepository->getIdByCartId($cart->id); - $saferPayOrder = new SaferPayOrder($saferPayOrderId); + $saferPayOrder = new SaferPayOrder($this->saferPayOrderRepository->getIdByCartId($cart->id)); $saferPayOrder->id_order = Order::getIdByCartId($cart->id); $saferPayOrder->update(); diff --git a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php index b53352a5..4b3aba86 100755 --- a/src/Service/TransactionFlow/SaferPayTransactionAssertion.php +++ b/src/Service/TransactionFlow/SaferPayTransactionAssertion.php @@ -61,14 +61,14 @@ public function __construct( } /** - * @param int $cartId + * @param string $cartId * * @return AssertBody * @throws \Exception */ public function assert($cartId) { - $saferPayOrder = $this->getSaferPayOrder($cartId); + $saferPayOrder = new SaferPayOrder($this->orderRepository->getIdByCartId($cartId)); $assertRequest = $this->assertRequestCreator->create($saferPayOrder->token); $assertResponse = $this->assertionService->assert($assertRequest, $saferPayOrder->id); @@ -83,17 +83,4 @@ public function assert($cartId) return $assertBody; } - - /** - * @param $cartId - * - * @return false|SaferPayOrder - * @throws \Exception - */ - private function getSaferPayOrder($cartId) - { - $saferPayOrderId = $this->orderRepository->getIdByCartId($cartId); - - return new SaferPayOrder($saferPayOrderId); - } } From f1704ef978bc974aafa1c670134c9ee3b4eeeaa1 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Tue, 19 Dec 2023 09:34:35 +0200 Subject: [PATCH 08/18] remove comment --- controllers/front/notify.php | 1 - 1 file changed, 1 deletion(-) diff --git a/controllers/front/notify.php b/controllers/front/notify.php index 52dedc38..d285c53b 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -44,7 +44,6 @@ class SaferPayOfficialNotifyModuleFrontController extends AbstractSaferPayContro * # WILL NOT work for local development, to AUTHORIZE payment this must be called manually. # * Example manual request: https://saferpay.demo.com/en/module/saferpayofficial/notify?success=1&cartId=12&orderId=12&secureKey=9366c61b59e918b2cd96ed0567c82e90 */ - //http://localhost/ps17810/index.php?fc=module&module=saferpayofficial&controller=notify&success=1&cartId=223&orderId=0&secureKey=26496a9004c1d081062e00bf2a1f9254 //todo add correct data public function postProcess() { $cartId = Tools::getValue('cartId'); From bf9c579d0f26744b621bc2ba9da4607c46ec7b81 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Tue, 19 Dec 2023 09:37:54 +0200 Subject: [PATCH 09/18] indexes added --- controllers/front/notify.php | 2 -- src/Controller/Front/index.php | 11 +++++++++++ src/Core/Order/Action/index.php | 31 +++++++++++++++++++++++++++++++ src/Processor/index.php | 11 +++++++++++ 4 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 src/Controller/Front/index.php create mode 100644 src/Core/Order/Action/index.php create mode 100644 src/Processor/index.php diff --git a/controllers/front/notify.php b/controllers/front/notify.php index d285c53b..48f62bfe 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -25,7 +25,6 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; use Invertus\SaferPay\Core\Order\Action\UpdateOrderStatusAction; -use Invertus\SaferPay\DTO\Response\Assert\AssertBody; use Invertus\SaferPay\Processor\CheckoutProcessor; use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\SaferPayOrderStatusService; @@ -155,5 +154,4 @@ protected function displayMaintenancePage() { return true; } - } diff --git a/src/Controller/Front/index.php b/src/Controller/Front/index.php new file mode 100644 index 00000000..15aba820 --- /dev/null +++ b/src/Controller/Front/index.php @@ -0,0 +1,11 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../'); +exit; diff --git a/src/Processor/index.php b/src/Processor/index.php new file mode 100644 index 00000000..15aba820 --- /dev/null +++ b/src/Processor/index.php @@ -0,0 +1,11 @@ + Date: Tue, 19 Dec 2023 15:23:33 +0200 Subject: [PATCH 10/18] moved checkout data into dto and refactored processor --- changelog.md | 4 +- ...dminSaferPayOfficialSettingsController.php | 2 +- controllers/front/ajax.php | 13 +- controllers/front/fail.php | 2 +- controllers/front/iframe.php | 14 +- controllers/front/notify.php | 52 +++--- controllers/front/return.php | 11 +- controllers/front/validation.php | 15 +- src/Adapter/Configuration.php | 35 +++- ...tController.php => CheckoutController.php} | 42 +---- .../Order/Action/UpdateOrderStatusAction.php | 43 +++-- src/Core/Payment/DTO/CheckoutData.php | 168 ++++++++++++++++++ src/Core/Payment/DTO/index.php | 31 ++++ .../Action/UpdateSaferPayOrderAction.php | 65 +++++++ src/Core/SaferPayOrder/Action/index.php | 31 ++++ src/Core/SaferPayOrder/index.php | 31 ++++ src/Exception/CouldNotProcessCheckout.php | 76 ++++++++ src/Exception/ExceptionCode.php | 43 +++++ .../Order/CouldNotChangeOrderStatus.php | 65 +++++++ src/Exception/Order/index.php | 31 ++++ src/Exception/SaferPayException.php | 63 +++++++ src/Install/Installer.php | 3 +- src/Processor/CheckoutProcessor.php | 98 ++++++++-- 23 files changed, 816 insertions(+), 122 deletions(-) rename src/Controller/Front/{PaymentFrontController.php => CheckoutController.php} (55%) create mode 100644 src/Core/Payment/DTO/CheckoutData.php create mode 100644 src/Core/Payment/DTO/index.php create mode 100644 src/Core/SaferPayOrder/Action/UpdateSaferPayOrderAction.php create mode 100644 src/Core/SaferPayOrder/Action/index.php create mode 100644 src/Core/SaferPayOrder/index.php create mode 100644 src/Exception/CouldNotProcessCheckout.php create mode 100644 src/Exception/ExceptionCode.php create mode 100644 src/Exception/Order/CouldNotChangeOrderStatus.php create mode 100644 src/Exception/Order/index.php create mode 100644 src/Exception/SaferPayException.php diff --git a/changelog.md b/changelog.md index e710fd77..89c98abd 100755 --- a/changelog.md +++ b/changelog.md @@ -144,6 +144,6 @@ ## [1.1.7] - * - BO : Added PrestaShop module security validations - FO : Added PrestaShop module security validations -- + - ## [1.2.0] - * -- BO : TODO +- BO : Added order creation after authorization functionality diff --git a/controllers/admin/AdminSaferPayOfficialSettingsController.php b/controllers/admin/AdminSaferPayOfficialSettingsController.php index a28d6fc1..94b3d7b1 100755 --- a/controllers/admin/AdminSaferPayOfficialSettingsController.php +++ b/controllers/admin/AdminSaferPayOfficialSettingsController.php @@ -275,7 +275,7 @@ public function initOptions() 1 => $this->l('After authorization'), 0 => $this->l('Before authorization'), ], - 'desc' => $this->l('TODO'), + 'desc' => $this->l('Select the option to determine whether the order should be created'), 'form_group_class' => 'thumbs_chose', ], ], diff --git a/controllers/front/ajax.php b/controllers/front/ajax.php index 34a46087..0ddabf00 100755 --- a/controllers/front/ajax.php +++ b/controllers/front/ajax.php @@ -22,7 +22,8 @@ */ use Invertus\SaferPay\Config\SaferPayConfig; -use Invertus\SaferPay\Controller\Front\PaymentFrontController; +use Invertus\SaferPay\Controller\Front\CheckoutController; +use Invertus\SaferPay\Core\Payment\DTO\CheckoutData; use Invertus\SaferPay\Enum\ControllerName; if (!defined('_PS_VERSION_')) { @@ -48,9 +49,6 @@ public function postProcess() private function submitHostedFields() { try { - /** @var PaymentFrontController $paymentFrontController */ - $paymentFrontController = $this->module->getService(PaymentFrontController::class); - if (Order::getOrderByCartId($this->context->cart->id)) { $this->ajaxDie(json_encode([ 'error' => true, @@ -59,7 +57,8 @@ private function submitHostedFields() ])); } - $initializeResponse = $paymentFrontController->create( + // refactor it to create checkout data from validator request + $checkoutData = CheckoutData::createFromRequest( $this->context->cart, Tools::getValue('paymentMethod'), (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE), @@ -69,7 +68,9 @@ private function submitHostedFields() true ); - $redirectUrl = $paymentFrontController->getRedirectionUrl($initializeResponse); + /** @var CheckoutController $checkoutController */ + $checkoutController = $this->module->getService(CheckoutController::class); + $redirectUrl = $checkoutController->execute($checkoutData); if (empty($redirectUrl)) { $redirectUrl = $this->getRedirectionToControllerUrl('successHosted'); diff --git a/controllers/front/fail.php b/controllers/front/fail.php index 52300df8..19530f8b 100755 --- a/controllers/front/fail.php +++ b/controllers/front/fail.php @@ -71,7 +71,7 @@ public function init() $cart = new Cart($this->id_cart); - if (!$this->module->id || !$this->secure_key || empty($this->secure_key)) { + if (!$this->module->id || empty($this->secure_key)) { Tools::redirect($redirectLink . (Tools::isSubmit('slowvalidation') ? '&slowvalidation' : '')); } diff --git a/controllers/front/iframe.php b/controllers/front/iframe.php index 96bee23d..6ac262a8 100755 --- a/controllers/front/iframe.php +++ b/controllers/front/iframe.php @@ -23,6 +23,8 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; +use Invertus\SaferPay\Controller\Front\CheckoutController; +use Invertus\SaferPay\Core\Payment\DTO\CheckoutData; use Invertus\SaferPay\Enum\ControllerName; if (!defined('_PS_VERSION_')) { @@ -84,17 +86,19 @@ public function initContent() } try { - /** @var \Invertus\SaferPay\Controller\Front\PaymentFrontController $paymentFrontController */ - $paymentFrontController = $this->module->getModuleContainer()->get(\Invertus\SaferPay\Controller\Front\PaymentFrontController::class); + /** @var CheckoutController $checkoutController */ + $checkoutController = $this->module->getService(CheckoutController::class); - $initializeResponse = $paymentFrontController->create( + // refactor it to create checkout data from validator request + $checkoutData = CheckoutData::createFromRequest( $this->context->cart, $paymentMethod, - Tools::getValue(\Invertus\SaferPay\Config\SaferPayConfig::IS_BUSINESS_LICENCE), + Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE), $selectedCard ); - $redirectUrl = $paymentFrontController->getRedirectionUrl($initializeResponse); + $redirectUrl = $checkoutController->execute($checkoutData); + } catch (\Exception $exception) { $redirectUrl = $this->context->link->getModuleLink( $this->module->name, diff --git a/controllers/front/notify.php b/controllers/front/notify.php index 48f62bfe..ac1e6e6f 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -25,6 +25,8 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; use Invertus\SaferPay\Core\Order\Action\UpdateOrderStatusAction; +use Invertus\SaferPay\Core\Payment\DTO\CheckoutData; +use Invertus\SaferPay\Core\SaferPayOrder\Action\UpdateSaferPayOrderAction; use Invertus\SaferPay\Processor\CheckoutProcessor; use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\SaferPayOrderStatusService; @@ -37,6 +39,7 @@ class SaferPayOfficialNotifyModuleFrontController extends AbstractSaferPayController { const FILENAME = 'notify'; + const SAFERPAY_ORDER_AUTHORIZE_ACTION = 'AUTHORIZE'; /** * This code is being called by SaferPay by using NotifyUrl in InitializeRequest. @@ -62,11 +65,15 @@ public function postProcess() } try { - /** @var SaferPayTransactionAssertion $transactionAssert */ - $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); - $assertResponseBody = $transactionAssert->assert($cartId); + $assertResponseBody = $this->assertTransaction($cartId); - $this->authorizeSaferPayOrderEntity($cartId); + /** @var SaferPayOrderRepository $saferPayOrderRepository */ + $saferPayOrderRepository = $this->module->getService(SaferPayOrderRepository::class); + $saferPayOrderId = $saferPayOrderRepository->getIdByCartId($cartId); + + /** @var UpdateSaferPayOrderAction $updateSaferPayOrderAction */ + $updateSaferPayOrderAction = $this->module->getService(UpdateSaferPayOrderAction::class); + $updateSaferPayOrderAction->run(new SaferPayOrder($saferPayOrderId), self::SAFERPAY_ORDER_AUTHORIZE_ACTION); // If order does not exist but assertion is valid that means order authorized or captured. $orderId = Order::getIdByCartId($cartId); @@ -74,11 +81,14 @@ public function postProcess() if (!$orderId) { /** @var CheckoutProcessor $checkoutProcessor **/ $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); - $checkoutProcessor - ->processCreateOrderAfterAuthorization( - $cart, - $assertResponseBody->getPaymentMeans()->getBrand()->getPaymentMethod() - ); + $checkoutData = CheckoutData::createFromRequest( + $cart, + $assertResponseBody->getPaymentMeans()->getBrand()->getPaymentMethod(), + Configuration::get(SaferPayConfig::IS_BUSINESS_LICENCE) + ); + $checkoutData->setIsAuthorizedOrder(true); + + $checkoutProcessor->run($checkoutData); } //TODO look into pipeline design pattern to use when object is modified in multiple places to avoid this issue. @@ -87,7 +97,7 @@ public function postProcess() /** @var UpdateOrderStatusAction $updateOrderStatusAction **/ $updateOrderStatusAction = $this->module->getService(UpdateOrderStatusAction::class); - $updateOrderStatusAction->run($order, $assertResponseBody->getTransaction()->getStatus()); + $updateOrderStatusAction->run((int) $orderId, (int) Configuration::get('SAFERPAY_PAYMENT_AUTHORIZED')); if (!$assertResponseBody->getLiability()->getLiabilityShift() && in_array($order->payment, SaferPayConfig::SUPPORTED_3DS_PAYMENT_METHODS) && @@ -129,25 +139,11 @@ public function postProcess() die($this->module->l('Success', self::FILENAME)); } - /** - * @param $cartId - * @return void - * @throws PrestaShopDatabaseException - * @throws PrestaShopException - */ - private function authorizeSaferPayOrderEntity($cartId) - { - /** @var SaferPayOrderRepository $saferPayOrderRepository */ - $saferPayOrderRepository = $this->module->getService(SaferPayOrderRepository::class); - $saferPayOrderId = $saferPayOrderRepository->getIdByCartId($cartId); - $saferPayOrder = new SaferPayOrder($saferPayOrderId); - - if ($saferPayOrder->authorized) { - return; - } + private function assertTransaction($cartId) { + /** @var SaferPayTransactionAssertion $transactionAssert */ + $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); - $saferPayOrder->authorized = 1; - $saferPayOrder->update(); + return $transactionAssert->assert(Order::getIdByCartId($cartId)); } protected function displayMaintenancePage() diff --git a/controllers/front/return.php b/controllers/front/return.php index 02ae7157..a4105b40 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -23,6 +23,7 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; +use Invertus\SaferPay\Core\Payment\DTO\CheckoutData; use Invertus\SaferPay\Enum\ControllerName; use Invertus\SaferPay\Service\TransactionFlow\SaferPayTransactionAssertion; use Invertus\SaferPay\Processor\CheckoutProcessor; @@ -70,11 +71,17 @@ public function postProcess() $assertionResponse = $transactionAssert->assert($cartId); if (!$orderId) { - $paymentMethod = $assertionResponse->getPaymentMeans()->getBrand()->getPaymentMethod(); + $checkoutData = CheckoutData::createFromRequest( + new \Cart($cartId), + $assertionResponse->getPaymentMeans()->getBrand()->getPaymentMethod(), + $isBusinessLicence + ); + + $checkoutData->setIsAuthorizedOrder(true); /** @var CheckoutProcessor $checkoutProcessor **/ $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); - $checkoutProcessor->processCreateOrderAfterAuthorization(new \Cart($cartId), $paymentMethod); + $checkoutProcessor->run($checkoutData); } $orderId = \Order::getIdByCartId($cartId); diff --git a/controllers/front/validation.php b/controllers/front/validation.php index 469b2acc..d3538d2b 100755 --- a/controllers/front/validation.php +++ b/controllers/front/validation.php @@ -23,8 +23,9 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; +use Invertus\SaferPay\Core\Payment\DTO\CheckoutData; use Invertus\SaferPay\Service\SaferPayExceptionService; -use Invertus\SaferPay\Controller\Front\PaymentFrontController; +use Invertus\SaferPay\Controller\Front\CheckoutController; if (!defined('_PS_VERSION_')) { exit; @@ -78,16 +79,16 @@ public function postProcess() } try { - /** @var PaymentFrontController $paymentFrontController */ - $paymentFrontController = $this->module->getService(PaymentFrontController::class); - - $initializeResponse = $paymentFrontController->create( - $this->context->cart, + /** @var CheckoutController $checkoutController */ + $checkoutController = $this->module->getService(CheckoutController::class); + // refactor it to create checkout data from validator request + $checkoutData = CheckoutData::createFromRequest( + $this->context->cart->id, $paymentMethod, (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE) ); - $redirectLink = $paymentFrontController->getRedirectionUrl($initializeResponse); + $redirectLink = $checkoutController->execute($checkoutData); Tools::redirect($redirectLink); } catch (\Exception $exception) { diff --git a/src/Adapter/Configuration.php b/src/Adapter/Configuration.php index d89f3203..0aad3b40 100644 --- a/src/Adapter/Configuration.php +++ b/src/Adapter/Configuration.php @@ -42,7 +42,13 @@ public function __construct(LegacyContext $context) $this->context = $context; } - public function set(string $id, $value, ?int $shopId = null) + /** + * @param string $id + * @param $value + * @param int|null $shopId + * @return void + */ + public function set($id, $value, $shopId = null) { if (!$shopId) { $shopId = $this->context->getShopId(); @@ -51,7 +57,12 @@ public function set(string $id, $value, ?int $shopId = null) PrestaShopConfiguration::updateValue($id, $value, false, null, $shopId); } - public function get(string $id, ?int $shopId = null) + /** + * @param string $id + * @param int|null $shopId + * @return false|string|null + */ + public function get($id, $shopId = null) { if (!$shopId) { $shopId = $this->context->getShopId(); @@ -62,7 +73,12 @@ public function get(string $id, ?int $shopId = null) return $result ?: null; } - public function getAsBoolean(string $id, ?int $shopId = null) + /** + * @param string $id + * @param int|null $shopId + * @return bool + */ + public function getAsBoolean($id, $shopId = null) { $result = $this->get($id, $shopId); @@ -73,7 +89,12 @@ public function getAsBoolean(string $id, ?int $shopId = null) return (bool) $result; } - public function getAsInteger(string $id, ?int $shopId = null) + /** + * @param string $id + * @param int|null $shopId + * @return int + */ + public function getAsInteger($id, $shopId = null) { $result = $this->get($id, $shopId); @@ -88,9 +109,9 @@ public function getAsInteger(string $id, ?int $shopId = null) * Removes by specific shop id * * @param string $id - * @param int $shopId + * @param int|null $shopId */ - public function remove(string $id, ?int $shopId) + public function remove($id, $shopId) { // making sure to set to null value only for single shop id PrestaShopConfiguration::updateValue($id, null, false, null, $shopId); @@ -101,7 +122,7 @@ public function remove(string $id, ?int $shopId) * * @param string $id */ - public function delete(string $id) + public function delete($id) { PrestaShopConfiguration::deleteByName($id); } diff --git a/src/Controller/Front/PaymentFrontController.php b/src/Controller/Front/CheckoutController.php similarity index 55% rename from src/Controller/Front/PaymentFrontController.php rename to src/Controller/Front/CheckoutController.php index b6a7fbbb..e16fb074 100644 --- a/src/Controller/Front/PaymentFrontController.php +++ b/src/Controller/Front/CheckoutController.php @@ -23,55 +23,27 @@ namespace Invertus\SaferPay\Controller\Front; +use Invertus\SaferPay\Core\Payment\DTO\CheckoutData; use Invertus\SaferPay\Processor\CheckoutProcessor; -use Invertus\SaferPay\Adapter\Configuration; -use Invertus\SaferPay\Config\SaferPayConfig; -class PaymentFrontController +class CheckoutController { /** * @var CheckoutProcessor */ private $checkoutProcessor; - /** - * @var Configuration - */ - private $configuration; - public function __construct( - CheckoutProcessor $checkoutProcessor, - Configuration $configuration + CheckoutProcessor $checkoutProcessor ) { $this->checkoutProcessor = $checkoutProcessor; - $this->configuration = $configuration; } - public function create(\Cart $cart, $paymentMethod, $isBusinessLicense, $selectedCard = -1, $fieldToken = null, $successController = null, $isTransaction = false) + public function execute(CheckoutData $checkoutData) { - if (!$this->configuration->getAsBoolean(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION)) { - $this->checkoutProcessor->processCreateOrder( - $cart, - $paymentMethod - ); - } - - $response = $this->checkoutProcessor->initializePayment( - $paymentMethod, - $isBusinessLicense, - $selectedCard, - $fieldToken, - $successController - ); - - $this->checkoutProcessor->processCreateSaferPayOrder( - $response, - $cart->id, - $cart->id_customer, - $isTransaction - ); + $response = $this->checkoutProcessor->run($checkoutData); - return $response; + return $this->getRedirectionUrl($response); } /** @@ -79,7 +51,7 @@ public function create(\Cart $cart, $paymentMethod, $isBusinessLicense, $selecte * * @return string */ - public function getRedirectionUrl($initializeBody) + private function getRedirectionUrl($initializeBody) { if (isset($initializeBody->RedirectUrl)) { return $initializeBody->RedirectUrl; diff --git a/src/Core/Order/Action/UpdateOrderStatusAction.php b/src/Core/Order/Action/UpdateOrderStatusAction.php index 082daf68..316bbd66 100644 --- a/src/Core/Order/Action/UpdateOrderStatusAction.php +++ b/src/Core/Order/Action/UpdateOrderStatusAction.php @@ -23,28 +23,43 @@ namespace Invertus\SaferPay\Core\Order\Action; +use Invertus\SaferPay\Exception\CouldNotChangeOrderStatus; +use Order; + if (!defined('_PS_VERSION_')) { exit; } class UpdateOrderStatusAction { - const STATUS_AUTHORIZED = 'AUTHORIZED'; - const STATUS_CAPTURED = 'CAPTURED'; - - public function run(\Order $order, $orderStatus) + /** + * @param int $orderId + * @param int $orderStatusId + * + * @return void + * @throws CouldNotChangeOrderStatus + */ + public function run($orderId, $orderStatusId) { - switch ($orderStatus) { - case self::STATUS_AUTHORIZED: - $order->setCurrentState(_SAFERPAY_PAYMENT_AUTHORIZED_); - break; - case self::STATUS_CAPTURED: - $order->setCurrentState(_SAFERPAY_PAYMENT_COMPLETED_); - break; - default: - die('Order status is invalid'); + try { + /** @var \Order|null $order */ + $order = new Order($orderId); + } catch (\Exception $exception) { + throw CouldNotChangeOrderStatus::unknownError($exception); + } + + if (!$order) { + throw CouldNotChangeOrderStatus::failedToFindOrder($orderId); + } + + try { + if ((int) $order->getCurrentState() !== (int) $orderStatusId) { + $order->setCurrentState($orderStatusId); + $order->update(); + } + } catch (\Exception $exception) { + throw CouldNotChangeOrderStatus::unknownError($exception); } - $order->update(); } } diff --git a/src/Core/Payment/DTO/CheckoutData.php b/src/Core/Payment/DTO/CheckoutData.php new file mode 100644 index 00000000..a8e1ce96 --- /dev/null +++ b/src/Core/Payment/DTO/CheckoutData.php @@ -0,0 +1,168 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Core\Payment\DTO; + +use Configuration; +use Invertus\SaferPay\Config\SaferPayConfig; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class CheckoutData +{ + private $cartId; + private $paymentMethod; + private $isBusinessLicense; + private $selectedCard; + private $fieldToken; + private $successController; + private $isTransaction; + private $createAfterAuthorization; + private $isAuthorizedOrder; + + public function __construct( + $cartId, + $paymentMethod, + $isBusinessLicense, + $selectedCard = -1, + $fieldToken = null, + $successController = null, + $isTransaction = false + ) + { + $this->cartId = $cartId; + $this->paymentMethod = $paymentMethod; + $this->isBusinessLicense = $isBusinessLicense; + $this->selectedCard = $selectedCard; + $this->fieldToken = $fieldToken; + $this->successController = $successController; + $this->isTransaction = $isTransaction; + $this->createAfterAuthorization = Configuration::get(SaferPayConfig::SAFERPAY_ORDER_CREATION_AFTER_AUTHORIZATION); + $this->isAuthorizedOrder = false; + } + + public static function createFromRequest( + $cartId, + $paymentMethod, + $isBusinessLicense, + $selectedCard = -1, + $fieldToken = null, + $successController = null, + $isTransaction = false + ) + { + return new self( + $cartId, + $paymentMethod, + $isBusinessLicense, + $selectedCard, + $fieldToken, + $successController, + $isTransaction + ); + } + + /** + * @return int $cartId + */ + public function getCartId() + { + return $this->cartId; + } + + /** + * @return string + */ + public function getPaymentMethod() + { + return $this->paymentMethod; + } + + /** + * @return string + */ + public function getIsBusinessLicense() + { + return $this->isBusinessLicense; + } + + /** + * @return int|mixed + */ + public function getSelectedCard() + { + return $this->selectedCard; + } + + /** + * @return string|null + */ + public function getFieldToken() + { + return $this->fieldToken; + } + + /** + * @return string|null + */ + public function getSuccessController() + { + return $this->successController; + } + + /** + * @return bool + */ + public function getIsTransaction() + { + return $this->isTransaction; + } + + /** + * @return bool + */ + public function getCreateAfterAuthorization() + { + return (bool) $this->createAfterAuthorization; + } + + /** + * @return bool + */ + public function getIsAuthorizedOrder() + { + return $this->isAuthorizedOrder; + } + + /** + * @param bool $isAuthorized + * + * @return void + */ + public function setIsAuthorizedOrder($isAuthorized) + { + $this->isAuthorizedOrder = $isAuthorized; + } +} \ No newline at end of file diff --git a/src/Core/Payment/DTO/index.php b/src/Core/Payment/DTO/index.php new file mode 100644 index 00000000..ee622726 --- /dev/null +++ b/src/Core/Payment/DTO/index.php @@ -0,0 +1,31 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../'); +exit; diff --git a/src/Core/SaferPayOrder/Action/UpdateSaferPayOrderAction.php b/src/Core/SaferPayOrder/Action/UpdateSaferPayOrderAction.php new file mode 100644 index 00000000..716b2e99 --- /dev/null +++ b/src/Core/SaferPayOrder/Action/UpdateSaferPayOrderAction.php @@ -0,0 +1,65 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Core\SaferPayOrder\Action; + +use SaferPayOrder; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class UpdateSaferPayOrderAction +{ + const ACTION_AUTHORIZE = 'AUTHORIZE'; + + /** + * @param SaferPayOrder $saferPayOrder + * @param string $action + * @return void + */ + public function run(SaferPayOrder $saferPayOrder, string $action) + { + switch ($action) { + case self::ACTION_AUTHORIZE: + $this->authorizeSaferPayOrder($saferPayOrder); + break; + default: + throw new \InvalidArgumentException('Unsupported saferpay order action provided.'); + } + } + + /** + * @param SaferPayOrder $saferPayOrder + * @return void + */ + private function authorizeSaferPayOrder($saferPayOrder) + { + if ($saferPayOrder->authorized) { + return; + } + + $saferPayOrder->authorized = 1; + $saferPayOrder->update(); + } +} diff --git a/src/Core/SaferPayOrder/Action/index.php b/src/Core/SaferPayOrder/Action/index.php new file mode 100644 index 00000000..ee622726 --- /dev/null +++ b/src/Core/SaferPayOrder/Action/index.php @@ -0,0 +1,31 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../'); +exit; diff --git a/src/Core/SaferPayOrder/index.php b/src/Core/SaferPayOrder/index.php new file mode 100644 index 00000000..ee622726 --- /dev/null +++ b/src/Core/SaferPayOrder/index.php @@ -0,0 +1,31 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../'); +exit; diff --git a/src/Exception/CouldNotProcessCheckout.php b/src/Exception/CouldNotProcessCheckout.php new file mode 100644 index 00000000..38b3fd37 --- /dev/null +++ b/src/Exception/CouldNotProcessCheckout.php @@ -0,0 +1,76 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Exception; + +use Invertus\SaferPay\Exception\Restriction\SaferPayException; + +class CouldNotProcessCheckout extends SaferPayException +{ + /** + * @param int $cartId + * @return static + */ + public static function failedToFindCart($cartId) + { + return new static( + sprintf('Failed to find cart by ID %s', $cartId), + ExceptionCode::PAYMENT_FAILED_TO_FIND_CART, + [ + 'cart_id' => $cartId, + ] + ); + } + + /** + * @param int $cartId + * + * @return static + */ + public static function failedToCreateOrder($cartId) + { + return new static( + sprintf('Failed to create order. Cart ID %s', $cartId), + ExceptionCode::PAYMENT_FAILED_TO_CREATE_ORDER, + [ + 'cart_id' => $cartId, + ] + ); + } + + /** + * @param int $cartId + * + * @return static + */ + public static function failedToCreateSaferPayOrder($cartId) + { + return new static( + sprintf('Failed to create order. Cart ID %s', $cartId), + ExceptionCode::PAYMENT_FAILED_TO_CREATE_ORDER, + [ + 'cart_id' => $cartId, + ] + ); + } +} \ No newline at end of file diff --git a/src/Exception/ExceptionCode.php b/src/Exception/ExceptionCode.php new file mode 100644 index 00000000..aabe86ec --- /dev/null +++ b/src/Exception/ExceptionCode.php @@ -0,0 +1,43 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Exception; + +if (!defined('_PS_VERSION_')) { + exit; +} + +// NOTE class to define most used exception codes for our development. +class ExceptionCode +{ + // Payment related codes starts from 5*** + const PAYMENT_FAILED_TO_FIND_CART = 5001; + const PAYMENT_FAILED_TO_CREATE_ORDER = 5002; + + // Order related codes starts from 7*** + const ORDER_FAILED_TO_FIND_ORDER = 7001; + const ORDER_UNHANDLED_TRANSACTION_STATUS = 7002; + + // Any other unhandled codes should start with 9*** + const UNKNOWN_ERROR = 9001; +} diff --git a/src/Exception/Order/CouldNotChangeOrderStatus.php b/src/Exception/Order/CouldNotChangeOrderStatus.php new file mode 100644 index 00000000..60ee5286 --- /dev/null +++ b/src/Exception/Order/CouldNotChangeOrderStatus.php @@ -0,0 +1,65 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Exception; + +use Invertus\SaferPay\Exception\Restriction\SaferPayException; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class CouldNotChangeOrderStatus extends SaferPayException +{ + /** + * @param string $transactionStatus + * + * @return CouldNotChangeOrderStatus + */ + public static function unhandledOrderStatus($transactionStatus) + { + return new self( + sprintf('Unhandled transaction status (%s)', $transactionStatus), + ExceptionCode::ORDER_UNHANDLED_TRANSACTION_STATUS, + [ + 'transaction_status' => $transactionStatus, + ] + ); + } + + /** + * @param int $orderId + * + * @return CouldNotChangeOrderStatus + */ + public static function failedToFindOrder($orderId) + { + return new self( + sprintf('Failed to find order %s', $orderId), + ExceptionCode::ORDER_FAILED_TO_FIND_ORDER, + [ + 'order_id' => $orderId, + ] + ); + } +} diff --git a/src/Exception/Order/index.php b/src/Exception/Order/index.php new file mode 100644 index 00000000..ee622726 --- /dev/null +++ b/src/Exception/Order/index.php @@ -0,0 +1,31 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../'); +exit; diff --git a/src/Exception/SaferPayException.php b/src/Exception/SaferPayException.php new file mode 100644 index 00000000..59b41e90 --- /dev/null +++ b/src/Exception/SaferPayException.php @@ -0,0 +1,63 @@ + + *@copyright SIX Payment Services + *@license SIX Payment Services + */ + +namespace Invertus\SaferPay\Exception\Restriction; + +use Invertus\SaferPay\Exception\ExceptionCode; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class SaferPayException extends \Exception +{ + private $context; + + final public function __construct( + $internalMessage, + $code, + array $context = [] + ) + { + parent::__construct($internalMessage, $code); + $this->context = $context; + } + + public function getContext() + { + return $this->context; + } + + /** + * @param \Exception $exception + * + * @return static + */ + public static function unknownError($exception) + { + return new static( + 'An unknown error error occurred. Please check system logs or contact Click to Pay support.', + ExceptionCode::UNKNOWN_ERROR + ); + } +} \ No newline at end of file diff --git a/src/Install/Installer.php b/src/Install/Installer.php index a8f5a0d0..962cdd72 100755 --- a/src/Install/Installer.php +++ b/src/Install/Installer.php @@ -228,7 +228,8 @@ private function installSaferPayOrderTable() return Db::getInstance()->execute( 'CREATE TABLE IF NOT EXISTS ' . _DB_PREFIX_ . 'saferpay_order' . '( `id_saferpay_order` INTEGER(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY, - `id_order` INTEGER(10) DEFAULT 0, + `id_order` INTEGER(10) DEFAULT 0 NULL, + `id_cart` INTEGER(10) DEFAULT 0, `id_customer` INTEGER(10) DEFAULT 0, `transaction_id` VARCHAR(64) DEFAULT NULL, `refund_id` VARCHAR(64) DEFAULT NULL, diff --git a/src/Processor/CheckoutProcessor.php b/src/Processor/CheckoutProcessor.php index 0903dd0c..35696319 100644 --- a/src/Processor/CheckoutProcessor.php +++ b/src/Processor/CheckoutProcessor.php @@ -25,11 +25,15 @@ use Cart; use Invertus\SaferPay\Config\SaferPayConfig; +use Invertus\SaferPay\Core\Payment\DTO\CheckoutData; use Invertus\SaferPay\EntityBuilder\SaferPayOrderBuilder; +use Invertus\SaferPay\Exception\Api\SaferPayApiException; +use Invertus\SaferPay\Exception\CouldNotProcessCheckout; use Invertus\SaferPay\Factory\ModuleFactory; use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\SaferPayInitialize; use Order; +use PrestaShopException; use SaferPayOrder; class CheckoutProcessor @@ -58,7 +62,70 @@ public function __construct( $this->saferPayOrderRepository = $saferPayOrderRepository; } - public function processCreateOrder(Cart $cart, $paymentMethod) + public function run(CheckoutData $data) { + + $cart = new Cart($data->getCartId()); + + if (!$cart) { + throw CouldNotProcessCheckout::failedToFindCart($data->getCartId()); + } + + if ($data->getIsAuthorizedOrder()) { + try { + $this->processCreateOrder($cart, $data->getPaymentMethod()); + + $saferPayOrder = new SaferPayOrder($this->saferPayOrderRepository->getIdByCartId($cart->id)); + $saferPayOrder->id_order = Order::getIdByCartId($cart->id); + + $saferPayOrder->update(); + + return ''; + } catch (\Exception $exception) { + throw CouldNotProcessCheckout::failedToCreateOrder($data->getCartId()); + } + } + + try { + if (!$data->getCreateAfterAuthorization()) { + $this->processCreateOrder($cart, $data->getPaymentMethod()); + } + } catch (\Exception $exception) { + throw CouldNotProcessCheckout::failedToCreateOrder($data->getCartId()); + } + + try { + $response = $this->processInitializePayment( + $data->getPaymentMethod(), + $data->getIsBusinessLicense(), + $data->getSelectedCard(), + $data->getFieldToken(), + $data->getSuccessController() + ); + } catch (\Exception $exception) { + throw new SaferPayApiException('Failed to initialize payment API', SaferPayApiException::INITIALIZE); + } + + try { + $this->processCreateSaferPayOrder( + $response, + $cart->id, + $cart->id_customer, + $data->getIsTransaction() + ); + } catch (\Exception $exception) { + throw CouldNotProcessCheckout::failedToCreateSaferPayOrder($data->getCartId()); + } + + return $response; + } + + /** + * @param Cart $cart + * @param $paymentMethod + * @return void + * @throws PrestaShopException + */ + private function processCreateOrder(Cart $cart, $paymentMethod) { $customer = new \Customer($cart->id_customer); @@ -75,7 +142,15 @@ public function processCreateOrder(Cart $cart, $paymentMethod) ); } - public function initializePayment( + /** + * @param $paymentMethod + * @param $isBusinessLicense + * @param $selectedCard + * @param $fieldToken + * @param $successController + * @return array|null + */ + private function processInitializePayment( $paymentMethod, $isBusinessLicense, $selectedCard, @@ -93,7 +168,14 @@ public function initializePayment( return $this->saferPayInitialize->initialize($request, $isBusinessLicense); } - public function processCreateSaferPayOrder($initializeBody, $cartId, $customerId, $isTransaction) + /** + * @param $initializeBody + * @param $cartId + * @param $customerId + * @param $isTransaction + * @return void + */ + private function processCreateSaferPayOrder($initializeBody, $cartId, $customerId, $isTransaction) { $this->saferPayOrderBuilder->create( $initializeBody, @@ -102,14 +184,4 @@ public function processCreateSaferPayOrder($initializeBody, $cartId, $customerId $isTransaction ); } - - public function processCreateOrderAfterAuthorization(Cart $cart, $paymentMethod) - { - $this->processCreateOrder($cart, $paymentMethod); - - $saferPayOrder = new SaferPayOrder($this->saferPayOrderRepository->getIdByCartId($cart->id)); - $saferPayOrder->id_order = Order::getIdByCartId($cart->id); - - $saferPayOrder->update(); - } } From bce3cf6b9d3afacddd2b0305deb05278b352351c Mon Sep 17 00:00:00 2001 From: Gytautas Date: Tue, 19 Dec 2023 15:48:22 +0200 Subject: [PATCH 11/18] type hints and action location fix --- controllers/front/ajax.php | 4 +-- controllers/front/iframe.php | 6 ++-- controllers/front/notify.php | 8 ++--- controllers/front/return.php | 6 ++-- controllers/front/validation.php | 4 +-- .../Action/UpdateSaferPayOrderAction.php | 4 +-- src/Core/Payment/DTO/CheckoutData.php | 6 ++-- src/Core/SaferPayOrder/Action/index.php | 31 ------------------- src/Core/SaferPayOrder/index.php | 31 ------------------- src/Exception/CouldNotProcessCheckout.php | 2 +- 10 files changed, 20 insertions(+), 82 deletions(-) rename src/Core/{SaferPayOrder => Order}/Action/UpdateSaferPayOrderAction.php (93%) delete mode 100644 src/Core/SaferPayOrder/Action/index.php delete mode 100644 src/Core/SaferPayOrder/index.php diff --git a/controllers/front/ajax.php b/controllers/front/ajax.php index 0ddabf00..270c768c 100755 --- a/controllers/front/ajax.php +++ b/controllers/front/ajax.php @@ -58,8 +58,8 @@ private function submitHostedFields() } // refactor it to create checkout data from validator request - $checkoutData = CheckoutData::createFromRequest( - $this->context->cart, + $checkoutData = CheckoutData::create( + (int) $this->context->cart->id, Tools::getValue('paymentMethod'), (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE), Tools::getValue('selectedCard'), diff --git a/controllers/front/iframe.php b/controllers/front/iframe.php index 6ac262a8..7fb34709 100755 --- a/controllers/front/iframe.php +++ b/controllers/front/iframe.php @@ -90,10 +90,10 @@ public function initContent() $checkoutController = $this->module->getService(CheckoutController::class); // refactor it to create checkout data from validator request - $checkoutData = CheckoutData::createFromRequest( - $this->context->cart, + $checkoutData = CheckoutData::create( + (int) $this->context->cart->id, $paymentMethod, - Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE), + (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE), $selectedCard ); diff --git a/controllers/front/notify.php b/controllers/front/notify.php index ac1e6e6f..7fc1af3b 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -25,8 +25,8 @@ use Invertus\SaferPay\Config\SaferPayConfig; use Invertus\SaferPay\Controller\AbstractSaferPayController; use Invertus\SaferPay\Core\Order\Action\UpdateOrderStatusAction; +use Invertus\SaferPay\Core\Order\Action\UpdateSaferPayOrderAction; use Invertus\SaferPay\Core\Payment\DTO\CheckoutData; -use Invertus\SaferPay\Core\SaferPayOrder\Action\UpdateSaferPayOrderAction; use Invertus\SaferPay\Processor\CheckoutProcessor; use Invertus\SaferPay\Repository\SaferPayOrderRepository; use Invertus\SaferPay\Service\SaferPayOrderStatusService; @@ -81,10 +81,10 @@ public function postProcess() if (!$orderId) { /** @var CheckoutProcessor $checkoutProcessor **/ $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); - $checkoutData = CheckoutData::createFromRequest( - $cart, + $checkoutData = CheckoutData::create( + (int) $cart->id, $assertResponseBody->getPaymentMeans()->getBrand()->getPaymentMethod(), - Configuration::get(SaferPayConfig::IS_BUSINESS_LICENCE) + (int) Configuration::get(SaferPayConfig::IS_BUSINESS_LICENCE) ); $checkoutData->setIsAuthorizedOrder(true); diff --git a/controllers/front/return.php b/controllers/front/return.php index a4105b40..8158d4db 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -71,10 +71,10 @@ public function postProcess() $assertionResponse = $transactionAssert->assert($cartId); if (!$orderId) { - $checkoutData = CheckoutData::createFromRequest( - new \Cart($cartId), + $checkoutData = CheckoutData::create( + (int) $cartId, $assertionResponse->getPaymentMeans()->getBrand()->getPaymentMethod(), - $isBusinessLicence + (int) $isBusinessLicence ); $checkoutData->setIsAuthorizedOrder(true); diff --git a/controllers/front/validation.php b/controllers/front/validation.php index d3538d2b..7ee765ce 100755 --- a/controllers/front/validation.php +++ b/controllers/front/validation.php @@ -82,8 +82,8 @@ public function postProcess() /** @var CheckoutController $checkoutController */ $checkoutController = $this->module->getService(CheckoutController::class); // refactor it to create checkout data from validator request - $checkoutData = CheckoutData::createFromRequest( - $this->context->cart->id, + $checkoutData = CheckoutData::create( + (int) $this->context->cart->id, $paymentMethod, (int) Tools::getValue(SaferPayConfig::IS_BUSINESS_LICENCE) ); diff --git a/src/Core/SaferPayOrder/Action/UpdateSaferPayOrderAction.php b/src/Core/Order/Action/UpdateSaferPayOrderAction.php similarity index 93% rename from src/Core/SaferPayOrder/Action/UpdateSaferPayOrderAction.php rename to src/Core/Order/Action/UpdateSaferPayOrderAction.php index 716b2e99..dc48a47c 100644 --- a/src/Core/SaferPayOrder/Action/UpdateSaferPayOrderAction.php +++ b/src/Core/Order/Action/UpdateSaferPayOrderAction.php @@ -21,7 +21,7 @@ *@license SIX Payment Services */ -namespace Invertus\SaferPay\Core\SaferPayOrder\Action; +namespace Invertus\SaferPay\Core\Order\Action; use SaferPayOrder; @@ -38,7 +38,7 @@ class UpdateSaferPayOrderAction * @param string $action * @return void */ - public function run(SaferPayOrder $saferPayOrder, string $action) + public function run(SaferPayOrder $saferPayOrder, $action) { switch ($action) { case self::ACTION_AUTHORIZE: diff --git a/src/Core/Payment/DTO/CheckoutData.php b/src/Core/Payment/DTO/CheckoutData.php index a8e1ce96..6920d416 100644 --- a/src/Core/Payment/DTO/CheckoutData.php +++ b/src/Core/Payment/DTO/CheckoutData.php @@ -63,8 +63,8 @@ public function __construct( $this->isAuthorizedOrder = false; } - public static function createFromRequest( - $cartId, + public static function create( + $cartId, $paymentMethod, $isBusinessLicense, $selectedCard = -1, @@ -101,7 +101,7 @@ public function getPaymentMethod() } /** - * @return string + * @return int */ public function getIsBusinessLicense() { diff --git a/src/Core/SaferPayOrder/Action/index.php b/src/Core/SaferPayOrder/Action/index.php deleted file mode 100644 index ee622726..00000000 --- a/src/Core/SaferPayOrder/Action/index.php +++ /dev/null @@ -1,31 +0,0 @@ - - *@copyright SIX Payment Services - *@license SIX Payment Services - */ -header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); -header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); - -header('Cache-Control: no-store, no-cache, must-revalidate'); -header('Cache-Control: post-check=0, pre-check=0', false); -header('Pragma: no-cache'); - -header('Location: ../'); -exit; diff --git a/src/Core/SaferPayOrder/index.php b/src/Core/SaferPayOrder/index.php deleted file mode 100644 index ee622726..00000000 --- a/src/Core/SaferPayOrder/index.php +++ /dev/null @@ -1,31 +0,0 @@ - - *@copyright SIX Payment Services - *@license SIX Payment Services - */ -header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); -header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); - -header('Cache-Control: no-store, no-cache, must-revalidate'); -header('Cache-Control: post-check=0, pre-check=0', false); -header('Pragma: no-cache'); - -header('Location: ../'); -exit; diff --git a/src/Exception/CouldNotProcessCheckout.php b/src/Exception/CouldNotProcessCheckout.php index 38b3fd37..95101b0e 100644 --- a/src/Exception/CouldNotProcessCheckout.php +++ b/src/Exception/CouldNotProcessCheckout.php @@ -61,7 +61,7 @@ public static function failedToCreateOrder($cartId) /** * @param int $cartId * - * @return static + * @return self */ public static function failedToCreateSaferPayOrder($cartId) { From c5a81101366b3ced24a49759ff73fcedc8180168 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Thu, 21 Dec 2023 13:00:39 +0200 Subject: [PATCH 12/18] fix: parameter fix --- controllers/front/notify.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/front/notify.php b/controllers/front/notify.php index 7fc1af3b..e4edbe7b 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -143,7 +143,7 @@ private function assertTransaction($cartId) { /** @var SaferPayTransactionAssertion $transactionAssert */ $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); - return $transactionAssert->assert(Order::getIdByCartId($cartId)); + return $transactionAssert->assert($cartId); } protected function displayMaintenancePage() From 9b80ccd264df052a5748cb908c716b7fe3c4b9a1 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Thu, 21 Dec 2023 13:11:40 +0200 Subject: [PATCH 13/18] comment deleted --- upgrade/install-1.2.0.php | 1 - 1 file changed, 1 deletion(-) diff --git a/upgrade/install-1.2.0.php b/upgrade/install-1.2.0.php index 4a7df724..d127a4e6 100644 --- a/upgrade/install-1.2.0.php +++ b/upgrade/install-1.2.0.php @@ -28,7 +28,6 @@ exit; } -//todo test it and todo upgrade method function upgrade_module_1_2_0($module) { // Make id_order nullable From 2d6adc82fe81daa177a234f2537114a9455a06c9 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Thu, 21 Dec 2023 16:27:10 +0200 Subject: [PATCH 14/18] fix: fixed authorization after order creation --- controllers/front/return.php | 24 +++++++++++------------- src/Processor/CheckoutProcessor.php | 18 +++++++++++++++--- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/controllers/front/return.php b/controllers/front/return.php index 8158d4db..4998eb21 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -70,19 +70,17 @@ public function postProcess() $transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class); $assertionResponse = $transactionAssert->assert($cartId); - if (!$orderId) { - $checkoutData = CheckoutData::create( - (int) $cartId, - $assertionResponse->getPaymentMeans()->getBrand()->getPaymentMethod(), - (int) $isBusinessLicence - ); - - $checkoutData->setIsAuthorizedOrder(true); - - /** @var CheckoutProcessor $checkoutProcessor **/ - $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); - $checkoutProcessor->run($checkoutData); - } + $checkoutData = CheckoutData::create( + (int) $cartId, + $assertionResponse->getPaymentMeans()->getBrand()->getPaymentMethod(), + (int) $isBusinessLicence + ); + + $checkoutData->setIsAuthorizedOrder(true); + + /** @var CheckoutProcessor $checkoutProcessor **/ + $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); + $checkoutProcessor->run($checkoutData); $orderId = \Order::getIdByCartId($cartId); diff --git a/src/Processor/CheckoutProcessor.php b/src/Processor/CheckoutProcessor.php index 35696319..7c1cd959 100644 --- a/src/Processor/CheckoutProcessor.php +++ b/src/Processor/CheckoutProcessor.php @@ -72,12 +72,24 @@ public function run(CheckoutData $data) { if ($data->getIsAuthorizedOrder()) { try { - $this->processCreateOrder($cart, $data->getPaymentMethod()); - $saferPayOrder = new SaferPayOrder($this->saferPayOrderRepository->getIdByCartId($cart->id)); - $saferPayOrder->id_order = Order::getIdByCartId($cart->id); + + if (!$saferPayOrder->id_order) { + $this->processCreateOrder($cart, $data->getPaymentMethod()); + $saferPayOrder->authorized = 1; + } + + $order = new Order(Order::getIdByCartId($cart->id)); + $saferPayOrder->id_order = $order->id; + + if ($status === 'AUTHORIZED') { + $order->setCurrentState(_SAFERPAY_PAYMENT_AUTHORIZED_); + } elseif ($status === 'CAPTURED') { + $order->setCurrentState(_SAFERPAY_PAYMENT_COMPLETED_); + } $saferPayOrder->update(); + $order->update(); return ''; } catch (\Exception $exception) { From f1ab8ba8376fbe79a3d48d4c5e05e354c3f81112 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Thu, 21 Dec 2023 16:40:07 +0200 Subject: [PATCH 15/18] corrected status insertion --- controllers/front/return.php | 3 ++- src/Core/Payment/DTO/CheckoutData.php | 19 +++++++++++++++++++ src/Processor/CheckoutProcessor.php | 4 ++-- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/controllers/front/return.php b/controllers/front/return.php index 4998eb21..26844018 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -77,7 +77,8 @@ public function postProcess() ); $checkoutData->setIsAuthorizedOrder(true); - + $checkoutData->setOrderStatus($assertBody->getTransaction()->getStatus()); + //todo set status as well possible authorized and captured. /** @var CheckoutProcessor $checkoutProcessor **/ $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); $checkoutProcessor->run($checkoutData); diff --git a/src/Core/Payment/DTO/CheckoutData.php b/src/Core/Payment/DTO/CheckoutData.php index 6920d416..7281cfe9 100644 --- a/src/Core/Payment/DTO/CheckoutData.php +++ b/src/Core/Payment/DTO/CheckoutData.php @@ -41,6 +41,7 @@ class CheckoutData private $isTransaction; private $createAfterAuthorization; private $isAuthorizedOrder; + private $status; public function __construct( $cartId, @@ -156,6 +157,14 @@ public function getIsAuthorizedOrder() return $this->isAuthorizedOrder; } + /** + * @return string + */ + public function getOrderStatus() + { + return $this->status; + } + /** * @param bool $isAuthorized * @@ -165,4 +174,14 @@ public function setIsAuthorizedOrder($isAuthorized) { $this->isAuthorizedOrder = $isAuthorized; } + + /** + * @param string $status + * + * @return void + */ + public function setOrderStatus($status) + { + $this->status = $status; + } } \ No newline at end of file diff --git a/src/Processor/CheckoutProcessor.php b/src/Processor/CheckoutProcessor.php index 7c1cd959..327d4473 100644 --- a/src/Processor/CheckoutProcessor.php +++ b/src/Processor/CheckoutProcessor.php @@ -82,9 +82,9 @@ public function run(CheckoutData $data) { $order = new Order(Order::getIdByCartId($cart->id)); $saferPayOrder->id_order = $order->id; - if ($status === 'AUTHORIZED') { + if ($data->getOrderStatus() === 'AUTHORIZED') { $order->setCurrentState(_SAFERPAY_PAYMENT_AUTHORIZED_); - } elseif ($status === 'CAPTURED') { + } elseif ($data->getOrderStatus() === 'CAPTURED') { $order->setCurrentState(_SAFERPAY_PAYMENT_COMPLETED_); } From 02ee19d0c77df0badf523ed800d3b5695f6a0d1e Mon Sep 17 00:00:00 2001 From: Gytautas Date: Thu, 21 Dec 2023 16:42:03 +0200 Subject: [PATCH 16/18] added status into notify controller --- controllers/front/notify.php | 2 ++ controllers/front/return.php | 2 +- src/Processor/CheckoutProcessor.php | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/controllers/front/notify.php b/controllers/front/notify.php index e4edbe7b..9cea37cd 100755 --- a/controllers/front/notify.php +++ b/controllers/front/notify.php @@ -86,7 +86,9 @@ public function postProcess() $assertResponseBody->getPaymentMeans()->getBrand()->getPaymentMethod(), (int) Configuration::get(SaferPayConfig::IS_BUSINESS_LICENCE) ); + $checkoutData->setIsAuthorizedOrder(true); + $checkoutData->setOrderStatus($assertResponseBody->getTransaction()->getStatus()); $checkoutProcessor->run($checkoutData); } diff --git a/controllers/front/return.php b/controllers/front/return.php index 26844018..9cce7f69 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -78,7 +78,7 @@ public function postProcess() $checkoutData->setIsAuthorizedOrder(true); $checkoutData->setOrderStatus($assertBody->getTransaction()->getStatus()); - //todo set status as well possible authorized and captured. + /** @var CheckoutProcessor $checkoutProcessor **/ $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); $checkoutProcessor->run($checkoutData); diff --git a/src/Processor/CheckoutProcessor.php b/src/Processor/CheckoutProcessor.php index 327d4473..5a25d272 100644 --- a/src/Processor/CheckoutProcessor.php +++ b/src/Processor/CheckoutProcessor.php @@ -70,6 +70,7 @@ public function run(CheckoutData $data) { throw CouldNotProcessCheckout::failedToFindCart($data->getCartId()); } + //todo move to different if ($data->getIsAuthorizedOrder()) { try { $saferPayOrder = new SaferPayOrder($this->saferPayOrderRepository->getIdByCartId($cart->id)); From bbf75b72b3f2d2f6b5dfd4bea4a80d7e4e437803 Mon Sep 17 00:00:00 2001 From: Gytautas Date: Thu, 21 Dec 2023 17:19:54 +0200 Subject: [PATCH 17/18] assert naming changed --- controllers/front/return.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/front/return.php b/controllers/front/return.php index 9cce7f69..826b0467 100755 --- a/controllers/front/return.php +++ b/controllers/front/return.php @@ -77,7 +77,7 @@ public function postProcess() ); $checkoutData->setIsAuthorizedOrder(true); - $checkoutData->setOrderStatus($assertBody->getTransaction()->getStatus()); + $checkoutData->setOrderStatus($assertionResponse->getTransaction()->getStatus()); /** @var CheckoutProcessor $checkoutProcessor **/ $checkoutProcessor = $this->module->getService(CheckoutProcessor::class); From 37fff1d10040adb8e8a900fb7353e9b20d4fa2ca Mon Sep 17 00:00:00 2001 From: Gytautas Date: Thu, 11 Jan 2024 09:31:10 +0200 Subject: [PATCH 18/18] comment deleted --- src/Processor/CheckoutProcessor.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Processor/CheckoutProcessor.php b/src/Processor/CheckoutProcessor.php index 5a25d272..327d4473 100644 --- a/src/Processor/CheckoutProcessor.php +++ b/src/Processor/CheckoutProcessor.php @@ -70,7 +70,6 @@ public function run(CheckoutData $data) { throw CouldNotProcessCheckout::failedToFindCart($data->getCartId()); } - //todo move to different if ($data->getIsAuthorizedOrder()) { try { $saferPayOrder = new SaferPayOrder($this->saferPayOrderRepository->getIdByCartId($cart->id));