diff --git a/Controller/Direct/Boleto.php b/Controller/Direct/Boleto.php index 3b81c3b..27b3ed6 100644 --- a/Controller/Direct/Boleto.php +++ b/Controller/Direct/Boleto.php @@ -41,6 +41,9 @@ class Boleto extends \Magento\Framework\App\Action\Action /** @var \Magento\Framework\Controller\Result\Json */ protected $result; + /** @var Magento\Sales\Model\Order */ + protected $order; + /** * Boleto payment constructor. * @param \Magento\Framework\App\Action\Context $context @@ -62,12 +65,13 @@ public function __construct( public function execute() { try { + $this->order = $this->loadOrder(); /** @var \UOL\PagSeguro\Model\Direct\BoletoMethod $boleto */ $boleto = new BoletoMethod( $this->_objectManager->create('Magento\Directory\Api\CountryInformationAcquirerInterface'), $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'), $this->_objectManager->create('Magento\Framework\Module\ModuleList'), - $this->loadOrder(), + $this->order, $this->_objectManager->create('UOL\PagSeguro\Helper\Library'), $data = [ 'sender_document' => $this->helperData()->formatDocument($this->getRequest()->getParam('sender_document')), @@ -77,7 +81,9 @@ public function execute() ); return $this->placeOrder($boleto); } catch (\Exception $exception) { - $this->changeOrderHistory('pagseguro_cancelada'); + if (!is_null($this->order)) { + $this->changeOrderHistory('pagseguro_cancelada'); + } $this->clearSession(); return $this->whenError($exception->getMessage()); } @@ -189,7 +195,13 @@ private function baseUrl() */ private function lastRealOrderId() { - return $this->_objectManager->create('\Magento\Checkout\Model\Session')->getLastRealOrder()->getId(); + $lastRealOrderId = $this->_objectManager->create('\Magento\Checkout\Model\Session')->getLastRealOrder()->getId(); + + if (is_null($lastRealOrderId)) { + throw new \Exception("There is no order associated with this session."); + } + + return $lastRealOrderId; } /** @@ -209,10 +221,9 @@ private function session() */ private function changeOrderHistory($status) { - $order = $this->loadOrder(); /** change payment status in magento */ - $order->addStatusToHistory($status, null, true); + $this->order->addStatusToHistory($status, null, true); /** save order */ - $order->save(); + $this->order->save(); } } diff --git a/Controller/Direct/Debit.php b/Controller/Direct/Debit.php index 276ff19..55ed37d 100755 --- a/Controller/Direct/Debit.php +++ b/Controller/Direct/Debit.php @@ -41,6 +41,9 @@ class Debit extends \Magento\Framework\App\Action\Action /** @var \Magento\Framework\Controller\Result\Json */ protected $result; + /** @var Magento\Sales\Model\Order */ + protected $order; + /** * Checkout constructor. * @param \Magento\Framework\App\Action\Context $context @@ -63,11 +66,12 @@ public function __construct( public function execute() { try { + $this->order = $this->loadOrder(); $debit = new DebitMethod( $this->_objectManager->create('Magento\Directory\Api\CountryInformationAcquirerInterface'), $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'), $this->_objectManager->create('Magento\Framework\Module\ModuleList'), - $this->loadOrder(), + $this->order, $this->_objectManager->create('UOL\PagSeguro\Helper\Library'), $data = [ 'sender_document' => $this->helperData()->formatDocument($this->getRequest()->getParam('sender_document')), @@ -78,7 +82,9 @@ public function execute() ); return $this->placeOrder($debit); } catch (\Exception $exception) { - $this->changeOrderHistory('pagseguro_cancelada'); + if (!is_null($this->order)) { + $this->changeOrderHistory('pagseguro_cancelada'); + } $this->clearSession(); return $this->whenError($exception->getMessage()); } @@ -226,8 +232,14 @@ private function baseUrl() * @return string id */ private function lastRealOrderId() - { - return $this->_objectManager->create('\Magento\Checkout\Model\Session')->getLastRealOrder()->getId(); + { + $lastRealOrderId = $this->_objectManager->create('\Magento\Checkout\Model\Session')->getLastRealOrder()->getId(); + + if (is_null($lastRealOrderId)) { + throw new \Exception("There is no order associated with this session."); + } + + return $lastRealOrderId; } /** @@ -247,10 +259,10 @@ private function session() */ private function changeOrderHistory($status) { - $order = $this->loadOrder(); /** change payment status in magento */ - $order->addStatusToHistory($status, null, true); + $this->order->addStatusToHistory($status, null, true); + /** save order */ - $order->save(); + $this->order->save(); } } diff --git a/Controller/Direct/Installments.php b/Controller/Direct/Installments.php index ef898c9..0f9a845 100644 --- a/Controller/Direct/Installments.php +++ b/Controller/Direct/Installments.php @@ -43,6 +43,9 @@ class Installments extends \Magento\Framework\App\Action\Action /** @var \Magento\Framework\Controller\Result\Json */ protected $result; + /** @var Magento\Sales\Model\Order */ + protected $order; + /** * installments constructor * @param \Magento\Framework\App\Action\Context $context @@ -56,6 +59,7 @@ public function __construct( parent::__construct($context); $this->resultJsonFactory = $resultJsonFactory; $this->result = $this->resultJsonFactory->create(); + $this->order = null; } /** @@ -65,10 +69,11 @@ public function __construct( public function execute() { try { + $this->order = $this->loadOrder(); $installments = new InstallmentsMethod( $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'), $this->_objectManager->create('Magento\Framework\Module\ModuleList'), - $this->loadOrder(), + $this->order, $this->_objectManager->create('UOL\PagSeguro\Helper\Library'), $data = [ 'brand' => $this->getRequest()->getParam('credit_card_brand'), @@ -77,9 +82,13 @@ public function execute() ); return $this->place($installments); - } catch (\Exception $exception) { - $this->changeOrderHistory('pagseguro_cancelada'); + } + catch (\Exception $exception) { + if (!is_null($this->order)) { + $this->changeOrderHistory('pagseguro_cancelada'); + } $this->clearSession(); + return $this->whenError($exception->getMessage()); } } @@ -170,10 +179,17 @@ private function baseUrl() * Get last real order id * * @return string id + * @throws \Exception */ private function lastRealOrderId() { - return $this->_objectManager->create('\Magento\Checkout\Model\Session')->getLastRealOrder()->getId(); + $lastRealOrderId = $this->_objectManager->create('\Magento\Checkout\Model\Session')->getLastRealOrder()->getId(); + + if (is_null($lastRealOrderId)) { + throw new \Exception("There is no order associated with this session."); + } + + return $lastRealOrderId; } /** @@ -193,10 +209,10 @@ private function session() */ private function changeOrderHistory($status) { - $order = $this->loadOrder(); /** change payment status in magento */ - $order->addStatusToHistory($status, null, true); + $this->order->addStatusToHistory($status, null, true); + /** save order */ - $order->save(); + $this->order->save(); } } diff --git a/Model/Direct/InstallmentsMethod.php b/Model/Direct/InstallmentsMethod.php index ce5d241..9de98d4 100644 --- a/Model/Direct/InstallmentsMethod.php +++ b/Model/Direct/InstallmentsMethod.php @@ -89,11 +89,11 @@ public function create($amount = false, $maxInstallment = false) try { $this->config(); $this->setOptions($this->getTotalAmount($amount), $this->getBrand()); - $installments = \PagSeguro\Services\Installment::create( $this->_library->getPagSeguroCredentials(), $this->getOptions() ); + return $this->output($installments->getInstallments(), $maxInstallment); } catch (PagSeguroServiceException $exception) { throw $exception; diff --git a/Observer/CreatePagSeguroOrder.php b/Observer/CreatePagSeguroOrder.php index 7587013..1f40f66 100644 --- a/Observer/CreatePagSeguroOrder.php +++ b/Observer/CreatePagSeguroOrder.php @@ -93,7 +93,7 @@ public function __construct( * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) - { + { $order = $observer->getEvent()->getOrder(); //verify pagseguro transaction diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 8d33da2..5ecf53d 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -69,7 +69,12 @@ - Nome do arquivo de log a ser utilizado, com caminho relativo ou absoluto e que tenham permissões de leitura e escrita (Ex.: var/log/pagseguro.log). + + 1 + + + Nome do arquivo de log a ser utilizado, com caminho relativo ou absoluto, que tenha permissões de leitura e escrita (Ex.: var/log/pagseguro.log). + Para que ocorra normalmente a geração de logs é estritamente necessário que o diretório e o arquivo de log configurados tenham permissões de leitura e escrita. diff --git a/view/frontend/templates/direct/payment.phtml b/view/frontend/templates/direct/payment.phtml index 5063dec..20bc73b 100644 --- a/view/frontend/templates/direct/payment.phtml +++ b/view/frontend/templates/direct/payment.phtml @@ -31,24 +31,28 @@
+
+
+
+
@@ -71,6 +75,7 @@ +
+
@@ -90,6 +96,7 @@
+
-
+
Esta compra está sendo feita no Brasil
@@ -119,10 +127,12 @@
+
+
@@ -169,7 +180,7 @@
  • Imprima o boleto e pague no banco
  • Ou pague pela internet utilizando o código de barras do boleto
  • -
  • o prazo de validade do boleto é de 1 dia útil
  • +
  • O prazo de validade do boleto é de 1 dia útil
@@ -191,7 +202,7 @@ function($, VMasker) { ;(function masksInputs($, VMasker, undefined) { VMasker(document.querySelector('.credit-card-mask')).maskPattern('9999 9999 9999 9999'); - VMasker(document.querySelector('.code-card-mask')).maskPattern('999'); + VMasker(document.querySelector('.code-card-mask')).maskPattern('9999'); VMasker(document.querySelector('.date-mask')).maskPattern('99/99/9999'); $('.cpf-cnpj-mask').on('keyup', function() { try { @@ -222,6 +233,7 @@ } }); }($)); + ;(function calcTotal($, undefined) { //Update the total value according with installments $('#card_installments').on('change', function() { @@ -229,6 +241,7 @@ $('#card_total').text('R$ ' + currency); }); }($)); + function loadElements(service, bank, creditCard) { var bank = bank || false; var creditCard = creditCard || false; @@ -260,20 +273,153 @@ //Event buttons methods buy types $('#payment-boleto').on('click', function(e){ e.preventDefault(); - var el = loadElements('boleto'); - PagSeguroDirectPayment.setSessionId(el.sessionCode); - var hash = PagSeguroDirectPayment.getSenderHash(); - WS.Ajax.Direct.Boleto.Payment(el.url, el.orderId, hash, el.document); + if (validateBoletoForm()) { + var el = loadElements('boleto'); + PagSeguroDirectPayment.setSessionId(el.sessionCode); + var hash = PagSeguroDirectPayment.getSenderHash(); + WS.Ajax.Direct.Boleto.Payment(el.url, el.orderId, hash, el.document); + } }); $('#payment-debit').on('click', function(e){ e.preventDefault(); - var el = loadElements('debit', true); - PagSeguroDirectPayment.setSessionId(el.sessionCode); - var hash = PagSeguroDirectPayment.getSenderHash(); - WS.Ajax.Direct.OnlineDebit.Payment(el.url, el.orderId, hash, el.document, el.bank); + if (validateOnlineDebitForm()) { + var el = loadElements('debit', true); + PagSeguroDirectPayment.setSessionId(el.sessionCode); + var hash = PagSeguroDirectPayment.getSenderHash(); + WS.Ajax.Direct.OnlineDebit.Payment(el.url, el.orderId, hash, el.document, el.bank); + } }); $('#payment-credit-card').on('click', function(e){ e.preventDefault(); + if(validateCreditCardForm()) { + createCardToken(); + } + }); + //get and showing brand credit card + function getBrandCard(cardBinVal) { + PagSeguroDirectPayment.setSessionId($('#session-code').attr('data-target')); + PagSeguroDirectPayment.getBrand({ + cardBin: cardBinVal, + internationalMode: true, + success: function(response) { + WS.Ajax.Direct.CreditCard.Installments( + $('#adminurl').attr('data-target'), + $('#order').attr('data-target'), + response.brand.name, + response.brand.international + ); + } + }); + }; + function unmaskField($el, val = true) { + try { + if (val === true) { + var $el = $el.val(); + } + $el = $el.replace(/[^0-9]+/g, '').trim(); + return $el; + } catch(e) { + alert('Ops, algo deu errado! Recarregue a página'); + }; + }; + + /** + * Validate online debit form + * @return true || false + */ + function validateOnlineDebitForm() + { + var formIsValid = true; + + // validate online debit sender document + if (! validateSenderDocument($('#document-debit'), '.document-debit-error-message')) { + formIsValid = false; + } + // validate online debit banklist + if (! validateBank($("#bankList input[type='radio']:checked").length, '#bankList')) { + formIsValid = false; + } + + return formIsValid; + } + + /** + * Validate online debit form bank field + * return true || false + */ + function validateBank(value, validationMessageReference) + { + if (value == 0) { + $(validationMessageReference).parents('.form-group').removeClass('has-success').addClass('has-error'); + return false; + } + $(validationMessageReference).parents('.form-group').removeClass('has-error').addClass('has-success'); + return true; + } + + /** + * Validates boleto form + * @return bool true || false + */ + function validateBoletoForm() + { + var formIsValid = true; + + // validate boleto sender document + if (! validateSenderDocument($('#document-boleto'), '.document-boleto-error-message')) { + formIsValid = false; + } + + return formIsValid; + } + + /** + * Validate the credit card form + * @return true || false + */ + function validateCreditCardForm() + { + var formIsValid = true; + //validate sender document + if (! validateSenderDocument($('#document-credit-card'), '.document-credit-card-error-message')) { + formIsValid = false; + } + //validate card number + if (! validateCardNumber($('#card_num').val(), '.card_num-error-message')) { + formIsValid = false; + } + //validate card name + if (! fieldValidationWithParameter($('#card_holder_name').val(), '.card_holder_name-error-message', '')) { + formIsValid = false; + } + //validate card holder birthdate + if (! validateBirthDate($('#card_holder_birthdate').val(), '.card_holder_birthdate-error-message')) { + formIsValid = false; + } + //validate card expiration month + if (! fieldValidationWithParameter($('#card_expiration_month').val(), '.card_expiration_month-error-message', null)) { + formIsValid = false; + } + //validate card expiration year + if (! fieldValidationWithParameter($('#card_expiration_year').val(), '.card_expiration_year-error-message', null)) { + formIsValid = false; + } + //validate card installments + if (! fieldValidationWithParameter($('#card_installments').val(), '.card_installments-error-message', null)) { + formIsValid = false; + } + //validate card code + if (! validateCardCode($('#card_cod').val(), '.card_cod-error-message')) { + formIsValid = false; + } + + return formIsValid; + }; + + /** + * Call pagseguro api and create credit card token and do the payment + */ + function createCardToken() { PagSeguroDirectPayment.createCardToken({ cardNumber: unmaskField($('#card_num')), brand: $('#card-brand').attr('data-target'), @@ -299,37 +445,125 @@ el.holderBirthdate ); }, 5000); + }, + error: function(response) { + if (response.error === true) { + console.log('erro'); + }; } }); - }); - //get and showing brand credit card - function getBrandCard(cardBinVal) { - PagSeguroDirectPayment.setSessionId($('#session-code').attr('data-target')); - PagSeguroDirectPayment.getBrand({ - cardBin: cardBinVal, - internationalMode: true, - success: function(response) { - WS.Ajax.Direct.CreditCard.Installments( - $('#adminurl').attr('data-target'), - $('#order').attr('data-target'), - response.brand.name, - response.brand.international - ); + } + + /** + * Validate CPF + * @return true | false + */ + function validateCpf(strCPF) { + var sum; + var rest; + sum = 0; + var equal_digits = 1; + for (i = 0; i < strCPF.length - 1; i++) { + if (strCPF.charAt(i) != strCPF.charAt(i + 1)) + { + equal_digits = 0; + break; } - }); + } + if (!equal_digits) { + for (var i = 1; i <= 9; i++) { + sum = sum + parseInt(strCPF.substring(i-1, i)) * (11 - i); + } + rest = sum % 11; + if ((rest == 0) || (rest == 1)) { + rest = 0; + } else { + rest = 11 - rest; + }; + if (rest != parseInt(strCPF.substring(9, 10)) ) { + return false; + } + sum = 0; + for (i = 1; i <= 10; i++) { + sum = sum + parseInt(strCPF.substring(i-1, i)) * (12 - i); + } + rest = sum % 11; + if ((rest == 0) || (rest == 1)) { + rest = 0; + } else { + rest = 11 - rest; + }; + if (rest != parseInt(strCPF.substring(10, 11) ) ) { + return false; + } + return true; + } else { + return false; + } }; - function unmaskField($el, val = true) { - try { - if (val === true) { - var $el = $el.val(); + + /** + * Validate CNPJ + * @return true | false + */ + function validateCnpj(cnpj) { + var numbersVal; + var digits; + var sum; + var i; + var result; + var pos; + var size; + var equal_digits; + equal_digits = 1; + if (cnpj.length < 14 && cnpj.length < 15) { + return false; + } + for (i = 0; i < cnpj.length - 1; i++) { + if (cnpj.charAt(i) != cnpj.charAt(i + 1)) + { + equal_digits = 0; + break; } - $el = $el.replace(/[^0-9]+/g, '').trim(); - return $el; - } catch(e) { - alert('Ops, algo deu errado! Recarregue a página'); - }; + } + if (!equal_digits) { + size = cnpj.length - 2 + numbersVal = cnpj.substring(0,size); + digits = cnpj.substring(size); + sum = 0; + pos = size - 7; + for (i = size; i >= 1; i--) + { + sum += numbersVal.charAt(size - i) * pos--; + if (pos < 2) + pos = 9; + } + result = sum % 11 < 2 ? 0 : 11 - sum % 11; + if (result != digits.charAt(0)) + return false; + size = size + 1; + numbersVal = cnpj.substring(0,size); + sum = 0; + pos = size - 7; + for (i = size; i >= 1; i--) + { + sum += numbersVal.charAt(size - i) * pos--; + if (pos < 2) + pos = 9; + } + result = sum % 11 < 2 ? 0 : 11 - sum % 11; + if (result != digits.charAt(1)) { + return false; + } + return true; + } else { + return false; + } }; + /** + * Get installments when the sixth digit of the credit card is typed + */ ;(function() { var kbinValue, @@ -355,6 +589,187 @@ return false; }); }($)); + + /** + * Show error form validation message / highlight status (in red) + */ + function showFormErrorValidation(validationMessageReference) + { + $(validationMessageReference).parents('.form-group').removeClass('has-success').addClass('has-error'); + $(validationMessageReference).show(); + return false; + } + + /** + * Show success form validation message / highlight status (in green) + */ + function showFormSuccessValidation(validationMessageReference) + { + $(validationMessageReference).parents('.form-group').removeClass('has-error').addClass('has-success'); + $(validationMessageReference).hide(); + return true; + } + + /** + * Validate sender document (CPF or CNPJ) + * @return true || false + */ + function validateSenderDocument(value, validationMessageReference) + { + value = unmaskField(value); + if(value == '' + || (value.length <= 11 && validateCpf(value) === false) + || (value.length > 11 && value.length < 15 && validateCnpj(value) === false) + ) { + return showFormErrorValidation(validationMessageReference); + } else { + return showFormSuccessValidation(validationMessageReference); + } + } + + /** + * Validate credit card number] + * @return + */ + function validateCardNumber(value, validationMessageReference) + { + if (value == '' || value.length !== 19) { + return showFormErrorValidation(validationMessageReference); + } else { + return showFormSuccessValidation(validationMessageReference); + } + } + + /** + * Validate if @value it's the same as the @invalidValueParameter + * @return true || false + */ + function fieldValidationWithParameter(value, validationMessageReference, invalidValueParameter) + { + if (value == invalidValueParameter) { + return showFormErrorValidation(validationMessageReference); + } else { + return showFormSuccessValidation(validationMessageReference); + } + } + + /** + * Validate birthdate (with 'mask') + * @return true || false + */ + function validateBirthDate(value, validationMessageReference) + { + if (value == '' || value.length !== 10) { + return showFormErrorValidation(validationMessageReference); + } else { + return showFormSuccessValidation(validationMessageReference); + } + } + + /** + * Validate credit card code + * @return true || false + */ + function validateCardCode(value, validationMessageReference) + { + if (value == '' || value.length < 3 || value.length > 4 ) { + return showFormErrorValidation(validationMessageReference); + } else { + return showFormSuccessValidation(validationMessageReference); + } + } + + /** + * On blur form validations + */ + + //validate credit card sender cpf/cnpj + ;(function() + { + $('#document-credit-card').on('blur', function (e) { + validateSenderDocument($('#document-credit-card'), '.document-credit-card-error-message'); + }); + }($)); + + //validate card number + ;(function() + { + $('#card_num').on('blur', function (e) { + validateCardNumber($('#card_num').val(), '.card_num-error-message'); + }); + }($)); + + //validate card name + ;(function() + { + $('#card_holder_name').on('blur', function (e) { + fieldValidationWithParameter($('#card_holder_name').val(), '.card_holder_name-error-message', ''); + }); + }($)); + + //validate card holder birthdate + ;(function() + { + $('#card_holder_birthdate').on('blur', function (e) { + validateBirthDate($('#card_holder_birthdate').val(), '.card_holder_birthdate-error-message'); + }); + }($)); + + //validate card expiration month + ;(function() + { + $('#card_expiration_month').on('blur', function (e) { + fieldValidationWithParameter($('#card_expiration_month').val(), '.card_expiration_month-error-message', null); + }); + }($)); + + //validate card expiration year + ;(function() + { + $('#card_expiration_year').on('blur', function (e) { + fieldValidationWithParameter($('#card_expiration_year').val(), '.card_expiration_year-error-message', null); + }); + }($)); + + //validate card installments + ;(function() + { + $('#card_installments').on('blur', function (e) { + fieldValidationWithParameter($('#card_installments').val(), '.card_installments-error-message', null); + }); + }($)); + + //validate card code + ;(function() + { + $('#card_cod').on('blur', function (e) { + validateCardCode($('#card_cod').val(), '.card_cod-error-message'); + }); + }($)); + + //validate online debit sender cpf/cnpj + ;(function() + { + $('#document-debit').on('blur', function (e) { + validateSenderDocument($('#document-debit'), '.document-debit-error-message'); + }); + }($)); + + //validate online debit bank + ;(function() + { + $('#bankList').on('click', function (e) { + validateBank($("#bankList input[type='radio']:checked").length, '#bankList'); + }); + }($)); + + //validate boleto sender cpf/cnpj + ;(function() + { + $('#document-boleto').on('blur', function (e) { + validateSenderDocument($('#document-boleto'), '.document-boleto-error-message'); + }); + }($)); } ); diff --git a/view/frontend/templates/failure.phtml b/view/frontend/templates/failure.phtml index 962afa1..3421790 100644 --- a/view/frontend/templates/failure.phtml +++ b/view/frontend/templates/failure.phtml @@ -1,8 +1,4 @@ - -

Finalizando sua compra com PagSeguro

diff --git a/view/frontend/web/js/public.js b/view/frontend/web/js/public.js index 843db14..97356d1 100644 --- a/view/frontend/web/js/public.js +++ b/view/frontend/web/js/public.js @@ -79,32 +79,35 @@ var WS = { type: 'POST', showLoader: true, }).success(function (response) { + if (response.success) { + //remove if already exists installment options + jQuery('#card_installments option').each(function(){ + if (!jQuery(this).val() === false) { + jQuery(this).remove(); + } + }); - //remove if already exists installment options - jQuery('#card_installments option').each(function(){ - if (!jQuery(this).val() === false) { - jQuery(this).remove(); - } - }); + //add installments options + jQuery.each(response.payload.data.installments, function (i, item) { + jQuery('#card_installments').append(jQuery('