From 138005bbc0129f67e1b55f90ba332f9dbe007cb4 Mon Sep 17 00:00:00 2001 From: kGablo Date: Tue, 28 Nov 2023 08:39:57 +0100 Subject: [PATCH 01/21] =?UTF-8?q?DX-161=20Stworzenie=20implementacji=20int?= =?UTF-8?q?erface=20p=C5=82atno=C5=9Bci=20Tpay=20dla=20Origin=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Api/Sales/OrderRepositoryInterface.php | 12 +- Api/TpayInterface.php | 133 ++++------- Controller/Tpaycom.php | 60 ----- Controller/tpay/Create.php | 120 +++++----- Controller/tpay/Error.php | 2 + Controller/tpay/Notification.php | 90 +++----- Controller/tpay/Redirect.php | 13 +- Controller/tpay/Refund.php | 96 -------- Controller/tpay/Success.php | 2 + Model/ApiFacade/OpenApi.php | 82 +++++++ Model/ApiFacade/Refund/RefundApiFacade.php | 62 +++++ Model/ApiFacade/Refund/RefundOriginApi.php | 60 +++++ .../Transaction/TransactionApiFacade.php | 67 ++++++ .../Transaction/TransactionOriginApi.php | 39 ++++ Model/NotificationModel.php | 19 -- Model/RefundModel.php | 23 -- Model/Sales/OrderRepository.php | 4 +- Model/Tpay.php | 215 +++++++----------- Model/TpayConfigProvider.php | 35 +-- Model/TransactionModel.php | 25 -- Service/TpayService.php | 73 ++---- etc/adminhtml/system.xml | 8 + etc/config.xml | 3 +- etc/csp_whitelist.xml | 6 + etc/module.xml | 2 +- i18n/pl_PL.csv | 4 +- view/base/web/js/render_channels.js | 63 ++++- .../payment/method-renderer/tpay-method.js | 5 +- .../web/template/payment/tpay-form.html | 4 +- 29 files changed, 652 insertions(+), 675 deletions(-) delete mode 100644 Controller/Tpaycom.php delete mode 100644 Controller/tpay/Refund.php create mode 100755 Model/ApiFacade/OpenApi.php create mode 100755 Model/ApiFacade/Refund/RefundApiFacade.php create mode 100755 Model/ApiFacade/Refund/RefundOriginApi.php create mode 100755 Model/ApiFacade/Transaction/TransactionApiFacade.php create mode 100755 Model/ApiFacade/Transaction/TransactionOriginApi.php delete mode 100644 Model/NotificationModel.php delete mode 100644 Model/RefundModel.php delete mode 100644 Model/TransactionModel.php diff --git a/Api/Sales/OrderRepositoryInterface.php b/Api/Sales/OrderRepositoryInterface.php index c9ef6e3..cda6705 100644 --- a/Api/Sales/OrderRepositoryInterface.php +++ b/Api/Sales/OrderRepositoryInterface.php @@ -1,17 +1,13 @@ _customerSession = $customerSession; - $this->_checkoutSession = $checkoutSession; - $this->_orderFactory = $orderFactory; - $this->_model = $model; - $this->localeResolver = $localeResolver; - $this->objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - parent::__construct($context); - - $this->_model->setCustomerID($this->_customerSession->getCustomerId()); - } - - protected function getDotAmount() - { - return $this->getFormatAmount($this->_checkoutSession->getLastRealOrder()->getGrandTotal()); - } -} diff --git a/Controller/tpay/Create.php b/Controller/tpay/Create.php index 434772f..ee6da94 100644 --- a/Controller/tpay/Create.php +++ b/Controller/tpay/Create.php @@ -1,17 +1,27 @@ tpay = $tpayModel; - $this->transactionFactory = $transactionModelFactory; $this->tpayService = $tpayService; $this->checkoutSession = $checkoutSession; Util::$loggingEnabled = false; @@ -45,53 +51,45 @@ public function __construct( parent::__construct($context); } + /** {@inheritdoc} */ public function execute() { - /** @var int $orderId */ $orderId = $this->checkoutSession->getLastRealOrderId(); - if ($orderId) { - /** @var DataObject $payment */ $payment = $this->tpayService->getPayment($orderId); - - /** @var array $paymentData */ $paymentData = $payment->getData(); - - $this->transaction = $this->transactionFactory->create( - [ - 'apiPassword' => $this->tpay->getApiPassword(), - 'apiKey' => $this->tpay->getApiKey(), - 'merchantId' => $this->tpay->getMerchantId(), - 'merchantSecret' => $this->tpay->getSecurityCode(), - ] - ); + $this->transaction = new TransactionApiFacade($this->tpay); $additionalPaymentInformation = $paymentData['additional_information']; - /** @var array $transaction */ $transaction = $this->prepareTransaction($orderId, $additionalPaymentInformation); if (!isset($transaction['title'], $transaction['url'])) { return $this->_redirect('magento2basic/tpay/error'); } - $this->tpayService->addCommentToHistory($orderId, 'Transaction title '.$transaction['title']); + + $this->handleOpenApiTrId($paymentData, $transaction); + + $this->tpayService->addCommentToHistory($orderId, 'Transaction title ' . $transaction['title']); $transactionUrl = $transaction['url']; - if (true === $this->tpay->redirectToChannel()) { + + if ($this->tpay->redirectToChannel() === true) { $transactionUrl = str_replace('gtitle', 'title', $transactionUrl); } - $this->tpayService->addCommentToHistory($orderId, 'Transaction link '.$transactionUrl); + + $this->tpayService->addCommentToHistory($orderId, 'Transaction link ' . $transactionUrl); $paymentData['additional_information']['transaction_url'] = $transactionUrl; $payment->setData($paymentData)->save(); - if (6 === strlen($additionalPaymentInformation['blik_code']) - && $this->tpay->checkBlikLevel0Settings() - ) { + if (strlen($additionalPaymentInformation['blik_code']) === 6 && $this->tpay->checkBlikLevel0Settings()) { + if (true === $this->transaction->isOpenApiUse()) { + return $this->_redirect('magento2basic/tpay/success'); + } $result = $this->blikPay($transaction['title'], $additionalPaymentInformation['blik_code']); $this->checkoutSession->unsQuoteId(); + if (!$result) { - $this->tpayService->addCommentToHistory( - $orderId, - 'User has typed wrong blik code and has been redirected to transaction panel in order to finish payment' - ); + $this->tpayService->addCommentToHistory($orderId, + 'User has typed wrong blik code and has been redirected to transaction panel in order to finish payment'); return $this->_redirect($transactionUrl); } @@ -105,33 +103,47 @@ public function execute() /** * Send BLIK code for transaction id - * * @param string $blikTransactionId * @param string $blikCode - * - * @return bool */ - protected function blikPay($blikTransactionId, $blikCode) + protected function blikPay($blikTransactionId, $blikCode): bool { - /** @var array $apiResult */ $apiResult = $this->transaction->blik($blikTransactionId, $blikCode); - return isset($apiResult['result']) && 1 === $apiResult['result']; + return isset($apiResult['result']) && $apiResult['result'] === 1; } - /** - * @param mixed $orderId - * @param array{blik_code: string, group: int|string} $additionalPaymentInformation - */ private function prepareTransaction($orderId, array $additionalPaymentInformation) { $data = $this->tpay->getTpayFormData($orderId); - if (6 === strlen($additionalPaymentInformation['blik_code'])) { - $data['group'] = TransactionModel::BLIK_CHANNEL; + + if (strlen($additionalPaymentInformation['blik_code']) === 6) { + $data['group'] = TransactionOriginApi::BLIK_CHANNEL; + $this->handleBlikData($data, $additionalPaymentInformation['blik_code']); } else { - $data['group'] = (int) $additionalPaymentInformation['group']; + $data['group'] = (int)$additionalPaymentInformation['group']; + + if ($this->tpay->redirectToChannel()) { + $data['direct'] = 1; + } } return $this->transaction->create($data); } + + private function handleBlikData(array &$data, string $blikCode) + { + if ($this->transaction->isOpenApiUse() && $this->tpay->checkBlikLevel0Settings()) { + $data['blikPaymentData'] = [ + 'blikToken' => $blikCode + ]; + } + } + + private function handleOpenApiTrId(array &$paymentData, array $transaction) + { + if (isset($transaction['transactionId'])) { + $paymentData['additional_information']['transaction_id'] = $transaction['transactionId']; + } + } } diff --git a/Controller/tpay/Error.php b/Controller/tpay/Error.php index 1772aad..e7dd0c1 100644 --- a/Controller/tpay/Error.php +++ b/Controller/tpay/Error.php @@ -1,5 +1,7 @@ tpay = $tpayModel; $this->remoteAddress = $remoteAddress; - $this->notificationFactory = $notificationModelFactory; $this->tpayService = $tpayService; Util::$loggingEnabled = false; parent::__construct($context); } - /** @return bool */ public function execute() { try { - $id = $this->tpay->getMerchantId(); $code = $this->tpay->getSecurityCode(); - $checkServer = $this->tpay->getCheckTpayIP(); - $checkProxy = $this->tpay->getCheckProxy(); - $forwardedIP = null; - $this->NotificationHandler = $this->notificationFactory->create( - [ - 'merchantId' => $id, - 'merchantSecret' => $code, - ] - ); - if (false === $checkServer) { - $this->NotificationHandler->disableValidationServerIP(); - } - if (true === $checkProxy) { - $this->NotificationHandler->enableForwardedIPValidation(); - } - - /** @var array $validParams */ - $validParams = $this->NotificationHandler->checkPayment(''); + $notification = (new JWSVerifiedPaymentNotification($code, !$this->tpay->useSandboxMode()))->getNotification(); + $notification = $notification->getNotificationAssociative(); + $orderId = base64_decode($notification['tr_crc']); - $orderId = base64_decode($validParams['tr_crc']); - if ('PAID' === $validParams['tr_status']) { + if ('PAID' === $notification['tr_status']) { $response = $this->getPaidTransactionResponse($orderId); - return $this - ->getResponse() - ->setStatusCode(Http::STATUS_CODE_200) - ->setContent($response); + return $this->getResponse()->setStatusCode(Http::STATUS_CODE_200)->setContent($response); } - $this->tpayService->SetOrderStatus($orderId, $validParams, $this->tpay); - return $this - ->getResponse() - ->setStatusCode(Http::STATUS_CODE_200) - ->setContent('TRUE'); + $this->tpayService->SetOrderStatus($orderId, $notification, $this->tpay); + + return $this->getResponse()->setStatusCode(Http::STATUS_CODE_200)->setContent('TRUE'); } catch (Exception $e) { - return false; + Util::log('Notification exception', "{$e->getMessage()} in file {$e->getFile()} line: {$e->getLine()} \n\n {$e->getTraceAsString()}"); + + return $this->getResponse()->setStatusCode(Http::STATUS_CODE_500)->setContent('FALSE'); } } /** * Create exception in case CSRF validation failed. * Return null if default exception will suffice. - * - * @return null|InvalidRequestException */ - public function createCsrfValidationException(RequestInterface $request) {} + public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException + { + return null; + } /** * Perform custom request validation. * Return null if default validation is needed. - * - * @return null|bool */ - public function validateForCsrf(RequestInterface $request) + public function validateForCsrf(RequestInterface $request): ?bool { return true; } /** * Check if the order has been canceled and get response to Tpay server. - * - * @param int $orderId - * - * @throws Exception - * * @return string response for Tpay server + * @throws Exception */ - protected function getPaidTransactionResponse($orderId) + protected function getPaidTransactionResponse(string $orderId): string { $order = $this->tpayService->getOrderById($orderId); + if (!$order->getId()) { - throw new Exception('Unable to get order by orderId %s', $orderId); + throw new Exception(sprintf('Unable to get order by orderId %s', $orderId)); } + if (Order::STATE_CANCELED === $order->getState()) { return 'FALSE'; } diff --git a/Controller/tpay/Redirect.php b/Controller/tpay/Redirect.php index c7576bc..e8e3518 100644 --- a/Controller/tpay/Redirect.php +++ b/Controller/tpay/Redirect.php @@ -1,5 +1,7 @@ getRequest()->getParam('uid'); - - /** @var int $orderId */ $orderId = $this->checkoutSession->getLastRealOrderId(); - if (!$orderId || !$uid) { return $this->_redirect('checkout/cart'); } $payment = $this->tpayService->getPayment($orderId); - - /** @var array $paymentData */ $paymentData = $payment->getData(); - $additionalPaymentInfo = $paymentData['additional_information']; if ( - (!isset($additionalPaymentInfo['group']) || (int) $additionalPaymentInfo['group'] < 1) - && (!isset($additionalPaymentInfo['blik_code']) || 6 !== strlen($additionalPaymentInfo['blik_code'])) + (!array_key_exists('group', $additionalPaymentInfo) || (int) $additionalPaymentInfo['group'] < 1) + && (!array_key_exists('blik_code', $additionalPaymentInfo) || 6 !== strlen($additionalPaymentInfo['blik_code'])) ) { return $this->_redirect('checkout/cart'); } diff --git a/Controller/tpay/Refund.php b/Controller/tpay/Refund.php deleted file mode 100644 index dac8236..0000000 --- a/Controller/tpay/Refund.php +++ /dev/null @@ -1,96 +0,0 @@ -apiPassword, $this->apiKey, $this->merchantId, $this->merchantSecret); - - /** @var array{result?: string, err?: int} $apiResult */ - $apiResult = $RefundModel - ->setTransactionID($payment->getParentTransactionId()) - ->refundAny(number_format($amount, 2)); - - if (isset($apiResult['result']) && 1 === (int) $apiResult['result']) { - return true; - } - $errCode = isset($apiResult['err']) ? ' error code: '.$apiResult['err'] : ''; - throw new Exception(__('Payment refunding error. -'.$errCode)); - } - - /** - * @param string $merchantSecret - * - * @return self - */ - public function setMerchantSecret($merchantSecret) - { - $this->merchantSecret = $merchantSecret; - - return $this; - } - - /** - * @param int $merchantId - * - * @return self - */ - public function setMerchantId($merchantId) - { - $this->merchantId = $merchantId; - - return $this; - } - - /** - * @param string $apiPassword - * - * @return self - */ - public function setApiPassword($apiPassword) - { - $this->apiPassword = $apiPassword; - - return $this; - } - - /** - * @param string $apiKey - * - * @return self - */ - public function setApiKey($apiKey) - { - $this->apiKey = $apiKey; - - return $this; - } -} diff --git a/Controller/tpay/Success.php b/Controller/tpay/Success.php index eeb9673..85ff48d 100644 --- a/Controller/tpay/Success.php +++ b/Controller/tpay/Success.php @@ -1,5 +1,7 @@ handleDataStructure($data); + $transaction = $this->Transactions->createTransaction($transactionData); + + return $this->updateRedirectUrl($transaction); + } + + public function makeRefund(InfoInterface $payment, string $amount): array + { + return $this->Transactions->createRefundByTransactionId(['amount' => number_format($amount, 2)], $payment->getAdditionalInformation('transaction_id')); + } + + private function handleDataStructure(array $data): array + { + $paymentData = [ + "amount" => $data['amount'], + "description" => $data['description'], + "hiddenDescription" => $data['crc'], + "payer" => [ + "email" => $data['email'], + "name" => $data['name'], + "phone" => $data['phone'], + "address" => $data['address'], + "code" => $data['zip'], + "city" => $data['city'], + "country" => $data['country'], + ], + "pay" => [ + "groupId" => $data['group'], + ], + "callbacks" => [ + "payerUrls" => [ + "success" => $data['return_url'], + "error" => $data['return_error_url'] + ], + "notification" => [ + "url" => $data['result_url'], + ] + ] + ]; + + if (!empty($data['blikPaymentData'])) { + $paymentData['pay']['blikPaymentData'] = [ + 'blikToken' => $data['blikPaymentData']['blikToken'] + ]; + } + + return $paymentData; + } + + private function updateRedirectUrl(array $transactionData): array + { + $blik0Url = null; + if (!isset($transactionData['transactionPaymentUrl']) && $transactionData['result'] === 'success') { + $blik0Url = 'blik0url'; + } + $transactionData['url'] = $transactionData['transactionPaymentUrl'] ?? $blik0Url; + + return $transactionData; + } +} diff --git a/Model/ApiFacade/Refund/RefundApiFacade.php b/Model/ApiFacade/Refund/RefundApiFacade.php new file mode 100755 index 0000000..7a74bb7 --- /dev/null +++ b/Model/ApiFacade/Refund/RefundApiFacade.php @@ -0,0 +1,62 @@ +originApi = new RefundOriginApi($tpay->getApiPassword(), $tpay->getApiKey(), $tpay->getMerchantId(), $tpay->getSecurityCode(), !$tpay->useSandboxMode()); + $this->createOpenApiInstance($tpay->getClientId(), $tpay->getOpenApiPassword(), !$tpay->useSandboxMode()); + } + + public function makeRefund(InfoInterface $payment, float $amount) + { + if ($payment->getAdditionalInformation('transaction_id')) { + return $this->getCurrentApi()->makeRefund($payment, $amount); + } + + return $this->originApi->makeRefund($payment, $amount); + } + + private function getCurrentApi() + { + return $this->useOpenApi ? $this->openApi : $this->originApi; + } + + private function createOpenApiInstance(string $clientId, string $apiPassword, bool $isProd) + { + try { + $this->openApi = new OpenApi($clientId, $apiPassword, $isProd); + $this->useOpenApi = true; + } catch (Exception $exception) { + $this->openApi = null; + $this->useOpenApi = false; + } + } +} diff --git a/Model/ApiFacade/Refund/RefundOriginApi.php b/Model/ApiFacade/Refund/RefundOriginApi.php new file mode 100755 index 0000000..e8da6d9 --- /dev/null +++ b/Model/ApiFacade/Refund/RefundOriginApi.php @@ -0,0 +1,60 @@ +trApiKey = $apiKey; + $this->trApiPass = $apiPassword; + $this->merchantId = $merchantId; + $this->merchantSecret = $merchantSecret; + parent::__construct(); + if (!$isProd) { + $this->apiURL = 'https://secure.sandbox.tpay.com/api/gw/'; + } + } + + /** + * @param InfoInterface $payment + * @param double $amount + * @return bool + * @throws \Exception + */ + public function makeRefund($payment, $amount) + { + Util::$loggingEnabled = false; + $apiResult = $this->setTransactionID($payment->getParentTransactionId()) + ->refundAny(number_format($amount, 2)); + if (isset($apiResult['result']) && (int)$apiResult['result'] === 1) { + return true; + } else { + $errCode = isset($apiResult['err']) ? ' error code: ' . $apiResult['err'] : ''; + throw new Exception(__('Payment refunding error. -' . $errCode)); + } + } +} diff --git a/Model/ApiFacade/Transaction/TransactionApiFacade.php b/Model/ApiFacade/Transaction/TransactionApiFacade.php new file mode 100755 index 0000000..4a54d53 --- /dev/null +++ b/Model/ApiFacade/Transaction/TransactionApiFacade.php @@ -0,0 +1,67 @@ +originApi = new TransactionOriginApi($tpay->getApiPassword(), $tpay->getApiKey(), $tpay->getMerchantId(), $tpay->getSecurityCode(), !$tpay->useSandboxMode()); + $this->createOpenApiInstance($tpay->getClientId(), $tpay->getOpenApiPassword(), !$tpay->useSandboxMode()); + } + + public function isOpenApiUse() + { + return $this->useOpenApi; + } + + public function create(array $config) + { + return $this->getCurrentApi()->create($config); + } + + public function blik($blikTransactionId, $blikCode) + { + return $this->originApi->blik($blikTransactionId, $blikCode); + } + + private function getCurrentApi() + { + return $this->useOpenApi ? $this->openApi : $this->originApi; + } + + private function createOpenApiInstance(string $clientId, string $apiPassword, bool $isProd) + { + try { + $this->openApi = new OpenApi($clientId, $apiPassword, $isProd); + $this->useOpenApi = true; + } catch (Exception $exception) { + $this->openApi = null; + $this->useOpenApi = false; + } + } +} diff --git a/Model/ApiFacade/Transaction/TransactionOriginApi.php b/Model/ApiFacade/Transaction/TransactionOriginApi.php new file mode 100755 index 0000000..ee548f1 --- /dev/null +++ b/Model/ApiFacade/Transaction/TransactionOriginApi.php @@ -0,0 +1,39 @@ +trApiKey = $apiKey; + $this->trApiPass = $apiPassword; + $this->merchantId = $merchantId; + $this->merchantSecret = $merchantSecret; + parent::__construct(); + if (!$isProd) { + $this->apiURL = 'https://secure.sandbox.tpay.com/api/gw/'; + } + } +} diff --git a/Model/NotificationModel.php b/Model/NotificationModel.php deleted file mode 100644 index 4950018..0000000 --- a/Model/NotificationModel.php +++ /dev/null @@ -1,19 +0,0 @@ -merchantId = $merchantId; - $this->merchantSecret = $merchantSecret; - parent::__construct(); - } -} diff --git a/Model/RefundModel.php b/Model/RefundModel.php deleted file mode 100644 index c5ea883..0000000 --- a/Model/RefundModel.php +++ /dev/null @@ -1,23 +0,0 @@ -trApiKey = $apiKey; - $this->trApiPass = $apiPassword; - $this->merchantId = $merchantId; - $this->merchantSecret = $merchantSecret; - parent::__construct(); - } -} diff --git a/Model/Sales/OrderRepository.php b/Model/Sales/OrderRepository.php index 6bc3b3a..f7a6832 100644 --- a/Model/Sales/OrderRepository.php +++ b/Model/Sales/OrderRepository.php @@ -1,5 +1,7 @@ */ protected $availableCurrencyCodes = ['PLN']; - - /** @var string */ protected $redirectURL = 'https://secure.tpay.com'; - - /** @var string */ protected $termsURL = 'https://secure.tpay.com/regulamin.pdf'; /** * Min. order amount for BLIK level 0 - * * @var float */ protected $minAmountBlik = 0.01; @@ -73,33 +56,29 @@ class Tpay extends AbstractMethod implements TpayInterface /** @var Escaper */ protected $escaper; - /** @var Refund */ - protected $refund; - /** @var StoreManager */ protected $storeManager; public function __construct( - Context $context, - Registry $registry, + Context $context, + Registry $registry, ExtensionAttributesFactory $extensionFactory, - AttributeValueFactory $customAttributeFactory, - Data $paymentData, - ScopeConfigInterface $scopeConfig, - Logger $logger, - UrlInterface $urlBuilder, - Session $checkoutSession, - OrderRepositoryInterface $orderRepository, - Refund $refund, - Escaper $escaper, - StoreManager $storeManager, - $data = [] - ) { + AttributeValueFactory $customAttributeFactory, + Data $paymentData, + ScopeConfigInterface $scopeConfig, + Logger $logger, + UrlInterface $urlBuilder, + Session $checkoutSession, + OrderRepositoryInterface $orderRepository, + Escaper $escaper, + StoreManager $storeManager, + $data = [] + ) + { $this->urlBuilder = $urlBuilder; $this->escaper = $escaper; $this->checkoutSession = $checkoutSession; $this->orderRepository = $orderRepository; - $this->refund = $refund; $this->storeManager = $storeManager; parent::__construct( @@ -116,12 +95,12 @@ public function __construct( ); } - public function getRedirectURL() + public function getRedirectURL(): string { return $this->redirectURL; } - public function checkBlikLevel0Settings() + public function checkBlikLevel0Settings(): bool { if (!$this->getBlikLevelZeroStatus() || !$this->checkBlikAmount()) { return false; @@ -134,55 +113,58 @@ public function checkBlikLevel0Settings() return !(empty($apiKey) || strlen($apiKey) < 8 || empty($apiPassword) || strlen($apiPassword) < 4); } - /** @return bool */ - public function getInstallmentsAmountValid() + public function getInstallmentsAmountValid(): bool { $amount = $this->getCheckoutTotal(); return $amount > 300 && $amount < 9259; } - public function getBlikLevelZeroStatus() + public function getBlikLevelZeroStatus(): bool { - return (bool) $this->getConfigData('blik_level_zero'); + return (bool)$this->getConfigData('blik_level_zero'); } - public function getApiKey() + public function getApiKey(): string { return $this->getConfigData('api_key_tpay'); } - public function getApiPassword() + public function getApiPassword(): string { return $this->getConfigData('api_password'); } - public function getInvoiceSendMail() + public function getInvoiceSendMail(): string { return $this->getConfigData('send_invoice_email'); } - public function getTermsURL() + public function getTermsURL(): string { return $this->termsURL; } - public function getTpayFormData($orderId = null) + /** {@inheritdoc} */ + public function getOpenApiPassword() + { + return $this->getConfigData('open_api_password'); + } + + public function getTpayFormData(?string $orderId = null): array { $order = $this->getOrder($orderId); $billingAddress = $order->getBillingAddress(); - $amount = number_format($order->getGrandTotal(), 2, '.', ''); + $amount = number_format((float)$order->getGrandTotal(), 2, '.', ''); $crc = base64_encode($orderId); - $name = $billingAddress->getData('firstname').' '.$billingAddress->getData('lastname'); - - /** @var string $phone */ + $name = $billingAddress->getData('firstname') . ' ' . $billingAddress->getData('lastname'); $phone = $billingAddress->getData('telephone'); return [ 'email' => $this->escaper->escapeHtml($order->getCustomerEmail()), 'name' => $this->escaper->escapeHtml($name), 'amount' => $amount, - 'description' => 'Zamówienie '.$orderId, + 'description' => 'Zamówienie ' . $orderId, 'crc' => $crc, 'address' => $this->escaper->escapeHtml($order->getBillingAddress()->getData('street')), 'city' => $this->escaper->escapeHtml($order->getBillingAddress()->getData('city')), @@ -193,56 +175,53 @@ public function getTpayFormData($orderId = null) 'return_url' => $this->urlBuilder->getUrl('magento2basic/tpay/success'), 'phone' => $phone, 'online' => $this->onlyOnlineChannels() ? 1 : 0, - 'module' => 'Magento '.$this->getMagentoVersion(), + 'module' => 'Magento ' . $this->getMagentoVersion(), ]; } - public function getMerchantId() + public function getMerchantId(): int { - return (int) $this->getConfigData('merchant_id'); + return (int)$this->getConfigData('merchant_id'); } - public function getSecurityCode() + /** {@inheritdoc} */ + public function getClientId() { - return $this->getConfigData('security_code'); + return $this->getConfigData('client_id'); } - public function onlyOnlineChannels() + public function getSecurityCode(): string { - return (bool) $this->getConfigData('show_payment_channels_online'); + return $this->getConfigData('security_code'); } - public function redirectToChannel() + public function onlyOnlineChannels(): bool { - return (bool) $this->getConfigData('redirect_directly_to_channel'); + return (bool)$this->getConfigData('show_payment_channels_online'); } - public function getCheckProxy() + public function redirectToChannel(): bool { - return (bool) $this->getConfigData('check_proxy'); + return (bool)$this->getConfigData('redirect_directly_to_channel'); } - public function getCheckTpayIP() + public function useSandboxMode(): bool { - return (bool) $this->getConfigData('check_server'); + return (bool)$this->getConfigData('use_sandbox'); } - public function getPaymentRedirectUrl() + public function getPaymentRedirectUrl(): string { - return $this->urlBuilder->getUrl('magento2basic/tpay/redirect', ['uid' => time().uniqid(true)]); + return $this->urlBuilder->getUrl('magento2basic/tpay/redirect', ['uid' => time() . uniqid('', true)]); } /** * {@inheritDoc} - * * Check that tpay.com payments should be available. */ - public function isAvailable(CartInterface $quote = null) + public function isAvailable(?CartInterface $quote = null) { - /** @var float|int $minAmount */ $minAmount = $this->getConfigData('min_order_total'); - - /** @var float|int $maxAmount */ $maxAmount = $this->getConfigData('max_order_total'); if ( @@ -263,22 +242,20 @@ public function isAvailable(CartInterface $quote = null) public function assignData(DataObject $data) { - /** @var array $additionalData */ $additionalData = $data->getData('additional_data'); - $info = $this->getInfoInstance(); $info->setAdditionalInformation( static::CHANNEL, - isset($additionalData[static::CHANNEL]) ? $additionalData[static::CHANNEL] : '' + array_key_exists(static::CHANNEL, $additionalData) ? $additionalData[static::CHANNEL] : '' ); $info->setAdditionalInformation( static::BLIK_CODE, - isset($additionalData[static::BLIK_CODE]) ? $additionalData[static::BLIK_CODE] : '' + array_key_exists(static::BLIK_CODE, $additionalData) ? $additionalData[static::BLIK_CODE] : '' ); - if (isset($additionalData[static::TERMS_ACCEPT]) && 1 === $additionalData[static::TERMS_ACCEPT]) { + if (array_key_exists(static::TERMS_ACCEPT, $additionalData) && 1 === $additionalData[static::TERMS_ACCEPT]) { $info->setAdditionalInformation( static::TERMS_ACCEPT, 1 @@ -290,21 +267,16 @@ public function assignData(DataObject $data) /** * Payment refund - * + * @param InfoInterface $payment * @param float $amount - * - * @throws \Exception - * * @return $this + * @throws \Exception */ public function refund(InfoInterface $payment, $amount) { - $this->refund - ->setApiKey($this->getApiKey()) - ->setApiPassword($this->getApiPassword()) - ->setMerchantId($this->getMerchantId()) - ->setMerchantSecret($this->getSecurityCode()); - $refundResult = $this->refund->makeRefund($payment, $amount); + $refundService = new RefundApiFacade($this); + + $refundResult = $refundService->makeRefund($payment, (float)$amount); try { if ($refundResult) { $payment @@ -322,70 +294,51 @@ public function refund(InfoInterface $payment, $amount) return $this; } - public function getConfigData($field, $storeId = null) - { - if (is_null($storeId)) { - $storeId = $this->storeManager->getStore()->getId(); - } - - return parent::getConfigData($field, $storeId); - } - - /** - * Check that the BLIK should be available for order/quote amount - * - * @return bool - */ - protected function checkBlikAmount() - { - return (bool) ($this->getCheckoutTotal() >= $this->minAmountBlik); - } - /** @return float current cart total */ - protected function getCheckoutTotal() + public function getCheckoutTotal() { - $amount = $this->getCheckout()->getQuote()->getBaseGrandTotal(); + $amount = (float)$this->getCheckout()->getQuote()->getBaseGrandTotal(); if (!$amount) { - /** @var int $orderId */ $orderId = $this->getCheckout()->getLastRealOrderId(); - $order = $this->orderRepository->getByIncrementId($orderId); $amount = $order->getGrandTotal(); } - return number_format($amount, 2, '.', ''); + return $amount; + } + + public function getConfigData($field, $storeId = null) + { + if (null === $storeId) { + $storeId = $this->storeManager->getStore()->getId(); + } + + return parent::getConfigData($field, $storeId); } - /** @return Session */ - protected function getCheckout() + /** Check that the BLIK should be available for order/quote amount */ + protected function checkBlikAmount(): bool + { + return (bool)($this->getCheckoutTotal() >= $this->minAmountBlik); + } + + protected function getCheckout(): Session { return $this->checkoutSession; } - /** - * @param int $orderId - * - * @return \Magento\Sales\Api\Data\OrderInterface - */ - protected function getOrder($orderId = null) + protected function getOrder(?string $orderId = null): \Magento\Sales\Api\Data\OrderInterface { if (null === $orderId) { - /** @var int $orderId */ $orderId = $this->getCheckout()->getLastRealOrderId(); } return $this->orderRepository->getByIncrementId($orderId); } - /** - * Availability for currency - * - * @param string $currencyCode - * - * @return bool - */ - protected function isAvailableForCurrency($currencyCode) + /** Availability for currency */ + protected function isAvailableForCurrency(string $currencyCode): bool { return !(!in_array($currencyCode, $this->availableCurrencyCodes)); } @@ -393,8 +346,6 @@ protected function isAvailableForCurrency($currencyCode) private function getMagentoVersion() { $objectManager = ObjectManager::getInstance(); - - /** @var ProductMetadataInterface $productMetadata */ $productMetadata = $objectManager->get('Magento\Framework\App\ProductMetadataInterface'); return $productMetadata->getVersion(); diff --git a/Model/TpayConfigProvider.php b/Model/TpayConfigProvider.php index b051ba1..bc8dab2 100644 --- a/Model/TpayConfigProvider.php +++ b/Model/TpayConfigProvider.php @@ -1,5 +1,7 @@ $this->createCSS('tpaycom_magento2basic::css/tpay.css'), 'blikStatus' => $this->getPaymentMethodInstance()->checkBlikLevel0Settings(), 'onlyOnlineChannels' => $this->getPaymentMethodInstance()->onlyOnlineChannels(), - 'getBlikChannelID' => TransactionModel::BLIK_CHANNEL, - 'isInstallmentsAmountValid' => $this->getPaymentMethodInstance()->getInstallmentsAmountValid(), + 'getBlikChannelID' => TransactionOriginApi::BLIK_CHANNEL, + 'useSandbox' => $tpay->useSandboxMode(), + 'grandTotal' => number_format($this->getPaymentMethodInstance()->getCheckoutTotal(), 2, '.', ''), ], ], ]; @@ -51,30 +55,19 @@ public function getConfig() return $tpay->isAvailable() ? $config : []; } - /** - * @param string $name - * - * @return string - */ - public function generateURL($name) + public function generateURL(string $name): string { return $this->assetRepository->createAsset($name)->getUrl(); } - /** @return null|string */ - public function showChannels() + public function showChannels(): ?string { $script = 'tpaycom_magento2basic::js/render_channels.js'; return $this->createScript($script); } - /** - * @param string $script - * - * @return string - */ - public function createScript($script) + public function createScript(string $script): string { return " "; } - /** @return null|string */ - public function getTerms() + public function getTerms(): ?string { return $this->getPaymentMethodInstance()->getTermsURL(); } - /** - * @param string $css - * - * @return string - */ - public function createCSS($css) + public function createCSS(string $css): string { return "generateURL($css)}\">"; } diff --git a/Model/TransactionModel.php b/Model/TransactionModel.php deleted file mode 100644 index 1d0efe0..0000000 --- a/Model/TransactionModel.php +++ /dev/null @@ -1,25 +0,0 @@ -trApiKey = $apiKey; - $this->trApiPass = $apiPassword; - $this->merchantId = $merchantId; - $this->merchantSecret = $merchantSecret; - parent::__construct(); - } -} diff --git a/Service/TpayService.php b/Service/TpayService.php index de77619..6364ca6 100644 --- a/Service/TpayService.php +++ b/Service/TpayService.php @@ -1,13 +1,15 @@ orderRepository->getByIncrementId($orderId); $order->setTotalDue($order->getGrandTotal()) @@ -85,14 +74,8 @@ public function addCommentToHistory($orderId, $comment) $order->save(); } - /** - * Return payment data - * - * @param int $orderId - * - * @return OrderPaymentInterface - */ - public function getPayment($orderId) + /** Return payment data */ + public function getPayment(string $orderId): OrderPaymentInterface { /** @var Order $order */ $order = $this->orderRepository->getByIncrementId($orderId); @@ -102,21 +85,19 @@ public function getPayment($orderId) /** * Validate order and set appropriate state - * - * @param int $orderId - * @param array $validParams - * @param TpayInterface $tpayModel - * - * @return bool|Order + * @return bool|OrderInterface + * @throws \Exception */ - public function SetOrderStatus($orderId, array $validParams, $tpayModel) + public function SetOrderStatus(string $orderId, array $validParams, TpayInterface $tpayModel) { $order = $this->getOrderById($orderId); + if (!$order->getId()) { return false; } + $sendNewInvoiceMail = (bool) $tpayModel->getInvoiceSendMail(); - $orderAmount = (float) number_format($order->getGrandTotal(), 2, '.', ''); + $orderAmount = (float) number_format((float) $order->getGrandTotal(), 2, '.', ''); $trStatus = $validParams['tr_status']; $emailNotify = false; @@ -124,7 +105,7 @@ public function SetOrderStatus($orderId, array $validParams, $tpayModel) 'TRUE' === $trStatus && ((float) number_format($validParams['tr_paid'], 2, '.', '') === $orderAmount) ) { - if (Order::STATE_PROCESSING != $order->getState()) { + if (Order::STATE_PROCESSING !== $order->getState()) { $emailNotify = true; } $status = Order::STATE_PROCESSING; @@ -135,7 +116,7 @@ public function SetOrderStatus($orderId, array $validParams, $tpayModel) return $order; } else { - if (Order::STATE_HOLDED != $order->getState()) { + if (Order::STATE_HOLDED !== $order->getState()) { $emailNotify = true; } $comment = __('The order has been holded: ').'
'.$this->getTransactionDesc($validParams); @@ -147,11 +128,8 @@ public function SetOrderStatus($orderId, array $validParams, $tpayModel) } $order->setStatus($status)->setState($status)->save(); if ($sendNewInvoiceMail) { - /** @var Invoice $invoice */ foreach ($order->getInvoiceCollection() as $invoice) { - /** @var int $invoiceId */ $invoiceId = $invoice->getId(); - $this->invoiceService->notify($invoiceId); } } @@ -159,23 +137,14 @@ public function SetOrderStatus($orderId, array $validParams, $tpayModel) return $order; } - /** - * Get Order object by orderId - * - * @param int $orderId - * - * @return Order - */ - public function getOrderById($orderId) + /** Get Order object by orderId */ + public function getOrderById(string $orderId): OrderInterface { return $this->orderRepository->getByIncrementId($orderId); } /** * Get description for transaction - * - * @param array $validParams - * * @return bool|string */ protected function getTransactionDesc(array $validParams) @@ -191,7 +160,7 @@ protected function getTransactionDesc(array $validParams) if ('CHARGEBACK' === $status) { $transactionDesc .= __('Transaction has been refunded'); } - if (isset($validParams['test_mode'])) { + if (array_key_exists('test_mode', $validParams)) { $transactionDesc .= ' TEST '; } @@ -200,18 +169,16 @@ protected function getTransactionDesc(array $validParams) /** * Registers capture notification. - * - * @param Payment $payment * @param float|string $amount - * @param array $validParams * @param bool|int $skipFraudDetection */ private function registerCaptureNotificationTpay( OrderPaymentInterface $payment, $amount, - $validParams, + array $validParams, $skipFraudDetection = false ) { + // @var $payment Payment $payment->setTransactionId( $this->transactionManager->generateTransactionId( $payment, diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 3ca7725..6e0e8a4 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -78,6 +78,14 @@ Leave empty for no limit validate-number + + + validate-length maximum-length-64 + + + + validate-length maximum-length-64 + diff --git a/etc/config.xml b/etc/config.xml index cdd16dc..f5303c0 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -27,8 +27,7 @@ 0 1 PLN - 1 - 0 + 0 diff --git a/etc/csp_whitelist.xml b/etc/csp_whitelist.xml index 6ca4386..4322ea9 100644 --- a/etc/csp_whitelist.xml +++ b/etc/csp_whitelist.xml @@ -6,36 +6,42 @@ https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com diff --git a/etc/module.xml b/etc/module.xml index 9421664..fb59980 100755 --- a/etc/module.xml +++ b/etc/module.xml @@ -9,7 +9,7 @@ */ --> - + diff --git a/i18n/pl_PL.csv b/i18n/pl_PL.csv index ad7fda0..f894662 100644 --- a/i18n/pl_PL.csv +++ b/i18n/pl_PL.csv @@ -22,9 +22,9 @@ "There was an error during your payment.","Wystąpił błąd podczas Twojej płatności." "Thank you for your payment!","Dziękujemy za dokonanie płatności!" "I do accept Tpay service regulations","Akceptuję regulamin Tpay" -"My server use proxy","Mój serwer korzysta z proxy" -"Validate Tpay notifications server IP (recommended)","Sprawdzaj adres IP serwera powiadomień (zalecane)" +"Use sandbox mode (avoid using it in real production store)","Użyj trybu sandox (nie używaj tego na produkcyjnym sklepie)" "BLIK code","Kod BLIK" "Choose a payment method","Wybierz metodę płatności" "Transaction has been refunded","Transakcja została zwrócona" "The order has been holded","Zamówienie zostało wstrzymane" +"Send new invoice email to customer", "Wyślij fakturę na adres email klienta" diff --git a/view/base/web/js/render_channels.js b/view/base/web/js/render_channels.js index 63508f3..e26bd95 100644 --- a/view/base/web/js/render_channels.js +++ b/view/base/web/js/render_channels.js @@ -7,7 +7,8 @@ */ require(['jquery', 'mage/translate'], function ($, $t) { - var payButton = $('#tpaycom_magento2basic_submit'); + var payButton = $('#tpaycom_magento2basic_submit'), + tos = $('#accept_tos'); function getBankTile(groupId, groupName, logoSrc) { return ' + + + + +
+
+ + +
+
+
+
+ +
+
+ +
+
+ + +
+
+ +
+
+
+ + + + + + +
+ + + +
+
+ + + +
+
+
+ +
+
+
+
From be90b228943cd7c8f81b39897e4cb6899abbe3c9 Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 11:11:34 +0100 Subject: [PATCH 06/21] Card --- Model/ApiFacade/CardTransaction/CardOpen.php | 39 +++----------------- 1 file changed, 6 insertions(+), 33 deletions(-) diff --git a/Model/ApiFacade/CardTransaction/CardOpen.php b/Model/ApiFacade/CardTransaction/CardOpen.php index 9f0f628..ac2b8b5 100755 --- a/Model/ApiFacade/CardTransaction/CardOpen.php +++ b/Model/ApiFacade/CardTransaction/CardOpen.php @@ -156,44 +156,17 @@ private function saveCard(string $orderId, bool $saveCard, array $additionalPaym private function handleDataStructure(): array { -// return [ -// 'amount' => (float)$this->tpayPaymentConfig['amount'], -// 'description' => $this->tpayPaymentConfig['description'], -// 'hiddenDescription' => $this->tpayPaymentConfig['crc'], -// 'payer' => [ -// 'email' => $this->tpayPaymentConfig['email'], -// 'name' => $this->tpayPaymentConfig['name'], -// 'phone' => $this->tpayPaymentConfig['phone'], -// 'address' => $this->tpayPaymentConfig['address'], -// 'code' => $this->tpayPaymentConfig['zip'], -// 'city' => $this->tpayPaymentConfig['city'], -// 'country' => $this->tpayPaymentConfig['country'], -// ], -// 'lang' => 'pl', -// 'pay' => [ -// 'groupId' => 103, -// ], -// 'callbacks' => [ -// 'notification' => [ -// "url" => $this->tpayPaymentConfig['result_url'], -// ], -// 'payerUrls' => [ -// "success" => $this->tpayPaymentConfig['return_url'], -// "error" => $this->tpayPaymentConfig['return_error_url'] -// ], -// ] -// ]; return [ 'amount' => (float)$this->tpayPaymentConfig['amount'], 'description' => $this->tpayPaymentConfig['description'], 'hiddenDescription' => $this->tpayPaymentConfig['crc'], 'payer' => [ - 'email' => 'ktpay@inny.com', - 'name' => 'Krzysztof Inny', - 'phone' => '695065220', - 'address' => 'Barwinek 7a', - 'code' => '38-454', - 'city' => 'Tylawa', + 'email' => $this->tpayPaymentConfig['email'], + 'name' => $this->tpayPaymentConfig['name'], + 'phone' => $this->tpayPaymentConfig['phone'], + 'address' => $this->tpayPaymentConfig['address'], + 'code' => $this->tpayPaymentConfig['zip'], + 'city' => $this->tpayPaymentConfig['city'], 'country' => $this->tpayPaymentConfig['country'], ], 'lang' => 'pl', From c772d73489879997c2a75fcac282291fdb06ad8c Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 11:33:53 +0100 Subject: [PATCH 07/21] Cards --- Model/ApiFacade/Refund/RefundCardOriginApi.php | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/Model/ApiFacade/Refund/RefundCardOriginApi.php b/Model/ApiFacade/Refund/RefundCardOriginApi.php index f2f4484..7c4b49b 100755 --- a/Model/ApiFacade/Refund/RefundCardOriginApi.php +++ b/Model/ApiFacade/Refund/RefundCardOriginApi.php @@ -22,21 +22,6 @@ class RefundCardOriginApi extends CardRefunds { public function __construct(TpayInterface $tpay) { -// -// $this->apiKey = 'bda5eda723bf1ae71a82e90a249803d3f852248d'; -// $this->apiPass = 'IhZVgraNcZoWPLgA1yQcGMIzquVWWrWtJ'; -// $this->verificationCode = '6680181602d396e640cb091ea5418171'; -// $this->keyRsa = 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0NCk1JR2ZNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0R05BRENCaVFLQmdRQ2NLRTVZNU1Wemd5a1Z5ODNMS1NTTFlEMEVrU2xadTRVZm1STS8NCmM5L0NtMENuVDM2ekU0L2dMRzBSYzQwODRHNmIzU3l5NVpvZ1kwQXFOVU5vUEptUUZGVyswdXJacU8yNFRCQkxCcU10TTVYSllDaVQNCmVpNkx3RUIyNnpPOFZocW9SK0tiRS92K1l1YlFhNGQ0cWtHU0IzeHBhSUJncllrT2o0aFJDOXk0WXdJREFRQUINCi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ=='; -// $this->hashType = 'sha512'; - - -// $this->tpay = $tpay; -// $this->apiKey = $tpay->getApiPassword(); -// $this->apiPass = $tpay->getApiKey(); -// $this->verificationCode = $tpay->getVerificationCode(); -// $this->keyRsa = $tpay->getRSAKey(); -// $this->hashType = $tpay->getHashType(); - Util::$loggingEnabled = false; $this->cardApiKey = $tpay->getCardApiKey(); $this->cardApiPass = $tpay->getCardApiPassword(); @@ -49,7 +34,6 @@ public function __construct(TpayInterface $tpay) public function makeCardRefund($payment, $amount, $currency = '985') { -// $tpayApi = new CardRefundModel($this->apiPass, $this->apiKey, $this->verificationCode, $this->keyRsa, $this->hashType); $transactionId = $payment->getParentTransactionId(); $this->setAmount($amount)->setCurrency($currency); $result = $this->refund($transactionId, __('Zwrot do zamówienia ') . $payment->getOrder()->getRealOrderId()); From d5ee4506d23560d64e7fe8ee16497599ce6e7386 Mon Sep 17 00:00:00 2001 From: kGablo Date: Tue, 28 Nov 2023 08:39:57 +0100 Subject: [PATCH 08/21] =?UTF-8?q?DX-161=20Stworzenie=20implementacji=20int?= =?UTF-8?q?erface=20p=C5=82atno=C5=9Bci=20Tpay=20dla=20Origin=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Api/Sales/OrderRepositoryInterface.php | 12 +- Api/TpayInterface.php | 133 ++++------- Controller/Tpaycom.php | 60 ----- Controller/tpay/Create.php | 120 +++++----- Controller/tpay/Error.php | 2 + Controller/tpay/Notification.php | 90 +++----- Controller/tpay/Redirect.php | 13 +- Controller/tpay/Refund.php | 96 -------- Controller/tpay/Success.php | 2 + Model/ApiFacade/OpenApi.php | 82 +++++++ Model/ApiFacade/Refund/RefundApiFacade.php | 62 +++++ Model/ApiFacade/Refund/RefundOriginApi.php | 60 +++++ .../Transaction/TransactionApiFacade.php | 67 ++++++ .../Transaction/TransactionOriginApi.php | 39 ++++ Model/NotificationModel.php | 19 -- Model/RefundModel.php | 23 -- Model/Sales/OrderRepository.php | 4 +- Model/Tpay.php | 215 +++++++----------- Model/TpayConfigProvider.php | 35 +-- Model/TransactionModel.php | 25 -- Service/TpayService.php | 73 ++---- etc/adminhtml/system.xml | 8 + etc/config.xml | 3 +- etc/csp_whitelist.xml | 6 + etc/module.xml | 2 +- i18n/pl_PL.csv | 4 +- view/base/web/js/render_channels.js | 63 ++++- .../payment/method-renderer/tpay-method.js | 5 +- .../web/template/payment/tpay-form.html | 4 +- 29 files changed, 652 insertions(+), 675 deletions(-) delete mode 100644 Controller/Tpaycom.php delete mode 100644 Controller/tpay/Refund.php create mode 100755 Model/ApiFacade/OpenApi.php create mode 100755 Model/ApiFacade/Refund/RefundApiFacade.php create mode 100755 Model/ApiFacade/Refund/RefundOriginApi.php create mode 100755 Model/ApiFacade/Transaction/TransactionApiFacade.php create mode 100755 Model/ApiFacade/Transaction/TransactionOriginApi.php delete mode 100644 Model/NotificationModel.php delete mode 100644 Model/RefundModel.php delete mode 100644 Model/TransactionModel.php diff --git a/Api/Sales/OrderRepositoryInterface.php b/Api/Sales/OrderRepositoryInterface.php index c9ef6e3..cda6705 100644 --- a/Api/Sales/OrderRepositoryInterface.php +++ b/Api/Sales/OrderRepositoryInterface.php @@ -1,17 +1,13 @@ _customerSession = $customerSession; - $this->_checkoutSession = $checkoutSession; - $this->_orderFactory = $orderFactory; - $this->_model = $model; - $this->localeResolver = $localeResolver; - $this->objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - parent::__construct($context); - - $this->_model->setCustomerID($this->_customerSession->getCustomerId()); - } - - protected function getDotAmount() - { - return $this->getFormatAmount($this->_checkoutSession->getLastRealOrder()->getGrandTotal()); - } -} diff --git a/Controller/tpay/Create.php b/Controller/tpay/Create.php index 434772f..ee6da94 100644 --- a/Controller/tpay/Create.php +++ b/Controller/tpay/Create.php @@ -1,17 +1,27 @@ tpay = $tpayModel; - $this->transactionFactory = $transactionModelFactory; $this->tpayService = $tpayService; $this->checkoutSession = $checkoutSession; Util::$loggingEnabled = false; @@ -45,53 +51,45 @@ public function __construct( parent::__construct($context); } + /** {@inheritdoc} */ public function execute() { - /** @var int $orderId */ $orderId = $this->checkoutSession->getLastRealOrderId(); - if ($orderId) { - /** @var DataObject $payment */ $payment = $this->tpayService->getPayment($orderId); - - /** @var array $paymentData */ $paymentData = $payment->getData(); - - $this->transaction = $this->transactionFactory->create( - [ - 'apiPassword' => $this->tpay->getApiPassword(), - 'apiKey' => $this->tpay->getApiKey(), - 'merchantId' => $this->tpay->getMerchantId(), - 'merchantSecret' => $this->tpay->getSecurityCode(), - ] - ); + $this->transaction = new TransactionApiFacade($this->tpay); $additionalPaymentInformation = $paymentData['additional_information']; - /** @var array $transaction */ $transaction = $this->prepareTransaction($orderId, $additionalPaymentInformation); if (!isset($transaction['title'], $transaction['url'])) { return $this->_redirect('magento2basic/tpay/error'); } - $this->tpayService->addCommentToHistory($orderId, 'Transaction title '.$transaction['title']); + + $this->handleOpenApiTrId($paymentData, $transaction); + + $this->tpayService->addCommentToHistory($orderId, 'Transaction title ' . $transaction['title']); $transactionUrl = $transaction['url']; - if (true === $this->tpay->redirectToChannel()) { + + if ($this->tpay->redirectToChannel() === true) { $transactionUrl = str_replace('gtitle', 'title', $transactionUrl); } - $this->tpayService->addCommentToHistory($orderId, 'Transaction link '.$transactionUrl); + + $this->tpayService->addCommentToHistory($orderId, 'Transaction link ' . $transactionUrl); $paymentData['additional_information']['transaction_url'] = $transactionUrl; $payment->setData($paymentData)->save(); - if (6 === strlen($additionalPaymentInformation['blik_code']) - && $this->tpay->checkBlikLevel0Settings() - ) { + if (strlen($additionalPaymentInformation['blik_code']) === 6 && $this->tpay->checkBlikLevel0Settings()) { + if (true === $this->transaction->isOpenApiUse()) { + return $this->_redirect('magento2basic/tpay/success'); + } $result = $this->blikPay($transaction['title'], $additionalPaymentInformation['blik_code']); $this->checkoutSession->unsQuoteId(); + if (!$result) { - $this->tpayService->addCommentToHistory( - $orderId, - 'User has typed wrong blik code and has been redirected to transaction panel in order to finish payment' - ); + $this->tpayService->addCommentToHistory($orderId, + 'User has typed wrong blik code and has been redirected to transaction panel in order to finish payment'); return $this->_redirect($transactionUrl); } @@ -105,33 +103,47 @@ public function execute() /** * Send BLIK code for transaction id - * * @param string $blikTransactionId * @param string $blikCode - * - * @return bool */ - protected function blikPay($blikTransactionId, $blikCode) + protected function blikPay($blikTransactionId, $blikCode): bool { - /** @var array $apiResult */ $apiResult = $this->transaction->blik($blikTransactionId, $blikCode); - return isset($apiResult['result']) && 1 === $apiResult['result']; + return isset($apiResult['result']) && $apiResult['result'] === 1; } - /** - * @param mixed $orderId - * @param array{blik_code: string, group: int|string} $additionalPaymentInformation - */ private function prepareTransaction($orderId, array $additionalPaymentInformation) { $data = $this->tpay->getTpayFormData($orderId); - if (6 === strlen($additionalPaymentInformation['blik_code'])) { - $data['group'] = TransactionModel::BLIK_CHANNEL; + + if (strlen($additionalPaymentInformation['blik_code']) === 6) { + $data['group'] = TransactionOriginApi::BLIK_CHANNEL; + $this->handleBlikData($data, $additionalPaymentInformation['blik_code']); } else { - $data['group'] = (int) $additionalPaymentInformation['group']; + $data['group'] = (int)$additionalPaymentInformation['group']; + + if ($this->tpay->redirectToChannel()) { + $data['direct'] = 1; + } } return $this->transaction->create($data); } + + private function handleBlikData(array &$data, string $blikCode) + { + if ($this->transaction->isOpenApiUse() && $this->tpay->checkBlikLevel0Settings()) { + $data['blikPaymentData'] = [ + 'blikToken' => $blikCode + ]; + } + } + + private function handleOpenApiTrId(array &$paymentData, array $transaction) + { + if (isset($transaction['transactionId'])) { + $paymentData['additional_information']['transaction_id'] = $transaction['transactionId']; + } + } } diff --git a/Controller/tpay/Error.php b/Controller/tpay/Error.php index 1772aad..e7dd0c1 100644 --- a/Controller/tpay/Error.php +++ b/Controller/tpay/Error.php @@ -1,5 +1,7 @@ tpay = $tpayModel; $this->remoteAddress = $remoteAddress; - $this->notificationFactory = $notificationModelFactory; $this->tpayService = $tpayService; Util::$loggingEnabled = false; parent::__construct($context); } - /** @return bool */ public function execute() { try { - $id = $this->tpay->getMerchantId(); $code = $this->tpay->getSecurityCode(); - $checkServer = $this->tpay->getCheckTpayIP(); - $checkProxy = $this->tpay->getCheckProxy(); - $forwardedIP = null; - $this->NotificationHandler = $this->notificationFactory->create( - [ - 'merchantId' => $id, - 'merchantSecret' => $code, - ] - ); - if (false === $checkServer) { - $this->NotificationHandler->disableValidationServerIP(); - } - if (true === $checkProxy) { - $this->NotificationHandler->enableForwardedIPValidation(); - } - - /** @var array $validParams */ - $validParams = $this->NotificationHandler->checkPayment(''); + $notification = (new JWSVerifiedPaymentNotification($code, !$this->tpay->useSandboxMode()))->getNotification(); + $notification = $notification->getNotificationAssociative(); + $orderId = base64_decode($notification['tr_crc']); - $orderId = base64_decode($validParams['tr_crc']); - if ('PAID' === $validParams['tr_status']) { + if ('PAID' === $notification['tr_status']) { $response = $this->getPaidTransactionResponse($orderId); - return $this - ->getResponse() - ->setStatusCode(Http::STATUS_CODE_200) - ->setContent($response); + return $this->getResponse()->setStatusCode(Http::STATUS_CODE_200)->setContent($response); } - $this->tpayService->SetOrderStatus($orderId, $validParams, $this->tpay); - return $this - ->getResponse() - ->setStatusCode(Http::STATUS_CODE_200) - ->setContent('TRUE'); + $this->tpayService->SetOrderStatus($orderId, $notification, $this->tpay); + + return $this->getResponse()->setStatusCode(Http::STATUS_CODE_200)->setContent('TRUE'); } catch (Exception $e) { - return false; + Util::log('Notification exception', "{$e->getMessage()} in file {$e->getFile()} line: {$e->getLine()} \n\n {$e->getTraceAsString()}"); + + return $this->getResponse()->setStatusCode(Http::STATUS_CODE_500)->setContent('FALSE'); } } /** * Create exception in case CSRF validation failed. * Return null if default exception will suffice. - * - * @return null|InvalidRequestException */ - public function createCsrfValidationException(RequestInterface $request) {} + public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException + { + return null; + } /** * Perform custom request validation. * Return null if default validation is needed. - * - * @return null|bool */ - public function validateForCsrf(RequestInterface $request) + public function validateForCsrf(RequestInterface $request): ?bool { return true; } /** * Check if the order has been canceled and get response to Tpay server. - * - * @param int $orderId - * - * @throws Exception - * * @return string response for Tpay server + * @throws Exception */ - protected function getPaidTransactionResponse($orderId) + protected function getPaidTransactionResponse(string $orderId): string { $order = $this->tpayService->getOrderById($orderId); + if (!$order->getId()) { - throw new Exception('Unable to get order by orderId %s', $orderId); + throw new Exception(sprintf('Unable to get order by orderId %s', $orderId)); } + if (Order::STATE_CANCELED === $order->getState()) { return 'FALSE'; } diff --git a/Controller/tpay/Redirect.php b/Controller/tpay/Redirect.php index c7576bc..e8e3518 100644 --- a/Controller/tpay/Redirect.php +++ b/Controller/tpay/Redirect.php @@ -1,5 +1,7 @@ getRequest()->getParam('uid'); - - /** @var int $orderId */ $orderId = $this->checkoutSession->getLastRealOrderId(); - if (!$orderId || !$uid) { return $this->_redirect('checkout/cart'); } $payment = $this->tpayService->getPayment($orderId); - - /** @var array $paymentData */ $paymentData = $payment->getData(); - $additionalPaymentInfo = $paymentData['additional_information']; if ( - (!isset($additionalPaymentInfo['group']) || (int) $additionalPaymentInfo['group'] < 1) - && (!isset($additionalPaymentInfo['blik_code']) || 6 !== strlen($additionalPaymentInfo['blik_code'])) + (!array_key_exists('group', $additionalPaymentInfo) || (int) $additionalPaymentInfo['group'] < 1) + && (!array_key_exists('blik_code', $additionalPaymentInfo) || 6 !== strlen($additionalPaymentInfo['blik_code'])) ) { return $this->_redirect('checkout/cart'); } diff --git a/Controller/tpay/Refund.php b/Controller/tpay/Refund.php deleted file mode 100644 index dac8236..0000000 --- a/Controller/tpay/Refund.php +++ /dev/null @@ -1,96 +0,0 @@ -apiPassword, $this->apiKey, $this->merchantId, $this->merchantSecret); - - /** @var array{result?: string, err?: int} $apiResult */ - $apiResult = $RefundModel - ->setTransactionID($payment->getParentTransactionId()) - ->refundAny(number_format($amount, 2)); - - if (isset($apiResult['result']) && 1 === (int) $apiResult['result']) { - return true; - } - $errCode = isset($apiResult['err']) ? ' error code: '.$apiResult['err'] : ''; - throw new Exception(__('Payment refunding error. -'.$errCode)); - } - - /** - * @param string $merchantSecret - * - * @return self - */ - public function setMerchantSecret($merchantSecret) - { - $this->merchantSecret = $merchantSecret; - - return $this; - } - - /** - * @param int $merchantId - * - * @return self - */ - public function setMerchantId($merchantId) - { - $this->merchantId = $merchantId; - - return $this; - } - - /** - * @param string $apiPassword - * - * @return self - */ - public function setApiPassword($apiPassword) - { - $this->apiPassword = $apiPassword; - - return $this; - } - - /** - * @param string $apiKey - * - * @return self - */ - public function setApiKey($apiKey) - { - $this->apiKey = $apiKey; - - return $this; - } -} diff --git a/Controller/tpay/Success.php b/Controller/tpay/Success.php index eeb9673..85ff48d 100644 --- a/Controller/tpay/Success.php +++ b/Controller/tpay/Success.php @@ -1,5 +1,7 @@ handleDataStructure($data); + $transaction = $this->Transactions->createTransaction($transactionData); + + return $this->updateRedirectUrl($transaction); + } + + public function makeRefund(InfoInterface $payment, string $amount): array + { + return $this->Transactions->createRefundByTransactionId(['amount' => number_format($amount, 2)], $payment->getAdditionalInformation('transaction_id')); + } + + private function handleDataStructure(array $data): array + { + $paymentData = [ + "amount" => $data['amount'], + "description" => $data['description'], + "hiddenDescription" => $data['crc'], + "payer" => [ + "email" => $data['email'], + "name" => $data['name'], + "phone" => $data['phone'], + "address" => $data['address'], + "code" => $data['zip'], + "city" => $data['city'], + "country" => $data['country'], + ], + "pay" => [ + "groupId" => $data['group'], + ], + "callbacks" => [ + "payerUrls" => [ + "success" => $data['return_url'], + "error" => $data['return_error_url'] + ], + "notification" => [ + "url" => $data['result_url'], + ] + ] + ]; + + if (!empty($data['blikPaymentData'])) { + $paymentData['pay']['blikPaymentData'] = [ + 'blikToken' => $data['blikPaymentData']['blikToken'] + ]; + } + + return $paymentData; + } + + private function updateRedirectUrl(array $transactionData): array + { + $blik0Url = null; + if (!isset($transactionData['transactionPaymentUrl']) && $transactionData['result'] === 'success') { + $blik0Url = 'blik0url'; + } + $transactionData['url'] = $transactionData['transactionPaymentUrl'] ?? $blik0Url; + + return $transactionData; + } +} diff --git a/Model/ApiFacade/Refund/RefundApiFacade.php b/Model/ApiFacade/Refund/RefundApiFacade.php new file mode 100755 index 0000000..7a74bb7 --- /dev/null +++ b/Model/ApiFacade/Refund/RefundApiFacade.php @@ -0,0 +1,62 @@ +originApi = new RefundOriginApi($tpay->getApiPassword(), $tpay->getApiKey(), $tpay->getMerchantId(), $tpay->getSecurityCode(), !$tpay->useSandboxMode()); + $this->createOpenApiInstance($tpay->getClientId(), $tpay->getOpenApiPassword(), !$tpay->useSandboxMode()); + } + + public function makeRefund(InfoInterface $payment, float $amount) + { + if ($payment->getAdditionalInformation('transaction_id')) { + return $this->getCurrentApi()->makeRefund($payment, $amount); + } + + return $this->originApi->makeRefund($payment, $amount); + } + + private function getCurrentApi() + { + return $this->useOpenApi ? $this->openApi : $this->originApi; + } + + private function createOpenApiInstance(string $clientId, string $apiPassword, bool $isProd) + { + try { + $this->openApi = new OpenApi($clientId, $apiPassword, $isProd); + $this->useOpenApi = true; + } catch (Exception $exception) { + $this->openApi = null; + $this->useOpenApi = false; + } + } +} diff --git a/Model/ApiFacade/Refund/RefundOriginApi.php b/Model/ApiFacade/Refund/RefundOriginApi.php new file mode 100755 index 0000000..e8da6d9 --- /dev/null +++ b/Model/ApiFacade/Refund/RefundOriginApi.php @@ -0,0 +1,60 @@ +trApiKey = $apiKey; + $this->trApiPass = $apiPassword; + $this->merchantId = $merchantId; + $this->merchantSecret = $merchantSecret; + parent::__construct(); + if (!$isProd) { + $this->apiURL = 'https://secure.sandbox.tpay.com/api/gw/'; + } + } + + /** + * @param InfoInterface $payment + * @param double $amount + * @return bool + * @throws \Exception + */ + public function makeRefund($payment, $amount) + { + Util::$loggingEnabled = false; + $apiResult = $this->setTransactionID($payment->getParentTransactionId()) + ->refundAny(number_format($amount, 2)); + if (isset($apiResult['result']) && (int)$apiResult['result'] === 1) { + return true; + } else { + $errCode = isset($apiResult['err']) ? ' error code: ' . $apiResult['err'] : ''; + throw new Exception(__('Payment refunding error. -' . $errCode)); + } + } +} diff --git a/Model/ApiFacade/Transaction/TransactionApiFacade.php b/Model/ApiFacade/Transaction/TransactionApiFacade.php new file mode 100755 index 0000000..4a54d53 --- /dev/null +++ b/Model/ApiFacade/Transaction/TransactionApiFacade.php @@ -0,0 +1,67 @@ +originApi = new TransactionOriginApi($tpay->getApiPassword(), $tpay->getApiKey(), $tpay->getMerchantId(), $tpay->getSecurityCode(), !$tpay->useSandboxMode()); + $this->createOpenApiInstance($tpay->getClientId(), $tpay->getOpenApiPassword(), !$tpay->useSandboxMode()); + } + + public function isOpenApiUse() + { + return $this->useOpenApi; + } + + public function create(array $config) + { + return $this->getCurrentApi()->create($config); + } + + public function blik($blikTransactionId, $blikCode) + { + return $this->originApi->blik($blikTransactionId, $blikCode); + } + + private function getCurrentApi() + { + return $this->useOpenApi ? $this->openApi : $this->originApi; + } + + private function createOpenApiInstance(string $clientId, string $apiPassword, bool $isProd) + { + try { + $this->openApi = new OpenApi($clientId, $apiPassword, $isProd); + $this->useOpenApi = true; + } catch (Exception $exception) { + $this->openApi = null; + $this->useOpenApi = false; + } + } +} diff --git a/Model/ApiFacade/Transaction/TransactionOriginApi.php b/Model/ApiFacade/Transaction/TransactionOriginApi.php new file mode 100755 index 0000000..ee548f1 --- /dev/null +++ b/Model/ApiFacade/Transaction/TransactionOriginApi.php @@ -0,0 +1,39 @@ +trApiKey = $apiKey; + $this->trApiPass = $apiPassword; + $this->merchantId = $merchantId; + $this->merchantSecret = $merchantSecret; + parent::__construct(); + if (!$isProd) { + $this->apiURL = 'https://secure.sandbox.tpay.com/api/gw/'; + } + } +} diff --git a/Model/NotificationModel.php b/Model/NotificationModel.php deleted file mode 100644 index 4950018..0000000 --- a/Model/NotificationModel.php +++ /dev/null @@ -1,19 +0,0 @@ -merchantId = $merchantId; - $this->merchantSecret = $merchantSecret; - parent::__construct(); - } -} diff --git a/Model/RefundModel.php b/Model/RefundModel.php deleted file mode 100644 index c5ea883..0000000 --- a/Model/RefundModel.php +++ /dev/null @@ -1,23 +0,0 @@ -trApiKey = $apiKey; - $this->trApiPass = $apiPassword; - $this->merchantId = $merchantId; - $this->merchantSecret = $merchantSecret; - parent::__construct(); - } -} diff --git a/Model/Sales/OrderRepository.php b/Model/Sales/OrderRepository.php index 6bc3b3a..f7a6832 100644 --- a/Model/Sales/OrderRepository.php +++ b/Model/Sales/OrderRepository.php @@ -1,5 +1,7 @@ */ protected $availableCurrencyCodes = ['PLN']; - - /** @var string */ protected $redirectURL = 'https://secure.tpay.com'; - - /** @var string */ protected $termsURL = 'https://secure.tpay.com/regulamin.pdf'; /** * Min. order amount for BLIK level 0 - * * @var float */ protected $minAmountBlik = 0.01; @@ -73,33 +56,29 @@ class Tpay extends AbstractMethod implements TpayInterface /** @var Escaper */ protected $escaper; - /** @var Refund */ - protected $refund; - /** @var StoreManager */ protected $storeManager; public function __construct( - Context $context, - Registry $registry, + Context $context, + Registry $registry, ExtensionAttributesFactory $extensionFactory, - AttributeValueFactory $customAttributeFactory, - Data $paymentData, - ScopeConfigInterface $scopeConfig, - Logger $logger, - UrlInterface $urlBuilder, - Session $checkoutSession, - OrderRepositoryInterface $orderRepository, - Refund $refund, - Escaper $escaper, - StoreManager $storeManager, - $data = [] - ) { + AttributeValueFactory $customAttributeFactory, + Data $paymentData, + ScopeConfigInterface $scopeConfig, + Logger $logger, + UrlInterface $urlBuilder, + Session $checkoutSession, + OrderRepositoryInterface $orderRepository, + Escaper $escaper, + StoreManager $storeManager, + $data = [] + ) + { $this->urlBuilder = $urlBuilder; $this->escaper = $escaper; $this->checkoutSession = $checkoutSession; $this->orderRepository = $orderRepository; - $this->refund = $refund; $this->storeManager = $storeManager; parent::__construct( @@ -116,12 +95,12 @@ public function __construct( ); } - public function getRedirectURL() + public function getRedirectURL(): string { return $this->redirectURL; } - public function checkBlikLevel0Settings() + public function checkBlikLevel0Settings(): bool { if (!$this->getBlikLevelZeroStatus() || !$this->checkBlikAmount()) { return false; @@ -134,55 +113,58 @@ public function checkBlikLevel0Settings() return !(empty($apiKey) || strlen($apiKey) < 8 || empty($apiPassword) || strlen($apiPassword) < 4); } - /** @return bool */ - public function getInstallmentsAmountValid() + public function getInstallmentsAmountValid(): bool { $amount = $this->getCheckoutTotal(); return $amount > 300 && $amount < 9259; } - public function getBlikLevelZeroStatus() + public function getBlikLevelZeroStatus(): bool { - return (bool) $this->getConfigData('blik_level_zero'); + return (bool)$this->getConfigData('blik_level_zero'); } - public function getApiKey() + public function getApiKey(): string { return $this->getConfigData('api_key_tpay'); } - public function getApiPassword() + public function getApiPassword(): string { return $this->getConfigData('api_password'); } - public function getInvoiceSendMail() + public function getInvoiceSendMail(): string { return $this->getConfigData('send_invoice_email'); } - public function getTermsURL() + public function getTermsURL(): string { return $this->termsURL; } - public function getTpayFormData($orderId = null) + /** {@inheritdoc} */ + public function getOpenApiPassword() + { + return $this->getConfigData('open_api_password'); + } + + public function getTpayFormData(?string $orderId = null): array { $order = $this->getOrder($orderId); $billingAddress = $order->getBillingAddress(); - $amount = number_format($order->getGrandTotal(), 2, '.', ''); + $amount = number_format((float)$order->getGrandTotal(), 2, '.', ''); $crc = base64_encode($orderId); - $name = $billingAddress->getData('firstname').' '.$billingAddress->getData('lastname'); - - /** @var string $phone */ + $name = $billingAddress->getData('firstname') . ' ' . $billingAddress->getData('lastname'); $phone = $billingAddress->getData('telephone'); return [ 'email' => $this->escaper->escapeHtml($order->getCustomerEmail()), 'name' => $this->escaper->escapeHtml($name), 'amount' => $amount, - 'description' => 'Zamówienie '.$orderId, + 'description' => 'Zamówienie ' . $orderId, 'crc' => $crc, 'address' => $this->escaper->escapeHtml($order->getBillingAddress()->getData('street')), 'city' => $this->escaper->escapeHtml($order->getBillingAddress()->getData('city')), @@ -193,56 +175,53 @@ public function getTpayFormData($orderId = null) 'return_url' => $this->urlBuilder->getUrl('magento2basic/tpay/success'), 'phone' => $phone, 'online' => $this->onlyOnlineChannels() ? 1 : 0, - 'module' => 'Magento '.$this->getMagentoVersion(), + 'module' => 'Magento ' . $this->getMagentoVersion(), ]; } - public function getMerchantId() + public function getMerchantId(): int { - return (int) $this->getConfigData('merchant_id'); + return (int)$this->getConfigData('merchant_id'); } - public function getSecurityCode() + /** {@inheritdoc} */ + public function getClientId() { - return $this->getConfigData('security_code'); + return $this->getConfigData('client_id'); } - public function onlyOnlineChannels() + public function getSecurityCode(): string { - return (bool) $this->getConfigData('show_payment_channels_online'); + return $this->getConfigData('security_code'); } - public function redirectToChannel() + public function onlyOnlineChannels(): bool { - return (bool) $this->getConfigData('redirect_directly_to_channel'); + return (bool)$this->getConfigData('show_payment_channels_online'); } - public function getCheckProxy() + public function redirectToChannel(): bool { - return (bool) $this->getConfigData('check_proxy'); + return (bool)$this->getConfigData('redirect_directly_to_channel'); } - public function getCheckTpayIP() + public function useSandboxMode(): bool { - return (bool) $this->getConfigData('check_server'); + return (bool)$this->getConfigData('use_sandbox'); } - public function getPaymentRedirectUrl() + public function getPaymentRedirectUrl(): string { - return $this->urlBuilder->getUrl('magento2basic/tpay/redirect', ['uid' => time().uniqid(true)]); + return $this->urlBuilder->getUrl('magento2basic/tpay/redirect', ['uid' => time() . uniqid('', true)]); } /** * {@inheritDoc} - * * Check that tpay.com payments should be available. */ - public function isAvailable(CartInterface $quote = null) + public function isAvailable(?CartInterface $quote = null) { - /** @var float|int $minAmount */ $minAmount = $this->getConfigData('min_order_total'); - - /** @var float|int $maxAmount */ $maxAmount = $this->getConfigData('max_order_total'); if ( @@ -263,22 +242,20 @@ public function isAvailable(CartInterface $quote = null) public function assignData(DataObject $data) { - /** @var array $additionalData */ $additionalData = $data->getData('additional_data'); - $info = $this->getInfoInstance(); $info->setAdditionalInformation( static::CHANNEL, - isset($additionalData[static::CHANNEL]) ? $additionalData[static::CHANNEL] : '' + array_key_exists(static::CHANNEL, $additionalData) ? $additionalData[static::CHANNEL] : '' ); $info->setAdditionalInformation( static::BLIK_CODE, - isset($additionalData[static::BLIK_CODE]) ? $additionalData[static::BLIK_CODE] : '' + array_key_exists(static::BLIK_CODE, $additionalData) ? $additionalData[static::BLIK_CODE] : '' ); - if (isset($additionalData[static::TERMS_ACCEPT]) && 1 === $additionalData[static::TERMS_ACCEPT]) { + if (array_key_exists(static::TERMS_ACCEPT, $additionalData) && 1 === $additionalData[static::TERMS_ACCEPT]) { $info->setAdditionalInformation( static::TERMS_ACCEPT, 1 @@ -290,21 +267,16 @@ public function assignData(DataObject $data) /** * Payment refund - * + * @param InfoInterface $payment * @param float $amount - * - * @throws \Exception - * * @return $this + * @throws \Exception */ public function refund(InfoInterface $payment, $amount) { - $this->refund - ->setApiKey($this->getApiKey()) - ->setApiPassword($this->getApiPassword()) - ->setMerchantId($this->getMerchantId()) - ->setMerchantSecret($this->getSecurityCode()); - $refundResult = $this->refund->makeRefund($payment, $amount); + $refundService = new RefundApiFacade($this); + + $refundResult = $refundService->makeRefund($payment, (float)$amount); try { if ($refundResult) { $payment @@ -322,70 +294,51 @@ public function refund(InfoInterface $payment, $amount) return $this; } - public function getConfigData($field, $storeId = null) - { - if (is_null($storeId)) { - $storeId = $this->storeManager->getStore()->getId(); - } - - return parent::getConfigData($field, $storeId); - } - - /** - * Check that the BLIK should be available for order/quote amount - * - * @return bool - */ - protected function checkBlikAmount() - { - return (bool) ($this->getCheckoutTotal() >= $this->minAmountBlik); - } - /** @return float current cart total */ - protected function getCheckoutTotal() + public function getCheckoutTotal() { - $amount = $this->getCheckout()->getQuote()->getBaseGrandTotal(); + $amount = (float)$this->getCheckout()->getQuote()->getBaseGrandTotal(); if (!$amount) { - /** @var int $orderId */ $orderId = $this->getCheckout()->getLastRealOrderId(); - $order = $this->orderRepository->getByIncrementId($orderId); $amount = $order->getGrandTotal(); } - return number_format($amount, 2, '.', ''); + return $amount; + } + + public function getConfigData($field, $storeId = null) + { + if (null === $storeId) { + $storeId = $this->storeManager->getStore()->getId(); + } + + return parent::getConfigData($field, $storeId); } - /** @return Session */ - protected function getCheckout() + /** Check that the BLIK should be available for order/quote amount */ + protected function checkBlikAmount(): bool + { + return (bool)($this->getCheckoutTotal() >= $this->minAmountBlik); + } + + protected function getCheckout(): Session { return $this->checkoutSession; } - /** - * @param int $orderId - * - * @return \Magento\Sales\Api\Data\OrderInterface - */ - protected function getOrder($orderId = null) + protected function getOrder(?string $orderId = null): \Magento\Sales\Api\Data\OrderInterface { if (null === $orderId) { - /** @var int $orderId */ $orderId = $this->getCheckout()->getLastRealOrderId(); } return $this->orderRepository->getByIncrementId($orderId); } - /** - * Availability for currency - * - * @param string $currencyCode - * - * @return bool - */ - protected function isAvailableForCurrency($currencyCode) + /** Availability for currency */ + protected function isAvailableForCurrency(string $currencyCode): bool { return !(!in_array($currencyCode, $this->availableCurrencyCodes)); } @@ -393,8 +346,6 @@ protected function isAvailableForCurrency($currencyCode) private function getMagentoVersion() { $objectManager = ObjectManager::getInstance(); - - /** @var ProductMetadataInterface $productMetadata */ $productMetadata = $objectManager->get('Magento\Framework\App\ProductMetadataInterface'); return $productMetadata->getVersion(); diff --git a/Model/TpayConfigProvider.php b/Model/TpayConfigProvider.php index b051ba1..bc8dab2 100644 --- a/Model/TpayConfigProvider.php +++ b/Model/TpayConfigProvider.php @@ -1,5 +1,7 @@ $this->createCSS('tpaycom_magento2basic::css/tpay.css'), 'blikStatus' => $this->getPaymentMethodInstance()->checkBlikLevel0Settings(), 'onlyOnlineChannels' => $this->getPaymentMethodInstance()->onlyOnlineChannels(), - 'getBlikChannelID' => TransactionModel::BLIK_CHANNEL, - 'isInstallmentsAmountValid' => $this->getPaymentMethodInstance()->getInstallmentsAmountValid(), + 'getBlikChannelID' => TransactionOriginApi::BLIK_CHANNEL, + 'useSandbox' => $tpay->useSandboxMode(), + 'grandTotal' => number_format($this->getPaymentMethodInstance()->getCheckoutTotal(), 2, '.', ''), ], ], ]; @@ -51,30 +55,19 @@ public function getConfig() return $tpay->isAvailable() ? $config : []; } - /** - * @param string $name - * - * @return string - */ - public function generateURL($name) + public function generateURL(string $name): string { return $this->assetRepository->createAsset($name)->getUrl(); } - /** @return null|string */ - public function showChannels() + public function showChannels(): ?string { $script = 'tpaycom_magento2basic::js/render_channels.js'; return $this->createScript($script); } - /** - * @param string $script - * - * @return string - */ - public function createScript($script) + public function createScript(string $script): string { return " "; } - /** @return null|string */ - public function getTerms() + public function getTerms(): ?string { return $this->getPaymentMethodInstance()->getTermsURL(); } - /** - * @param string $css - * - * @return string - */ - public function createCSS($css) + public function createCSS(string $css): string { return "generateURL($css)}\">"; } diff --git a/Model/TransactionModel.php b/Model/TransactionModel.php deleted file mode 100644 index 1d0efe0..0000000 --- a/Model/TransactionModel.php +++ /dev/null @@ -1,25 +0,0 @@ -trApiKey = $apiKey; - $this->trApiPass = $apiPassword; - $this->merchantId = $merchantId; - $this->merchantSecret = $merchantSecret; - parent::__construct(); - } -} diff --git a/Service/TpayService.php b/Service/TpayService.php index de77619..6364ca6 100644 --- a/Service/TpayService.php +++ b/Service/TpayService.php @@ -1,13 +1,15 @@ orderRepository->getByIncrementId($orderId); $order->setTotalDue($order->getGrandTotal()) @@ -85,14 +74,8 @@ public function addCommentToHistory($orderId, $comment) $order->save(); } - /** - * Return payment data - * - * @param int $orderId - * - * @return OrderPaymentInterface - */ - public function getPayment($orderId) + /** Return payment data */ + public function getPayment(string $orderId): OrderPaymentInterface { /** @var Order $order */ $order = $this->orderRepository->getByIncrementId($orderId); @@ -102,21 +85,19 @@ public function getPayment($orderId) /** * Validate order and set appropriate state - * - * @param int $orderId - * @param array $validParams - * @param TpayInterface $tpayModel - * - * @return bool|Order + * @return bool|OrderInterface + * @throws \Exception */ - public function SetOrderStatus($orderId, array $validParams, $tpayModel) + public function SetOrderStatus(string $orderId, array $validParams, TpayInterface $tpayModel) { $order = $this->getOrderById($orderId); + if (!$order->getId()) { return false; } + $sendNewInvoiceMail = (bool) $tpayModel->getInvoiceSendMail(); - $orderAmount = (float) number_format($order->getGrandTotal(), 2, '.', ''); + $orderAmount = (float) number_format((float) $order->getGrandTotal(), 2, '.', ''); $trStatus = $validParams['tr_status']; $emailNotify = false; @@ -124,7 +105,7 @@ public function SetOrderStatus($orderId, array $validParams, $tpayModel) 'TRUE' === $trStatus && ((float) number_format($validParams['tr_paid'], 2, '.', '') === $orderAmount) ) { - if (Order::STATE_PROCESSING != $order->getState()) { + if (Order::STATE_PROCESSING !== $order->getState()) { $emailNotify = true; } $status = Order::STATE_PROCESSING; @@ -135,7 +116,7 @@ public function SetOrderStatus($orderId, array $validParams, $tpayModel) return $order; } else { - if (Order::STATE_HOLDED != $order->getState()) { + if (Order::STATE_HOLDED !== $order->getState()) { $emailNotify = true; } $comment = __('The order has been holded: ').'
'.$this->getTransactionDesc($validParams); @@ -147,11 +128,8 @@ public function SetOrderStatus($orderId, array $validParams, $tpayModel) } $order->setStatus($status)->setState($status)->save(); if ($sendNewInvoiceMail) { - /** @var Invoice $invoice */ foreach ($order->getInvoiceCollection() as $invoice) { - /** @var int $invoiceId */ $invoiceId = $invoice->getId(); - $this->invoiceService->notify($invoiceId); } } @@ -159,23 +137,14 @@ public function SetOrderStatus($orderId, array $validParams, $tpayModel) return $order; } - /** - * Get Order object by orderId - * - * @param int $orderId - * - * @return Order - */ - public function getOrderById($orderId) + /** Get Order object by orderId */ + public function getOrderById(string $orderId): OrderInterface { return $this->orderRepository->getByIncrementId($orderId); } /** * Get description for transaction - * - * @param array $validParams - * * @return bool|string */ protected function getTransactionDesc(array $validParams) @@ -191,7 +160,7 @@ protected function getTransactionDesc(array $validParams) if ('CHARGEBACK' === $status) { $transactionDesc .= __('Transaction has been refunded'); } - if (isset($validParams['test_mode'])) { + if (array_key_exists('test_mode', $validParams)) { $transactionDesc .= ' TEST '; } @@ -200,18 +169,16 @@ protected function getTransactionDesc(array $validParams) /** * Registers capture notification. - * - * @param Payment $payment * @param float|string $amount - * @param array $validParams * @param bool|int $skipFraudDetection */ private function registerCaptureNotificationTpay( OrderPaymentInterface $payment, $amount, - $validParams, + array $validParams, $skipFraudDetection = false ) { + // @var $payment Payment $payment->setTransactionId( $this->transactionManager->generateTransactionId( $payment, diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 3ca7725..6e0e8a4 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -78,6 +78,14 @@ Leave empty for no limit validate-number + + + validate-length maximum-length-64 + + + + validate-length maximum-length-64 + diff --git a/etc/config.xml b/etc/config.xml index cdd16dc..f5303c0 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -27,8 +27,7 @@ 0 1 PLN - 1 - 0 + 0 diff --git a/etc/csp_whitelist.xml b/etc/csp_whitelist.xml index 6ca4386..4322ea9 100644 --- a/etc/csp_whitelist.xml +++ b/etc/csp_whitelist.xml @@ -6,36 +6,42 @@ https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com https://secure.tpay.com + https://secure.sandbox.tpay.com https://tpay.com diff --git a/etc/module.xml b/etc/module.xml index 9421664..fb59980 100755 --- a/etc/module.xml +++ b/etc/module.xml @@ -9,7 +9,7 @@ */ --> - + diff --git a/i18n/pl_PL.csv b/i18n/pl_PL.csv index ad7fda0..f894662 100644 --- a/i18n/pl_PL.csv +++ b/i18n/pl_PL.csv @@ -22,9 +22,9 @@ "There was an error during your payment.","Wystąpił błąd podczas Twojej płatności." "Thank you for your payment!","Dziękujemy za dokonanie płatności!" "I do accept Tpay service regulations","Akceptuję regulamin Tpay" -"My server use proxy","Mój serwer korzysta z proxy" -"Validate Tpay notifications server IP (recommended)","Sprawdzaj adres IP serwera powiadomień (zalecane)" +"Use sandbox mode (avoid using it in real production store)","Użyj trybu sandox (nie używaj tego na produkcyjnym sklepie)" "BLIK code","Kod BLIK" "Choose a payment method","Wybierz metodę płatności" "Transaction has been refunded","Transakcja została zwrócona" "The order has been holded","Zamówienie zostało wstrzymane" +"Send new invoice email to customer", "Wyślij fakturę na adres email klienta" diff --git a/view/base/web/js/render_channels.js b/view/base/web/js/render_channels.js index 63508f3..e26bd95 100644 --- a/view/base/web/js/render_channels.js +++ b/view/base/web/js/render_channels.js @@ -7,7 +7,8 @@ */ require(['jquery', 'mage/translate'], function ($, $t) { - var payButton = $('#tpaycom_magento2basic_submit'); + var payButton = $('#tpaycom_magento2basic_submit'), + tos = $('#accept_tos'); function getBankTile(groupId, groupName, logoSrc) { return ' + + + + +
+
+ + +
+
+
+
+ +
+
+ +
+
+ + +
+
+ +
+
+
+ + + + + + +
+ + + +
+
+ + + +
+
+
+ +
+
+
+
From e162cc27acb6410cdc3a0411e6fd98bd9b4ad3a4 Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 11:11:34 +0100 Subject: [PATCH 13/21] Card --- Model/ApiFacade/CardTransaction/CardOpen.php | 39 +++----------------- 1 file changed, 6 insertions(+), 33 deletions(-) diff --git a/Model/ApiFacade/CardTransaction/CardOpen.php b/Model/ApiFacade/CardTransaction/CardOpen.php index 9f0f628..ac2b8b5 100755 --- a/Model/ApiFacade/CardTransaction/CardOpen.php +++ b/Model/ApiFacade/CardTransaction/CardOpen.php @@ -156,44 +156,17 @@ private function saveCard(string $orderId, bool $saveCard, array $additionalPaym private function handleDataStructure(): array { -// return [ -// 'amount' => (float)$this->tpayPaymentConfig['amount'], -// 'description' => $this->tpayPaymentConfig['description'], -// 'hiddenDescription' => $this->tpayPaymentConfig['crc'], -// 'payer' => [ -// 'email' => $this->tpayPaymentConfig['email'], -// 'name' => $this->tpayPaymentConfig['name'], -// 'phone' => $this->tpayPaymentConfig['phone'], -// 'address' => $this->tpayPaymentConfig['address'], -// 'code' => $this->tpayPaymentConfig['zip'], -// 'city' => $this->tpayPaymentConfig['city'], -// 'country' => $this->tpayPaymentConfig['country'], -// ], -// 'lang' => 'pl', -// 'pay' => [ -// 'groupId' => 103, -// ], -// 'callbacks' => [ -// 'notification' => [ -// "url" => $this->tpayPaymentConfig['result_url'], -// ], -// 'payerUrls' => [ -// "success" => $this->tpayPaymentConfig['return_url'], -// "error" => $this->tpayPaymentConfig['return_error_url'] -// ], -// ] -// ]; return [ 'amount' => (float)$this->tpayPaymentConfig['amount'], 'description' => $this->tpayPaymentConfig['description'], 'hiddenDescription' => $this->tpayPaymentConfig['crc'], 'payer' => [ - 'email' => 'ktpay@inny.com', - 'name' => 'Krzysztof Inny', - 'phone' => '695065220', - 'address' => 'Barwinek 7a', - 'code' => '38-454', - 'city' => 'Tylawa', + 'email' => $this->tpayPaymentConfig['email'], + 'name' => $this->tpayPaymentConfig['name'], + 'phone' => $this->tpayPaymentConfig['phone'], + 'address' => $this->tpayPaymentConfig['address'], + 'code' => $this->tpayPaymentConfig['zip'], + 'city' => $this->tpayPaymentConfig['city'], 'country' => $this->tpayPaymentConfig['country'], ], 'lang' => 'pl', From 93838bc9eb955e4aa2a300762c3d2a122bf65c4e Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 11:33:53 +0100 Subject: [PATCH 14/21] Cards --- Model/ApiFacade/Refund/RefundCardOriginApi.php | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/Model/ApiFacade/Refund/RefundCardOriginApi.php b/Model/ApiFacade/Refund/RefundCardOriginApi.php index f2f4484..7c4b49b 100755 --- a/Model/ApiFacade/Refund/RefundCardOriginApi.php +++ b/Model/ApiFacade/Refund/RefundCardOriginApi.php @@ -22,21 +22,6 @@ class RefundCardOriginApi extends CardRefunds { public function __construct(TpayInterface $tpay) { -// -// $this->apiKey = 'bda5eda723bf1ae71a82e90a249803d3f852248d'; -// $this->apiPass = 'IhZVgraNcZoWPLgA1yQcGMIzquVWWrWtJ'; -// $this->verificationCode = '6680181602d396e640cb091ea5418171'; -// $this->keyRsa = 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0NCk1JR2ZNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0R05BRENCaVFLQmdRQ2NLRTVZNU1Wemd5a1Z5ODNMS1NTTFlEMEVrU2xadTRVZm1STS8NCmM5L0NtMENuVDM2ekU0L2dMRzBSYzQwODRHNmIzU3l5NVpvZ1kwQXFOVU5vUEptUUZGVyswdXJacU8yNFRCQkxCcU10TTVYSllDaVQNCmVpNkx3RUIyNnpPOFZocW9SK0tiRS92K1l1YlFhNGQ0cWtHU0IzeHBhSUJncllrT2o0aFJDOXk0WXdJREFRQUINCi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ=='; -// $this->hashType = 'sha512'; - - -// $this->tpay = $tpay; -// $this->apiKey = $tpay->getApiPassword(); -// $this->apiPass = $tpay->getApiKey(); -// $this->verificationCode = $tpay->getVerificationCode(); -// $this->keyRsa = $tpay->getRSAKey(); -// $this->hashType = $tpay->getHashType(); - Util::$loggingEnabled = false; $this->cardApiKey = $tpay->getCardApiKey(); $this->cardApiPass = $tpay->getCardApiPassword(); @@ -49,7 +34,6 @@ public function __construct(TpayInterface $tpay) public function makeCardRefund($payment, $amount, $currency = '985') { -// $tpayApi = new CardRefundModel($this->apiPass, $this->apiKey, $this->verificationCode, $this->keyRsa, $this->hashType); $transactionId = $payment->getParentTransactionId(); $this->setAmount($amount)->setCurrency($currency); $result = $this->refund($transactionId, __('Zwrot do zamówienia ') . $payment->getOrder()->getRealOrderId()); From 4341c5005d88763b6f4269e3fde4a1beec52dd76 Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 13:03:06 +0100 Subject: [PATCH 15/21] normalized --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 1072a13..dda7500 100755 --- a/composer.json +++ b/composer.json @@ -12,8 +12,8 @@ "require": { "php": ">=7", "magento/product-community-edition": "^2.3", - "tpay-com/tpay-php": "^2.3.6", - "tpay-com/tpay-openapi-php": "^1.3" + "tpay-com/tpay-openapi-php": "^1.3", + "tpay-com/tpay-php": "^2.3.6" }, "autoload": { "psr-4": { From 21d0158c89fc7c53d96eb4fb662f5a46d76e62eb Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 13:06:05 +0100 Subject: [PATCH 16/21] normalized --- Api/TpayInterface.php | 1 - Controller/tpay/Create.php | 40 ++--- Controller/tpay/Notification.php | 14 +- Controller/tpay/Redirect.php | 2 +- .../CardTransaction/CardApiFacade.php | 11 -- Model/ApiFacade/CardTransaction/CardOpen.php | 33 ++-- .../ApiFacade/CardTransaction/CardOrigin.php | 47 ++--- Model/ApiFacade/OpenApi.php | 57 +++--- Model/ApiFacade/Refund/RefundApiFacade.php | 11 -- .../ApiFacade/Refund/RefundCardOriginApi.php | 24 +-- Model/ApiFacade/Refund/RefundOriginApi.php | 18 +- Model/ApiFacade/TpayConfig/ConfigFacade.php | 10 -- Model/ApiFacade/TpayConfig/ConfigOpen.php | 20 +-- Model/ApiFacade/TpayConfig/ConfigOrigin.php | 18 +- .../Transaction/TransactionApiFacade.php | 11 -- .../Transaction/TransactionOriginApi.php | 13 +- Model/Config/Source/HashTypes.php | 2 +- Model/Tpay.php | 83 ++++----- Service/TpayService.php | 163 +++++++++--------- Service/TpayTokensService.php | 7 +- Setup/InstallSchema.php | 6 +- Setup/Uninstall.php | 4 +- Setup/UpgradeSchema.php | 8 +- 23 files changed, 233 insertions(+), 370 deletions(-) diff --git a/Api/TpayInterface.php b/Api/TpayInterface.php index 3485101..f0bc35e 100644 --- a/Api/TpayInterface.php +++ b/Api/TpayInterface.php @@ -58,7 +58,6 @@ public function useSandboxMode(): bool; /** Check if checkout amount is in range of installments payment channel */ public function getInstallmentsAmountValid(): bool; - // KARTY public function getCardApiKey(): ?string; diff --git a/Controller/tpay/Create.php b/Controller/tpay/Create.php index 21a47c5..fd98d71 100644 --- a/Controller/tpay/Create.php +++ b/Controller/tpay/Create.php @@ -1,11 +1,4 @@ tpay = $tpayModel; @@ -51,7 +35,6 @@ public function __construct(Context $context, TpayInterface $tpayModel, TpayServ parent::__construct($context); } - /** {@inheritdoc} */ public function execute() { $orderId = $this->checkoutSession->getLastRealOrderId(); @@ -69,18 +52,18 @@ public function execute() $this->handleOpenApiTrId($paymentData, $transaction); - $this->tpayService->addCommentToHistory($orderId, 'Transaction title ' . $transaction['title']); + $this->tpayService->addCommentToHistory($orderId, 'Transaction title '.$transaction['title']); $transactionUrl = $transaction['url']; - if ($this->tpay->redirectToChannel() === true) { + if (true === $this->tpay->redirectToChannel()) { $transactionUrl = str_replace('gtitle', 'title', $transactionUrl); } - $this->tpayService->addCommentToHistory($orderId, 'Transaction link ' . $transactionUrl); + $this->tpayService->addCommentToHistory($orderId, 'Transaction link '.$transactionUrl); $paymentData['additional_information']['transaction_url'] = $transactionUrl; $payment->setData($paymentData)->save(); - if (strlen($additionalPaymentInformation['blik_code']) === 6 && $this->tpay->checkBlikLevel0Settings()) { + if (6 === strlen($additionalPaymentInformation['blik_code']) && $this->tpay->checkBlikLevel0Settings()) { if (true === $this->transaction->isOpenApiUse()) { return $this->_redirect('magento2basic/tpay/success'); } @@ -88,8 +71,10 @@ public function execute() $this->checkoutSession->unsQuoteId(); if (!$result) { - $this->tpayService->addCommentToHistory($orderId, - 'User has typed wrong blik code and has been redirected to transaction panel in order to finish payment'); + $this->tpayService->addCommentToHistory( + $orderId, + 'User has typed wrong blik code and has been redirected to transaction panel in order to finish payment' + ); return $this->_redirect($transactionUrl); } @@ -103,6 +88,7 @@ public function execute() /** * Send BLIK code for transaction id + * * @param string $blikTransactionId * @param string $blikCode */ @@ -110,18 +96,18 @@ protected function blikPay($blikTransactionId, $blikCode): bool { $apiResult = $this->transaction->blik($blikTransactionId, $blikCode); - return isset($apiResult['result']) && $apiResult['result'] === 1; + return isset($apiResult['result']) && 1 === $apiResult['result']; } private function prepareTransaction($orderId, array $additionalPaymentInformation) { $data = $this->tpay->getTpayFormData($orderId); - if (strlen($additionalPaymentInformation['blik_code']) === 6) { + if (6 === strlen($additionalPaymentInformation['blik_code'])) { $data['group'] = TransactionOriginApi::BLIK_CHANNEL; $this->handleBlikData($data, $additionalPaymentInformation['blik_code']); } else { - $data['group'] = (int)$additionalPaymentInformation['group']; + $data['group'] = (int) $additionalPaymentInformation['group']; if ($this->tpay->redirectToChannel()) { $data['direct'] = 1; @@ -135,7 +121,7 @@ private function handleBlikData(array &$data, string $blikCode) { if ($this->transaction->isOpenApiUse() && $this->tpay->checkBlikLevel0Settings()) { $data['blikPaymentData'] = [ - 'blikToken' => $blikCode + 'blikToken' => $blikCode, ]; } } diff --git a/Controller/tpay/Notification.php b/Controller/tpay/Notification.php index 08967e3..a2e4222 100644 --- a/Controller/tpay/Notification.php +++ b/Controller/tpay/Notification.php @@ -13,9 +13,9 @@ use Magento\Framework\App\Response\Http; use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress; use Magento\Sales\Model\Order; +use Tpay\OriginApi\Utilities\Util; use tpaycom\magento2basic\Api\TpayInterface; use tpaycom\magento2basic\Service\TpayService; -use Tpay\OriginApi\Utilities\Util; use tpaycom\magento2basic\Service\TpayTokensService; use tpaySDK\Webhook\JWSVerifiedPaymentNotification; @@ -30,11 +30,11 @@ class Notification extends Action implements CsrfAwareActionInterface /** @var TpayService */ protected $tpayService; + protected $request; + /** @var TpayTokensService */ private $tokensService; - protected $request; - public function __construct(Context $context, RemoteAddress $remoteAddress, TpayInterface $tpayModel, TpayService $tpayService, TpayTokensService $tokensService) { $this->tpay = $tpayModel; @@ -90,8 +90,10 @@ public function validateForCsrf(RequestInterface $request): ?bool /** * Check if the order has been canceled and get response to Tpay server. - * @return string response for Tpay server + * * @throws Exception + * + * @return string response for Tpay server */ protected function getPaidTransactionResponse(string $orderId): string { @@ -113,9 +115,9 @@ private function saveCard(array $notification, string $orderId) $order = $this->tpayService->getOrderById($orderId); if (isset($notification['card_token']) && !$this->tpay->isCustomerGuest($orderId)) { - $token = $this->tokensService->getWithoutAuthCustomerTokens((int)$order->getCustomerId(), $notification['tr_crc']); + $token = $this->tokensService->getWithoutAuthCustomerTokens((int) $order->getCustomerId(), $notification['tr_crc']); if (!empty($token)) { - $this->tokensService->updateTokenById((int)$token['tokenId'], $notification['card_token']); + $this->tokensService->updateTokenById((int) $token['tokenId'], $notification['card_token']); } } } diff --git a/Controller/tpay/Redirect.php b/Controller/tpay/Redirect.php index d8b80b1..36c6871 100644 --- a/Controller/tpay/Redirect.php +++ b/Controller/tpay/Redirect.php @@ -41,7 +41,7 @@ public function execute() return $this->_redirect('magento2basic/tpay/CardPayment'); } - if ((!array_key_exists(TpayInterface::CHANNEL, $additionalPaymentInfo) || (int)$additionalPaymentInfo[TpayInterface::CHANNEL] < 1) && (!array_key_exists(TpayInterface::BLIK_CODE, $additionalPaymentInfo) || 6 !== strlen($additionalPaymentInfo[TpayInterface::BLIK_CODE]))) { + if ((!array_key_exists(TpayInterface::CHANNEL, $additionalPaymentInfo) || (int) $additionalPaymentInfo[TpayInterface::CHANNEL] < 1) && (!array_key_exists(TpayInterface::BLIK_CODE, $additionalPaymentInfo) || 6 !== strlen($additionalPaymentInfo[TpayInterface::BLIK_CODE]))) { return $this->_redirect('checkout/cart'); } $this->tpayService->setOrderStatePendingPayment($orderId, true); diff --git a/Model/ApiFacade/CardTransaction/CardApiFacade.php b/Model/ApiFacade/CardTransaction/CardApiFacade.php index 2015250..a081af6 100755 --- a/Model/ApiFacade/CardTransaction/CardApiFacade.php +++ b/Model/ApiFacade/CardTransaction/CardApiFacade.php @@ -1,11 +1,4 @@ tpayPaymentConfig = $this->tpay->getTpayFormData($orderId); if (isset($additionalPaymentInformation['card_id']) && false !== $additionalPaymentInformation['card_id'] && $this->tpay->getCardSaveEnabled()) { - $cardId = (int)$additionalPaymentInformation['card_id']; + $cardId = (int) $additionalPaymentInformation['card_id']; return $this->processSavedCardPayment($orderId, $cardId); } @@ -87,9 +77,9 @@ private function processSavedCardPayment(string $orderId, int $cardId): string } if (isset($paymentResult['status']) && 'declined' === $paymentResult['status']) { - $this->tpayService->addCommentToHistory($orderId, 'Failed to pay by saved card, Elavon rejection code: ' . $paymentResult['reason']); + $this->tpayService->addCommentToHistory($orderId, 'Failed to pay by saved card, Elavon rejection code: '.$paymentResult['reason']); } else { - $this->tpayService->addCommentToHistory($orderId, 'Failed to pay by saved card, error: ' . $paymentResult['err_desc']); + $this->tpayService->addCommentToHistory($orderId, 'Failed to pay by saved card, error: '.$paymentResult['err_desc']); } } catch (Exception $e) { return 'magento2basic/tpay/error'; @@ -111,7 +101,7 @@ private function addToPaymentData(string $orderId, string $key, $value) private function processNewCardPayment(string $orderId, array $additionalPaymentInformation): string { - $saveCard = isset($additionalPaymentInformation['card_save']) && $this->tpay->getCardSaveEnabled() ? (bool)$additionalPaymentInformation['card_save'] : false; + $saveCard = isset($additionalPaymentInformation['card_save']) && $this->tpay->getCardSaveEnabled() ? (bool) $additionalPaymentInformation['card_save'] : false; try { $transaction = $this->tpayApi->Transactions->createTransaction($this->handleDataStructure()); $request = [ @@ -124,14 +114,13 @@ private function processNewCardPayment(string $orderId, array $additionalPayment ]; $result = $this->tpayApi->Transactions->createPaymentByTransactionId($request, $transaction['transactionId']); $this->tpayService->setCardOrderStatus($orderId, $this->handleValidParams($result), $this->tpay); - } catch (Exception $e) { return 'magento2basic/tpay/error'; } - if (isset($result['transactionPaymentUrl']) && $result['payments']['status'] === 'pending') { + if (isset($result['transactionPaymentUrl']) && 'pending' === $result['payments']['status']) { $url3ds = $result['transactionPaymentUrl']; - $this->tpayService->addCommentToHistory($orderId, '3DS Transaction link ' . $url3ds); + $this->tpayService->addCommentToHistory($orderId, '3DS Transaction link '.$url3ds); $this->addToPaymentData($orderId, 'transaction_url', $url3ds); $this->saveCard($orderId, $saveCard, $additionalPaymentInformation); @@ -157,7 +146,7 @@ private function saveCard(string $orderId, bool $saveCard, array $additionalPaym private function handleDataStructure(): array { return [ - 'amount' => (float)$this->tpayPaymentConfig['amount'], + 'amount' => (float) $this->tpayPaymentConfig['amount'], 'description' => $this->tpayPaymentConfig['description'], 'hiddenDescription' => $this->tpayPaymentConfig['crc'], 'payer' => [ @@ -175,13 +164,13 @@ private function handleDataStructure(): array ], 'callbacks' => [ 'notification' => [ - "url" => $this->tpayPaymentConfig['result_url'], + 'url' => $this->tpayPaymentConfig['result_url'], ], 'payerUrls' => [ - "success" => $this->tpayPaymentConfig['return_url'], - "error" => $this->tpayPaymentConfig['return_error_url'] + 'success' => $this->tpayPaymentConfig['return_url'], + 'error' => $this->tpayPaymentConfig['return_error_url'], ], - ] + ], ]; } diff --git a/Model/ApiFacade/CardTransaction/CardOrigin.php b/Model/ApiFacade/CardTransaction/CardOrigin.php index c3744f2..a4a5cd7 100755 --- a/Model/ApiFacade/CardTransaction/CardOrigin.php +++ b/Model/ApiFacade/CardTransaction/CardOrigin.php @@ -1,10 +1,4 @@ setModuleName($this->tpayPaymentConfig['module']); if (isset($additionalPaymentInformation['card_id']) && false !== $additionalPaymentInformation['card_id'] && $this->tpay->getCardSaveEnabled()) { - $cardId = (int)$additionalPaymentInformation['card_id']; + $cardId = (int) $additionalPaymentInformation['card_id']; return $this->processSavedCardPayment($orderId, $cardId); } @@ -79,7 +69,7 @@ private function processSavedCardPayment(string $orderId, string $cardId): strin $isValid = false; $token = ''; foreach ($customerTokens as $key => $value) { - if ((int)$value['tokenId'] === $cardId) { + if ((int) $value['tokenId'] === $cardId) { $isValid = true; $token = $value['token']; } @@ -92,7 +82,7 @@ private function processSavedCardPayment(string $orderId, string $cardId): strin $paymentResult = $this->sale($paymentResult['sale_auth'], $token); } - if (1 === (int)$paymentResult['result'] && isset($paymentResult['status']) && 'correct' === $paymentResult['status']) { + if (1 === (int) $paymentResult['result'] && isset($paymentResult['status']) && 'correct' === $paymentResult['status']) { $this->tpayService->setOrderStatus($orderId, $paymentResult, $this->tpay); $this->tpayService->addCommentToHistory($orderId, 'Successful payment by saved card'); @@ -102,12 +92,12 @@ private function processSavedCardPayment(string $orderId, string $cardId): strin if (isset($paymentResult['status']) && 'declined' === $paymentResult['status']) { $this->tpayService->addCommentToHistory( $orderId, - 'Failed to pay by saved card, Elavon rejection code: ' . $paymentResult['reason'] + 'Failed to pay by saved card, Elavon rejection code: '.$paymentResult['reason'] ); } else { $this->tpayService->addCommentToHistory( $orderId, - 'Failed to pay by saved card, error: ' . $paymentResult['err_desc'] + 'Failed to pay by saved card, error: '.$paymentResult['err_desc'] ); } } catch (Exception $e) { @@ -127,8 +117,8 @@ private function trySaleAgain(string $orderId): string $result = $this->registerSale($this->tpayPaymentConfig['name'], $this->tpayPaymentConfig['email'], $this->tpayPaymentConfig['description']); if (isset($result['sale_auth'])) { - $url = 'https://secure.tpay.com/cards?sale_auth=' . $result['sale_auth']; - $this->tpayService->addCommentToHistory($orderId, 'Customer has been redirected to tpay.com transaction panel. Transaction link ' . $url); + $url = 'https://secure.tpay.com/cards?sale_auth='.$result['sale_auth']; + $this->tpayService->addCommentToHistory($orderId, 'Customer has been redirected to tpay.com transaction panel. Transaction link '.$url); $this->addToPaymentData($orderId, 'transaction_url', $url); return $url; @@ -147,7 +137,7 @@ private function addToPaymentData(string $orderId, string $key, $value) private function processNewCardPayment(string $orderId, array $additionalPaymentInformation): string { - $saveCard = isset($additionalPaymentInformation['card_save']) && $this->tpay->getCardSaveEnabled() ? (bool)$additionalPaymentInformation['card_save'] : false; + $saveCard = isset($additionalPaymentInformation['card_save']) && $this->tpay->getCardSaveEnabled() ? (bool) $additionalPaymentInformation['card_save'] : false; if (true === $saveCard) { $this->setOneTimer(false); } @@ -158,7 +148,7 @@ private function processNewCardPayment(string $orderId, array $additionalPayment } if (isset($result['3ds_url'])) { $url3ds = $result['3ds_url']; - $this->tpayService->addCommentToHistory($orderId, '3DS Transaction link ' . $url3ds); + $this->tpayService->addCommentToHistory($orderId, '3DS Transaction link '.$url3ds); $this->addToPaymentData($orderId, 'transaction_url', $url3ds); return $url3ds; @@ -178,7 +168,7 @@ private function processNewCardPayment(string $orderId, array $additionalPayment ); } - return 1 === (int)$result['result'] && isset($result['status']) && 'correct' === $result['status'] ? 'magento2basic/tpay/success' : $this->trySaleAgain($orderId); + return 1 === (int) $result['result'] && isset($result['status']) && 'correct' === $result['status'] ? 'magento2basic/tpay/success' : $this->trySaleAgain($orderId); } private function createNewCardPayment(array $additionalPaymentInformation): array @@ -200,18 +190,17 @@ private function validateNon3dsSign(array $tpayResponse) $localHash = hash( $this->tpay->getHashType(), $testMode - . $tpayResponse['sale_auth'] - . $cliAuth - . $tpayResponse['card'] - . $this->tpayPaymentConfig['currency'] - . $this->tpayPaymentConfig['amount'] - . $tpayResponse['date'] - . $tpayResponse['status'] - . $this->tpay->getVerificationCode() + .$tpayResponse['sale_auth'] + .$cliAuth + .$tpayResponse['card'] + .$this->tpayPaymentConfig['currency'] + .$this->tpayPaymentConfig['amount'] + .$tpayResponse['date'] + .$tpayResponse['status'] + .$this->tpay->getVerificationCode() ); if ($tpayResponse['sign'] !== $localHash) { throw new Exception('Card payment - invalid checksum'); } } } - diff --git a/Model/ApiFacade/OpenApi.php b/Model/ApiFacade/OpenApi.php index df051e6..10157a1 100755 --- a/Model/ApiFacade/OpenApi.php +++ b/Model/ApiFacade/OpenApi.php @@ -1,21 +1,10 @@ $data['amount'], - "description" => $data['description'], - "hiddenDescription" => $data['crc'], - "payer" => [ - "email" => $data['email'], - "name" => $data['name'], - "phone" => $data['phone'], - "address" => $data['address'], - "code" => $data['zip'], - "city" => $data['city'], - "country" => $data['country'], + 'amount' => $data['amount'], + 'description' => $data['description'], + 'hiddenDescription' => $data['crc'], + 'payer' => [ + 'email' => $data['email'], + 'name' => $data['name'], + 'phone' => $data['phone'], + 'address' => $data['address'], + 'code' => $data['zip'], + 'city' => $data['city'], + 'country' => $data['country'], ], - "pay" => [ - "groupId" => $data['group'], + 'pay' => [ + 'groupId' => $data['group'], ], - "callbacks" => [ - "payerUrls" => [ - "success" => $data['return_url'], - "error" => $data['return_error_url'] + 'callbacks' => [ + 'payerUrls' => [ + 'success' => $data['return_url'], + 'error' => $data['return_error_url'], ], - "notification" => [ - "url" => $data['result_url'], - ] - ] + 'notification' => [ + 'url' => $data['result_url'], + ], + ], ]; if (!empty($data['blikPaymentData'])) { $paymentData['pay']['blikPaymentData'] = [ - 'blikToken' => $data['blikPaymentData']['blikToken'] + 'blikToken' => $data['blikPaymentData']['blikToken'], ]; } @@ -72,7 +61,7 @@ private function handleDataStructure(array $data): array private function updateRedirectUrl(array $transactionData): array { $blik0Url = null; - if (!isset($transactionData['transactionPaymentUrl']) && $transactionData['result'] === 'success') { + if (!isset($transactionData['transactionPaymentUrl']) && 'success' === $transactionData['result']) { $blik0Url = 'blik0url'; } $transactionData['url'] = $transactionData['transactionPaymentUrl'] ?? $blik0Url; diff --git a/Model/ApiFacade/Refund/RefundApiFacade.php b/Model/ApiFacade/Refund/RefundApiFacade.php index 9ddd19e..58b067e 100755 --- a/Model/ApiFacade/Refund/RefundApiFacade.php +++ b/Model/ApiFacade/Refund/RefundApiFacade.php @@ -1,11 +1,4 @@ getParentTransactionId(); $this->setAmount($amount)->setCurrency($currency); - $result = $this->refund($transactionId, __('Zwrot do zamówienia ') . $payment->getOrder()->getRealOrderId()); + $result = $this->refund($transactionId, __('Zwrot do zamówienia ').$payment->getOrder()->getRealOrderId()); - if (1 === (int)$result['result'] && isset($result['status']) && 'correct' === $result['status']) { + if (1 === (int) $result['result'] && isset($result['status']) && 'correct' === $result['status']) { return $result['sale_auth']; } - $errDesc = isset($result['err_desc']) ? ' error description: ' . $result['err_desc'] : ''; - $errCode = isset($result['err_code']) ? ' error code: ' . $result['err_code'] : ''; - $reason = isset($result['reason']) ? ' reason: ' . $result['reason'] : ''; - throw new Exception(__('Payment refunding error. -' . $errCode . $errDesc . $reason)); + $errDesc = isset($result['err_desc']) ? ' error description: '.$result['err_desc'] : ''; + $errCode = isset($result['err_code']) ? ' error code: '.$result['err_code'] : ''; + $reason = isset($result['reason']) ? ' reason: '.$result['reason'] : ''; + throw new Exception(__('Payment refunding error. -'.$errCode.$errDesc.$reason)); } } diff --git a/Model/ApiFacade/Refund/RefundOriginApi.php b/Model/ApiFacade/Refund/RefundOriginApi.php index 7a48390..659b515 100755 --- a/Model/ApiFacade/Refund/RefundOriginApi.php +++ b/Model/ApiFacade/Refund/RefundOriginApi.php @@ -1,11 +1,4 @@ setTransactionID($payment->getParentTransactionId())->refundAny(number_format($amount, 2)); - if (isset($apiResult['result']) && (int)$apiResult['result'] === 1) { + if (isset($apiResult['result']) && 1 === (int) $apiResult['result']) { return true; - } else { - $errCode = isset($apiResult['err']) ? ' error code: ' . $apiResult['err'] : ''; - throw new Exception(__('Payment refunding error. -' . $errCode)); } + $errCode = isset($apiResult['err']) ? ' error code: '.$apiResult['err'] : ''; + throw new Exception(__('Payment refunding error. -'.$errCode)); } } diff --git a/Model/ApiFacade/TpayConfig/ConfigFacade.php b/Model/ApiFacade/TpayConfig/ConfigFacade.php index 2513e68..686cf9e 100755 --- a/Model/ApiFacade/TpayConfig/ConfigFacade.php +++ b/Model/ApiFacade/TpayConfig/ConfigFacade.php @@ -1,10 +1,4 @@ tpay = $tpay; @@ -52,7 +41,7 @@ public function getConfig(): array 'getBlikChannelID' => TransactionOriginApi::BLIK_CHANNEL, 'useSandbox' => $this->tpay->useSandboxMode(), 'grandTotal' => number_format($this->tpay->getCheckoutTotal(), 2, '.', ''), - 'groups' => $this->Transactions->getBankGroups((bool)$this->tpay->onlyOnlineChannels())['groups'] + 'groups' => $this->Transactions->getBankGroups((bool) $this->tpay->onlyOnlineChannels())['groups'], ], ], ]; @@ -107,6 +96,7 @@ public function getCardConfig() ]; } } + return [ 'tpaycards' => [ 'payment' => [ diff --git a/Model/ApiFacade/TpayConfig/ConfigOrigin.php b/Model/ApiFacade/TpayConfig/ConfigOrigin.php index 9afdd96..086a456 100755 --- a/Model/ApiFacade/TpayConfig/ConfigOrigin.php +++ b/Model/ApiFacade/TpayConfig/ConfigOrigin.php @@ -1,11 +1,4 @@ tpay = $tpay; @@ -107,6 +96,7 @@ private function getCardConfig() ]; } } + return [ 'tpaycards' => [ 'payment' => [ diff --git a/Model/ApiFacade/Transaction/TransactionApiFacade.php b/Model/ApiFacade/Transaction/TransactionApiFacade.php index e352823..cabe2bc 100755 --- a/Model/ApiFacade/Transaction/TransactionApiFacade.php +++ b/Model/ApiFacade/Transaction/TransactionApiFacade.php @@ -1,11 +1,4 @@ + * @return list */ public function toArray() { diff --git a/Model/Tpay.php b/Model/Tpay.php index c4007be..032de04 100755 --- a/Model/Tpay.php +++ b/Model/Tpay.php @@ -43,6 +43,7 @@ class Tpay extends AbstractMethod implements TpayInterface /** * Min. order amount for BLIK level 0 + * * @var float */ protected $minAmountBlik = 0.01; @@ -72,21 +73,20 @@ class Tpay extends AbstractMethod implements TpayInterface ]; public function __construct( - Context $context, - Registry $registry, + Context $context, + Registry $registry, ExtensionAttributesFactory $extensionFactory, - AttributeValueFactory $customAttributeFactory, - Data $paymentData, - ScopeConfigInterface $scopeConfig, - Logger $logger, - UrlInterface $urlBuilder, - Session $checkoutSession, - OrderRepositoryInterface $orderRepository, - Escaper $escaper, - StoreManager $storeManager, - $data = [] - ) - { + AttributeValueFactory $customAttributeFactory, + Data $paymentData, + ScopeConfigInterface $scopeConfig, + Logger $logger, + UrlInterface $urlBuilder, + Session $checkoutSession, + OrderRepositoryInterface $orderRepository, + Escaper $escaper, + StoreManager $storeManager, + $data = [] + ) { $this->urlBuilder = $urlBuilder; $this->escaper = $escaper; $this->checkoutSession = $checkoutSession; @@ -134,7 +134,7 @@ public function getInstallmentsAmountValid(): bool public function getBlikLevelZeroStatus(): bool { - return (bool)$this->getConfigData('blik_level_zero'); + return (bool) $this->getConfigData('blik_level_zero'); } public function getApiKey(): string @@ -167,7 +167,6 @@ public function getTermsURL(): string return $this->termsURL; } - /** {@inheritdoc} */ public function getOpenApiPassword() { return $this->getConfigData('open_api_password'); @@ -177,9 +176,9 @@ public function getTpayFormData(?string $orderId = null): array { $order = $this->getOrder($orderId); $billingAddress = $order->getBillingAddress(); - $amount = number_format((float)$order->getGrandTotal(), 2, '.', ''); + $amount = number_format((float) $order->getGrandTotal(), 2, '.', ''); $crc = base64_encode($orderId); - $name = $billingAddress->getData('firstname') . ' ' . $billingAddress->getData('lastname'); + $name = $billingAddress->getData('firstname').' '.$billingAddress->getData('lastname'); $phone = $billingAddress->getData('telephone'); $om = ObjectManager::getInstance(); @@ -190,7 +189,7 @@ public function getTpayFormData(?string $orderId = null): array 'email' => $this->escaper->escapeHtml($order->getCustomerEmail()), 'name' => $this->escaper->escapeHtml($name), 'amount' => $amount, - 'description' => 'Zamówienie ' . $orderId, + 'description' => 'Zamówienie '.$orderId, 'crc' => $crc, 'address' => $this->escaper->escapeHtml($order->getBillingAddress()->getData('street')), 'city' => $this->escaper->escapeHtml($order->getBillingAddress()->getData('city')), @@ -201,7 +200,7 @@ public function getTpayFormData(?string $orderId = null): array 'return_url' => $this->urlBuilder->getUrl('magento2basic/tpay/success'), 'phone' => $phone, 'online' => $this->onlyOnlineChannels() ? 1 : 0, - 'module' => 'Magento ' . $this->getMagentoVersion(), + 'module' => 'Magento '.$this->getMagentoVersion(), 'currency' => $this->getISOCurrencyCode($order->getOrderCurrencyCode()), 'language' => $language, ]; @@ -209,10 +208,9 @@ public function getTpayFormData(?string $orderId = null): array public function getMerchantId(): int { - return (int)$this->getConfigData('merchant_id'); + return (int) $this->getConfigData('merchant_id'); } - /** {@inheritdoc} */ public function getOpenApiClientId() { return $this->getConfigData('open_api_client_id'); @@ -230,22 +228,22 @@ public function getOpenApiSecurityCode(): ?string public function onlyOnlineChannels(): bool { - return (bool)$this->getConfigData('show_payment_channels_online'); + return (bool) $this->getConfigData('show_payment_channels_online'); } public function redirectToChannel(): bool { - return (bool)$this->getConfigData('redirect_directly_to_channel'); + return (bool) $this->getConfigData('redirect_directly_to_channel'); } public function useSandboxMode(): bool { - return (bool)$this->getConfigData('use_sandbox'); + return (bool) $this->getConfigData('use_sandbox'); } public function getPaymentRedirectUrl(): string { - return $this->urlBuilder->getUrl('magento2basic/tpay/redirect', ['uid' => time() . uniqid('', true)]); + return $this->urlBuilder->getUrl('magento2basic/tpay/redirect', ['uid' => time().uniqid('', true)]); } /** @@ -281,7 +279,7 @@ public function assignData(DataObject $data) $info->setAdditionalInformation(static::TERMS_ACCEPT, 1); } - //KARTY + // KARTY $info->setAdditionalInformation(static::CARDDATA, isset($additionalData[static::CARDDATA]) ? $additionalData[static::CARDDATA] : ''); $info->setAdditionalInformation(static::CARD_VENDOR, isset($additionalData[static::CARD_VENDOR]) && in_array($additionalData[static::CARD_VENDOR], $this->supportedVendors) ? $additionalData[static::CARD_VENDOR] : 'undefined'); $info->setAdditionalInformation(static::CARD_SAVE, isset($additionalData[static::CARD_SAVE]) ? '1' === $additionalData[static::CARD_SAVE] : false); @@ -293,16 +291,18 @@ public function assignData(DataObject $data) /** * Payment refund - * @param InfoInterface $payment + * * @param float $amount - * @return $this + * * @throws \Exception + * + * @return $this */ public function refund(InfoInterface $payment, $amount) { $refundService = new RefundApiFacade($this); - $refundResult = $refundService->makeRefund($payment, (float)$amount); + $refundResult = $refundService->makeRefund($payment, (float) $amount); try { if ($refundResult) { $payment @@ -323,7 +323,7 @@ public function refund(InfoInterface $payment, $amount) /** @return float current cart total */ public function getCheckoutTotal() { - $amount = (float)$this->getCheckout()->getQuote()->getBaseGrandTotal(); + $amount = (float) $this->getCheckout()->getQuote()->getBaseGrandTotal(); if (!$amount) { $orderId = $this->getCheckout()->getLastRealOrderId(); @@ -343,11 +343,10 @@ public function getConfigData($field, $storeId = null) return parent::getConfigData($field, $storeId); } - -// KARTY + // KARTY public function getCardSaveEnabled(): bool { - return (bool)$this->getConfigData('card_save_enabled'); + return (bool) $this->getConfigData('card_save_enabled'); } public function getCheckoutCustomerId(): ?string @@ -387,6 +386,7 @@ public function getVerificationCode(): string /** * @param string $orderId + * * @return string */ public function getCustomerId($orderId) @@ -398,19 +398,27 @@ public function getCustomerId($orderId) /** * check if customer was logged while placing order + * * @param string $orderId + * * @return bool */ public function isCustomerGuest($orderId) { $order = $this->getOrder($orderId); + return $order->getCustomerIsGuest(); } + public function getISOCurrencyCode($orderCurrency) + { + return $this->validateCardCurrency($orderCurrency); + } + /** Check that the BLIK should be available for order/quote amount */ protected function checkBlikAmount(): bool { - return (bool)($this->getCheckoutTotal() >= $this->minAmountBlik); + return (bool) ($this->getCheckoutTotal() >= $this->minAmountBlik); } protected function getCheckout(): Session @@ -418,11 +426,6 @@ protected function getCheckout(): Session return $this->checkoutSession; } - public function getISOCurrencyCode($orderCurrency) - { - return $this->validateCardCurrency($orderCurrency); - } - protected function getOrder(?string $orderId = null): \Magento\Sales\Api\Data\OrderInterface { if (null === $orderId) { diff --git a/Service/TpayService.php b/Service/TpayService.php index 1ebe4f8..0a517e6 100644 --- a/Service/TpayService.php +++ b/Service/TpayService.php @@ -4,6 +4,7 @@ namespace tpaycom\magento2basic\Service; +use Exception; use Magento\Framework\App\ObjectManager; use Magento\Framework\Event\ManagerInterface as EventManagerInterface; use Magento\Sales\Api\Data\OrderInterface; @@ -32,14 +33,13 @@ class TpayService extends RegisterCaptureNotificationOperation public function __construct( OrderRepositoryInterface $orderRepository, - BuilderInterface $builder, - CommandInterface $stateCommand, - BuilderInterface $transactionBuilder, - ManagerInterface $transactionManager, - EventManagerInterface $eventManager, - InvoiceService $invoiceService - ) - { + BuilderInterface $builder, + CommandInterface $stateCommand, + BuilderInterface $transactionBuilder, + ManagerInterface $transactionManager, + EventManagerInterface $eventManager, + InvoiceService $invoiceService + ) { $this->orderRepository = $orderRepository; $this->builder = $builder; $this->objectManager = ObjectManager::getInstance(); @@ -88,8 +88,10 @@ public function getPayment(string $orderId): OrderPaymentInterface /** * Validate order and set appropriate state + * + * @throws Exception + * * @return bool|OrderInterface - * @throws \Exception */ public function SetOrderStatus(string $orderId, array $validParams, TpayInterface $tpayModel) { @@ -99,12 +101,12 @@ public function SetOrderStatus(string $orderId, array $validParams, TpayInterfac return false; } - $sendNewInvoiceMail = (bool)$tpayModel->getInvoiceSendMail(); - $orderAmount = (float)number_format((float)$order->getGrandTotal(), 2, '.', ''); + $sendNewInvoiceMail = (bool) $tpayModel->getInvoiceSendMail(); + $orderAmount = (float) number_format((float) $order->getGrandTotal(), 2, '.', ''); $trStatus = $validParams['tr_status']; $emailNotify = false; - if ('TRUE' === $trStatus && ((float)number_format($validParams['tr_paid'], 2, '.', '') === $orderAmount)) { + if ('TRUE' === $trStatus && ((float) number_format($validParams['tr_paid'], 2, '.', '') === $orderAmount)) { if (Order::STATE_PROCESSING !== $order->getState()) { $emailNotify = true; } @@ -119,7 +121,7 @@ public function SetOrderStatus(string $orderId, array $validParams, TpayInterfac if (Order::STATE_HOLDED !== $order->getState()) { $emailNotify = true; } - $comment = __('The order has been holded: ') . '
' . $this->getTransactionDesc($validParams); + $comment = __('The order has been holded: ').'
'.$this->getTransactionDesc($validParams); $status = Order::STATE_HOLDED; $order->addStatusToHistory($status, $comment, true); } @@ -143,8 +145,48 @@ public function getOrderById(string $orderId): OrderInterface return $this->orderRepository->getByIncrementId($orderId); } + // KARTY + public function setCardOrderStatus($orderId, array $validParams, $tpayModel) + { + /** @var Order $order */ + $order = $this->orderRepository->getByIncrementId($orderId); + if (!$order->getId()) { + return false; + } + $sendNewInvoiceMail = (bool) $tpayModel->getInvoiceSendMail(); + $transactionDesc = $this->getCardTransactionDesc($validParams); + $orderAmount = (float) number_format((float) $order->getGrandTotal(), 2, '.', ''); + $emailNotify = false; + + $order = $this->updateTransactionId($order, $validParams); + + if (!isset($validParams['status']) || 'correct' !== $validParams['status'] || ((float) number_format((float) $validParams['amount'], 2, '.', '') !== $orderAmount)) { + $comment = __('Payment has been declined. ').'
'.$transactionDesc; + $this->addCommentToHistory($orderId, $comment); + } else { + if (Order::STATE_PROCESSING != $order->getState()) { + $emailNotify = true; + } + $this->registerCardCaptureNotificationTpay($order->getPayment(), $order->getGrandTotal(), $validParams); + } + + if ($emailNotify) { + $order->setSendEmail(true); + } + $order->save(); + if ($sendNewInvoiceMail) { + foreach ($order->getInvoiceCollection() as $invoice) { + $invoiceId = $invoice->getId(); + $this->invoiceService->notify($invoiceId); + } + } + + return $order; + } + /** * Get description for transaction + * * @return bool|string */ protected function getTransactionDesc(array $validParams) @@ -155,8 +197,8 @@ protected function getTransactionDesc(array $validParams) $error = $validParams['tr_error']; $paid = $validParams['tr_paid']; $status = $validParams['tr_status']; - $transactionDesc = '' . $validParams['tr_id'] . ' '; - $transactionDesc .= 'none' === $error ? ' ' : ' Error: ' . strtoupper($error) . ' (' . $paid . ')'; + $transactionDesc = ''.$validParams['tr_id'].' '; + $transactionDesc .= 'none' === $error ? ' ' : ' Error: '.strtoupper($error).' ('.$paid.')'; if ('CHARGEBACK' === $status) { $transactionDesc .= __('Transaction has been refunded'); } @@ -167,10 +209,30 @@ protected function getTransactionDesc(array $validParams) return $transactionDesc; } + protected function getCardTransactionDesc($validParams) + { + if (empty($validParams)) { + return false; + } + if (isset($validParams['err_desc'])) { + return 'Payment error: '.$validParams['err_desc'].', error code: '.$validParams['err_code']; + } + $error = null; + if ('declined' === $validParams['status']) { + $error = $validParams['reason']; + } + + $transactionDesc = (is_null($error)) ? ' ' : ' Reason: '.$error.''; + $transactionDesc .= (isset($validParams['test_mode'])) && 1 === (int) $validParams['test_mode'] ? ' TEST ' : ' '; + + return $transactionDesc; + } + /** * Registers capture notification. + * * @param float|string $amount - * @param bool|int $skipFraudDetection + * @param bool|int $skipFraudDetection */ private function registerCaptureNotificationTpay(OrderPaymentInterface $payment, $amount, array $validParams, $skipFraudDetection = false) { @@ -178,7 +240,7 @@ private function registerCaptureNotificationTpay(OrderPaymentInterface $payment, $payment->setTransactionId($this->transactionManager->generateTransactionId($payment, Transaction::TYPE_CAPTURE, $payment->getAuthorizationTransaction())); $order = $payment->getOrder(); - $amount = (float)$amount; + $amount = (float) $amount; $invoice = $this->getInvoiceForTransactionId($order, $payment->getTransactionId()); $orderCurrency = $order->getOrderCurrency()->getCode(); // register new capture @@ -211,80 +273,21 @@ private function registerCaptureNotificationTpay(OrderPaymentInterface $payment, $payment->addTransactionCommentsToOrder($transaction, $message); } - - // KARTY - public function setCardOrderStatus($orderId, array $validParams, $tpayModel) - { - /** @var Order $order */ - $order = $this->orderRepository->getByIncrementId($orderId); - if (!$order->getId()) { - return false; - } - $sendNewInvoiceMail = (bool)$tpayModel->getInvoiceSendMail(); - $transactionDesc = $this->getCardTransactionDesc($validParams); - $orderAmount = (double)number_format((float)$order->getGrandTotal(), 2, '.', ''); - $emailNotify = false; - - $order = $this->updateTransactionId($order, $validParams); - - if (!isset($validParams['status']) || $validParams['status'] !== 'correct' || ((double)number_format((float)$validParams['amount'], 2, '.', '') !== $orderAmount)) { - $comment = __('Payment has been declined. ') . '
' . $transactionDesc; - $this->addCommentToHistory($orderId, $comment); - } else { - if ($order->getState() != Order::STATE_PROCESSING) { - $emailNotify = true; - } - $this->registerCardCaptureNotificationTpay($order->getPayment(), $order->getGrandTotal(), $validParams); - } - - if ($emailNotify) { - $order->setSendEmail(true); - } - $order->save(); - if ($sendNewInvoiceMail) { - foreach ($order->getInvoiceCollection() as $invoice) { - $invoiceId = $invoice->getId(); - $this->invoiceService->notify($invoiceId); - } - } - - return $order; - } - - protected function getCardTransactionDesc($validParams) - { - if (empty($validParams)) { - return false; - } - if (isset ($validParams['err_desc'])) { - return 'Payment error: ' . $validParams['err_desc'] . ', error code: ' . $validParams['err_code']; - } - $error = null; - if ($validParams['status'] === 'declined') { - $error = $validParams['reason']; - } - - $transactionDesc = (is_null($error)) ? ' ' : ' Reason: ' . $error . ''; - $transactionDesc .= (isset($validParams['test_mode'])) && (int)$validParams['test_mode'] === 1 ? ' TEST ' : ' '; - - return $transactionDesc; - } - private function registerCardCaptureNotificationTpay(OrderPaymentInterface $payment, $amount, $validParams, $skipFraudDetection = false) { - /** @var $payment Payment */ + // @var $payment Payment $payment->setTransactionId($this->transactionManager->generateTransactionId($payment, Transaction::TYPE_CAPTURE, $payment->getAuthorizationTransaction())); $order = $payment->getOrder(); - $amount = (double)$amount; + $amount = (float) $amount; $invoice = $this->getInvoiceForTransactionId($order, $payment->getTransactionId()); $orderCurrencyCode = $order->getOrderCurrency()->getCode(); if (!in_array($orderCurrencyCode, CurrencyCodesDictionary::CODES)) { - throw new \Exception(sprintf('Order currency %s does not exist in Tpay dictionary!', $orderCurrencyCode)); + throw new Exception(sprintf('Order currency %s does not exist in Tpay dictionary!', $orderCurrencyCode)); } $orderCurrency = array_search($orderCurrencyCode, CurrencyCodesDictionary::CODES); // register new capture - if (!$invoice && $payment->isCaptureFinal($amount) && ($orderCurrency === (int)$validParams['currency'] || $orderCurrencyCode === $validParams['currency'])) { + if (!$invoice && $payment->isCaptureFinal($amount) && ($orderCurrency === (int) $validParams['currency'] || $orderCurrencyCode === $validParams['currency'])) { $invoice = $order->prepareInvoice()->register(); $invoice->setOrder($order); $order->addRelatedObject($invoice); diff --git a/Service/TpayTokensService.php b/Service/TpayTokensService.php index 0205726..fc310dc 100644 --- a/Service/TpayTokensService.php +++ b/Service/TpayTokensService.php @@ -7,6 +7,7 @@ use Magento\Framework\Model\Context; use Magento\Framework\Registry; use tpaycom\magento2basic\Model\Tokens; +use Zend_Db_Expr; class TpayTokensService extends Tokens { @@ -42,8 +43,8 @@ public function getCustomerTokens(string $customerId, bool $crcRequired = false) $select = $connection->select() ->from($tableName) ->where('cli_id = ?', $customerId) - ->where(new \Zend_Db_Expr('cli_auth IS NOT NULL')) - ->where(new \Zend_Db_Expr($crcRequired ? 'crc IS NOT NULL' : 'crc IS NULL')); + ->where(new Zend_Db_Expr('cli_auth IS NOT NULL')) + ->where(new Zend_Db_Expr($crcRequired ? 'crc IS NOT NULL' : 'crc IS NULL')); $results = []; foreach ($connection->fetchAll($select) as $token) { @@ -94,7 +95,7 @@ public function getTokenById(int $tokenId, int $customerId, bool $crcRequired = ->from($tableName) ->where('id = ?', $tokenId) ->where('cli_id = ?', $customerId) - ->where(new \Zend_Db_Expr($crcRequired ? 'crc IS NOT NULL' : 'crc IS NULL')); + ->where(new Zend_Db_Expr($crcRequired ? 'crc IS NOT NULL' : 'crc IS NULL')); $result = $connection->fetchAll($select); diff --git a/Setup/InstallSchema.php b/Setup/InstallSchema.php index 7a4142a..2fa4f81 100644 --- a/Setup/InstallSchema.php +++ b/Setup/InstallSchema.php @@ -2,10 +2,10 @@ namespace tpaycom\magento2basic\Setup; +use Magento\Framework\DB\Ddl\Table; use Magento\Framework\Setup\InstallSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; -use Magento\Framework\DB\Ddl\Table; class InstallSchema implements InstallSchemaInterface { @@ -17,7 +17,7 @@ public function install(SchemaSetupInterface $setup, ModuleContextInterface $con // Get tpay cards table $tableName = $installer->getTable('tpay_credit_cards'); // Check if the table already exists - if ($installer->getConnection()->isTableExists($tableName) != true) { + if (true != $installer->getConnection()->isTableExists($tableName)) { // Create table $table = $installer->getConnection() ->newTable($tableName) @@ -29,7 +29,7 @@ public function install(SchemaSetupInterface $setup, ModuleContextInterface $con 'identity' => true, 'unsigned' => true, 'nullable' => false, - 'primary' => true + 'primary' => true, ], 'ID' ) diff --git a/Setup/Uninstall.php b/Setup/Uninstall.php index 6bfa6dc..92d64a8 100644 --- a/Setup/Uninstall.php +++ b/Setup/Uninstall.php @@ -2,9 +2,9 @@ namespace Mageplaza\Example\Setup; -use Magento\Framework\Setup\UninstallInterface; -use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Framework\Setup\ModuleContextInterface; +use Magento\Framework\Setup\SchemaSetupInterface; +use Magento\Framework\Setup\UninstallInterface; class Uninstall implements UninstallInterface { diff --git a/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php index b319958..7b3f033 100644 --- a/Setup/UpgradeSchema.php +++ b/Setup/UpgradeSchema.php @@ -2,14 +2,14 @@ namespace tpaycom\magento2basic\Setup; -use Magento\Framework\Setup\UpgradeSchemaInterface; -use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Framework\Setup\ModuleContextInterface; +use Magento\Framework\Setup\SchemaSetupInterface; +use Magento\Framework\Setup\UpgradeSchemaInterface; class UpgradeSchema implements UpgradeSchemaInterface { - public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $context ) { - + public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) + { (new InstallSchema())->install($setup, $context); } } From ab3c938da90f5a733a9993cb84a6456140a15e6e Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 13:08:19 +0100 Subject: [PATCH 17/21] normalized --- Model/ApiFacade/Transaction/TransactionOriginApi.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Model/ApiFacade/Transaction/TransactionOriginApi.php b/Model/ApiFacade/Transaction/TransactionOriginApi.php index 4e094f1..e63cdcf 100755 --- a/Model/ApiFacade/Transaction/TransactionOriginApi.php +++ b/Model/ApiFacade/Transaction/TransactionOriginApi.php @@ -11,8 +11,9 @@ class TransactionOriginApi extends PaymentBlik /** * @param string $apiPassword * @param string $apiKey - * @param int $merchantId + * @param int $merchantId * @param string $merchantSecret + * @param mixed $isProd */ public function __construct($apiPassword, $apiKey, $merchantId, $merchantSecret, $isProd = true) { From 926dee904b750c7d9df6faeafe51ae909e3ed0ef Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 13:10:45 +0100 Subject: [PATCH 18/21] normalized --- Model/ApiFacade/Transaction/TransactionOriginApi.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Model/ApiFacade/Transaction/TransactionOriginApi.php b/Model/ApiFacade/Transaction/TransactionOriginApi.php index e63cdcf..4dcd2cb 100755 --- a/Model/ApiFacade/Transaction/TransactionOriginApi.php +++ b/Model/ApiFacade/Transaction/TransactionOriginApi.php @@ -11,9 +11,9 @@ class TransactionOriginApi extends PaymentBlik /** * @param string $apiPassword * @param string $apiKey - * @param int $merchantId + * @param int $merchantId * @param string $merchantSecret - * @param mixed $isProd + * @param mixed $isProd */ public function __construct($apiPassword, $apiKey, $merchantId, $merchantSecret, $isProd = true) { From 5637f1d02549beba1e88c8bd784c93e0e69bdcab Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 13:16:48 +0100 Subject: [PATCH 19/21] normalized --- composer.json | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index dda7500..fad81df 100755 --- a/composer.json +++ b/composer.json @@ -10,10 +10,13 @@ } ], "require": { - "php": ">=7", - "magento/product-community-edition": "^2.3", + "php": ">=7.1", + "magento/module-sales": ">=100.0", + "magento/module-checkout": ">=100.0", + "magento/module-payment": ">=100.0", + "magento/framework": ">=100.0", "tpay-com/tpay-openapi-php": "^1.3", - "tpay-com/tpay-php": "^2.3.6" + "tpay-com/tpay-php": "^2.3" }, "autoload": { "psr-4": { From 326765a2ad08c96a0c253ca9665fafa0e15278d7 Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 13:18:20 +0100 Subject: [PATCH 20/21] normalized --- composer.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index fad81df..31c56e3 100755 --- a/composer.json +++ b/composer.json @@ -11,10 +11,10 @@ ], "require": { "php": ">=7.1", - "magento/module-sales": ">=100.0", - "magento/module-checkout": ">=100.0", - "magento/module-payment": ">=100.0", - "magento/framework": ">=100.0", + "magento/module-sales": "^100.0", + "magento/module-checkout": "^100.0", + "magento/module-payment": "^100.0", + "magento/framework": "^100.0", "tpay-com/tpay-openapi-php": "^1.3", "tpay-com/tpay-php": "^2.3" }, From b26e3ff48a270a85d886b86c917e5535881ae610 Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 13:19:58 +0100 Subject: [PATCH 21/21] normalized --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 31c56e3..f577c2c 100755 --- a/composer.json +++ b/composer.json @@ -11,10 +11,10 @@ ], "require": { "php": ">=7.1", - "magento/module-sales": "^100.0", + "magento/framework": "^100.0", "magento/module-checkout": "^100.0", "magento/module-payment": "^100.0", - "magento/framework": "^100.0", + "magento/module-sales": "^100.0", "tpay-com/tpay-openapi-php": "^1.3", "tpay-com/tpay-php": "^2.3" },