From 21d0158c89fc7c53d96eb4fb662f5a46d76e62eb Mon Sep 17 00:00:00 2001 From: kGablo Date: Fri, 5 Jan 2024 13:06:05 +0100 Subject: [PATCH] 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); } }