From 6d0ca39e39d11b7043198762ae0e8a81693cdeff Mon Sep 17 00:00:00 2001 From: joaocouto-ifthenpay Date: Fri, 21 Apr 2023 11:18:37 +0000 Subject: [PATCH] release: module update from ifthenpay/dev_prestashop_8 (https://github.com/ifthenpay/dev_prestashop_8/commit/1da9565df82e0839d870cc7cec4e05ec72aa632f) --- .../Admin/Payments/CCardAdminOrder.php | 2 +- .../Admin/Payments/MbwayAdminOrder.php | 2 +- .../Admin/Payments/PayshopAdminOrder.php | 2 +- ifthenpay/classes/Base/Payments/CCardBase.php | 4 +- ifthenpay/classes/Base/Payments/MbwayBase.php | 4 +- .../classes/Base/Payments/MultibancoBase.php | 2 +- .../classes/Base/Payments/PayshopBase.php | 4 +- ifthenpay/classes/Callback/CallbackOnline.php | 33 +++--- .../classes/Callback/CallbackProcess.php | 6 +- .../classes/Callback/CallbackStrategy.php | 1 - ifthenpay/classes/Config/IfthenpaySql.php | 14 +-- ifthenpay/classes/Log/IfthenpayLogProcess.php | 4 +- ifthenpay/classes/Models/IfthenpayCCard.php | 8 +- ifthenpay/classes/Models/IfthenpayMbway.php | 8 +- .../classes/Models/IfthenpayMultibanco.php | 2 +- ifthenpay/classes/Models/IfthenpayPayshop.php | 8 +- ifthenpay/classes/Payments/Gateway.php | 12 ++ ifthenpay/classes/Payments/Payment.php | 7 ++ ifthenpay/classes/Request/WebService.php | 8 +- ifthenpay/classes/Utility/Utility.php | 20 +--- .../controllers/front/cancelMbwayOrder.php | 2 +- .../front/resendMbwayNotification.php | 2 +- ifthenpay/ifthenpay.php | 111 ++++++++++++++---- ifthenpay/translations/pt.php | 6 +- ifthenpay/views/templates/admin/config.tpl | 2 +- ifthenpay/views/templates/hook/admin.tpl | 47 +++++++- 26 files changed, 221 insertions(+), 100 deletions(-) diff --git a/ifthenpay/classes/Admin/Payments/CCardAdminOrder.php b/ifthenpay/classes/Admin/Payments/CCardAdminOrder.php index 56a52d3..d661ef4 100644 --- a/ifthenpay/classes/Admin/Payments/CCardAdminOrder.php +++ b/ifthenpay/classes/Admin/Payments/CCardAdminOrder.php @@ -38,7 +38,7 @@ class CCardAdminOrder extends CCardBase implements AdminOrderInterface { public function setSmartyVariables($paymentInDatabase) { - $this->smartyDefaultData->setIdPedido($this->paymentDataFromDb['requestId']); + $this->smartyDefaultData->setIdPedido($this->paymentDataFromDb['transaction_id']); } public function getAdminOrder() diff --git a/ifthenpay/classes/Admin/Payments/MbwayAdminOrder.php b/ifthenpay/classes/Admin/Payments/MbwayAdminOrder.php index bdfa110..db01f4b 100644 --- a/ifthenpay/classes/Admin/Payments/MbwayAdminOrder.php +++ b/ifthenpay/classes/Admin/Payments/MbwayAdminOrder.php @@ -38,7 +38,7 @@ class MbwayAdminOrder extends MbwayBase implements AdminOrderInterface public function setSmartyVariables($paymentInDatabase) { $this->smartyDefaultData->setTelemovel($this->paymentDataFromDb['telemovel']); - $this->smartyDefaultData->setIdPedido($this->paymentDataFromDb['id_transacao']); + $this->smartyDefaultData->setIdPedido($this->paymentDataFromDb['transaction_id']); } public function getAdminOrder() diff --git a/ifthenpay/classes/Admin/Payments/PayshopAdminOrder.php b/ifthenpay/classes/Admin/Payments/PayshopAdminOrder.php index 082b7b8..8848b30 100644 --- a/ifthenpay/classes/Admin/Payments/PayshopAdminOrder.php +++ b/ifthenpay/classes/Admin/Payments/PayshopAdminOrder.php @@ -40,7 +40,7 @@ public function setSmartyVariables($paymentInDatabase) $this->smartyDefaultData->setValidade($this->paymentDataFromDb['validade'] !== '' ? (new \DateTime($this->paymentDataFromDb['validade']))->format('d-m-Y') : '' ); - $this->smartyDefaultData->setIdPedido($this->paymentDataFromDb['id_transacao']); + $this->smartyDefaultData->setIdPedido($this->paymentDataFromDb['transaction_id']); } else { $this->smartyDefaultData->setReferencia($this->paymentGatewayResultData->referencia); $this->smartyDefaultData->setValidade($this->paymentGatewayResultData->validade !== '' ? diff --git a/ifthenpay/classes/Base/Payments/CCardBase.php b/ifthenpay/classes/Base/Payments/CCardBase.php index f7ee24c..718b6f8 100644 --- a/ifthenpay/classes/Base/Payments/CCardBase.php +++ b/ifthenpay/classes/Base/Payments/CCardBase.php @@ -61,7 +61,7 @@ protected function setGatewayBuilderData() protected function saveToDatabase() { - $this->paymentModel->requestId = $this->paymentGatewayResultData->idPedido; + $this->paymentModel->transaction_id = $this->paymentGatewayResultData->idPedido; $this->paymentModel->order_id = $this->paymentDefaultData->order->id; $this->paymentModel->status = 'pending'; $this->paymentModel->save(); @@ -71,7 +71,7 @@ protected function updateDatabase() { /*$this->setPaymentModel('ccard', $this->paymentDataFromDb['id_ifthenpay_ccard']); $this->paymentModel->referencia = $this->paymentGatewayResultData->referencia; - $this->paymentModel->id_transacao = $this->paymentGatewayResultData->idPedido; + $this->paymentModel->transaction_id = $this->paymentGatewayResultData->idPedido; $this->paymentModel->update();*/ } diff --git a/ifthenpay/classes/Base/Payments/MbwayBase.php b/ifthenpay/classes/Base/Payments/MbwayBase.php index 28bc3a5..72ac8f2 100644 --- a/ifthenpay/classes/Base/Payments/MbwayBase.php +++ b/ifthenpay/classes/Base/Payments/MbwayBase.php @@ -82,7 +82,7 @@ protected function setGatewayBuilderData() protected function saveToDatabase() { - $this->paymentModel->id_transacao = $this->paymentGatewayResultData->idPedido; + $this->paymentModel->transaction_id = $this->paymentGatewayResultData->idPedido; $this->paymentModel->telemovel = $this->paymentGatewayResultData->telemovel; $this->paymentModel->order_id = $this->paymentDefaultData->order->id; $this->paymentModel->status = 'pending'; @@ -92,7 +92,7 @@ protected function saveToDatabase() protected function updateDatabase() { $this->setPaymentModel('mbway', $this->paymentDataFromDb['id_ifthenpay_mbway']); - $this->paymentModel->id_transacao = $this->paymentGatewayResultData->idPedido; + $this->paymentModel->transaction_id = $this->paymentGatewayResultData->idPedido; $this->paymentModel->update(); } diff --git a/ifthenpay/classes/Base/Payments/MultibancoBase.php b/ifthenpay/classes/Base/Payments/MultibancoBase.php index 6eb8955..6afa70d 100644 --- a/ifthenpay/classes/Base/Payments/MultibancoBase.php +++ b/ifthenpay/classes/Base/Payments/MultibancoBase.php @@ -49,7 +49,7 @@ protected function saveToDatabase() $this->paymentModel->entidade = $this->paymentGatewayResultData->entidade; $this->paymentModel->referencia = $this->paymentGatewayResultData->referencia; $this->paymentModel->order_id = $this->paymentDefaultData->order->id; - $this->paymentModel->request_id = isset($this->paymentGatewayResultData->idPedido) ? $this->paymentGatewayResultData->idPedido : null; + $this->paymentModel->transaction_id = isset($this->paymentGatewayResultData->idPedido) ? $this->paymentGatewayResultData->idPedido : null; $this->paymentModel->validade = isset($this->paymentGatewayResultData->validade) ? $this->paymentGatewayResultData->validade : null; $this->paymentModel->status = 'pending'; $this->paymentModel->save(); diff --git a/ifthenpay/classes/Base/Payments/PayshopBase.php b/ifthenpay/classes/Base/Payments/PayshopBase.php index 828a262..523c001 100644 --- a/ifthenpay/classes/Base/Payments/PayshopBase.php +++ b/ifthenpay/classes/Base/Payments/PayshopBase.php @@ -41,7 +41,7 @@ protected function setGatewayBuilderData() protected function saveToDatabase() { - $this->paymentModel->id_transacao = $this->paymentGatewayResultData->idPedido; + $this->paymentModel->transaction_id = $this->paymentGatewayResultData->idPedido; $this->paymentModel->referencia = $this->paymentGatewayResultData->referencia; $this->paymentModel->validade = $this->paymentGatewayResultData->validade; $this->paymentModel->order_id = $this->paymentDefaultData->order->id; @@ -53,7 +53,7 @@ protected function updateDatabase() { $this->setPaymentModel('payshop', $this->paymentDataFromDb['id_ifthenpay_payshop']); $this->paymentModel->referencia = $this->paymentGatewayResultData->referencia; - $this->paymentModel->id_transacao = $this->paymentGatewayResultData->idPedido; + $this->paymentModel->transaction_id = $this->paymentGatewayResultData->idPedido; $this->paymentModel->update(); } diff --git a/ifthenpay/classes/Callback/CallbackOnline.php b/ifthenpay/classes/Callback/CallbackOnline.php index 4004abd..81c19b5 100644 --- a/ifthenpay/classes/Callback/CallbackOnline.php +++ b/ifthenpay/classes/Callback/CallbackOnline.php @@ -62,37 +62,41 @@ public function process() $customer = PrestashopModelFactory::buildCustomer((string) $cart->id_customer); $this->setOrder(); $redirectUrl = \Context::getContext()->link->getPageLink('order-confirmation', true) . - '?id_cart=' . $this->request['cartId'] . '&id_module=' . (int)$ifthenpayModule->id . '&id_order=' . $this->order->id . '&key='. - $customer->secure_key . '&paymentOption=ccard'; + '?id_cart=' . $this->request['cartId'] . '&id_module=' . (int)$ifthenpayModule->id . '&id_order=' . $this->order->id . '&key='. + $customer->secure_key . '&paymentOption=ccard'; + if ($this->paymentData['status'] === 'pending') { $paymentStatus = Status::getTokenStatus( Token::decrypt($this->request['qn']) ); + if ($paymentStatus === 'success') { if ($this->request['sk'] !== TokenExtra::encript( - $this->request['id'] . $this->request['amount'] . $this->request['requestId'], \Configuration::get('IFTHENPAY_CCARD_KEY'))) { - throw new \Exception($ifthenpayModule->l('Invalid security token', Utility::getClassName($this))); + $this->request['id'] . $this->request['amount'] . $this->request['requestId'], + \Configuration::get('IFTHENPAY_CCARD_KEY' + ))) { + throw new \Exception($ifthenpayModule->l('Invalid security token', Utility::getClassName($this))); } $orderTotal = floatval(Utility::convertPriceToEuros($this->order)); $requestValor = floatval($this->request['amount']); + if (round($orderTotal, 2) !== round($requestValor, 2)) { IfthenpayLogProcess::addLog('Payment value by credit card not valid - ' . print_r($_GET), IfthenpayLogProcess::ERROR, $this->order->id); \Context::getContext()->controller[] = $ifthenpayModule->l('Payment by credit card not valid', Utility::getClassName($this)); \Context::getContext()->controller->redirectWithNotifications($redirectUrl); } + $this->changeIfthenpayPaymentStatus('paid'); $this->changePrestashopOrderStatus(\Configuration::get('IFTHENPAY_' . \Tools::strtoupper($this->paymentMethod) . '_OS_CONFIRMED')); IfthenpayLogProcess::addLog('Payment by credit card made with success', IfthenpayLogProcess::INFO, $this->order->id); $this->redirectUser('success', $ifthenpayModule, $redirectUrl, $ifthenpayModule->l('Payment by credit card made with success', Utility::getClassName($this))); - } else if($paymentStatus === 'cancel') { - $this->changeIfthenpayPaymentStatus('cancel'); - $this->changePrestashopOrderStatus(\Configuration::get('PS_OS_CANCELED')); - $msg = isset($this->$this->request['error']) - ? ' id:' . $this->request['id'] . ' amount:' . $this->request['amount'] . ' requestId:' . $this->request['requestId'] . 'error: ' . json_encode($this->request['error']) - : 'error data not found'; - - IfthenpayLogProcess::addLog('Payment by credit card canceled by the client', IfthenpayLogProcess::INFO, $this->order->id); - $this->redirectUser('cancel', $ifthenpayModule, $redirectUrl, $ifthenpayModule->l('Payment by credit card canceled', Utility::getClassName($this))); + + } else if ($paymentStatus === 'cancel') { + $this->changeIfthenpayPaymentStatus('cancel'); + $this->changePrestashopOrderStatus(\Configuration::get('PS_OS_CANCELED')); + IfthenpayLogProcess::addLog('Payment by credit card canceled by the client', IfthenpayLogProcess::INFO, $this->order->id); + $this->redirectUser('cancel', $ifthenpayModule, $redirectUrl, $ifthenpayModule->l('Payment by credit card canceled', Utility::getClassName($this))); + } else { $this->changeIfthenpayPaymentStatus('error'); $this->changePrestashopOrderStatus(\Configuration::get('PS_OS_ERROR')); @@ -105,10 +109,10 @@ public function process() } $errorMsg = $errorMsg === '{}' ? 'error data not found' : $errorMsg; - IfthenpayLogProcess::addLog('Error processing credit card payment - ' . $errorMsg, IfthenpayLogProcess::INFO, $this->order->id); $this->redirectUser('error', $ifthenpayModule, $redirectUrl, $ifthenpayModule->l('Error processing credit card payment', Utility::getClassName($this))); } + } else if ($this->paymentData['status'] === 'cancel') { $this->redirectUser('cancel', $ifthenpayModule, $redirectUrl, $ifthenpayModule->l('Order has already been canceled by the customer', Utility::getClassName($this))); } else if ($this->paymentData['status'] === 'error') { @@ -116,6 +120,7 @@ public function process() } else { $this->redirectUser('error', $ifthenpayModule, $redirectUrl, $ifthenpayModule->l('Order has already been paid', Utility::getClassName($this))); } + } catch (\Throwable $th) { $this->changeIfthenpayPaymentStatus('error'); $this->changePrestashopOrderStatus(\Configuration::get('PS_OS_ERROR')); diff --git a/ifthenpay/classes/Callback/CallbackProcess.php b/ifthenpay/classes/Callback/CallbackProcess.php index d40146b..4a27466 100644 --- a/ifthenpay/classes/Callback/CallbackProcess.php +++ b/ifthenpay/classes/Callback/CallbackProcess.php @@ -87,9 +87,9 @@ protected function changeIfthenpayPaymentStatus($status) { $ifthenpayModel = IfthenpayModelFactory::build($this->paymentMethod, $this->paymentData['id_ifthenpay_' . $this->paymentMethod]); - //WORKAROUND: odd behaviour from prestashop model object, it loses the requestId of the order for Ccard, so there is a need to set it in the next two lines - if($this->paymentMethod == 'ccard' && isset($this->paymentData['requestId'])){ - $ifthenpayModel->requestId = $this->paymentData['requestId']; + //WORKAROUND: odd behaviour from prestashop model object, it loses the transaction_id of the order for Ccard, so there is a need to set it in the next two lines + if($this->paymentMethod == 'ccard' && isset($this->paymentData['transaction_id'])){ + $ifthenpayModel->transaction_id = $this->paymentData['transaction_id']; } $ifthenpayModel->status = $status; $ifthenpayModel->update(); diff --git a/ifthenpay/classes/Callback/CallbackStrategy.php b/ifthenpay/classes/Callback/CallbackStrategy.php index f3d7a55..67b7788 100644 --- a/ifthenpay/classes/Callback/CallbackStrategy.php +++ b/ifthenpay/classes/Callback/CallbackStrategy.php @@ -36,7 +36,6 @@ class CallbackStrategy { public function execute($request) { - $request['type'] = 'offline'; if ($request['type'] === 'offline') { return (new CallbackOffline())->setPaymentMethod($request['payment'])->setRequest($request)->process(); } else if ($request['type'] === 'online') { diff --git a/ifthenpay/classes/Config/IfthenpaySql.php b/ifthenpay/classes/Config/IfthenpaySql.php index 8c376a2..63d2f56 100644 --- a/ifthenpay/classes/Config/IfthenpaySql.php +++ b/ifthenpay/classes/Config/IfthenpaySql.php @@ -43,7 +43,7 @@ class IfthenpaySql implements InstallerInterface `entidade` varchar(5) NOT NULL, `referencia` varchar(9) NOT NULL, `validade` varchar(16), - `request_id` varchar(50), + `transaction_id` varchar(50), `order_id` int(11) NOT NULL, `status` varchar(50) NOT NULL, PRIMARY KEY (`id_ifthenpay_multibanco`), @@ -51,30 +51,30 @@ class IfthenpaySql implements InstallerInterface ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;', 'mbway' => 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'ifthenpay_mbway` ( `id_ifthenpay_mbway` int(10) unsigned NOT NULL auto_increment, - `id_transacao` varchar(20) NOT NULL, + `transaction_id` varchar(20) NOT NULL, `telemovel` varchar(20) NOT NULL, `order_id` int(11) NOT NULL, `status` varchar(50) NOT NULL, PRIMARY KEY (`id_ifthenpay_mbway`), - INDEX `idTransacao` (`id_transacao`) + INDEX `transaction_id` (`transaction_id`) ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;', 'payshop' => 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'ifthenpay_payshop` ( `id_ifthenpay_payshop` int(10) unsigned NOT NULL auto_increment, - `id_transacao` varchar(20) NOT NULL, + `transaction_id` varchar(20) NOT NULL, `referencia` varchar(13) NOT NULL, `validade` varchar(8) NOT NULL, `order_id` int(11) NOT NULL, `status` varchar(50) NOT NULL, PRIMARY KEY (`id_ifthenpay_payshop`), - INDEX `idTransacao` (`id_transacao`) + INDEX `transaction_id` (`transaction_id`) ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;', 'ccard' => 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'ifthenpay_ccard` ( `id_ifthenpay_ccard` int(10) unsigned NOT NULL auto_increment, - `requestId` varchar(50) NOT NULL, + `transaction_id` varchar(50) NOT NULL, `order_id` int(11) NOT NULL, `status` varchar(50) NOT NULL, PRIMARY KEY (`id_ifthenpay_ccard`), - INDEX `requestId` (`requestId`) + INDEX `transaction_id` (`transaction_id`) ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;', ]; diff --git a/ifthenpay/classes/Log/IfthenpayLogProcess.php b/ifthenpay/classes/Log/IfthenpayLogProcess.php index cf34784..949e02e 100644 --- a/ifthenpay/classes/Log/IfthenpayLogProcess.php +++ b/ifthenpay/classes/Log/IfthenpayLogProcess.php @@ -33,9 +33,9 @@ class IfthenpayLogProcess { - const ERROR = 'error'; - const INFO = 'info'; + const WARNING = 'warning'; + const ERROR = 'error'; public static function addLog($message, $type, $orderId) { diff --git a/ifthenpay/classes/Models/IfthenpayCCard.php b/ifthenpay/classes/Models/IfthenpayCCard.php index 7861ab9..4db87bb 100644 --- a/ifthenpay/classes/Models/IfthenpayCCard.php +++ b/ifthenpay/classes/Models/IfthenpayCCard.php @@ -36,7 +36,7 @@ class IfthenpayCCard extends \ObjectModel implements PaymentModelInterface { public $id; public $id_ifthenpay_ccard; - public $id_transacao; + public $transaction_id; public $referencia; public $validade; public $order_id; @@ -47,7 +47,7 @@ class IfthenpayCCard extends \ObjectModel implements PaymentModelInterface 'multilang' => false, 'multishop' => true, 'fields' => [ - 'requestId' => [ + 'transaction_id' => [ 'type' => self::TYPE_STRING, 'required' => true, 'validate' => 'isString', @@ -87,10 +87,10 @@ public static function getByOrderId($orderId) } } - public static function getCCardByRequestId($requestId) + public static function getCCardByRequestId($transaction_id) { $rowOrder = \Db::getInstance() - ->executeS('SELECT * FROM ' . _DB_PREFIX_ . self::$definition['table'] . ' WHERE (requestId = ' . '\'' . \pSQL((string) $requestId) . '\') '); + ->executeS('SELECT * FROM ' . _DB_PREFIX_ . self::$definition['table'] . ' WHERE (transaction_id = ' . '\'' . \pSQL((string) $transaction_id) . '\') '); if (is_array($rowOrder)) { return $rowOrder[0]; } else { diff --git a/ifthenpay/classes/Models/IfthenpayMbway.php b/ifthenpay/classes/Models/IfthenpayMbway.php index 578e878..a810447 100644 --- a/ifthenpay/classes/Models/IfthenpayMbway.php +++ b/ifthenpay/classes/Models/IfthenpayMbway.php @@ -36,7 +36,7 @@ class IfthenpayMbway extends \ObjectModel implements PaymentModelInterface { public $id; public $id_ifthenpay_mbway; - public $id_transacao; + public $transaction_id; public $telemovel; public $order_id; @@ -46,7 +46,7 @@ class IfthenpayMbway extends \ObjectModel implements PaymentModelInterface 'multilang' => false, 'multishop' => true, 'fields' => [ - 'id_transacao' => [ + 'transaction_id' => [ 'type' => self::TYPE_STRING, 'required' => true, 'validate' => 'isString', @@ -92,10 +92,10 @@ public static function getByOrderId($orderId) } } - public static function getMbwayByIdTransacao($idTransacao) + public static function getMbwayByIdTransacao($transaction_id) { $rowOrder = \Db::getInstance() - ->executeS('SELECT * FROM ' . _DB_PREFIX_ . self::$definition['table'] . ' WHERE (id_transacao = ' . '\'' . \pSQL($idTransacao) . '\') '); + ->executeS('SELECT * FROM ' . _DB_PREFIX_ . self::$definition['table'] . ' WHERE (transaction_id = ' . '\'' . \pSQL($transaction_id) . '\') '); if (is_array($rowOrder) && !empty($rowOrder)) { return $rowOrder[0]; diff --git a/ifthenpay/classes/Models/IfthenpayMultibanco.php b/ifthenpay/classes/Models/IfthenpayMultibanco.php index 423440e..94b5c78 100644 --- a/ifthenpay/classes/Models/IfthenpayMultibanco.php +++ b/ifthenpay/classes/Models/IfthenpayMultibanco.php @@ -64,7 +64,7 @@ class IfthenpayMultibanco extends \ObjectModel implements PaymentModelInterface 'validate' => 'isString', 'size' => 16 ], - 'request_id' => [ + 'transaction_id' => [ 'type' => self::TYPE_STRING, 'required' => false, 'validate' => 'isString', diff --git a/ifthenpay/classes/Models/IfthenpayPayshop.php b/ifthenpay/classes/Models/IfthenpayPayshop.php index cc42581..3fcf900 100644 --- a/ifthenpay/classes/Models/IfthenpayPayshop.php +++ b/ifthenpay/classes/Models/IfthenpayPayshop.php @@ -36,7 +36,7 @@ class IfthenpayPayshop extends \ObjectModel implements PaymentModelInterface { public $id; public $id_ifthenpay_payshop; - public $id_transacao; + public $transaction_id; public $referencia; public $validade; public $order_id; @@ -47,7 +47,7 @@ class IfthenpayPayshop extends \ObjectModel implements PaymentModelInterface 'multilang' => false, 'multishop' => true, 'fields' => [ - 'id_transacao' => [ + 'transaction_id' => [ 'type' => self::TYPE_STRING, 'required' => true, 'validate' => 'isString', @@ -98,10 +98,10 @@ public static function getByOrderId($orderId) } } - public static function getPayshopByIdTransacao($idTransacao) + public static function getPayshopByIdTransacao($transaction_id) { $rowOrder = \Db::getInstance() - ->executeS('SELECT * FROM ' . _DB_PREFIX_ . self::$definition['table'] . ' WHERE (id_transacao = ' . '\'' . \pSQL((string) $idTransacao) . '\') '); + ->executeS('SELECT * FROM ' . _DB_PREFIX_ . self::$definition['table'] . ' WHERE (transaction_id = ' . '\'' . \pSQL((string) $transaction_id) . '\') '); if (is_array($rowOrder)) { return $rowOrder[0]; } else { diff --git a/ifthenpay/classes/Payments/Gateway.php b/ifthenpay/classes/Payments/Gateway.php index 39cc77b..8180d2e 100644 --- a/ifthenpay/classes/Payments/Gateway.php +++ b/ifthenpay/classes/Payments/Gateway.php @@ -33,6 +33,7 @@ use PrestaShop\Module\Ifthenpay\Factory\Payment\PaymentFactory; use PrestaShop\Module\Ifthenpay\Factory\Request\RequestFactory; use PrestaShop\Module\Ifthenpay\Builders\GatewayDataBuilder; +use PrestaShop\Module\Ifthenpay\Log\IfthenpayLogProcess; class Gateway { @@ -183,4 +184,15 @@ public function execute($paymentMethod, $data, $orderId, $valor) $paymentMethod = PaymentFactory::build($paymentMethod, $data, $orderId, $valor, $this->webservice); return $paymentMethod->buy(); } + + public function refund($body) + { + $refund = $this->webservice->postRequest( + 'http://ifthenpay.com/api/endpoint/payments/refund', + $body, + true + )->getResponseJson(); + + return $refund; + } } diff --git a/ifthenpay/classes/Payments/Payment.php b/ifthenpay/classes/Payments/Payment.php index 6ed0fca..fb48b68 100644 --- a/ifthenpay/classes/Payments/Payment.php +++ b/ifthenpay/classes/Payments/Payment.php @@ -50,6 +50,13 @@ public function __construct($orderId, $valor) protected function formatNumber($number) { + /** + * Verifies if $number is an integer + */ + if (ctype_digit($number)) { + $number = number_format($number, 2); + } + $verifySepDecimal = number_format(99, 2); $valorTmp = $number; diff --git a/ifthenpay/classes/Request/WebService.php b/ifthenpay/classes/Request/WebService.php index 9bf927f..5eea1d8 100644 --- a/ifthenpay/classes/Request/WebService.php +++ b/ifthenpay/classes/Request/WebService.php @@ -62,20 +62,20 @@ public function getResponseJson() return json_decode(json_encode(json_decode((string) $this->response->getBody())), true); } - public function postRequest($url, $data, $jsonContentType = false) + public function postRequest($url, $data, $json = false) { try { $this->response = $this->client->post( $url, - $jsonContentType ? ['json' => $data] : - ['form_params' => $data] + $json ? ['json' => $data] : ['form_params' => $data] ); return $this; } catch (\Throwable $th) { throw $th; } } - + + // TODO: Verify if this method is deprecated public function getRequest($url, $data = []) { try { diff --git a/ifthenpay/classes/Utility/Utility.php b/ifthenpay/classes/Utility/Utility.php index 6f5ba77..1cfe1fb 100644 --- a/ifthenpay/classes/Utility/Utility.php +++ b/ifthenpay/classes/Utility/Utility.php @@ -84,16 +84,8 @@ public static function unsetPrestashopCookie($cookieName) public static function getFormatedPrice($order) { $price = $order->getOrdersTotalPaid(); - if (version_compare(_PS_VERSION_, '1.7.6', '<')) { - return \Tools::displayPrice( - $price, - PrestashopModelFactory::buildCurrency((string) $order->id_currency), - false - ); - } else { - return \Context::getContext()->currentLocale - ->formatPrice($price, \Context::getContext()->currency->iso_code); - } + return \Context::getContext() + ->currentLocale->formatPrice($price, \Context::getContext()->currency->iso_code); } public static function getMailTranslationString($paymentType, $type = '') @@ -108,8 +100,9 @@ public static function getMailTranslationString($paymentType, $type = '') public static function convertPriceToEuros($order) { $actualCurrency = PrestashopModelFactory::buildCurrency((string) $order->id_currency); - $ammount = $order->getOrdersTotalPaid(); - //convert ammount to euros if currency is no euros + $amount = $order->getOrdersTotalPaid(); + + // Convert amount to EUR if currency is different if ($actualCurrency->iso_code !== 'EUR') { return \Tools::convertPriceFull( $order->getOrdersTotalPaid(), @@ -117,7 +110,7 @@ public static function convertPriceToEuros($order) PrestashopModelFactory::buildCurrency((string) \Currency::getIdByIsoCode('EUR')) ); } - return $ammount; + return $amount; } public static function getClassName($class) @@ -130,7 +123,6 @@ public static function numberToPagination($rows, $page) $range = 50; $pages = ceil($rows / $range); - $html = ''; if ($pages) { $htmlList = ''; diff --git a/ifthenpay/controllers/front/cancelMbwayOrder.php b/ifthenpay/controllers/front/cancelMbwayOrder.php index 734130a..981259c 100644 --- a/ifthenpay/controllers/front/cancelMbwayOrder.php +++ b/ifthenpay/controllers/front/cancelMbwayOrder.php @@ -56,7 +56,7 @@ public function displayAjax() $orderId = Tools::getValue('orderId'); $mbwayKey = Configuration::get('IFTHENPAY_MBWAY_KEY'); $paymentData = IfthenpayModelFactory::build('mbway')->getByOrderId((string) $orderId); - $requestId = $paymentData['id_transacao']; + $requestId = $paymentData['transaction_id']; $request = $this->webservice->getRequest( diff --git a/ifthenpay/controllers/front/resendMbwayNotification.php b/ifthenpay/controllers/front/resendMbwayNotification.php index a05b9c2..5d46e9d 100644 --- a/ifthenpay/controllers/front/resendMbwayNotification.php +++ b/ifthenpay/controllers/front/resendMbwayNotification.php @@ -65,7 +65,7 @@ public function initContent() $ifthenpayMbway = IfthenpayModelFactory::build('mbway'); $mbwayDB = $ifthenpayMbway->getByOrderId($orderId); $ifthenpayMbway = IfthenpayModelFactory::build('mbway', $mbwayDB['id_ifthenpay_mbway']); - $ifthenpayMbway->id_transacao = $gatewayResult->idPedido; + $ifthenpayMbway->transaction_id = $gatewayResult->idPedido; $ifthenpayMbway->update(); Utility::setPrestashopCookie('mbwayResendNotificationSent', true); IfthenpayLogProcess::addLog('Resend MB WAY notification (front-end) with success', IfthenpayLogProcess::INFO, (int) $orderId); diff --git a/ifthenpay/ifthenpay.php b/ifthenpay/ifthenpay.php index 33c081c..f307c85 100644 --- a/ifthenpay/ifthenpay.php +++ b/ifthenpay/ifthenpay.php @@ -87,7 +87,7 @@ public function __construct() /** * Don't forget to create update methods if needed: - * http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update + * https://devdocs.prestashop-project.org/8/modules/creation/enabling-auto-update/ */ public function install() { @@ -101,9 +101,9 @@ public function install() } if ( !parent::install() || !$this->registerHook('payment') || !$this->registerHook('paymentOptions') || - !$this->registerHook('paymentReturn') || !$this->registerHook('displayAdminOrder') || - !$this->registerHook('displayOrderDetail') || !$this->registerHook('header') || - !$this->registerHook('actionAdminControllerSetMedia') || !$this->registerHook('actionFrontControllerSetMedia') || !$this->registerHook('displayBackOfficeHeader') + !$this->registerHook('paymentReturn') || !$this->registerHook('displayAdminOrder') || !$this->registerHook('displayOrderDetail') || + !$this->registerHook('header') || !$this->registerHook('actionAdminControllerSetMedia') || !$this->registerHook('actionFrontControllerSetMedia') || + !$this->registerHook('displayBackOfficeHeader') || !$this->registerHook('actionProductCancel') ) { return false; } @@ -139,7 +139,7 @@ public function uninstall() /** * Load the configuration form - * this is the first configuration page, where it shows all four payment methods and update status + * this is the first configuration page, where it shows all payment methods and update status */ public function getContent() { @@ -190,7 +190,6 @@ public function getContent() /** * Create the form that will be displayed in the configuration of your module. - * this is the first configuration page, where it shows all four payment methods and update status */ protected function renderForm() { @@ -216,15 +215,19 @@ protected function renderForm() return $helper->generateForm(array($this->getConfigForm())); } + /** * Create the structure of your form. - * this is the first configuration page, where it shows all four payment methods and update status + * This is the first configuration page, where it shows all payment methods and update status. */ protected function getConfigForm() { $form = []; - // if there is no backoffice key in database...ask for one + /** + * If there is no backofficeKey stored in the DB, + * the user will be asked to enter one. + */ if (!$this->ifthenpayConfig['IFTHENPAY_BACKOFFICE_KEY']) { $form = [ @@ -248,9 +251,10 @@ protected function getConfigForm() return $form; } - // if already has backoffice key then show config for available payment methods - - + /** + * If there is already a backofficeKey inserted, + * then the module configuration menu will appear. + */ $form = [ 'form' => [ 'input' => [ @@ -282,7 +286,9 @@ protected function getConfigForm() ], ]; - // get available payment methods + /** + * Get available payment methods + */ $ifthenpayUserPaymentMethods = (array) unserialize( $this->ifthenpayConfig['IFTHENPAY_USER_PAYMENT_METHODS'] ); @@ -337,8 +343,11 @@ protected function getConfigForm() ]; } - // check for mb dynamic references and if not create "request" button + /** + * Check MB Dynamic References. + * Otherwise, a "request" button must be created. + */ $accounts = unserialize(Configuration::get('IFTHENPAY_USER_ACCOUNT')); if ($accounts) { @@ -391,10 +400,9 @@ protected function getConfigForm() return $form; } - /** - * Set values for the inputs. - * this is the first configuration page, where it shows all four payment methods and update status - */ + /** + * Set values for the inputs. + */ protected function getConfigFormValues() { $formValues = array( @@ -585,14 +593,16 @@ private function getOrderedPaymentMethods() $paymentMethods[$paymentMethod] = $order; } - // order by value + /** + * Sort by value + */ asort($paymentMethods, 1); return array_keys($paymentMethods); } /** - * Return payment options available for PS 1.7+ + * Return payment options available for Prestashop 8 * * @param array Hook parameters * @@ -800,8 +810,6 @@ private function isAboveMinValue($params, $paymentMethod) - - public function hookPaymentReturn($params) { if (!$this->active) { @@ -864,7 +872,7 @@ public function hookPaymentReturn($params) ); return $this->display(__FILE__, 'payment_return.tpl'); } - //return $this->fetch('module:ifthenpay/views/templates/hook/payment_return.tpl'); + // return $this->fetch('module:ifthenpay/views/templates/hook/payment_return.tpl'); return $this->display(__FILE__, 'payment_return.tpl'); } } @@ -875,10 +883,9 @@ public function hookdisplayAdminOrder($params) return; } - $order = PrestashopModelFactory::buildOrder((string) $params['id_order']); $message = ''; + $order = PrestashopModelFactory::buildOrder((string) $params['id_order']); $ifthenpayGateway = GatewayFactory::build('gateway'); - $previousModulePaymentMethod = $ifthenpayGateway->checkIfPaymentMethodIsPreviousModule($order->payment); if ($previousModulePaymentMethod) { @@ -919,11 +926,17 @@ public function hookdisplayAdminOrder($params) $this, $message )->execute(); + + $array = (array) unserialize($this->ifthenpayConfig['IFTHENPAY_USER_PAYMENT_METHODS']); + $this->smarty->assign($ifthenpayAdminOrder->getSmartyVariables()->toArray()); + $this->smarty->assign('backofficeKey', $this->ifthenpayConfig['IFTHENPAY_BACKOFFICE_KEY']); + $this->smarty->assign('paymentMethods', (array) unserialize($this->ifthenpayConfig['IFTHENPAY_USER_PAYMENT_METHODS'])); // commented out since it would quickly add records to table unnecessarily // IfthenpayLogProcess::addLog('Payment order successfully withdrawn (hookdisplayAdminOrder).', IfthenpayLogProcess::INFO, $params['id_order']); return $this->display(__FILE__, 'admin.tpl'); + } catch (\Throwable $th) { IfthenpayLogProcess::addLog('Error getting admin order payment details (hookdisplayAdminOrder) possible assignment of payment method that is not yet saved - ' . $th->getMessage(), IfthenpayLogProcess::ERROR, $params['id_order']); return $this->displayError($this->l('An error occurred while getting payment method information, check logs for more details')); @@ -943,11 +956,13 @@ public function hookActionAdminControllerSetMedia() $this->context->controller->addJS($this->_path . 'views/js/adminAccountSettingsPage' . $versioning . '.js'); $this->context->controller->addCSS($this->_path . 'views/css/ifthenpayConfig' . $versioning . '.css'); + Media::addJsDef( [ 'controllerUrl' => $this->context->link->getAdminLink('AdminIfthenpayResetAccount'), ] ); + } elseif ( Tools::getValue('controller') === 'AdminOrders' && $this->ifthenpayConfig['IFTHENPAY_USER_PAYMENT_METHODS'] @@ -1076,4 +1091,52 @@ public function hookDisplayBackOfficeHeader($params) ConfigFactory::buildCancelMultibancoOrder()->cancelOrder(); } } + + public function hookActionProductCancel($params) + { + if (!$this->active || !Validate::isLoadedObject($params['order'])) { + return false; + } + + $orderID = (int) $params['order']->id; + $payment = $params['order']->payment; + $router = $this->get('router'); + $paymentData = IfthenpayModelFactory::build($payment)->getByOrderId((string) $orderID); + + if ($payment == 'payshop' || $payment == 'multibanco') { + + $type = 'warning'; + $msg = 'It is not possible to proceed with the refund through '.$payment; + + IfthenpayLogProcess::addLog($msg, IfthenpayLogProcess::WARNING, $orderID); + $this->get('session')->getFlashBag()->add($type, $msg); + Tools::redirectAdmin($router->generate('admin_orders_view', ['orderId'=> $orderID])); + } + + $ifthenpayGateway = GatewayFactory::build('gateway'); + + $body = [ + 'backofficekey' => $this->ifthenpayConfig['IFTHENPAY_BACKOFFICE_KEY'], + 'requestId' => $paymentData['transaction_id'], + 'amount' => $params['cancel_amount'] + ]; + + $response = $ifthenpayGateway->refund($body); + + if($response['Code'] != 1) { + + $type = 'error'; + IfthenpayLogProcess::addLog($response['Message'], IfthenpayLogProcess::ERROR, $orderID); + $this->get('session')->getFlashBag()->add($type, $response['Message']); + Tools::redirectAdmin($router->generate('admin_orders_view', ['orderId'=> $orderID])); + } + else { + $new_history = PrestashopModelFactory::buildOrderHistory(); + $new_history->id_order = $orderID; + $new_history->changeIdOrderState((int) Configuration::get('PS_OS_REFUND'), $orderID); + $new_history->addWithemail(); + IfthenpayLogProcess::addLog($response['Message'], IfthenpayLogProcess::INFO, $orderID); + } + + } } diff --git a/ifthenpay/translations/pt.php b/ifthenpay/translations/pt.php index 8b7e1c6..59130c2 100644 --- a/ifthenpay/translations/pt.php +++ b/ifthenpay/translations/pt.php @@ -85,9 +85,9 @@ $_MODULE['<{ifthenpay}prestashop>config_160228cd93e04943afb5a0851dca6a21'] = 'Pagamentos por Multibanco, MB WAY, PAYSHOP e Cartão de Crédito têm vantagens para o seu negócio'; $_MODULE['<{ifthenpay}prestashop>config_15c5438becb339d5b59e1d7d5c806c4d'] = 'Sem custos para o utilizador'; $_MODULE['<{ifthenpay}prestashop>config_1efb0f79ed270c023a8c7e0cc19e9f90'] = 'Pagamentos 24 horas por dia com notificações imediatas'; -$_MODULE['<{ifthenpay}prestashop>config_6e4391fe18602f27ecc98473600c4b61'] = 'Pagamentos seguros por multibanco, MB WAY, PAYSHOP e Cartão de Crédito'; +$_MODULE['<{ifthenpay}prestashop>config_6e4391fe18602f27ecc98473600c4b61'] = 'Pagamentos seguros por Multibanco, MB WAY, PAYSHOP e Cartão de Crédito'; $_MODULE['<{ifthenpay}prestashop>config_72e96c106c7b1c3f54960881c6b04a39'] = 'Proteção dos dados do utilizador, sem necessidade de introduzir dados bancários online'; -$_MODULE['<{ifthenpay}prestashop>config_e1e43f94a2977e58f85b268d6b9dc347'] = 'Pagamento em multicanal: terminal multibanco, home-banking, MB Spot, telemóvel, TPA, MB WAY, Agente PAYSHOP ou Loja CTT '; +$_MODULE['<{ifthenpay}prestashop>config_e1e43f94a2977e58f85b268d6b9dc347'] = 'Pagamento em multicanal: terminal Multibanco, Homebanking, MB Spot, telemóvel, TPA, MB WAY, Agente PAYSHOP ou Loja CTT '; $_MODULE['<{ifthenpay}prestashop>config_3b0271438e9545336fec51eb323781e2'] = 'Diretamente da conta bancária dos utilizadores sem necessidade de criar ou carregar previamente outro tipo de contas (wallets)'; $_MODULE['<{ifthenpay}prestashop>config_b05de066de4d80ea93d6715e0b9fb60e'] = 'O \"Checkout\" nas lojas online é efetuado integralmente dentro do site do vendedor'; $_MODULE['<{ifthenpay}prestashop>config_caae9ff05bff71e0ad0cbc4a1903c51e'] = 'Controlo das vendas no smartphone através da nossa app gratuita'; @@ -99,7 +99,7 @@ $_MODULE['<{ifthenpay}prestashop>config_526d688f37a86d3c3f27d0c5016eb71d'] = 'Reset'; $_MODULE['<{ifthenpay}prestashop>config_935cc0d7ffe68032534a1d822ff1c7be'] = 'Nova atualização disponível!'; $_MODULE['<{ifthenpay}prestashop>config_7a4c8c666aeb0fdd740eb648bc83e051'] = 'Descarregar atualização de módulo'; -$_MODULE['<{ifthenpay}prestashop>config_3c2cc0108255326e07da1e0b9c098689'] = 'Versão'; +$_MODULE['<{ifthenpay}prestashop>config_3c2cc0108255326e07da1e0b9c098689'] = 'Versão '; $_MODULE['<{ifthenpay}prestashop>config_39378e4ed45f9d286ae667780ad270b7'] = 'O seu módulo está atualizado!'; $_MODULE['<{ifthenpay}prestashop>paymentmethodsetup_1ebf6b62a890e57840d9eed25d069624'] = 'Método de pagamento %s'; $_MODULE['<{ifthenpay}prestashop>paymentmethodsetup_7ad8d66a3bc93f5ebaebc0092882fcb4'] = 'Este módulo permite o pagamento seguro por %s'; diff --git a/ifthenpay/views/templates/admin/config.tpl b/ifthenpay/views/templates/admin/config.tpl index 50ff8c7..88873b5 100644 --- a/ifthenpay/views/templates/admin/config.tpl +++ b/ifthenpay/views/templates/admin/config.tpl @@ -63,7 +63,7 @@
{l s='Protected user data, no need to enter bank or card information' mod='ifthenpay'}
  • -
    {l s='Multichannel payments: Multibanco ATMs, Homebanking,
    mobile phones, POS, MB SPOT network, MB WAY, PAYSHOP network, Post Offices' mod='ifthenpay'} +
    {l s='Multichannel payments: Multibanco ATMs, Homebanking, mobile phones, POS, MB SPOT network, MB WAY, PAYSHOP network, Post Offices' mod='ifthenpay'}
  • diff --git a/ifthenpay/views/templates/hook/admin.tpl b/ifthenpay/views/templates/hook/admin.tpl index 5b8b0d3..25e8803 100644 --- a/ifthenpay/views/templates/hook/admin.tpl +++ b/ifthenpay/views/templates/hook/admin.tpl @@ -95,7 +95,7 @@ {else}