From c697187fb9c9867cc8ba7a1ac652d882d995b3ac Mon Sep 17 00:00:00 2001 From: woutse Date: Fri, 28 May 2021 17:34:05 +0200 Subject: [PATCH 1/5] Now using the status SDK method. --- Controller/Checkout/Exchange.php | 45 +++++-- Controller/Checkout/Finish.php | 175 +++++++++++++------------- Model/Config.php | 2 + Model/Paymentmethod/Paylink.php | 45 +++---- Model/Paymentmethod/PaymentMethod.php | 4 +- composer.json | 2 +- 6 files changed, 148 insertions(+), 125 deletions(-) diff --git a/Controller/Checkout/Exchange.php b/Controller/Checkout/Exchange.php index ac874c67..cbc67a99 100644 --- a/Controller/Checkout/Exchange.php +++ b/Controller/Checkout/Exchange.php @@ -13,6 +13,7 @@ use Magento\Sales\Model\OrderRepository; use Paynl\Payment\Controller\CsrfAwareActionInterface; use Paynl\Payment\Controller\PayAction; +use Paynl\Result\Transaction\Status; use Paynl\Result\Transaction\Transaction; @@ -124,19 +125,20 @@ public function execute() $params = $this->getRequest()->getParams(); $action = !empty($params['action']) ? strtolower($params['action']) : ''; + $payOrderId = isset($params['order_id']) ? $params['order_id'] : null; + $orderEntityId = isset($params['extra3']) ? $params['extra3'] : null; if ($action == 'pending') { return $this->result->setContents('TRUE| Ignore pending'); } - if (!isset($params['order_id'])) { - $this->logger->critical('Exchange: order_id is not set in the request', $params); - + if (empty($payOrderId) || empty($orderEntityId)) { + $this->logger->critical('Exchange: order_id or orderEntity is not set', $params); return $this->result->setContents('FALSE| order_id is not set in the request'); } try { - $transaction = \Paynl\Transaction::get($params['order_id']); + $transaction = \Paynl\Transaction::status($payOrderId); } catch (\Exception $e) { $this->logger->critical($e, $params); @@ -156,22 +158,39 @@ public function execute() return $this->result->setContents("TRUE| Ignoring pending"); } - $orderEntityId = $transaction->getExtra3(); - /** @var Order $order */ + $orderNumber = $transaction->getOrderNumber(); $order = $this->orderRepository->get($orderEntityId); if (empty($order)) { $this->logger->critical('Cannot load order: ' . $orderEntityId); - return $this->result->setContents('FALSE| Cannot load order'); } - if ($order->getTotalDue() <= 0) { - $this->logger->debug('Total due <= 0, so not touching the status of the order: ' . $orderEntityId); + if ($order->getIncrementId() != $orderNumber) { + $this->logger->critical('Ordernumber not equal' . $orderEntityId); + return $this->result->setContents('TRUE| Failed. Ordernumber not found.'); + } + + $payment = $order->getPayment(); + $info = $payment->getAdditionalInformation(); + if (!empty($info['transactionId'])) { + if($info['transactionId'] != $payOrderId) { + $this->logger->critical('transaction not equal'); + return $this->result->setContents('FALSE| Cannot load order'); + } else { + $this->logger->debug('transactions match!'); + } + } else { + $this->logger->critical('transaction not set in order'); + return $this->result->setContents('TRUE| Failed. transaction not set.'); + } + + if ($order->getTotalDue() <= 0) { + $this->logger->debug($action . '. Ignoring - already paid: ' . $orderEntityId); return $this->result->setContents('TRUE| Ignoring: order has already been paid'); } + if ($action == 'capture') { - $payment = $order->getPayment(); if (!empty($payment) && $payment->getAdditionalInformation('manual_capture')) { $this->logger->debug('Already captured.'); return $this->result->setContents('TRUE| Already captured.'); @@ -261,7 +280,7 @@ private function uncancelOrder(Order $order) * @param Order $order * @return \Magento\Framework\Controller\Result\Raw */ - private function processPaidOrder(Transaction $transaction, Order $order) + private function processPaidOrder(Status $transaction, Order $order) { if ($transaction->isPaid()) { $message = "PAID"; @@ -326,9 +345,9 @@ private function processPaidOrder(Transaction $transaction, Order $order) $payment->save(); $transactionBuilder->save(); - # Change amount paid manually + # Change amount paid manually $order->setTotalPaid($order->getGrandTotal()); - $order->setBaseTotalPaid($order->getBaseGrandTotal()); + $order->setBaseTotalPaid($order->getBaseGrandTotal()); $order->addStatusHistoryComment(__('B2B Setting: Skipped creating invoice')); $this->orderRepository->save($order); diff --git a/Controller/Checkout/Finish.php b/Controller/Checkout/Finish.php index 6461ada1..abb075ac 100644 --- a/Controller/Checkout/Finish.php +++ b/Controller/Checkout/Finish.php @@ -18,7 +18,7 @@ /** * Description of Redirect * - * @author Andy Pieters + * @author PAY. */ class Finish extends PayAction { @@ -31,22 +31,22 @@ class Finish extends PayAction /** * @var Session */ - private $checkoutSession; + private $checkoutSession; /** * @var LoggerInterface */ - private $logger; + private $logger; /** * @var OrderRepository */ - private $orderRepository; + private $orderRepository; - /** - * @var QuoteRepository - */ - private $quoteRepository; + /** + * @var QuoteRepository + */ + private $quoteRepository; /** * Index constructor. @@ -56,19 +56,12 @@ class Finish extends PayAction * @param LoggerInterface $logger * @param OrderRepository $orderRepository */ - public function __construct( - Context $context, - Config $config, - Session $checkoutSession, - LoggerInterface $logger, - OrderRepository $orderRepository, - QuoteRepository $quoteRepository - ) + public function __construct(Context $context, Config $config, Session $checkoutSession, LoggerInterface $logger, OrderRepository $orderRepository, QuoteRepository $quoteRepository) { - $this->config = $config; - $this->checkoutSession = $checkoutSession; - $this->logger = $logger; - $this->orderRepository = $orderRepository; + $this->config = $config; + $this->checkoutSession = $checkoutSession; + $this->logger = $logger; + $this->orderRepository = $orderRepository; $this->quoteRepository = $quoteRepository; parent::__construct($context); @@ -85,86 +78,94 @@ private function checkSession(Order $order, $orderId, $session) } } + private function checkEmpty($field, $name, $errorCode, $desc = null) + { + if (empty($field)) { + $desc = empty($desc) ? $name . ' is empty' : $desc; + throw new \Exception('Finish: ' . $desc, $errorCode); + } + } + public function execute() { $resultRedirect = $this->resultRedirectFactory->create(); \Paynl\Config::setApiToken($this->config->getApiToken()); $params = $this->getRequest()->getParams(); - if(!isset($params['orderId']) && !isset($params['orderid'])){ - $this->messageManager->addNoticeMessage(__('Invalid return, no transactionId specified')); - $this->logger->critical('Invalid return, no transactionId specified', $params); - $resultRedirect->setPath('checkout/cart'); - return $resultRedirect; - } - try{ - if (empty($params['orderId'])) - $params['orderId'] = $params['orderid']; - $transaction = \Paynl\Transaction::get($params['orderId']); - } catch(\Exception $e){ - $this->logger->critical($e, $params); - $this->messageManager->addExceptionMessage($e, __('There was an error checking the transaction status')); - $resultRedirect->setPath('checkout/cart'); - return $resultRedirect; - } - - /** - * @var Order $order - */ - $order = $this->orderRepository->get($transaction->getExtra3()); - $payment = $order->getPayment(); - $information = $payment->getAdditionalInformation(); + $payOrderId = empty($params['orderId']) ? (empty($params['orderid']) ? null : $params['orderid']) : $params['orderId']; + $orderStatusId = empty($params['orderStatusId']) ? null : intval($params['orderStatusId']); + $magOrderId = empty($params['entityid']) ? null : $params['entityid']; + $bSuccess = $orderStatusId === Config::ORDERSTATUS_PAID; + $bDenied = $orderStatusId === Config::ORDERSTATUS_DENIED; $pinStatus = null; - if(isset($information['terminal_hash'])){ - $hash = $information['terminal_hash']; - $status = \Paynl\Instore::status([ - 'hash' => $hash - ]); - $pinStatus = $status->getTransactionState(); - } - - if ($transaction->isPaid() || $transaction->isAuthorized() || ($transaction->isPending() && $pinStatus == null)) { - $successUrl = $this->config->getSuccessPage($payment->getMethod()); - - if(empty($successUrl)) { - $successUrl = ($payment->getMethod() == 'paynl_payment_paylink') ? Config::FINISH_PAYLINK : Config::FINISH_STANDARD; + $pinCanceled = null; + + try { + $this->checkEmpty($payOrderId, 'payOrderid', 101); + $this->checkEmpty($magOrderId, 'magOrderId', 1012); + + $order = $this->orderRepository->get($magOrderId); + $this->checkEmpty($order, 'order', 1013); + + $payment = $order->getPayment(); + $information = $payment->getAdditionalInformation(); + + $this->checkEmpty($information['transactionId'] == $payOrderId, '', 1014, 'transaction mismatch'); + + if (!empty($information['terminal_hash'])) { + $status = \Paynl\Instore::status(['hash' => $information['terminal_hash']]); + $this->logger->debug($status->getTransactionState(), $params); + $pinStatus = $status->getTransactionState(); + $pinCanceled = false; + if (in_array($pinStatus, ['cancelled', 'expired', 'error'])) { + # Instore does not send a canceled exchange message, so cancel it here + $order->cancel(); + $this->orderRepository->save($order); + $pinCanceled = true; + } } - $resultRedirect->setPath($successUrl, ['_query' => ['utm_nooverride' => '1']]); - - # Make the cart inactive - $session = $this->checkoutSession; - $this->checkSession($order, $params['orderId'], $session); - - $quote = $session->getQuote(); - $quote->setIsActive(false); - $this->quoteRepository->save($quote); - - return $resultRedirect; - } + if (empty($bSuccess) || $pinCanceled == false) { + $transaction = \Paynl\Transaction::status($payOrderId); + $orderNumber = $transaction->getOrderNumber(); + $this->checkEmpty($order->getIncrementId() == $orderNumber, '', 104, 'order mismatch'); + $bSuccess = ($transaction->isPaid() || $transaction->isAuthorized() || $transaction->isPending()); + } - $orderStatus = empty($params['orderStatusId']) ? null : $params['orderStatusId']; - $cancelMessage = $orderStatus == -63 ? __('Payment denied') : __('Payment canceled'); - $this->messageManager->addNoticeMessage($cancelMessage); + if ($bSuccess) { + $successUrl = $this->config->getSuccessPage($payment->getMethod()); + if (empty($successUrl)) { + $successUrl = ($payment->getMethod() == 'paynl_payment_paylink') ? Config::FINISH_PAYLINK : Config::FINISH_STANDARD; + } + + $resultRedirect->setPath($successUrl, ['_query' => ['utm_nooverride' => '1']]); + + # Make the cart inactive + $session = $this->checkoutSession; + if (empty($order)) { + $order = $this->getOrder($magOrderId, $payOrderId); + } + $this->checkSession($order, $payOrderId, $session); + + $quote = $session->getQuote(); + $quote->setIsActive(false); + $this->quoteRepository->save($quote); + } else { + $cancelMessage = $bDenied ? __('Payment denied') : __('Payment canceled'); + $this->messageManager->addNoticeMessage($cancelMessage); + $resultRedirect->setPath($payment->getMethod() == 'paynl_payment_paylink' ? Config::FINISH_PAYLINK . '?cancel=1' : $this->config->getCancelURL()); + } + } catch (\Exception $e) { + $this->logger->critical($e->getCode() . ': ' . $e->getMessage(), $params); - if ($payment->getMethod() == 'paynl_payment_paylink') { - $cancelURL = Config::FINISH_PAYLINK . '?cancel=1'; - } else { - $cancelURL = $this->config->getCancelURL(); + if ($e->getCode() == 101) { + $this->messageManager->addNoticeMessage(__('Invalid return, no transactionId specified')); + } else { + $this->messageManager->addNoticeMessage(__('Unfortunately something went wrong')); + } + $resultRedirect->setPath('checkout/cart'); } - $resultRedirect->setPath($cancelURL); - - - if(in_array($pinStatus,[ - 'cancelled', - 'expired', - 'error' - ])){ - // Instore does not send a canceled exchange message, so we cancel it here - $order->cancel(); - $this->orderRepository->save($order); - } return $resultRedirect; } diff --git a/Model/Config.php b/Model/Config.php index 8cdddda0..4f138481 100644 --- a/Model/Config.php +++ b/Model/Config.php @@ -16,6 +16,8 @@ class Config { const FINISH_PAYLINK = 'paynl/checkout/paylink'; const FINISH_STANDARD = 'checkout/onepage/success'; + const ORDERSTATUS_PAID = 100; + const ORDERSTATUS_DENIED = -63; /** @var Store */ private $store; diff --git a/Model/Paymentmethod/Paylink.php b/Model/Paymentmethod/Paylink.php index bc9c85f1..c45c2727 100644 --- a/Model/Paymentmethod/Paylink.php +++ b/Model/Paymentmethod/Paylink.php @@ -28,7 +28,7 @@ protected function getDefaultPaymentOptionId() // this is an admin only method protected $_canUseCheckout = false; - + public function initialize($paymentAction, $stateObject) { @@ -38,25 +38,26 @@ public function initialize($paymentAction, $stateObject) $this->orderRepository->save($order); $transaction = $this->doStartTransaction($order); - + + $order->getPayment()->setAdditionalInformation('transactionId', $transaction->getTransactionId()); + $status = $this->getConfigData('order_status'); $url = $transaction->getRedirectUrl(); $objectManager = \Magento\Framework\App\ObjectManager::GetInstance(); - + $getLocale = $objectManager->get('Magento\Framework\Locale\Resolver'); - $haystack = $getLocale->getLocale(); - $lang = strstr($haystack, '_', true); - + $haystack = $getLocale->getLocale(); + $lang = strstr($haystack, '_', true); + $pos = strrpos($url, 'NL'); - if($pos !== false) - { + if ($pos !== false) { $url = substr_replace($url, strtoupper($lang), $pos, strlen('NL')); - } + } $paylinktext = __('A PAY. Paylink has been send to'); - $order->addStatusHistoryComment($paylinktext . ' ' . $order->getCustomerEmail() . '.', $status); + $order->addStatusHistoryComment($paylinktext . ' ' . $order->getCustomerEmail() . '.', $status); $store = $order->getStore(); $storeId = $order->getStoreId(); @@ -68,7 +69,7 @@ public function initialize($paymentAction, $stateObject) $sender = [ 'name' => $senderName, 'email' => $senderEmail, - ]; + ]; $customerEmail = array($order->getCustomerEmail()); @@ -77,7 +78,7 @@ public function initialize($paymentAction, $stateObject) $orderHTML = $paymentHelper->getInfoBlockHtml( $order->getPayment(), $storeId - ); + ); $addressRenderer = $objectManager->create('Magento\Sales\Model\Order\Address\Renderer'); @@ -95,7 +96,7 @@ public function initialize($paymentAction, $stateObject) $subject = str_replace('((store_name))',$order->getStore()->getName(),$subject); $subject = str_replace('((support_email))',''.$supportEmail.'',$subject); $subject = str_replace('((order_id))',$order->getIncrementId(),$subject); - + $body = $this->_scopeConfig->getValue('payment/paynl_payment_paylink/paylink_body', 'store', $storeId); $body = nl2br($body); $body = str_replace('((paylink))',''.__('PAY. paylink').'',$body); @@ -103,7 +104,7 @@ public function initialize($paymentAction, $stateObject) $body = str_replace('((store_name))',$order->getStore()->getName(),$body); $body = str_replace('((support_email))',''.$supportEmail.'',$body); $body = str_replace('((order_id))',$order->getIncrementId(),$body); - + $templateVars = array( 'subject' => $subject, 'body' => $body, @@ -113,9 +114,9 @@ public function initialize($paymentAction, $stateObject) 'paylink' => $url, 'support_email' => $supportEmail, 'current_language' => $lang, - 'order_id' => $order->getIncrementId(), + 'order_id' => $order->getIncrementId(), 'billing' => $order->getBillingAddress(), - 'payment_html' => $orderHTML, + 'payment_html' => $orderHTML, 'formattedShippingAddress' => $order->getIsVirtual() ? null : $addressRenderer->format($order->getShippingAddress(), 'html'), 'formattedBillingAddress' => $addressRenderer->format($order->getBillingAddress(), 'html'), 'created_at_formatted' => $order->getCreatedAtFormatted(1), @@ -124,10 +125,10 @@ public function initialize($paymentAction, $stateObject) 'is_not_virtual' => $order->getIsNotVirtual(), 'email_customer_note' => $order->getEmailCustomerNote(), 'frontend_status_label' => $order->getFrontendStatusLabel(), - 'show_order_in_mail' => $show_order_in_mail + 'show_order_in_mail' => $show_order_in_mail ], - - ); + + ); $transportBuilder = $objectManager->create('\Magento\Framework\Mail\Template\TransportBuilder'); @@ -136,10 +137,10 @@ public function initialize($paymentAction, $stateObject) ->setTemplateVars($templateVars) ->setFrom($sender) ->addTo($customerEmail) - ->setReplyTo($supportEmail) - ->getTransport(); + ->setReplyTo($supportEmail) + ->getTransport(); $transport->sendMessage(); - + parent::initialize($paymentAction, $stateObject); } } diff --git a/Model/Paymentmethod/PaymentMethod.php b/Model/Paymentmethod/PaymentMethod.php index 757d755a..632c4774 100644 --- a/Model/Paymentmethod/PaymentMethod.php +++ b/Model/Paymentmethod/PaymentMethod.php @@ -294,8 +294,8 @@ protected function doStartTransaction(Order $order) $store = $order->getStore(); $baseUrl = $store->getBaseUrl(); - // i want to use the url builder here, but that doenst work from admin, even if the store is supplied - $returnUrl = $baseUrl . 'paynl/checkout/finish/'; + + $returnUrl = $baseUrl . 'paynl/checkout/finish/?entityid=' . $order->getEntityId(); $exchangeUrl = $baseUrl . 'paynl/checkout/exchange/'; $paymentOptionId = $this->getPaymentOptionId(); diff --git a/composer.json b/composer.json index be44179e..a9bb9e4b 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,7 @@ "magento/module-sales": "^102.0.0", "magento/module-payment": "^100.3.0", "magento/module-quote": "^101.1.0", - "paynl/sdk": "^1.5.14" + "paynl/sdk": "^1.5.19", }, "authors": [ { From f08f8b0bc04b2ecd2e10f51631b8c1bdbeec8928 Mon Sep 17 00:00:00 2001 From: woutse Date: Fri, 28 May 2021 20:25:00 +0200 Subject: [PATCH 2/5] Now using the status SDK method. --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index a9bb9e4b..c316e93e 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,7 @@ "magento/module-sales": "^102.0.0", "magento/module-payment": "^100.3.0", "magento/module-quote": "^101.1.0", - "paynl/sdk": "^1.5.19", + "paynl/sdk": "^1.5.19" }, "authors": [ { From cbc278b184521e30121a3800910e8a260576c84d Mon Sep 17 00:00:00 2001 From: woutse Date: Wed, 2 Jun 2021 16:34:50 +0200 Subject: [PATCH 3/5] Code polish --- Controller/Checkout/Exchange.php | 12 +++++------- Controller/Checkout/Finish.php | 3 +-- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/Controller/Checkout/Exchange.php b/Controller/Checkout/Exchange.php index cbc67a99..ca463b5c 100644 --- a/Controller/Checkout/Exchange.php +++ b/Controller/Checkout/Exchange.php @@ -174,15 +174,13 @@ public function execute() $payment = $order->getPayment(); $info = $payment->getAdditionalInformation(); if (!empty($info['transactionId'])) { - if($info['transactionId'] != $payOrderId) { - $this->logger->critical('transaction not equal'); + if ($info['transactionId'] != $payOrderId) { + $this->logger->critical('Transaction not equal'); return $this->result->setContents('FALSE| Cannot load order'); - } else { - $this->logger->debug('transactions match!'); } } else { - $this->logger->critical('transaction not set in order'); - return $this->result->setContents('TRUE| Failed. transaction not set.'); + $this->logger->critical('Transaction not set in order'); + return $this->result->setContents('TRUE| Failed. Transaction not set.'); } if ($order->getTotalDue() <= 0) { @@ -196,7 +194,7 @@ public function execute() return $this->result->setContents('TRUE| Already captured.'); } } - + if ($transaction->isPaid() || $transaction->isAuthorized()) { return $this->processPaidOrder($transaction, $order); } elseif ($transaction->isCanceled()) { diff --git a/Controller/Checkout/Finish.php b/Controller/Checkout/Finish.php index abb075ac..5e99eae7 100644 --- a/Controller/Checkout/Finish.php +++ b/Controller/Checkout/Finish.php @@ -99,7 +99,7 @@ public function execute() $bDenied = $orderStatusId === Config::ORDERSTATUS_DENIED; $pinStatus = null; $pinCanceled = null; - + try { $this->checkEmpty($payOrderId, 'payOrderid', 101); $this->checkEmpty($magOrderId, 'magOrderId', 1012); @@ -114,7 +114,6 @@ public function execute() if (!empty($information['terminal_hash'])) { $status = \Paynl\Instore::status(['hash' => $information['terminal_hash']]); - $this->logger->debug($status->getTransactionState(), $params); $pinStatus = $status->getTransactionState(); $pinCanceled = false; if (in_array($pinStatus, ['cancelled', 'expired', 'error'])) { From f4120d4e6cb3f648ff23863a454252b9eb04070a Mon Sep 17 00:00:00 2001 From: woutse Date: Wed, 2 Jun 2021 20:40:08 +0200 Subject: [PATCH 4/5] Fixed an issue with pintransactions and prevented uncatched exception errors --- Controller/Checkout/Finish.php | 36 +++++++++++++++---------- Model/Paymentmethod/Instore.php | 38 +++++++++++++++++++-------- Model/Paymentmethod/PaymentMethod.php | 26 +++++++++++++----- 3 files changed, 69 insertions(+), 31 deletions(-) diff --git a/Controller/Checkout/Finish.php b/Controller/Checkout/Finish.php index 5e99eae7..79a4db82 100644 --- a/Controller/Checkout/Finish.php +++ b/Controller/Checkout/Finish.php @@ -97,9 +97,8 @@ public function execute() $magOrderId = empty($params['entityid']) ? null : $params['entityid']; $bSuccess = $orderStatusId === Config::ORDERSTATUS_PAID; $bDenied = $orderStatusId === Config::ORDERSTATUS_DENIED; - $pinStatus = null; - $pinCanceled = null; - + $isPinTransaction = false; + try { $this->checkEmpty($payOrderId, 'payOrderid', 101); $this->checkEmpty($magOrderId, 'magOrderId', 1012); @@ -112,19 +111,12 @@ public function execute() $this->checkEmpty($information['transactionId'] == $payOrderId, '', 1014, 'transaction mismatch'); - if (!empty($information['terminal_hash'])) { - $status = \Paynl\Instore::status(['hash' => $information['terminal_hash']]); - $pinStatus = $status->getTransactionState(); - $pinCanceled = false; - if (in_array($pinStatus, ['cancelled', 'expired', 'error'])) { - # Instore does not send a canceled exchange message, so cancel it here - $order->cancel(); - $this->orderRepository->save($order); - $pinCanceled = true; - } + if (!empty($information['terminal_hash']) && !$bSuccess) { + $isPinTransaction = true; + $this->handlePin($information['terminal_hash'], $order); } - if (empty($bSuccess) || $pinCanceled == false) { + if (empty($bSuccess) && !$isPinTransaction) { $transaction = \Paynl\Transaction::status($payOrderId); $orderNumber = $transaction->getOrderNumber(); $this->checkEmpty($order->getIncrementId() == $orderNumber, '', 104, 'order mismatch'); @@ -168,4 +160,20 @@ public function execute() return $resultRedirect; } + /** + * @param $hash + * @param $order + * @throws \Magento\Framework\Exception\AlreadyExistsException + * @throws \Magento\Framework\Exception\InputException + * @throws \Magento\Framework\Exception\NoSuchEntityException + */ + private function handlePin($hash, $order) + { + $status = \Paynl\Instore::status(['hash' => $hash]); + if (in_array($status->getTransactionState(), ['cancelled', 'expired', 'error'])) { + # Instore does not send a canceled exchange message, so cancel it here + $order->cancel(); + $this->orderRepository->save($order); + } + } } diff --git a/Model/Paymentmethod/Instore.php b/Model/Paymentmethod/Instore.php index a0e1b734..49467700 100644 --- a/Model/Paymentmethod/Instore.php +++ b/Model/Paymentmethod/Instore.php @@ -22,27 +22,43 @@ protected function getDefaultPaymentOptionId() public function startTransaction(Order $order) { + $store = $order->getStore(); + $url = $store->getBaseUrl() . 'checkout/cart/'; $additionalData = $order->getPayment()->getAdditionalInformation(); - $bankId = null; + $terminalId = null; if (isset($additionalData['bank_id'])) { - $bankId = $additionalData['bank_id']; + $terminalId = $additionalData['bank_id']; } unset($additionalData['bank_id']); - $transaction = $this->doStartTransaction($order); + try { + if (empty($terminalId)) { + throw new \Exception(__('Please select a pin-terminal'), 201); + } + $transaction = $this->doStartTransaction($order); + + $instorePayment = \Paynl\Instore::payment(['transactionId' => $transaction->getTransactionId(), 'terminalId' => $terminalId]); + + $additionalData['transactionId'] = $transaction->getTransactionId(); + $additionalData['terminal_hash'] = $instorePayment->getHash(); - $instorePayment = \Paynl\Instore::payment([ - 'transactionId' => $transaction->getTransactionId(), - 'terminalId' => $bankId - ]); + $order->getPayment()->setAdditionalInformation($additionalData); + $order->save(); - $additionalData['terminal_hash'] = $instorePayment->getHash(); + $url = $instorePayment->getRedirectUrl(); - $order->getPayment()->setAdditionalInformation($additionalData); - $order->save(); + } catch (\Exception $e) { + $this->logger->critical($e->getMessage(), array()); + + if ($e->getCode() == 201) { + $this->messageManager->addNoticeMessage($e->getMessage()); + } else { + $this->messageManager->addNoticeMessage(__('Pin transaction could not be started')); + } + } - return $instorePayment->getRedirectUrl(); + return $url; } public function assignData(\Magento\Framework\DataObject $data) diff --git a/Model/Paymentmethod/PaymentMethod.php b/Model/Paymentmethod/PaymentMethod.php index 632c4774..40c609f7 100644 --- a/Model/Paymentmethod/PaymentMethod.php +++ b/Model/Paymentmethod/PaymentMethod.php @@ -12,11 +12,13 @@ use Magento\Framework\Data\Collection\AbstractDb; use Magento\Framework\Model\Context; use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Registry; use Magento\Payment\Helper\Data; use Magento\Payment\Model\InfoInterface; use Magento\Payment\Model\Method\AbstractMethod; use Magento\Payment\Model\Method\Logger; +use Psr\Log\LoggerInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\OrderRepository; use Paynl\Payment\Model\Config; @@ -31,7 +33,6 @@ abstract class PaymentMethod extends AbstractMethod { protected $_code = 'paynl_payment_base'; - protected $_isInitializeNeeded = true; protected $_canRefund = true; @@ -41,6 +42,11 @@ abstract class PaymentMethod extends AbstractMethod protected $_canVoid = true; + /** + * + * @var Psr\Log\LoggerInterface + */ + protected $logger; /** * @var Config @@ -58,6 +64,11 @@ abstract class PaymentMethod extends AbstractMethod protected $helper; + /** + * @var Magento\Framework\Message\ManagerInterface + */ + protected $messageManager; + public function __construct( Context $context, Registry $registry, @@ -65,25 +76,28 @@ public function __construct( AttributeValueFactory $customAttributeFactory, Data $paymentData, ScopeConfigInterface $scopeConfig, - Logger $logger, + Logger $methodLogger, \Magento\Sales\Model\Order\Config $orderConfig, OrderRepository $orderRepository, Config $paynlConfig, AbstractResource $resource = null, AbstractDb $resourceCollection = null, - array $data = [] + array $data = [], + ManagerInterface $messageManager, + LoggerInterface $logger ) { parent::__construct( $context, $registry, $extensionFactory, $customAttributeFactory, - $paymentData, $scopeConfig, $logger, $resource, $resourceCollection, $data); + $paymentData, $scopeConfig, $methodLogger, $resource, $resourceCollection, $data); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - + $this->messageManager = $messageManager; $this->helper = $objectManager->create('Paynl\Payment\Helper\PayHelper'); $this->paynlConfig = $paynlConfig; $this->orderRepository = $orderRepository; $this->orderConfig = $orderConfig; + $this->logger = $logger; } protected function getState($status) @@ -294,7 +308,7 @@ protected function doStartTransaction(Order $order) $store = $order->getStore(); $baseUrl = $store->getBaseUrl(); - + $returnUrl = $baseUrl . 'paynl/checkout/finish/?entityid=' . $order->getEntityId(); $exchangeUrl = $baseUrl . 'paynl/checkout/exchange/'; From ddfc28938e2867413d4bc1f283bd1fa1950fca78 Mon Sep 17 00:00:00 2001 From: woutse Date: Fri, 4 Jun 2021 16:38:11 +0200 Subject: [PATCH 5/5] Removed construct inserts --- Model/Paymentmethod/PaymentMethod.php | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/Model/Paymentmethod/PaymentMethod.php b/Model/Paymentmethod/PaymentMethod.php index 40c609f7..45de5281 100644 --- a/Model/Paymentmethod/PaymentMethod.php +++ b/Model/Paymentmethod/PaymentMethod.php @@ -12,13 +12,11 @@ use Magento\Framework\Data\Collection\AbstractDb; use Magento\Framework\Model\Context; use Magento\Framework\Model\ResourceModel\AbstractResource; -use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Registry; use Magento\Payment\Helper\Data; use Magento\Payment\Model\InfoInterface; use Magento\Payment\Model\Method\AbstractMethod; use Magento\Payment\Model\Method\Logger; -use Psr\Log\LoggerInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\OrderRepository; use Paynl\Payment\Model\Config; @@ -82,9 +80,7 @@ public function __construct( Config $paynlConfig, AbstractResource $resource = null, AbstractDb $resourceCollection = null, - array $data = [], - ManagerInterface $messageManager, - LoggerInterface $logger + array $data = [] ) { parent::__construct( @@ -92,12 +88,13 @@ public function __construct( $paymentData, $scopeConfig, $methodLogger, $resource, $resourceCollection, $data); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $this->messageManager = $messageManager; + + $this->messageManager = $objectManager->get(\Magento\Framework\Message\ManagerInterface::class); $this->helper = $objectManager->create('Paynl\Payment\Helper\PayHelper'); $this->paynlConfig = $paynlConfig; $this->orderRepository = $orderRepository; $this->orderConfig = $orderConfig; - $this->logger = $logger; + $this->logger = $objectManager->get(\Psr\Log\LoggerInterface::class); } protected function getState($status)