Skip to content

Commit c185b04

Browse files
authored
Merge pull request #10 from ipagdevs/feat/AddFlowRedirectTransactionAuthentication
feat: adiciona fluxo de redirecionamento de autenticação de pagamento
2 parents f08cb61 + 787644a commit c185b04

11 files changed

Lines changed: 351 additions & 12 deletions

File tree

Block/Adminhtml/System/Config/Environment.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,15 @@ class Environment implements \Magento\Framework\Option\ArrayInterface
1010

1111
public function toOptionArray()
1212
{
13-
return [
13+
$defaultOptions = [
1414
'production' => 'Produção',
1515
'sandbox' => 'Sandbox - Ambiente de Teste',
1616
];
17+
18+
if (getenv('IPAG_ENVIRONMENT_LOCAL')) {
19+
$defaultOptions['local'] = 'Local - Ambiente de Desenvolvimento';
20+
}
21+
22+
return $defaultOptions;
1723
}
1824
}

CHANGELOG.md

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@ Todas as mudanças notáveis neste projeto serão documentadas neste arquivo.
44

55
O formato é baseado em [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), e este projeto adere ao [Versionamento Semântico](https://semver.org/spec/v2.0.0.html).
66

7+
## v1.7.0 - 2025-12-15
8+
- Adiciona novo fluxo de redirecionamento de autenticação de pgamento.
9+
710
## v1.6.0 - 2025-06-12
8-
- Habilita métodos de pagamento Pix e Boleto nas opções de pagamento de uma nova ordem no painel Admin
11+
- Habilita métodos de pagamento Pix e Boleto nas opções de pagamento de uma nova ordem no painel Admin.
912

1013
## v1.5.3 - 2025-06-11
11-
- Altera label de opções de parcelas com juros
14+
- Altera label de opções de parcelas com juros.
1215

1316
## v1.5.2 - 2024-10-23
1417
- Retirada dependências antigas do módulo não utilizadas.
@@ -61,16 +64,16 @@ O formato é baseado em [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
6164

6265
### Changed
6366

64-
- Corrigido erros no código para suporte do php 8.2
67+
- Corrigido erros no código para suporte do php 8.2.
6568

6669
## v1.1.0 - 2024-02-21
6770

6871
### Changed
6972

70-
- Melhorias no código para suporte ao php 8.2
73+
- Melhorias no código para suporte ao php 8.2.
7174

7275
## v1.0.39 - 2024-02-21
7376

7477
### Changed
7578

76-
- Melhorada o comportamento do state da order no processamento de pagamento
79+
- Melhorada o comportamento do state da order no processamento de pagamento.

Controller/Redirect/Result.php

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
<?php
2+
3+
namespace Ipag\Payment\Controller\Redirect;
4+
5+
use Magento\Sales\Model\OrderFactory;
6+
use Magento\Framework\App\Action\Context;
7+
use Magento\Framework\View\Result\PageFactory;
8+
use Magento\Sales\Api\OrderManagementInterface;
9+
use Magento\Sales\Api\OrderRepositoryInterface;
10+
use Magento\Framework\Exception\LocalizedException;
11+
use Magento\Framework\Encryption\EncryptorInterface;
12+
use Magento\Framework\App\RequestInterface;
13+
use Magento\Framework\App\Request\InvalidRequestException;
14+
use Magento\Framework\App\CsrfAwareActionInterface;
15+
16+
use Ipag\Classes\Services\CallbackService;
17+
18+
class Result extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface
19+
{
20+
protected $_logger;
21+
22+
protected $_ipagHelper;
23+
24+
protected $_ipagBoletoModel;
25+
26+
protected $_ipagInvoiceInstallments;
27+
28+
protected $_invoiceService;
29+
30+
protected $orderFactory;
31+
32+
protected $orderManagement;
33+
34+
protected $orderRepository;
35+
36+
protected $scopeConfig;
37+
38+
protected $ipagOrderStatus;
39+
40+
protected $invoiceSender;
41+
42+
protected $productMetadata;
43+
44+
protected $transactionFactory;
45+
46+
protected $ipagLogger;
47+
48+
protected $encryptor;
49+
50+
protected $resultPageFactory;
51+
52+
public function __construct(
53+
\Magento\Framework\App\Action\Context $context,
54+
\Psr\Log\LoggerInterface $logger,
55+
OrderFactory $orderFactory,
56+
OrderManagementInterface $orderManagement,
57+
OrderRepositoryInterface $orderRepository,
58+
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
59+
\Ipag\Payment\Model\Source\OrderStatus $ipagOrderStatus,
60+
\Magento\Sales\Model\Service\InvoiceService $invoiceService,
61+
\Magento\Sales\Model\Order\Email\Sender\InvoiceSender $invoiceSender,
62+
\Magento\Framework\App\ProductMetadataInterface $productMetadata,
63+
\Ipag\Payment\Helper\Data $ipagHelper,
64+
\Ipag\Payment\Logger\Logger $ipagLogger,
65+
\Ipag\Payment\Model\Method\Boleto $ipagBoletoModel,
66+
\Ipag\Payment\Model\IpagInvoiceInstallments $ipagInvoiceInstallments,
67+
\Magento\Framework\DB\TransactionFactory $transactionFactory,
68+
PageFactory $resultPageFactory,
69+
EncryptorInterface $encryptor
70+
)
71+
{
72+
$this->_invoiceService = $invoiceService;
73+
$this->_logger = $logger;
74+
$this->orderFactory = $orderFactory;
75+
$this->orderManagement = $orderManagement;
76+
$this->orderRepository = $orderRepository;
77+
$this->scopeConfig = $scopeConfig;
78+
$this->ipagOrderStatus = $ipagOrderStatus;
79+
$this->invoiceSender = $invoiceSender;
80+
$this->_ipagHelper = $ipagHelper;
81+
$this->_ipagBoletoModel = $ipagBoletoModel;
82+
$this->_ipagInvoiceInstallments = $ipagInvoiceInstallments;
83+
$this->productMetadata = $productMetadata;
84+
$this->transactionFactory = $transactionFactory;
85+
$this->ipagLogger = $ipagLogger;
86+
$this->encryptor = $encryptor;
87+
$this->resultPageFactory = $resultPageFactory;
88+
89+
parent::__construct($context);
90+
91+
//compatibilidade com Magento 2.3
92+
//o certo seria implementar a interface CsrfAwareActionInterface, mas isso quebra a retrocompatibilidade com Magento < 2.2 e PHP < 7.1
93+
// compatibility block removed: do not execute controller from constructor
94+
}
95+
96+
public function execute()
97+
{
98+
$token = $this->getRequest()->getParam('p');
99+
100+
$this->_logger->debug('redirect result controller called', ['token' => $token]);
101+
102+
try {
103+
104+
if (empty($token)) {
105+
$this->_logger->notice('Missing redirect token, redirecting to home');
106+
return $this->redirectToHome();
107+
}
108+
109+
$decoded = base64_decode($token, true);
110+
111+
if ($decoded === false) {
112+
$this->_logger->notice('Invalid base64 token, redirecting to home', ['token' => $token]);
113+
return $this->redirectToHome();
114+
}
115+
116+
$payload = $this->encryptor->decrypt($decoded);
117+
118+
$data = json_decode($payload, true);
119+
120+
if (empty($data) || empty($data['order'])) {
121+
$this->thrownException('redirect result controller: Invalid token payload', ['token' => $token, 'payload' => $payload]);
122+
}
123+
124+
$orderId = $data['order'];
125+
$this->_logger->debug('Decoded redirect token', ['order' => $orderId]);
126+
127+
$order = $this->orderFactory->create()->loadByIncrementId($orderId);
128+
129+
if (!$order || !$order->getId()) {
130+
$this->thrownLocalizedException('Order not found for decoded token', ['order' => $orderId]);
131+
}
132+
133+
$transactionId = $this->getRequest()->getParam('transaction_id');
134+
135+
if (!$transactionId) {
136+
$this->thrownLocalizedException('Missing transaction_id parameter in redirect request', ['order' => $orderId]);
137+
}
138+
139+
$ipag = $this->_ipagHelper->AuthorizationValidate();
140+
141+
$response = $ipag->transaction()->setNumPedido($orderId)->consult();
142+
143+
if (isset($response->error)) {
144+
$this->thrownLocalizedException('iPag returned an error for order consult', ['order' => $orderId, 'error' => $response->error, 'message' => $response->errorMessage]);
145+
}
146+
147+
if (!isset($response->order->orderId) || $response->order->orderId != $orderId) {
148+
$this->thrownLocalizedException('iPag returned invalid order data for order consult', ['order' => $orderId, 'response_order_id' => $response->order->orderId ?? null]);
149+
}
150+
151+
if (isset($response->payment->status) && in_array($response->payment->status, ['5', '8'])) {
152+
return $this->redirectToResultSuccess();
153+
}
154+
155+
return $this->redirectToResultError();
156+
157+
} catch (LocalizedException $e) {
158+
$this->messageManager->addError($e->getMessage());
159+
$this->_logger->error($e->getMessage());
160+
return $this->redirectToResultError();
161+
} catch (\Exception $e) {
162+
$this->messageManager->addError($e->getMessage());
163+
$this->_logger->critical($e->getMessage());
164+
return $this->redirectToHome();
165+
}
166+
}
167+
168+
private function thrownException($message, ...$rest)
169+
{
170+
$this->_logger->error($message, ...$rest);
171+
throw new \Exception($message);
172+
}
173+
174+
private function thrownLocalizedException($message, ...$rest)
175+
{
176+
$this->_logger->error($message, ...$rest);
177+
throw new LocalizedException(__($message));
178+
}
179+
180+
/**
181+
* Allow external POSTs by disabling default CSRF validation for this action.
182+
*
183+
* @param RequestInterface $request
184+
* @return InvalidRequestException|null
185+
*/
186+
public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
187+
{
188+
return null;
189+
}
190+
191+
/**
192+
* Allow the request (disable CSRF check).
193+
*
194+
* @param RequestInterface $request
195+
* @return bool|null
196+
*/
197+
public function validateForCsrf(RequestInterface $request): ?bool
198+
{
199+
return true;
200+
}
201+
202+
private function registerExceptionLog(...$rest)
203+
{
204+
$this->_logger->error(...$rest);
205+
}
206+
207+
private function redirectToResultSuccess()
208+
{
209+
$resultPage = $this->resultPageFactory->create();
210+
$resultPage->addHandle('ipag_redirect_success');
211+
$this->_logger->debug('Returning ipag redirect success page', ['handle' => 'ipag_redirect_success']);
212+
return $resultPage;
213+
}
214+
215+
private function redirectToResultError()
216+
{
217+
$resultPage = $this->resultPageFactory->create();
218+
$resultPage->addHandle('ipag_redirect_error');
219+
$this->_logger->debug('Returning ipag redirect error page', ['handle' => 'ipag_redirect_error']);
220+
return $resultPage;
221+
}
222+
223+
private function redirectToHome()
224+
{
225+
$resultRedirect = $this->resultRedirectFactory->create();
226+
$resultRedirect->setPath('');
227+
return $resultRedirect;
228+
}
229+
}

Helper/Data.php

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Ipag\Classes\Authentication;
66
use Ipag\Classes\Endpoint;
77
use Ipag\Ipag;
8+
use Magento\Framework\Encryption\EncryptorInterface;
89

910
class Data extends \Magento\Framework\App\Helper\AbstractHelper
1011
{
@@ -16,6 +17,7 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper
1617
protected $date;
1718
protected $_storeManager;
1819
protected $customerFactory;
20+
protected $encryptor;
1921

2022
const ROUND_UP = 100;
2123

@@ -75,14 +77,16 @@ public function __construct(
7577
\Magento\Framework\Stdlib\DateTime\DateTime $date,
7678
\Magento\Store\Model\StoreManagerInterface $storeManager,
7779
\Magento\Payment\Model\Method\Logger $logger,
78-
\Magento\Customer\Model\CustomerFactory $customerFactory
80+
\Magento\Customer\Model\CustomerFactory $customerFactory,
81+
EncryptorInterface $encryptor
7982
) {
8083
$this->_scopeConfig = $scopeConfig;
8184
$this->_objectManager = $objectManager;
8285
$this->date = $date;
8386
$this->_storeManager = $storeManager;
8487
$this->_logger = $logger;
8588
$this->customerFactory = $customerFactory;
89+
$this->encryptor = $encryptor;
8690
}
8791

8892
public function AuthorizationValidate()
@@ -91,6 +95,7 @@ public function AuthorizationValidate()
9195
$identification = $this->getIdentification();
9296
$apikey = $this->getApiKey();
9397
$env = $_environment === "production" ? Endpoint::PRODUCTION : Endpoint::SANDBOX;
98+
$env = $_environment === "local" ? getenv('IPAG_ENVIRONMENT_URL') : $env;
9499

95100
$auth = new Authentication($identification, $apikey);
96101
$ipag = new Ipag($auth, $env);
@@ -431,15 +436,24 @@ public function getStreetPositionDistrict()
431436
public function createOrderIpag($order, $ipag, $cart, $payment, $customer, $additionalPrice, $installments, $fingerprint = '', $deviceFingerprint = '')
432437
{
433438
$baseUrl = $this->_storeManager->getStore()->getBaseUrl();
434-
$callbackUrl = $baseUrl . 'ipag/notification/Callback';
435439

436440
$number_date = $this->getDueNumber();
437441
$expiration_date = $this->getDateDue($number_date);
438442
$orderId = $order->getIncrementId();
439443
$amount = $order->getGrandTotal() + $additionalPrice;
444+
445+
$callbackUrl = $baseUrl . 'ipag/notification/Callback';
446+
447+
$payload = json_encode(['order'=>$orderId, 'ts'=>time()]);
448+
449+
$token = base64_encode($this->encryptor->encrypt($payload));
450+
451+
$redirectUrl = $baseUrl . 'ipag/redirect/result?p=' . $token;
452+
440453
$ipagOrder = $ipag->transaction()->getOrder()
441454
->setOrderId($orderId)
442455
->setCallbackUrl($callbackUrl)
456+
->setRedirectUrl($redirectUrl)
443457
->setAmount($amount)
444458
->setInstallments($installments)
445459
->setPayment($payment)

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "ipag/payment",
33
"description": "iPag Payment Extension for Magento 2",
44
"type": "magento2-module",
5-
"version": "1.6.0",
5+
"version": "1.7.0",
66
"license": "MIT",
77
"authors": [
88
{

etc/module.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
2-
<module name="Ipag_Payment" setup_version="1.6.0">
2+
<module name="Ipag_Payment" setup_version="1.7.0">
33
<sequence>
44
<module name="Magento_Sales"/>
55
<module name="Magento_Payment"/>
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0"?>
2+
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="1column">
3+
<body>
4+
<referenceContainer name="content">
5+
<block class="Magento\Framework\View\Element\Template" name="ipag.redirect_error" template="Ipag_Payment::order/redirect/error.phtml" />
6+
</referenceContainer>
7+
</body>
8+
</page>
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0"?>
2+
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="1column">
3+
<body>
4+
<referenceContainer name="content">
5+
<block class="Magento\Framework\View\Element\Template" name="ipag.redirect_success" template="Ipag_Payment::order/redirect/success.phtml" />
6+
</referenceContainer>
7+
</body>
8+
</page>

0 commit comments

Comments
 (0)