Mundipagg_Integracao - Version 2.9.3

Version Notes

Fix in installments;
Fix in notification NotAuthorized and Capture;
Fix in recurrency fields in the new product screen;
Fix in PHP 5.4 retrocompatibility;
Fix in interests data serialization;
Fix in "boleto" underpaid/overpaid notification.

Download this release

Release Info

Developer MundiPagg
Extension Mundipagg_Integracao
Version 2.9.3
Comparing to
See all releases


Code changes from version 2.9.2 to 2.9.3

Files changed (26) hide show
  1. app/code/community/Uecommerce/Mundipagg/Helper/Data.php +10 -4
  2. app/code/community/Uecommerce/Mundipagg/Helper/Installments.php +4 -8
  3. app/code/community/Uecommerce/Mundipagg/Helper/UnserializeArray.php +23 -0
  4. app/code/community/Uecommerce/Mundipagg/Model/.DS_Store +0 -0
  5. app/code/community/Uecommerce/Mundipagg/Model/Adminvalidators/Antifraud/Minval.php +36 -36
  6. app/code/community/Uecommerce/Mundipagg/Model/Adminvalidators/Offlineretry.php +32 -32
  7. app/code/community/Uecommerce/Mundipagg/Model/Adminvalidators/Timeout.php +20 -0
  8. app/code/community/Uecommerce/Mundipagg/Model/Api.php +2422 -2207
  9. app/code/community/Uecommerce/Mundipagg/Model/Observer.php +408 -418
  10. app/code/community/Uecommerce/Mundipagg/Model/Order/Payment.php +23 -2
  11. app/code/community/Uecommerce/Mundipagg/Model/Recurrency.php +8 -2
  12. app/code/community/Uecommerce/Mundipagg/Model/Resource/Offlineretry.php +7 -7
  13. app/code/community/Uecommerce/Mundipagg/Model/Resource/Offlineretry/Collection.php +8 -8
  14. app/code/community/Uecommerce/Mundipagg/Model/Source/Frequency.php +1 -1
  15. app/code/community/Uecommerce/Mundipagg/Model/Standard.php +2126 -1984
  16. app/code/community/Uecommerce/Mundipagg/controllers/StandardController.php +7 -5
  17. app/code/community/Uecommerce/Mundipagg/data/mundipagg_setup/data-upgrade-2.9.1-2.9.2.php +10 -10
  18. app/code/community/Uecommerce/Mundipagg/etc/config.xml +350 -336
  19. app/code/community/Uecommerce/Mundipagg/etc/system.xml +1130 -1118
  20. app/design/adminhtml/default/default/layout/mundipagg.xml +33 -52
  21. app/design/adminhtml/default/default/template/mundipagg/payment/info/mundipagg.phtml +13 -1
  22. app/locale/pt_BR/Uecommerce_Mundipagg.csv +222 -217
  23. js/uecommerce/fcontrol/fingerprint-sandbox.js +0 -368
  24. js/uecommerce/fcontrol/script-fingerprint-fcontrol-prod.js +0 -367
  25. js/uecommerce/mundipagg.js +876 -876
  26. package.xml +13 -5
app/code/community/Uecommerce/Mundipagg/Helper/Data.php CHANGED
@@ -487,14 +487,13 @@ class Uecommerce_Mundipagg_Helper_Data extends Mage_Core_Helper_Abstract {
487
}
488
489
public function isAntiFraudEnabled() {
490
- $antifraud = Mage::getStoreConfig('payment/mundipagg_standard/antifraud');
491
-
492
- return boolval($antifraud);
493
}
494
495
public function priceFormatter($amountInCents) {
496
$number = round($amountInCents, 2, PHP_ROUND_HALF_DOWN);
497
$number = number_format($number, 2, ',', '');
498
return $number;
499
}
500
@@ -522,7 +521,7 @@ class Uecommerce_Mundipagg_Helper_Data extends Mage_Core_Helper_Abstract {
522
$arrVal = explode('.', $value);
523
$cents = $arrVal[1];
524
525
- if (strlen($cents) > 2 || !is_numeric($value)){
526
return false;
527
}
528
@@ -572,4 +571,11 @@ class Uecommerce_Mundipagg_Helper_Data extends Mage_Core_Helper_Abstract {
572
return $antifraudProvider;
573
}
574
575
}
487
}
488
489
public function isAntiFraudEnabled() {
490
+ return Mage::getStoreConfig('payment/mundipagg_standard/antifraud');
491
}
492
493
public function priceFormatter($amountInCents) {
494
$number = round($amountInCents, 2, PHP_ROUND_HALF_DOWN);
495
$number = number_format($number, 2, ',', '');
496
+
497
return $number;
498
}
499
521
$arrVal = explode('.', $value);
522
$cents = $arrVal[1];
523
524
+ if (strlen($cents) > 2 || !is_numeric($value)) {
525
return false;
526
}
527
571
return $antifraudProvider;
572
}
573
574
+ public function obfuscate($string) {
575
+ $qty = strlen($string);
576
+ $newString = str_repeat('*', $qty);
577
+
578
+ return $newString;
579
+ }
580
+
581
}
app/code/community/Uecommerce/Mundipagg/Helper/Installments.php CHANGED
@@ -299,24 +299,20 @@ class Uecommerce_Mundipagg_Helper_Installments extends Mage_Core_Helper_Abstract
299
300
if ($installments > 0) {
301
$ccTypeInstallments = "installments_" . $ccType;
302
- //Mage::log( 'ccTypeInstallments' );
303
- //Mage::log( print_r($ccTypeInstallments,1) );
304
$all_installments = $this->getInstallments(null, $ccTypeInstallments);
305
- //Mage::log( 'all_installments' );
306
- //Mage::log( print_r($all_installments,1) );
307
if (empty($all_installments)) {
308
$all_installments = $this->getInstallments();
309
}
310
311
- //Mage::log( 'if empty all_installments' );
312
- //Mage::log( print_r($all_installments,1) );
313
-
314
$installmentKey = $installments - 1;
315
316
if (!$installmentKey) {
317
return 0;
318
}
319
- $installment = $all_installments[$installmentKey];
320
321
if ($installment != null && is_array($installment)) {
322
// check if interest rate is filled in
299
300
if ($installments > 0) {
301
$ccTypeInstallments = "installments_" . $ccType;
302
$all_installments = $this->getInstallments(null, $ccTypeInstallments);
303
+
304
if (empty($all_installments)) {
305
$all_installments = $this->getInstallments();
306
}
307
308
$installmentKey = $installments - 1;
309
310
if (!$installmentKey) {
311
return 0;
312
}
313
+
314
+ $helper = Mage::helper('mundipagg');
315
+ $installment = $helper->issetOr($all_installments[$installmentKey]);
316
317
if ($installment != null && is_array($installment)) {
318
// check if interest rate is filled in
app/code/community/Uecommerce/Mundipagg/Helper/UnserializeArray.php ADDED
@@ -0,0 +1,23 @@
1
+ <?php
2
+
3
+ class Uecommerce_Mundipagg_Helper_UnserializeArray extends Mage_Core_Helper_UnserializeArray {
4
+
5
+ /**
6
+ * This module serialize the order interests information in an Varien_Object.
7
+ * Magento class Unserialize_Parser throws an Exception when an Varien_Object is unserialized.
8
+ * This rewrite catch this exception and get the serialized data with PHP native unserialize function
9
+ *
10
+ * @param string $str
11
+ * @return array|mixed
12
+ */
13
+ public function unserialize($str) {
14
+ try {
15
+ $result = parent::unserialize($str);
16
+ } catch (Exception $e) {
17
+ $result = unserialize($str);
18
+ }
19
+
20
+ return $result;
21
+ }
22
+
23
+ }
app/code/community/Uecommerce/Mundipagg/Model/.DS_Store DELETED
Binary file
app/code/community/Uecommerce/Mundipagg/Model/Adminvalidators/Antifraud/Minval.php CHANGED
@@ -1,37 +1,37 @@
1
- <?php
2
-
3
- class Uecommerce_Mundipagg_Model_Adminvalidators_Antifraud_Minval extends Mage_Core_Model_Config_Data {
4
-
5
- public function save() {
6
- $helper = Mage::helper('mundipagg');
7
- $value = $this->getValue();
8
-
9
- if (empty($value)) {
10
- $this->setValue('0.00');
11
-
12
- return parent::save();
13
- }
14
-
15
- $valueInCents = $helper->formatPriceToCents($value);
16
- $groups = $this->getGroups();
17
- $antifraudProvider = $helper->issetOr($groups['mundipagg_standard']['fields']['antifraud_provider']['value']);
18
- $afProviderName = $helper->getAntifraudName($antifraudProvider);
19
- $afProviderNameCaptilized = strtoupper($afProviderName);
20
-
21
- if ($helper->isValidNumber($value) === false) {
22
- $errMsg = $helper->__("Order minimum value '%s' for antifraud %s isn't in the valid format", $value, $afProviderNameCaptilized);
23
- Mage::throwException($errMsg);
24
- }
25
-
26
- if ($valueInCents < 0) {
27
- $errMsg = $helper->__("Order minimum value for antifraud %s can't be negative", $afProviderNameCaptilized);
28
- Mage::throwException($errMsg);
29
- }
30
-
31
- $floatValue = $helper->priceInCentsToFloat($valueInCents);
32
- $this->setValue($floatValue);
33
-
34
- return parent::save();
35
- }
36
-
37
}
1
+ <?php
2
+
3
+ class Uecommerce_Mundipagg_Model_Adminvalidators_Antifraud_Minval extends Mage_Core_Model_Config_Data {
4
+
5
+ public function save() {
6
+ $helper = Mage::helper('mundipagg');
7
+ $value = $this->getValue();
8
+
9
+ if (empty($value)) {
10
+ $this->setValue('0.00');
11
+
12
+ return parent::save();
13
+ }
14
+
15
+ $valueInCents = $helper->formatPriceToCents($value);
16
+ $groups = $this->getGroups();
17
+ $antifraudProvider = $helper->issetOr($groups['mundipagg_standard']['fields']['antifraud_provider']['value']);
18
+ $afProviderName = $helper->getAntifraudName($antifraudProvider);
19
+ $afProviderNameCaptilized = strtoupper($afProviderName);
20
+
21
+ if ($helper->isValidNumber($value) === false) {
22
+ $errMsg = $helper->__("Order minimum value '%s' for antifraud %s isn't in the valid format", $value, $afProviderNameCaptilized);
23
+ Mage::throwException($errMsg);
24
+ }
25
+
26
+ if ($valueInCents < 0) {
27
+ $errMsg = $helper->__("Order minimum value for antifraud %s can't be negative", $afProviderNameCaptilized);
28
+ Mage::throwException($errMsg);
29
+ }
30
+
31
+ $floatValue = $helper->priceInCentsToFloat($valueInCents);
32
+ $this->setValue($floatValue);
33
+
34
+ return parent::save();
35
+ }
36
+
37
}
app/code/community/Uecommerce/Mundipagg/Model/Adminvalidators/Offlineretry.php CHANGED
@@ -1,33 +1,33 @@
1
- <?php
2
-
3
- class Uecommerce_Mundipagg_Model_Adminvalidators_Offlineretry extends Mage_Core_Model_Config_Data {
4
-
5
- public function save() {
6
- $value = $this->getValue();
7
- $groups = $this->getGroups();
8
- $forbidPaymentMethods = array(
9
- 'mundipagg_twocreditcards',
10
- 'mundipagg_threecreditcards',
11
- 'mundipagg_fourcreditcards',
12
- 'mundipagg_fivecreditcards',
13
- );
14
-
15
- if ($value) {
16
- foreach ($forbidPaymentMethods as $i) {
17
- $isActive = $groups[$i]['fields']['active']['value'];
18
-
19
- if ($isActive) {
20
- $helper = Mage::helper('mundipagg');
21
- $errMsg = $helper->__("Offline retry can't be used with more than 1 creditcard payment method yet. This feature will be available comming soon.");
22
-
23
- Mage::throwException($errMsg);
24
- break;
25
- }
26
-
27
- }
28
- }
29
-
30
- return parent::save();
31
- }
32
-
33
}
1
+ <?php
2
+
3
+ class Uecommerce_Mundipagg_Model_Adminvalidators_Offlineretry extends Mage_Core_Model_Config_Data {
4
+
5
+ public function save() {
6
+ $value = $this->getValue();
7
+ $groups = $this->getGroups();
8
+ $forbidPaymentMethods = array(
9
+ 'mundipagg_twocreditcards',
10
+ 'mundipagg_threecreditcards',
11
+ 'mundipagg_fourcreditcards',
12
+ 'mundipagg_fivecreditcards',
13
+ );
14
+
15
+ if ($value) {
16
+ foreach ($forbidPaymentMethods as $i) {
17
+ $isActive = $groups[$i]['fields']['active']['value'];
18
+
19
+ if ($isActive) {
20
+ $helper = Mage::helper('mundipagg');
21
+ $errMsg = $helper->__("Offline retry can't be used with more than 1 creditcard payment method yet. This feature will be available comming soon.");
22
+
23
+ Mage::throwException($errMsg);
24
+ break;
25
+ }
26
+
27
+ }
28
+ }
29
+
30
+ return parent::save();
31
+ }
32
+
33
}
app/code/community/Uecommerce/Mundipagg/Model/Adminvalidators/Timeout.php ADDED
@@ -0,0 +1,20 @@
1
+ <?php
2
+
3
+ class Uecommerce_Mundipagg_Model_Adminvalidators_Timeout extends Mage_Core_Model_Config_Data {
4
+
5
+ const DISABLED = 0;
6
+ const ENABLED = 1;
7
+
8
+ public function save() {
9
+ $limit = $this->getValue();
10
+ $helper = Mage::helper('mundipagg');
11
+
12
+ if (is_numeric($limit) === false) {
13
+ $errMsg = $helper->__("Integration timeout limit must be an numeric value");
14
+ Mage::throwException($errMsg);
15
+ }
16
+
17
+ return parent::save();
18
+ }
19
+
20
+ }
app/code/community/Uecommerce/Mundipagg/Model/Api.php CHANGED
@@ -1,2207 +1,2422 @@
1
- <?php
2
- /**
3
- * Uecommerce
4
- *
5
- * NOTICE OF LICENSE
6
- *
7
- * This source file is subject to the Uecommerce EULA.
8
- * It is also available through the world-wide-web at this URL:
9
- * http://www.uecommerce.com.br/
10
- *
11
- * DISCLAIMER
12
- *
13
- * Do not edit or add to this file if you wish to upgrade the extension
14
- * to newer versions in the future. If you wish to customize the extension
15
- * for your needs please refer to http://www.uecommerce.com.br/ for more information
16
- *
17
- * @category Uecommerce
18
- * @package Uecommerce_Mundipagg
19
- * @copyright Copyright (c) 2012 Uecommerce (http://www.uecommerce.com.br/)
20
- * @license http://www.uecommerce.com.br/
21
- */
22
-
23
- /**
24
- * Mundipagg Payment module
25
- *
26
- * @category Uecommerce
27
- * @package Uecommerce_Mundipagg
28
- * @author Uecommerce Dev Team
29
- */
30
- class Uecommerce_Mundipagg_Model_Api extends Uecommerce_Mundipagg_Model_Standard {
31
-
32
- const TRANSACTION_NOT_FOUND = "Transaction not found";
33
- const TRANSACTION_ALREADY_CAPTURED = "Transaction already captured";
34
- const TRANSACTION_CAPTURED = "Transaction captured";
35
-
36
- private $helperUtil;
37
- private $modelStandard;
38
- private $debugEnabled;
39
- private $moduleVersion;
40
-
41
- public function __construct() {
42
- $this->helperUtil = new Uecommerce_Mundipagg_Helper_Util();
43
- $this->modelStandard = new Uecommerce_Mundipagg_Model_Standard();
44
- $this->moduleVersion = Mage::helper('mundipagg')->getExtensionVersion();
45
- $this->debugEnabled = $this->modelStandard->getDebug();
46
- parent::_construct();
47
- }
48
-
49
- /**
50
- * Credit Card Transaction
51
- */
52
- public function creditCardTransaction($order, $data, Uecommerce_Mundipagg_Model_Standard $standard) {
53
- $_logRequest = array();
54
-
55
- try {
56
- // Installments configuration
57
- $installment = $standard->getParcelamento();
58
- $qtdParcelasMax = $standard->getParcelamentoMax();
59
-
60
- // Get Webservice URL
61
- $url = $standard->getURL();
62
-
63
- // Set Data
64
- $_request = array();
65
- $_request["Order"] = array();
66
- $_request["Order"]["OrderReference"] = $order->getIncrementId();
67
-
68
- // if ($standard->getEnvironment() != 'production') {
69
- // $_request["Order"]["OrderReference"] = md5(date('Y-m-d H:i:s')); // Identificação do pedido na loja
70
- // }
71
-
72
- /*
73
- * Append transaction (multi credit card payments)
74
- * When one of Credit Cards has not been authorized and we try with a new one)
75
- */
76
- if ($orderReference = $order->getPayment()->getAdditionalInformation('OrderReference')) {
77
- $_request["Order"]["OrderReference"] = $orderReference;
78
- }
79
-
80
- // Collection
81
- $_request["CreditCardTransactionCollection"] = array();
82
-
83
- /* @var $recurrencyModel Uecommerce_Mundipagg_Model_Recurrency */
84
- $recurrencyModel = Mage::getModel('mundipagg/recurrency');
85
-
86
- $creditcardTransactionCollection = array();
87
-
88
- // Partial Payment (we use this reference in order to authorize the rest of the amount)
89
- if ($order->getPayment()->getAdditionalInformation('OrderReference')) {
90
- $_request["CreditCardTransactionCollection"]["OrderReference"] = $order->getPayment()->getAdditionalInformation('OrderReference');
91
- }
92
-
93
- $baseGrandTotal = str_replace(',', '.', $order->getBaseGrandTotal());
94
- $amountInCentsVar = intval(strval(($baseGrandTotal * 100)));
95
-
96
- // CreditCardOperationEnum : if more than one payment method we use AuthOnly and then capture if all are ok
97
- $helper = Mage::helper('mundipagg');
98
-
99
- $num = $helper->getCreditCardsNumber($data['payment_method']);
100
-
101
- $installmentCount = 1;
102
-
103
- if ($num > 1) {
104
- $creditCardOperationEnum = 'AuthOnly';
105
- } else {
106
- $creditCardOperationEnum = $standard->getCreditCardOperationEnum();
107
- }
108
-
109
- foreach ($data['payment'] as $i => $paymentData) {
110
- $creditcardTransactionData = new stdclass();
111
- $creditcardTransactionData->CreditCard = new stdclass();
112
- $creditcardTransactionData->Options = new stdclass();
113
-
114
- // InstantBuyKey payment
115
- if (isset($paymentData['card_on_file_id'])) {
116
- $token = Mage::getModel('mundipagg/cardonfile')->load($paymentData['card_on_file_id']);
117
-
118
- if ($token->getId() && $token->getEntityId() == $order->getCustomerId()) {
119
- $creditcardTransactionData->CreditCard->InstantBuyKey = $token->getToken();
120
- $creditcardTransactionData->CreditCard->CreditCardBrand = $token->getCcType();
121
- $creditcardTransactionData->CreditCardOperation = $creditCardOperationEnum;
122
- /** Tipo de operação: AuthOnly | AuthAndCapture | AuthAndCaptureWithDelay */
123
- $creditcardTransactionData->AmountInCents = intval(strval(($paymentData['AmountInCents']))); // Valor da transação
124
- $creditcardTransactionData->InstallmentCount = $paymentData['InstallmentCount']; // Nº de parcelas
125
- $creditcardTransactionData->Options->CurrencyIso = "BRL"; //Moeda do pedido
126
- }
127
-
128
- } else { // Credit Card
129
- $creditcardTransactionData->CreditCard->CreditCardNumber = $paymentData['CreditCardNumber']; // Número do cartão
130
- $creditcardTransactionData->CreditCard->HolderName = $paymentData['HolderName']; // Nome do cartão
131
- $creditcardTransactionData->CreditCard->SecurityCode = $paymentData['SecurityCode']; // Código de segurança
132
- $creditcardTransactionData->CreditCard->ExpMonth = $paymentData['ExpMonth']; // Mês Exp
133
- $creditcardTransactionData->CreditCard->ExpYear = $paymentData['ExpYear']; // Ano Exp
134
- $creditcardTransactionData->CreditCard->CreditCardBrand = $paymentData['CreditCardBrandEnum']; // Bandeira do cartão : Visa ,MasterCard ,Hipercard ,Amex */
135
- $creditcardTransactionData->CreditCardOperation = $creditCardOperationEnum;
136
- /** Tipo de operação: AuthOnly | AuthAndCapture | AuthAndCaptureWithDelay */
137
- $creditcardTransactionData->AmountInCents = intval(strval(($paymentData['AmountInCents']))); // Valor da transação
138
- $creditcardTransactionData->InstallmentCount = $paymentData['InstallmentCount']; // Nº de parcelas
139
- $creditcardTransactionData->Options->CurrencyIso = "BRL"; //Moeda do pedido
140
- }
141
-
142
- $installmentCount = $paymentData['InstallmentCount'];
143
-
144
- // BillingAddress
145
- if ($standard->getAntiFraud() == 1) {
146
- $addy = $this->buyerBillingData($order, $data, $_request, $standard);
147
-
148
- $creditcardTransactionData->CreditCard->BillingAddress = $addy['AddressCollection'][0];
149
- }
150
-
151
- if ($standard->getEnvironment() != 'production') {
152
- $creditcardTransactionData->Options->PaymentMethodCode = $standard->getPaymentMethodCode(); // Código do meio de pagamento
153
- }
154
-
155
- // Verificamos se tem o produto de teste da Cielo no carrinho
156
- foreach ($order->getItemsCollection() as $item) {
157
- if ($item->getSku() == $standard->getCieloSku() && $standard->getEnvironment() == 'production') {
158
- $creditcardTransactionData->Options->PaymentMethodCode = 5; // Código do meio de pagamento Cielo
159
- }
160
-
161
- // Adicionamos o produto a lógica de recorrência.
162
- $qty = $item->getQtyOrdered();
163
-
164
- for ($qt = 1; $qt <= $qty; $qt++) {
165
- $recurrencyModel->setItem($item);
166
- }
167
- }
168
-
169
- $creditcardTransactionCollection[] = $creditcardTransactionData;
170
- }
171
-
172
- $_request["CreditCardTransactionCollection"] = $this->ConvertCreditcardTransactionCollectionFromRequest($creditcardTransactionCollection, $standard);
173
-
174
- $_request = $recurrencyModel->generateRecurrences($_request, $installmentCount);
175
-
176
- // Buyer data
177
- $_request["Buyer"] = array();
178
- $_request["Buyer"] = $this->buyerBillingData($order, $data, $_request, $standard);
179
-
180
- // Cart data
181
- $_request["ShoppingCartCollection"] = array();
182
- $_request["ShoppingCartCollection"] = $this->cartData($order, $data, $_request, $standard);
183
-
184
- //verify anti-fraud config and mount the node 'RequestData'
185
- $nodeRequestData = $this->getRequestDataNode();
186
-
187
- if (is_array($nodeRequestData)) {
188
- $_request['RequestData'] = $nodeRequestData;
189
- }
190
-
191
- if ($standard->getDebug() == 1) {
192
- $_logRequest = $_request;
193
-
194
- foreach ($_request["CreditCardTransactionCollection"] as $key => $paymentData) {
195
- if (isset($_logRequest["CreditCardTransactionCollection"][$key]["CreditCard"]["CreditCardNumber"])) {
196
- $_logRequest["CreditCardTransactionCollection"][$key]["CreditCard"]["CreditCardNumber"] = 'xxxxxxxxxxxxxxxx';
197
- }
198
-
199
- if (isset($_logRequest["CreditCardTransactionCollection"][$key]["CreditCard"]["SecurityCode"])) {
200
- $_logRequest["CreditCardTransactionCollection"][$key]["CreditCard"]["SecurityCode"] = 'xxx';
201
- }
202
-
203
- if (isset($_logRequest["CreditCardTransactionCollection"][$key]["CreditCard"]["ExpMonth"])) {
204
- $_logRequest["CreditCardTransactionCollection"][$key]["CreditCard"]["ExpMonth"] = 'xx';
205
- }
206
-
207
- if (isset($_logRequest["CreditCardTransactionCollection"][$key]["CreditCard"]["ExpYear"])) {
208
- $_logRequest["CreditCardTransactionCollection"][$key]["CreditCard"]["ExpYear"] = 'xx';
209
- }
210
- }
211
- }
212
-
213
- // check anti fraud minimum value
214
- if ($helper->isAntiFraudEnabled()) {
215
- $antifraudProviderConfig = intval(Mage::getStoreConfig('payment/mundipagg_standard/antifraud_provider'));
216
- $antifraudProvider = null;
217
-
218
- switch ($antifraudProviderConfig) {
219
- case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_CLEARSALE:
220
- $antifraudProvider = 'clearsale';
221
- break;
222
-
223
- case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_FCONTROL:
224
- $antifraudProvider = 'fcontrol';
225
- break;
226
-
227
- case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_STONE:
228
- $antifraudProvider = 'stone';
229
- break;
230
- }
231
-
232
- $minValueConfig = Mage::getStoreConfig("payment/mundipagg_standard/antifraud_minimum_{$antifraudProvider}");
233
- $minValueConfig = $helper->formatPriceToCents($minValueConfig);
234
-
235
- if ($amountInCentsVar >= $minValueConfig) {
236
- $_request['Options']['IsAntiFraudEnabled'] = true;
237
- } else {
238
- $_request['Options']['IsAntiFraudEnabled'] = false;
239
- }
240
-
241
- }
242
-
243
- // Data
244
- $_response = $this->sendRequest($_request, $url, $_logRequest);
245
- $xml = $_response['xmlData'];
246
- $dataR = $_response['arrayData'];
247
-
248
- // if some error ocurred ex.: http 500 internal server error
249
- if (isset($dataR['ErrorReport']) && !empty($dataR['ErrorReport'])) {
250
- $_errorItemCollection = $dataR['ErrorReport']['ErrorItemCollection'];
251
-
252
- // Return errors
253
- return array(
254
- 'error' => 1,
255
- 'ErrorCode' => '',
256
- 'ErrorDescription' => '',
257
- 'OrderKey' => isset($dataR['OrderResult']['OrderKey']) ? $dataR['OrderResult']['OrderKey'] : null,
258
- 'OrderReference' => isset($dataR['OrderResult']['OrderReference']) ? $dataR['OrderResult']['OrderReference'] : null,
259
- 'ErrorItemCollection' => $_errorItemCollection,
260
- 'result' => $dataR,
261
- );
262
- }
263
-
264
- // Transactions colllection
265
- $creditCardTransactionResultCollection = $dataR['CreditCardTransactionResultCollection'];
266
-
267
- // Only 1 transaction
268
- if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
269
- //and transaction success is true
270
- if ((string)$creditCardTransactionResultCollection['CreditCardTransactionResult']['Success'] == 'true') {
271
- $trans = $creditCardTransactionResultCollection['CreditCardTransactionResult'];
272
-
273
- // We save Card On File
274
- if ($data['customer_id'] != 0 && isset($data['payment'][1]['token']) && $data['payment'][1]['token'] == 'new') {
275
- $cardonfile = Mage::getModel('mundipagg/cardonfile');
276
-
277
- $cardonfile->setEntityId($data['customer_id']);
278
- $cardonfile->setAddressId($data['address_id']);
279
- $cardonfile->setCcType($data['payment'][1]['CreditCardBrandEnum']);
280
- $cardonfile->setCreditCardMask($trans['CreditCard']['MaskedCreditCardNumber']);
281
- $cardonfile->setExpiresAt(date("Y-m-t", mktime(0, 0, 0, $data['payment'][1]['ExpMonth'], 1, $data['payment'][1]['ExpYear'])));
282
- $cardonfile->setToken($trans['CreditCard']['InstantBuyKey']);
283
- $cardonfile->setActive(1);
284
-
285
- $cardonfile->save();
286
- }
287
-
288
- $result = array(
289
- 'success' => true,
290
- 'message' => 1,
291
- 'returnMessage' => urldecode($creditCardTransactionResultCollection['CreditCardTransactionResult']['AcquirerMessage']),
292
- 'OrderKey' => $dataR['OrderResult']['OrderKey'],
293
- 'OrderReference' => $dataR['OrderResult']['OrderReference'],
294
- 'isRecurrency' => $recurrencyModel->recurrencyExists(),
295
- 'result' => $xml
296
- );
297
-
298
- if (isset($dataR['OrderResult']['CreateDate'])) {
299
- $result['CreateDate'] = $dataR['OrderResult']['CreateDate'];
300
- }
301
-
302
- return $result;
303
-
304
- } else {
305
- // CreditCardTransactionResult success == false, not authorized
306
- $result = array(
307
- 'error' => 1,
308
- 'ErrorCode' => $creditCardTransactionResultCollection['CreditCardTransactionResult']['AcquirerReturnCode'],
309
- 'ErrorDescription' => urldecode($creditCardTransactionResultCollection['CreditCardTransactionResult']['AcquirerMessage']),
310
- 'OrderKey' => $dataR['OrderResult']['OrderKey'],
311
- 'OrderReference' => $dataR['OrderResult']['OrderReference'],
312
- 'result' => $xml
313
- );
314
-
315
- if (isset($dataR['OrderResult']['CreateDate'])) {
316
- $result['CreateDate'] = $dataR['OrderResult']['CreateDate'];
317
- }
318
-
319
- /**
320
- * @TODO precisa refatorar isto, pois deste jeito esta gravando offlineretry pra que qualquer pedido
321
- * com mais de 1 cartao
322
- */
323
- // save offline retry statements if this feature is enabled
324
- $orderResult = $dataR['OrderResult'];
325
- $this->saveOfflineRetryStatements($orderResult['OrderReference'], new DateTime($orderResult['CreateDate']));
326
-
327
- return $result;
328
- }
329
- } else { // More than 1 transaction
330
- $allTransactions = $creditCardTransactionResultCollection['CreditCardTransactionResult'];
331
-
332
- // We remove other transactions made before
333
- $actualTransactions = count($data['payment']);
334
- $totalTransactions = count($creditCardTransactionResultCollection['CreditCardTransactionResult']);
335
- $transactionsToDelete = $totalTransactions - $actualTransactions;
336
-
337
- if ($totalTransactions > $actualTransactions) {
338
- for ($i = 0; $i <= ($transactionsToDelete - 1); $i++) {
339
- unset($allTransactions[$i]);
340
- }
341
-
342
- // Reorganize array indexes from 0
343
- $allTransactions = array_values($allTransactions);
344
- }
345
-
346
- $needSaveOfflineRetry = true;
347
-
348
- foreach ($allTransactions as $key => $trans) {
349
-
350
- // We save Cards On File for current transaction(s)
351
- if ($data['customer_id'] != 0 && isset($data['payment'][$key + 1]['token']) && $data['payment'][$key + 1]['token'] == 'new') {
352
- $cardonfile = Mage::getModel('mundipagg/cardonfile');
353
-
354
- $cardonfile->setEntityId($data['customer_id']);
355
- $cardonfile->setAddressId($data['address_id']);
356
- $cardonfile->setCcType($data['payment'][$key + 1]['CreditCardBrandEnum']);
357
- $cardonfile->setCreditCardMask($trans['CreditCard']['MaskedCreditCardNumber']);
358
- $cardonfile->setExpiresAt(date("Y-m-t", mktime(0, 0, 0, $data['payment'][$key + 1]['ExpMonth'], 1, $data['payment'][$key + 1]['ExpYear'])));
359
- $cardonfile->setToken($trans['CreditCard']['InstantBuyKey']);
360
- $cardonfile->setActive(1);
361
-
362
- $cardonfile->save();
363
- }
364
-
365
- // //some transaction not authorized, save offline retry if necessary
366
- // if (isset($trans['Success']) && $trans['Success'] == 'false' && $needSaveOfflineRetry) {
367
- // $needSaveOfflineRetry = false;
368
- // $orderResult = $dataR['OrderResult'];
369
- //
370
- // $this->saveOfflineRetryStatements($orderResult['OrderReference'], new DateTime($orderResult['CreateDate']));
371
- // }
372
-
373
- }
374
-
375
- // Result
376
- $result = array(
377
- 'success' => true,
378
- 'message' => 1,
379
- 'OrderKey' => $dataR['OrderResult']['OrderKey'],
380
- 'OrderReference' => $dataR['OrderResult']['OrderReference'],
381
- 'isRecurrency' => $recurrencyModel->recurrencyExists(),
382
- 'result' => $xml,
383
- );
384
-
385
- if (isset($dataR['OrderResult']['CreateDate'])) {
386
- $result['CreateDate'] = $dataR['OrderResult']['CreateDate'];
387
- }
388
-
389
- return $result;
390
- }
391
- } catch (Exception $e) {
392
- //Redirect to Cancel page
393
-
394
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
395
-
396
- //Log error
397
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
398
- $helperLog->error($e, true);
399
-
400
- //Mail error
401
- $this->mailError(print_r($e->getMessage(), 1));
402
-
403
- // Return error
404
- $approvalRequest['error'] = 'Error WS';
405
- $approvalRequest['ErrorCode'] = 'ErrorCode WS';
406
- $approvalRequest['ErrorDescription'] = 'ErrorDescription WS';
407
- $approvalRequest['OrderKey'] = '';
408
- $approvalRequest['OrderReference'] = '';
409
-
410
- return $approvalRequest;
411
- }
412
- }
413
-
414
- /**
415
- * Convert CreditcardTransaction Collection From Request
416
- */
417
- public function ConvertCreditcardTransactionCollectionFromRequest($creditcardTransactionCollectionRequest, $standard) {
418
- $newCreditcardTransCollection = array();
419
- $counter = 0;
420
-
421
- foreach ($creditcardTransactionCollectionRequest as $creditcardTransItem) {
422
- $creditcardTrans = array();
423
- $creditcardTrans["AmountInCents"] = $creditcardTransItem->AmountInCents;
424
-
425
- if (isset($creditcardTransItem->CreditCard->CreditCardNumber)) {
426
- $creditcardTrans['CreditCard']["CreditCardNumber"] = $creditcardTransItem->CreditCard->CreditCardNumber;
427
- }
428
-
429
- if (isset($creditcardTransItem->CreditCard->HolderName)) {
430
- $creditcardTrans['CreditCard']["HolderName"] = $creditcardTransItem->CreditCard->HolderName;
431
- }
432
-
433
- if (isset($creditcardTransItem->CreditCard->SecurityCode)) {
434
- $creditcardTrans['CreditCard']["SecurityCode"] = $creditcardTransItem->CreditCard->SecurityCode;
435
- }
436
-
437
- if (isset($creditcardTransItem->CreditCard->ExpMonth)) {
438
- $creditcardTrans['CreditCard']["ExpMonth"] = $creditcardTransItem->CreditCard->ExpMonth;
439
- }
440
-
441
- if (isset($creditcardTransItem->CreditCard->ExpYear)) {
442
- $creditcardTrans['CreditCard']["ExpYear"] = $creditcardTransItem->CreditCard->ExpYear;
443
- }
444
-
445
- if (isset($creditcardTransItem->CreditCard->InstantBuyKey)) {
446
- $creditcardTrans['CreditCard']["InstantBuyKey"] = $creditcardTransItem->CreditCard->InstantBuyKey;
447
- }
448
-
449
- $creditcardTrans['CreditCard']["CreditCardBrand"] = $creditcardTransItem->CreditCard->CreditCardBrand;
450
- $creditcardTrans["CreditCardOperation"] = $creditcardTransItem->CreditCardOperation;
451
- $creditcardTrans["InstallmentCount"] = $creditcardTransItem->InstallmentCount;
452
- $creditcardTrans['Options']["CurrencyIso"] = $creditcardTransItem->Options->CurrencyIso;
453
-
454
- if ($standard->getEnvironment() != 'production') {
455
- $creditcardTrans['Options']["PaymentMethodCode"] = $creditcardTransItem->Options->PaymentMethodCode;
456
- }
457
-
458
- if ($standard->getAntiFraud() == 1) {
459
- $creditcardTrans['CreditCard']['BillingAddress'] = $creditcardTransItem->CreditCard->BillingAddress;
460
-
461
- unset($creditcardTrans['CreditCard']['BillingAddress']['AddressType']);
462
- }
463
-
464
- $newCreditcardTransCollection[$counter] = $creditcardTrans;
465
- $counter += 1;
466
- }
467
-
468
- return $newCreditcardTransCollection;
469
- }
470
-
471
- /**
472
- * Boleto transaction
473
- **/
474
- public function boletoTransaction($order, $data, Uecommerce_Mundipagg_Model_Standard $standard) {
475
- try {
476
- // Get Webservice URL
477
- $url = $standard->getURL();
478
-
479
- // Set Data
480
- $_request = array();
481
- $_request["Order"] = array();
482
- $_request["Order"]["OrderReference"] = $order->getIncrementId();
483
-
484
- // if ($standard->getEnvironment() != 'production') {
485
- // $_request["Order"]["OrderReference"] = md5(date('Y-m-d H:i:s')); // Identificação do pedido na loja
486
- // }
487
-
488
- $_request["BoletoTransactionCollection"] = array();
489
-
490
- $boletoTransactionCollection = new stdclass();
491
-
492
- for ($i = 1; $i <= $data['boleto_parcelamento']; $i++) {
493
- $boletoTransactionData = new stdclass();
494
-
495
- if (!empty($data['boleto_dates'])) {
496
- $datePagamentoBoleto = $data['boleto_dates'][$i - 1];
497
- $now = strtotime(date('Y-m-d'));
498
- $yourDate = strtotime($datePagamentoBoleto);
499
- $datediff = $yourDate - $now;
500
- $daysToAddInBoletoExpirationDate = floor($datediff / (60 * 60 * 24));
501
- } else {
502
- $daysToAddInBoletoExpirationDate = $standard->getDiasValidadeBoleto();
503
- }
504
-
505
- $baseGrandTotal = str_replace(',', '.', $order->getBaseGrandTotal());
506
- $amountInCentsVar = intval(strval((($baseGrandTotal / $data['boleto_parcelamento']) * 100)));
507
-
508
- $boletoTransactionData->AmountInCents = $amountInCentsVar;
509
- $boletoTransactionData->Instructions = $standard->getInstrucoesCaixa();
510
-
511
- if ($standard->getEnvironment() != 'production') {
512
- $boletoTransactionData->BankNumber = $standard->getBankNumber();
513
- }
514
-
515
- $boletoTransactionData->DocumentNumber = '';
516
-
517
- $boletoTransactionData->Options = new stdclass();
518
- $boletoTransactionData->Options->CurrencyIso = 'BRL';
519
- $boletoTransactionData->Options->DaysToAddInBoletoExpirationDate = $daysToAddInBoletoExpirationDate;
520
-
521
- $addy = $this->buyerBillingData($order, $data, $_request, $standard);
522
-
523
- $boletoTransactionData->BillingAddress = $addy['AddressCollection'][0];
524
-
525
- $boletoTransactionCollection = array($boletoTransactionData);
526
- }
527
-
528
- $_request["BoletoTransactionCollection"] = $this->ConvertBoletoTransactionCollectionFromRequest($boletoTransactionCollection);
529
-
530
- // Buyer data
531
- $_request["Buyer"] = array();
532
- $_request["Buyer"] = $this->buyerBillingData($order, $data, $_request, $standard);
533
-
534
- // Cart data
535
- $_request["ShoppingCartCollection"] = array();
536
- $_request["ShoppingCartCollection"] = $this->cartData($order, $data, $_request, $standard);
537
-
538
- //verify anti-fraud config and mount the node 'RequestData'
539
- $nodeRequestData = $this->getRequestDataNode();
540
-
541
- if (is_array($nodeRequestData)) {
542
- $_request['RequestData'] = $nodeRequestData;
543
- }
544
-
545
- // Data
546
- $_response = $this->sendRequest($_request, $url);
547
-
548
- $xml = $_response['xmlData'];
549
- $data = $_response['arrayData'];
550
-
551
- // Error
552
- if (isset($data['ErrorReport']) && !empty($data['ErrorReport'])) {
553
- $_errorItemCollection = $data['ErrorReport']['ErrorItemCollection'];
554
-
555
- foreach ($_errorItemCollection as $errorItem) {
556
- $errorCode = $errorItem['ErrorCode'];
557
- $ErrorDescription = $errorItem['Description'];
558
- }
559
-
560
- return array(
561
- 'error' => 1,
562
- 'ErrorCode' => $errorCode,
563
- 'ErrorDescription' => Mage::helper('mundipagg')->__($ErrorDescription),
564
- 'result' => $data
565
- );
566
- }
567
-
568
- // False
569
- if (isset($data['Success']) && (string)$data['Success'] == 'false') {
570
- return array(
571
- 'error' => 1,
572
- 'ErrorCode' => 'WithError',
573
- 'ErrorDescription' => 'WithError',
574
- 'result' => $data
575
- );
576
- } else {
577
- // Success
578
- $result = array(
579
- 'success' => true,
580
- 'message' => 0,
581
- 'OrderKey' => $data['OrderResult']['OrderKey'],
582
- 'OrderReference' => $data['OrderResult']['OrderReference'],
583
- 'result' => $data
584
- );
585
-
586
- if (isset($data['OrderResult']['CreateDate'])) {
587
- $result['CreateDate'] = $data['OrderResult']['CreateDate'];
588
- }
589
-
590
- return $result;
591
- }
592
- } catch (Exception $e) {
593
- //Redirect to Cancel page
594
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
595
-
596
- //Log error
597
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
598
- $helperLog->error($e, true);
599
-
600
- //Mail error
601
- $this->mailError(print_r($e->getMessage(), 1));
602
-
603
- // Return error
604
- $approvalRequest['error'] = 'Error WS';
605
- $approvalRequest['ErrorCode'] = 'ErrorCode WS';
606
- $approvalRequest['ErrorDescription'] = 'ErrorDescription WS';
607
- $approvalRequest['OrderKey'] = '';
608
- $approvalRequest['OrderReference'] = '';
609
-
610
- return $approvalRequest;
611
- }
612
- }
613
-
614
- /**
615
- * Convert BoletoTransaction Collection From Request
616
- */
617
- public function ConvertBoletoTransactionCollectionFromRequest($boletoTransactionCollectionRequest) {
618
- $newBoletoTransCollection = array();
619
- $counter = 0;
620
-
621
- foreach ($boletoTransactionCollectionRequest as $boletoTransItem) {
622
- $boletoTrans = array();
623
-
624
- $boletoTrans["AmountInCents"] = $boletoTransItem->AmountInCents;
625
- $boletoTrans["BankNumber"] = isset($boletoTransItem->BankNumber) ? $boletoTransItem->BankNumber : '';
626
- $boletoTrans["Instructions"] = $boletoTransItem->Instructions;
627
- $boletoTrans["DocumentNumber"] = $boletoTransItem->DocumentNumber;
628
- $boletoTrans["Options"]["CurrencyIso"] = $boletoTransItem->Options->CurrencyIso;
629
- $boletoTrans["Options"]["DaysToAddInBoletoExpirationDate"] = $boletoTransItem->Options->DaysToAddInBoletoExpirationDate;
630
- $boletoTrans['BillingAddress'] = $boletoTransItem->BillingAddress;
631
-
632
- $newBoletoTransCollection[$counter] = $boletoTrans;
633
- $counter += 1;
634
- }
635
-
636
- return $newBoletoTransCollection;
637
- }
638
-
639
- /**
640
- * Debit transaction
641
- **/
642
- public function debitTransaction($order, $data, Uecommerce_Mundipagg_Model_Standard $standard) {
643
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
644
-
645
- try {
646
- // Get Webservice URL
647
- $url = $standard->getURL();
648
-
649
- $baseGrandTotal = str_replace(',', '.', $order->getBaseGrandTotal());
650
- $amountInCentsVar = intval(strval(($baseGrandTotal * 100)));
651
-
652
- // Set Data
653
- $_request = array();
654
-
655
- $_request["RequestKey"] = '00000000-0000-0000-0000-000000000000';
656
- $_request["AmountInCents"] = $amountInCentsVar;
657
- $_request['Bank'] = $data['Bank'];
658
- $_request['MerchantKey'] = $standard->getMerchantKey();
659
-
660
- // Buyer data
661
- $_request["Buyer"] = array();
662
- $_request["Buyer"] = $this->buyerDebitBillingData($order, $data, $_request, $standard);
663
-
664
- // Order data
665
- $_request['InstallmentCount'] = '0';
666
- $_request["OrderKey"] = '00000000-0000-0000-0000-000000000000';
667
- $_request["OrderRequest"]['AmountInCents'] = $amountInCentsVar;
668
- $_request["OrderRequest"]['OrderReference'] = $order->getIncrementId();
669
-
670
- if ($standard->getEnvironment() != 'production') {
671
- $_request["OrderRequest"]["OrderReference"] = md5(date('Y-m-d H:i:s')); // Identificação do pedido na loja
672
- }
673
-
674
- if ($standard->getEnvironment() != 'production') {
675
- $_request['PaymentMethod'] = 'CieloSimulator';
676
- }
677
-
678
- $_request['PaymentType'] = null;
679
-
680
- // Cart data
681
- $shoppingCart = $this->cartData($order, $data, $_request, $standard);
682
- if (!is_array($shoppingCart)) {
683
- $shoppingCart = array();
684
- }
685
- $_request["ShoppingCart"] = $shoppingCart[0];
686
- $deliveryAddress = $_request['ShoppingCart']['DeliveryAddress'];
687
- unset($_request['ShoppingCart']['DeliveryAddress']);
688
- $_request['DeliveryAddress'] = $deliveryAddress;
689
- $_request['ShoppingCart']['ShoppingCartItemCollection'][0]['DiscountAmountInCents'] = 0;
690
-
691
- // Data
692
- $dataToPost = json_encode($_request);
693
-
694
- $helperLog->debug(print_r($_request, true));
695
-
696
- // Send payment data to MundiPagg
697
- $ch = curl_init();
698
-
699
- if (Mage::getStoreConfig('mundipagg_tests_cpf_cnpj') != '') {
700
- // If tests runinig
701
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
702
- }
703
-
704
- // Header
705
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'MerchantKey: ' . $standard->getMerchantKey() . ''));
706
-
707
- // Set the url, number of POST vars, POST data
708
- curl_setopt($ch, CURLOPT_URL, $url);
709
-
710
- curl_setopt($ch, CURLOPT_POSTFIELDS, $dataToPost);
711
-
712
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
713
-
714
- // Execute post
715
- $_response = curl_exec($ch);
716
-
717
- if (curl_errno($ch)) {
718
- $helperLog->info(curl_error($ch));
719
- // Mage::log(curl_error($ch), null, 'Uecommerce_Mundipagg.log');
720
- }
721
-
722
- // Close connection
723
- curl_close($ch);
724
-
725
- $helperLog->debug(print_r($_response, true));
726
-
727
- // Is there an error?
728
- $xml = simplexml_load_string($_response);
729
- $json = json_encode($xml);
730
- $data = array();
731
- $data = json_decode($json, true);
732
-
733
- $helperLog->debug(print_r($data, true));
734
-
735
- // Error
736
- if (isset($data['ErrorReport']) && !empty($data['ErrorReport'])) {
737
- $_errorItemCollection = $data['ErrorReport']['ErrorItemCollection'];
738
-
739
- foreach ($_errorItemCollection as $errorItem) {
740
- $errorCode = $errorItem['ErrorCode'];
741
- $ErrorDescription = $errorItem['Description'];
742
- }
743
-
744
- return array(
745
- 'error' => 1,
746
- 'ErrorCode' => $errorCode,
747
- 'ErrorDescription' => Mage::helper('mundipagg')->__($ErrorDescription),
748
- 'result' => $data
749
- );
750
- }
751
-
752
- // False
753
- if (isset($data['Success']) && (string)$data['Success'] == 'false') {
754
- return array(
755
- 'error' => 1,
756
- 'ErrorCode' => 'WithError',
757
- 'ErrorDescription' => 'WithError',
758
- 'result' => $data
759
- );
760
- } else {
761
- // Success
762
- $result = array(
763
- 'success' => true,
764
- 'message' => 4,
765
- 'OrderKey' => $data['OrderKey'],
766
- 'TransactionKey' => $data['TransactionKey'],
767
- 'TransactionKeyToBank' => $data['TransactionKeyToBank'],
768
- 'TransactionReference' => $data['TransactionReference'],
769
- 'result' => $data
770
- );
771
-
772
- if (isset($data['CreateDate'])) {
773
- $result['CreateDate'] = $data['CreateDate'];
774
- }
775
-
776
- return $result;
777
- }
778
- } catch (Exception $e) {
779
- //Redirect to Cancel page
780
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
781
-
782
- //Log error
783
- $helperLog->error($e, true);
784
-
785
- //Mail error
786
- $this->mailError(print_r($e->getMessage(), 1));
787
-
788
- // Return error
789
- $approvalRequest['error'] = 'Error WS';
790
- $approvalRequest['ErrorCode'] = 'ErrorCode WS';
791
- $approvalRequest['ErrorDescription'] = 'ErrorDescription WS';
792
- $approvalRequest['OrderKey'] = '';
793
- $approvalRequest['OrderReference'] = '';
794
-
795
- return $approvalRequest;
796
- }
797
- }
798
-
799
- /**
800
- * Set buyer data
801
- */
802
- public function buyerBillingData($order, $data, $_request, $standard) {
803
- if ($order->getData()) {
804
- $gender = null;
805
-
806
- if ($order->getCustomerGender()) {
807
- $gender = $order->getCustomerGender();
808
- }
809
-
810
- if ($order->getCustomerIsGuest() == 0) {
811
- $customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
812
-
813
- $gender = $customer->getGender();
814
-
815
- $createdAt = explode(' ', $customer->getCreatedAt());
816
- $updatedAt = explode(' ', $customer->getUpdatedAt());
817
- $currentDateTime = Mage::getModel('core/date')->date('Y-m-d H:i:s');
818
- if (!array_key_exists(1, $createdAt)) {
819
- $createdAt = explode(' ', $currentDateTime);
820
- }
821
-
822
- if (!array_key_exists(1, $updatedAt)) {
823
- $updatedAt = explode(' ', $currentDateTime);
824
- }
825
-
826
- $createDateInMerchant = substr($createdAt[0] . 'T' . $createdAt[1], 0, 19);
827
- $lastBuyerUpdateInMerchant = substr($updatedAt[0] . 'T' . $updatedAt[1], 0, 19);
828
- } else {
829
- $createDateInMerchant = $lastBuyerUpdateInMerchant = date('Y-m-d') . 'T' . date('H:i:s');
830
- }
831
-
832
- switch ($gender) {
833
- case '1':
834
- $gender = 'M';
835
- break;
836
-
837
- case '2':
838
- $gender = 'F';
839
- break;
840
- }
841
- }
842
-
843
- $billingAddress = $order->getBillingAddress();
844
- $street = $billingAddress->getStreet();
845
- $regionCode = $billingAddress->getRegionCode();
846
-
847
- if ($billingAddress->getRegionCode() == '') {
848
- $regionCode = 'RJ';
849
- }
850
-
851
- $telephone = Mage::helper('mundipagg')->applyTelephoneMask($billingAddress->getTelephone());
852
-
853
- if ($billingAddress->getTelephone() == '') {
854
- $telephone = '55(21)88888888';
855
- }
856
-
857
- // In case we doesn't have CPF or CNPJ informed we set default value for MundiPagg (required field)
858
- $data['DocumentNumber'] = isset($data['TaxDocumentNumber']) ? $data['TaxDocumentNumber'] : $order->getCustomerTaxvat();
859
-
860
- $invalid = 0;
861
-
862
- if (Mage::helper('mundipagg')->validateCPF($data['DocumentNumber'])) {
863
- $data['PersonType'] = 'Person';
864
- $data['DocumentType'] = 'CPF';
865
- $data['DocumentNumber'] = $data['DocumentNumber'];
866
- } else {
867
- $invalid++;
868
- }
869
-
870
- // We verify if a CNPJ is informed
871
- if (Mage::helper('mundipagg')->validateCNPJ($data['DocumentNumber'])) {
872
- $data['PersonType'] = 'Company';
873
- $data['DocumentType'] = 'CNPJ';
874
- $data['DocumentNumber'] = $data['DocumentNumber'];
875
- } else {
876
- $invalid++;
877
- }
878
-
879
- if ($invalid == 2) {
880
- $data['DocumentNumber'] = '00000000000';
881
- $data['DocumentType'] = 'CPF';
882
- $data['PersonType'] = 'Person';
883
- }
884
-
885
- // Request
886
- if ($gender == 'M' || $gender == 'F') {
887
- $_request["Buyer"]["Gender"] = $gender;
888
- }
889
-
890
- $_request["Buyer"]["DocumentNumber"] = preg_replace('[\D]', '', $data['DocumentNumber']);
891
- $_request["Buyer"]["DocumentType"] = $data['DocumentType'];
892
- $_request["Buyer"]["Email"] = $order->getCustomerEmail();
893
- $_request["Buyer"]["EmailType"] = 'Personal';
894
- $_request["Buyer"]["Name"] = $order->getCustomerName();
895
- $_request["Buyer"]["PersonType"] = $data['PersonType'];
896
- $_request["Buyer"]["MobilePhone"] = $telephone;
897
- $_request["Buyer"]['BuyerCategory'] = 'Normal';
898
- $_request["Buyer"]['FacebookId'] = '';
899
- $_request["Buyer"]['TwitterId'] = '';
900
- $_request["Buyer"]['BuyerReference'] = '';
901
- $_request["Buyer"]['CreateDateInMerchant'] = $createDateInMerchant;
902
- $_request["Buyer"]['LastBuyerUpdateInMerchant'] = $lastBuyerUpdateInMerchant;
903
-
904
- // Address
905
- $address = array();
906
- $address['AddressType'] = 'Residential';
907
- $address['City'] = $billingAddress->getCity();
908
- $address['District'] = isset($street[3]) ? $street[3] : 'xxx';
909
- $address['Complement'] = isset($street[2]) ? $street[2] : '';
910
- $address['Number'] = isset($street[1]) ? $street[1] : '0';
911
- $address['State'] = $regionCode;
912
- $address['Street'] = isset($street[0]) ? $street[0] : 'xxx';
913
- $address['ZipCode'] = preg_replace('[\D]', '', $billingAddress->getPostcode());
914
- $address['Country'] = 'Brazil';
915
-
916
- $_request["Buyer"]["AddressCollection"] = array();
917
- $_request["Buyer"]["AddressCollection"] = array($address);
918
-
919
- return $_request["Buyer"];
920
- }
921
-
922
- /**
923
- * Set buyer data
924
- */
925
- public function buyerDebitBillingData($order, $data, $_request, $standard) {
926
- if ($order->getData()) {
927
- if ($order->getCustomerGender()) {
928
- $gender = $order->getCustomerGender();
929
- } else {
930
- $customerId = $order->getCustomerId();
931
-
932
- $customer = Mage::getModel('customer/customer')->load($customerId);
933
-
934
- $gender = $customer->getGender();
935
- }
936
-
937
- switch ($gender) {
938
- case '1':
939
- $gender = 'M';
940
- break;
941
-
942
- case '2':
943
- $gender = 'F';
944
- break;
945
- }
946
- }
947
-
948
- $billingAddress = $order->getBillingAddress();
949
- $street = $billingAddress->getStreet();
950
- $regionCode = $billingAddress->getRegionCode();
951
-
952
- if ($billingAddress->getRegionCode() == '') {
953
- $regionCode = 'RJ';
954
- }
955
-
956
- $telephone = Mage::helper('mundipagg')->applyTelephoneMask($billingAddress->getTelephone());
957
-
958
- if ($billingAddress->getTelephone() == '') {
959
- $telephone = '55(21)88888888';
960
- }
961
-
962
- $testCpfCnpj = Mage::getStoreConfig('mundipagg_tests_cpf_cnpj');
963
- if ($testCpfCnpj != '') {
964
- $data['TaxDocumentNumber'] = $testCpfCnpj;
965
- }
966
-
967
- // In case we doesn't have CPF or CNPJ informed we set default value for MundiPagg (required field)
968
- $data['DocumentNumber'] = isset($data['TaxDocumentNumber']) ? $data['TaxDocumentNumber'] : $order->getCustomerTaxvat();
969
-
970
- $invalid = 0;
971
-
972
- if (Mage::helper('mundipagg')->validateCPF($data['DocumentNumber'])) {
973
- $data['PersonType'] = 'Person';
974
- $data['DocumentType'] = 'CPF';
975
- $data['DocumentNumber'] = $data['DocumentNumber'];
976
- } else {
977
- $invalid++;
978
- }
979
-
980
- // We verify if a CNPJ is informed
981
- if (Mage::helper('mundipagg')->validateCNPJ($data['DocumentNumber'])) {
982
- $data['PersonType'] = 'Company';
983
- $data['DocumentType'] = 'CNPJ';
984
- $data['DocumentNumber'] = $data['DocumentNumber'];
985
- } else {
986
- $invalid++;
987
- }
988
-
989
- if ($invalid == 2) {
990
- $data['DocumentNumber'] = '00000000000';
991
- $data['DocumentType'] = 'CPF';
992
- $data['PersonType'] = 'Person';
993
- }
994
-
995
- // Request
996
- if ($gender == 'M' || $gender == 'F') {
997
- $_request["Buyer"]["Gender"] = $gender;
998
- $_request["Buyer"]["GenderEnum"] = $gender;
999
- }
1000
-
1001
- $_request["Buyer"]["TaxDocumentNumber"] = preg_replace('[\D]', '', $data['DocumentNumber']);
1002
- $_request["Buyer"]["TaxDocumentTypeEnum"] = $data['DocumentType'];
1003
- $_request["Buyer"]["Email"] = $order->getCustomerEmail();
1004
- $_request["Buyer"]["EmailType"] = 'Personal';
1005
- $_request["Buyer"]["Name"] = $order->getCustomerName();
1006
- $_request["Buyer"]["PersonType"] = $data['PersonType'];
1007
- $_request['Buyer']['PhoneRequestCollection'] = Mage::helper('mundipagg')->getPhoneRequestCollection($order);
1008
- //$_request["Buyer"]["MobilePhone"] = $telephone;
1009
- $_request["Buyer"]['BuyerCategory'] = 'Normal';
1010
- $_request["Buyer"]['FacebookId'] = '';
1011
- $_request["Buyer"]['TwitterId'] = '';
1012
- $_request["Buyer"]['BuyerReference'] = '';
1013
-
1014
- // Address
1015
- $address = array();
1016
- $address['AddressTypeEnum'] = 'Residential';
1017
- $address['City'] = $billingAddress->getCity();
1018
- $address['District'] = isset($street[3]) ? $street[3] : 'xxx';
1019
- $address['Complement'] = isset($street[2]) ? $street[2] : '';
1020
- $address['Number'] = isset($street[1]) ? $street[1] : '0';
1021
- $address['State'] = $regionCode;
1022
- $address['Street'] = isset($street[0]) ? $street[0] : 'xxx';
1023
- $address['ZipCode'] = preg_replace('[\D]', '', $billingAddress->getPostcode());
1024
-
1025
- $_request["Buyer"]["BuyerAddressCollection"] = array();
1026
- $_request["Buyer"]["BuyerAddressCollection"] = array($address);
1027
-
1028
- return $_request["Buyer"];
1029
- }
1030
-
1031
- /**
1032
- * Set cart data
1033
- */
1034
- public function cartData($order, $data, $_request, $standard) {
1035
- $baseGrandTotal = round($order->getBaseGrandTotal(), 2);
1036
- $baseDiscountAmount = round($order->getBaseDiscountAmount(), 2);
1037
-
1038
- if (abs($order->getBaseDiscountAmount()) > 0) {
1039
- $totalWithoutDiscount = $baseGrandTotal + abs($baseDiscountAmount);
1040
-
1041
- $discount = round(($baseGrandTotal / $totalWithoutDiscount), 4);
1042
- } else {
1043
- $discount = 1;
1044
- }
1045
-
1046
- $shippingDiscountAmount = round($order->getShippingDiscountAmount(), 2);
1047
-
1048
- if (abs($shippingDiscountAmount) > 0) {
1049
- $totalShippingWithoutDiscount = round($order->getBaseShippingInclTax(), 2);
1050
- $totalShippingWithDiscount = $totalShippingWithoutDiscount - abs($shippingDiscountAmount);
1051
-
1052
- $shippingDiscount = round(($totalShippingWithDiscount / $totalShippingWithoutDiscount), 4);
1053
- } else {
1054
- $shippingDiscount = 1;
1055
- }
1056
-
1057
- $items = array();
1058
-
1059
- foreach ($order->getItemsCollection() as $item) {
1060
- if ($item->getParentItemId() == '') {
1061
- $items[$item->getItemId()]['sku'] = $item->getProductId();
1062
- $items[$item->getItemId()]['name'] = $item->getName();
1063
-
1064
- $items[$item->getItemId()]['description'] = Mage::getModel('catalog/product')->load($item->getProductId())->getShortDescription();
1065
-
1066
- $items[$item->getItemId()]['qty'] = round($item->getQtyOrdered(), 0);
1067
- $items[$item->getItemId()]['price'] = $item->getBasePrice();
1068
- }
1069
- }
1070
-
1071
- $i = 0;
1072
-
1073
- $shipping = intval(strval(($order->getBaseShippingInclTax() * $shippingDiscount * 100)));
1074
-
1075
- $deadlineConfig = Mage::getStoreConfig('payment/mundipagg_standard/delivery_deadline');
1076
- if ($deadlineConfig != '') {
1077
- $date = new Zend_Date($order->getCreatedAtStoreDate()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT), Zend_Date::DATETIME);
1078
- $date->addDay((int)$deadlineConfig);
1079
- $deliveryDeadline = $date->toString('yyyy-MM-ddTHH:mm:ss');
1080
-
1081
- $_request["ShoppingCartCollection"]['DeliveryDeadline'] = $deliveryDeadline;
1082
- $_request["ShoppingCartCollection"]['EstimatedDeliveryDate'] = $deliveryDeadline;
1083
- }
1084
-
1085
- $_request["ShoppingCartCollection"]["FreightCostInCents"] = $shipping;
1086
-
1087
- $_request['ShoppingCartCollection']['ShippingCompany'] = Mage::getStoreConfig('payment/mundipagg_standard/shipping_company');
1088
-
1089
- foreach ($items as $itemId) {
1090
- $unitCostInCents = intval(strval(($itemId['price'] * $discount * 100)));
1091
-
1092
- $_request["ShoppingCartCollection"]["ShoppingCartItemCollection"][$i]["Description"] = empty($itemId['description']) || ($itemId['description'] == '') ? $itemId['name'] : $itemId['description'];
1093
- $_request["ShoppingCartCollection"]["ShoppingCartItemCollection"][$i]["ItemReference"] = $itemId['sku'];
1094
- $_request["ShoppingCartCollection"]["ShoppingCartItemCollection"][$i]["Name"] = $itemId['name'];
1095
- $_request["ShoppingCartCollection"]["ShoppingCartItemCollection"][$i]["Quantity"] = $itemId['qty'];
1096
- $_request["ShoppingCartCollection"]["ShoppingCartItemCollection"][$i]["UnitCostInCents"] = $unitCostInCents;
1097
- //}
1098
-
1099
- $totalInCents = intval(strval(($itemId['qty'] * $itemId['price'] * $discount * 100)));
1100
-
1101
- $_request["ShoppingCartCollection"]["ShoppingCartItemCollection"][$i]["TotalCostInCents"] = $totalInCents;
1102
-
1103
- $i++;
1104
- }
1105
-
1106
- // Delivery address
1107
- if ($order->getIsVirtual()) {
1108
- $addy = $order->getBillingAddress();
1109
- } else {
1110
- $addy = $order->getShippingAddress();
1111
- }
1112
-
1113
- $street = $addy->getStreet();
1114
- $regionCode = $addy->getRegionCode();
1115
-
1116
- if ($addy->getRegionCode() == '') {
1117
- $regionCode = 'RJ';
1118
- }
1119
-
1120
- $address = array();
1121
- $address['City'] = $addy->getCity();
1122
- $address['District'] = isset($street[3]) ? $street[3] : 'xxx';
1123
- $address['Complement'] = isset($street[2]) ? $street[2] : '';
1124
- $address['Number'] = isset($street[1]) ? $street[1] : '0';
1125
- $address['State'] = $regionCode;
1126
- $address['Street'] = isset($street[0]) ? $street[0] : 'xxx';
1127
- $address['ZipCode'] = preg_replace('[\D]', '', $addy->getPostcode());
1128
- $address['Country'] = 'Brazil';
1129
- $address['AddressType'] = "Shipping";
1130
-
1131
- $_request["ShoppingCartCollection"]["DeliveryAddress"] = array();
1132
-
1133
- $_request["ShoppingCartCollection"]["DeliveryAddress"] = $address;
1134
-
1135
- return array($_request["ShoppingCartCollection"]);
1136
- }
1137
-
1138
- /**
1139
- * Manage Order Request: capture / void / refund
1140
- **/
1141
- public function manageOrderRequest($data, Uecommerce_Mundipagg_Model_Standard $standard) {
1142
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1143
-
1144
- try {
1145
- // Get Webservice URL
1146
- $url = "{$standard->getURL()}{$data['ManageOrderOperationEnum']}";
1147
-
1148
- unset($data['ManageOrderOperationEnum']);
1149
-
1150
- // Get store key
1151
- $key = $standard->getMerchantKey();
1152
- $dataToPost = json_encode($data);
1153
- $helperUtil = new Uecommerce_Mundipagg_Helper_Util();
1154
-
1155
- $helperLog->debug("Url: {$url}");
1156
- $helperLog->info("Request:\n{$helperUtil->jsonEncodePretty($data)}\n");
1157
-
1158
- // Send payment data to MundiPagg
1159
- $ch = curl_init();
1160
-
1161
- // Header
1162
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'MerchantKey: ' . $key . ''));
1163
-
1164
- // Set the url, number of POST vars, POST data
1165
- curl_setopt($ch, CURLOPT_URL, $url);
1166
- curl_setopt($ch, CURLOPT_POSTFIELDS, $dataToPost);
1167
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1168
-
1169
- // Execute post
1170
- $_response = curl_exec($ch);
1171
- $xml = simplexml_load_string($_response);
1172
- $json = $helperUtil->jsonEncodePretty($xml);
1173
-
1174
- // Close connection
1175
- curl_close($ch);
1176
-
1177
- $helperLog->info("Response:\n{$json}\n");
1178
-
1179
- // Return
1180
- return array('result' => simplexml_load_string($_response));
1181
-
1182
- } catch (Exception $e) {
1183
- //Redirect to Cancel page
1184
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess(false);
1185
-
1186
- //Log error
1187
- $helperLog->error($e, true);
1188
-
1189
- //Mail error
1190
- $this->mailError(print_r($e->getMessage(), true));
1191
-
1192
- // Throw Exception
1193
- Mage::throwException(Mage::helper('mundipagg')->__('Payment Error'));
1194
- }
1195
- }
1196
-
1197
- /**
1198
- * Process order
1199
- * @param $order
1200
- * @param $data
1201
- */
1202
- public function processOrder($postData) {
1203
- $standard = Mage::getModel('mundipagg/standard');
1204
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1205
- $returnMessage = '';
1206
-
1207
- try {
1208
-
1209
- if (!isset($postData['xmlStatusNotification'])) {
1210
- $helperLog->info("Index xmlStatusNotification not found");
1211
-
1212
- return 'KO | Internal error.';
1213
- }
1214
-
1215
- $xmlStatusNotificationString = htmlspecialchars_decode($postData['xmlStatusNotification']);
1216
- $xml = simplexml_load_string($xmlStatusNotificationString);
1217
- $json = json_encode($xml);
1218
- $data = json_decode($json, true);
1219
- $orderReference = isset($xml->OrderReference) ? $xml->OrderReference : null;
1220
-
1221
- if (is_null($orderReference)) {
1222
- $logMessage = "Notification post:\n{$xmlStatusNotificationString}\n";
1223
-
1224
- } else {
1225
- $logMessage = "Notification post for order #{$orderReference}:\n{$xmlStatusNotificationString}";
1226
- }
1227
-
1228
- $helperLog->info($logMessage);
1229
-
1230
- $orderReference = $data['OrderReference'];
1231
- $order = Mage::getModel('sales/order');
1232
-
1233
- $order->loadByIncrementId($orderReference);
1234
-
1235
- if (!$order->getId()) {
1236
- $returnMessage = "OrderReference don't correspond to a store order.";
1237
-
1238
- $helperLog->info("OrderReference: {$orderReference} | {$returnMessage}");
1239
-
1240
- return "KO | {$returnMessage}";
1241
- }
1242
-
1243
- $transactionData = null;
1244
-
1245
- if (!empty($data['BoletoTransaction'])) {
1246
- $status = $data['BoletoTransaction']['BoletoTransactionStatus'];
1247
- $transactionKey = $data['BoletoTransaction']['TransactionKey'];
1248
- $capturedAmountInCents = $data['BoletoTransaction']['AmountPaidInCents'];
1249
- $transactionData = $data['BoletoTransaction'];
1250
- }
1251
-
1252
- if (!empty($data['CreditCardTransaction'])) {
1253
- $status = $data['CreditCardTransaction']['CreditCardTransactionStatus'];
1254
- $transactionKey = $data['CreditCardTransaction']['TransactionKey'];
1255
- $capturedAmountInCents = $data['CreditCardTransaction']['CapturedAmountInCents'];
1256
- $transactionData = $data['CreditCardTransaction'];
1257
- }
1258
-
1259
- if (!empty($data['OnlineDebitTransaction'])) {
1260
- $status = $data['OnlineDebitTransaction']['OnlineDebitTransactionStatus'];
1261
- $transactionKey = $data['OnlineDebitTransaction']['TransactionKey'];
1262
- $capturedAmountInCents = $data['OnlineDebitTransaction']['AmountPaidInCents'];
1263
- $transactionData = $data['OnlineDebitTransaction'];
1264
- }
1265
-
1266
- $returnMessageLabel = "Order #{$order->getIncrementId()}";
1267
-
1268
- if (isset($data['OrderStatus'])) {
1269
- $orderStatus = $data['OrderStatus'];
1270
-
1271
- //if MundiPagg order status is canceled, cancel the order on Magento
1272
- if ($orderStatus == Uecommerce_Mundipagg_Model_Enum_OrderStatusEnum::CANCELED) {
1273
-
1274
- if ($order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) {
1275
- $returnMessage = "OK | {$returnMessageLabel} | Order already canceled.";
1276
-
1277
- $helperLog->info($returnMessage);
1278
-
1279
- return $returnMessage;
1280
- }
1281
-
1282
- try {
1283
- $this->tryCancelOrder($order, "Transaction update received: {$status}");
1284
- $returnMessage = "OK | {$returnMessageLabel} | Canceled successfully";
1285
- $helperLog->info($returnMessage);
1286
-
1287
- } catch (Exception $e) {
1288
- $returnMessage = "KO | {$returnMessageLabel} | {$e->getMessage()}";
1289
- $helperLog->error($returnMessage);
1290
- }
1291
-
1292
- return $returnMessage;
1293
- }
1294
- }
1295
-
1296
- // We check if transactionKey exists in database
1297
- $t = 0;
1298
-
1299
- $transactions = Mage::getModel('sales/order_payment_transaction')
1300
- ->getCollection()
1301
- ->addAttributeToFilter('order_id', array('eq' => $order->getEntityId()));
1302
-
1303
- foreach ($transactions as $key => $transaction) {
1304
- $orderTransactionKey = $transaction->getAdditionalInformation('TransactionKey');
1305
-
1306
- // transactionKey found
1307
- if ($orderTransactionKey == $transactionKey) {
1308
- $t++;
1309
- continue;
1310
- }
1311
- }
1312
-
1313
- if ($t <= 0) {
1314
- $helperLog->info("Order #{$orderReference} | TransactionKey {$transactionKey} not found on database for this order. Adding...");
1315
-
1316
- $payment = $order->getPayment();
1317
- $transactionId = $transactionKey;
1318
- $transactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH;
1319
-
1320
- $this->_addTransaction($payment, $transactionId, $transactionType, $transactionData);
1321
- }
1322
-
1323
- $order->addStatusHistoryComment("Transaction update received: {$status}", false);
1324
- $order->save();
1325
-
1326
- // transactionKey has been found so we can proceed
1327
- /**
1328
- * @var $recurrence Uecommerce_Mundiapgg_Model_Recurrency
1329
- */
1330
- $recurrence = Mage::getModel('mundipagg/recurrency');
1331
- $recurrence->checkRecurrencesByOrder($order);
1332
-
1333
- $statusWithError = Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum::WITH_ERROR;
1334
- $statusWithError = strtolower($statusWithError);
1335
-
1336
- $lowerStatus = strtolower($status);
1337
-
1338
- switch ($lowerStatus) {
1339
- case 'captured':
1340
- $amountToCapture = $capturedAmountInCents * 0.01;
1341
-
1342
- try {
1343
- $return = $this->captureTransaction($order, $amountToCapture, $transactionKey);
1344
-
1345
- } catch (Exception $e) {
1346
- $orderPayment = new Uecommerce_Mundipagg_Model_Order_Payment();
1347
- $error = $e->getMessage();
1348
-
1349
- $helperLog->setLogLabel("#{$orderReference} | {$transactionKey}");
1350
-
1351
- switch ($error) {
1352
- case $orderPayment::ERR_CANNOT_CREATE_INVOICE:
1353
- $error = "Can't created invoice";
1354
- $helperLog->error($error);
1355
- break;
1356
-
1357
- case $orderPayment::ERR_CANNOT_CREATE_INVOICE_WITHOUT_PRODUCTS:
1358
- $error = "Can't create invoice without products";
1359
- $helperLog->error($error);
1360
- break;
1361
-
1362
- default:
1363
- $error = "Can't create invoice, unexpected error: {$error}";
1364
- $helperLog->error($error);
1365
- }
1366
-
1367
- $returnMessage = "KO | #{$orderReference} | Can't capture transaction {$transactionKey} | {$error}";
1368
-
1369
- $helperLog->setLogLabel("");
1370
- $helperLog->info($returnMessage);
1371
-
1372
- return $returnMessage;
1373
- }
1374
-
1375
- switch ($return) {
1376
- case self::TRANSACTION_ALREADY_CAPTURED:
1377
- $returnMessage = "OK | #{$orderReference} | {$transactionKey} | " . self::TRANSACTION_ALREADY_CAPTURED;
1378
- $helperLog->info($returnMessage);
1379
-
1380
- return $returnMessage;
1381
- break;
1382
-
1383
- case self::TRANSACTION_CAPTURED:
1384
- $returnMessage = "OK | #{$orderReference} | {$transactionKey} | " . self::TRANSACTION_CAPTURED;
1385
- $helperLog->info($returnMessage);
1386
-
1387
- return $returnMessage;
1388
- break;
1389
- }
1390
-
1391
- break;
1392
-
1393
- case 'paid':
1394
- case 'overpaid':
1395
- if ($order->canUnhold()) {
1396
- $order->unhold();
1397
- $helperLog->info("{$returnMessageLabel} | unholded.");
1398
- }
1399
-
1400
- if (!$order->canInvoice()) {
1401
- $returnMessage = "OK | {$returnMessageLabel} | Can't create invoice. Transaction status '{$status}' processed.";
1402
-
1403
- $helperLog->info($returnMessage);
1404
-
1405
- return $returnMessage;
1406
- }
1407
-
1408
- // Partial invoice
1409
- $epsilon = 0.00001;
1410
-
1411
- if ($order->canInvoice() && abs($order->getGrandTotal() - $capturedAmountInCents * 0.01) > $epsilon) {
1412
- $baseTotalPaid = $order->getTotalPaid();
1413
-
1414
- // If there is already a positive baseTotalPaid value it's not the first transaction
1415
- if ($baseTotalPaid > 0) {
1416
- $baseTotalPaid += $capturedAmountInCents * 0.01;
1417
-
1418
- $order->setTotalPaid(0);
1419
- } else {
1420
- $baseTotalPaid = $capturedAmountInCents * 0.01;
1421
-
1422
- $order->setTotalPaid($baseTotalPaid);
1423
- }
1424
-
1425
- // Can invoice only if total captured amount is equal to GrandTotal
1426
- if (abs($order->getGrandTotal() - $baseTotalPaid) < $epsilon) {
1427
- $result = $this->createInvoice($order, $data, $baseTotalPaid, $status);
1428
-
1429
- return $result;
1430
-
1431
- } else {
1432
- $order->save();
1433
-
1434
- $returnMessage = "OK | {$returnMessageLabel} | Captured amount isn't equal to grand total, invoice not created. Transaction status '{$status}' received.";
1435
-
1436
- return $returnMessage;
1437
- }
1438
- }
1439
-
1440
- // Create invoice
1441
- if ($order->canInvoice() && abs($capturedAmountInCents * 0.01 - $order->getGrandTotal()) < $epsilon) {
1442
- $result = $this->createInvoice($order, $data, $order->getGrandTotal(), $status);
1443
-
1444
- return $result;
1445
- }
1446
-
1447
- $returnMessage = "Order {$order->getIncrementId()} | Unable to create invoice for this order.";
1448
-
1449
- $helperLog->error($returnMessage);
1450
-
1451
- return "KO | {$returnMessage}";
1452
-
1453
- break;
1454
-
1455
- case 'underpaid':
1456
- if ($order->canUnhold()) {
1457
- $helperLog->info("{$returnMessageLabel} | unholded.");
1458
- $order->unhold();
1459
- }
1460
-
1461
- $order->addStatusHistoryComment('Captured offline amount of R#x27; . $capturedAmountInCents * 0.01, false);
1462
- $order->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, 'underpaid');
1463
- $order->setBaseTotalPaid($capturedAmountInCents * 0.01);
1464
- $order->setTotalPaid($capturedAmountInCents * 0.01);
1465
- $order->save();
1466
-
1467
- $returnMessage = "OK | {$returnMessageLabel} | Transaction status '{$status}' processed. Order status updated.";
1468
-
1469
- $helperLog->info($returnMessage);
1470
-
1471
- return $returnMessage;
1472
-
1473
- break;
1474
-
1475
- case 'notauthorized':
1476
- $orderIncrementId = $order->getIncrementId();
1477
- $offlineRetryModel = Mage::getModel('mundipagg/offlineretry');
1478
- $offlineRetry = $offlineRetryModel->loadByIncrementId($orderIncrementId);
1479
-
1480
- if (is_null($offlineRetry->getId())) {
1481
- $returnMessage = "OK | {$returnMessageLabel} | Transaction status '{$status}' received";
1482
- $helperLog->info($returnMessage);
1483
-
1484
- return $returnMessage;
1485
- }
1486
-
1487
- $helper = Mage::helper('mundipagg');
1488
- $grandTotal = $order->getGrandTotal();
1489
- $grandTotalInCents = $helper->formatPriceToCents($grandTotal);
1490
- $amountInCents = $transactionData['AmountInCents'];
1491
-
1492
- // if not authorized amount equal to order grand total, order must be canceled
1493
- if ($amountInCents != $grandTotalInCents) {
1494
- $returnMessage = "OK | {$returnMessageLabel} | Order grand_total not equal to transaction AmountInCents";
1495
- $helperLog->info($returnMessage);
1496
-
1497
- return $returnMessage;
1498
- }
1499
-
1500
- try {
1501
- $this->tryCancelOrder($order);
1502
-
1503
- } catch (Exception $e) {
1504
- $returnMessage = "OK | {$returnMessageLabel} | {$e->getMessage()}";
1505
-
1506
- $helperLog->error($e, true);
1507
- $helperLog->info($returnMessage);
1508
-
1509
- return $returnMessage;
1510
- }
1511
-
1512
- $returnMessage = "OK | {$returnMessageLabel} | Order canceled: total amount not authorized";
1513
- $helperLog->info($returnMessage);
1514
-
1515
- return $returnMessage;
1516
- break;
1517
-
1518
- case 'canceled':
1519
- case 'refunded':
1520
- case 'voided':
1521
- if ($order->canUnhold()) {
1522
- $helperLog->info("{$returnMessageLabel} unholded.");
1523
- $order->unhold();
1524
- }
1525
-
1526
- $ok = 0;
1527
- $invoices = array();
1528
- $canceledInvoices = array();
1529
-
1530
- foreach ($order->getInvoiceCollection() as $invoice) {
1531
- // We check if invoice can be refunded
1532
- if ($invoice->canRefund()) {
1533
- $invoices[] = $invoice;
1534
- }
1535
-
1536
- // We check if invoice has already been canceled
1537
- if ($invoice->isCanceled()) {
1538
- $canceledInvoices[] = $invoice;
1539
- }
1540
- }
1541
-
1542
- // Refund invoices and Credit Memo
1543
- if (!empty($invoices)) {
1544
- $service = Mage::getModel('sales/service_order', $order);
1545
-
1546
- foreach ($invoices as $invoice) {
1547
- $invoice->setState(Mage_Sales_Model_Order_Invoice::STATE_CANCELED);
1548
- $invoice->save();
1549
-
1550
- $creditmemo = $service->prepareInvoiceCreditmemo($invoice);
1551
- $creditmemo->setOfflineRequested(true);
1552
- $creditmemo->register()->save();
1553
- }
1554
-
1555
- // Close order
1556
- $order->setData('state', 'closed');
1557
- $order->setStatus('closed');
1558
- $order->save();
1559
-
1560
- // Return
1561
- $ok++;
1562
- }
1563
-
1564
- // Credit Memo
1565
- if (!empty($canceledInvoices)) {
1566
- $service = Mage::getModel('sales/service_order', $order);
1567
-
1568
- foreach ($invoices as $invoice) {
1569
- $creditmemo = $service->prepareInvoiceCreditmemo($invoice);
1570
- $creditmemo->setOfflineRequested(true);
1571
- $creditmemo->register()->save();
1572
- }
1573
-
1574
- // Close order
1575
- $order->setData('state', Mage_Sales_Model_Order::STATE_CLOSED);
1576
- $order->setStatus(Mage_Sales_Model_Order::STATE_CLOSED);
1577
- $order->save();
1578
-
1579
- // Return
1580
- $ok++;
1581
- }
1582
-
1583
- if (empty($invoices) && empty($canceledInvoices)) {
1584
- // Cancel order
1585
- $order->cancel()->save();
1586
- $helperLog->info("{$returnMessageLabel} | Order canceled.");
1587
-
1588
- // Return
1589
- $ok++;
1590
- }
1591
-
1592
- if ($ok > 0) {
1593
- $returnMessage = "{$returnMessageLabel} | Order status '{$status}' processed.";
1594
- $helperLog->info($returnMessage);
1595
-
1596
- return "OK | {$returnMessage}";
1597
-
1598
- } else {
1599
- $returnMessage = "{$returnMessageLabel} | Unable to process transaction status '{$status}'.";
1600
-
1601
- $helperLog->info($returnMessage);
1602
-
1603
- return "KO | {$returnMessage}";
1604
- }
1605
-
1606
- break;
1607
-
1608
- case 'authorizedpendingcapture':
1609
- $returnMessage = "Order #{$order->getIncrementId()} | Transaction status '{$status}' received.";
1610
-
1611
- $helperLog->info($returnMessage);
1612
-
1613
- return "OK | {$returnMessage}";
1614
- break;
1615
-
1616
- case $statusWithError:
1617
- try {
1618
- Uecommerce_Mundipagg_Model_Standard::transactionWithError($order, false);
1619
- $returnMessage = "OK | {$returnMessageLabel} | Order changed to WithError status";
1620
-
1621
- } catch (Exception $e) {
1622
- $returnMessage = "KO | {$returnMessageLabel} | {$e->getMessage()}";
1623
- }
1624
-
1625
- $helperLog->info($returnMessage);
1626
-
1627
- return $returnMessage;
1628
-
1629
- break;
1630
-
1631
- // For other status we add comment to history
1632
- default:
1633
- $returnMessage = "Order #{$order->getIncrementId()} | unexpected transaction status: {$status}";
1634
-
1635
- $helperLog->info($returnMessage);
1636
-
1637
- return "OK | {$returnMessage}";
1638
- }
1639
-
1640
-
1641
- } catch (Exception $e) {
1642
- $returnMessage = "Internal server error | {$e->getCode()} - ErrMsg: {$e->getMessage()}";
1643
-
1644
- //Log error
1645
- $helperLog->error($e, true);
1646
-
1647
- //Mail error
1648
- $this->mailError(print_r($e->getMessage(), 1));
1649
-
1650
- return "KO | {$returnMessage}";
1651
- }
1652
- }
1653
-
1654
- /**
1655
- * @param Mage_Sales_Model_Order $order
1656
- * @param string $comment
1657
- * @return bool
1658
- * @throws RuntimeException
1659
- */
1660
- public function tryCancelOrder(Mage_Sales_Model_Order $order, $comment = null) {
1661
- if ($order->canCancel()) {
1662
- try {
1663
- $order->cancel();
1664
-
1665
- if (!is_null($comment) && is_string($comment)) {
1666
- $order->addStatusHistoryComment($comment);
1667
- }
1668
-
1669
- $order->save();
1670
-
1671
- return true;
1672
-
1673
- } catch (Exception $e) {
1674
- throw new RuntimeException("Order cannot be canceled. Error reason: {$e->getMessage()}");
1675
- }
1676
-
1677
- } else {
1678
- throw new RuntimeException("Order cannot be canceled.");
1679
- }
1680
- }
1681
-
1682
- /**
1683
- * @param Mage_Sales_Model_Order $order
1684
- * @param $amountToCapture
1685
- * @param $transactionKey
1686
- * @throws RuntimeException
1687
- * @return string
1688
- */
1689
- private function captureTransaction(Mage_Sales_Model_Order $order, $amountToCapture, $transactionKey) {
1690
- $log = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1691
- $log->setLogLabel("#{$order->getIncrementId()} | {$transactionKey}");
1692
-
1693
- $totalPaid = $order->getTotalPaid();
1694
- $grandTotal = $order->getGrandTotal();
1695
- $createInvoice = false;
1696
- $transaction = null;
1697
-
1698
- if (is_null($totalPaid)) {
1699
- $totalPaid = 0;
1700
- }
1701
-
1702
- $totalPaid += $amountToCapture;
1703
-
1704
- $transactions = Mage::getModel('sales/order_payment_transaction')
1705
- ->getCollection()
1706
- ->addAttributeToFilter('order_id', array('eq' => $order->getEntityId()));
1707
-
1708
- foreach ($transactions as $i) {
1709
- $orderTransactionKey = $i->getAdditionalInformation('TransactionKey');
1710
-
1711
- // transactionKey found
1712
- if ($orderTransactionKey == $transactionKey) {
1713
- $transaction = $i;
1714
- break;
1715
- }
1716
- }
1717
-
1718
- if (is_null($transaction)) {
1719
- Mage::throwException(self::TRANSACTION_NOT_FOUND);
1720
- }
1721
-
1722
- if ($transaction->getIsClosed() == '1') {
1723
- return self::TRANSACTION_ALREADY_CAPTURED;
1724
- }
1725
-
1726
- if ($totalPaid < $grandTotal) {
1727
- $order->setStatus('underpaid');
1728
- } elseif ($totalPaid > $grandTotal) {
1729
- $order->setStatus('overpaid');
1730
- }
1731
-
1732
- if ($totalPaid == $grandTotal) {
1733
- // reset total paid, preparing to invoice
1734
- $createInvoice = true;
1735
- }
1736
-
1737
- $orderPayment = new Uecommerce_Mundipagg_Model_Order_Payment();
1738
-
1739
- try {
1740
- if ($createInvoice) {
1741
- $invoice = $orderPayment->createInvoice($order);
1742
- $log->info("Invoice {$invoice->getIncrementId()} created");
1743
- }
1744
-
1745
- $resource = Mage::getSingleton('core/resource');
1746
- $conn = $resource->getConnection('core_write');
1747
- $query = "UPDATE sales_payment_transaction SET is_closed = TRUE WHERE transaction_id={$transaction->getId()}";
1748
-
1749
- $conn->query($query);
1750
- $log->info("Magento payment transaction closed");
1751
-
1752
- $order->setTotalPaid($totalPaid);
1753
- $order->save();
1754
-
1755
- } catch (Exception $e) {
1756
- throw new RuntimeException($e->getMessage());
1757
- }
1758
-
1759
- $log->info("Captured amount: {$amountToCapture}");
1760
-
1761
- return self::TRANSACTION_CAPTURED;
1762
- }
1763
-
1764
- private function queryTransactions() {
1765
-
1766
- }
1767
-
1768
- /**
1769
- * Create invoice
1770
- * @return string OK|KO
1771
- */
1772
- private function createInvoice($order, $data, $totalPaid, $status) {
1773
- $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
1774
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1775
- $returnMessageLabel = "Order #{$order->getIncrementId()}";
1776
-
1777
- if (!$invoice->getTotalQty()) {
1778
- $returnMessage = 'Cannot create an invoice without products.';
1779
-
1780
- $order->addStatusHistoryComment($returnMessage, false);
1781
- $order->save();
1782
-
1783
- $helperLog->info("{$returnMessageLabel} | {$returnMessage}");
1784
-
1785
- return $returnMessage;
1786
- }
1787
-
1788
- $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
1789
- $invoice->register();
1790
- $invoice->getOrder()->setCustomerNoteNotify(true);
1791
- $invoice->getOrder()->setIsInProcess(true);
1792
- $invoice->setCanVoidFlag(true);
1793
-
1794
- $transactionSave = Mage::getModel('core/resource_transaction')
1795
- ->addObject($invoice)
1796
- ->addObject($invoice->getOrder());
1797
- $transactionSave->save();
1798
-
1799
- // Send invoice email if enabled
1800
- if (Mage::helper('sales')->canSendNewInvoiceEmail($order->getStoreId())) {
1801
- $invoice->sendEmail(true);
1802
- $invoice->setEmailSent(true);
1803
- }
1804
-
1805
- $order->setBaseTotalPaid($totalPaid);
1806
- $order->addStatusHistoryComment('Captured offline', false);
1807
-
1808
- $payment = $order->getPayment();
1809
-
1810
- $payment->setAdditionalInformation('OrderStatusEnum', $data['OrderStatus']);
1811
-
1812
- if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_creditcard') {
1813
- $payment->setAdditionalInformation('CreditCardTransactionStatusEnum', $data['CreditCardTransaction']['CreditCardTransactionStatus']);
1814
- }
1815
-
1816
- if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_boleto') {
1817
- $payment->setAdditionalInformation('BoletoTransactionStatusEnum', $data['BoletoTransaction']['BoletoTransactionStatus']);
1818
- }
1819
-
1820
- if (isset($data['OnlineDebitTransaction']['BankPaymentDate'])) {
1821
- $payment->setAdditionalInformation('BankPaymentDate', $data['OnlineDebitTransaction']['BankPaymentDate']);
1822
- }
1823
-
1824
- if (isset($data['OnlineDebitTransaction']['BankName'])) {
1825
- $payment->setAdditionalInformation('BankName', $data['OnlineDebitTransaction']['BankName']);
1826
- }
1827
-
1828
- if (isset($data['OnlineDebitTransaction']['Signature'])) {
1829
- $payment->setAdditionalInformation('Signature', $data['OnlineDebitTransaction']['Signature']);
1830
- }
1831
-
1832
- if (isset($data['OnlineDebitTransaction']['TransactionIdentifier'])) {
1833
- $payment->setAdditionalInformation('TransactionIdentifier', $data['OnlineDebitTransaction']['TransactionIdentifier']);
1834
- }
1835
-
1836
- $payment->save();
1837
-
1838
- if (strtolower($status) == 'overpaid') {
1839
- $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, 'overpaid');
1840
- } else {
1841
- $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true);
1842
- }
1843
-
1844
- $order->save();
1845
-
1846
- $returnMessage = "OK | {$returnMessageLabel} | invoice created and order status changed to processing.";
1847
-
1848
- $helperLog->info($returnMessage);
1849
-
1850
- return $returnMessage;
1851
- }
1852
-
1853
- /**
1854
- * Search by orderkey
1855
- * @param string $orderKey
1856
- * @return array
1857
- */
1858
- public function getTransactionHistory($orderKey) {
1859
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1860
-
1861
- // @var $standard Uecommerce_Mundipagg_Model_Standard
1862
- $standard = Mage::getModel('mundipagg/standard');
1863
-
1864
- // Get store key
1865
- $key = $standard->getMerchantKey();
1866
-
1867
- // Get Webservice URL
1868
- $url = $standard->getURL() . '/Query/' . http_build_query(array('OrderKey' => $orderKey));
1869
-
1870
- // get transactions from MundiPagg
1871
- $ch = curl_init();
1872
-
1873
- // Header
1874
- curl_setopt($ch, CURLOPT_HEADER, false);
1875
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'MerchantKey: ' . $key . ''));
1876
- curl_setopt($ch, CURLOPT_URL, $url);
1877
-
1878
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1879
-
1880
- // Execute get
1881
- $_response = curl_exec($ch);
1882
-
1883
- // Close connection
1884
- curl_close($ch);
1885
-
1886
- $helperLog->debug(print_r($_response, true));
1887
-
1888
- // Return
1889
- return array('result' => simplexml_load_string($_response));
1890
- }
1891
-
1892
- /**
1893
- * Status reference:
1894
- * http://docs.mundipagg.com/docs/enumera%C3%A7%C3%B5es
1895
- *
1896
- * @param array $postData
1897
- * @TODO refatorar o tratamento das transacoes com este metodo
1898
- */
1899
- private function processCreditCardTransactionNotification($postData) {
1900
- $status = $postData['CreditCardTransaction']['CreditCardTransactionStatus'];
1901
- $transactionKey = $postData['CreditCardTransaction']['TransactionKey'];
1902
- $capturedAmountInCents = $postData['CreditCardTransaction']['CapturedAmountInCents'];
1903
- $ccTransactionEnum = new Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum();
1904
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1905
-
1906
- switch ($status) {
1907
- case $ccTransactionEnum::AUTHORIZED_PENDING_CAPTURE:
1908
- break;
1909
-
1910
- case $ccTransactionEnum::CAPTURED:
1911
- break;
1912
-
1913
- case $ccTransactionEnum::PARTIAL_CAPTURE:
1914
- break;
1915
-
1916
- case $ccTransactionEnum::NOT_AUTHORIZED:
1917
- break;
1918
-
1919
- case $ccTransactionEnum::VOIDED:
1920
- break;
1921
-
1922
- case $ccTransactionEnum::PENDING_VOID:
1923
- break;
1924
-
1925
- case $ccTransactionEnum::PARTIAL_VOID:
1926
- break;
1927
-
1928
- case $ccTransactionEnum::REFUNDED:
1929
- break;
1930
-
1931
- case $ccTransactionEnum::PENDING_REFUND:
1932
- break;
1933
-
1934
- case $ccTransactionEnum::PARTIAL_REFUNDED:
1935
- break;
1936
-
1937
- case $ccTransactionEnum::WITH_ERROR:
1938
- break;
1939
-
1940
- case $ccTransactionEnum::NOT_FOUND_ACQUIRER:
1941
- break;
1942
-
1943
- case $ccTransactionEnum::PENDING_AUTHORIZE:
1944
- break;
1945
-
1946
- case $ccTransactionEnum::INVALID:
1947
- break;
1948
- }
1949
- }
1950
-
1951
- /**
1952
- * @author Ruan Azevedo
1953
- * @since 2016-07-20
1954
- * Status reference:
1955
- * http://docs.mundipagg.com/docs/enumera%C3%A7%C3%B5es
1956
- * @TODO refatorar o tratamento das transacoes de boleto com este metodo
1957
- */
1958
- private function processBoletoTransactionNotification() {
1959
- $status = '';
1960
- $boletoTransactionEnum = new Uecommerce_Mundipagg_Model_Enum_BoletoTransactionStatusEnum();
1961
-
1962
- switch ($status) {
1963
- case $boletoTransactionEnum::GENERATED:
1964
- break;
1965
-
1966
- case $boletoTransactionEnum::PAID:
1967
- break;
1968
-
1969
- case $boletoTransactionEnum::UNDERPAID:
1970
- break;
1971
-
1972
- case $boletoTransactionEnum::OVERPAID:
1973
- break;
1974
- }
1975
- }
1976
-
1977
- /**
1978
- * Mail error to Mage::getStoreConfig('trans_email/ident_custom1/email')
1979
- *
1980
- * @author Ruan Azevedo <razevedo@mundipagg.com>
1981
- * @since 31-05-2016
1982
- * @param string $message
1983
- */
1984
- public function mailError($message = '') {
1985
- $mail = new Zend_Mail();
1986
- $fromName = Mage::getStoreConfig('trans_email/ident_sales/name');
1987
- $fromEmail = Mage::getStoreConfig('trans_email/ident_sales/email');
1988
- $toEmail = Mage::getStoreConfig('trans_email/ident_custom1/email');
1989
- $toName = Mage::getStoreConfig('trans_email/ident_custom1/name');
1990
- $bcc = array('razevedo@mundipagg.com');
1991
- $subject = 'Error Report - MundiPagg Magento Integration';
1992
- $body = "Error Report from: {$_SERVER['HTTP_HOST']}<br><br>{$message}";
1993
-
1994
- $mail->setFrom($fromEmail, $fromName)
1995
- ->addTo($toEmail, $toName)
1996
- ->addBcc($bcc)
1997
- ->setSubject($subject)
1998
- ->setBodyHtml($body);
1999
-
2000
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
2001
-
2002
- try {
2003
- $mail->send();
2004
- $helperLog->info("Error Report Sent: {$message}");
2005
-
2006
- } catch (Exception $e) {
2007
- $helperLog->error($e);
2008
- }
2009
-
2010
- }
2011
-
2012
- /**
2013
- * Get 'RequestData' node for the One v2 request if antifraud is enabled
2014
- *
2015
- * @author Ruan Azevedo <razvedo@mundipagg.com>
2016
- * @since 06-01-2016
2017
- * @throws Mage_Core_Exception
2018
- * @return array $requestData
2019
- */
2020
- private function getRequestDataNode() {
2021
- $antifraud = Mage::getStoreConfig('payment/mundipagg_standard/antifraud');
2022
- $antifraudProvider = Mage::getStoreConfig('payment/mundipagg_standard/antifraud_provider');
2023
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
2024
- $helperHttpCore = new Mage_Core_Helper_Http();
2025
- $customerIp = $helperHttpCore->getRemoteAddr();
2026
- $outputMsg = "";
2027
- $sessionId = '';
2028
- $error = false;
2029
-
2030
- $requestData = array(
2031
- 'IpAddress' => $customerIp,
2032
- 'SessionId' => ''
2033
- );
2034
-
2035
- if ($antifraud == false) {
2036
- return false;
2037
- }
2038
-
2039
- if ($this->debugEnabled) {
2040
- $helperLog->debug("Antifraud enabled...");
2041
- }
2042
-
2043
- switch ($antifraudProvider) {
2044
- case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_NONE:
2045
- $outputMsg = "Antifraud enabled and none antifraud provider selected at module configuration.";
2046
- $error = true;
2047
- break;
2048
-
2049
- case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_CLEARSALE:
2050
- $outputMsg = "Antifraud provider: Clearsale";
2051
- $sessionId = Uecommerce_Mundipagg_Model_Customer_Session::getSessionId();
2052
- break;
2053
-
2054
- case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_FCONTROL:
2055
- $outputMsg = "Antifraud provider: FControl";
2056
- $sessionId = Uecommerce_Mundipagg_Model_Customer_Session::getSessionId();
2057
- break;
2058
- }
2059
-
2060
- if ($error) {
2061
- $helperLog->error($outputMsg, true);
2062
- // Mage::throwException($outputMsg);
2063
- }
2064
-
2065
- if (is_null($sessionId)) {
2066
- $sessionId = '';
2067
- }
2068
-
2069
- $requestData['SessionId'] = $sessionId;
2070
-
2071
- $helperLog->info($outputMsg);
2072
-
2073
- return $requestData;
2074
- }
2075
-
2076
- private function clearAntifraudDataFromSession() {
2077
- $customerSession = Mage::getSingleton('customer/session');
2078
- $customerSession->unsetData(Uecommerce_Mundipagg_Model_Customer_Session::SESSION_ID);
2079
- }
2080
-
2081
- /**
2082
- * Method to unify the transactions requests and his logs
2083
- *
2084
- * @author Ruan Azevedo <razvedo@mundipagg.com>
2085
- * @since 05-24-2016
2086
- * @param array $dataToPost
2087
- * @param string $url
2088
- * @param array $_logRequest
2089
- * @return array $_response
2090
- */
2091
- public function sendRequest($dataToPost, $url, $_logRequest = array()) {
2092
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
2093
-
2094
- if (empty($dataToPost) || empty($url)) {
2095
- $errMsg = __METHOD__ . "Exception: one or more arguments not informed to request";
2096
-
2097
- $helperLog->error($errMsg);
2098
- throw new InvalidArgumentException($errMsg);
2099
- }
2100
-
2101
- if (empty($_logRequest)) {
2102
- $_logRequest = $dataToPost;
2103
- }
2104
-
2105
- $requestRawJson = json_encode($dataToPost);
2106
- $requestJSON = $this->helperUtil->jsonEncodePretty($_logRequest);
2107
-
2108
- $helperLog->info("Request:\n{$requestJSON}\n");
2109
-
2110
- $ch = curl_init();
2111
-
2112
- // Header
2113
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'MerchantKey: ' . $this->modelStandard->getMerchantKey() . ''));
2114
- // Set the url, number of POST vars, POST data
2115
- curl_setopt($ch, CURLOPT_URL, $url);
2116
- curl_setopt($ch, CURLOPT_POSTFIELDS, $requestRawJson);
2117
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2118
-
2119
- // Execute post
2120
- $_response = curl_exec($ch);
2121
-
2122
- // Close connection
2123
- curl_close($ch);
2124
-
2125
- // Is there an error?
2126
- $xml = simplexml_load_string($_response);
2127
- $responseJSON = $this->helperUtil->jsonEncodePretty($xml);
2128
- $responseArray = json_decode($responseJSON, true);
2129
-
2130
- $helperLog->info("Response:\n{$responseJSON} \n");
2131
-
2132
- $responseData = array(
2133
- 'xmlData' => $xml,
2134
- 'arrayData' => $responseArray
2135
- );
2136
-
2137
- $this->clearAntifraudDataFromSession();
2138
-
2139
- return $responseData;
2140
- }
2141
-
2142
- /**
2143
- * Check if order is in offline retry time
2144
- *
2145
- * @author Ruan Azevedo <razevedo@mundipagg.com>
2146
- * @since 2016-06-20
2147
- * @param string $orderIncrementId
2148
- * @return boolean
2149
- */
2150
- public function orderIsInOfflineRetry($orderIncrementId) {
2151
- $model = Mage::getModel('mundipagg/offlineretry');
2152
- $offlineRetry = $model->loadByIncrementId($orderIncrementId);
2153
- $deadline = $offlineRetry->getDeadline();
2154
- $now = new DateTime();
2155
- $deadline = new DateTime($deadline);
2156
-
2157
- if ($now < $deadline) {
2158
- // in offline retry yet
2159
- return true;
2160
-
2161
- } else {
2162
- // offline retry time is over
2163
- return false;
2164
- }
2165
- }
2166
-
2167
- /**
2168
- * If the Offline Retry feature is enabled, save order offline retry statements
2169
- *
2170
- * @author Ruan Azevedo <razevedo@mundipagg.com>
2171
- * @since 2016-06-23
2172
- * @param string $orderIncrementId
2173
- * @param DateTime $createDate
2174
- */
2175
- private function saveOfflineRetryStatements($orderIncrementId, DateTime $createDate) {
2176
- // is offline retry is enabled, save statements
2177
- if (Uecommerce_Mundipagg_Model_Offlineretry::offlineRetryIsEnabled()) {
2178
- $offlineRetryTime = Mage::getStoreConfig('payment/mundipagg_standard/delayed_retry_max_time');
2179
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
2180
- $offlineRetryLogLabel = "Order #{$orderIncrementId} | offline retry statements";
2181
-
2182
- $model = new Uecommerce_Mundipagg_Model_Offlineretry();
2183
- $offlineRetry = $model->loadByIncrementId($orderIncrementId);
2184
-
2185
- try {
2186
- $offlineRetry->setOrderIncrementId($orderIncrementId);
2187
- $offlineRetry->setCreateDate($createDate->getTimestamp());
2188
-
2189
- $deadline = new DateTime();
2190
- $interval = new DateInterval('PT' . $offlineRetryTime . 'M');
2191
-
2192
- $deadline->setTimestamp($createDate->getTimestamp());
2193
- $deadline->add($interval);
2194
-
2195
- $offlineRetry->setDeadline($deadline->getTimestamp());
2196
- $offlineRetry->save();
2197
-
2198
- $helperLog->info("{$offlineRetryLogLabel} saved successfully.");
2199
-
2200
- } catch (Exception $e) {
2201
- $helperLog->error("{$offlineRetryLogLabel} cannot be saved: {$e}");
2202
- }
2203
-
2204
- }
2205
- }
2206
-
2207
- }
1
+ <?php
2
+ /**
3
+ * Uecommerce
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Uecommerce EULA.
8
+ * It is also available through the world-wide-web at this URL:
9
+ * http://www.uecommerce.com.br/
10
+ *
11
+ * DISCLAIMER
12
+ *
13
+ * Do not edit or add to this file if you wish to upgrade the extension
14
+ * to newer versions in the future. If you wish to customize the extension
15
+ * for your needs please refer to http://www.uecommerce.com.br/ for more information
16
+ *
17
+ * @category Uecommerce
18
+ * @package Uecommerce_Mundipagg
19
+ * @copyright Copyright (c) 2012 Uecommerce (http://www.uecommerce.com.br/)
20
+ * @license http://www.uecommerce.com.br/
21
+ */
22
+
23
+ /**
24
+ * Mundipagg Payment module
25
+ *
26
+ * @category Uecommerce
27
+ * @package Uecommerce_Mundipagg
28
+ * @author Uecommerce Dev Team
29
+ */
30
+ class Uecommerce_Mundipagg_Model_Api extends Uecommerce_Mundipagg_Model_Standard {
31
+
32
+ const TRANSACTION_NOT_FOUND = "Transaction not found";
33
+ const TRANSACTION_ALREADY_CAPTURED = "Transaction already captured";
34
+ const TRANSACTION_CAPTURED = "Transaction captured";
35
+ const ORDER_UNDERPAID = "Order underpaid";
36
+ const ORDER_OVERPAID = "Order overpaid";
37
+ const INTEGRATION_TIMEOUT = "MundiPagg API timeout, waiting Mundi notification";
38
+ const UNEXPECTED_ERROR = "Unexpected error";
39
+
40
+ private $helperUtil;
41
+ private $modelStandard;
42
+ private $debugEnabled;
43
+ private $moduleVersion;
44
+
45
+ public function __construct() {
46
+ $this->helperUtil = new Uecommerce_Mundipagg_Helper_Util();
47
+ $this->modelStandard = new Uecommerce_Mundipagg_Model_Standard();
48
+ $this->moduleVersion = Mage::helper('mundipagg')->getExtensionVersion();
49
+ $this->debugEnabled = $this->modelStandard->getDebug();
50
+ parent::_construct();
51
+ }
52
+
53
+ /**
54
+ * Credit Card Transaction
55
+ */
56
+ public function creditCardTransaction($order, $data, Uecommerce_Mundipagg_Model_Standard $standard) {
57
+ $helper = Mage::helper('mundipagg');
58
+
59
+ try {
60
+ // Installments configuration
61
+ $installment = $standard->getParcelamento();
62
+ $qtdParcelasMax = $standard->getParcelamentoMax();
63
+
64
+ // Get Webservice URL
65
+ $url = $standard->getURL();
66
+
67
+ // Set Data
68
+ $_request = array();
69
+ $_request["Order"] = array();
70
+ $_request["Order"]["OrderReference"] = $order->getIncrementId();
71
+
72
+ // if ($standard->getEnvironment() != 'production') {
73
+ // $_request["Order"]["OrderReference"] = md5(date('Y-m-d H:i:s')); // Identificação do pedido na loja
74
+ // }
75
+
76
+ /*
77
+ * Append transaction (multi credit card payments)
78
+ * When one of Credit Cards has not been authorized and we try with a new one)
79
+ */
80
+ if ($orderReference = $order->getPayment()->getAdditionalInformation('OrderReference')) {
81
+ $_request["Order"]["OrderReference"] = $orderReference;
82
+ }
83
+
84
+ // Collection
85
+ $_request["CreditCardTransactionCollection"] = array();
86
+
87
+ /* @var $recurrencyModel Uecommerce_Mundipagg_Model_Recurrency */
88
+ $recurrencyModel = Mage::getModel('mundipagg/recurrency');
89
+
90
+ $creditcardTransactionCollection = array();
91
+
92
+ // Partial Payment (we use this reference in order to authorize the rest of the amount)
93
+ if ($order->getPayment()->getAdditionalInformation('OrderReference')) {
94
+ $_request["CreditCardTransactionCollection"]["OrderReference"] = $order->getPayment()->getAdditionalInformation('OrderReference');
95
+ }
96
+
97
+ $baseGrandTotal = str_replace(',', '.', $order->getBaseGrandTotal());
98
+ $amountInCentsVar = intval(strval(($baseGrandTotal * 100)));
99
+
100
+ // CreditCardOperationEnum : if more than one payment method we use AuthOnly and then capture if all are ok
101
+
102
+ $num = $helper->getCreditCardsNumber($data['payment_method']);
103
+
104
+ $installmentCount = 1;
105
+
106
+ if ($num > 1) {
107
+ $creditCardOperationEnum = 'AuthOnly';
108
+ } else {
109
+ $creditCardOperationEnum = $standard->getCreditCardOperationEnum();
110
+ }
111
+
112
+ foreach ($data['payment'] as $i => $paymentData) {
113
+ $creditcardTransactionData = new stdclass();
114
+ $creditcardTransactionData->CreditCard = new stdclass();
115
+ $creditcardTransactionData->Options = new stdclass();
116
+
117
+ // InstantBuyKey payment
118
+ if (isset($paymentData['card_on_file_id'])) {
119
+ $token = Mage::getModel('mundipagg/cardonfile')->load($paymentData['card_on_file_id']);
120
+
121
+ if ($token->getId() && $token->getEntityId() == $order->getCustomerId()) {
122
+ $creditcardTransactionData->CreditCard->InstantBuyKey = $token->getToken();
123
+ $creditcardTransactionData->CreditCard->CreditCardBrand = $token->getCcType();
124
+ $creditcardTransactionData->CreditCardOperation = $creditCardOperationEnum;
125
+ /** Tipo de operação: AuthOnly | AuthAndCapture | AuthAndCaptureWithDelay */
126
+ $creditcardTransactionData->AmountInCents = intval(strval(($paymentData['AmountInCents']))); // Valor da transação
127
+ $creditcardTransactionData->InstallmentCount = $paymentData['InstallmentCount']; // Nº de parcelas
128
+ $creditcardTransactionData->Options->CurrencyIso = "BRL"; //Moeda do pedido
129
+ }
130
+
131
+ } else { // Credit Card
132
+ $creditcardTransactionData->CreditCard->CreditCardNumber = $paymentData['CreditCardNumber']; // Número do cartão
133
+ $creditcardTransactionData->CreditCard->HolderName = $paymentData['HolderName']; // Nome do cartão
134
+ $creditcardTransactionData->CreditCard->SecurityCode = $paymentData['SecurityCode']; // Código de segurança
135
+ $creditcardTransactionData->CreditCard->ExpMonth = $paymentData['ExpMonth']; // Mês Exp
136
+ $creditcardTransactionData->CreditCard->ExpYear = $paymentData['ExpYear']; // Ano Exp
137
+ $creditcardTransactionData->CreditCard->CreditCardBrand = $paymentData['CreditCardBrandEnum']; // Bandeira do cartão : Visa ,MasterCard ,Hipercard ,Amex */
138
+ $creditcardTransactionData->CreditCardOperation = $creditCardOperationEnum;
139
+ /** Tipo de operação: AuthOnly | AuthAndCapture | AuthAndCaptureWithDelay */
140
+ $creditcardTransactionData->AmountInCents = intval(strval(($paymentData['AmountInCents']))); // Valor da transação
141
+ $creditcardTransactionData->InstallmentCount = $paymentData['InstallmentCount']; // Nº de parcelas
142
+ $creditcardTransactionData->Options->CurrencyIso = "BRL"; //Moeda do pedido
143
+ }
144
+
145
+ $installmentCount = $paymentData['InstallmentCount'];
146
+
147
+ // BillingAddress
148
+ if ($standard->getAntiFraud() == 1) {
149
+ $addy = $this->buyerBillingData($order, $data, $_request, $standard);
150
+
151
+ $creditcardTransactionData->CreditCard->BillingAddress = $addy['AddressCollection'][0];
152
+ }
153
+
154
+ if ($standard->getEnvironment() != 'production') {
155
+ $creditcardTransactionData->Options->PaymentMethodCode = $standard->getPaymentMethodCode(); // Código do meio de pagamento
156
+ }
157
+
158
+ // Verificamos se tem o produto de teste da Cielo no carrinho
159
+ foreach ($order->getItemsCollection() as $item) {
160
+ if ($item->getSku() == $standard->getCieloSku() && $standard->getEnvironment() == 'production') {
161
+ $creditcardTransactionData->Options->PaymentMethodCode = 5; // Código do meio de pagamento Cielo
162
+ }
163
+
164
+ // Adicionamos o produto a lógica de recorrência.
165
+ $qty = $item->getQtyOrdered();
166
+
167
+ for ($qt = 1; $qt <= $qty; $qt++) {
168
+ $recurrencyModel->setItem($item);
169
+ }
170
+ }
171
+
172
+ $creditcardTransactionCollection[] = $creditcardTransactionData;
173
+ }
174
+
175
+ $_request["CreditCardTransactionCollection"] = $this->ConvertCreditcardTransactionCollectionFromRequest($creditcardTransactionCollection, $standard);
176
+
177
+ $_request = $recurrencyModel->generateRecurrences($_request, $installmentCount);
178
+
179
+ // Buyer data
180
+ $_request["Buyer"] = array();
181
+ $_request["Buyer"] = $this->buyerBillingData($order, $data, $_request, $standard);
182
+
183
+ // Cart data
184
+ $_request["ShoppingCartCollection"] = array();
185
+ $_request["ShoppingCartCollection"] = $this->cartData($order, $data, $_request, $standard);
186
+
187
+ //verify anti-fraud config and mount the node 'RequestData'
188
+ $nodeRequestData = $this->getRequestDataNode();
189
+
190
+ if (is_array($nodeRequestData)) {
191
+ $_request['RequestData'] = $nodeRequestData;
192
+ }
193
+
194
+ // check anti fraud minimum value
195
+ if ($helper->isAntiFraudEnabled()) {
196
+ $antifraudProviderConfig = intval(Mage::getStoreConfig('payment/mundipagg_standard/antifraud_provider'));
197
+ $antifraudProvider = null;
198
+
199
+ switch ($antifraudProviderConfig) {
200
+ case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_CLEARSALE:
201
+ $antifraudProvider = 'clearsale';
202
+ break;
203
+
204
+ case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_FCONTROL:
205
+ $antifraudProvider = 'fcontrol';
206
+ break;
207
+
208
+ case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_STONE:
209
+ $antifraudProvider = 'stone';
210
+ break;
211
+ }
212
+
213
+ $minValueConfig = Mage::getStoreConfig("payment/mundipagg_standard/antifraud_minimum_{$antifraudProvider}");
214
+ $minValueConfig = $helper->formatPriceToCents($minValueConfig);
215
+
216
+ if ($amountInCentsVar >= $minValueConfig) {
217
+ $_request['Options']['IsAntiFraudEnabled'] = true;
218
+ } else {
219
+ $_request['Options']['IsAntiFraudEnabled'] = false;
220
+ }
221
+
222
+ }
223
+
224
+ $response = $this->sendJSON($_request);
225
+ $errorReport = $helper->issetOr($response['ErrorReport']);
226
+ $orderKey = $helper->issetOr($response['OrderResult']['OrderKey']);
227
+ $orderReference = $helper->issetOr($response['OrderResult']['OrderReference']);
228
+ $createDate = $helper->issetOr($response['OrderResult']['CreateDate']);
229
+
230
+ // if some error ocurred ex.: http 500 internal server error
231
+ if (!is_null($errorReport)) {
232
+ $errorItemCollection = $errorReport['ErrorItemCollection'];
233
+
234
+ // Return errors
235
+ return array(
236
+ 'error' => 1,
237
+ 'ErrorCode' => '',
238
+ 'ErrorDescription' => '',
239
+ 'OrderKey' => $orderKey,
240
+ 'OrderReference' => $orderReference,
241
+ 'ErrorItemCollection' => $errorItemCollection,
242
+ 'result' => $response,
243
+ );
244
+ }
245
+
246
+ // Transactions colllection
247
+ $creditCardTransactionResultCollection = $helper->issetOr($response['CreditCardTransactionResultCollection']);
248
+ $transactionsQty = count($creditCardTransactionResultCollection);
249
+
250
+ // Only 1 transaction
251
+ if (count($creditCardTransactionResultCollection) == 1) {
252
+ $creditCardTransaction = $creditCardTransactionResultCollection[0];
253
+ $success = $helper->issetOr($creditCardTransaction['Success'], false);
254
+
255
+ //and transaction success is true
256
+ if ($success === true) {
257
+ // $trans = $creditCardTransactionResultCollection['CreditCardTransactionResult'];
258
+
259
+ // We save Card On File
260
+ if ($data['customer_id'] != 0 && isset($data['payment'][1]['token']) && $data['payment'][1]['token'] == 'new') {
261
+ $cardonfile = Mage::getModel('mundipagg/cardonfile');
262
+
263
+ $cardonfile->setEntityId($data['customer_id']);
264
+ $cardonfile->setAddressId($data['address_id']);
265
+ $cardonfile->setCcType($data['payment'][1]['CreditCardBrandEnum']);
266
+ $cardonfile->setCreditCardMask($creditCardTransaction['CreditCard']['MaskedCreditCardNumber']);
267
+ $cardonfile->setExpiresAt(date("Y-m-t", mktime(0, 0, 0, $data['payment'][1]['ExpMonth'], 1, $data['payment'][1]['ExpYear'])));
268
+ $cardonfile->setToken($creditCardTransaction['CreditCard']['InstantBuyKey']);
269
+ $cardonfile->setActive(1);
270
+ $cardonfile->save();
271
+ }
272
+
273
+ $result = array(
274
+ 'success' => true,
275
+ 'message' => 1,
276
+ 'returnMessage' => urldecode($creditCardTransaction['AcquirerMessage']),
277
+ 'OrderKey' => $orderKey,
278
+ 'OrderReference' => $orderReference,
279
+ 'isRecurrency' => $recurrencyModel->recurrencyExists(),
280
+ 'result' => $response
281
+ );
282
+
283
+ if (is_null($createDate === false)) {
284
+ $result['CreateDate'] = $createDate;
285
+ }
286
+
287
+ return $result;
288
+
289
+ } else {
290
+ // CreditCardTransactionResult success == false, not authorized
291
+ $result = array(
292
+ 'error' => 1,
293
+ 'ErrorCode' => $creditCardTransaction['AcquirerReturnCode'],
294
+ 'ErrorDescription' => urldecode($creditCardTransaction['AcquirerMessage']),
295
+ 'OrderKey' => $orderKey,
296
+ 'OrderReference' => $orderReference,
297
+ 'result' => $response
298
+ );
299
+
300
+ if (is_null($createDate) === false) {
301
+ $result['CreateDate'] = $createDate;
302
+ }
303
+
304
+ /**
305
+ * @TODO precisa refatorar isto, pois deste jeito esta gravando offlineretry pra que qualquer pedido
306
+ * com mais de 1 cartao
307
+ */
308
+ // save offline retry statements if this feature is enabled
309
+ $this->saveOfflineRetryStatements($orderReference, new DateTime($createDate));
310
+
311
+ return $result;
312
+ }
313