From 138005bbc0129f67e1b55f90ba332f9dbe007cb4 Mon Sep 17 00:00:00 2001 From: kGablo Date: Tue, 28 Nov 2023 08:39:57 +0100 Subject: [PATCH 1/7] =?UTF-8?q?DX-161=20Stworzenie=20implementacji=20inter?= =?UTF-8?q?face=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 6/7] 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 7/7] 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());