From a057bca859044781fca16e5c1eef4035414c46eb Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 13 Oct 2023 12:12:00 +0200 Subject: [PATCH 1/7] Various fixes e.g. sandbox/translations [DX-76] - Fixed [DX-159] - Fixed --- .dev-tools/.php-cs-fixer.php | 2 + .gitignore | 2 + Api/Sales/OrderRepositoryInterface.php | 12 +- Api/TpayInterface.php | 133 +++++--------- Controller/Tpaycom.php | 8 +- Controller/tpay/Create.php | 33 +--- Controller/tpay/Error.php | 2 + Controller/tpay/Notification.php | 56 ++---- Controller/tpay/Redirect.php | 13 +- Controller/tpay/Refund.php | 45 ++--- Controller/tpay/Success.php | 2 + Model/NotificationModel.php | 8 +- Model/RefundModel.php | 29 +++- Model/Sales/OrderRepository.php | 4 +- Model/Tpay.php | 162 ++++++------------ Model/TpayConfigProvider.php | 32 +--- Model/TransactionModel.php | 15 +- README.md | 55 +++--- Service/TpayService.php | 60 ++----- composer.json | 30 ++-- etc/adminhtml/system.xml | 11 +- etc/config.xml | 3 +- etc/csp_whitelist.xml | 6 + etc/module.xml | 2 +- i18n/pl_PL.csv | 4 +- registration.php | 2 + view/base/web/js/render_channels.js | 51 +++++- .../payment/method-renderer/tpay-method.js | 5 +- .../web/template/payment/tpay-form.html | 4 +- 29 files changed, 317 insertions(+), 474 deletions(-) diff --git a/.dev-tools/.php-cs-fixer.php b/.dev-tools/.php-cs-fixer.php index 8c778bf..4e51108 100644 --- a/.dev-tools/.php-cs-fixer.php +++ b/.dev-tools/.php-cs-fixer.php @@ -1,5 +1,7 @@ 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(), + 'isProd' => !$this->tpay->useSandboxMode(), ] ); $additionalPaymentInformation = $paymentData['additional_information']; - - /** @var array $transaction */ $transaction = $this->prepareTransaction($orderId, $additionalPaymentInformation); if (!isset($transaction['title'], $transaction['url'])) { @@ -103,26 +97,14 @@ public function execute() } } - /** - * Send BLIK code for transaction id - * - * @param string $blikTransactionId - * @param string $blikCode - * - * @return bool - */ - protected function blikPay($blikTransactionId, $blikCode) + /** Send BLIK code for transaction id */ + protected function blikPay(string $blikTransactionId, string $blikCode): bool { - /** @var array $apiResult */ $apiResult = $this->transaction->blik($blikTransactionId, $blikCode); - return isset($apiResult['result']) && 1 === $apiResult['result']; + return array_key_exists('result', $apiResult) && 1 === $apiResult['result']; } - /** - * @param mixed $orderId - * @param array{blik_code: string, group: int|string} $additionalPaymentInformation - */ private function prepareTransaction($orderId, array $additionalPaymentInformation) { $data = $this->tpay->getTpayFormData($orderId); @@ -130,6 +112,9 @@ private function prepareTransaction($orderId, array $additionalPaymentInformatio $data['group'] = TransactionModel::BLIK_CHANNEL; } else { $data['group'] = (int) $additionalPaymentInformation['group']; + if ($this->tpay->redirectToChannel()) { + $data['direct'] = 1; + } } return $this->transaction->create($data); 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() + public function execute(): bool { 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(); - } + $notification = (new JWSVerifiedPaymentNotification($code, !$this->tpay->useSandboxMode()))->getNotification(); - /** @var array $validParams */ $validParams = $this->NotificationHandler->checkPayment(''); - - $orderId = base64_decode($validParams['tr_crc']); - if ('PAID' === $validParams['tr_status']) { + $orderId = base64_decode($notification->tr_crc->getValue()); + if ('PAID' === $notification->tr_status->getValue()) { $response = $this->getPaidTransactionResponse($orderId); return $this @@ -103,18 +76,17 @@ public function execute() /** * 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; } @@ -122,13 +94,11 @@ public function validateForCsrf(RequestInterface $request) /** * Check if the order has been canceled and get response to Tpay server. * - * @param int $orderId - * * @throws Exception * * @return string response for Tpay server */ - protected function getPaidTransactionResponse($orderId) + protected function getPaidTransactionResponse(int $orderId): string { $order = $this->tpayService->getOrderById($orderId); if (!$order->getId()) { 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 index dac8236..fa6aef0 100644 --- a/Controller/tpay/Refund.php +++ b/Controller/tpay/Refund.php @@ -1,5 +1,7 @@ apiPassword, $this->apiKey, $this->merchantId, $this->merchantSecret); @@ -39,55 +34,35 @@ public function makeRefund($payment, $amount) ->setTransactionID($payment->getParentTransactionId()) ->refundAny(number_format($amount, 2)); - if (isset($apiResult['result']) && 1 === (int) $apiResult['result']) { + if (array_key_exists('result', $apiResult) && 1 === (int) $apiResult['result']) { return true; } - $errCode = isset($apiResult['err']) ? ' error code: '.$apiResult['err'] : ''; + $errCode = array_key_exists('err', $apiResult) ? ' error code: '.$apiResult['err'] : ''; throw new Exception(__('Payment refunding error. -'.$errCode)); } - /** - * @param string $merchantSecret - * - * @return self - */ - public function setMerchantSecret($merchantSecret) + public function setMerchantSecret(string $merchantSecret): self { $this->merchantSecret = $merchantSecret; return $this; } - /** - * @param int $merchantId - * - * @return self - */ - public function setMerchantId($merchantId) + public function setMerchantId(int $merchantId): self { $this->merchantId = $merchantId; return $this; } - /** - * @param string $apiPassword - * - * @return self - */ - public function setApiPassword($apiPassword) + public function setApiPassword(string $apiPassword): self { $this->apiPassword = $apiPassword; return $this; } - /** - * @param string $apiKey - * - * @return self - */ - public function setApiKey($apiKey) + public function setApiKey(string $apiKey): self { $this->apiKey = $apiKey; 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 @@ merchantId = $merchantId; $this->merchantSecret = $merchantSecret; diff --git a/Model/RefundModel.php b/Model/RefundModel.php index c5ea883..fbf0805 100644 --- a/Model/RefundModel.php +++ b/Model/RefundModel.php @@ -1,23 +1,38 @@ trApiKey = $apiKey; $this->trApiPass = $apiPassword; $this->merchantId = $merchantId; $this->merchantSecret = $merchantSecret; parent::__construct(); + if (!$isProd) { + $this->apiURL = 'https://secure.sandbox.tpay.com/api/gw/'; + } + } + + /** @throws \Exception */ + public function makeRefund(InfoInterface $payment, float $amount): bool + { + Util::$loggingEnabled = false; + $apiResult = $this->setTransactionID($payment->getParentTransactionId()) + ->refundAny(number_format($amount, 2)); + if (array_key_exists('result', $apiResult) && 1 === (int) $apiResult['result']) { + return true; + } + $errCode = array_key_exists('err', $apiResult) ? ' error code: '.$apiResult['err'] : ''; + throw new Exception(__('Payment refunding error. -'.$errCode)); } } 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'; /** @@ -73,9 +56,6 @@ class Tpay extends AbstractMethod implements TpayInterface /** @var Escaper */ protected $escaper; - /** @var Refund */ - protected $refund; - /** @var StoreManager */ protected $storeManager; @@ -90,7 +70,7 @@ public function __construct( UrlInterface $urlBuilder, Session $checkoutSession, OrderRepositoryInterface $orderRepository, - Refund $refund, + RefundModelFactory $refundFactory, Escaper $escaper, StoreManager $storeManager, $data = [] @@ -99,7 +79,7 @@ public function __construct( $this->escaper = $escaper; $this->checkoutSession = $checkoutSession; $this->orderRepository = $orderRepository; - $this->refund = $refund; + $this->refundFactory = $refundFactory; $this->storeManager = $storeManager; parent::__construct( @@ -116,12 +96,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,48 +114,45 @@ 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'); } - 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) + public function getTpayFormData($orderId = null): array { $order = $this->getOrder($orderId); $billingAddress = $order->getBillingAddress(); $amount = number_format($order->getGrandTotal(), 2, '.', ''); $crc = base64_encode($orderId); $name = $billingAddress->getData('firstname').' '.$billingAddress->getData('lastname'); - - /** @var string $phone */ $phone = $billingAddress->getData('telephone'); return [ @@ -197,37 +174,32 @@ public function getTpayFormData($orderId = null) ]; } - public function getMerchantId() + public function getMerchantId(): int { return (int) $this->getConfigData('merchant_id'); } - public function getSecurityCode() + public function getSecurityCode(): string { return $this->getConfigData('security_code'); } - public function onlyOnlineChannels() + public function onlyOnlineChannels(): bool { return (bool) $this->getConfigData('show_payment_channels_online'); } - public function redirectToChannel() + public function redirectToChannel(): bool { return (bool) $this->getConfigData('redirect_directly_to_channel'); } - public function getCheckProxy() - { - return (bool) $this->getConfigData('check_proxy'); - } - - 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)]); } @@ -237,12 +209,9 @@ public function getPaymentRedirectUrl() * * 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 +232,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 @@ -291,20 +258,22 @@ public function assignData(DataObject $data) /** * Payment refund * - * @param float $amount - * * @throws \Exception * * @return $this */ - public function refund(InfoInterface $payment, $amount) + public function refund(InfoInterface $payment, float $amount) { - $this->refund - ->setApiKey($this->getApiKey()) - ->setApiPassword($this->getApiPassword()) - ->setMerchantId($this->getMerchantId()) - ->setMerchantSecret($this->getSecurityCode()); - $refundResult = $this->refund->makeRefund($payment, $amount); + $refundService = $this->refundFactory->create( + [ + 'apiPassword' => $this->getApiPassword(), + 'apiKey' => $this->getApiKey(), + 'merchantId' => $this->getMerchantId(), + 'merchantSecret' => $this->getSecurityCode(), + 'isProd' => !$this->useSandboxMode(), + ] + ); + $refundResult = $refundService->makeRefund($payment, $amount); try { if ($refundResult) { $payment @@ -322,34 +291,13 @@ 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(); if (!$amount) { - /** @var int $orderId */ $orderId = $this->getCheckout()->getLastRealOrderId(); - $order = $this->orderRepository->getByIncrementId($orderId); $amount = $order->getGrandTotal(); } @@ -357,35 +305,37 @@ protected function getCheckoutTotal() return number_format($amount, 2, '.', ''); } - /** @return Session */ - protected function getCheckout() + public function getConfigData($field, $storeId = null) + { + if (null === $storeId) { + $storeId = $this->storeManager->getStore()->getId(); + } + + return parent::getConfigData($field, $storeId); + } + + /** 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(?int $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 +343,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..fb1502c 100644 --- a/Model/TpayConfigProvider.php +++ b/Model/TpayConfigProvider.php @@ -1,5 +1,7 @@ $this->getPaymentMethodInstance()->checkBlikLevel0Settings(), 'onlyOnlineChannels' => $this->getPaymentMethodInstance()->onlyOnlineChannels(), 'getBlikChannelID' => TransactionModel::BLIK_CHANNEL, - 'isInstallmentsAmountValid' => $this->getPaymentMethodInstance()->getInstallmentsAmountValid(), + 'useSandbox' => $tpay->useSandboxMode(), + 'grandTotal' => $this->getPaymentMethodInstance()->getCheckoutTotal(), ], ], ]; @@ -51,30 +54,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 index 1d0efe0..d4d92f6 100644 --- a/Model/TransactionModel.php +++ b/Model/TransactionModel.php @@ -1,25 +1,24 @@ 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/README.md b/README.md index 9b8a505..8215baf 100644 --- a/README.md +++ b/README.md @@ -1,49 +1,44 @@ -# Magento2-Tpay +Magento2-Tpay +====================== -[Tpay](https://tpay.com) payment gateway Magento2 module. +Tpay payment gateway Magento2 extension -[![Latest stable version](https://img.shields.io/packagist/v/tpaycom/magento2basic.svg?label=current%20version)](https://packagist.org/packages/tpaycom/magento2basic) -[![PHP version](https://img.shields.io/packagist/php-v/tpaycom/magento2basic.svg)](https://php.net) -[![License](https://img.shields.io/github/license/tpay-com/tpay-magento2-basic.svg)](LICENSE) -[![CI status](https://github.com/tpay-com/tpay-magento2-basic/actions/workflows/ci.yaml/badge.svg?branch=master)](https://github.com/tpay-com/tpay-magento2-basic/actions) -[![Type coverage](https://shepherd.dev/github/tpay-com/tpay-magento2-basic/coverage.svg)](https://shepherd.dev/github/tpay-com/tpay-magento2-basic) +Install +======= -[Polish version :poland: wersja polska](./README_PL.md) +1. Go to Magento2 root folder -## Manual installation +2. Copy plugin files to app/code/tpaycom/magento2basic -1. Go to Magento2 root directory. +3. If you have already installed the [magento2cards](https://github.com/tpay-com/tpay-magento2-cards) module, you can skip this step. +Download and copy depending library [tpay-php,tpay-openapi-php](https://github.com/tpay-com/tpay-php, https://github.com/tpay-com/tpay-openapi-php) to app/code folder. In the result your should have 2 folders in app/code - tpaycom and tpayLibs. -2. Copy plugin files to `app/code/tpaycom/magento2basic`. +4. Enter following commands to enable module: -3. If you have already installed the [`magento2cards`](https://github.com/tpay-com/tpay-magento2-cards) module, you can skip this step. - Download and copy required library [`tpay-php`](https://github.com/tpay-com/tpay-php) to `app/code` directory. In the result you should have 2 directories in `app/code` - `tpaycom` and `tpayLibs`. - -4. Execute following commands to enable module: - ```console - php bin/magento module:enable tpaycom_magento2basic + ```bash + php bin/magento module:enable tpaycom_magento2basic php bin/magento setup:upgrade ``` +5. Enable and configure module in Magento Admin under Stores/Configuration/Payment Methods/tpay.com -5. Enable and configure module in Magento Admin under `Stores/Configuration/Payment Methods/tpay.com`. - - -## [Composer](https://getcomposer.org) installation +Composer install +======= -1. Execute following command to download module: - ```console - composer require tpaycom/magento2basic +1. Enter following commands to download module: + ```bash + composer require tpaycom/magento2basic ``` +2. Enter following commands to enable module: -2. Execute following commands to enable module: - ```console - php bin/magento module:enable tpaycom_magento2basic + ```bash + php bin/magento module:enable tpaycom_magento2basic php bin/magento setup:upgrade ``` +3. Enable and configure module in Magento Admin under Stores/Configuration/Payment Methods/tpay.com -3. Enable and configure module in Magento Admin under `Stores/Configuration/Payment Methods/tpay.com`. +Other Notes +=========== -## Notes +tpaycom works with PLN only!** If PLN is not your base currency, you will not see this module on checkout pages. -This module works with PLN only! If PLN is not your base currency, you will not see this module on checkout pages. diff --git a/Service/TpayService.php b/Service/TpayService.php index de77619..5355952 100644 --- a/Service/TpayService.php +++ b/Service/TpayService.php @@ -1,5 +1,7 @@ orderRepository->getByIncrementId($orderId); @@ -85,14 +75,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(int $orderId): OrderPaymentInterface { /** @var Order $order */ $order = $this->orderRepository->getByIncrementId($orderId); @@ -103,13 +87,9 @@ public function getPayment($orderId) /** * Validate order and set appropriate state * - * @param int $orderId - * @param array $validParams - * @param TpayInterface $tpayModel - * * @return bool|Order */ - public function SetOrderStatus($orderId, array $validParams, $tpayModel) + public function SetOrderStatus(int $orderId, array $validParams, TpayInterface $tpayModel) { $order = $this->getOrderById($orderId); if (!$order->getId()) { @@ -124,7 +104,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 +115,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 +127,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,14 +136,8 @@ 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(int $orderId): Order { return $this->orderRepository->getByIncrementId($orderId); } @@ -174,8 +145,6 @@ public function getOrderById($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 '; } @@ -201,17 +170,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/composer.json b/composer.json index 8bd075d..bbaf19a 100755 --- a/composer.json +++ b/composer.json @@ -1,25 +1,29 @@ { "name": "tpaycom/magento2basic", "description": "Tpay payments module", - "license": "MIT", "type": "magento2-module", - "authors": [ - { - "name": "tpay.com", - "homepage": "https://tpay.com/" - } + "version": "1.6.0", + "license": [ + "OSL-3.0" ], "require": { "php": ">=7", - "magento/product-community-edition": "^2.3", - "tpay-com/tpay-php": "^2.3" + "magento/product-community-edition": "~2.3|~2.4", + "tpay-com/tpay-php": "^2.3", + "tpay-com/tpay-openapi-php": "^1.3" }, "autoload": { - "psr-4": { - "tpaycom\\magento2basic\\": "" - }, "files": [ "registration.php" - ] - } + ], + "psr-4": { + "tpaycom\\magento2basic\\": "" + } + }, + "authors": [ + { + "name": "tpay.com", + "homepage": "https://tpay.com/" + } + ] } diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index c002061..39335df 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -53,16 +53,13 @@ Magento\Config\Model\Config\Source\Yesno - - - Magento\Config\Model\Config\Source\Yesno - - - + + Magento\Config\Model\Config\Source\Yesno + validate-number @@ -74,10 +71,12 @@ + validate-number Leave empty for no limit + validate-number 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/registration.php b/registration.php index d280bc0..78ab101 100644 --- a/registration.php +++ b/registration.php @@ -1,5 +1,7 @@ ' + @@ -25,25 +26,40 @@ require(['jquery', 'mage/translate'], function ($, $t) { return false; } + function doesAmountFitToInstallments(grandTotal, channelId){ + switch (channelId){ + case 167: //twisto + return grandTotal >= 1 && grandTotal <= 1500; + break; + case 169: //raty pekao + return grandTotal >= 100 && grandTotal <= 20000; + break; + case 109: //alior raty + return grandTotal >= 300 && grandTotal <= 9259; + break; + } + + return true; + } + function ShowChannelsCombo() { var str = '', i, str2 = '', tile, others = [157, 106, 109, 148, 104], - installmentsGroupId = 109, + installmentsGroupId = [109,169,167], group, id, groupName, logoSrc, bank_selection_form = document.getElementById('bank-selection-form'); - for (i in tr_groups) { group = tr_groups[i]; id = group[0]; groupName = group[1]; logoSrc = group[3]; - if (id == installmentsGroupId && window.checkoutConfig.tpay.payment.isInstallmentsAmountValid === false) { + if (inArray(id, installmentsGroupId) && !doesAmountFitToInstallments(parseFloat(window.checkoutConfig.tpay.payment.grandTotal), parseInt(id))) { continue; } tile = getBankTile(id, groupName, logoSrc); @@ -64,7 +80,7 @@ require(['jquery', 'mage/translate'], function ($, $t) { active_bank_blocks[0].className = active_bank_blocks[0].className.replace('tpay-active', ''); } this.className = this.className + ' tpay-active'; - if (input.val() > 0 && $('#blik_code').val().length === 0) { + if (input.val() > 0 && $('#blik_code').val().length === 0 && tos.is(':checked')) { payButton.removeClass('disabled'); } }); @@ -94,7 +110,11 @@ require(['jquery', 'mage/translate'], function ($, $t) { } else { $('#tpay-basic-main-payment').css('display', 'block'); } - if (that.val().length === 6 || (that.val().length === 0 && $('#tpay-channel-input').val() > 0)) { + if ( + (that.val().length === 6 || (that.val().length === 0 && $('#tpay-channel-input').val() > 0)) + && + tos.is(':checked') + ) { payButton.removeClass('disabled'); } if (that.val().length > 0 && that.val().length !== 6) { @@ -103,11 +123,28 @@ require(['jquery', 'mage/translate'], function ($, $t) { }); } - $.getScript("https://secure.tpay.com/groups-" + window.checkoutConfig.tpay.payment.merchantId + showOnlyOnlinePayments() + ".js", function () { + url = 'https://secure.tpay.com/'; + if (window.checkoutConfig.tpay.payment.useSandbox) { + url = 'https://secure.sandbox.tpay.com/'; + } + $.getScript(url + "groups-" + window.checkoutConfig.tpay.payment.merchantId + showOnlyOnlinePayments() + ".js", function () { ShowChannelsCombo(); checkBlikInput(); setBlikInputAction(); payButton.addClass('disabled'); + tos.on('change', function () { + var input = $('#tpay-channel-input'); + if (input.val() > 0 && $('#blik_code').val().length === 0 && tos.is(':checked')) { + payButton.removeClass('disabled'); + return; + } + + if ($('#blik_code').val().length === 6 && tos.is(':checked')) { + payButton.removeClass('disabled'); + return; + } + payButton.addClass('disabled'); + }); }); } ); diff --git a/view/frontend/web/js/view/payment/method-renderer/tpay-method.js b/view/frontend/web/js/view/payment/method-renderer/tpay-method.js index 16ea944..2b18f02 100644 --- a/view/frontend/web/js/view/payment/method-renderer/tpay-method.js +++ b/view/frontend/web/js/view/payment/method-renderer/tpay-method.js @@ -8,7 +8,8 @@ define( [ 'Magento_Checkout/js/view/payment/default', - 'jquery' + 'jquery', + 'Magento_Checkout/js/model/totals' ], function (Component, $) { 'use strict'; @@ -59,7 +60,7 @@ define( isActive: function () { return true; - } + }, }); } ); diff --git a/view/frontend/web/template/payment/tpay-form.html b/view/frontend/web/template/payment/tpay-form.html index 28afe0c..d9637bf 100644 --- a/view/frontend/web/template/payment/tpay-form.html +++ b/view/frontend/web/template/payment/tpay-form.html @@ -78,7 +78,7 @@
- +