Skip to content

Commit

Permalink
Merge pull request #73 from elisei/Magento@2.4.6
Browse files Browse the repository at this point in the history
PagBank 😍 Magento
  • Loading branch information
elisei authored Dec 5, 2024
2 parents 0ef5fa1 + b6a769d commit 23e80c9
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 8 deletions.
90 changes: 85 additions & 5 deletions Gateway/Config/ConfigCc.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@

namespace PagBank\PaymentMagento\Gateway\Config;

use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Payment\Gateway\Config\Config as PaymentConfig;
use Magento\Payment\Model\Method\AbstractMethod;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Store\Model\ScopeInterface;

/**
Expand Down Expand Up @@ -94,17 +97,41 @@ class ConfigCc extends PaymentConfig
protected $json;

/**
* @param ScopeConfigInterface $scopeConfig
* @param Json $json
* @param string $methodCode
* @var SearchCriteriaBuilder
*/
protected $searchCriteria;

/**
* @var DateTime
*/
protected $dateTime;

/**
* @var OrderRepositoryInterface
*/
protected $orderRepository;

/**
* @param ScopeConfigInterface $scopeConfig
* @param Json $json
* @param SearchCriteriaBuilder $searchCriteria
* @param DateTime $dateTime
* @param OrderRepositoryInterface $orderRepository
* @param string $methodCode
*/
public function __construct(
ScopeConfigInterface $scopeConfig,
Json $json,
SearchCriteriaBuilder $searchCriteria,
DateTime $dateTime,
OrderRepositoryInterface $orderRepository,
$methodCode = self::METHOD
) {
parent::__construct($scopeConfig, $methodCode);
$this->scopeConfig = $scopeConfig;
$this->searchCriteria = $searchCriteria;
$this->dateTime = $dateTime;
$this->orderRepository = $orderRepository;
$this->json = $json;
}

Expand Down Expand Up @@ -462,6 +489,55 @@ public function getThreeDsSkus($storeId = null): array
return $threeDsSkus ? explode(',', $threeDsSkus) : [];
}

/**
* Get Canceled Transaction Time.
*
* @param int|null $storeId
* @return string
*/
public function getCanceledTransTime($storeId = null): string
{
$pathPattern = 'payment/%s/%s';

return (string) $this->scopeConfig->getValue(
sprintf($pathPattern, self::METHOD, 'three_ds_canceled_trans_time'),
ScopeInterface::SCOPE_STORE,
$storeId
) ?: '';
}

/**
* Has transaction been cancelled in time.
*
* @param \Magento\Checkout\Model\Cart $cart
* @param int|null $storeId
* @return bool
*/
public function hasTransBeenCanceled(\Magento\Checkout\Model\Cart $cart, $storeId = null): bool
{
$customerEmail = $cart->getQuote()->getCustomerEmail();
$time = $this->getCanceledTransTime($storeId);

if (!$time) {
return false;
}

$timeStart = $this->dateTime->gmtDate('Y-m-d H:i:s', strtotime("-{$time} hours"));
$timeEnd = $this->dateTime->gmtDate('Y-m-d H:i:s');

$search = $this->searchCriteria
->addFilter('customer_email', $customerEmail, 'eq')
->addFilter('state', 'canceled', 'eq')
->addFilter('created_at', $timeStart, 'gteq')
->addFilter('created_at', $timeEnd, 'lteq')
->create();

$orderList = $this->orderRepository->getList($search);
$orders = $orderList->getItems();

return !empty($orders);
}

/**
* Is 3ds Applicable.
*
Expand All @@ -472,12 +548,12 @@ public function getThreeDsSkus($storeId = null): array
*/
public function isThreeDsApplicable(\Magento\Checkout\Model\Cart $cart, $storeId = null): bool
{
$quote = $cart->getQuote();

if (!$this->hasThreeDsAuth($storeId)) {
return false;
}

$quote = $cart->getQuote();

$threeDsMinOrderTotal = (float) $this->getThreeDsMinOrderTotal($storeId);

$total = $quote->getGrandTotal();
Expand All @@ -498,6 +574,10 @@ public function isThreeDsApplicable(\Magento\Checkout\Model\Cart $cart, $storeId
}
}

if ($this->hasTransBeenCanceled($cart, $storeId)) {
return true;
}

return false;
}
}
36 changes: 36 additions & 0 deletions Model/Adminhtml/Source/Times.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
/**
* PagBank Payment Magento Module.
*
* Copyright © 2023 PagBank. All rights reserved.
*
* @author Bruno Elisei <brunoelisei@o2ti.com>
* @license See LICENSE for license details.
*/

namespace PagBank\PaymentMagento\Model\Adminhtml\Source;

use Magento\Framework\Option\ArrayInterface;

/**
* Class Times - Defines possible times for rule 3ds.
*/
class Times implements ArrayInterface
{
/**
* Returns Options.
*
* @return array
*/
public function toOptionArray(): array
{
return [
'0' => __('Do not apply rule'),
'24' => __('1 day'),
'48' => __('2 days - recommended'),
'72' => __('3 days'),
'168' => __('1 week'),
'720' => __('1 month'),
];
}
}
9 changes: 8 additions & 1 deletion etc/adminhtml/system/credit_card.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
</field>
<group id="three_ds_rules" translate="label comment" type="text" sortOrder="1000" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Activation rules</label>
<comment>Advanced settings for 3D Secure application.</comment>
<comment>Advanced settings for 3D Secure application. Activation will be done if the order meets at least 1 of the rules.</comment>
<field id="three_ds_max_try_place_order" translate="label comment tooltip" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Activate after the number of failed attempts</label>
<comment><![CDATA[3D Secure authentication will be required if the <b>number of purchase attempts</b> (that fail) exceeds the value registered here.]]></comment>
Expand All @@ -86,6 +86,13 @@
<tooltip><![CDATA[<p>If you have products that are more sensitive to fraud, you can register these SKUs here.</p>]]></tooltip>
<config_path>payment/pagbank_paymentmagento_cc/three_ds_has_sku</config_path>
</field>
<field id="three_ds_canceled_trans_time" translate="label comment tooltip" type="select" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
<label>If the customer has canceled the order in the last few</label>
<source_model>PagBank\PaymentMagento\Model\Adminhtml\Source\Times</source_model>
<comment><![CDATA[Authentication via 3D Secure will be requested if the customer has an <b>order cancelled</b> within the chosen time period.]]></comment>
<tooltip><![CDATA[<p>When verifying that the customer has an order canceled within the chosen time interval, 3ds authentication will be requested.</p>]]></tooltip>
<config_path>payment/pagbank_paymentmagento_cc/three_ds_canceled_trans_time</config_path>
</field>
</group>
</group>
<group id="basic_configuration" translate="label comment" type="text" sortOrder="1000" showInDefault="1" showInWebsite="1" showInStore="1">
Expand Down
9 changes: 8 additions & 1 deletion i18n/en_US.csv
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ Close,Close
"4st line of the street","4st line of the street"
"by customer form (taxvat - customer account)","by customer form (taxvat - customer account)"
"by address form (vat_id - checkout)","by address form (vat_id - checkout)"
"Do not apply rule","Do not apply rule"
"2 days - recommended","2 days - recommended"
"1 week","1 week"
"1 month","1 month"
"Set in your Account","Set in your Account"
"Receive within 14 days","Receive within 14 days"
"Receive within 30 days","Receive within 30 days"
Expand Down Expand Up @@ -246,7 +250,7 @@ Title,Title
"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."
"Advanced settings for 3D Secure application. Activation will be done if the order meets at least 1 of the rules.","Advanced settings for 3D Secure application. Activation will be done if the order meets at least 1 of the rules."
"Activate after the number of failed attempts","Activate after the number of failed attempts"
"3D Secure authentication will be required if the <b>number of purchase attempts</b> (that fail) exceeds the value registered here.","3D Secure authentication will be required if the <b>number of purchase attempts</b> (that fail) exceeds the value registered here."
"<p>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.</p>","<p>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.</p>"
Expand All @@ -256,6 +260,9 @@ Title,Title
"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 <b>order contains the SKU</b>.","You can register multiple SKUs, use commas to separate them. 3D Secure authentication will be required if the <b>order contains the SKU</b>."
"<p>If you have products that are more sensitive to fraud, you can register these SKUs here.</p>","<p>If you have products that are more sensitive to fraud, you can register these SKUs here.</p>"
"If the customer has canceled the order in the last few","If the customer has canceled the order in the last few"
"Authentication via 3D Secure will be requested if the customer has an <b>order cancelled</b> within the chosen time period.","Authentication via 3D Secure will be requested if the customer has an <b>order cancelled</b> within the chosen time period."
"<p>When verifying that the customer has an order canceled within the chosen time interval, 3ds authentication will be requested.</p>","<p>When verifying that the customer has an order canceled within the chosen time interval, 3ds authentication will be requested.</p>"
"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"
Expand Down
8 changes: 7 additions & 1 deletion i18n/pt_BR.csv
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ Close,Fechar
"4st line of the street","4ª linha de endereço"
"by customer form (taxvat - customer account)","pelo formulário de cliente (taxvat - customer account)"
"by address form (vat_id - checkout)","pelo formulário de endereço (vat_id - checkout)"
"Do not apply rule","Não aplicar essa regra"
"2 days - recommended","2 dias - recomendado"
"1 week","1 semana"
"1 month","1 mês"
"Set in your Account","Definido em sua Conta"
"Receive within 14 days","Receba em até 14 dias"
"Receive within 30 days","Receba em até 30 dias"
Expand Down Expand Up @@ -247,7 +251,7 @@ Title,Título
"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."
"Advanced settings for 3D Secure application. Activation will be done if the order meets at least 1 of the rules.","Configurações avançadas para aplicação do 3D Secure. A ativação será feita caso o pedido atenda a pelo menos 1 das regras."
"Activate after the number of failed attempts","Ativar após número de tentativas falhas"
"3D Secure authentication will be required if the <b>number of purchase attempts</b> (that fail) exceeds the value registered here.","Será solicitada a autenticação via 3D Secure caso o <b>número de tentativas de compras</b> (que derem falha) supere o valor aqui cadastrado."
"<p>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.</p>","<p>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.</p>"
Expand All @@ -256,6 +260,8 @@ Title,Título
"<p>We recommend using values that exceed the normal ticket, which may indicate possible fraud.</p>","<p>Recomendamos que utilize valores que superem o ticket normal, o que pode ser um indicativo de uma possível fraude.</p>"
"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 <b>order contains the SKU</b>.","Você pode cadastrar diversos, use virgula para separar os sku's. Será solicitada a autenticação via 3D Secure caso o <b>pedido tenha o SKU</b>"
"Authentication via 3D Secure will be requested if the customer has an <b>order cancelled</b> within the chosen time period.","A autenticação via 3D Secure será solicitada caso o cliente tenha um <b>pedido cancelado</b> dentro do período de tempo escolhido."
"<p>When verifying that the customer has an order canceled within the chosen time interval, 3ds authentication will be requested.</p>","<p>Ao verificar que o cliente possui um pedido cancelado dentro do intervalo de tempo escolhido, será solicitada a autenticação 3ds.</p>"
"<p>If you have products that are more sensitive to fraud, you can register these SKUs here.</p>","<p>Caso tenha produtos que sejam mais sensíveis a fraude, vocês pode cadastrar esses sku's aqui.</p>"
"Capture phone in the payment form?","Capturar telefone no formulário de pagamento?"
"Installment and interest","Parcelamento e Juros"
Expand Down

0 comments on commit 23e80c9

Please sign in to comment.