diff --git a/Api/Data/CardTypeTransactionInterface.php b/Api/Data/CardTypeTransactionInterface.php new file mode 100644 index 0000000..b487885 --- /dev/null +++ b/Api/Data/CardTypeTransactionInterface.php @@ -0,0 +1,44 @@ + + * @license See LICENSE for license details. + */ + +declare(strict_types=1); + +namespace PagBank\PaymentMagento\Api\Data; + +/** + * Interface Card Type Transaction - Data Card Type Transaction. + * + * @api + * + * @since 100.0.1 + */ +interface CardTypeTransactionInterface +{ + /** + * @const string + */ + public const PAGBANK_CARD_TYPE_TRANSACTION = 'card_type_transaction'; + + /** + * Get Card Type Transaction. + * + * @return string + */ + public function getCardTypeTransaction(); + + /** + * Set Card Type Transaction. + * + * @param string $cardTypeTransaction + * + * @return void + */ + public function setCardTypeTransaction($cardTypeTransaction); +} diff --git a/Api/GuestListInstallmentsManagementInterface.php b/Api/GuestListInstallmentsManagementInterface.php index db2ed5e..995df3c 100644 --- a/Api/GuestListInstallmentsManagementInterface.php +++ b/Api/GuestListInstallmentsManagementInterface.php @@ -22,13 +22,15 @@ interface GuestListInstallmentsManagementInterface /** * Generate the list installments by credit card. * - * @param string $cartId - * @param \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + * @param string $cartId + * @param \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + * @param \PagBank\PaymentMagento\Api\Data\CardTypeTransactionInterface $cardTypeTransaction * * @return mixed */ public function generateListInstallments( $cartId, - \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin, + \PagBank\PaymentMagento\Api\Data\CardTypeTransactionInterface $cardTypeTransaction = null ); } diff --git a/Api/ListInstallmentsManagementInterface.php b/Api/ListInstallmentsManagementInterface.php index 0115fe0..d796859 100644 --- a/Api/ListInstallmentsManagementInterface.php +++ b/Api/ListInstallmentsManagementInterface.php @@ -22,13 +22,15 @@ interface ListInstallmentsManagementInterface /** * Generate the list installments by credit card number. * - * @param int $cartId - * @param \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + * @param int $cartId + * @param \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + * @param \PagBank\PaymentMagento\Api\Data\CardTypeTransactionInterface $cardTypeTransaction * * @return mixed */ public function generateListInstallments( $cartId, - \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin, + \PagBank\PaymentMagento\Api\Data\CardTypeTransactionInterface $cardTypeTransaction = null ); } diff --git a/Block/Adminhtml/System/Config/Apps.php b/Block/Adminhtml/System/Config/Apps.php new file mode 100644 index 0000000..1b12328 --- /dev/null +++ b/Block/Adminhtml/System/Config/Apps.php @@ -0,0 +1,67 @@ + + * @license See LICENSE for license details. + */ + +namespace PagBank\PaymentMagento\Block\Adminhtml\System\Config; + +use Magento\Backend\Block\Template\Context; +use Magento\Config\Block\System\Config\Form\Field; +use Magento\Framework\Data\Form\Element\AbstractElement; + +/** + * Class Apps - Type apps. + * + * @SuppressWarnings(PHPMD.CamelCaseMethodName) + * @SuppressWarnings(PHPMD.CamelCasePropertyName) + */ +class Apps extends Field +{ + /** + * Template oAuth. + */ + public const TEMPLATE = 'PagBank_PaymentMagento::system/config/apps.phtml'; + + /** + * @param Context $context + */ + public function __construct( + Context $context + ) { + parent::__construct($context); + $this->setTemplate(self::TEMPLATE); + } + + /** + * Override render method to remove label and td elements + * + * @param AbstractElement $element + */ + public function render(AbstractElement $element) + { + $html = ''; + $html .= ''; + $html .= $this->_getElementHtml($element); + $html .= ''; + $html .= ''; + return $html; + } + + /** + * Render the field HTML + * + * @param AbstractElement $element + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * @SuppressWarnings(PHPMD.CamelCaseMethodName) + */ + protected function _getElementHtml(AbstractElement $element) + { + return $this->toHtml(); + } +} diff --git a/Block/Adminhtml/System/Config/Oauth.php b/Block/Adminhtml/System/Config/Oauth.php index 18e7b62..bafc25b 100644 --- a/Block/Adminhtml/System/Config/Oauth.php +++ b/Block/Adminhtml/System/Config/Oauth.php @@ -247,6 +247,20 @@ public function getUrlToConnect() $appId = Config::APP_ID_SANDBOX; } + if ($this->config->getTypeApp($storeId) === 'd14') { + $appId = Config::APP_ID_FOURTEEN_PRODUCTION; + if ($this->config->getEnvironmentMode($storeId) === Config::ENVIRONMENT_SANDBOX) { + $appId = Config::APP_ID_FOURTEEN_SANDBOX; + } + } + + if ($this->config->getTypeApp($storeId) === 'd30') { + $appId = Config::APP_ID_THIRTY_PRODUCTION; + if ($this->config->getEnvironmentMode($storeId) === Config::ENVIRONMENT_SANDBOX) { + $appId = Config::APP_ID_THIRTY_SANDBOX; + } + } + $params = [ 'response_type' => $responseType, 'client_id' => $appId, diff --git a/Gateway/Config/Config.php b/Gateway/Config/Config.php index 6dd3e64..c04ded6 100644 --- a/Gateway/Config/Config.php +++ b/Gateway/Config/Config.php @@ -44,6 +44,11 @@ class Config extends PaymentConfig */ public const ENDPOINT_PRODUCTION = 'https://api.pagseguro.com/'; + /** + * @const string + */ + public const ENDPOINT_SDK_PRODUCTION = 'https://sdk.pagseguro.com/'; + /** * @const string */ @@ -54,6 +59,15 @@ class Config extends PaymentConfig */ public const APP_ID_PRODUCTION = '1782a592-5eea-442c-8e67-c940d020dc53'; + /** + * @const string + */ + public const APP_ID_THIRTY_PRODUCTION = '4875151e-9caa-4019-b6b7-d29852efe7ee'; + + /** + * @const string + */ + public const APP_ID_FOURTEEN_PRODUCTION = 'fd0305da-da00-42b6-a9f4-dac498bc05e4'; /** * @const string */ @@ -64,11 +78,26 @@ class Config extends PaymentConfig */ public const ENDPOINT_SANDBOX = 'https://sandbox.api.pagseguro.com/'; + /** + * @const string + */ + public const ENDPOINT_SDK_SANDBOX = 'https://sandbox.sdk.pagseguro.com/'; + /** * @const string */ public const APP_ID_SANDBOX = '16670d56-c0cb-4a45-a7c7-616868c2c94d'; + /** + * @const string + */ + public const APP_ID_THIRTY_SANDBOX = '38a3acd5-b628-4bab-8364-079343cce978'; + + /** + * @const string + */ + public const APP_ID_FOURTEEN_SANDBOX = 'ebde0a80-a80c-4e81-b375-9d1e8b8671d3'; + /** * @const string */ @@ -185,6 +214,24 @@ public function getApiUrl($storeId = null): ?string return self::ENDPOINT_PRODUCTION; } + /** + * Gets the API endpoint URL. + * + * @param int|null $storeId + * + * @return string|null + */ + public function getApiSDKUrl($storeId = null): ?string + { + $environment = $this->getEnvironmentMode($storeId); + + if ($environment === 'sandbox') { + return self::ENDPOINT_SDK_SANDBOX; + } + + return self::ENDPOINT_SDK_PRODUCTION; + } + /** * Gets the Environment Mode. * @@ -203,6 +250,18 @@ public function getEnvironmentMode($storeId = null): ?string return self::ENVIRONMENT_PRODUCTION; } + /** + * Get Type App. + * + * @param int|null $storeId + * + * @return string|null + */ + public function getTypeApp($storeId = null): ?string + { + return $this->getAddtionalValue('type_app', $storeId); + } + /** * Get Api Headers. * @@ -245,11 +304,26 @@ public function getPubHeader($storeId = null) { $environment = $this->getAddtionalValue('environment', $storeId); $pub = $this->getAddtionalValue('cipher_text_production', $storeId); + $app = $this->getTypeApp($storeId); if ($environment === 'sandbox') { $pub = $this->getAddtionalValue('cipher_text_sandbox'); } + if ($app === 'd14') { + $pub = $this->getAddtionalValue('d14_cipher_text_production', $storeId); + if ($environment === 'sandbox') { + $pub = $this->getAddtionalValue('d14_cipher_text_sandbox'); + } + } + + if ($app === 'd30') { + $pub = $this->getAddtionalValue('d30_cipher_text_production', $storeId); + if ($environment === 'sandbox') { + $pub = $this->getAddtionalValue('d30_cipher_text_sandbox'); + } + } + return [ 'Content-Type' => 'application/json', 'Authorization' => 'Pub '.$pub, diff --git a/Gateway/Config/ConfigCc.php b/Gateway/Config/ConfigCc.php index c48c71d..5debc27 100644 --- a/Gateway/Config/ConfigCc.php +++ b/Gateway/Config/ConfigCc.php @@ -216,6 +216,42 @@ public function hasThreeDsAuth($storeId = null): bool ); } + /** + * Is Active Debit. + * + * @param int|null $storeId + * + * @return bool + */ + public function isActiveDebit($storeId = null): bool + { + $pathPattern = 'payment/%s/%s'; + + return (bool) $this->scopeConfig->getValue( + sprintf($pathPattern, self::METHOD, 'enable_debit'), + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * Is Active Debit. + * + * @param int|null $storeId + * + * @return int + */ + public function getMaxTryPlaceOrder($storeId = null): int + { + $pathPattern = 'payment/%s/%s'; + + return (int) $this->scopeConfig->getValue( + sprintf($pathPattern, self::METHOD, 'three_ds_max_try_place_order'), + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + /** * Get Instruction for 3ds. * @@ -389,4 +425,79 @@ public function getMinValuelInstallment($storeId = null): int $storeId ); } + + /** + * Get the configured minimum order total for 3DS. + * + * @param int|null $storeId + * @return float + */ + public function getThreeDsMinOrderTotal($storeId = null): float + { + $pathPattern = 'payment/%s/%s'; + + return (float) $this->scopeConfig->getValue( + sprintf($pathPattern, self::METHOD, 'three_ds_min_order_total'), + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * Get the configured SKUs that require 3DS. + * + * @param int|null $storeId + * @return array + */ + public function getThreeDsSkus($storeId = null): array + { + $pathPattern = 'payment/%s/%s'; + + $threeDsSkus = $this->scopeConfig->getValue( + sprintf($pathPattern, self::METHOD, 'three_ds_has_sku'), + ScopeInterface::SCOPE_STORE, + $storeId + ); + + return $threeDsSkus ? explode(',', $threeDsSkus) : []; + } + + /** + * Is 3ds Applicable. + * + * @param \Magento\Checkout\Model\Cart $cart + * @param int|null $storeId + * + * @return bool + */ + public function isThreeDsApplicable(\Magento\Checkout\Model\Cart $cart, $storeId = null): bool + { + $quote = $cart->getQuote(); + + if (!$this->hasThreeDsAuth($storeId)) { + return false; + } + + $threeDsMinOrderTotal = (float) $this->getThreeDsMinOrderTotal($storeId); + + $total = $quote->getGrandTotal(); + + if ($total >= $threeDsMinOrderTotal) { + return true; + } + + $threeDsSkus = $this->getThreeDsSkus($storeId); + + if ($threeDsSkus) { + $items = $quote->getAllItems(); + + foreach ($items as $item) { + if (in_array($item->getSku(), $threeDsSkus, true)) { + return true; + } + } + } + + return false; + } } diff --git a/Gateway/Request/CreditCard/PaymentCcDataRequest.php b/Gateway/Request/CreditCard/PaymentCcDataRequest.php index 2fbdb3b..cea372c 100644 --- a/Gateway/Request/CreditCard/PaymentCcDataRequest.php +++ b/Gateway/Request/CreditCard/PaymentCcDataRequest.php @@ -126,9 +126,10 @@ public function getDataPaymetCc($payment, $storeId) { $instruction = []; $installment = $payment->getAdditionalInformation('cc_installments') ?: 1; + $typeCard = $payment->getAdditionalInformation('card_type_transaction') ?: self::TYPE_VALUE; $instruction = [ - self::TYPE => self::TYPE_VALUE, + self::TYPE => $typeCard, self::SOFT_DESCRIPTOR => $this->config->getSoftDescriptor($storeId), self::CAPTURE => $this->configCc->hasCapture($storeId), self::INSTALLMENTS => $installment, diff --git a/Gateway/Response/TxnDataCcHandler.php b/Gateway/Response/TxnDataCcHandler.php index ef31f28..31f4880 100644 --- a/Gateway/Response/TxnDataCcHandler.php +++ b/Gateway/Response/TxnDataCcHandler.php @@ -215,10 +215,15 @@ public function handle(array $handlingSubject, array $response) public function setAdditionalInfo($payment, $paymentMethod, $cardData) { $ccType = null; + $installment = 1; + + if (isset($paymentMethod[self::RESPONSE_PM_INSTALLMENTS])) { + $installment = $paymentMethod[self::RESPONSE_PM_INSTALLMENTS]; + } $payment->setAdditionalInformation( self::PAYMENT_INFO_CC_INSTALLMENTS, - $paymentMethod[self::RESPONSE_PM_INSTALLMENTS] + $installment ); $ccType = $cardData[self::RESPONSE_PM_CARD_BRAND]; diff --git a/Gateway/Response/TxnDetailDataCcHandler.php b/Gateway/Response/TxnDetailDataCcHandler.php new file mode 100644 index 0000000..621dca6 --- /dev/null +++ b/Gateway/Response/TxnDetailDataCcHandler.php @@ -0,0 +1,138 @@ + + * @license See LICENSE for license details. + */ + +namespace PagBank\PaymentMagento\Gateway\Response; + +use InvalidArgumentException; +use Magento\Framework\Serialize\Serializer\Json; +use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; +use Magento\Payment\Gateway\Response\HandlerInterface; +use Magento\Payment\Model\InfoInterface; +use PagBank\PaymentMagento\Gateway\Config\Config; + +/** + * Txn Data Datail Cc Handler - Reply Flow for Cc data. + */ +class TxnDetailDataCcHandler implements HandlerInterface +{ + /** + * Cc Authorization Code - Payment Addtional Information. + */ + public const PAYMENT_INFO_CC_AUTHORIZATION_CODE = 'cc_authorization_code'; + + /** + * Cc NSU - Payment Addtional Information. + */ + public const PAYMENT_INFO_CC_NSU = 'cc_nsu'; + + /** + * Response Pay Charges - Block name. + */ + public const RESPONSE_CHARGES = 'charges'; + + /** + * Response Pay Payment Response - Block Name. + */ + public const RESPONSE_PAYMENT_RESPONSE = 'payment_response'; + + /** + * Response Raw Data - Block name. + */ + public const RAW_DATA = 'raw_data'; + + /** + * Response Authorization Code - Block name. + */ + public const RESPONSE_AUTHORIZATION_CODE = 'authorization_code'; + + /** + * Response Pay Payment Method - Block name. + */ + public const RESPONSE_NSU = 'nsu'; + + /** + * @var Json + */ + protected $json; + + /** + * @var Config + */ + protected $config; + + /** + * @param Json $json + * @param Config $config + */ + public function __construct( + Json $json, + Config $config + ) { + $this->json = $json; + $this->config = $config; + } + + /** + * Handles. + * + * @param array $handlingSubject + * @param array $response + * + * @return void + */ + public function handle(array $handlingSubject, array $response) + { + if (!isset($handlingSubject['payment']) + || !$handlingSubject['payment'] instanceof PaymentDataObjectInterface + ) { + throw new InvalidArgumentException('Payment data object should be provided'); + } + + $paymentDO = $handlingSubject['payment']; + + $payment = $paymentDO->getPayment(); + + $charges = $response[self::RESPONSE_CHARGES][0]; + + $paymentResponse = $charges[self::RESPONSE_PAYMENT_RESPONSE]; + + if (isset($paymentResponse)) { + /** Set Addtional Information */ + $this->setAdditionalInfo($payment, $paymentResponse); + } + } + + /** + * Set Additional Info. + * + * @param InfoInterface $payment + * @param array $paymentResponse + * + * @return void + */ + public function setAdditionalInfo($payment, $paymentResponse) + { + $data = $paymentResponse[self::RAW_DATA]; + + if (isset($data[self::RESPONSE_AUTHORIZATION_CODE])) { + $payment->setAdditionalInformation( + self::PAYMENT_INFO_CC_AUTHORIZATION_CODE, + $data[self::RESPONSE_AUTHORIZATION_CODE] + ); + } + + if (isset($data[self::RESPONSE_NSU])) { + $payment->setAdditionalInformation( + self::PAYMENT_INFO_CC_NSU, + $data[self::RESPONSE_NSU] + ); + } + } +} diff --git a/Model/Adminhtml/Source/TypeApp.php b/Model/Adminhtml/Source/TypeApp.php new file mode 100644 index 0000000..09c4c65 --- /dev/null +++ b/Model/Adminhtml/Source/TypeApp.php @@ -0,0 +1,33 @@ + + * @license See LICENSE for license details. + */ + +namespace PagBank\PaymentMagento\Model\Adminhtml\Source; + +use Magento\Framework\Option\ArrayInterface; + +/** + * Class Type App - Defines the types of type App. + */ +class TypeApp implements ArrayInterface +{ + /** + * Returns Options. + * + * @return array + */ + public function toOptionArray(): array + { + return [ + 'account' => __('Set in your Account'), + 'd14' => __('Receive within 14 days'), + 'd30' => __('Receive within 30 days'), + ]; + } +} diff --git a/Model/Api/ConsultPSInstallments.php b/Model/Api/ConsultPSInstallments.php index 10ffbd3..4c66c9f 100644 --- a/Model/Api/ConsultPSInstallments.php +++ b/Model/Api/ConsultPSInstallments.php @@ -25,11 +25,6 @@ */ class ConsultPSInstallments { - /** - * Credit Card - Block Name. - */ - public const CREDIT_CARD = 'CREDIT_CARD'; - /** * @var ConfigBase */ @@ -76,10 +71,11 @@ public function __construct( * @param int|null $storeId * @param string $creditCardBin * @param string $amount + * @param string $cardTypeTransaction * * @return array */ - public function getPagBankInstallments($storeId, $creditCardBin, $amount) + public function getPagBankInstallments($storeId, $creditCardBin, $amount, $cardTypeTransaction = 'CREDIT_CARD') { /** @var ZendClient $client */ $client = $this->httpClientFactory->create(); @@ -91,7 +87,7 @@ public function getPagBankInstallments($storeId, $creditCardBin, $amount) $list = []; $data = [ - 'payment_methods' => self::CREDIT_CARD, + 'payment_methods' => $cardTypeTransaction, 'value' => $amount, 'max_installments' => $this->configCc->getMaxInstallments($storeId), 'max_installments_no_interest' => $this->configCc->getInterestFree($storeId), diff --git a/Model/Api/Credential.php b/Model/Api/Credential.php index ce5bbe6..f198a16 100644 --- a/Model/Api/Credential.php +++ b/Model/Api/Credential.php @@ -143,13 +143,13 @@ public function getAuthorize($storeId, $code, $codeVerifier) $store = $this->storeManager->getStore('admin'); $storeCode = '/'.$store->getCode().'/'; - $redirectUrl = $store->getUrl('pagbank/system_config/oauth', [ + $redirectUrl = (string) $store->getUrl('pagbank/system_config/oauth', [ 'website' => $storeId, 'code_verifier' => $codeVerifier, ]); $search = '/'.preg_quote($storeCode, '/').'/'; - $redirectUrl = preg_replace($search, '/', $redirectUrl, -1); + $redirectUrl = preg_replace($search, '/', $redirectUrl, 0); $data = [ 'grant_type' => 'authorization_code', diff --git a/Model/Api/Data/CardTypeTransaction.php b/Model/Api/Data/CardTypeTransaction.php new file mode 100644 index 0000000..f0c30dc --- /dev/null +++ b/Model/Api/Data/CardTypeTransaction.php @@ -0,0 +1,38 @@ + + * @license See LICENSE for license details. + */ + +declare(strict_types=1); + +namespace PagBank\PaymentMagento\Model\Api\Data; + +use Magento\Framework\Api\AbstractSimpleObject; +use PagBank\PaymentMagento\Api\Data\CardTypeTransactionInterface; + +/** + * Class Credit Card Bin - Model data. + */ +class CardTypeTransaction extends AbstractSimpleObject implements CardTypeTransactionInterface +{ + /** + * @inheritdoc + */ + public function getCardTypeTransaction() + { + return $this->_get(CardTypeTransactionInterface::PAGBANK_CARD_TYPE_TRANSACTION); + } + + /** + * @inheritdoc + */ + public function setCardTypeTransaction($cardTypeTransaction) + { + return $this->setData(CardTypeTransactionInterface::PAGBANK_CARD_TYPE_TRANSACTION, $cardTypeTransaction); + } +} diff --git a/Model/Api/GuestListInstallmentsManagement.php b/Model/Api/GuestListInstallmentsManagement.php index a38e901..425effe 100644 --- a/Model/Api/GuestListInstallmentsManagement.php +++ b/Model/Api/GuestListInstallmentsManagement.php @@ -14,6 +14,7 @@ use Magento\Quote\Model\QuoteIdMaskFactory; use PagBank\PaymentMagento\Api\Data\CreditCardBinInterface; +use PagBank\PaymentMagento\Api\Data\CardTypeTransactionInterface; use PagBank\PaymentMagento\Api\GuestListInstallmentsManagementInterface; use PagBank\PaymentMagento\Api\ListInstallmentsManagementInterface; @@ -47,21 +48,24 @@ public function __construct( /** * Generate List Installments. * - * @param string $cartId - * @param \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + * @param string $cartId + * @param \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + * @param \PagBank\PaymentMagento\Api\Data\CardTypeTransactionInterface $cardTypeTransaction * * @return array */ public function generateListInstallments( $cartId, - CreditCardBinInterface $creditCardBin + CreditCardBinInterface $creditCardBin, + CardTypeTransactionInterface $cardTypeTransaction = null ) { /** @var \Magento\Quote\Model\QuoteIdMask */ $quoteIdMask = $this->quoteIdMaskFactory->create()->load($cartId, 'masked_id'); return $this->cardNumberInterface->generateListInstallments( $quoteIdMask->getQuoteId(), - $creditCardBin + $creditCardBin, + $cardTypeTransaction ); } } diff --git a/Model/Api/ListInstallmentsManagement.php b/Model/Api/ListInstallmentsManagement.php index 025fa94..09064d9 100644 --- a/Model/Api/ListInstallmentsManagement.php +++ b/Model/Api/ListInstallmentsManagement.php @@ -18,6 +18,7 @@ use Magento\Quote\Api\CartTotalRepositoryInterface; use Magento\Quote\Api\Data\CartInterface as QuoteCartInterface; use PagBank\PaymentMagento\Api\Data\CreditCardBinInterface; +use PagBank\PaymentMagento\Api\Data\CardTypeTransactionInterface; use PagBank\PaymentMagento\Api\Data\InstallmentSelectedInterface; use PagBank\PaymentMagento\Api\ListInstallmentsManagementInterface; use PagBank\PaymentMagento\Gateway\Config\Config as ConfigBase; @@ -72,8 +73,9 @@ public function __construct( /** * Generate List Installments. * - * @param int $cartId - * @param \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + * @param int $cartId + * @param \PagBank\PaymentMagento\Api\Data\CreditCardBinInterface $creditCardBin + * @param \PagBank\PaymentMagento\Api\Data\CardTypeTransactionInterface $cardTypeTransaction * * @throws CouldNotSaveException * @throws NoSuchEntityException @@ -82,7 +84,8 @@ public function __construct( */ public function generateListInstallments( $cartId, - CreditCardBinInterface $creditCardBin + CreditCardBinInterface $creditCardBin, + CardTypeTransactionInterface $cardTypeTransaction = null ) { $quote = $this->quoteRepository->getActive($cartId); if (!$quote->getItemsCount()) { @@ -93,6 +96,10 @@ public function generateListInstallments( $creditCardBin = $creditCardBin->getCreditCardBin(); + if ($cardTypeTransaction) { + $cardTypeTransaction = $cardTypeTransaction->getCardTypeTransaction(); + } + $storeId = $quote->getData(QuoteCartInterface::KEY_STORE_ID); $amount = $quoteTotal->getBaseGrandTotal(); diff --git a/Model/Api/ThreeDsSession.php b/Model/Api/ThreeDsSession.php index e5c3d30..8ff0906 100644 --- a/Model/Api/ThreeDsSession.php +++ b/Model/Api/ThreeDsSession.php @@ -111,16 +111,16 @@ public function getSessionInPagBank() /** @var ZendClient $client */ $client = $this->httpZendClientFactory->create(); - $url = $this->configBase->getApiUrl($storeId); + $url = $this->configBase->getApiSDKUrl($storeId); $apiConfigs = $this->configBase->getApiConfigs(); $headers = $this->configBase->getApiHeaders($storeId); $uri = $url.'checkout-sdk/sessions'; try { $client->setUri($uri); $client->setHeaders($headers); - $client->setMethod(Request::POST); + $client->setMethod(ZendClient::POST); $client->setConfig($apiConfigs); - $responseBody = $client->send()->getBody(); + $responseBody = $client->request()->getBody(); $dataResponse = $this->json->unserialize($responseBody); diff --git a/Model/Console/Command/Basic/Refresh.php b/Model/Console/Command/Basic/Refresh.php index 392ed53..268c353 100644 --- a/Model/Console/Command/Basic/Refresh.php +++ b/Model/Console/Command/Basic/Refresh.php @@ -126,7 +126,7 @@ public function newToken($storeId = null) $this->refreshToken(true, 0, 0); } - if (!$storeIds) { + if ($storeIds) { $allStores = $this->storeManager->getStores(); foreach ($allStores as $stores) { @@ -219,7 +219,7 @@ public function getConfigInWebsite($websiteId) * * @return void */ - protected function refreshToken(bool $storeIdIsDefault, int $storeId = 0, int $webSiteId = 0) + public function refreshToken(bool $storeIdIsDefault, int $storeId = 0, int $webSiteId = 0) { $newToken = $this->credential->generateNewoAuth($storeId); $newToken = $this->json->unserialize($newToken); diff --git a/Model/Ui/ConfigProviderCc.php b/Model/Ui/ConfigProviderCc.php index 4cd0bfd..5917a5f 100644 --- a/Model/Ui/ConfigProviderCc.php +++ b/Model/Ui/ConfigProviderCc.php @@ -12,10 +12,9 @@ use Magento\Checkout\Model\ConfigProviderInterface; use Magento\Framework\Escaper; -use Magento\Framework\Session\SessionManager; use Magento\Framework\View\Asset\Source; use Magento\Payment\Model\CcConfig; -use Magento\Quote\Api\Data\CartInterface; +use Magento\Checkout\Model\Cart; use PagBank\PaymentMagento\Gateway\Config\Config as ConfigBase; use PagBank\PaymentMagento\Gateway\Config\ConfigCc; @@ -45,7 +44,7 @@ class ConfigProviderCc implements ConfigProviderInterface protected $configCc; /** - * @var CartInterface + * @var Cart */ protected $cart; @@ -64,11 +63,6 @@ class ConfigProviderCc implements ConfigProviderInterface */ protected $assetSource; - /** - * @var SessionManager - */ - protected $session; - /** * @var Escaper */ @@ -77,19 +71,17 @@ class ConfigProviderCc implements ConfigProviderInterface /** * @param ConfigBase $configBase * @param ConfigCc $configCc - * @param CartInterface $cart + * @param Cart $cart * @param CcConfig $ccConfig * @param Source $assetSource - * @param SessionManager $session * @param Escaper $escaper */ public function __construct( ConfigBase $configBase, ConfigCc $configCc, - CartInterface $cart, + Cart $cart, CcConfig $ccConfig, Source $assetSource, - SessionManager $session, Escaper $escaper ) { $this->configBase = $configBase; @@ -97,7 +89,6 @@ public function __construct( $this->cart = $cart; $this->ccConfig = $ccConfig; $this->assetSource = $assetSource; - $this->session = $session; $this->escaper = $escaper; } @@ -108,7 +99,9 @@ public function __construct( */ public function getConfig() { - $storeId = $this->cart->getStoreId(); + $quote = $this->cart->getQuote(); // Obter a instância de Quote + $storeId = $quote->getStoreId(); // Obter o Store ID a partir do Quote + // $cartId = $quote->getId(); // Obter o Cart ID a partir do Quote return [ 'payment' => [ @@ -124,8 +117,11 @@ public function getConfig() 'public_key' => $this->configBase->getMerchantGatewayPublicKey($storeId), 'ccVaultCode' => self::VAULT_CODE, 'threeDs' => [ + 'enable' => $this->configCc->hasThreeDsAuth($storeId), + 'enable_deb' => $this->configCc->isActiveDebit($storeId), + 'applicable' => $this->configCc->isThreeDsApplicable($this->cart, $storeId), + 'max_try_place' => $this->configCc->getMaxTryPlaceOrder($storeId), 'env' => $this->configCc->getThreeDsEnv($storeId), - 'active' => $this->configCc->hasThreeDsAuth($storeId), 'reject' => $this->configCc->hasRejectNotAuth($storeId), 'instruction' => nl2br( $this->escaper->escapeHtml( diff --git a/Model/Ui/ConfigProviderDeepLink.php b/Model/Ui/ConfigProviderDeepLink.php index 849cdd2..020b24f 100644 --- a/Model/Ui/ConfigProviderDeepLink.php +++ b/Model/Ui/ConfigProviderDeepLink.php @@ -130,7 +130,7 @@ public function getLogo() 'url' => $asset->getUrl(), 'width' => '48px', 'height' => '32px', - 'title' => __('`Pay in PagBank'), + 'title' => __('Pay in PagBank'), ]; } diff --git a/Observer/DataAssignCcObserver.php b/Observer/DataAssignCcObserver.php index c5468c0..9e93231 100644 --- a/Observer/DataAssignCcObserver.php +++ b/Observer/DataAssignCcObserver.php @@ -54,6 +54,11 @@ class DataAssignCcObserver extends AbstractDataAssignObserver */ public const PAYMENT_INFO_CC_CID = 'cc_cid'; + /** + * @const string + */ + public const PAYMENT_INFO_TYPE_CARD = 'card_type_transaction'; + /** * @const string */ @@ -86,6 +91,7 @@ class DataAssignCcObserver extends AbstractDataAssignObserver self::PAYMENT_INFO_CC_CID, self::PAYMENT_INFO_PAYER_TAX_ID, self::PAYMENT_INFO_PAYER_PHONE, + self::PAYMENT_INFO_TYPE_CARD, self::PAYMENT_INFO_THREE_DS_SESSION, self::PAYMENT_INFO_THREE_DS_AUTH, self::PAYMENT_INFO_THREE_DS_AUTH_STATUS diff --git a/README.md b/README.md index 90de16f..cbe3e14 100644 --- a/README.md +++ b/README.md @@ -16,13 +16,14 @@ Desenvolvida no padrão Gateway, nosso módulo irá oferecer uma perfeita integr Receba e gerencie pagamentos a pioneira e lider de mercado no Brasil! -### Cartão de Crédito e Cofre (Vault) +### Cartão de Crédito, Débito e Cofre (Vault) Receba e gerencie transações de cartão de crédito em sua loja. Principais Recursos: - Método transparente +- Autenticação 3DS - AntiFraude aprimorado com revisão manual - Captura automatizada ou tardia - Reembolso online total ou parcial diff --git a/etc/adminhtml/system/base_settings.xml b/etc/adminhtml/system/base_settings.xml index 7b62ef5..d00192b 100644 --- a/etc/adminhtml/system/base_settings.xml +++ b/etc/adminhtml/system/base_settings.xml @@ -10,6 +10,9 @@ */ --> + Define the relationship between your store and our application. @@ -24,7 +27,13 @@ payment/pagbank_paymentmagento/environment required-entry validate-select - + + PagBank\PaymentMagento\Block\Adminhtml\System\Config\Oauth diff --git a/etc/adminhtml/system/credit_card.xml b/etc/adminhtml/system/credit_card.xml index c8ce542..3532da1 100644 --- a/etc/adminhtml/system/credit_card.xml +++ b/etc/adminhtml/system/credit_card.xml @@ -37,7 +37,7 @@ PagBank\PaymentMagento\Model\Adminhtml\Source\PaymentAction payment/pagbank_paymentmagento_cc/payment_action - + + + Advanced settings for 3D Secure application. + + + number of purchase attempts (that fail) exceeds the value registered here.]]> + During checkout, if the customer tries to purchase and their order is denied, the number of attempts will increase. This feature is useful to prevent automated fraud attempts.

]]>
+ validate-number validate-zero-or-greater + payment/pagbank_paymentmagento_cc/three_ds_max_try_place_order +
+ + + the order value exceeds the value registered here.]]> + We recommend using values that exceed the normal ticket, which may indicate possible fraud.

]]>
+ validate-number validate-zero-or-greater + payment/pagbank_paymentmagento_cc/three_ds_min_order_total +
+ + + order contains the SKU.]]> + If you have products that are more sensitive to fraud, you can register these SKUs here.

]]>
+ payment/pagbank_paymentmagento_cc/three_ds_has_sku +
+
+
Basic configuration of payment methods. diff --git a/etc/config.xml b/etc/config.xml index 08afe42..6059597 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -46,8 +46,13 @@ 1 fraud,processing,pending_payment,holded,complete,closed,canceled,paypal_canceled_reversal,paypal_reversed,pending_paypal header + account TDTmdLh3LyGKMrRqdg6CLF4FxWhSBDRMYFqG7o4EwUIS6vESXJCmtjjzdX8NY+ggxLci6dcZrNfnYYezdY/wSi/sdNNzijSDgjVX5nRSdExr8DXPdlgTlEAKg8iZFeoFvtxJZPqgxeEJVjZ3bwRm2nYGU/YPXTH5wk+w2LOKeaSEfewgMfiElFZW8F9ay+Exwivmxosa8nqQzlmLyJhBnvYLjHJuaXy+lAjFyFSQh75gHnr3bGcKGZx2roDnozFLQlMf+ix4RywVaMg0+5Y3Z8BaYwIjtyX0gddgi4hRm2nFVFVaAHf2uFWvUlLGMNZiLhCpixe9tjFJ25Qlcuf+sA== JIPYFxLrvP0wFDYTdUSzvvDCetb/GQxDRGEqfKsh4vSEKZvQKaQtvy8+/dyYclbkZhQPxiTdN2mg6Z6GVSrRJg2JPp62EzGGZt+9cI6xTQDlqCByolVPP2rJLF1IcRnnUjdHNjipXpL6B8Q7FANzoCgIGMux6frge3VdhXCb1zIkWhGeAGCunmBDjNetrUyt91Tw+xJ04grQNhrUvIHZfJ8qmapoGja4jrhA9hZFoBTGIg5UJKBJdLze/cmNnhDTt5WFBQEbq2I2kwsxuStSVT9rnS3Jet2lYCLEk0WAqmZmMg1ux0JTMU7Bk2S3MUn/w/hIfjccG7q4Lh7MX5zb3A== + MzZoI8aObUW+CYukRGA9sMcqZKImVM9CfvHbjGlCovYtKXZYENZ1+6ICKMjNSbdRq8/hsywmdgShAr47Kh2U50HoxX4rBTBB+b3EjJYEagxMVor4yPeqFoyJZyK2n4eBVRNgichx4PQZLOLOpMOHMgNVr70mOXnf9duEEImXn5dTzFZnTHBO+E/L1qT1EEyBdYHzITytFMH8BcxMTUaYULWYAMunlBTjTFVzyfCaBqw8XniKfQrjsdlgIafYtn1dCsiOPLiJuCe11HglblUq2MSOrQuqRr7UdJUKcT2gs5nUbEATBrHEk4CS4c3TE35BuTucAOc1baBoGIBaknsxnw== + Wmba3WqDAtXoQMud1imNLjpOboMZJLKEB92GZsiKR3EV2VNl/gc8fmshnUS5RsVM1eCdrtzRUF6Q6RUd7tdm6yhGE7kyj/MJSJLLRfCTM3gSt3+SeWDU8A/0P5wfQFOu9Iv5T5KVgXdrHuYkULdae+i6XiLiLML9xu7UDPX77jttYM0+rjhJZbebkt8Rzxm4P82WdDWtFaJdcxh7l4588zmV6PuWC3wcSQxp4jZP33wSPLVHtnufaOEu0Fo80kZHhKFNQLf22xAnXO0YgsHOt9hQev4xOgDlQ2yrv2gofScibJ+iLLB3LADQhrCOYQiSC1U1jYcHlkNgPEmKLCNyWg== + cxRbs0qyWpJ4Wj2jXQslwP2aWXbdsz/NhIs8EzY2eHY3UvV1WTSi+P/vn5DMwugV+FKtzzJpE3GZaNM0nLP6PJoJHdXRgDD1fxNW7HYmbvQTQc+NxF/jF7B5DHqNX4OfoEcWGnTGi/lWOh4BP+Tqn2jBvxy1E1jaxg+NdgT0/1Lc15+fZc/YkEF98q+Rp+3YUfqEGCOeKDqWkazbrFhp1JPFZJtCaSIesPWAvtv0cRVQVd60oRFZTQvWSoahjq/IbX+eGRxIFbHazcTHyNK8/GVCfBeS+pvhcwf1lkkjP+n/dbQeLewus+mWv6ueXORwM6KWMNIyM7k0RojJCc3aZQ== + Y2UbzntpYlH6t3vRtMqJ6qwckrg2+ARvbiq6cuPA5oTQcScK7KynxHH9JgmcNEHQ+Kr6cdL8qeP/ydnc5tMxv4xv5Vvmfz+DouklPK36J5h7ALJ7qOjTU51mY4AGNsft5wKuw2RIfioJcJCAtN0RO9l+DCNOv2F2VSfXdmTkXhuU1j7Iy+f5IRduEALFNVngZ/qA5ws/vWyQYT62WbSZfEb5DJNL/TI7fVPVWEbktOGox04NFoloucFEHR8RTWzrljAzSwpelETcCwfc9HU/r2t9JCMv8GbKtO26exhoyOE5Rs8IeYS6yKdUENmoqxwBbNrRnPigsxEfQsMeR+YU/g== pagbank_group @@ -73,8 +78,8 @@ 1 1 1 - cc_installments,cc_type,cc_number,cc_exp_month,cc_exp_year,cc_cardholder_name,payer_tax_id,payer_phone,three_ds_session,three_ds_auth,three_ds_auth_status - three_ds_session,three_ds_auth,three_ds_auth_status + cc_installments,cc_type,cc_number,cc_exp_month,cc_exp_year,cc_cardholder_name,payer_tax_id,payer_phone,three_ds_session,three_ds_auth,three_ds_auth_status,cc_authorization_code,cc_nsu + three_ds_session,three_ds_auth,three_ds_auth_status,cc_authorization_code,cc_nsu 1 Cartão de Crédito @@ -92,6 +97,8 @@ 10 0 1 + 0 + 3 %1 solicita a confirmação dos seus dados junto ao seu banco. Para isso, uma nova tela será aberta, onde você precisará seguir as instruções passo a passo fornecidas pelo banco emissor do seu cartão. @@ -106,8 +113,8 @@ Este é o processo de autenticação 3DS, um processo seguro, como você pode ve 0 1 1 - cc_installments,cc_type,cc_number,cc_exp_month,cc_exp_year,cc_cardholder_name,payer_tax_id,payer_phone,three_ds_session,three_ds_auth,three_ds_auth_status - three_ds_session,three_ds_auth,three_ds_auth_status + cc_installments,cc_type,cc_number,cc_exp_month,cc_exp_year,cc_cardholder_name,payer_tax_id,payer_phone,three_ds_session,three_ds_auth,three_ds_auth_status,cc_authorization_code,cc_nsu + three_ds_session,three_ds_auth,three_ds_auth_statu,cc_authorization_code,cc_nsu 1 Stored Cards (PagBank) diff --git a/etc/csp_whitelist.xml b/etc/csp_whitelist.xml index 2196028..7bed6a6 100644 --- a/etc/csp_whitelist.xml +++ b/etc/csp_whitelist.xml @@ -14,6 +14,13 @@ *.pagseguro.com.br + *.pagseguro.com + + + + + *.pagseguro.com.br + *.pagseguro.com diff --git a/etc/di.xml b/etc/di.xml index a899cf8..f055185 100644 --- a/etc/di.xml +++ b/etc/di.xml @@ -45,6 +45,7 @@ + @@ -509,6 +510,7 @@ PagBank\PaymentMagento\Gateway\Response\ExtOrdIdHandler PagBank\PaymentMagento\Gateway\Response\TxnOrderedHandler PagBank\PaymentMagento\Gateway\Response\TxnDataCcHandler + PagBank\PaymentMagento\Gateway\Response\TxnDetailDataCcHandler PagBank\PaymentMagento\Gateway\Response\VaultDetailsHandler diff --git a/i18n/en_US.csv b/i18n/en_US.csv index 490f2de..e565fd9 100644 --- a/i18n/en_US.csv +++ b/i18n/en_US.csv @@ -11,6 +11,7 @@ Production,Production "You are connected to PagBank. =)","You are connected to PagBank. =)" "Unable to get the code, try again. =(","Unable to get the code, try again. =(" "You should not be here...","You should not be here..." +"Not apply.","Not apply." "PagBank, error when checking order status.","PagBank, error when checking order status." "It is not possible to check the status of order %1, please perform a manual verification.","It is not possible to check the status of order %1, please perform a manual verification." "Transaction has been declined. Please try again later.","Transaction has been declined. Please try again later." @@ -21,6 +22,7 @@ Production,Production "1 day","1 day" "3 days","3 days" "%1 minutes","%1 minutes" +"Invalid JSON was returned by the gateway","Invalid JSON was returned by the gateway" "Pay for Order #%1","Pay for Order #%1" "Order Canceled.","Order Canceled." "Awaiting payment.","Awaiting payment." @@ -75,12 +77,14 @@ Finished,Finished "Update not available because the initial state is incompatible: %1","Update not available because the initial state is incompatible: %1" "Boleto Bancário - PagBank","Boleto Bancário - PagBank" "Cartão de Crédito - PagBank","Cartão de Crédito - PagBank" -"`Pay in PagBank","`Pay in PagBank" +"Pay in PagBank","Pay in PagBank" "Pix - PagBank","Pix - PagBank" "Get Payment Update","Get Payment Update" "This decision will not change the status in PagBank.","This decision will not change the status in PagBank." "Accept Offline Payment","Accept Offline Payment" "Deny Offline Payment","Deny Offline Payment" +"Not implemented","Not implemented" +"Capture can not be performed through vault","Capture can not be performed through vault" Due,Due Instruction,Instruction "Not available.","Not available." @@ -101,19 +105,19 @@ Copied,Copied "To make the payment:","To make the payment:" "Access your PagBank account by clicking on the link:","Access your PagBank account by clicking on the link:" "You must be redirected to PagBank to complete the payment.","You must be redirected to PagBank to complete the payment." -"Use the camera on your mobile device to scan the QR Code:","Use the camera on your mobile device to scan the QR Code:" -"Pay in PagBank","Pay in PagBank" -"You must click the link indicated by the camera.","You must click the link indicated by the camera." -"To pay, read the Qr Code","To pay, read the Qr Code" "Open the PagBank app on your phone;","Open the PagBank app on your phone;" "Go to the Pix/Qr Code option;","Go to the Pix/Qr Code option;" -"Select the option "Pay with Qr Code";","Select the option "Pay with Qr Code";" +"Select the option Pay with Qr Code;","Select the option Pay with Qr Code;" "Scan the Qr Code:","Scan the Qr Code:" +"Pay in PagBank","Pay in PagBank" +"Atenção o Qr Code gerado só é válido para uso no aplicatico do PagBank.","Atenção o Qr Code gerado só é válido para uso no aplicatico do PagBank." +"To pay, read the Qr Code","To pay, read the Qr Code" "Or if you prefer, copy and paste the code","Or if you prefer, copy and paste the code" "Boleto Information","Boleto Information" Waiting...,Waiting... "Place Order","Place Order" -"Credit Card Information","Credit Card Information" +"Card Information","Card Information" +"Type Transaction","Type Transaction" "Credit Card Number","Credit Card Number" "What is this?","What is this?" "CVV - Card Verification Number","CVV - Card Verification Number" @@ -123,6 +127,7 @@ Waiting...,Waiting... "Select Instalmment","Select Instalmment" "Save for later use.","Save for later use." "A 3-digit number in italics on the back of your credit card.","A 3-digit number in italics on the back of your credit card." +"Card Type","Card Type" Month,Month Year,Year "Information for paying with PagBank","Information for paying with PagBank" @@ -145,6 +150,8 @@ expires,expires "Please enter a valid credit card number.","Please enter a valid credit card number." "Please enter a valid credit card verification number.","Please enter a valid credit card verification number." "Please provide a valid CPF/CNPJ.","Please provide a valid CPF/CNPJ." +Credit,Credit +Debit,Debit "Unable to complete the payment with this card, please verify the information and try again.","Unable to complete the payment with this card, please verify the information and try again." "Error while processing Payment","Error while processing Payment" Ok,Ok @@ -185,6 +192,25 @@ Title,Title "You can run charges to a credit card using national currency and to top it off with rates that fit your pocket.","You can run charges to a credit card using national currency and to top it off with rates that fit your pocket." "Enabled Vault","Enabled Vault" "Credit Card Types","Credit Card Types" +"3D Secure","3D Secure" +"3D Secure configuration.","3D Secure configuration." +"Authorization is required to use this service. Please get in touch with PagBank for further assistance.","Authorization is required to use this service. Please get in touch with PagBank for further assistance." +"Enabled Debit Card","Enabled Debit Card" +"Allow payment with debit card.","Allow payment with debit card." +"Reject payment not authenticated","Reject payment not authenticated" +"Instruction before challenge","Instruction before challenge" +"%1 and %2 are two variables, they will be replaced by the card's flag and the issuer bank's name, respectively.","%1 and %2 are two variables, they will be replaced by the card's flag and the issuer bank's name, respectively." +"Activation rules","Activation rules" +"Advanced settings for 3D Secure application.","Advanced settings for 3D Secure application." +"Activate after the number of failed attempts","Activate after the number of failed attempts" +"3D Secure authentication will be required if the number of purchase attempts (that fail) exceeds the value registered here.","3D Secure authentication will be required if the number of purchase attempts (that fail) exceeds the value registered here." +"

During checkout, if the customer tries to purchase and their order is denied, the number of attempts will increase. This feature is useful to prevent automated fraud attempts.

","

During checkout, if the customer tries to purchase and their order is denied, the number of attempts will increase. This feature is useful to prevent automated fraud attempts.

" +"Activate after the order value exceeds","Activate after the order value exceeds" +"3D Secure authentication will be required if the order value exceeds the value registered here.","3D Secure authentication will be required if the order value exceeds the value registered here." +"

We recommend using values that exceed the normal ticket, which may indicate possible fraud.

","

We recommend using values that exceed the normal ticket, which may indicate possible fraud.

" +"If the order contains the SKU","If the order contains the SKU" +"You can register multiple SKUs, use commas to separate them. 3D Secure authentication will be required if the order contains the SKU.","You can register multiple SKUs, use commas to separate them. 3D Secure authentication will be required if the order contains the SKU." +"

If you have products that are more sensitive to fraud, you can register these SKUs here.

","

If you have products that are more sensitive to fraud, you can register these SKUs here.

" "Capture phone in the payment form?","Capture phone in the payment form?" "Installment and interest","Installment and interest" "Maximum number of installment","Maximum number of installment" @@ -193,7 +219,7 @@ Title,Title "Number of installments you want to accept without applying interest","Number of installments you want to accept without applying interest" "The minimum installment price","The minimum installment price" "It is the minimum value that the installment can have","It is the minimum value that the installment can have" -"Pague com PagBank","Pague com PagBank" +"Pagar com PagBank","Pagar com PagBank" "O botão de pagamento que deixa você um passo à frente da concorrência!","O botão de pagamento que deixa você um passo à frente da concorrência!" Developers,Developers "Meet our Wiki.","Meet our Wiki." @@ -275,4 +301,6 @@ Pix,Pix "cc_cardholder_name","Holder name" "three_ds_session","3DS Session ID" "three_ds_auth","3DS Authentication Type" -"three_ds_auth_status","3DS Authentication Status" \ No newline at end of file +"three_ds_auth_status","3DS Authentication Status" +"cc_authorization_code","Authorization Code" +"cc_nsu","NSU" \ No newline at end of file diff --git a/i18n/not_automatically_collected.csv b/i18n/not_automatically_collected.csv index efa8888..ce4054c 100644 --- a/i18n/not_automatically_collected.csv +++ b/i18n/not_automatically_collected.csv @@ -16,6 +16,8 @@ "three_ds_session","3DS Session ID" "three_ds_auth","3DS Authentication Type" "three_ds_auth_status","3DS Authentication Status" +"cc_authorization_code","Authorization Code" +"cc_nsu","NSU" [pt_BR] "qr_code_image","Imagem do Qr Code" "qr_code","Qr Code" @@ -33,4 +35,6 @@ "cc_cardholder_name","Nome Impresso" "three_ds_session","Id da Sessão 3DS" "three_ds_auth","Tipo de Autenticação 3DS" -"three_ds_auth_status","Status da Autenticação 3DS" \ No newline at end of file +"three_ds_auth_status","Status da Autenticação 3DS" +"cc_authorization_code","Código da Autorização" +"cc_nsu","NSU" \ No newline at end of file diff --git a/i18n/pt_BR.csv b/i18n/pt_BR.csv index b288d38..512ba67 100644 --- a/i18n/pt_BR.csv +++ b/i18n/pt_BR.csv @@ -11,6 +11,7 @@ Production,Produção "You are connected to PagBank. =)","Você foi conectado ao PagBank. =)" "Unable to get the code, try again. =(","Não foi possível obter o código, tente novamente. =(" "You should not be here...","Não é para você estar aqui..." +"Not apply.","Não Aplicado." "PagBank, error when checking order status.","PagBank, erro ao verificar o status do pedido." "It is not possible to check the status of order %1, please perform a manual verification.","Não é possível verificar o status do pedido %1, por favor, realize uma verificação manual." "Transaction has been declined. Please try again later.","Pedido recusado, por favor, tente mais tarde." @@ -21,10 +22,11 @@ Production,Produção "1 day","1 dia" "3 days","3 dias" "%1 minutes","%1 minutos" +"Invalid JSON was returned by the gateway","Comunicação inválida com o processador de pagamento." "Pay for Order #%1","Pagamento do pedido #%1" "Order Canceled.","Pedido Cancelado." -"Awaiting payment review.","Aguardando revisão do pagamento." "Awaiting payment.","Aguardando pagamento." +"Awaiting payment review.","Aguardando revisão do pagamento." "Gateway rejected the transaction.","Gateway rejeitou a transação." "Sandbox - Environment for tests","Sandbox - Ambiente de teste" "1 installment","1 parcela" @@ -70,16 +72,19 @@ Finished,Finalizado "token update returns errors code: %1","Erro ao atualizar o token: %1" "Querying the status of the order at the gateway.","Consultando o status do pedido no gateway." "Order cancelled, payment deadline has expired.","Pedido cancelado, prazo de pagamento expirou." -"Order %1 was in state %2 has been updated to state %3 expired?","O pedido %1 estava no estado %2 foi atualizado para o estado %3 expirou?" +"Order %1 was in state %2 has been updated to state %3.","O pedido %1 estava no estado %2 foi atualizado para o estado %3." "Order not found","Pedido não encontrado" "Update not available because the initial state is incompatible: %1","Atualização não disponível pois state inicial é incompativel: %1" "Boleto Bancário - PagBank","Boleto Bancário - PagBank" "Cartão de Crédito - PagBank","Cartão de Crédito - PagBank" +"Pay in PagBank","Pagar no PagBank" "Pix - PagBank","Pix - PagBank" "Get Payment Update","Obter Atualização de Pagamento" "This decision will not change the status in PagBank.","Esta decisão não mudará o status no PagBank." "Accept Offline Payment","Aceitar Pagamento Offline" "Deny Offline Payment","Negar Pagamento Offline" +"Not implemented","Não implementado" +"Capture can not be performed through vault","A captura não pode ser realizada através do cofre" Due,Vencimento Instruction,Instruções "Not available.","Não disponível." @@ -91,28 +96,28 @@ Link,Link "Payer Tax Id","CPF/CNPJ do Pagador" "Pay by Compute","Pagar pelo Computador" "Pay by Mobile","Pagar pelo Celular" +"Payer Phone","Telefone do Pagador" "Pix Qr Code","Pix Qr Code" "Pix Copy and Paste","Pix Cópia e Cola" -"Payer Phone","Telefone do Pagador" "The Boleto barcode is","O código de barras do boleto é" Copy,Copiar Copied,Copiado "To make the payment:","Para realizar o pagamento:" "Access your PagBank account by clicking on the link:","Acesse sua conta PagBank clicando no link:" "You must be redirected to PagBank to complete the payment.","Você deve será redirecionado ao PagBank para concluir o pagamento." -"Use the camera on your mobile device to scan the QR Code:","Use a câmera do seu celular para escanear o Qr Code:" -"Pay in PagBank","Pagar com PagBank" -"You must click the link indicated by the camera.","Você deve clicar no link indicado pela câmera para concluir o pagamento diretamente sua conta PagBank." -"To pay, read the Qr Code","Para o pagamento, faço a leitura do Qr Code" "Open the PagBank app on your phone;","Abra no seu celular o aplicativo PagBank;" "Go to the Pix/Qr Code option;","Vá em na opção Pix/Qr Code;" -"Select the option "Pay with Qr Code";","Escolha a opção "Pagar com Qr Code"; e" +"Select the option Pay with Qr Code;","Escolha a opção Pagar com Qr Code; e" "Scan the Qr Code:","Faça a leitura do Qr Code:" +"Pay in PagBank","Pagar com PagBank" +"Atenção o Qr Code gerado só é válido para uso no aplicatico do PagBank.","Atenção o Qr Code gerado só é válido para uso no aplicatico do PagBank." +"To pay, read the Qr Code","Para o pagamento, faço a leitura do Qr Code" "Or if you prefer, copy and paste the code","Ou se preferir, copie e cole o código" "Boleto Information","Informações do Boleto" Waiting...,Aguardando... "Place Order","Concluir Pagamento" -"Credit Card Information","Informações do Cartão de Crédito" +"Card Information","Informações do Cartão" +"Type Transaction","Tipo de Pagamento" "Credit Card Number","Número do Cartão de Crédito" "What is this?","O que é isso?" "CVV - Card Verification Number","CVV - Código de Segurança" @@ -122,8 +127,10 @@ Waiting...,Aguardando... "Select Instalmment","Selecione o Parcelamento" "Save for later use.","Salvar para uso futuro." "A 3-digit number in italics on the back of your credit card.","Um número de 3 dígitos em itálico no verso do seu cartão de crédito." +"Card Type","Tipo de Cartão" Month,Mês Year,Ano +"Information for paying with PagBank","Informações para pagar com PagBank" "Payer Information","Informação do Pagador" "Payer Tax id","CPF/CNPJ do Pagador" "Payer Full Name","Nome do Pagador" @@ -137,12 +144,14 @@ expires,expirando "%1x of %2 %3","%1x de %2 %3" "card issuer","banco emissor" "Verification of data","Confirmação de dados" -"Confirm my data","Comfirmar meus dados" +"Confirm my data","Confirmar meus dados" "This type of card is not accepted.","Este tipo de cartão não é aceito." "Please enter a valid credit card type number.","Insira um número de tipo de cartão de crédito válido." "Please enter a valid credit card number.","Por favor digite um número de cartão de crédito válido." "Please enter a valid credit card verification number.","Insira um número de verificação de cartão de crédito válido (CVV)." "Please provide a valid CPF/CNPJ.","Forneça um CPF/CNPJ válido." +"Credit","Crédito" +"Debit","Débito" "Unable to complete the payment with this card, please verify the information and try again.","Não foi possível concluir o pagamento com este cartão, por favor verifique as informações e tente novamente." "Error while processing Payment","Erro ao processar o pagamento." Ok,Ok @@ -186,9 +195,22 @@ Title,Título "3D Secure","3D Secure" "3D Secure configuration.","3D Secure configuração." "Authorization is required to use this service. Please get in touch with PagBank for further assistance.","Para utilizar esse serviço você precisa de autorização. Por favor entre em contato com a PagBank." +"Enabled Debit Card","Habilitar cartão de débito" +"Allow payment with debit card.","Permitir pagamento com cartão de débito" "Reject payment not authenticated","Rejeitar pagamentos não autenticados" "Instruction before challenge","Instrução antes do desafio" "%1 and %2 are two variables, they will be replaced by the card's flag and the issuer bank's name, respectively.","%1 e %2 são duas variáveis que serão substituídas pela bandeira do cartão e pelo nome do banco emissor, respectivamente." +"Activation rules","Regras de ativação" +"Advanced settings for 3D Secure application.","Configurações avançadas para aplicação do 3D Secure." +"Activate after the number of failed attempts","Ativar após número de tentativas falhas" +"3D Secure authentication will be required if the number of purchase attempts (that fail) exceeds the value registered here.","Será solicitada a autenticação via 3D Secure caso o número de tentativas de compras (que derem falha) supere o valor aqui cadastrado." +"

During checkout, if the customer tries to purchase and their order is denied, the number of attempts will increase. This feature is useful to prevent automated fraud attempts.

","

Durante o checkout se o cliente tentar comprar e tiver o seu pedido negado, será acrescido o número de tentativas. Esse recurso é útil para previnir tentativas de fraude automatizadas.

" +"Activate after the order value exceeds","Ativar após valor do pedido exceder" +"3D Secure authentication will be required if the order value exceeds the value registered here.","Será solicitada a autenticação via 3D Secure caso o valor do pedido supere o valor aqui cadastrado." +"

We recommend using values that exceed the normal ticket, which may indicate possible fraud.

","

Recomendamos que utilize valores que superem o ticket normal, o que pode ser um indicativo de uma possível fraude.

" +"If the order contains the SKU","Se o pedido contiver o SKU" +"You can register multiple SKUs, use commas to separate them. 3D Secure authentication will be required if the order contains the SKU.","Você pode cadastrar diversos, use virgula para separar os sku's. Será solicitada a autenticação via 3D Secure caso o pedido tenha o SKU" +"

If you have products that are more sensitive to fraud, you can register these SKUs here.

","

Caso tenha produtos que sejam mais sensíveis a fraude, vocês pode cadastrar esses sku's aqui.

" "Capture phone in the payment form?","Capturar telefone no formulário de pagamento?" "Installment and interest","Parcelamento e Juros" "Maximum number of installment","Número máximo de parcelas" @@ -197,6 +219,8 @@ Title,Título "Number of installments you want to accept without applying interest","Número de parcelas que pretende aceitar sem aplicar juros" "The minimum installment price","O preço mínimo da parcela" "It is the minimum value that the installment can have","É o valor mínimo que a parcela pode ter" +"Pagar com PagBank","Pagar com PagBank" +"O botão de pagamento que deixa você um passo à frente da concorrência!","O botão de pagamento que deixa você um passo à frente da concorrência!" Developers,Desenvolvedores "Meet our Wiki.","Conheça a nossa Wiki." Debug,Debug @@ -260,6 +284,7 @@ Pix,Pix "[10002] Transação não autorizada, por favor utilize outro forma de pagamento.","[10002] Transação não autorizada, por favor utilize outro forma de pagamento." "[10003] Transação inválida, por favor utilize outra forma de pagamento.","[10003] Transação inválida, por favor utilize outra forma de pagamento." "[10004] Transação não permitida, por favor utilize outro forma de pagamento.","[10004] Transação não permitida, por favor utilize outro forma de pagamento." +PagBank Interest,Juros de Parcelamento "qr_code_image","Imagem do Qr Code" "qr_code","Qr Code" "expiration_date","Data de expiração" @@ -276,4 +301,6 @@ Pix,Pix "cc_cardholder_name","Nome Impresso" "three_ds_session","Id da Sessão 3DS" "three_ds_auth","Tipo de Autenticação 3DS" -"three_ds_auth_status","Status da Autenticação 3DS" \ No newline at end of file +"three_ds_auth_status","Status da Autenticação 3DS" +"cc_authorization_code","Código da Autorização" +"cc_nsu","NSU" \ No newline at end of file diff --git a/view/adminhtml/templates/system/config/apps.phtml b/view/adminhtml/templates/system/config/apps.phtml new file mode 100644 index 0000000..63d7703 --- /dev/null +++ b/view/adminhtml/templates/system/config/apps.phtml @@ -0,0 +1,106 @@ + + * @license See LICENSE for license details. + */ + +/** + * @var \PagBank\PaymentMagento\Block\Adminhtml\System\Config\Oauth $block + */ +?> +
+

escapeHtml(__('Conheça e compare nossos planos promocionais'), ['b']) ?>

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
escapeHtml(__('Magento e Adobe Commerce - Account Profile')) ?>escapeHtml(__('Magento e Adobe Commerce - D14')) ?>escapeHtml(__('Magento e Adobe Commerce - D30')) ?>
escapeHtml(__('Tipo de Recebimento')) ?>escapeHtml(__('Conforme definido em sua conta')) ?>escapeHtml(__('Receba em até 14 dias')) ?>escapeHtml(__('Receba em até 30 dias')) ?>
escapeHtml(__('Taxas*')) ?>escapeHtml(__('Conforme definido em sua conta')) ?> + escapeHtml(__('Cartão:')) ?> +
    +
  • escapeHtml(__('1x com taxa de 1.69%')) ?>
  • +
  • escapeHtml(__('2x a 4x com taxa de 1.99%')) ?>
  • +
  • escapeHtml(__('5x a 18x com taxa de 1.99%')) ?>
  • +
+ escapeHtml(__('Pix:')) ?> +
    +
  • escapeHtml(__('Fixa em R$ 0,50')) ?>
  • +
+ escapeHtml(__('Boleto:')) ?> +
    +
  • escapeHtml(__('Fixa em R$ 0,50')) ?>
  • +
+
+ escapeHtml(__('Cartão:')) ?> +
    +
  • escapeHtml(__('1x com taxa de 1.69%')) ?>
  • +
  • escapeHtml(__('2x a 4x com taxa de 1.99%')) ?>
  • +
  • escapeHtml(__('5x a 18x com taxa de 1.99%')) ?>
  • +
+ escapeHtml(__('Pix:')) ?> +
    +
  • escapeHtml(__('Fixa em R$ 0,50')) ?>
  • +
+ escapeHtml(__('Boleto:')) ?> +
    +
  • escapeHtml(__('Fixa em R$ 0,50')) ?>
  • +
+
escapeHtml(__('Vantagens')) ?> +
    +
  • escapeHtml(__('Ideal para quem fatura acima de R$ 300.000')) ?>
  • +
  • escapeHtml(__('Taxas e recebimentos personalizados')) ?>
  • +
+
+
    +
  • escapeHtml(__('Ideal para quem precisa de maior fluxo de caixa')) ?>
  • +
  • escapeHtml(__('Taxas reduzidas')) ?>
  • +
+
+
    +
  • escapeHtml(__('Ideal para quem tem maior fluxo de caixa')) ?>
  • +
  • escapeHtml(__('As melhores taxas do mercado')) ?>
  • +
+
escapeHtml(__('Estado')) ?> + escapeHtml(__('Esse plano está configurado e em uso atualmente.'), ['b']) ?> + + escapeHtml(__('Esse plano está configurado mas não está em uso.'), ['b']) ?> + escapeHtml(__('Para usar esse plano, selecione na guia credenciais.')) ?> + + escapeHtml(__('Para usar esse plano, selecione na guia credenciais.')) ?> +
+

+ escapeHtml( + __('* As taxas aqui anunciadas podem sofrer variações, consulte nossa página para os valores atualizados.') + ) ?> +

+
diff --git a/view/adminhtml/templates/system/config/oauth.phtml b/view/adminhtml/templates/system/config/oauth.phtml index 2c1d746..a0e19ee 100644 --- a/view/adminhtml/templates/system/config/oauth.phtml +++ b/view/adminhtml/templates/system/config/oauth.phtml @@ -18,23 +18,44 @@ require([ 'jquery', 'prototype' ], function($) { - var pagbankOauthSpan = jQuery('#pagbank-oauth_span'); - + console.log('account'); + $('#payment_other_pagbank_base_settings_environment').change( () => { - $('#pagbank_elements_for_pagbank-oauth').html( - 'After changing the environment,' + - ' it is necessary to save the configuration' + - 'before using the authentication function.' - );} + $('#pagbank_elements_for_pagbank-oauth').html( + 'After changing the environment,' + + ' it is necessary to save the configuration' + + 'before using the authentication function.' + ); + } ); $('#payment_us_pagbank_base_settings_environment').change( () => { - $('#pagbank_elements_for_pagbank-oauth').html( - 'Após mudar o ambiente é necessário salvar' + - ' a configuração antes de usar a função de autenticação.' - );} + $('#pagbank_elements_for_pagbank-oauth').html( + 'Após mudar o ambiente é necessário salvar' + + ' a configuração antes de usar a função de autenticação.' + ); + } + ); + + $('#payment_other_pagbank_base_settings_type_app').change( + () => { + $('#pagbank_elements_for_pagbank-oauth').html( + 'After changing the environment,' + + ' it is necessary to save the configuration' + + 'before using the authentication function.' + ); + } + ); + + $('#payment_us_pagbank_base_settings_type_app').change( + () => { + $('#pagbank_elements_for_pagbank-oauth').html( + 'Após mudar o ambiente é necessário salvar' + + ' a configuração antes de usar a função de autenticação.' + ); + } ); $('#pagbank-oauth').click(function () { diff --git a/view/adminhtml/web/css/system_config.css b/view/adminhtml/web/css/system_config.css index e59d192..a9421a0 100644 --- a/view/adminhtml/web/css/system_config.css +++ b/view/adminhtml/web/css/system_config.css @@ -43,4 +43,43 @@ fieldset#payment_us_pagbank_base { .pagbank-sub-title { padding-top: 15px; +} + +.admin__table_apps_pagbank h1 { + text-align: center; + color: #2c3e50; +} +.admin__table_apps_pagbank table { + width: 96%; + border-collapse: collapse; + background-color: white; + box-shadow: 0 2px 2px 0 rgba(0, 0, 0, .24), 0 0 2px 0 rgba(0, 0, 0, .12); + margin: 20px auto; +} +.admin__table_apps_pagbank th, .admin__table_apps_pagbank td { + padding: 15px !important; + text-align: left; + border: 1px solid #ddd; +} +.admin__table_apps_pagbank th { + background-color: #1bb99a; + color: white; + font-weight: bold; +} +.admin__table_apps_pagbank .feature { + width: 15%; + font-weight: bold; + background-color: #f8f8f8; +} +.admin__table_apps_pagbank .plan { + width: 28.33%; +} +.admin__table_apps_pagbank ul { + margin: 0; + padding-left: 20px; +} + +.admin__table_apps_pagbank .note { + color: #999; + font-size: 10; } \ No newline at end of file diff --git a/view/base/web/js/action/checkout/list-installments.js b/view/base/web/js/action/checkout/list-installments.js index c3e2e09..b75a443 100644 --- a/view/base/web/js/action/checkout/list-installments.js +++ b/view/base/web/js/action/checkout/list-installments.js @@ -28,8 +28,7 @@ define([ ) { 'use strict'; - return function (creditCardBin) { - + return function (payload) { var deferred = $.Deferred(), serviceUrl, options, @@ -40,11 +39,7 @@ define([ label, supplementaryText, quoteId = quote.getQuoteId(), - payload = { - 'creditCardBin': { - 'credit_card_bin': creditCardBin - } - }; + creditCardBin = payload.creditCardBin.credit_card_bin; serviceUrl = urlBuilder.createUrl('/carts/mine/pagbank-list-installments', {}); @@ -54,9 +49,8 @@ define([ }); } - if (creditCardBin.length === 6) { + if (creditCardBin && creditCardBin.length === 6) { try { - $.ajax({ url: urlFormatter.build(serviceUrl), global: false, @@ -70,21 +64,20 @@ define([ listFormated = _.map(options, (value) => { supplementaryText = $t('in total of %1') - .replace('%1', priceUtils.formatPrice( - value.amount.value / 100, quote.getPriceFormat() - )); + .replace('%1', priceUtils.formatPrice( + value.amount.value / 100, quote.getPriceFormat() + )); if (value.interest_free) { supplementaryText = $t('not interest'); } label = $t('%1x of %2 %3') - .replace('%1', value.installments) - .replace('%2', priceUtils.formatPrice( - value.installment_value / 100, quote.getPriceFormat() - ) - ) - .replace('%3', supplementaryText); + .replace('%1', value.installments) + .replace('%2', priceUtils.formatPrice( + value.installment_value / 100, quote.getPriceFormat() + )) + .replace('%3', supplementaryText); return { 'installment_value': value.installments, @@ -94,10 +87,14 @@ define([ deferred.resolve(listFormated); } - ); + ).fail(() => { + deferred.reject(new Error('Error when generating installments.')); + }); } catch (exc) { deferred.reject(new Error('Error when generating installments.')); } + } else { + deferred.resolve(listFormated); } return deferred.promise(); diff --git a/view/base/web/js/model/pagbank-cc-data.js b/view/base/web/js/model/pagbank-cc-data.js index 80e79ea..cc4f867 100644 --- a/view/base/web/js/model/pagbank-cc-data.js +++ b/view/base/web/js/model/pagbank-cc-data.js @@ -23,6 +23,7 @@ define([], function () { creditCardInstallment: null, selectedCardType: null, creditCardOptionsInstallments: null, + cardTypeTransaction: null, threeDSecureSession: null, threeDSecureAuth: null, threeDSecureAuthStatus: null diff --git a/view/frontend/templates/sales/order/success/deep-link.phtml b/view/frontend/templates/sales/order/success/deep-link.phtml index f58a5f1..339ebb0 100644 --- a/view/frontend/templates/sales/order/success/deep-link.phtml +++ b/view/frontend/templates/sales/order/success/deep-link.phtml @@ -56,7 +56,7 @@ $qrCodeImage = $block->getInfo('qr_code_url_image');
  • escapeHtml( - __('Select the option "Pay with Qr Code";'), + __('Select the option Pay with Qr Code;'), ['strong'] ) ?>
  • diff --git a/view/frontend/web/js/view/payment/base-data-for-payment-form.js b/view/frontend/web/js/view/payment/base-data-for-payment-form.js index bcd2e3f..a5e4efc 100644 --- a/view/frontend/web/js/view/payment/base-data-for-payment-form.js +++ b/view/frontend/web/js/view/payment/base-data-for-payment-form.js @@ -66,22 +66,12 @@ function ( : false; }, - /** - * Has 3ds - * @returns {Boolean|*} - */ - hasThreeDs() { - return window.checkoutConfig.payment[this.paymentCode].threeDs.hasOwnProperty('active') ? - window.checkoutConfig.payment[this.paymentCode].threeDs.active - : false; - }, - /** * Get Env * @returns {String|*} */ getEnv() { - return window.checkoutConfig.payment[this.paymentCode].threeDs.hasOwnProperty('active') ? + return window.checkoutConfig.payment[this.paymentCode].threeDs.hasOwnProperty('env') ? window.checkoutConfig.payment[this.paymentCode].threeDs.env : false; }, diff --git a/view/frontend/web/js/view/payment/cc-form.js b/view/frontend/web/js/view/payment/cc-form.js index 8ccf934..559cbf9 100644 --- a/view/frontend/web/js/view/payment/cc-form.js +++ b/view/frontend/web/js/view/payment/cc-form.js @@ -37,15 +37,16 @@ define([ return Component.extend({ defaults: { - creditCardNumber: '', - creditCardVerificationNumber: '', - creditCardType: '', - creditCardExpYear: '', - creditCardExpMonth: '', - creditCardHolderName: '', + creditCardNumber: '', //5200000000001096 + creditCardVerificationNumber: '', //123 + creditCardType: '', //MC + creditCardExpYear: '', //2024 + creditCardExpMonth: '', //10 + creditCardHolderName: '', //Test tres ds creditCardInstallment: '', - selectedCardType: '', - creditCardOptionsInstallments: null + selectedCardType: '', //MC + creditCardOptionsInstallments: null, + cardTypeTransaction: 'CREDIT_CARD' }, totals: quote.getTotals(), @@ -63,6 +64,8 @@ define([ 'creditCardInstallment', 'selectedCardType', 'creditCardOptionsInstallments', + 'cardTypeTransaction', + 'countTryPlaceOrder', 'threeDSecureSession', 'threeDSecureAuth', 'threeDSecureAuthStatus' @@ -124,6 +127,15 @@ define([ self.getListInstallments(number); } }); + self.cardTypeTransaction.subscribe((value) => { + if (value === 'DEBIT_CARD') { + self.creditCardInstallment(1); + creditCardData.creditCardInstallment = 1; + } else { + self.creditCardInstallment(0); + creditCardData.creditCardInstallment = 0; + } + }); }, /** @@ -135,9 +147,19 @@ define([ getListInstallments(number) { var self = this, creditCardBin = number.replace(/\s/g,'').slice(0, 6), - deferred = $.Deferred(); + cardTypeTransaction = self.cardTypeTransaction(), + deferred = $.Deferred(), + requestData = { + 'creditCardBin': { + 'credit_card_bin': creditCardBin + }, + 'cardTypeTransaction': { + 'card_type_transaction': cardTypeTransaction + } + }; + - ListInstallments(creditCardBin) + ListInstallments(requestData) .then((response) => { self.creditCardOptionsInstallments(response); deferred.resolve(response); @@ -235,6 +257,23 @@ define([ return window.checkoutConfig.payment.ccform.hasVerification[this.getCode()]; }, + /** + * Get card type values + * @returns {Object} + */ + getCardTypeTransactionValues() { + return [ + { + 'value': 'CREDIT_CARD', + 'label': $t('Credit') + }, + { + 'value': 'DEBIT_CARD', + 'label': $t('Debit') + } + ]; + }, + /** * Get list of available credit card types values * @returns {Object} diff --git a/view/frontend/web/js/view/payment/method-renderer/cc.js b/view/frontend/web/js/view/payment/method-renderer/cc.js index 010966f..a28eee6 100644 --- a/view/frontend/web/js/view/payment/method-renderer/cc.js +++ b/view/frontend/web/js/view/payment/method-renderer/cc.js @@ -36,6 +36,7 @@ define([ ccForm: 'PagBank_PaymentMagento/payment/cc-form', payerForm: 'PagBank_PaymentMagento/payment/payer-form', creditCardNumberToken: '', + countTryPlaceOrder: 0, threeDSecureSession: '', threeDSecureAuth: '', threeDSecureAuthStatus: '', @@ -134,7 +135,8 @@ define([ 'method': this.getCode(), 'additional_data': { 'cc_number_token': this.creditCardNumberToken(), - 'cc_installments': this.creditCardInstallment(), + 'cc_installments': this.creditCardInstallment() ? this.creditCardInstallment() : 1, + 'card_type_transaction': this.cardTypeTransaction(), 'three_ds_session': this.threeDSecureSession(), 'three_ds_auth': this.threeDSecureAuth(), 'three_ds_auth_status': this.threeDSecureAuthStatus(), @@ -160,8 +162,48 @@ define([ * Is vault enabled * @returns {Boolean} */ - isVaultEnabled: function () { + isVaultEnabled() { return this.vaultEnabler.isVaultEnabled(); + }, + + /** + * Has 3ds + * @returns {Boolean|*} + */ + isEnableDebit() { + return window.checkoutConfig.payment[this.getCode()].threeDs.hasOwnProperty('enable_deb') ? + window.checkoutConfig.payment[this.getCode()].threeDs.enable_deb + : false; + }, + + /** + * Get Max Try Place Order + * @returns {Interger} + */ + getMaxTryPlaceOrder() { + return window.checkoutConfig.payment[this.getCode()].threeDs.hasOwnProperty('max_try_place') ? + window.checkoutConfig.payment[this.getCode()].threeDs.max_try_place + : 0; + }, + + /** + * Is Applicable + * @returns {Boolean|*} + */ + isApplicable() { + return window.checkoutConfig.payment[this.getCode()].threeDs.hasOwnProperty('applicable') ? + window.checkoutConfig.payment[this.getCode()].threeDs.applicable + : false; + }, + + /** + * Is Active 3ds + * @returns {Boolean|*} + */ + isActiveThreeDs() { + return window.checkoutConfig.payment[this.getCode()].threeDs.hasOwnProperty('enable') ? + window.checkoutConfig.payment[this.getCode()].threeDs.enable + : false; } }); }); diff --git a/view/frontend/web/js/view/payment/method-renderer/vault.js b/view/frontend/web/js/view/payment/method-renderer/vault.js index e8e3fe7..b3f1e70 100644 --- a/view/frontend/web/js/view/payment/method-renderer/vault.js +++ b/view/frontend/web/js/view/payment/method-renderer/vault.js @@ -121,9 +121,17 @@ define([ */ getListInstallments(creditCardBin) { var self = this, - deferred = $.Deferred(); - - ListInstallments(creditCardBin) + deferred = $.Deferred(), + requestData = { + 'creditCardBin': { + 'credit_card_bin': creditCardBin + }, + 'cardTypeTransaction': { + 'card_type_transaction': 'CREDIT_CARD' + } + }; + + ListInstallments(requestData) .then((response) => { self.creditCardOptionsInstallments(response); }) diff --git a/view/frontend/web/js/view/payment/pagbank-place-order.js b/view/frontend/web/js/view/payment/pagbank-place-order.js index 77decc3..c1ffc56 100644 --- a/view/frontend/web/js/view/payment/pagbank-place-order.js +++ b/view/frontend/web/js/view/payment/pagbank-place-order.js @@ -48,10 +48,15 @@ define([ * @returns {Void} */ getPagBankPlace(context, callback, errorCallback) { - let encrypted; + let encrypted, + countPlaceOrder = context.countTryPlaceOrder(), + maxTry = context.getMaxTryPlaceOrder(), + typePay = context.cardTypeTransaction(), + enable = context.isActiveThreeDs(), + applicable = context.isApplicable(), + forceThreeDs = false; fullScreenLoader.startLoader(); - encrypted = this.getPagBankTokenize(context); if (!encrypted) { @@ -59,13 +64,20 @@ define([ } if (encrypted) { - if (context.baseDataForPaymentForm.hasThreeDs()) { + countPlaceOrder++; + context.countTryPlaceOrder(countPlaceOrder); + + if (countPlaceOrder > maxTry) { + forceThreeDs = enable ? true : false; + } + + if (applicable || typePay === 'DEBIT_CARD' || forceThreeDs) { ThreeDS() .then((session) => { var sessionId = session.session_id, cardPayData = { - type: 'CREDIT_CARD', - installments: context.creditCardInstallment(), + type: context.cardTypeTransaction(), + installments: context.creditCardInstallment() ? context.creditCardInstallment() : 1, card: { number: context.creditCardNumber().replace(/\s/g,''), expMonth: context.creditCardExpMonth(), @@ -80,12 +92,15 @@ define([ return this.sendDataForThreeDS(sessionId, data, context); }).then((result) => { if (result) { + fullScreenLoader.stopLoader(); callback(); } else { errorCallback(); + fullScreenLoader.stopLoader(); } }).catch(() => { errorCallback(); + fullScreenLoader.stopLoader(); }); } else { fullScreenLoader.stopLoader(); diff --git a/view/frontend/web/template/payment/cc-form.html b/view/frontend/web/template/payment/cc-form.html index 8e1c080..b4cd11c 100644 --- a/view/frontend/web/template/payment/cc-form.html +++ b/view/frontend/web/template/payment/cc-form.html @@ -12,7 +12,7 @@
    - +
      @@ -49,6 +49,25 @@ + +
      +
      + + +
      +
      +
      @@ -59,6 +78,9 @@ autocomplete: 'cc-number', id: getCode() + '_number', title: $t('Credit Card Number'), + maxlength: '26', + minlength: '8', + pattern: '^[0-9\\s]+$', placeholder: $t('Credit Card Number'), 'data-container': getCode() + '-cc-number', 'data-validate': JSON.stringify({ @@ -98,12 +120,15 @@
      -