Mundipagg_Integracao - Version 2.9.2

Version Notes

Offline retry not authorized transactions fix

Download this release

Release Info

Developer MundiPagg
Extension Mundipagg_Integracao
Version 2.9.2
Comparing to
See all releases


Code changes from version 2.9.1 to 2.9.2

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 ADDED
@@ -0,0 +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
+ }
app/code/community/Uecommerce/Mundipagg/Model/Api.php CHANGED
@@ -1,2171 +1,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
-
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
- if (!empty($data['BoletoTransaction'])) {
1244
- $status = $data['BoletoTransaction']['BoletoTransactionStatus'];
1245
- $transactionKey = $data['BoletoTransaction']['TransactionKey'];
1246
- $capturedAmountInCents = $data['BoletoTransaction']['AmountPaidInCents'];
1247
- $transactionData = $data['BoletoTransaction'];
1248
- }
1249
-
1250
- if (!empty($data['CreditCardTransaction'])) {
1251
- $status = $data['CreditCardTransaction']['CreditCardTransactionStatus'];
1252
- $transactionKey = $data['CreditCardTransaction']['TransactionKey'];
1253
- $capturedAmountInCents = $data['CreditCardTransaction']['CapturedAmountInCents'];
1254
- $transactionData = $data['CreditCardTransaction'];
1255
- }
1256
-
1257
- if (!empty($data['OnlineDebitTransaction'])) {
1258
- $status = $data['OnlineDebitTransaction']['OnlineDebitTransactionStatus'];
1259
- $transactionKey = $data['OnlineDebitTransaction']['TransactionKey'];
1260
- $capturedAmountInCents = $data['OnlineDebitTransaction']['AmountPaidInCents'];
1261
- $transactionData = $data['OnlineDebitTransaction'];
1262
- }
1263
-
1264
- $returnMessageLabel = "Order #{$order->getIncrementId()}";
1265
-
1266
- if (isset($data['OrderStatus'])) {
1267
- $orderStatus = $data['OrderStatus'];
1268
-
1269
- //if MundiPagg order status is canceled, cancel the order on Magento
1270
- if ($orderStatus == Uecommerce_Mundipagg_Model_Enum_OrderStatusEnum::CANCELED) {
1271
-
1272
- if ($order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) {
1273
- $returnMessage = "OK | {$returnMessageLabel} | Order already canceled.";
1274
-
1275
- $helperLog->info($returnMessage);
1276
-
1277
- return $returnMessage;
1278
- }
1279
-
1280
- try {
1281
- $this->tryCancelOrder($order, "Transaction update received: {$status}");
1282
- $returnMessage = "OK | {$returnMessageLabel} | Canceled successfully";
1283
- $helperLog->info($returnMessage);
1284
-
1285
- } catch (Exception $e) {
1286
- $returnMessage = "KO | {$returnMessageLabel} | {$e->getMessage()}";
1287
- $helperLog->error($returnMessage);
1288
- }
1289
-
1290
- return $returnMessage;
1291
- }
1292
- }
1293
-
1294
- // We check if transactionKey exists in database
1295
- $t = 0;
1296
-
1297
- $transactions = Mage::getModel('sales/order_payment_transaction')
1298
- ->getCollection()
1299
- ->addAttributeToFilter('order_id', array('eq' => $order->getEntityId()));
1300
-
1301
- foreach ($transactions as $key => $transaction) {
1302
- $orderTransactionKey = $transaction->getAdditionalInformation('TransactionKey');
1303
-
1304
- // transactionKey found
1305
- if ($orderTransactionKey == $transactionKey) {
1306
- $t++;
1307
- continue;
1308
- }
1309
- }
1310
-
1311
- if ($t <= 0) {
1312
- $helperLog->info("Order #{$orderReference} | TransactionKey {$transactionKey} not found on database for this order. Adding...");
1313
-
1314
- $payment = $order->getPayment();
1315
- $transactionId = $transactionKey;
1316
- $transactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH;
1317
-
1318
- $this->_addTransaction($payment, $transactionId, $transactionType, $transactionData);
1319
- }
1320
-
1321
- $order->addStatusHistoryComment("Transaction update received: {$status}", false);
1322
- $order->save();
1323
-
1324
- // transactionKey has been found so we can proceed
1325
- /**
1326
- * @var $recurrence Uecommerce_Mundiapgg_Model_Recurrency
1327
- */
1328
- $recurrence = Mage::getModel('mundipagg/recurrency');
1329
- $recurrence->checkRecurrencesByOrder($order);
1330
-
1331
- $statusWithError = Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum::WITH_ERROR;
1332
- $statusWithError = strtolower($statusWithError);
1333
-
1334
- $lowerStatus = strtolower($status);
1335
-
1336
- switch ($lowerStatus) {
1337
- case 'captured':
1338
- $amountToCapture = $capturedAmountInCents * 0.01;
1339
-
1340
- try {
1341
- $return = $this->captureTransaction($order, $amountToCapture, $transactionKey);
1342
-
1343
- } catch (Exception $e) {
1344
- $orderPayment = new Uecommerce_Mundipagg_Model_Order_Payment();
1345
- $error = $e->getMessage();
1346
-
1347
- $helperLog->setLogLabel("#{$orderReference} | {$transactionKey}");
1348
-
1349
- switch ($error) {
1350
- case $orderPayment::ERR_CANNOT_CREATE_INVOICE:
1351
- $error = "Can't created invoice";
1352
- $helperLog->error($error);
1353
- break;
1354
-
1355
- case $orderPayment::ERR_CANNOT_CREATE_INVOICE_WITHOUT_PRODUCTS:
1356
- $error = "Can't create invoice without products";
1357
- $helperLog->error($error);
1358
- break;
1359
-
1360
- default:
1361
- $error = "Can't create invoice, unexpected error: {$error}";
1362
- $helperLog->error($error);
1363
- }
1364
-
1365
- $returnMessage = "KO | #{$orderReference} | Can't capture transaction {$transactionKey} | {$error}";
1366
-
1367
- $helperLog->setLogLabel("");
1368
- $helperLog->info($returnMessage);
1369
-
1370
- return $returnMessage;
1371
- }
1372
-
1373
- switch ($return) {
1374
- case self::TRANSACTION_ALREADY_CAPTURED:
1375
- $returnMessage = "OK | #{$orderReference} | {$transactionKey} | " . self::TRANSACTION_ALREADY_CAPTURED;
1376
- $helperLog->info($returnMessage);
1377
-
1378
- return $returnMessage;
1379
- break;
1380
-
1381
- case self::TRANSACTION_CAPTURED:
1382
- $returnMessage = "OK | #{$orderReference} | {$transactionKey} | " . self::TRANSACTION_CAPTURED;
1383
- $helperLog->info($returnMessage);
1384
-
1385
- return $returnMessage;
1386
- break;
1387
- }
1388
-
1389
- break;
1390
-
1391
- case 'paid':
1392
- case 'overpaid':
1393
- if ($order->canUnhold()) {
1394
- $order->unhold();
1395
- $helperLog->info("{$returnMessageLabel} | unholded.");
1396
- }
1397
-
1398
- if (!$order->canInvoice()) {
1399
- $returnMessage = "OK | {$returnMessageLabel} | Can't create invoice. Transaction status '{$status}' processed.";
1400
-
1401
- $helperLog->info($returnMessage);
1402
-
1403
- return $returnMessage;
1404
- }
1405
-
1406
- // Partial invoice
1407
- $epsilon = 0.00001;
1408
-
1409
- if ($order->canInvoice() && abs($order->getGrandTotal() - $capturedAmountInCents * 0.01) > $epsilon) {
1410
- $baseTotalPaid = $order->getTotalPaid();
1411
-
1412
- // If there is already a positive baseTotalPaid value it's not the first transaction
1413
- if ($baseTotalPaid > 0) {
1414
- $baseTotalPaid += $capturedAmountInCents * 0.01;
1415
-
1416
- $order->setTotalPaid(0);
1417
- } else {
1418
- $baseTotalPaid = $capturedAmountInCents * 0.01;
1419
-
1420
- $order->setTotalPaid($baseTotalPaid);
1421
- }
1422
-
1423
- // Can invoice only if total captured amount is equal to GrandTotal
1424
- if (abs($order->getGrandTotal() - $baseTotalPaid) < $epsilon) {
1425
- $result = $this->createInvoice($order, $data, $baseTotalPaid, $status);
1426
-
1427
- return $result;
1428
-
1429
- } else {
1430
- $order->save();
1431
-
1432
- $returnMessage = "OK | {$returnMessageLabel} | Captured amount isn't equal to grand total, invoice not created. Transaction status '{$status}' received.";
1433
-
1434
- return $returnMessage;
1435
- }
1436
- }
1437
-
1438
- // Create invoice
1439
- if ($order->canInvoice() && abs($capturedAmountInCents * 0.01 - $order->getGrandTotal()) < $epsilon) {
1440
- $result = $this->createInvoice($order, $data, $order->getGrandTotal(), $status);
1441
-
1442
- return $result;
1443
- }
1444
-
1445
- $returnMessage = "Order {$order->getIncrementId()} | Unable to create invoice for this order.";
1446
-
1447
- $helperLog->error($returnMessage);
1448
-
1449
- return "KO | {$returnMessage}";
1450
-
1451
- break;
1452
-
1453
- case 'underpaid':
1454
- if ($order->canUnhold()) {
1455
- $helperLog->info("{$returnMessageLabel} | unholded.");
1456
- $order->unhold();
1457
- }
1458
-
1459
- $order->addStatusHistoryComment('Captured offline amount of R$' . $capturedAmountInCents * 0.01, false);
1460
- $order->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, 'underpaid');
1461
- $order->setBaseTotalPaid($capturedAmountInCents * 0.01);
1462
- $order->setTotalPaid($capturedAmountInCents * 0.01);
1463
- $order->save();
1464
-
1465
- $returnMessage = "OK | {$returnMessageLabel} | Transaction status '{$status}' processed. Order status updated.";
1466
-
1467
- $helperLog->info($returnMessage);
1468
-
1469
- return $returnMessage;
1470
-
1471
- break;
1472
-
1473
- case 'notauthorized':
1474
- $returnMessage = "OK | {$returnMessageLabel} | Transaction status '{$status}' received.";
1475
-
1476
- $helperLog->info($returnMessage);
1477
-
1478
- return $returnMessage;
1479
-
1480
- break;
1481
-
1482
- case 'canceled':
1483
- case 'refunded':
1484
- case 'voided':
1485
- if ($order->canUnhold()) {
1486
- $helperLog->info("{$returnMessageLabel} unholded.");
1487
- $order->unhold();
1488
- }
1489
-
1490
- $ok = 0;
1491
- $invoices = array();
1492
- $canceledInvoices = array();
1493
-
1494
- foreach ($order->getInvoiceCollection() as $invoice) {
1495
- // We check if invoice can be refunded
1496
- if ($invoice->canRefund()) {
1497
- $invoices[] = $invoice;
1498
- }
1499
-
1500
- // We check if invoice has already been canceled
1501
- if ($invoice->isCanceled()) {
1502
- $canceledInvoices[] = $invoice;
1503
- }
1504
- }
1505
-
1506
- // Refund invoices and Credit Memo
1507
- if (!empty($invoices)) {
1508
- $service = Mage::getModel('sales/service_order', $order);
1509
-
1510
- foreach ($invoices as $invoice) {
1511
- $invoice->setState(Mage_Sales_Model_Order_Invoice::STATE_CANCELED);
1512
- $invoice->save();
1513
-
1514
- $creditmemo = $service->prepareInvoiceCreditmemo($invoice);
1515
- $creditmemo->setOfflineRequested(true);
1516
- $creditmemo->register()->save();
1517
- }
1518
-
1519
- // Close order
1520
- $order->setData('state', 'closed');
1521
- $order->setStatus('closed');
1522
- $order->save();
1523
-
1524
- // Return
1525
- $ok++;
1526
- }
1527
-
1528
- // Credit Memo
1529
- if (!empty($canceledInvoices)) {
1530
- $service = Mage::getModel('sales/service_order', $order);
1531
-
1532
- foreach ($invoices as $invoice) {
1533
- $creditmemo = $service->prepareInvoiceCreditmemo($invoice);
1534
- $creditmemo->setOfflineRequested(true);
1535
- $creditmemo->register()->save();
1536
- }
1537
-
1538
- // Close order
1539
- $order->setData('state', Mage_Sales_Model_Order::STATE_CLOSED);
1540
- $order->setStatus(Mage_Sales_Model_Order::STATE_CLOSED);
1541
- $order->save();
1542
-
1543
- // Return
1544
- $ok++;
1545
- }
1546
-
1547
- if (empty($invoices) && empty($canceledInvoices)) {
1548
- // Cancel order
1549
- $order->cancel()->save();
1550
- $helperLog->info("{$returnMessageLabel} | Order canceled.");
1551
-
1552
- // Return
1553
- $ok++;
1554
- }
1555
-
1556
- if ($ok > 0) {
1557
- $returnMessage = "{$returnMessageLabel} | Order status '{$status}' processed.";
1558
- $helperLog->info($returnMessage);
1559
-
1560
- return "OK | {$returnMessage}";
1561
-
1562
- } else {
1563
- $returnMessage = "{$returnMessageLabel} | Unable to process transaction status '{$status}'.";
1564
-
1565
- $helperLog->info($returnMessage);
1566
-
1567
- return "KO | {$returnMessage}";
1568
- }
1569
-
1570
- break;
1571
-
1572
- case 'authorizedpendingcapture':
1573
- $returnMessage = "Order #{$order->getIncrementId()} | Transaction status '{$status}' received.";
1574
-
1575
- $helperLog->info($returnMessage);
1576
-
1577
- return "OK | {$returnMessage}";
1578
- break;
1579
-
1580
- case $statusWithError:
1581
- try {
1582
- Uecommerce_Mundipagg_Model_Standard::transactionWithError($order, false);
1583
- $returnMessage = "OK | {$returnMessageLabel} | Order changed to WithError status";
1584
-
1585
- } catch (Exception $e) {
1586
- $returnMessage = "KO | {$returnMessageLabel} | {$e->getMessage()}";
1587
- }
1588
-
1589
- $helperLog->info($returnMessage);
1590
-
1591
- return $returnMessage;
1592
-
1593
- break;
1594
-
1595
- // For other status we add comment to history
1596
- default:
1597
- $returnMessage = "Order #{$order->getIncrementId()} | unexpected transaction status: {$status}";
1598
-
1599
- $helperLog->info($returnMessage);
1600
-
1601
- return "OK | {$returnMessage}";
1602
- }
1603
-
1604
-
1605
- } catch (Exception $e) {
1606
- $returnMessage = "Internal server error | {$e->getCode()} - ErrMsg: {$e->getMessage()}";
1607
-
1608
- //Log error
1609
- $helperLog->error($e, true);
1610
-
1611
- //Mail error
1612
- $this->mailError(print_r($e->getMessage(), 1));
1613
-
1614
- return "KO | {$returnMessage}";
1615
- }
1616
- }
1617
-
1618
- /**
1619
- * @param Mage_Sales_Model_Order $order
1620
- * @param string $comment
1621
- * @return bool
1622
- * @throws RuntimeException
1623
- */
1624
- public function tryCancelOrder(Mage_Sales_Model_Order $order, $comment = null) {
1625
- if ($order->canCancel()) {
1626
- try {
1627
- $order->cancel();
1628
-
1629
- if (!is_null($comment) && is_string($comment)) {
1630
- $order->addStatusHistoryComment($comment);
1631
- }
1632
-
1633
- $order->save();
1634
-
1635
- return true;
1636
-
1637
- } catch (Exception $e) {
1638
- throw new RuntimeException("Order cannot be canceled. Error reason: {$e->getMessage()}");
1639
- }
1640
-
1641
- } else {
1642
- throw new RuntimeException("Order cannot be canceled.");
1643
- }
1644
- }
1645
-
1646
- /**
1647
- * @param Mage_Sales_Model_Order $order
1648
- * @param $amountToCapture
1649
- * @param $transactionKey
1650
- * @throws RuntimeException
1651
- * @return string
1652
- */
1653
- private function captureTransaction(Mage_Sales_Model_Order $order, $amountToCapture, $transactionKey) {
1654
- $log = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1655
- $log->setLogLabel("#{$order->getIncrementId()} | {$transactionKey}");
1656
-
1657
- $totalPaid = $order->getTotalPaid();
1658
- $grandTotal = $order->getGrandTotal();
1659
- $createInvoice = false;
1660
- $transaction = null;
1661
-
1662
- if (is_null($totalPaid)) {
1663
- $totalPaid = 0;
1664
- }
1665
-
1666
- $totalPaid += $amountToCapture;
1667
-
1668
- $transactions = Mage::getModel('sales/order_payment_transaction')
1669
- ->getCollection()
1670
- ->addAttributeToFilter('order_id', array('eq' => $order->getEntityId()));
1671
-
1672
- foreach ($transactions as $i) {
1673
- $orderTransactionKey = $i->getAdditionalInformation('TransactionKey');
1674
-
1675
- // transactionKey found
1676
- if ($orderTransactionKey == $transactionKey) {
1677
- $transaction = $i;
1678
- break;
1679
- }
1680
- }
1681
-
1682
- if (is_null($transaction)) {
1683
- Mage::throwException(self::TRANSACTION_NOT_FOUND);
1684
- }
1685
-
1686
- if ($transaction->getIsClosed() == '1') {
1687
- return self::TRANSACTION_ALREADY_CAPTURED;
1688
- }
1689
-
1690
- if ($totalPaid < $grandTotal) {
1691
- $order->setStatus('underpaid');
1692
- } elseif ($totalPaid > $grandTotal) {
1693
- $order->setStatus('overpaid');
1694
- }
1695
-
1696
- if ($totalPaid == $grandTotal) {
1697
- // reset total paid, preparing to invoice
1698
- $createInvoice = true;
1699
- }
1700
-
1701
- $orderPayment = new Uecommerce_Mundipagg_Model_Order_Payment();
1702
-
1703
- try {
1704
- if ($createInvoice) {
1705
- $invoice = $orderPayment->createInvoice($order);
1706
- $log->info("Invoice {$invoice->getIncrementId()} created");
1707
- }
1708
-
1709
- $resource = Mage::getSingleton('core/resource');
1710
- $conn = $resource->getConnection('core_write');
1711
- $query = "UPDATE sales_payment_transaction SET is_closed = TRUE WHERE transaction_id={$transaction->getId()}";
1712
-
1713
- $conn->query($query);
1714
- $log->info("Magento payment transaction closed");
1715
-
1716
- $order->setTotalPaid($totalPaid);
1717
- $order->save();
1718
-
1719
- } catch (Exception $e) {
1720
- throw new RuntimeException($e->getMessage());
1721
- }
1722
-
1723
- $log->info("Captured amount: {$amountToCapture}");
1724
-
1725
- return self::TRANSACTION_CAPTURED;
1726
- }
1727
-
1728
- private function queryTransactions() {
1729
-
1730
- }
1731
-
1732
- /**
1733
- * Create invoice
1734
- * @return string OK|KO
1735
- */
1736
- private function createInvoice($order, $data, $totalPaid, $status) {
1737
- $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
1738
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1739
- $returnMessageLabel = "Order #{$order->getIncrementId()}";
1740
-
1741
- if (!$invoice->getTotalQty()) {
1742
- $returnMessage = 'Cannot create an invoice without products.';
1743
-
1744
- $order->addStatusHistoryComment($returnMessage, false);
1745
- $order->save();
1746
-
1747
- $helperLog->info("{$returnMessageLabel} | {$returnMessage}");
1748
-
1749
- return $returnMessage;
1750
- }
1751
-
1752
- $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
1753
- $invoice->register();
1754
- $invoice->getOrder()->setCustomerNoteNotify(true);
1755
- $invoice->getOrder()->setIsInProcess(true);
1756
- $invoice->setCanVoidFlag(true);
1757
-
1758
- $transactionSave = Mage::getModel('core/resource_transaction')
1759
- ->addObject($invoice)
1760
- ->addObject($invoice->getOrder());
1761
- $transactionSave->save();
1762
-
1763
- // Send invoice email if enabled
1764
- if (Mage::helper('sales')->canSendNewInvoiceEmail($order->getStoreId())) {
1765
- $invoice->sendEmail(true);
1766
- $invoice->setEmailSent(true);
1767
- }
1768
-
1769
- $order->setBaseTotalPaid($totalPaid);
1770
- $order->addStatusHistoryComment('Captured offline', false);
1771
-
1772
- $payment = $order->getPayment();
1773
-
1774
- $payment->setAdditionalInformation('OrderStatusEnum', $data['OrderStatus']);
1775
-
1776
- if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_creditcard') {
1777
- $payment->setAdditionalInformation('CreditCardTransactionStatusEnum', $data['CreditCardTransaction']['CreditCardTransactionStatus']);
1778
- }
1779
-
1780
- if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_boleto') {
1781
- $payment->setAdditionalInformation('BoletoTransactionStatusEnum', $data['BoletoTransaction']['BoletoTransactionStatus']);
1782
- }
1783
-
1784
- if (isset($data['OnlineDebitTransaction']['BankPaymentDate'])) {
1785
- $payment->setAdditionalInformation('BankPaymentDate', $data['OnlineDebitTransaction']['BankPaymentDate']);
1786
- }
1787
-
1788
- if (isset($data['OnlineDebitTransaction']['BankName'])) {
1789
- $payment->setAdditionalInformation('BankName', $data['OnlineDebitTransaction']['BankName']);
1790
- }
1791
-
1792
- if (isset($data['OnlineDebitTransaction']['Signature'])) {
1793
- $payment->setAdditionalInformation('Signature', $data['OnlineDebitTransaction']['Signature']);
1794
- }
1795
-
1796
- if (isset($data['OnlineDebitTransaction']['TransactionIdentifier'])) {
1797
- $payment->setAdditionalInformation('TransactionIdentifier', $data['OnlineDebitTransaction']['TransactionIdentifier']);
1798
- }
1799
-
1800
- $payment->save();
1801
-
1802
- if (strtolower($status) == 'overpaid') {
1803
- $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, 'overpaid');
1804
- } else {
1805
- $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true);
1806
- }
1807
-
1808
- $order->save();
1809
-
1810
- $returnMessage = "OK | {$returnMessageLabel} | invoice created and order status changed to processing.";
1811
-
1812
- $helperLog->info($returnMessage);
1813
-
1814
- return $returnMessage;
1815
- }
1816
-
1817
- /**
1818
- * Search by orderkey
1819
- * @param string $orderKey
1820
- * @return array
1821
- */
1822
- public function getTransactionHistory($orderKey) {
1823
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1824
-
1825
- // @var $standard Uecommerce_Mundipagg_Model_Standard
1826
- $standard = Mage::getModel('mundipagg/standard');
1827
-
1828
- // Get store key
1829
- $key = $standard->getMerchantKey();
1830
-
1831
- // Get Webservice URL
1832
- $url = $standard->getURL() . '/Query/' . http_build_query(array('OrderKey' => $orderKey));
1833
-
1834
- // get transactions from MundiPagg
1835
- $ch = curl_init();
1836
-
1837
- // Header
1838
- curl_setopt($ch, CURLOPT_HEADER, false);
1839
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'MerchantKey: ' . $key . ''));
1840
- curl_setopt($ch, CURLOPT_URL, $url);
1841
-
1842
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1843
-
1844
- // Execute get
1845
- $_response = curl_exec($ch);
1846
-
1847
- // Close connection
1848
- curl_close($ch);
1849
-
1850
- $helperLog->debug(print_r($_response, true));
1851
-
1852
- // Return
1853
- return array('result' => simplexml_load_string($_response));
1854
- }
1855
-
1856
- /**
1857
- * Status reference:
1858
- * http://docs.mundipagg.com/docs/enumera%C3%A7%C3%B5es
1859
- *
1860
- * @param array $postData
1861
- * @TODO refatorar o tratamento das transacoes com este metodo
1862
- */
1863
- private function processCreditCardTransactionNotification($postData) {
1864
- $status = $postData['CreditCardTransaction']['CreditCardTransactionStatus'];
1865
- $transactionKey = $postData['CreditCardTransaction']['TransactionKey'];
1866
- $capturedAmountInCents = $postData['CreditCardTransaction']['CapturedAmountInCents'];
1867
- $ccTransactionEnum = new Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum();
1868
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1869
-
1870
- switch ($status) {
1871
- case $ccTransactionEnum::AUTHORIZED_PENDING_CAPTURE:
1872
- break;
1873
-
1874
- case $ccTransactionEnum::CAPTURED:
1875
- break;
1876
-
1877
- case $ccTransactionEnum::PARTIAL_CAPTURE:
1878
- break;
1879
-
1880
- case $ccTransactionEnum::NOT_AUTHORIZED:
1881
- break;
1882
-
1883
- case $ccTransactionEnum::VOIDED:
1884
- break;
1885
-
1886
- case $ccTransactionEnum::PENDING_VOID:
1887
- break;
1888
-
1889
- case $ccTransactionEnum::PARTIAL_VOID:
1890
- break;
1891
-
1892
- case $ccTransactionEnum::REFUNDED:
1893
- break;
1894
-
1895
- case $ccTransactionEnum::PENDING_REFUND:
1896
- break;
1897
-
1898
- case $ccTransactionEnum::PARTIAL_REFUNDED:
1899
- break;
1900
-
1901
- case $ccTransactionEnum::WITH_ERROR:
1902
- break;
1903
-
1904
- case $ccTransactionEnum::NOT_FOUND_ACQUIRER:
1905
- break;
1906
-
1907
- case $ccTransactionEnum::PENDING_AUTHORIZE:
1908
- break;
1909
-
1910
- case $ccTransactionEnum::INVALID:
1911
- break;
1912
- }
1913
- }
1914
-
1915
- /**
1916
- * @author Ruan Azevedo
1917
- * @since 2016-07-20
1918
- * Status reference:
1919
- * http://docs.mundipagg.com/docs/enumera%C3%A7%C3%B5es
1920
- * @TODO refatorar o tratamento das transacoes de boleto com este metodo
1921
- */
1922
- private function processBoletoTransactionNotification() {
1923
- $status = '';
1924
- $boletoTransactionEnum = new Uecommerce_Mundipagg_Model_Enum_BoletoTransactionStatusEnum();
1925
-
1926
- switch ($status) {
1927
- case $boletoTransactionEnum::GENERATED:
1928
- break;
1929
-
1930
- case $boletoTransactionEnum::PAID:
1931
- break;
1932
-
1933
- case $boletoTransactionEnum::UNDERPAID:
1934
- break;
1935
-
1936
- case $boletoTransactionEnum::OVERPAID:
1937
- break;
1938
- }
1939
- }
1940
-
1941
- /**
1942
- * Mail error to Mage::getStoreConfig('trans_email/ident_custom1/email')
1943
- *
1944
- * @author Ruan Azevedo <razevedo@mundipagg.com>
1945
- * @since 31-05-2016
1946
- * @param string $message
1947
- */
1948
- public function mailError($message = '') {
1949
- $mail = new Zend_Mail();
1950
- $fromName = Mage::getStoreConfig('trans_email/ident_sales/name');
1951
- $fromEmail = Mage::getStoreConfig('trans_email/ident_sales/email');
1952
- $toEmail = Mage::getStoreConfig('trans_email/ident_custom1/email');
1953
- $toName = Mage::getStoreConfig('trans_email/ident_custom1/name');
1954
- $bcc = array('razevedo@mundipagg.com');
1955
- $subject = 'Error Report - MundiPagg Magento Integration';
1956
- $body = "Error Report from: {$_SERVER['HTTP_HOST']}<br><br>{$message}";
1957
-
1958
- $mail->setFrom($fromEmail, $fromName)
1959
- ->addTo($toEmail, $toName)
1960
- ->addBcc($bcc)
1961
- ->setSubject($subject)
1962
- ->setBodyHtml($body);
1963
-
1964
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1965
-
1966
- try {
1967
- $mail->send();
1968
- $helperLog->info("Error Report Sent: {$message}");
1969
-
1970
- } catch (Exception $e) {
1971
- $helperLog->error($e);
1972
- }
1973
-
1974
- }
1975
-
1976
- /**
1977
- * Get 'RequestData' node for the One v2 request if antifraud is enabled
1978
- *
1979
- * @author Ruan Azevedo <razvedo@mundipagg.com>
1980
- * @since 06-01-2016
1981
- * @throws Mage_Core_Exception
1982
- * @return array $requestData
1983
- */
1984
- private function getRequestDataNode() {
1985
- $antifraud = Mage::getStoreConfig('payment/mundipagg_standard/antifraud');
1986
- $antifraudProvider = Mage::getStoreConfig('payment/mundipagg_standard/antifraud_provider');
1987
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1988
- $helperHttpCore = new Mage_Core_Helper_Http();
1989
- $customerIp = $helperHttpCore->getRemoteAddr();
1990
- $outputMsg = "";
1991
- $sessionId = '';
1992
- $error = false;
1993
-
1994
- $requestData = array(
1995
- 'IpAddress' => $customerIp,
1996
- 'SessionId' => ''
1997
- );
1998
-
1999
- if ($antifraud == false) {
2000
- return false;
2001
- }
2002
-
2003
- if ($this->debugEnabled) {
2004
- $helperLog->debug("Antifraud enabled...");
2005
- }
2006
-
2007
- switch ($antifraudProvider) {
2008
- case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_NONE:
2009
- $outputMsg = "Antifraud enabled and none antifraud provider selected at module configuration.";
2010
- $error = true;
2011
- break;
2012
-
2013
- case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_CLEARSALE:
2014
- $outputMsg = "Antifraud provider: Clearsale";
2015
- $sessionId = Uecommerce_Mundipagg_Model_Customer_Session::getSessionId();
2016
- break;
2017
-
2018
- case Uecommerce_Mundipagg_Model_Source_Antifraud::ANTIFRAUD_FCONTROL:
2019
- $outputMsg = "Antifraud provider: FControl";
2020
- $sessionId = Uecommerce_Mundipagg_Model_Customer_Session::getSessionId();
2021
- break;
2022
- }
2023
-
2024
- if ($error) {
2025
- $helperLog->error($outputMsg, true);
2026
- // Mage::throwException($outputMsg);
2027
- }
2028
-
2029
- if (is_null($sessionId)) {
2030
- $sessionId = '';
2031
- }
2032
-
2033
- $requestData['SessionId'] = $sessionId;
2034
-
2035
- $helperLog->info($outputMsg);
2036
-
2037
- return $requestData;
2038
- }
2039
-
2040
- private function clearAntifraudDataFromSession() {
2041
- $customerSession = Mage::getSingleton('customer/session');
2042
- $customerSession->unsetData(Uecommerce_Mundipagg_Model_Customer_Session::SESSION_ID);
2043
- }
2044
-
2045
- /**
2046
- * Method to unify the transactions requests and his logs
2047
- *
2048
- * @author Ruan Azevedo <razvedo@mundipagg.com>
2049
- * @since 05-24-2016
2050
- * @param array $dataToPost
2051
- * @param string $url
2052
- * @param array $_logRequest
2053
- * @return array $_response
2054
- */
2055
- public function sendRequest($dataToPost, $url, $_logRequest = array()) {
2056
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
2057
-
2058
- if (empty($dataToPost) || empty($url)) {
2059
- $errMsg = __METHOD__ . "Exception: one or more arguments not informed to request";
2060
-
2061
- $helperLog->error($errMsg);
2062
- throw new InvalidArgumentException($errMsg);
2063
- }
2064
-
2065
- if (empty($_logRequest)) {
2066
- $_logRequest = $dataToPost;
2067
- }
2068
-
2069
- $requestRawJson = json_encode($dataToPost);
2070
- $requestJSON = $this->helperUtil->jsonEncodePretty($_logRequest);
2071
-
2072
- $helperLog->info("Request:\n{$requestJSON}\n");
2073
-
2074
- $ch = curl_init();
2075
-
2076
- // Header
2077
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'MerchantKey: ' . $this->modelStandard->getMerchantKey() . ''));
2078
- // Set the url, number of POST vars, POST data
2079
- curl_setopt($ch, CURLOPT_URL, $url);
2080
- curl_setopt($ch, CURLOPT_POSTFIELDS, $requestRawJson);
2081
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2082
-
2083
- // Execute post
2084
- $_response = curl_exec($ch);
2085
-
2086
- // Close connection
2087
- curl_close($ch);
2088
-
2089
- // Is there an error?
2090
- $xml = simplexml_load_string($_response);
2091
- $responseJSON = $this->helperUtil->jsonEncodePretty($xml);
2092
- $responseArray = json_decode($responseJSON, true);
2093
-
2094
- $helperLog->info("Response:\n{$responseJSON} \n");
2095
-
2096
- $responseData = array(
2097
- 'xmlData' => $xml,
2098
- 'arrayData' => $responseArray
2099
- );
2100
-
2101
- $this->clearAntifraudDataFromSession();
2102
-
2103
- return $responseData;
2104
- }
2105
-
2106
- /**
2107
- * Check if order is in offline retry time
2108
- *
2109
- * @author Ruan Azevedo <razevedo@mundipagg.com>
2110
- * @since 2016-06-20
2111
- * @param string $orderIncrementId
2112
- * @return boolean
2113
- */
2114
- public function orderIsInOfflineRetry($orderIncrementId) {
2115
- $model = Mage::getModel('mundipagg/offlineretry');
2116
- $offlineRetry = $model->loadByIncrementId($orderIncrementId);
2117
- $deadline = $offlineRetry->getDeadline();
2118
- $now = new DateTime();
2119
- $deadline = new DateTime($deadline);
2120
-
2121
- if ($now < $deadline) {
2122
- // in offline retry yet
2123
- return true;
2124
-
2125
- } else {
2126
- // offline retry time is over
2127
- return false;
2128
- }
2129
- }
2130
-
2131
- /**
2132
- * If the Offline Retry feature is enabled, save order offline retry statements
2133
- *
2134
- * @author Ruan Azevedo <razevedo@mundipagg.com>
2135
- * @since 2016-06-23
2136
- * @param string $orderIncrementId
2137
- * @param DateTime $createDate
2138
- */
2139
- private function saveOfflineRetryStatements($orderIncrementId, DateTime $createDate) {
2140
- // is offline retry is enabled, save statements
2141
- if (Uecommerce_Mundipagg_Model_Offlineretry::offlineRetryIsEnabled()) {
2142
- $offlineRetryTime = Mage::getStoreConfig('payment/mundipagg_standard/delayed_retry_max_time');
2143
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
2144
- $offlineRetryLogLabel = "Order #{$orderIncrementId} | offline retry statements";
2145
-
2146
- $model = new Uecommerce_Mundipagg_Model_Offlineretry();
2147
- $offlineRetry = $model->loadByIncrementId($orderIncrementId);
2148
-
2149
- try {
2150
- $offlineRetry->setOrderIncrementId($orderIncrementId);
2151
- $offlineRetry->setCreateDate($createDate->getTimestamp());
2152
-
2153
- $deadline = new DateTime();
2154
- $interval = new DateInterval('PT' . $offlineRetryTime . 'M');
2155
-
2156
- $deadline->setTimestamp($createDate->getTimestamp());
2157
- $deadline->add($interval);
2158
-
2159
- $offlineRetry->setDeadline($deadline->getTimestamp());
2160
- $offlineRetry->save();
2161
-
2162
- $helperLog->info("{$offlineRetryLogLabel} saved successfully.");
2163
-
2164
- } catch (Exception $e) {
2165
- $helperLog->error("{$offlineRetryLogLabel} cannot be saved: {$e}");
2166
- }
2167
-
2168
- }
2169
- }
2170
-
2171
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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$' . $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
+ }
app/code/community/Uecommerce/Mundipagg/Model/Observer.php CHANGED
@@ -1,418 +1,418 @@
1
- <?php
2
-
3
- /**
4
- * Uecommerce
5
- *
6
- * NOTICE OF LICENSE
7
- *
8
- * This source file is subject to the Uecommerce EULA.
9
- * It is also available through the world-wide-web at this URL:
10
- * http://www.uecommerce.com.br/
11
- *
12
- * DISCLAIMER
13
- *
14
- * Do not edit or add to this file if you wish to upgrade the extension
15
- * to newer versions in the future. If you wish to customize the extension
16
- * for your needs please refer to http://www.uecommerce.com.br/ for more information
17
- *
18
- * @category Uecommerce
19
- * @package Uecommerce_Mundipagg
20
- * @copyright Copyright (c) 2012 Uecommerce (http://www.uecommerce.com.br/)
21
- * @license http://www.uecommerce.com.br/
22
- */
23
-
24
- /**
25
- * Mundipagg Payment module
26
- *
27
- * @category Uecommerce
28
- * @package Uecommerce_Mundipagg
29
- * @author Uecommerce Dev Team
30
- */
31
- class Uecommerce_Mundipagg_Model_Observer extends Uecommerce_Mundipagg_Model_Standard {
32
- /*
33
- * Update status and notify customer or not
34
- */
35
- private function _updateStatus($order, $state, $status, $comment, $notified) {
36
-
37
- try {
38
- $order->setState($state, $status, $comment, $notified);
39
- $order->save();
40
-
41
- return $this;
42
-
43
- } catch (Exception $e) {
44
- //Api
45
- $api = Mage::getModel('mundipagg/api');
46
-
47
- //Log error
48
- Mage::logException($e);
49
-
50
- //Mail error
51
- $api->mailError(print_r($e->getMessage(), 1));
52
- }
53
- }
54
-
55
- public function canceledOrder($event) {
56
- $order = $event->getOrder();
57
- $state = $order->getState();
58
-
59
- if ($state == Mage_Sales_Model_Order::STATE_CANCELED) {
60
-
61
- // if a order is canceled successfuly, offline retry data must be deleted if exists
62
- if (Uecommerce_Mundipagg_Model_Offlineretry::offlineRetryIsEnabled()) {
63
- $model = Mage::getModel('mundipagg/offlineretry');
64
- $incrementId = $order->getIncrementId();
65
- $offlineRetry = $model->loadByIncrementId($incrementId);
66
- $offlineRetryData =$offlineRetry->getData();
67
-
68
- if (!empty($offlineRetryData)) {
69
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
70
- $helperLog->setLogLabel("Order #{$incrementId} canceled");
71
-
72
- try {
73
- $offlineRetry->delete();
74
- $helperLog->info("Offline retry data deleted successfully.");
75
-
76
- } catch (Exception $e) {
77
- $helperLog->info("Offline retry data cannot be deleted: {$e}");
78
- }
79
- }
80
- }
81
-
82
- //cancel Mundi transactions via API
83
- $this->cancelOrderViaApi($order);
84
- }
85
- }
86
-
87
- private function cancelOrderViaApi(Mage_Sales_Model_Order $order) {
88
- $payment = $order->getPayment();
89
- $paymentMethod = $payment->getAdditionalInformation('PaymentMethod');
90
- $allowedPaymentMethods = array(
91
- 'mundipagg_creditcardoneinstallment',
92
- 'mundipagg_creditcard',
93
- 'mundipagg_twocreditcards',
94
- 'mundipagg_threecreditcards',
95
- 'mundipagg_fourcreditcards',
96
- 'mundipagg_fivecreditcards'
97
- );
98
-
99
- if (!in_array($paymentMethod, $allowedPaymentMethods)) {
100
- return;
101
- }
102
-
103
- $logHelper = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
104
- $api = new Uecommerce_Mundipagg_Model_Api();
105
- $url = "{$this->getUrl()}/Cancel";
106
-
107
- $incrementId = $order->getIncrementId();
108
- $orderKeys = (array)$payment->getAdditionalInformation('OrderKey');
109
-
110
- foreach ($orderKeys as $orderKey) {
111
- $data = array('OrderKey' => $orderKey);
112
-
113
- $logHelper->info("Order #{$incrementId} | Order canceled. Cancel via MundiPagg Api...");
114
- $api->sendRequest($data, $url);
115
- }
116
-
117
- }
118
-
119
- /**
120
- * Update status
121
- * */
122
- public function updateStatus($event) {
123
- $standard = Mage::getModel('mundipagg/standard');
124
-
125
- $paymentAction = $standard->getConfigData('payment_action');
126
-
127
- $method = $event->getOrder()->getPayment()->getAdditionalInformation('PaymentMethod');
128
-
129
- // If it's a multi-payment types we force to ACTION_AUTHORIZE
130
- $num = substr($method, 0, 1);
131
-
132
- if ($num > 1) {
133
- $paymentAction = Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE;
134
- }
135
-
136
- $approvalRequestSuccess = Mage::getSingleton('checkout/session')->getApprovalRequestSuccess();
137
-
138
- if ($method == 'mundipagg_boleto' && $approvalRequestSuccess != 'cancel') {
139
- $comment = Mage::helper('mundipagg')->__('Waiting for Boleto Bancário payment');
140
-
141
- $this->_updateStatus($event->getOrder(), Mage_Sales_Model_Order::STATE_HOLDED, true, $comment, false);
142
- }
143
-
144
- if ($method != 'mundipagg_boleto' && $paymentAction == 'authorize' && $approvalRequestSuccess == 'partial') {
145
- $this->_updateStatus($event->getOrder(), Mage_Sales_Model_Order::STATE_NEW, 'pending', '', false);
146
- }
147
-
148
- if ($method != 'mundipagg_boleto' && $paymentAction == 'authorize' && $approvalRequestSuccess == 'success') {
149
- $comment = Mage::helper('mundipagg')->__('Authorized');
150
-
151
- $this->_updateStatus($event->getOrder(), Mage_Sales_Model_Order::STATE_NEW, 'pending', $comment, false);
152
- }
153
- }
154
-
155
- /**
156
- * If were are not in a Mundipagg controller methods listed above we unset parcial
157
- */
158
- public function sessionUpdate($observer) {
159
- $action = $observer['controller_action']->getFullActionName();
160
-
161
- if (
162
- $action != 'mundipagg_standard_redirect'
163
- && $action != 'mundipagg_standard_installments'
164
- && $action != 'mundipagg_standard_installmentsandinterest'
165
- && $action != 'mundipagg_standard_partial'
166
- && $action != 'mundipagg_standard_partialPost'
167
- && $action != 'mundipagg_standard_success'
168
- ) {
169
- Mage::getSingleton('checkout/session')->unsetData('approval_request_success');
170
- Mage::getSingleton('checkout/session')->unsetData('authorized_amount');
171
- }
172
- }
173
-
174
- /**
175
- * Remove all non MundiPagg payment methods and MundiPagg Boleto from partial payment page
176
- */
177
- public function removePaymentMethods($observer) {
178
- $event = $observer->getEvent();
179
- $method = $event->getMethodInstance();
180
- $result = $event->getResult();
181
- $isPartial = Mage::getSingleton('checkout/session')->getApprovalRequestSuccess();
182
-
183
- if ($isPartial == 'partial') {
184
- switch ($method->getCode()) {
185
- case 'mundipagg_creditcardoneinstallment':
186
- case 'mundipagg_creditcard':
187
- case 'mundipagg_twocreditcards':
188
- case 'mundipagg_threecreditcards':
189
- case 'mundipagg_fourcreditcards':
190
- case 'mundipagg_fivecreditcards':
191
- $active = Mage::getStoreConfig('payment/' . $method->getCode() . '/active');
192
-
193
- if ($active == '1') {
194
- $result->isAvailable = true;
195
- } else {
196
- $result->isAvailable = false;
197
- }
198
- break;
199
- case 'mundipagg_boleto':
200
- $result->isAvailable = false;
201
- break;
202
- default:
203
- $result->isAvailable = false;
204
- break;
205
- }
206
- }
207
- }
208
-
209
- public function removeInterest($observer) {
210
- $session = Mage::getSingleton('admin/session');
211
-
212
- if ($session->isLoggedIn()) {
213
- $quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
214
- } else {
215
- $quote = Mage::getSingleton('checkout/session')->getQuote();
216
- }
217
-
218
- $quote->setMundipaggInterest(0.0);
219
- $quote->setMundipaggBaseInterest(0.0);
220
- $quote->setTotalsCollectedFlag(false)->collectTotals();
221
- $quote->save();
222
- }
223
-
224
- /**
225
- * Check if recurrency product is in cart in order to show only Mundipagg Credit Card payment
226
- */
227
- public function checkForRecurrency($observer) {
228
- $recurrent = 0;
229
-
230
- $session = Mage::getSingleton('admin/session');
231
-
232
- if ($session->isLoggedIn()) {
233
- $quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
234
- } else {
235
- $quote = Mage::getSingleton('checkout/session')->getQuote();
236
- }
237
-
238
- $cartItems = $quote->getAllVisibleItems();
239
-
240
- foreach ($cartItems as $item) {
241
- $productId = $item->getProductId();
242
-
243
- $product = Mage::getModel('catalog/product')->load($productId);
244
-
245
- if ($product->getMundipaggRecurrent()) {
246
- $recurrent++;
247
- }
248
- }
249
-
250
- if ($recurrent > 0) {
251
- $instance = $observer->getMethodInstance();
252
- $result = $observer->getResult();
253
-
254
- switch ($instance->getCode()) {
255
- case 'mundipagg_boleto':
256
- case 'mundipagg_debit':
257
- case 'mundipagg_creditcardoneinstallment':
258
- case 'mundipagg_twocreditcards':
259
- case 'mundipagg_threecreditcards':
260
- case 'mundipagg_fourcreditcards':
261
- case 'mundipagg_fivecreditcards':
262
- $result->isAvailable = false;
263
- break;
264
- case 'mundipagg_creditcard':
265
- $result->isAvailable = true;
266
- break;
267
- default:
268
- $result->isAvailable = false;
269
- break;
270
- }
271
- }
272
- }
273
-
274
- /**
275
- * Add discount amount in the quote when partial payment
276
- *
277
- * @param type $observer
278
- */
279
- public function addDiscountWhenPartial($observer) {
280
- $session = Mage::getSingleton('checkout/session');
281
- if (!$session->getApprovalRequestSuccess() == 'partial') {
282
- $request = Mage::app()->getRequest();
283
- if (Mage::app()->getRequest()->getActionName() != 'partialPost' && $request->getModuleName() != 'mundipagg' && $request->getControllerName() != 'standard') {
284
- return $this;
285
- }
286
- }
287
- $quote = $observer->getEvent()->getQuote();
288
- $quoteid = $quote->getId();
289
-
290
- $reservedOrderId = $quote->getReservedOrderId();
291
-
292
- if (!$reservedOrderId) {
293
- return $this;
294
- }
295
-
296
- $order = Mage::getModel('sales/order')->loadByIncrementId($reservedOrderId);
297
-
298
- if (!$order->getId()) {
299
- return $this;
300
- }
301
-
302
- $payment = $order->getPayment();
303
-
304
- $interestInformation = $payment->getAdditionalInformation('mundipagg_interest_information');
305
- $discountAmount = 0;
306
-
307
- if (isset($interestInformation)) {
308
- foreach ($interestInformation as $ii) {
309
- $discountAmount += (float)$ii->getValue();
310
- }
311
- }
312
-
313
- if ($quoteid) {
314
- $total = $quote->getBaseSubtotal();
315
- $quote->setSubtotal(0);
316
- $quote->setBaseSubtotal(0);
317
-
318
- $quote->setSubtotalWithDiscount(0);
319
- $quote->setBaseSubtotalWithDiscount(0);
320
-
321
- $quote->setGrandTotal(0);
322
- $quote->setBaseGrandTotal(0);
323
-
324
-
325
- $canAddItems = $quote->isVirtual() ? ('billing') : ('shipping');
326
- foreach ($quote->getAllAddresses() as $address) {
327
-
328
- $discountAmount -= $address->getShippingAmount();
329
-
330
- $address->setSubtotal(0);
331
- $address->setBaseSubtotal(0);
332
-
333
- $address->setGrandTotal(0);
334
- $address->setBaseGrandTotal(0);
335
-
336
- $address->collectTotals();
337
-
338
- $quote->setSubtotal((float)$quote->getSubtotal() + $address->getSubtotal());
339
- $quote->setBaseSubtotal((float)$quote->getBaseSubtotal() + $address->getBaseSubtotal());
340
-
341
- $quote->setSubtotalWithDiscount(
342
- (float)$quote->getSubtotalWithDiscount() + $address->getSubtotalWithDiscount()
343
- );
344
- $quote->setBaseSubtotalWithDiscount(
345
- (float)$quote->getBaseSubtotalWithDiscount() + $address->getBaseSubtotalWithDiscount()
346
- );
347
-
348
- $quote->setGrandTotal((float)$quote->getGrandTotal() + $address->getGrandTotal());
349
- $quote->setBaseGrandTotal((float)$quote->getBaseGrandTotal() + $address->getBaseGrandTotal());
350
-
351
- $quote->save();
352
-
353
- $quote->setGrandTotal($quote->getBaseSubtotal() - $discountAmount)
354
- ->setBaseGrandTotal($quote->getBaseSubtotal() - $discountAmount)
355
- ->setSubtotalWithDiscount($quote->getBaseSubtotal() - $discountAmount)
356
- ->setBaseSubtotalWithDiscount($quote->getBaseSubtotal() - $discountAmount)
357
- ->save();
358
-
359
-
360
- if ($address->getAddressType() == $canAddItems) {
361
- //echo $address->setDiscountAmount; exit;
362
- $address->setSubtotalWithDiscount((float)$address->getSubtotalWithDiscount() - $discountAmount);
363
- $address->setGrandTotal((float)$address->getGrandTotal() - $discountAmount);
364
- $address->setBaseSubtotalWithDiscount((float)$address->getBaseSubtotalWithDiscount() - $discountAmount);
365
- $address->setBaseGrandTotal((float)$address->getBaseGrandTotal() - $discountAmount);
366
- if ($address->getDiscountDescription()) {
367
- $address->setDiscountAmount(-($address->getDiscountAmount() - $discountAmount));
368
- $address->setDiscountDescription($address->getDiscountDescription() . ', Discount to Partial Payment');
369
- $address->setBaseDiscountAmount(-($address->getBaseDiscountAmount() - $discountAmount));
370
- } else {
371
- $address->setDiscountAmount(-($discountAmount));
372
- $address->setDiscountDescription('Discount to Partial Payment');
373
- $address->setBaseDiscountAmount(-($discountAmount));
374
- }
375
- $address->save();
376
- }
377
- }
378
- //echo $quote->getGrandTotal();
379
-
380
- foreach ($quote->getAllItems() as $item) {
381
- //We apply discount amount based on the ratio between the GrandTotal and the RowTotal
382
- $rat = $item->getPriceInclTax() / $total;
383
- $ratdisc = $discountAmount * $rat;
384
- $item->setDiscountAmount(($item->getDiscountAmount() + $ratdisc) * $item->getQty());
385
- $item->setBaseDiscountAmount(($item->getBaseDiscountAmount() + $ratdisc) * $item->getQty())->save();
386
- }
387
- }
388
- }
389
-
390
- public function catalogProductSaveBefore($event) {
391
- $product = $event->getProduct();
392
- $recurrentOption = (boolean)$product->getMundipaggRecurrent();
393
-
394
- if ($recurrentOption) {
395
- $isRequired = true;
396
- } else {
397
- $isRequired = false;
398
- }
399
-
400
- try {
401
- $attribute = new Mage_Eav_Model_Entity_Attribute();
402
- $attribute->loadByCode(Mage_Catalog_Model_Product::ENTITY, 'mundipagg_recurrences');
403
- $attribute->setIsRequired($isRequired);
404
- $attribute->save();
405
-
406
- } catch (Mage_Adminhtml_Exception $e) {
407
- $log = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
408
- $helper = Mage::helper('mundipagg');
409
-
410
- $errMsg = "{$helper->__("Internal error")}: {$e->getMessage()}";
411
- $log->error($helper->__("Unable to save product configuration: {$e}"));
412
-
413
- throw new Mage_Adminhtml_Exception($errMsg);
414
- }
415
-
416
- }
417
-
418
- }
1
+ <?php
2
+
3
+ /**
4
+ * Uecommerce
5
+ *
6
+ * NOTICE OF LICENSE
7
+ *
8
+ * This source file is subject to the Uecommerce EULA.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://www.uecommerce.com.br/
11
+ *
12
+ * DISCLAIMER
13
+ *
14
+ * Do not edit or add to this file if you wish to upgrade the extension
15
+ * to newer versions in the future. If you wish to customize the extension
16
+ * for your needs please refer to http://www.uecommerce.com.br/ for more information
17
+ *
18
+ * @category Uecommerce
19
+ * @package Uecommerce_Mundipagg
20
+ * @copyright Copyright (c) 2012 Uecommerce (http://www.uecommerce.com.br/)
21
+ * @license http://www.uecommerce.com.br/
22
+ */
23
+
24
+ /**
25
+ * Mundipagg Payment module
26
+ *
27
+ * @category Uecommerce
28
+ * @package Uecommerce_Mundipagg
29
+ * @author Uecommerce Dev Team
30
+ */
31
+ class Uecommerce_Mundipagg_Model_Observer extends Uecommerce_Mundipagg_Model_Standard {
32
+ /*
33
+ * Update status and notify customer or not
34
+ */
35
+ private function _updateStatus($order, $state, $status, $comment, $notified) {
36
+
37
+ try {
38
+ $order->setState($state, $status, $comment, $notified);
39
+ $order->save();
40
+
41
+ return $this;
42
+
43
+ } catch (Exception $e) {
44
+ //Api
45
+ $api = Mage::getModel('mundipagg/api');
46
+
47
+ //Log error
48
+ Mage::logException($e);
49
+
50
+ //Mail error
51
+ $api->mailError(print_r($e->getMessage(), 1));
52
+ }
53
+ }
54
+
55
+ public function canceledOrder($event) {
56
+ $order = $event->getOrder();
57
+ $state = $order->getState();
58
+
59
+ if ($state == Mage_Sales_Model_Order::STATE_CANCELED) {
60
+
61
+ // if a order is canceled successfuly, offline retry data must be deleted if exists
62
+ if (Uecommerce_Mundipagg_Model_Offlineretry::offlineRetryIsEnabled()) {
63
+ $model = Mage::getModel('mundipagg/offlineretry');
64
+ $incrementId = $order->getIncrementId();
65
+ $offlineRetry = $model->loadByIncrementId($incrementId);
66
+ $offlineRetryData =$offlineRetry->getData();
67
+
68
+ if (!empty($offlineRetryData)) {
69
+ $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
70
+ $helperLog->setLogLabel("Order #{$incrementId} canceled");
71
+
72
+ try {
73
+ $offlineRetry->delete();
74
+ $helperLog->info("Offline retry data deleted successfully.");
75
+
76
+ } catch (Exception $e) {
77
+ $helperLog->info("Offline retry data cannot be deleted: {$e}");
78
+ }
79
+ }
80
+ }
81
+
82
+ //cancel Mundi transactions via API
83
+ $this->cancelOrderViaApi($order);
84
+ }
85
+ }
86
+
87
+ private function cancelOrderViaApi(Mage_Sales_Model_Order $order) {
88
+ $payment = $order->getPayment();
89
+ $paymentMethod = $payment->getAdditionalInformation('PaymentMethod');
90
+ $allowedPaymentMethods = array(
91
+ 'mundipagg_creditcardoneinstallment',
92
+ 'mundipagg_creditcard',
93
+ 'mundipagg_twocreditcards',
94
+ 'mundipagg_threecreditcards',
95
+ 'mundipagg_fourcreditcards',
96
+ 'mundipagg_fivecreditcards'
97
+ );
98
+
99
+ if (!in_array($paymentMethod, $allowedPaymentMethods)) {
100
+ return;
101
+ }
102
+
103
+ $logHelper = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
104
+ $api = new Uecommerce_Mundipagg_Model_Api();
105
+ $url = "{$this->getUrl()}/Cancel";
106
+
107
+ $incrementId = $order->getIncrementId();
108
+ $orderKeys = (array)$payment->getAdditionalInformation('OrderKey');
109
+
110
+ foreach ($orderKeys as $orderKey) {
111
+ $data = array('OrderKey' => $orderKey);
112
+
113
+ $logHelper->info("Order #{$incrementId} | Order canceled. Cancel via MundiPagg Api...");
114
+ $api->sendRequest($data, $url);
115
+ }
116
+
117
+ }
118
+
119
+ /**
120
+ * Update status
121
+ * */
122
+ public function updateStatus($event) {
123
+ $standard = Mage::getModel('mundipagg/standard');
124
+
125
+ $paymentAction = $standard->getConfigData('payment_action');
126
+
127
+ $method = $event->getOrder()->getPayment()->getAdditionalInformation('PaymentMethod');
128
+
129
+ // If it's a multi-payment types we force to ACTION_AUTHORIZE
130
+ $num = substr($method, 0, 1);
131
+
132
+ if ($num > 1) {
133
+ $paymentAction = Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE;
134
+ }
135
+
136
+ $approvalRequestSuccess = Mage::getSingleton('checkout/session')->getApprovalRequestSuccess();
137
+
138
+ if ($method == 'mundipagg_boleto' && $approvalRequestSuccess != 'cancel') {
139
+ $comment = Mage::helper('mundipagg')->__('Waiting for Boleto Bancário payment');
140
+
141
+ $this->_updateStatus($event->getOrder(), Mage_Sales_Model_Order::STATE_HOLDED, true, $comment, false);
142
+ }
143
+
144
+ if ($method != 'mundipagg_boleto' && $paymentAction == 'authorize' && $approvalRequestSuccess == 'partial') {
145
+ $this->_updateStatus($event->getOrder(), Mage_Sales_Model_Order::STATE_NEW, 'pending', '', false);
146
+ }
147
+
148
+ if ($method != 'mundipagg_boleto' && $paymentAction == 'authorize' && $approvalRequestSuccess == 'success') {
149
+ $comment = Mage::helper('mundipagg')->__('Authorized');
150
+
151
+ $this->_updateStatus($event->getOrder(), Mage_Sales_Model_Order::STATE_NEW, 'pending', $comment, false);
152
+ }
153
+ }
154
+
155
+ /**
156
+ * If were are not in a Mundipagg controller methods listed above we unset parcial
157
+ */
158
+ public function sessionUpdate($observer) {
159
+ $action = $observer['controller_action']->getFullActionName();
160
+
161
+ if (
162
+ $action != 'mundipagg_standard_redirect'
163
+ && $action != 'mundipagg_standard_installments'
164
+ && $action != 'mundipagg_standard_installmentsandinterest'
165
+ && $action != 'mundipagg_standard_partial'
166
+ && $action != 'mundipagg_standard_partialPost'
167
+ && $action != 'mundipagg_standard_success'
168
+ ) {
169
+ Mage::getSingleton('checkout/session')->unsetData('approval_request_success');
170
+ Mage::getSingleton('checkout/session')->unsetData('authorized_amount');
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Remove all non MundiPagg payment methods and MundiPagg Boleto from partial payment page
176
+ */
177
+ public function removePaymentMethods($observer) {
178
+ $event = $observer->getEvent();
179
+ $method = $event->getMethodInstance();
180
+ $result = $event->getResult();
181
+ $isPartial = Mage::getSingleton('checkout/session')->getApprovalRequestSuccess();
182
+
183
+ if ($isPartial == 'partial') {
184
+ switch ($method->getCode()) {
185
+ case 'mundipagg_creditcardoneinstallment':
186
+ case 'mundipagg_creditcard':
187
+ case 'mundipagg_twocreditcards':
188
+ case 'mundipagg_threecreditcards':
189
+ case 'mundipagg_fourcreditcards':
190
+ case 'mundipagg_fivecreditcards':
191
+ $active = Mage::getStoreConfig('payment/' . $method->getCode() . '/active');
192
+
193
+ if ($active == '1') {
194
+ $result->isAvailable = true;
195
+ } else {
196
+ $result->isAvailable = false;
197
+ }
198
+ break;
199
+ case 'mundipagg_boleto':
200
+ $result->isAvailable = false;
201
+ break;
202
+ default:
203
+ $result->isAvailable = false;
204
+ break;
205
+ }
206
+ }
207
+ }
208
+
209
+ public function removeInterest($observer) {
210
+ $session = Mage::getSingleton('admin/session');
211
+
212
+ if ($session->isLoggedIn()) {
213
+ $quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
214
+ } else {
215
+ $quote = Mage::getSingleton('checkout/session')->getQuote();
216
+ }
217
+
218
+ $quote->setMundipaggInterest(0.0);
219
+ $quote->setMundipaggBaseInterest(0.0);
220
+ $quote->setTotalsCollectedFlag(false)->collectTotals();
221
+ $quote->save();
222
+ }
223
+
224
+ /**
225
+ * Check if recurrency product is in cart in order to show only Mundipagg Credit Card payment
226
+ */
227
+ public function checkForRecurrency($observer) {
228
+ $recurrent = 0;
229
+
230
+ $session = Mage::getSingleton('admin/session');
231
+
232
+ if ($session->isLoggedIn()) {
233
+ $quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
234
+ } else {
235
+ $quote = Mage::getSingleton('checkout/session')->getQuote();
236
+ }
237
+
238
+ $cartItems = $quote->getAllVisibleItems();
239
+
240
+ foreach ($cartItems as $item) {
241
+ $productId = $item->getProductId();
242
+
243
+ $product = Mage::getModel('catalog/product')->load($productId);
244
+
245
+ if ($product->getMundipaggRecurrent()) {
246
+ $recurrent++;
247
+ }
248
+ }
249
+
250
+ if ($recurrent > 0) {
251
+ $instance = $observer->getMethodInstance();
252
+ $result = $observer->getResult();
253
+
254
+ switch ($instance->getCode()) {
255
+ case 'mundipagg_boleto':
256
+ case 'mundipagg_debit':
257
+ case 'mundipagg_creditcardoneinstallment':
258
+ case 'mundipagg_twocreditcards':
259
+ case 'mundipagg_threecreditcards':
260
+ case 'mundipagg_fourcreditcards':
261
+ case 'mundipagg_fivecreditcards':
262
+ $result->isAvailable = false;
263
+ break;
264
+ case 'mundipagg_creditcard':
265
+ $result->isAvailable = true;
266
+ break;
267
+ default:
268
+ $result->isAvailable = false;
269
+ break;
270
+ }
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Add discount amount in the quote when partial payment
276
+ *
277
+ * @param type $observer
278
+ */
279
+ public function addDiscountWhenPartial($observer) {
280
+ $session = Mage::getSingleton('checkout/session');
281
+ if (!$session->getApprovalRequestSuccess() == 'partial') {
282
+ $request = Mage::app()->getRequest();
283
+ if (Mage::app()->getRequest()->getActionName() != 'partialPost' && $request->getModuleName() != 'mundipagg' && $request->getControllerName() != 'standard') {
284
+ return $this;
285
+ }
286
+ }
287
+ $quote = $observer->getEvent()->getQuote();
288
+ $quoteid = $quote->getId();
289
+
290
+ $reservedOrderId = $quote->getReservedOrderId();
291
+
292
+ if (!$reservedOrderId) {
293
+ return $this;
294
+ }
295
+
296
+ $order = Mage::getModel('sales/order')->loadByIncrementId($reservedOrderId);
297
+
298
+ if (!$order->getId()) {
299
+ return $this;
300
+ }
301
+
302
+ $payment = $order->getPayment();
303
+
304
+ $interestInformation = $payment->getAdditionalInformation('mundipagg_interest_information');
305
+ $discountAmount = 0;
306
+
307
+ if (isset($interestInformation)) {
308
+ foreach ($interestInformation as $ii) {
309
+ $discountAmount += (float)$ii->getValue();
310
+ }
311
+ }
312
+
313
+ if ($quoteid) {
314
+ $total = $quote->getBaseSubtotal();
315
+ $quote->setSubtotal(0);
316
+ $quote->setBaseSubtotal(0);
317
+
318
+ $quote->setSubtotalWithDiscount(0);
319
+ $quote->setBaseSubtotalWithDiscount(0);
320
+
321
+ $quote->setGrandTotal(0);
322
+ $quote->setBaseGrandTotal(0);
323
+
324
+
325
+ $canAddItems = $quote->isVirtual() ? ('billing') : ('shipping');
326
+ foreach ($quote->getAllAddresses() as $address) {
327
+
328
+ $discountAmount -= $address->getShippingAmount();
329
+
330
+ $address->setSubtotal(0);
331
+ $address->setBaseSubtotal(0);
332
+
333
+ $address->setGrandTotal(0);
334
+ $address->setBaseGrandTotal(0);
335
+
336
+ $address->collectTotals();
337
+
338
+ $quote->setSubtotal((float)$quote->getSubtotal() + $address->getSubtotal());
339
+ $quote->setBaseSubtotal((float)$quote->getBaseSubtotal() + $address->getBaseSubtotal());
340
+
341
+ $quote->setSubtotalWithDiscount(
342
+ (float)$quote->getSubtotalWithDiscount() + $address->getSubtotalWithDiscount()
343
+ );
344
+ $quote->setBaseSubtotalWithDiscount(
345
+ (float)$quote->getBaseSubtotalWithDiscount() + $address->getBaseSubtotalWithDiscount()
346
+ );
347
+
348
+ $quote->setGrandTotal((float)$quote->getGrandTotal() + $address->getGrandTotal());
349
+ $quote->setBaseGrandTotal((float)$quote->getBaseGrandTotal() + $address->getBaseGrandTotal());
350
+
351
+ $quote->save();
352
+
353
+ $quote->setGrandTotal($quote->getBaseSubtotal() - $discountAmount)
354
+ ->setBaseGrandTotal($quote->getBaseSubtotal() - $discountAmount)
355
+ ->setSubtotalWithDiscount($quote->getBaseSubtotal() - $discountAmount)
356
+ ->setBaseSubtotalWithDiscount($quote->getBaseSubtotal() - $discountAmount)
357
+ ->save();
358
+
359
+
360
+ if ($address->getAddressType() == $canAddItems) {
361
+ //echo $address->setDiscountAmount; exit;
362
+ $address->setSubtotalWithDiscount((float)$address->getSubtotalWithDiscount() - $discountAmount);
363
+ $address->setGrandTotal((float)$address->getGrandTotal() - $discountAmount);
364
+ $address->setBaseSubtotalWithDiscount((float)$address->getBaseSubtotalWithDiscount() - $discountAmount);
365
+ $address->setBaseGrandTotal((float)$address->getBaseGrandTotal() - $discountAmount);
366
+ if ($address->getDiscountDescription()) {
367
+ $address->setDiscountAmount(-($address->getDiscountAmount() - $discountAmount));
368
+ $address->setDiscountDescription($address->getDiscountDescription() . ', Discount to Partial Payment');
369
+ $address->setBaseDiscountAmount(-($address->getBaseDiscountAmount() - $discountAmount));
370
+ } else {
371
+ $address->setDiscountAmount(-($discountAmount));
372
+ $address->setDiscountDescription('Discount to Partial Payment');
373
+ $address->setBaseDiscountAmount(-($discountAmount));
374
+ }
375
+ $address->save();
376
+ }
377
+ }
378
+ //echo $quote->getGrandTotal();
379
+
380
+ foreach ($quote->getAllItems() as $item) {
381
+ //We apply discount amount based on the ratio between the GrandTotal and the RowTotal
382
+ $rat = $item->getPriceInclTax() / $total;
383
+ $ratdisc = $discountAmount * $rat;
384
+ $item->setDiscountAmount(($item->getDiscountAmount() + $ratdisc) * $item->getQty());
385
+ $item->setBaseDiscountAmount(($item->getBaseDiscountAmount() + $ratdisc) * $item->getQty())->save();
386
+ }
387
+ }
388
+ }
389
+
390
+ public function catalogProductSaveBefore($event) {
391
+ $product = $event->getProduct();
392
+ $recurrentOption = (boolean)$product->getMundipaggRecurrent();
393
+
394
+ if ($recurrentOption) {
395
+ $isRequired = true;
396
+ } else {
397
+ $isRequired = false;
398
+ }
399
+
400
+ try {
401
+ $attribute = new Mage_Eav_Model_Entity_Attribute();
402
+ $attribute->loadByCode(Mage_Catalog_Model_Product::ENTITY, 'mundipagg_recurrences');
403
+ $attribute->setIsRequired($isRequired);
404
+ $attribute->save();
405
+
406
+ } catch (Mage_Adminhtml_Exception $e) {
407
+ $log = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
408
+ $helper = Mage::helper('mundipagg');
409
+
410
+ $errMsg = "{$helper->__("Internal error")}: {$e->getMessage()}";
411
+ $log->error($helper->__("Unable to save product configuration: {$e}"));
412
+
413
+ throw new Mage_Adminhtml_Exception($errMsg);
414
+ }
415
+
416
+ }
417
+
418
+ }
app/code/community/Uecommerce/Mundipagg/Model/Resource/Offlineretry.php CHANGED
@@ -1,7 +1,8 @@
1
- <?php
2
-
3
- class Uecommerce_Mundipagg_Model_Resource_Offlineretry extends Mage_Core_Model_Mysql4_Abstract {
4
- public function _construct() {
5
- $this->_init('mundipagg/mundipagg_offline_retry', 'id');
6
- }
 
7
  }
1
+ <?php
2
+
3
+ class Uecommerce_Mundipagg_Model_Resource_Offlineretry extends Mage_Core_Model_Mysql4_Abstract {
4
+
5
+ public function _construct() {
6
+ $this->_init('mundipagg/mundipagg_offline_retry', 'id');
7
+ }
8
  }
app/code/community/Uecommerce/Mundipagg/Model/Resource/Offlineretry/Collection.php CHANGED
@@ -1,20 +1,9 @@
1
- <?php
2
-
3
- class Uecommerce_Mundipagg_Model_Resource_Offlineretry_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract {
4
-
5
- protected function _construct() {
6
- $this->_init('mundipagg/offlineretry');
7
- }
8
-
9
- // public function addEntityIdFilter($entityId) {
10
- // $this->addFieldToFilter('entity_id', $entityId);
11
- //
12
- // return $this;
13
- // }
14
- //
15
- // public function addExpiresAtFilter() {
16
- // $this->addFieldToFilter('expires_at', array('gteq' => date('Y-m-t')));
17
- //
18
- // return $this;
19
- // }
20
  }
1
+ <?php
2
+
3
+ class Uecommerce_Mundipagg_Model_Resource_Offlineretry_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract {
4
+
5
+ protected function _construct() {
6
+ $this->_init('mundipagg/offlineretry');
7
+ }
8
+
 
 
 
 
 
 
 
 
 
 
 
9
  }
app/code/community/Uecommerce/Mundipagg/Model/Standard.php CHANGED
@@ -1,1985 +1,1985 @@
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_Standard extends Mage_Payment_Model_Method_Abstract {
31
- /**
32
- * Availability options
33
- */
34
- protected $_code = 'mundipagg_standard';
35
- protected $_formBlockType = 'mundipagg/standard_form';
36
- protected $_infoBlockType = 'mundipagg/info';
37
- protected $_isGateway = true;
38
- protected $_canOrder = true;
39
- protected $_canAuthorize = true;
40
- protected $_canCapture = true;
41
- protected $_canCapturePartial = false;
42
- protected $_canRefund = true;
43
- protected $_canVoid = true;
44
- protected $_canUseInternal = false;
45
- protected $_canUseCheckout = false;
46
- protected $_canUseForMultishipping = true;
47
- protected $_canSaveCc = false;
48
- protected $_canFetchTransactionInfo = false;
49
- protected $_canManageRecurringProfiles = false;
50
- protected $_allowCurrencyCode = array('BRL', 'USD', 'EUR');
51
- protected $_isInitializeNeeded = true;
52
-
53
- /**
54
- * Transaction ID
55
- **/
56
- protected $_transactionId = null;
57
-
58
- /**
59
- * CreditCardOperationEnum na gateway
60
- * @var $CreditCardOperationEnum varchar
61
- */
62
- private $_creditCardOperationEnum;
63
-
64
- public function getUrl() {
65
- return $this->url;
66
- }
67
-
68
- public function setUrl($url) {
69
- $this->url = $url;
70
- }
71
-
72
- public function setmerchantKey($merchantKey) {
73
- $this->merchantKey = $merchantKey;
74
- }
75
-
76
- public function getmerchantKey() {
77
- return $this->merchantKey;
78
- }
79
-
80
- public function setEnvironment($environment) {
81
- $this->environment = $environment;
82
- }
83
-
84
- public function getEnvironment() {
85
- return $this->environment;
86
- }
87
-
88
- public function setPaymentMethodCode($paymentMethodCode) {
89
- $this->paymentMethodCode = $paymentMethodCode;
90
- }
91
-
92
- public function getPaymentMethodCode() {
93
- return $this->paymentMethodCode;
94
- }
95
-
96
- public function setAntiFraud($antiFraud) {
97
- $this->antiFraud = $antiFraud;
98
- }
99
-
100
- public function getAntiFraud() {
101
- return $this->antiFraud;
102
- }
103
-
104
- public function setBankNumber($bankNumber) {
105
- $this->bankNumber = $bankNumber;
106
- }
107
-
108
- public function getBankNumber() {
109
- return $this->bankNumber;
110
- }
111
-
112
- public function setDebug($debug) {
113
- $this->_debug = $debug;
114
- }
115
-
116
- public function getDebug() {
117
- return $this->_debug;
118
- }
119
-
120
- public function setDiasValidadeBoleto($diasValidadeBoleto) {
121
- $this->_diasValidadeBoleto = $diasValidadeBoleto;
122
- }
123
-
124
- public function getDiasValidadeBoleto() {
125
- return $this->_diasValidadeBoleto;
126
- }
127
-
128
- public function setInstrucoesCaixa($instrucoesCaixa) {
129
- $this->_instrucoesCaixa = $instrucoesCaixa;
130
- }
131
-
132
- public function getInstrucoesCaixa() {
133
- return $this->_instrucoesCaixa;
134
- }
135
-
136
- public function setCreditCardOperationEnum($creditCardOperationEnum) {
137
- $this->_creditCardOperationEnum = $creditCardOperationEnum;
138
- }
139
-
140
- public function getCreditCardOperationEnum() {
141
- return $this->_creditCardOperationEnum;
142
- }
143
-
144
- public function setParcelamento($parcelamento) {
145
- $this->parcelamento = $parcelamento;
146
- }
147
-
148
- public function getParcelamento() {
149
- return $this->parcelamento;
150
- }
151
-
152
- public function setParcelamentoMax($parcelamentoMax) {
153
- $this->parcelamentoMax = $parcelamentoMax;
154
- }
155
-
156
- public function getParcelamentoMax() {
157
- return $this->parcelamentoMax;
158
- }
159
-
160
- public function setPaymentAction($paymentAction) {
161
- $this->paymentAction = $paymentAction;
162
- }
163
-
164
- public function getPaymentAction() {
165
- return $this->paymentAction;
166
- }
167
-
168
- public function setCieloSku($cieloSku) {
169
- $this->cieloSku = $cieloSku;
170
- }
171
-
172
- public function getCieloSku() {
173
- return $this->cieloSku;
174
- }
175
-
176
- public function __construct() {
177
- $this->setEnvironment($this->getConfigData('environment'));
178
- $this->setPaymentAction($this->getConfigData('payment_action'));
179
-
180
- switch ($this->getConfigData('environment')) {
181
- case 'localhost':
182
- case 'development':
183
- case 'staging':
184
- default:
185
- $this->setmerchantKey(trim($this->getConfigData('merchantKeyStaging')));
186
- $this->setUrl(trim($this->getConfigData('apiUrlStaging')));
187
- $this->setAntiFraud($this->getConfigData('antifraud'));
188
- $this->setPaymentMethodCode(1);
189
- $this->setBankNumber(341);
190
- $this->setParcelamento($this->getConfigData('parcelamento'));
191
- $this->setParcelamentoMax($this->getConfigData('parcelamento_max'));
192
- $this->setDebug($this->getConfigData('debug'));
193
- $this->setEnvironment($this->getConfigData('environment'));
194
- $this->setCieloSku($this->getConfigData('cielo_sku'));
195
- break;
196
-
197
- case 'production':
198
- $this->setmerchantKey(trim($this->getConfigData('merchantKeyProduction')));
199
- $this->setUrl(trim($this->getConfigData('apiUrlProduction')));
200
- $this->setAntiFraud($this->getConfigData('antifraud'));
201
- $this->setParcelamento($this->getConfigData('parcelamento'));
202
- $this->setParcelamentoMax($this->getConfigData('parcelamento_max'));
203
- $this->setDebug($this->getConfigData('debug'));
204
- $this->setEnvironment($this->getConfigData('environment'));
205
- $this->setCieloSku($this->getConfigData('cielo_sku'));
206
- break;
207
- }
208
- }
209
-
210
- /**
211
- * Armazena as informações passadas via formulário no frontend
212
- * @access public
213
- * @param array $data
214
- * @return Uecommerce_Mundipagg_Model_Standard
215
- */
216
- public function assignData($data) {
217
- if (!($data instanceof Varien_Object)) {
218
- $data = new Varien_Object($data);
219
- }
220
-
221
- $info = $this->getInfoInstance();
222
- $mundipagg = array();
223
- $helper = Mage::helper('mundipagg');
224
-
225
- foreach ($data->getData() as $id => $value) {
226
- $mundipagg[$id] = $value;
227
-
228
- // We verify if a CPF OR CNPJ is valid
229
- $posTaxvat = strpos($id, 'taxvat');
230
-
231
- if ($posTaxvat !== false && $value != '') {
232
- if (!$helper->validateCPF($value) && !$helper->validateCNPJ($value)) {
233
- $error = $helper->__('CPF or CNPJ is invalid');
234
-
235
- Mage::throwException($error);
236
- }
237
- }
238
- }
239
-
240
- if (!empty($mundipagg)) {
241
- $helperInstallments = Mage::helper('mundipagg/Installments');
242
-
243
- //Set Mundipagg Data in Session
244
- $session = Mage::getSingleton('checkout/session');
245
- $session->setMundipaggData($mundipagg);
246
-
247
- $info = $this->getInfoInstance();
248
-
249
- if (isset($mundipagg['mundipagg_type'])) {
250
- $info->setAdditionalInformation('PaymentMethod', $mundipagg['method']);
251
-
252
- switch ($mundipagg['method']) {
253
- case 'mundipagg_creditcard':
254
- if (isset($mundipagg['mundipagg_creditcard_1_1_cc_type'])) {
255
- if (array_key_exists('mundipagg_creditcard_credito_parcelamento_1_1', $mundipagg)) {
256
- if ($mundipagg['mundipagg_creditcard_credito_parcelamento_1_1'] > $helperInstallments->getMaxInstallments($mundipagg['mundipagg_creditcard_1_1_cc_type'])) {
257
- Mage::throwException($helper->__('it is not possible to divide by %s times', $mundipagg['mundipagg_creditcard_credito_parcelamento_1_1']));
258
- }
259
- }
260
- $info->setCcType($mundipagg['mundipagg_creditcard_1_1_cc_type'])
261
- ->setCcOwner($mundipagg['mundipagg_creditcard_cc_holder_name_1_1'])
262
- ->setCcLast4(substr($mundipagg['mundipagg_creditcard_1_1_cc_number'], -4))
263
- ->setCcNumber($mundipagg['mundipagg_creditcard_1_1_cc_number'])
264
- ->setCcCid($mundipagg['mundipagg_creditcard_cc_cid_1_1'])
265
- ->setCcExpMonth($mundipagg['mundipagg_creditcard_expirationMonth_1_1'])
266
- ->setCcExpYear($mundipagg['mundipagg_creditcard_expirationYear_1_1']);
267
- } else {
268
- $info->setAdditionalInformation('mundipagg_creditcard_token_1_1', $mundipagg['mundipagg_creditcard_token_1_1']);
269
- }
270
-
271
- break;
272
-
273
- default:
274
-
275
- $info->setCcType(null)
276
- ->setCcOwner(null)
277
- ->setCcLast4(null)
278
- ->setCcNumber(null)
279
- ->setCcCid(null)
280
- ->setCcExpMonth(null)
281
- ->setCcExpYear(null);
282
-
283
- break;
284
- }
285
-
286
- foreach ($mundipagg as $key => $value) {
287
- // We don't save CcNumber
288
- $posCcNumber = strpos($key, 'number');
289
-
290
- // We don't save Security Code
291
- $posCid = strpos($key, 'cid');
292
-
293
- // We don't save Cc Holder name
294
- $posHolderName = strpos($key, 'holder_name');
295
-
296
- if ($value != '' &&
297
- $posCcNumber === false &&
298
- $posCid === false &&
299
- $posHolderName === false
300
- ) {
301
- if (strpos($key, 'cc_type')) {
302
- $value = $helper->issuer($value);
303
- }
304
-
305
- $info->setAdditionalInformation($key, $value);
306
- }
307
- }
308
-
309
- // We check if quote grand total is equal to installments sum
310
- if ($mundipagg['method'] != 'mundipagg_boleto'
311
- && $mundipagg['method'] != 'mundipagg_creditcardoneinstallment'
312
- && $mundipagg['method'] != 'mundipagg_creditcard'
313
- ) {
314
- $num = $helper->getCreditCardsNumber($mundipagg['method']);
315
- $method = $helper->getPaymentMethod($num);
316
-
317
- (float)$grandTotal = $info->getQuote()->getGrandTotal();
318
- (float)$totalInstallmentsToken = 0;
319
- (float)$totalInstallmentsNew = 0;
320
- (float)$totalInstallments = 0;
321
-
322
- for ($i = 1; $i <= $num; $i++) {
323
-
324
- if (isset($mundipagg[$method . '_token_' . $num . '_' . $i]) && $mundipagg[$method . '_token_' . $num . '_' . $i] != 'new') {
325
- (float)$value = str_replace(',', '.', $mundipagg[$method . '_value_' . $num . '_' . $i]);
326
-
327
- if (array_key_exists($method . '_credito_parcelamento_' . $num . '_' . $i, $mundipagg)) {
328
- if (!array_key_exists($method . '_' . $num . '_' . $i . '_cc_type', $mundipagg)) {
329
- $cardonFile = Mage::getModel('mundipagg/cardonfile')->load($mundipagg[$method . '_token_' . $num . '_' . $i]);
330
-
331
- $mundipagg[$method . '_' . $num . '_' . $i . '_cc_type'] = Mage::helper('mundipagg')->getCardTypeByIssuer($cardonFile->getCcType());
332
- }
333
-
334
- if ($mundipagg[$method . '_credito_parcelamento_' . $num . '_' . $i] > $helperInstallments->getMaxInstallments($mundipagg[$method . '_' . $num . '_' . $i . '_cc_type'], $value)) {
335
- Mage::throwException($helper->__('it is not possible to divide by %s times', $mundipagg[$method . '_credito_parcelamento_' . $num . '_' . $i]));
336
- }
337
- }
338
-
339
- (float)$totalInstallmentsToken += $value;
340
- } else {
341
- (float)$value = str_replace(',', '.', $mundipagg[$method . '_new_value_' . $num . '_' . $i]);
342
-
343
- if (array_key_exists($method . '_new_credito_parcelamento_' . $num . '_' . $i, $mundipagg)) {
344
- if ($mundipagg[$method . '_new_credito_parcelamento_' . $num . '_' . $i] > $helperInstallments->getMaxInstallments($mundipagg[$method . '_' . $num . '_' . $i . '_cc_type'], $value)) {
345
- Mage::throwException($helper->__('it is not possible to divide by %s times', $mundipagg[$method . '_new_credito_parcelamento_' . $num . '_' . $i]));
346
- }
347
- }
348
-
349
- (float)$totalInstallmentsNew += $value;
350
- }
351
- }
352
-
353
- // Total Installments from token and Credit Card
354
- (float)$totalInstallments = $totalInstallmentsToken + $totalInstallmentsNew;
355
-
356
- // If an amount has already been authorized
357
- if (isset($mundipagg['multi']) && Mage::getSingleton('checkout/session')->getAuthorizedAmount()) {
358
- (float)$totalInstallments += (float)Mage::getSingleton('checkout/session')->getAuthorizedAmount();
359
-
360
- // Unset session
361
- Mage::getSingleton('checkout/session')->setAuthorizedAmount();
362
- }
363
-
364
- $epsilon = 0.00001;
365
-
366
- // $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
367
- // $helperLog->info("totalInstallments: {$totalInstallments}");
368
- // $helperLog->info("grandTotal: {$grandTotal}");
369
- // $helperLog->info("getPaymentInterest: {$info->getPaymentInterest()}");
370
- // $helperLog->info("epsilon: {$epsilon}");
371
-
372
- // if ($totalInstallments > 0 && ($grandTotal - $totalInstallments - $info->getPaymentInterest())) {
373
- // Mage::throwException(Mage::helper('payment')->__('Installments does not match with quote.'));
374
- // }
375
- }
376
- } else {
377
- if (isset($mundipagg['method'])) {
378
- $info->setAdditionalInformation('PaymentMethod', $mundipagg['method']);
379
- }
380
- }
381
- }
382
-
383
- // Get customer_id from Quote (payment made on site) or from POST (payment made from API)
384
- if (Mage::getSingleton('customer/session')->isLoggedIn()) {
385
- if ($this->getQuote()->getCustomer()->getEntityId()) {
386
- $customerId = $this->getQuote()->getCustomer()->getEntityId();
387
- }
388
- } elseif (isset($mundipagg['entity_id'])) {
389
- $customerId = $mundipagg['entity_id'];
390
- }
391
-
392
- // We verifiy if token is from customer
393
- if (isset($customerId) && isset($mundipagg['method'])) {
394
- $num = $helper->getCreditCardsNumber($mundipagg['method']);
395
-
396
- if ($num == 0) {
397
- $num = 1;
398
- }
399
-
400
- foreach ($mundipagg as $key => $value) {
401
- $pos = strpos($key, 'token_' . $num);
402
-
403
- if ($pos !== false && $value != '' && $value != 'new') {
404
- $token = Mage::getModel('mundipagg/cardonfile')->load($value);
405
-
406
- if ($token->getId() && $token->getEntityId() == $customerId) {
407
- // Ok
408
- $info->setAdditionalInformation('CreditCardBrandEnum_' . $key, $token->getCcType());
409
- } else {
410
- $error = $helper->__('Token not found');
411
-
412
- //Log error
413
- Mage::log($error, null, 'Uecommerce_Mundipagg.log');
414
-
415
- Mage::throwException($error);
416
- }
417
- }
418
- }
419
- }
420
-
421
- return $this;
422
- }
423
-
424
- /**
425
- * Prepare info instance for save
426
- *
427
- * @return Mage_Payment_Model_Abstract
428
- */
429
- public function prepareSave() {
430
- $info = $this->getInfoInstance();
431
- if ($this->_canSaveCc) {
432
- $info->setCcNumberEnc($info->encrypt($info->getCcNumber()));
433
- }
434
-
435
- $info->setCcNumber(null);
436
-
437
- return $this;
438
- }
439
-
440
- /**
441
- * Get payment quote
442
- */
443
- public function getPayment() {
444
- return $this->getQuote()->getPayment();
445
- }
446
-
447
- /**
448
- * Get Modulo session namespace
449
- *
450
- * @return Uecommerce_Mundipagg_Model_Session
451
- */
452
- public function getSession() {
453
- return Mage::getSingleton('mundipagg/session');
454
- }
455
-
456
- /**
457
- * Get checkout session namespace
458
- *
459
- * @return Mage_Checkout_Model_Session
460
- */
461
- public function getCheckout() {
462
- return Mage::getSingleton('checkout/session');
463
- }
464
-
465
- /**
466
- * Get current quote
467
- *
468
- * @return Mage_Sales_Model_Quote
469
- */
470
- public function getQuote() {
471
- return $this->getCheckout()->getQuote();
472
- }
473
-
474
- /**
475
- * Check order availability
476
- *
477
- * @return bool
478
- */
479
- public function canOrder() {
480
- return $this->_canOrder;
481
- }
482
-
483
- /**
484
- * Check authorize availability
485
- *
486
- * @return bool
487
- */
488
- public function canAuthorize() {
489
- return $this->_canAuthorize;
490
- }
491
-
492
- /**
493
- * Check capture availability
494
- *
495
- * @return bool
496
- */
497
- public function canCapture() {
498
- return $this->_canCapture;
499
- }
500
-
501
- /**
502
- * Instantiate state and set it to state object
503
- *
504
- * @param string $paymentAction
505
- * @param Varien_Object
506
- */
507
- public function initialize($paymentAction, $stateObject) {
508
- // TODO move initialize method to appropriate model (Boleto, Creditcard ...)
509
- $paymentAction = $this->getPaymentAction();
510
-
511
- switch ($paymentAction) {
512
- case 'order':
513
- $this->setCreditCardOperationEnum('AuthAndCapture');
514
- break;
515
-
516
- case 'authorize':
517
- $this->setCreditCardOperationEnum('AuthOnly');
518
- break;
519
-
520
- case 'authorize_capture':
521
- $this->setCreditCardOperationEnum('AuthAndCaptureWithDelay');
522
- break;
523
- }
524
-
525
- $mageVersion = Mage::helper('mundipagg/version')->convertVersionToCommunityVersion(Mage::getVersion());
526
-
527
- if (version_compare($mageVersion, '1.5.0', '<')) {
528
- $orderAction = 'order';
529
- } else {
530
- $orderAction = Mage_Payment_Model_Method_Abstract::ACTION_ORDER;
531
- }
532
-
533
- $payment = $this->getInfoInstance();
534
- $order = $payment->getOrder();
535
-
536
- // If payment method is Boleto Bancário we call "order" method
537
- if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_boleto') {
538
- $this->order($payment, $order->getBaseTotalDue());
539
-
540
- return $this;
541
- }
542
-
543
- // If it's a multi-payment types we force to ACTION_AUTHORIZE
544
- $num = Mage::helper('mundipagg')->getCreditCardsNumber($payment->getAdditionalInformation('PaymentMethod'));
545
-
546
- if ($num > 1) {
547
- $paymentAction = Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE;
548
- }
549
-
550
- switch ($paymentAction) {
551
- case Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE:
552
- $payment->authorize($payment, $order->getBaseTotalDue());
553
- break;
554
-
555
- case Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE_CAPTURE:
556
- $payment->authorize($payment, $order->getBaseTotalDue());
557
- break;
558
-
559
- case $orderAction:
560
- $this->order($payment, $order->getBaseTotalDue());
561
- break;
562
-
563
- default:
564
- $this->order($payment, $order->getBaseTotalDue());
565
- break;
566
- }
567
- }
568
-
569
- /**
570
- * Authorize payment abstract method
571
- *
572
- * @param Varien_Object $payment
573
- * @param float $amount
574
- *
575
- * @return Mage_Payment_Model_Abstract
576
- */
577
- public function authorize(Varien_Object $payment, $amount) {
578
- try {
579
- if (!$this->canAuthorize()) {
580
- Mage::throwException(Mage::helper('payment')->__('Authorize action is not available.'));
581
- }
582
-
583
- // Load order
584
- $order = $payment->getOrder();
585
-
586
- // Proceed to authorization on Gateway
587
- $resultPayment = $this->doPayment($payment, $order);
588
-
589
- // We record transaction(s)
590
- if (isset($resultPayment['result'])) {
591
- $xml = $resultPayment['result'];
592
- $json = json_encode($xml);
593
-
594
- $resultPayment['result'] = array();
595
- $resultPayment['result'] = json_decode($json, true);
596
-
597
- if (isset($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult)) {
598
- if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
599
- $trans = $resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
600
-
601
- $transaction = $this->_addTransaction($payment, $trans['TransactionKey'], Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH, $trans);
602
- } else {
603
- foreach ($resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
604
- $transaction = $this->_addTransaction($payment, $trans['TransactionKey'], Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH, $trans, $key);
605
- }
606
- }
607
- }
608
- }
609
-
610
- // Return
611
- if (isset($resultPayment['error'])) {
612
- try {
613
- $payment->setSkipOrderProcessing(true)->save();
614
-
615
- Mage::throwException(Mage::helper('mundipagg')->__($resultPayment['ErrorDescription']));
616
- } catch (Exception $e) {
617
- Mage::logException($e);
618
-
619
- return $this;
620
- }
621
- } else {
622
- // Send new order email when not in admin
623
- if (Mage::app()->getStore()->getCode() != 'admin') {
624
- $order->sendNewOrderEmail();
625
- }
626
-
627
- if (isset($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult)) {
628
- $creditCardTransactionResultCollection = $xml->CreditCardTransactionResultCollection->CreditCardTransactionResult;
629
-
630
- // We can capture only if:
631
- // 1. Multiple Credit Cards Payment
632
- // 2. Anti fraud is disabled
633
- // 3. Payment action is "AuthorizeAndCapture"
634
- if (
635
- count($creditCardTransactionResultCollection) > 1 &&
636
- $this->getAntiFraud() == 0 &&
637
- $this->getPaymentAction() == 'order' &&
638
- $order->getPaymentAuthorizationAmount() == $order->getGrandTotal()
639
- ) {
640
- $this->captureAndcreateInvoice($payment);
641
- }
642
- }
643
- }
644
-
645
- return $this;
646
-
647
- } catch (Exception $e) {
648
- Mage::logException($e);
649
- }
650
- }
651
-
652
- /**
653
- * Capture payment abstract method
654
- *
655
- * @param Varien_Object $payment
656
- * @param float $amount
657
- *
658
- * @return Mage_Payment_Model_Abstract
659
- */
660
- public function capture(Varien_Object $payment, $amount) {
661
- $helper = Mage::helper('payment');
662
-
663
- if (!$this->canCapture()) {
664
- Mage::throwException($helper->__('Capture action is not available.'));
665
- }
666
-
667
- if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_boleto') {
668
- Mage::throwException($helper->__('You cannot capture Boleto Bancário.'));
669
- }
670
-
671
- if ($this->getAntiFraud() == 1) {
672
- Mage::throwException($helper->__('You cannot capture having anti fraud activated.'));
673
- }
674
-
675
- // Already captured
676
- if ($payment->getAdditionalInformation('CreditCardTransactionStatusEnum') == 'Captured' || $payment->getAdditionalInformation('CreditCardTransactionStatus') == 'Captured') {
677
- return $this;
678
- }
679
-
680
- // Prepare data in order to capture
681
- if ($payment->getAdditionalInformation('OrderKey')) {
682
- $transactions = Mage::getModel('sales/order_payment_transaction')
683
- ->getCollection()
684
- ->addAttributeToFilter('order_id', array('eq' => $payment->getOrder()->getEntityId()))
685
- ->addAttributeToFilter('txn_type', array('eq' => 'authorization'));
686
-
687
- foreach ($transactions as $key => $transaction) {
688
- $TransactionKey = $transaction->getAdditionalInformation('TransactionKey');
689
- $TransactionReference = $transaction->getAdditionalInformation('TransactionReference');
690
- }
691
-
692
- // $data['CreditCardTransactionCollection']['AmountInCents'] = $payment->getOrder()->getBaseGrandTotal() * 100;
693
- // $data['CreditCardTransactionCollection']['TransactionKey'] = $TransactionKey;
694
- // $data['CreditCardTransactionCollection']['TransactionReference'] = $TransactionReference;
695
- $orderkeys = (array)$payment->getAdditionalInformation('OrderKey');
696
-
697
- foreach ($orderkeys as $orderkey) {
698
- $data['OrderKey'] = $orderkey;
699
- $data['ManageOrderOperationEnum'] = 'Capture';
700
-
701
- //Call Gateway Api
702
- $api = Mage::getModel('mundipagg/api');
703
-
704
- $capture = $api->manageOrderRequest($data, $this);
705
-
706
- // Xml
707
- $xml = $capture['result'];
708
- $json = json_encode($xml);
709
-
710
- $capture['result'] = array();
711
- $capture['result'] = json_decode($json, true);
712
-
713
- // Save transactions
714
- if (isset($capture['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'])) {
715
- if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
716
- $trans = $capture['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
717
-
718
- $this->_addTransaction($payment, $trans['TransactionKey'], Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE, $trans);
719
- } else {
720
- $CapturedAmountInCents = 0;
721
-
722
- foreach ($capture['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
723
- $TransactionKey = $trans['TransactionKey'];
724
- $CapturedAmountInCents += $trans['CapturedAmountInCents'];
725
- }
726
-
727
- $trans = array();
728
- $trans['CapturedAmountInCents'] = $CapturedAmountInCents;
729
- $trans['Success'] = true;
730
-
731
- $this->_addTransaction($payment, $TransactionKey, Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE, $trans);
732
- }
733
- } else {
734
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
735
-
736
- return false;
737
- }
738
- }
739
- } else {
740
- Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
741
-
742
- return false;
743
- }
744
- }
745
-
746
- /**
747
- * Capture payment abstract method
748
- *
749
- * @param Varien_Object $payment
750
- * @param float $amount
751
- *
752
- * @return Mage_Payment_Model_Abstract
753
- */
754
- public function captureAndcreateInvoice(Varien_Object $payment) {
755
- $order = $payment->getOrder();
756
-
757
- // Capture
758
- $capture = $this->capture($payment, $order->getGrandTotal());
759
-
760
- // Error
761
- if (!$capture) {
762
- return $this;
763
- }
764
-
765
- // Create invoice
766
- $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice(array());
767
- $invoice->register();
768
-
769
- $invoice->setCanVoidFlag(true);
770
- $invoice->getOrder()->setIsInProcess(true);
771
- $invoice->setState(2);
772
-
773
- if (Mage::helper('sales')->canSendNewInvoiceEmail($order->getStoreId())) {
774
- $invoice->setEmailSent(true);
775
- $invoice->sendEmail();
776
- }
777
-
778
- $invoice->save();
779
-
780
- $order->setBaseTotalPaid($order->getBaseGrandTotal());
781
- $order->setTotalPaid($order->getBaseGrandTotal());
782
- $order->addStatusHistoryComment('Captured online amount of R$' . $order->getBaseGrandTotal(), false);
783
- $order->save();
784
-
785
- return $this;
786
- }
787
-
788
- /**
789
- * Order payment abstract method
790
- *
791
- * @param Varien_Object $payment
792
- * @param float $amount
793
- *
794
- * @return Mage_Payment_Model_Abstract
795
- */
796
- public function order(Varien_Object $payment, $amount) {
797
- if (!$this->canOrder()) {
798
- Mage::throwException(Mage::helper('payment')->__('Order action is not available.'));
799
- }
800
-
801
- // Load order
802
- $order = $payment->getOrder();
803
-
804
- $order = Mage::getModel('sales/order')->loadByIncrementId($order->getRealOrderId());
805
-
806
- // Proceed to payment on Gateway
807
- $resultPayment = $this->doPayment($payment, $order);
808
-
809
- // Return error
810
- if (isset($resultPayment['error'])) {
811
- try {
812
- $mageVersion = Mage::helper('mundipagg/version')->convertVersionToCommunityVersion(Mage::getVersion());
813
-
814
- if (version_compare($mageVersion, '1.5.0', '<')) {
815
- $transactionType = 'payment';
816
- } else {
817
- $transactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER;
818
- }
819
-
820
- // Xml
821
- $xml = $resultPayment['result'];
822
- $json = json_encode($xml);
823
-
824
- $resultPayment['result'] = array();
825
- $resultPayment['result'] = json_decode($json, true);
826
-
827
- // We record transaction(s)
828
- if (isset($resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'])) {
829
- if (count($resultPayment['result']['CreditCardTransactionResultCollection']) == 1) {
830
- $trans = $resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
831
-
832
- $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
833
- } else {
834
- foreach ($resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
835
- $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans, $key);
836
- }
837
- }
838
- }
839
-
840
- if (isset($resultPayment['ErrorItemCollection'])) {
841
- if (count($resultPayment['ErrorItemCollection']) == 1) {
842
- foreach ($resultPayment['ErrorItemCollection']['ErrorItem'] as $key => $value) {
843
- $payment->setAdditionalInformation($key, $value)->save();
844
- }
845
- } else {
846
- foreach ($resultPayment['ErrorItemCollection'] as $key1 => $error) {
847
- foreach ($error as $key2 => $value) {
848
- $payment->setAdditionalInformation($key1 . '_' . $key2, $value)->save();
849
- }
850
- }
851
- }
852
- }
853
-
854
- $payment->setSkipOrderProcessing(true)->save();
855
-
856
- if (isset($resultPayment['ErrorDescription'])) {
857
- $order->addStatusHistoryComment(Mage::helper('mundipagg')->__(htmlspecialchars_decode($resultPayment['ErrorDescription'])));
858
- $order->save();
859
-
860
- Mage::throwException(Mage::helper('mundipagg')->__($resultPayment['ErrorDescription']));
861
- } else {
862
- Mage::throwException(Mage::helper('mundipagg')->__('Erro'));
863
- }
864
- } catch (Exception $e) {
865
- return $this;
866
- }
867
- } else {
868
- if (isset($resultPayment['message'])) {
869
- $mageVersion = Mage::helper('mundipagg/version')->convertVersionToCommunityVersion(Mage::getVersion());
870
-
871
- if (version_compare($mageVersion, '1.5.0', '<')) {
872
- $transactionType = 'payment';
873
- } else {
874
- $transactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER;
875
- }
876
-
877
- // Xml
878
- $xml = $resultPayment['result'];
879
- $json = json_encode($xml);
880
-
881
- $resultPayment['result'] = array();
882
- $resultPayment['result'] = json_decode($json, true);
883
-
884
- switch ($resultPayment['message']) {
885
- // Boleto
886
- case 0:
887
- $payment->setAdditionalInformation('BoletoUrl', $resultPayment['result']['BoletoTransactionResultCollection']['BoletoTransactionResult']['BoletoUrl']);
888
-
889
- // In order to show "Print Boleto" link in order email
890
- $order->getPayment()->setAdditionalInformation('BoletoUrl', $resultPayment['result']['BoletoTransactionResultCollection']['BoletoTransactionResult']['BoletoUrl']);
891
-
892
- // We record transaction(s)
893
- if (count($resultPayment['result']['BoletoTransactionResultCollection']) == 1) {
894
- $trans = $resultPayment['result']['BoletoTransactionResultCollection']['BoletoTransactionResult'];
895
-
896
- $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
897
- } else {
898
- foreach ($resultPayment['result']['BoletoTransactionResultCollection']['BoletoTransactionResult'] as $key => $trans) {
899
- $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans, $key);
900
- }
901
- }
902
-
903
- $payment->setTransactionId($this->_transactionId);
904
-
905
- $payment->save();
906
-
907
- // Send new order email when not in admin
908
- if (Mage::app()->getStore()->getCode() != 'admin') {
909
- $order->sendNewOrderEmail();
910
- }
911
-
912
- break;
913
-
914
- // Credit Card
915
- case 1:
916
- // We record transaction(s)
917
- if (count($resultPayment['result']['CreditCardTransactionResultCollection']) == 1) {
918
- $trans = $resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
919
- if (array_key_exists('TransactionKey', $trans)) {
920
- $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
921
- }
922
- } else {
923
- foreach ($resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
924
- if (array_key_exists('TransactionKey', $trans)) {
925
- $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans, $key);
926
- }
927
- }
928
- }
929
-
930
- // Send new order email when not in admin
931
- if (Mage::app()->getStore()->getCode() != 'admin') {
932
- $order->sendNewOrderEmail();
933
- }
934
-
935
- // Invoice
936
- $order = $payment->getOrder();
937
-
938
- if (!$order->canInvoice()) {
939
- // Log error
940
- Mage::logException(Mage::helper('core')->__('Cannot create an invoice.'));
941
-
942
- Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
943
- }
944
-
945
- // Create invoice
946
- $invoice = Mage::getModel('sales/service_order', $payment->getOrder())->prepareInvoice(array());
947
- $invoice->register();
948
-
949
- // Set capture case to offline and register the invoice.
950
- $invoice->setTransactionId($this->_transactionId);
951
- $invoice->setCanVoidFlag(true);
952
- $invoice->getOrder()->setIsInProcess(true);
953
- $invoice->setState(2);
954
-
955
- // Send invoice if enabled
956
- if (Mage::helper('sales')->canSendNewInvoiceEmail($order->getStoreId())) {
957
- $invoice->setEmailSent(true);
958
- $invoice->sendEmail();
959
- }
960
-
961
- $invoice->save();
962
-
963
- $order->setBaseTotalPaid($order->getBaseGrandTotal());
964
- $order->setTotalPaid($order->getBaseGrandTotal());
965
- $order->addStatusHistoryComment('Captured online amount of R$' . $order->getBaseGrandTotal(), false);
966
- $order->save();
967
-
968
- $payment->setLastTransId($this->_transactionId);
969
- $payment->save();
970
-
971
- break;
972
-
973
- // Debit
974
- case 4:
975
- // We record transaction
976
- $trans = $resultPayment['result'];
977
-
978
- $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
979
- break;
980
- }
981
- }
982
-
983
- return $this;
984
- }
985
- }
986
-
987
- /**
988
- * Proceed to payment
989
- * @param object $order
990
- */
991
- public function doPayment($payment, $order) {
992
- try {
993
- $session = Mage::getSingleton('checkout/session');
994
- $mundipaggData = $session->getMundipaggData();
995
-
996
- //Post data
997
- $postData = Mage::app()->getRequest()->getPost();
998
-
999
- // Get customer taxvat
1000
- $taxvat = '';
1001
-
1002
- if ($order->getCustomerTaxvat() == '') {
1003
- $customerId = $order->getCustomerId();
1004
-
1005
- if ($customerId) {
1006
- $customer = Mage::getModel('customer/customer')->load($customerId);
1007
- $taxvat = $customer->getTaxvat();
1008
- }
1009
-
1010
- if ($taxvat != '') {
1011
- $order->setCustomerTaxvat($taxvat)->save();
1012
- }
1013
- } else {
1014
- $taxvat = $order->getCustomerTaxvat();
1015
- }
1016
-
1017
- // Data to pass to api
1018
- $data['customer_id'] = $order->getCustomerId();
1019
- $data['address_id'] = $order->getBillingAddress()->getCustomerAddressId();
1020
- $data['payment_method'] = isset($postData['payment']['method']) ? $postData['payment']['method'] : $mundipaggData['method'];
1021
- $type = $data['payment_method'];
1022
-
1023
- // 1 or more Credit Cards Payment
1024
- if ($data['payment_method'] != 'mundipagg_boleto' && $data['payment_method'] != 'mundipagg_debit') {
1025
- $helper = Mage::helper('mundipagg');
1026
- $num = $helper->getCreditCardsNumber($type);
1027
- $method = $helper->getPaymentMethod($num);
1028
-
1029
- if ($num == 0) {
1030
- $num = 1;
1031
- }
1032
-
1033
- for ($i = 1; $i <= $num; $i++) {
1034
- // New Credit Card
1035
- if (
1036
- !isset($postData['payment'][$method . '_token_' . $num . '_' . $i]) ||
1037
- (isset($postData['payment'][$method . '_token_' . $num . '_' . $i]) && $postData['payment'][$method . '_token_' . $num . '_' . $i] == 'new')
1038
- ) {
1039
- $data['payment'][$i]['HolderName'] = isset($postData['payment'][$method . '_cc_holder_name_' . $num . '_' . $i]) ? $postData['payment'][$method . '_cc_holder_name_' . $num . '_' . $i] : $mundipaggData[$method . '_cc_holder_name_' . $num . '_' . $i];
1040
- $data['payment'][$i]['CreditCardNumber'] = isset($postData['payment'][$method . '_' . $num . '_' . $i . '_cc_number']) ? $postData['payment'][$method . '_' . $num . '_' . $i . '_cc_number'] : $mundipaggData[$method . '_' . $num . '_' . $i . '_cc_number'];
1041
- $data['payment'][$i]['ExpMonth'] = isset($postData['payment'][$method . '_expirationMonth_' . $num . '_' . $i]) ? $postData['payment'][$method . '_expirationMonth_' . $num . '_' . $i] : $mundipaggData[$method . '_expirationMonth_' . $num . '_' . $i];
1042
- $data['payment'][$i]['ExpYear'] = isset($postData['payment'][$method . '_expirationYear_' . $num . '_' . $i]) ? $postData['payment'][$method . '_expirationYear_' . $num . '_' . $i] : $mundipaggData[$method . '_expirationYear_' . $num . '_' . $i];
1043
- $data['payment'][$i]['SecurityCode'] = isset($postData['payment'][$method . '_cc_cid_' . $num . '_' . $i]) ? $postData['payment'][$method . '_cc_cid_' . $num . '_' . $i] : $mundipaggData[$method . '_cc_cid_' . $num . '_' . $i];
1044
- $data['payment'][$i]['CreditCardBrandEnum'] = Mage::helper('mundipagg')->issuer(isset($postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type']) ? $postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type'] : $mundipaggData[$method . '_' . $num . '_' . $i . '_cc_type']);
1045
- $data['payment'][$i]['InstallmentCount'] = isset($postData['payment'][$method . '_new_credito_parcelamento_' . $num . '_' . $i]) ? $postData['payment'][$method . '_new_credito_parcelamento_' . $num . '_' . $i] : 1;
1046
- $data['payment'][$i]['token'] = isset($postData['payment'][$method . '_save_token_' . $num . '_' . $i]) ? $postData['payment'][$method . '_save_token_' . $num . '_' . $i] : null;
1047
-
1048
- if (isset($postData['payment'][$method . '_new_value_' . $num . '_' . $i]) && $postData['payment'][$method . '_new_value_' . $num . '_' . $i] != '') {
1049
- $data['payment'][$i]['AmountInCents'] = str_replace(',', '.', $postData['payment'][$method . '_new_value_' . $num . '_' . $i]);
1050
- $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] + Mage::helper('mundipagg/installments')->getInterestForCard($data['payment'][$i]['InstallmentCount'], isset($postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type']) ? $postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type'] : $mundipaggData[$method . '_' . $num . '_' . $i . '_cc_type'], $data['payment'][$i]['AmountInCents']);
1051
-
1052
- $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] * 100;
1053
- } else {
1054
- if (!isset($postData['partial'])) {
1055
- $data['payment'][$i]['AmountInCents'] = $order->getGrandTotal() * 100;
1056
- } else { // If partial payment we deduct authorized amount already processed
1057
- if (Mage::getSingleton('checkout/session')->getAuthorizedAmount()) {
1058
- $data['payment'][$i]['AmountInCents'] = ($order->getGrandTotal()) * 100 - Mage::getSingleton('checkout/session')->getAuthorizedAmount() * 100;
1059
- } else {
1060
- $data['payment'][$i]['AmountInCents'] = ($order->getGrandTotal()) * 100;
1061
- }
1062
- }
1063
- }
1064
-
1065
- $data['payment'][$i]['TaxDocumentNumber'] = isset($postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i]) ? $postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i] : $taxvat;
1066
-
1067
- } else { // Token
1068
- $data['payment'][$i]['card_on_file_id'] = isset($postData['payment'][$method . '_token_' . $num . '_' . $i]) ? $postData['payment'][$method . '_token_' . $num . '_' . $i] : $mundipaggData[$method . '_token_' . $num . '_' . $i];
1069
- $data['payment'][$i]['InstallmentCount'] = isset($postData['payment'][$method . '_credito_parcelamento_' . $num . '_' . $i]) ? $postData['payment'][$method . '_credito_parcelamento_' . $num . '_' . $i] : 1;
1070
-
1071
- if (isset($postData['payment'][$method . '_value_' . $num . '_' . $i]) && $postData['payment'][$method . '_value_' . $num . '_' . $i] != '') {
1072
- $data['payment'][$i]['AmountInCents'] = str_replace(',', '.', $postData['payment'][$method . '_value_' . $num . '_' . $i]);
1073
- $cardonFile = Mage::getModel('mundipagg/cardonfile')->load($postData['payment'][$method . '_token_' . $num . '_' . $i]);
1074
- $tokenCctype = Mage::getSingleton('mundipagg/source_cctypes')->getCcTypeForLabel($cardonFile->getCcType());
1075
- $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] + Mage::helper('mundipagg/installments')->getInterestForCard($data['payment'][$i]['InstallmentCount'], $tokenCctype, $data['payment'][$i]['AmountInCents']);
1076
- $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] * 100;
1077
-
1078
- } else {
1079
- if (!isset($postData['partial'])) {
1080
- $data['payment'][$i]['AmountInCents'] = $order->getGrandTotal() * 100;
1081
- } else { // If partial payment we deduct authorized amount already processed
1082
- if (Mage::getSingleton('checkout/session')->getAuthorizedAmount()) {
1083
- $data['payment'][$i]['AmountInCents'] = ($order->getGrandTotal()) * 100 - Mage::getSingleton('checkout/session')->getAuthorizedAmount() * 100;
1084
- } else {
1085
- $data['payment'][$i]['AmountInCents'] = $order->getGrandTotal() * 100;
1086
- }
1087
- }
1088
- }
1089
-
1090
- $data['payment'][$i]['TaxDocumentNumber'] = isset($postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i]) ? $postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i] : $taxvat;
1091
- }
1092
-
1093
- if (Mage::helper('mundipagg')->validateCPF($data['payment'][$i]['TaxDocumentNumber'])) {
1094
- $data['PersonTypeEnum'] = 'Person';
1095
- $data['TaxDocumentTypeEnum'] = 'CPF';
1096
- $data['TaxDocumentNumber'] = $data['payment'][$i]['TaxDocumentNumber'];
1097
- }
1098
-
1099
- // We verify if a CNPJ is informed
1100
- if (Mage::helper('mundipagg')->validateCNPJ($data['payment'][$i]['TaxDocumentNumber'])) {
1101
- $data['PersonTypeEnum'] = 'Company';
1102
- $data['TaxDocumentTypeEnum'] = 'CNPJ';
1103
- $data['TaxDocumentNumber'] = $data['payment'][$i]['TaxDocumentNumber'];
1104
- }
1105
- }
1106
- }
1107
-
1108
- // Boleto Payment
1109
- if ($data['payment_method'] == 'mundipagg_boleto') {
1110
- $data['TaxDocumentNumber'] = isset($postData['payment']['boleto_taxvat']) ? $postData['payment']['boleto_taxvat'] : $taxvat;
1111
- $data['boleto_parcelamento'] = isset($postData['payment']['boleto_parcelamento']) ? $postData['payment']['boleto_parcelamento'] : 1;
1112
- $data['boleto_dates'] = isset($postData['payment']['boleto_dates']) ? $postData['payment']['boleto_dates'] : null;
1113
-
1114
- // We verify if a CPF is informed
1115
- if (Mage::helper('mundipagg')->validateCPF($data['TaxDocumentNumber'])) {
1116
- $data['PersonTypeEnum'] = 'Person';
1117
- $data['TaxDocumentTypeEnum'] = 'CPF';
1118
- }
1119
-
1120
- // We verify if a CNPJ is informed
1121
- if (Mage::helper('mundipagg')->validateCNPJ($data['TaxDocumentNumber'])) {
1122
- $data['PersonTypeEnum'] = 'Company';
1123
- $data['TaxDocumentTypeEnum'] = 'CNPJ';
1124
- }
1125
- }
1126
-
1127
- // Debit Payment
1128
- if ($data['payment_method'] == 'mundipagg_debit') {
1129
- $data['TaxDocumentNumber'] = isset($postData['payment']['taxvat']) ? $postData['payment']['taxvat'] : $taxvat;
1130
- $data['Bank'] = isset($postData['payment']['mundipagg_debit']) ? $postData['payment']['mundipagg_debit'] : $mundipaggData['mundipagg_debit'];
1131
-
1132
- // We verify if a CPF is informed
1133
- if (Mage::helper('mundipagg')->validateCPF($data['TaxDocumentNumber'])) {
1134
- $data['PersonTypeEnum'] = 'Person';
1135
- $data['TaxDocumentTypeEnum'] = 'CPF';
1136
- }
1137
-
1138
- // We verify if a CNPJ is informed
1139
- if (Mage::helper('mundipagg')->validateCNPJ($data['TaxDocumentNumber'])) {
1140
- $data['PersonTypeEnum'] = 'Company';
1141
- $data['TaxDocumentTypeEnum'] = 'CNPJ';
1142
- }
1143
- }
1144
-
1145
- // Unset MundipaggData data
1146
- $session->setMundipaggData();
1147
-
1148
- // Api
1149
- $api = Mage::getModel('mundipagg/api');
1150
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1151
-
1152
- // Get approval request from gateway
1153
- switch ($type) {
1154
- case 'mundipagg_boleto':
1155
- $approvalRequest = $api->boletoTransaction($order, $data, $this);
1156
- break;
1157
-
1158
- case 'mundipagg_debit':
1159
- $approvalRequest = $api->debitTransaction($order, $data, $this);
1160
- break;
1161
-
1162
- case $type:
1163
- $approvalRequest = $api->creditCardTransaction($order, $data, $this);
1164
- break;
1165
- }
1166
-
1167
- // Set some data from Mundipagg
1168
- $payment = $this->setPaymentAdditionalInformation($approvalRequest, $payment);
1169
- $authorizedAmount = $order->getPaymentAuthorizationAmount();
1170
-
1171
- if (is_null($authorizedAmount)) {
1172
- $authorizedAmount = 0;
1173
- }
1174
-
1175
- // Payment gateway error
1176
- if (isset($approvalRequest['error'])) {
1177
-
1178
- if (isset($approvalRequest['ErrorItemCollection'])) {
1179
- $errorItemCollection = $approvalRequest['ErrorItemCollection'];
1180
-
1181
- if (isset($errorItemCollection['ErrorItem']['ErrorCode'])) {
1182
- $errorCode = $errorItemCollection['ErrorItem']['ErrorCode'];
1183
-
1184
- if ($errorCode == '504') {
1185
- $statusWithError = Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum::WITH_ERROR;
1186
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess($statusWithError);
1187
-
1188
- return $approvalRequest;
1189
- }
1190
- }
1191
- }
1192
-
1193
- if (isset($approvalRequest['ErrorCode']) && $approvalRequest['ErrorCode'] == 'multi') {
1194
- // Partial payment
1195
-
1196
- // We set authorized amount
1197
- $orderGrandTotal = $order->getGrandTotal();
1198
-
1199
- foreach ($approvalRequest['result']->CreditCardTransactionResultCollection->CreditCardTransactionResult as $key => $result) {
1200
- if ($result->Success == true) {
1201
- $authorizedAmount += $result->AuthorizedAmountInCents * 0.01;
1202
- }
1203
- }
1204
-
1205
- // If authorized amount is the same as order grand total we can show success page
1206
- $epsilon = 0.1;
1207
-
1208
- if ($authorizedAmount != 0) {
1209
- if (($orderGrandTotal - $authorizedAmount) <= $epsilon) {
1210
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1211
- Mage::getSingleton('checkout/session')->setAuthorizedAmount();
1212
-
1213
- } else {
1214
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('partial');
1215
- Mage::getSingleton('checkout/session')->setAuthorizedAmount($authorizedAmount);
1216
- }
1217
-
1218
- $order->setPaymentAuthorizationAmount($authorizedAmount);
1219
- $order->save();
1220
-
1221
- } else {
1222
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
1223
- }
1224
- } else {
1225
- $this->offlineRetryCancelOrSuccessOrder($order->getIncrementId());
1226
- }
1227
-
1228
- return $approvalRequest;
1229
- }
1230
-
1231
- switch ($approvalRequest['message']) {
1232
- // BoletoBancario
1233
- case 0:
1234
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1235
- break;
1236
-
1237
- // 1CreditCards
1238
- case 1: // AuthAndCapture
1239
- case 2: // AuthOnly
1240
- case 3: // AuthAndCaptureWithDelay
1241
- // We set authorized amount in session
1242
- $orderGrandTotal = $order->getGrandTotal();
1243
- $xml = $approvalRequest['result'];
1244
-
1245
- if (isset($xml->OrderResult)) {
1246
- $orderResult = $xml->OrderResult;
1247
- }
1248
-
1249
- if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
1250
- $result = $xml->CreditCardTransactionResultCollection->CreditCardTransactionResult;
1251
-
1252
- if ($result->Success == true) {
1253
- $authorizedAmount += $result->AuthorizedAmountInCents * 0.01;
1254
- }
1255
- } else {
1256
- foreach ($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult as $key => $result) {
1257
- if ($result->Success == true) {
1258
- $authorizedAmount += $result->AuthorizedAmountInCents * 0.01;
1259
- }
1260
- }
1261
- }
1262
-
1263
- // If authorized amount is the same as order grand total we can show success page
1264
- $epsilon = 0.1;
1265
-
1266
- if (($orderGrandTotal - $authorizedAmount) <= $epsilon) {
1267
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1268
- Mage::getSingleton('checkout/session')->setAuthorizedAmount();
1269
-
1270
- if ($orderGrandTotal < $authorizedAmount) {
1271
- $interestInformation = $payment->getAdditionalInformation('mundipagg_interest_information');
1272
- $newInterestInformation = array();
1273
-
1274
- if (count($interestInformation)) {
1275
- $newInterest = 0;
1276
-
1277
- foreach ($interestInformation as $key => $ii) {
1278
- if (strpos($key, 'partial') !== false) {
1279
- if ($ii->hasValue()) {
1280
- $newInterest += (float)($ii->getInterest());
1281
- }
1282
- }
1283
-
1284
- }
1285
- }
1286
- $this->addInterestToOrder($order, $newInterest);
1287
- }
1288
-
1289
- } else {
1290
- if ($authorizedAmount != 0) {
1291
- if (($orderGrandTotal - $authorizedAmount) >= $epsilon) {
1292
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('partial');
1293
- Mage::getSingleton('checkout/session')->setAuthorizedAmount($authorizedAmount);
1294
-
1295
- $interestInformation = $payment->getAdditionalInformation('mundipagg_interest_information');
1296
- $unauthorizedAmount = (float)($orderGrandTotal - $authorizedAmount);
1297
- $newInterestInformation = array();
1298
-
1299
- if (count($interestInformation)) {
1300
- foreach ($interestInformation as $key => $ii) {
1301
-
1302
- if ($ii->hasValue()) {
1303
- if ((float)($ii->getValue() + $ii->getInterest()) == (float)trim($unauthorizedAmount)) {
1304
- $this->removeInterestToOrder($order, $ii->getInterest());
1305
- } else {
1306
- $newInterestInformation[$key] = $ii;
1307
- }
1308
- } else {
1309
- if (($order->getGrandTotal() + $order->getMundipaggInterest()) == $unauthorizedAmount) {
1310
- $this->removeInterestToOrder($order, $ii->getInterest());
1311
- } else {
1312
- $newInterestInformation[$key] = $ii;
1313
- }
1314
- }
1315
- }
1316
-
1317
- $payment->setAdditionalInformation('mundipagg_interest_information', $newInterestInformation);
1318
- }
1319
- }
1320
- } else {
1321
- $this->offlineRetryCancelOrSuccessOrder($order->getIncrementId());
1322
- }
1323
- }
1324
-
1325
- // Session
1326
- $xml = simplexml_load_string($approvalRequest['result']);
1327
- $json = json_encode($xml);
1328
- $dataR = array();
1329
- $dataR = json_decode($json, true);
1330
-
1331
- // Transaction
1332
- $transactionKey = isset($dataR['CreditCardTransactionResultCollection']['CreditCardTransactionResult']['TransactionKey']) ? $dataR['CreditCardTransactionResultCollection']['CreditCardTransactionResult']['TransactionKey'] : null;
1333
- $creditCardTransactionStatusEnum = isset($dataR['CreditCardTransactionResultCollection']['CreditCardTransactionResult']['CreditCardTransactionStatus']) ? $dataR['CreditCardTransactionResultCollection']['CreditCardTransactionResult']['CreditCardTransactionStatus'] : null;
1334
-
1335
- try {
1336
- if ($transactionKey != null) {
1337
- $this->_transactionId = $transactionKey;
1338
-
1339
- $payment->setTransactionId($this->_transactionId);
1340
- $payment->save();
1341
- }
1342
- } catch (Exception $e) {
1343
- $helperLog->error($e->getMessage());
1344
- continue;
1345
- }
1346
- break;
1347
-
1348
- // Debit
1349
- case 4:
1350
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('debit');
1351
- Mage::getSingleton('checkout/session')->setBankRedirectUrl($approvalRequest['result']['BankRedirectUrl']);
1352
- break;
1353
- }
1354
-
1355
- if (isset($orderResult)) {
1356
- $newOrderKey = (string)$orderResult->OrderKey;
1357
- $orderPayment = $order->getPayment();
1358
- $orderKeys = (array)$orderPayment->getAdditionalInformation('OrderKey');
1359
-
1360
- if (is_null($orderKeys) || !is_array($orderKeys)) {
1361
- $orderKeys = array();
1362
- }
1363
-
1364
- if (!in_array($newOrderKey, $orderKeys)) {
1365
- $orderKeys[] = $newOrderKey;
1366
- }
1367
-
1368
- $orderPayment->setAdditionalInformation('OrderKey', $orderKeys);
1369
- $orderPayment->save();
1370
- }
1371
-
1372
- $order->setPaymentAuthorizationAmount($authorizedAmount);
1373
- $order->save();
1374
-
1375
- if ($authorizedAmount == $order->getGrandTotal()) {
1376
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1377
- }
1378
-
1379
- return $approvalRequest;
1380
-
1381
- } catch (Exception $e) {
1382
- //Api
1383
- $api = Mage::getModel('mundipagg/api');
1384
-
1385
- //Log error
1386
- Mage::logException($e);
1387
-
1388
- //Mail error
1389
- $api->mailError(print_r($e->getMessage(), 1));
1390
- }
1391
- }
1392
-
1393
- private function setPaymentAdditionalInformation($approvalRequest, $payment) {
1394
- if (isset($approvalRequest['ErrorCode'])) {
1395
- $payment->setAdditionalInformation('ErrorCode', $approvalRequest['ErrorCode']);
1396
- }
1397
-
1398
- if (isset($approvalRequest['ErrorDescription'])) {
1399
- $payment->setAdditionalInformation('ErrorDescription', $approvalRequest['ErrorDescription']);
1400
- }
1401
-
1402
- if (isset($approvalRequest['OrderKey'])) {
1403
- $payment->setAdditionalInformation('OrderKey', $approvalRequest['OrderKey']);
1404
- }
1405
-
1406
- if (isset($approvalRequest['OrderReference'])) {
1407
- $payment->setAdditionalInformation('OrderReference', $approvalRequest['OrderReference']);
1408
- }
1409
-
1410
- if (isset($approvalRequest['CreateDate'])) {
1411
- $payment->setAdditionalInformation('CreateDate', $approvalRequest['CreateDate']);
1412
- }
1413
-
1414
- if (isset($approvalRequest['OrderStatusEnum'])) {
1415
- $payment->setAdditionalInformation('OrderStatusEnum', $approvalRequest['OrderStatusEnum']);
1416
- }
1417
-
1418
- if (isset($approvalRequest['TransactionKey'])) {
1419
- $payment->setAdditionalInformation('TransactionKey', $approvalRequest['TransactionKey']);
1420
- }
1421
-
1422
- if (isset($approvalRequest['OnlineDebitStatus'])) {
1423
- $payment->setAdditionalInformation('OnlineDebitStatus', $approvalRequest['OnlineDebitStatus']);
1424
- }
1425
-
1426
- if (isset($approvalRequest['TransactionKeyToBank'])) {
1427
- $payment->setAdditionalInformation('TransactionKeyToBank', $approvalRequest['TransactionKeyToBank']);
1428
- }
1429
-
1430
- if (isset($approvalRequest['TransactionReference'])) {
1431
- $payment->setAdditionalInformation('TransactionReference', $approvalRequest['TransactionReference']);
1432
- }
1433
-
1434
- if (array_key_exists('isRecurrency', $approvalRequest)) {
1435
- $payment->setAdditionalInformation('isRecurrency', $approvalRequest['isRecurrency']);
1436
- }
1437
-
1438
- return $payment;
1439
- }
1440
-
1441
- /**
1442
- * Set capture transaction ID and enable Void to invoice for informational purposes
1443
- * @param Mage_Sales_Model_Order_Invoice $invoice
1444
- * @param Mage_Sales_Model_Order_Payment $payment
1445
- * @return Mage_Payment_Model_Method_Abstract
1446
- */
1447
- public function processInvoice($invoice, $payment) {
1448
- if ($payment->getLastTransId()) {
1449
- $invoice->setTransactionId($payment->getLastTransId());
1450
- $invoice->setCanVoidFlag(true);
1451
-
1452
- if (Mage::helper('sales')->canSendNewInvoiceEmail($payment->getOrder()->getStoreId())) {
1453
- $invoice->setEmailSent(true);
1454
- $invoice->sendEmail();
1455
- }
1456
-
1457
- return $this;
1458
- }
1459
-
1460
- return false;
1461
- }
1462
-
1463
- /**
1464
- * Check void availability
1465
- *
1466
- * @return bool
1467
- */
1468
- public function canVoid(Varien_Object $payment) {
1469
- if ($payment instanceof Mage_Sales_Model_Order_Creditmemo) {
1470
- return false;
1471
- }
1472
-
1473
- return $this->_canVoid;
1474
- }
1475
-
1476
- public function void(Varien_Object $payment) {
1477
- if (!$this->canVoid($payment)) {
1478
- Mage::throwException(Mage::helper('payment')->__('Void action is not available.'));
1479
- }
1480
-
1481
- //Prepare data in order to void
1482
- if ($payment->getAdditionalInformation('OrderKey')) {
1483
- $transactions = Mage::getModel('sales/order_payment_transaction')
1484
- ->getCollection()
1485
- ->addAttributeToFilter('order_id', array('eq' => $payment->getOrder()->getEntityId()));
1486
-
1487
- foreach ($transactions as $key => $transaction) {
1488
- $TransactionKey = $transaction->getAdditionalInformation('TransactionKey');
1489
- $TransactionReference = $transaction->getAdditionalInformation('TransactionReference');
1490
- }
1491
-
1492
- // $data['CreditCardTransactionCollection']['AmountInCents'] = $payment->getOrder()->getBaseGrandTotal() * 100;
1493
- // $data['CreditCardTransactionCollection']['TransactionKey'] = $TransactionKey;
1494
- // $data['CreditCardTransactionCollection']['TransactionReference'] = $TransactionReference;
1495
- // $data['OrderKey'] = $payment->getAdditionalInformation('OrderKey');
1496
- $orderkeys = $payment->getAdditionalInformation('OrderKey');
1497
-
1498
- if (!is_array($orderkeys)) {
1499
- // $errMsg = "Impossible to capture: orderkeys must be an array";
1500
- // $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1501
- //
1502
- // $helperLog->error($errMsg);
1503
- // Mage::throwException($errMsg);
1504
- $orderkeys = array($orderkeys);
1505
- }
1506
-
1507
- foreach ($orderkeys as $orderkey) {
1508
- $data['ManageOrderOperationEnum'] = 'Cancel';
1509
- $data['OrderKey'] = $orderkey;
1510
-
1511
- //Call Gateway Api
1512
- $api = Mage::getModel('mundipagg/api');
1513
-
1514
- $void = $api->manageOrderRequest($data, $this);
1515
-
1516
- // Xml
1517
- $xml = $void['result'];
1518
- $json = json_encode($xml);
1519
-
1520
- $void['result'] = array();
1521
- $void['result'] = json_decode($json, true);
1522
-
1523
- // We record transaction(s)
1524
- if (count($void['result']['CreditCardTransactionResultCollection']) > 0) {
1525
- if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
1526
- $trans = $void['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
1527
-
1528
- $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans);
1529
- } else {
1530
- foreach ($void['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
1531
- $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans, $key);
1532
- }
1533
- }
1534
- }
1535
-
1536
- if (isset($void['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'])) {
1537
- $order = $payment->getOrder();
1538
- $order->setBaseDiscountRefunded($order->getBaseDiscountInvoiced());
1539
- $order->setBaseShippingRefunded($order->getBaseShippingAmount());
1540
- $order->setBaseShippingTaxRefunded($order->getBaseShippingTaxInvoiced());
1541
- $order->setBaseSubtotalRefunded($order->getBaseSubtotalInvoiced());
1542
- $order->setBaseTaxRefunded($order->getBaseTaxInvoiced());
1543
- $order->setBaseTotalOnlineRefunded($order->getBaseGrandTotal());
1544
- $order->setDiscountRefunded($order->getDiscountInvoiced());
1545
- $order->setShippinRefunded($order->getShippingInvoiced());
1546
- $order->setShippinTaxRefunded($order->getShippingTaxAmount());
1547
- $order->setSubtotalRefunded($order->getSubtotalInvoiced());
1548
- $order->setTaxRefunded($order->getTaxInvoiced());
1549
- $order->setTotalOnlineRefunded($order->getBaseGrandTotal());
1550
- $order->setTotalRefunded($order->getBaseGrandTotal());
1551
- $order->save();
1552
-
1553
- return $this;
1554
- } else {
1555
- $error = Mage::helper('mundipagg')->__('Unable to void order.');
1556
-
1557
- //Log error
1558
- Mage::log($error, null, 'Uecommerce_Mundipagg.log');
1559
-
1560
- Mage::throwException($error);
1561
- }
1562
- }
1563
- } else {
1564
- Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
1565
- }
1566
- }
1567
-
1568
- /**
1569
- * Check refund availability
1570
- *
1571
- * @return bool
1572
- */
1573
- public function canRefund() {
1574
- return $this->_canRefund;
1575
- }
1576
-
1577
- /**
1578
- * Set refund transaction id to payment object for informational purposes
1579
- * Candidate to be deprecated:
1580
- * there can be multiple refunds per payment, thus payment.refund_transactionId doesn't make big sense
1581
- *
1582
- * @param Mage_Sales_Model_Order_Invoice $invoice
1583
- * @param Mage_Sales_Model_Order_Payment $payment
1584
- * @return Mage_Payment_Model_Method_Abstract
1585
- */
1586
- public function processBeforeRefund($invoice, $payment) {
1587
- $payment->setRefundTransactionId($invoice->getTransactionId());
1588
-
1589
- return $this;
1590
- }
1591
-
1592
- /**
1593
- * Refund specified amount for payment
1594
- *
1595
- * @param Varien_Object $payment
1596
- * @param float $amount
1597
- *
1598
- * @return Mage_Payment_Model_Abstract
1599
- */
1600
- public function refund(Varien_Object $payment, $amount) {
1601
- if (!$this->canRefund()) {
1602
- Mage::throwException(Mage::helper('payment')->__('Refund action is not available.'));
1603
- }
1604
-
1605
- //Prepare data in order to refund
1606
- if ($payment->getAdditionalInformation('OrderKey')) {
1607
- $data['OrderKey'] = $payment->getAdditionalInformation('OrderKey');
1608
- $data['ManageOrderOperationEnum'] = 'Void';
1609
-
1610
- //Call Gateway Api
1611
- $api = Mage::getModel('mundipagg/api');
1612
-
1613
- $refund = $api->manageOrderRequest($data, $this);
1614
-
1615
- // Xml
1616
- $xml = $refund['result'];
1617
- $json = json_encode($xml);
1618
-
1619
- $refund['result'] = array();
1620
- $refund['result'] = json_decode($json, true);
1621
-
1622
- // We record transaction(s)
1623
- if (count($refund['result']['CreditCardTransactionResultCollection']) > 0) {
1624
- if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
1625
- $trans = $refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
1626
-
1627
- $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans);
1628
- } else {
1629
- foreach ($refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
1630
- $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans, $key);
1631
- }
1632
- }
1633
- }
1634
-
1635
- if (isset($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult)) {
1636
- if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
1637
- $capturedAmountInCents = $manageOrderResult->CreditCardTransactionResultCollection->CreditCardTransactionResult->CapturedAmountInCents;
1638
- } else {
1639
- $capturedAmountInCents = 0;
1640
-
1641
- foreach ($refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
1642
- $capturedAmountInCents += $trans['CapturedAmountInCents'];
1643
- }
1644
- }
1645
-
1646
- $order = $payment->getOrder();
1647
- $order->setBaseDiscountRefunded($order->getBaseDiscountInvoiced());
1648
- $order->setBaseShippingRefunded($order->getBaseShippingAmount());
1649
- $order->setBaseShippingTaxRefunded($order->getBaseShippingTaxInvoiced());
1650
- $order->setBaseSubtotalRefunded($order->getBaseSubtotalInvoiced());
1651
- $order->setBaseTaxRefunded($order->getBaseTaxInvoiced());
1652
- $order->setBaseTotalOnlineRefunded($capturedAmountInCents * 0.01);
1653
- $order->setDiscountRefunded($order->getDiscountInvoiced());
1654
- $order->setShippinRefunded($order->getShippingInvoiced());
1655
- $order->setShippinTaxRefunded($order->getShippingTaxAmount());
1656
- $order->setSubtotalRefunded($order->getSubtotalInvoiced());
1657
- $order->setTaxRefunded($order->getTaxInvoiced());
1658
- $order->setTotalOnlineRefunded($capturedAmountInCents * 0.01);
1659
- $order->setTotalRefunded($capturedAmountInCents * 0.01);
1660
- $order->save();
1661
-
1662
- return $this;
1663
- } else {
1664
- $error = Mage::helper('mundipagg')->__('Unable to refund order.');
1665
-
1666
- //Log error
1667
- Mage::log($error, null, 'Uecommerce_Mundipagg.log');
1668
-
1669
- Mage::throwException($error);
1670
- }
1671
- } else {
1672
- Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
1673
- }
1674
- }
1675
-
1676
- /**
1677
- * Validate
1678
- */
1679
- public function validate() {
1680
- parent::validate();
1681
-
1682
- $currencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
1683
-
1684
- if (!in_array($currencyCode, $this->_allowCurrencyCode)) {
1685
- Mage::throwException(Mage::helper('payment')->__('Selected currency code (' . $currencyCode . ') is not compatabile with Mundipagg'));
1686
- }
1687
-
1688
- $info = $this->getInfoInstance();
1689
-
1690
- $errorMsg = array();
1691
-
1692
- // Check if we are dealing with a new Credit Card
1693
- $isToken = $info->getAdditionalInformation('mundipagg_creditcard_token_1_1');
1694
-
1695
- if ($info->getAdditionalInformation('PaymentMethod') == 'mundipagg_creditcard' && ($isToken == '' || $isToken == 'new')) {
1696
- $availableTypes = $this->getCcTypes();
1697
-
1698
- $ccNumber = $info->getCcNumber();
1699
-
1700
- // refresh quote to remove promotions from others payment methods
1701
- try {
1702
- $this->getQuote()->save();
1703
-
1704
- } catch (Exception $e) {
1705
- $errorMsg[] = $e->getMessage();
1706
-
1707
- }
1708
-
1709
- // remove credit card number delimiters such as "-" and space
1710
- $ccNumber = preg_replace('/[\-\s]+/', '', $ccNumber);
1711
- $info->setCcNumber($ccNumber);
1712
-
1713
- if (in_array($info->getCcType(), $availableTypes)) {
1714
- if (!Mage::helper('mundipagg')->validateCcNum($ccNumber) && $info->getCcType() != 'HI') {
1715
- $errorMsg[] = Mage::helper('payment')->__('Invalid Credit Card Number');
1716
- }
1717
- } else {
1718
- $errorMsg[] = Mage::helper('payment')->__('Credit card type is not allowed for this payment method.');
1719
- }
1720
-
1721
- if (!$info->getCcType()) {
1722
- $errorMsg[] = Mage::helper('payment')->__('Please select your credit card type.');
1723
- }
1724
-
1725
- if (!$info->getCcOwner()) {
1726
- $errorMsg[] = Mage::helper('payment')->__('Please enter your credit card holder name.');
1727
- }
1728
-
1729
- if ($info->getCcType() && $info->getCcType() != 'SS' && !Mage::helper('mundipagg')->validateExpDate('20' . $info->getCcExpYear(), $info->getCcExpMonth())) {
1730
- $errorMsg[] = Mage::helper('payment')->__('Incorrect credit card expiration date.');
1731
- }
1732
- }
1733
-
1734
- if ($errorMsg) {
1735
- $json = json_encode($errorMsg);
1736
- Mage::throwException($json);
1737
- }
1738
-
1739
- return $this;
1740
- }
1741
-
1742
- /**
1743
- * Redirect Url
1744
- *
1745
- * @return void
1746
- */
1747
- public function getOrderPlaceRedirectUrl() {
1748
- $statusWithError = Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum::WITH_ERROR;
1749
-
1750
- switch (Mage::getSingleton('checkout/session')->getApprovalRequestSuccess()) {
1751
- case 'debit':
1752
- $redirectUrl = Mage::getSingleton('checkout/session')->getBankRedirectUrl();
1753
- break;
1754
-
1755
- case 'success':
1756
- $redirectUrl = Mage::getUrl('mundipagg/standard/success', array('_secure' => true));
1757
- break;
1758
-
1759
- case $statusWithError:
1760
- $redirectUrl = Mage::getUrl('mundipagg/standard/success', array('_secure' => true));
1761
- break;
1762
-
1763
- case 'partial':
1764
- $redirectUrl = Mage::getUrl('mundipagg/standard/partial', array('_secure' => true));
1765
- break;
1766
-
1767
- case 'cancel':
1768
- $redirectUrl = Mage::getUrl('mundipagg/standard/cancel', array('_secure' => true));
1769
- break;
1770
-
1771
- default:
1772
- $redirectUrl = Mage::getUrl('mundipagg/standard/cancel', array('_secure' => true));
1773
- break;
1774
- }
1775
-
1776
- return $redirectUrl;
1777
- }
1778
-
1779
- public function prepare() {
1780
-
1781
- }
1782
-
1783
- /**
1784
- * Get payment methods
1785
- */
1786
- public function getPaymentMethods() {
1787
- $payment_methods = $this->getConfigData('payment_methods');
1788
-
1789
- if ($payment_methods != '') {
1790
- $payment_methods = explode(",", $payment_methods);
1791
- } else {
1792
- $payment_methods = array();
1793
- }
1794
-
1795
- return $payment_methods;
1796
- }
1797
-
1798
- /**
1799
- * CCards
1800
- */
1801
- public function getCcTypes() {
1802
- $ccTypes = Mage::getStoreConfig('payment/mundipagg_standard/cc_types');
1803
-
1804
- if ($ccTypes != '') {
1805
- $ccTypes = explode(",", $ccTypes);
1806
- } else {
1807
- $ccTypes = array();
1808
- }
1809
-
1810
- return $ccTypes;
1811
- }
1812
-
1813
- /**
1814
- * Reset interest
1815
- */
1816
- public function resetInterest($info) {
1817
- if ($info->getQuote()->getMundipaggInterest() > 0 || $info->getQuote()->getMundipaggBaseInterest() > 0) {
1818
- $info->getQuote()->setMundipaggInterest(0.0);
1819
- $info->getQuote()->setMundipaggBaseInterest(0.0);
1820
- $info->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
1821
- $info->getQuote()->save();
1822
- }
1823
-
1824
- return $info;
1825
- }
1826
-
1827
- /**
1828
- * Apply interest
1829
- */
1830
- public function applyInterest($info, $interest) {
1831
- $info->getQuote()->setMundipaggInterest($info->getQuote()->getStore()->convertPrice($interest, false));
1832
- $info->getQuote()->setMundipaggBaseInterest($interest);
1833
- $info->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
1834
- $info->getQuote()->save();
1835
- }
1836
-
1837
- /**
1838
- * Remove interest to order when the total is not allowed.
1839
- *
1840
- * @param Mage_Sales_Model_Order $order
1841
- * @param float $interest
1842
- */
1843
- protected function removeInterestToOrder(Mage_Sales_Model_Order $order, $interest) {
1844
- $mundipaggInterest = $order->getMundipaggInterest();
1845
- $setInterest = (float)($mundipaggInterest - $interest);
1846
- $order->setMundipaggInterest(($setInterest) ? $setInterest : 0);
1847
- $order->setMundipaggBaseInterest(($setInterest) ? $setInterest : 0);
1848
- $order->setGrandTotal(($order->getGrandTotal() - $interest));
1849
- $order->setBaseGrandTotal(($order->getBaseGrandTotal() - $interest));
1850
- $order->save();
1851
- $info = $this->getInfoInstance();
1852
- $info->setPaymentInterest(($info->getPaymentInterest() - $setInterest));
1853
- $info->save();
1854
-
1855
- }
1856
-
1857
- /**
1858
- * Add interest to order
1859
- */
1860
- protected function addInterestToOrder(Mage_Sales_Model_Order $order, $interest) {
1861
- $mundipaggInterest = $order->getMundipaggInterest();
1862
- $setInterest = (float)($mundipaggInterest + $interest);
1863
- $order->setMundipaggInterest(($setInterest) ? $setInterest : 0);
1864
- $order->setMundipaggBaseInterest(($setInterest) ? $setInterest : 0);
1865
- $order->setGrandTotal(($order->getGrandTotal() + $interest));
1866
- $order->setBaseGrandTotal(($order->getBaseGrandTotal() + $interest));
1867
- $order->save();
1868
- }
1869
-
1870
- /**
1871
- * Add payment transaction
1872
- *
1873
- * @param Mage_Sales_Model_Order_Payment $payment
1874
- * @param string $transactionId
1875
- * @param string $transactionType
1876
- * @param array $transactionAdditionalInfo
1877
- * @return null|Mage_Sales_Model_Order_Payment_Transaction
1878
- */
1879
- public function _addTransaction(Mage_Sales_Model_Order_Payment $payment, $transactionId, $transactionType, $transactionAdditionalInfo, $num = 0) {
1880
- // Num
1881
- $num = $num + 1;
1882
-
1883
- // Transaction
1884
- $transaction = Mage::getModel('sales/order_payment_transaction');
1885
- $transaction->setOrderPaymentObject($payment);
1886
-
1887
- $transaction = $transaction->loadByTxnId($transactionId . '-' . $transactionType);
1888
-
1889
- $transaction->setTxnType($transactionType);
1890
- $transaction->setTxnId($transactionId . '-' . $transactionType);
1891
-
1892
- if ($transactionType == 'authorization') {
1893
- if ($transactionAdditionalInfo['CreditCardTransactionStatus'] == 'AuthorizedPendingCapture') {
1894
- $transaction->setIsClosed(0);
1895
- }
1896
-
1897
- if ($transactionAdditionalInfo['CreditCardTransactionStatus'] == 'NotAuthorized') {
1898
- $transaction->setIsClosed(1);
1899
- }
1900
- }
1901
-
1902
- foreach ($transactionAdditionalInfo as $transKey => $value) {
1903
-
1904
- if (!is_array($value)) {
1905
- $transaction->setAdditionalInformation($transKey, htmlspecialchars_decode($value));
1906
- $payment->setAdditionalInformation($num . '_' . $transKey, htmlspecialchars_decode($value));
1907
-
1908
- } else {
1909
-
1910
- if (empty($value)) {
1911
- $transaction->setAdditionalInformation($transKey, '');
1912
- $payment->setAdditionalInformation($num . '_' . $transKey, '');
1913
-
1914
- } else {
1915
- foreach ($value as $key2 => $value2) {
1916
- $transaction->setAdditionalInformation($key2, htmlspecialchars_decode($value2));
1917
- $payment->setAdditionalInformation($num . '_' . $key2, htmlspecialchars_decode($value2));
1918
- }
1919
- }
1920
- }
1921
- }
1922
-
1923
- return $transaction->save();
1924
- }
1925
-
1926
- /**
1927
- * Cancel order or not if is in offline retry time
1928
- *
1929
- * @author Ruan Azevedo <razevedo@mundipagg.com>
1930
- * @since 2016-06-21
1931
- * @param string $orderIncrementId
1932
- */
1933
- private function offlineRetryCancelOrSuccessOrder($orderIncrementId) {
1934
- $offlineRetryIsEnabled = Uecommerce_Mundipagg_Model_Offlineretry::offlineRetryIsEnabled();
1935
- $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1936
- $logLabel = "Order #{$orderIncrementId}";
1937
-
1938
- if ($offlineRetryIsEnabled == false) {
1939
- $helperLog->info("{$logLabel} | Payment not authorized and store don't have offline retry, order will be canceled.");
1940
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
1941
-
1942
- return;
1943
- }
1944
-
1945
- $api = new Uecommerce_Mundipagg_Model_Api();
1946
-
1947
- if ($api->orderIsInOfflineRetry($orderIncrementId)) {
1948
- $message = "{$logLabel} | payment not authorized but order is in offline retry yet, not cancel.";
1949
-
1950
- $helperLog->info($message);
1951
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1952
-
1953
- }/* else {
1954
- $helperLog->info("{$logLabel} | Payment not authorized and order is not on offline retry.");
1955
- Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
1956
- }*/
1957
- }
1958
-
1959
- /**
1960
- * @param Mage_Sales_Model_Order $order
1961
- * @throws Exception
1962
- */
1963
- public static function transactionWithError(Mage_Sales_Model_Order $order, $comment = true) {
1964
- try {
1965
- if ($comment) {
1966
- $order->setState(
1967
- 'pending',
1968
- 'mundipagg_with_error',
1969
- 'With Error',
1970
- false
1971
- );
1972
- } else {
1973
- $order->setStatus('mundipagg_with_error');
1974
- }
1975
-
1976
- $order->save();
1977
-
1978
- } catch (Exception $e) {
1979
- $errMsg = "Unable to modify order status to 'mundipagg_with_error: {$e->getMessage()}";
1980
-
1981
- throw new Exception($errMsg);
1982
- }
1983
- }
1984
-
1985
  }
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_Standard extends Mage_Payment_Model_Method_Abstract {
31
+ /**
32
+ * Availability options
33
+ */
34
+ protected $_code = 'mundipagg_standard';
35
+ protected $_formBlockType = 'mundipagg/standard_form';
36
+ protected $_infoBlockType = 'mundipagg/info';
37
+ protected $_isGateway = true;
38
+ protected $_canOrder = true;
39
+ protected $_canAuthorize = true;
40
+ protected $_canCapture = true;
41
+ protected $_canCapturePartial = false;
42
+ protected $_canRefund = true;
43
+ protected $_canVoid = true;
44
+ protected $_canUseInternal = false;
45
+ protected $_canUseCheckout = false;
46
+ protected $_canUseForMultishipping = true;
47
+ protected $_canSaveCc = false;
48
+ protected $_canFetchTransactionInfo = false;
49
+ protected $_canManageRecurringProfiles = false;
50
+ protected $_allowCurrencyCode = array('BRL', 'USD', 'EUR');
51
+ protected $_isInitializeNeeded = true;
52
+
53
+ /**
54
+ * Transaction ID
55
+ **/
56
+ protected $_transactionId = null;
57
+
58
+ /**
59
+ * CreditCardOperationEnum na gateway
60
+ * @var $CreditCardOperationEnum varchar
61
+ */
62
+ private $_creditCardOperationEnum;
63
+
64
+ public function getUrl() {
65
+ return $this->url;
66
+ }
67
+
68
+ public function setUrl($url) {
69
+ $this->url = $url;
70
+ }
71
+
72
+ public function setmerchantKey($merchantKey) {
73
+ $this->merchantKey = $merchantKey;
74
+ }
75
+
76
+ public function getmerchantKey() {
77
+ return $this->merchantKey;
78
+ }
79
+
80
+ public function setEnvironment($environment) {
81
+ $this->environment = $environment;
82
+ }
83
+
84
+ public function getEnvironment() {
85
+ return $this->environment;
86
+ }
87
+
88
+ public function setPaymentMethodCode($paymentMethodCode) {
89
+ $this->paymentMethodCode = $paymentMethodCode;
90
+ }
91
+
92
+ public function getPaymentMethodCode() {
93
+ return $this->paymentMethodCode;
94
+ }
95
+
96
+ public function setAntiFraud($antiFraud) {
97
+ $this->antiFraud = $antiFraud;
98
+ }
99
+
100
+ public function getAntiFraud() {
101
+ return $this->antiFraud;
102
+ }
103
+
104
+ public function setBankNumber($bankNumber) {
105
+ $this->bankNumber = $bankNumber;
106
+ }
107
+
108
+ public function getBankNumber() {
109
+ return $this->bankNumber;
110
+ }
111
+
112
+ public function setDebug($debug) {
113
+ $this->_debug = $debug;
114
+ }
115
+
116
+ public function getDebug() {
117
+ return $this->_debug;
118
+ }
119
+
120
+ public function setDiasValidadeBoleto($diasValidadeBoleto) {
121
+ $this->_diasValidadeBoleto = $diasValidadeBoleto;
122
+ }
123
+
124
+ public function getDiasValidadeBoleto() {
125
+ return $this->_diasValidadeBoleto;
126
+ }
127
+
128
+ public function setInstrucoesCaixa($instrucoesCaixa) {
129
+ $this->_instrucoesCaixa = $instrucoesCaixa;
130
+ }
131
+
132
+ public function getInstrucoesCaixa() {
133
+ return $this->_instrucoesCaixa;
134
+ }
135
+
136
+ public function setCreditCardOperationEnum($creditCardOperationEnum) {
137
+ $this->_creditCardOperationEnum = $creditCardOperationEnum;
138
+ }
139
+
140
+ public function getCreditCardOperationEnum() {
141
+ return $this->_creditCardOperationEnum;
142
+ }
143
+
144
+ public function setParcelamento($parcelamento) {
145
+ $this->parcelamento = $parcelamento;
146
+ }
147
+
148
+ public function getParcelamento() {
149
+ return $this->parcelamento;
150
+ }
151
+
152
+ public function setParcelamentoMax($parcelamentoMax) {
153
+ $this->parcelamentoMax = $parcelamentoMax;
154
+ }
155
+
156
+ public function getParcelamentoMax() {
157
+ return $this->parcelamentoMax;
158
+ }
159
+
160
+ public function setPaymentAction($paymentAction) {
161
+ $this->paymentAction = $paymentAction;
162
+ }
163
+
164
+ public function getPaymentAction() {
165
+ return $this->paymentAction;
166
+ }
167
+
168
+ public function setCieloSku($cieloSku) {
169
+ $this->cieloSku = $cieloSku;
170
+ }
171
+
172
+ public function getCieloSku() {
173
+ return $this->cieloSku;
174
+ }
175
+
176
+ public function __construct() {
177
+ $this->setEnvironment($this->getConfigData('environment'));
178
+ $this->setPaymentAction($this->getConfigData('payment_action'));
179
+
180
+ switch ($this->getConfigData('environment')) {
181
+ case 'localhost':
182
+ case 'development':
183
+ case 'staging':
184
+ default:
185
+ $this->setmerchantKey(trim($this->getConfigData('merchantKeyStaging')));
186
+ $this->setUrl(trim($this->getConfigData('apiUrlStaging')));
187
+ $this->setAntiFraud($this->getConfigData('antifraud'));
188
+ $this->setPaymentMethodCode(1);
189
+ $this->setBankNumber(341);
190
+ $this->setParcelamento($this->getConfigData('parcelamento'));
191
+ $this->setParcelamentoMax($this->getConfigData('parcelamento_max'));
192
+ $this->setDebug($this->getConfigData('debug'));
193
+ $this->setEnvironment($this->getConfigData('environment'));
194
+ $this->setCieloSku($this->getConfigData('cielo_sku'));
195
+ break;
196
+
197
+ case 'production':
198
+ $this->setmerchantKey(trim($this->getConfigData('merchantKeyProduction')));
199
+ $this->setUrl(trim($this->getConfigData('apiUrlProduction')));
200
+ $this->setAntiFraud($this->getConfigData('antifraud'));
201
+ $this->setParcelamento($this->getConfigData('parcelamento'));
202
+ $this->setParcelamentoMax($this->getConfigData('parcelamento_max'));
203
+ $this->setDebug($this->getConfigData('debug'));
204
+ $this->setEnvironment($this->getConfigData('environment'));
205
+ $this->setCieloSku($this->getConfigData('cielo_sku'));
206
+ break;
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Armazena as informações passadas via formulário no frontend
212
+ * @access public
213
+ * @param array $data
214
+ * @return Uecommerce_Mundipagg_Model_Standard
215
+ */
216
+ public function assignData($data) {
217
+ if (!($data instanceof Varien_Object)) {
218
+ $data = new Varien_Object($data);
219
+ }
220
+
221
+ $info = $this->getInfoInstance();
222
+ $mundipagg = array();
223
+ $helper = Mage::helper('mundipagg');
224
+
225
+ foreach ($data->getData() as $id => $value) {
226
+ $mundipagg[$id] = $value;
227
+
228
+ // We verify if a CPF OR CNPJ is valid
229
+ $posTaxvat = strpos($id, 'taxvat');
230
+
231
+ if ($posTaxvat !== false && $value != '') {
232
+ if (!$helper->validateCPF($value) && !$helper->validateCNPJ($value)) {
233
+ $error = $helper->__('CPF or CNPJ is invalid');
234
+
235
+ Mage::throwException($error);
236
+ }
237
+ }
238
+ }
239
+
240
+ if (!empty($mundipagg)) {
241
+ $helperInstallments = Mage::helper('mundipagg/Installments');
242
+
243
+ //Set Mundipagg Data in Session
244
+ $session = Mage::getSingleton('checkout/session');
245
+ $session->setMundipaggData($mundipagg);
246
+
247
+ $info = $this->getInfoInstance();
248
+
249
+ if (isset($mundipagg['mundipagg_type'])) {
250
+ $info->setAdditionalInformation('PaymentMethod', $mundipagg['method']);
251
+
252
+ switch ($mundipagg['method']) {
253
+ case 'mundipagg_creditcard':
254
+ if (isset($mundipagg['mundipagg_creditcard_1_1_cc_type'])) {
255
+ if (array_key_exists('mundipagg_creditcard_credito_parcelamento_1_1', $mundipagg)) {
256
+ if ($mundipagg['mundipagg_creditcard_credito_parcelamento_1_1'] > $helperInstallments->getMaxInstallments($mundipagg['mundipagg_creditcard_1_1_cc_type'])) {
257
+ Mage::throwException($helper->__('it is not possible to divide by %s times', $mundipagg['mundipagg_creditcard_credito_parcelamento_1_1']));
258
+ }
259
+ }
260
+ $info->setCcType($mundipagg['mundipagg_creditcard_1_1_cc_type'])
261
+ ->setCcOwner($mundipagg['mundipagg_creditcard_cc_holder_name_1_1'])
262
+ ->setCcLast4(substr($mundipagg['mundipagg_creditcard_1_1_cc_number'], -4))
263
+ ->setCcNumber($mundipagg['mundipagg_creditcard_1_1_cc_number'])
264
+ ->setCcCid($mundipagg['mundipagg_creditcard_cc_cid_1_1'])
265
+ ->setCcExpMonth($mundipagg['mundipagg_creditcard_expirationMonth_1_1'])
266
+ ->setCcExpYear($mundipagg['mundipagg_creditcard_expirationYear_1_1']);
267
+ } else {
268
+ $info->setAdditionalInformation('mundipagg_creditcard_token_1_1', $mundipagg['mundipagg_creditcard_token_1_1']);
269
+ }
270
+
271
+ break;
272
+
273
+ default:
274
+
275
+ $info->setCcType(null)
276
+ ->setCcOwner(null)
277
+ ->setCcLast4(null)
278
+ ->setCcNumber(null)
279
+ ->setCcCid(null)
280
+ ->setCcExpMonth(null)
281
+ ->setCcExpYear(null);
282
+
283
+ break;
284
+ }
285
+
286
+ foreach ($mundipagg as $key => $value) {
287
+ // We don't save CcNumber
288
+ $posCcNumber = strpos($key, 'number');
289
+
290
+ // We don't save Security Code
291
+ $posCid = strpos($key, 'cid');
292
+
293
+ // We don't save Cc Holder name
294
+ $posHolderName = strpos($key, 'holder_name');
295
+
296
+ if ($value != '' &&
297
+ $posCcNumber === false &&
298
+ $posCid === false &&
299
+ $posHolderName === false
300
+ ) {
301
+ if (strpos($key, 'cc_type')) {
302
+ $value = $helper->issuer($value);
303
+ }
304
+
305
+ $info->setAdditionalInformation($key, $value);
306
+ }
307
+ }
308
+
309
+ // We check if quote grand total is equal to installments sum
310
+ if ($mundipagg['method'] != 'mundipagg_boleto'
311
+ && $mundipagg['method'] != 'mundipagg_creditcardoneinstallment'
312
+ && $mundipagg['method'] != 'mundipagg_creditcard'
313
+ ) {
314
+ $num = $helper->getCreditCardsNumber($mundipagg['method']);
315
+ $method = $helper->getPaymentMethod($num);
316
+
317
+ (float)$grandTotal = $info->getQuote()->getGrandTotal();
318
+ (float)$totalInstallmentsToken = 0;
319
+ (float)$totalInstallmentsNew = 0;
320
+ (float)$totalInstallments = 0;
321
+
322
+ for ($i = 1; $i <= $num; $i++) {
323
+
324
+ if (isset($mundipagg[$method . '_token_' . $num . '_' . $i]) && $mundipagg[$method . '_token_' . $num . '_' . $i] != 'new') {
325
+ (float)$value = str_replace(',', '.', $mundipagg[$method . '_value_' . $num . '_' . $i]);
326
+
327
+ if (array_key_exists($method . '_credito_parcelamento_' . $num . '_' . $i, $mundipagg)) {
328
+ if (!array_key_exists($method . '_' . $num . '_' . $i . '_cc_type', $mundipagg)) {
329
+ $cardonFile = Mage::getModel('mundipagg/cardonfile')->load($mundipagg[$method . '_token_' . $num . '_' . $i]);
330
+
331
+ $mundipagg[$method . '_' . $num . '_' . $i . '_cc_type'] = Mage::helper('mundipagg')->getCardTypeByIssuer($cardonFile->getCcType());
332
+ }
333
+
334
+ if ($mundipagg[$method . '_credito_parcelamento_' . $num . '_' . $i] > $helperInstallments->getMaxInstallments($mundipagg[$method . '_' . $num . '_' . $i . '_cc_type'], $value)) {
335
+ Mage::throwException($helper->__('it is not possible to divide by %s times', $mundipagg[$method . '_credito_parcelamento_' . $num . '_' . $i]));
336
+ }
337
+ }
338
+
339
+ (float)$totalInstallmentsToken += $value;
340
+ } else {
341
+ (float)$value = str_replace(',', '.', $mundipagg[$method . '_new_value_' . $num . '_' . $i]);
342
+
343
+ if (array_key_exists($method . '_new_credito_parcelamento_' . $num . '_' . $i, $mundipagg)) {
344
+ if ($mundipagg[$method . '_new_credito_parcelamento_' . $num . '_' . $i] > $helperInstallments->getMaxInstallments($mundipagg[$method . '_' . $num . '_' . $i . '_cc_type'], $value)) {
345
+ Mage::throwException($helper->__('it is not possible to divide by %s times', $mundipagg[$method . '_new_credito_parcelamento_' . $num . '_' . $i]));
346
+ }
347
+ }
348
+
349
+ (float)$totalInstallmentsNew += $value;
350
+ }
351
+ }
352
+
353
+ // Total Installments from token and Credit Card
354
+ (float)$totalInstallments = $totalInstallmentsToken + $totalInstallmentsNew;
355
+
356
+ // If an amount has already been authorized
357
+ if (isset($mundipagg['multi']) && Mage::getSingleton('checkout/session')->getAuthorizedAmount()) {
358
+ (float)$totalInstallments += (float)Mage::getSingleton('checkout/session')->getAuthorizedAmount();
359
+
360
+ // Unset session
361
+ Mage::getSingleton('checkout/session')->setAuthorizedAmount();
362
+ }
363
+
364
+ $epsilon = 0.00001;
365
+
366
+ // $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
367
+ // $helperLog->info("totalInstallments: {$totalInstallments}");
368
+ // $helperLog->info("grandTotal: {$grandTotal}");
369
+ // $helperLog->info("getPaymentInterest: {$info->getPaymentInterest()}");
370
+ // $helperLog->info("epsilon: {$epsilon}");
371
+
372
+ // if ($totalInstallments > 0 && ($grandTotal - $totalInstallments - $info->getPaymentInterest())) {
373
+ // Mage::throwException(Mage::helper('payment')->__('Installments does not match with quote.'));
374
+ // }
375
+ }
376
+ } else {
377
+ if (isset($mundipagg['method'])) {
378
+ $info->setAdditionalInformation('PaymentMethod', $mundipagg['method']);
379
+ }
380
+ }
381
+ }
382
+
383
+ // Get customer_id from Quote (payment made on site) or from POST (payment made from API)
384
+ if (Mage::getSingleton('customer/session')->isLoggedIn()) {
385
+ if ($this->getQuote()->getCustomer()->getEntityId()) {
386
+ $customerId = $this->getQuote()->getCustomer()->getEntityId();
387
+ }
388
+ } elseif (isset($mundipagg['entity_id'])) {
389
+ $customerId = $mundipagg['entity_id'];
390
+ }
391
+
392
+ // We verifiy if token is from customer
393
+ if (isset($customerId) && isset($mundipagg['method'])) {
394
+ $num = $helper->getCreditCardsNumber($mundipagg['method']);
395
+
396
+ if ($num == 0) {
397
+ $num = 1;
398
+ }
399
+
400
+ foreach ($mundipagg as $key => $value) {
401
+ $pos = strpos($key, 'token_' . $num);
402
+
403
+ if ($pos !== false && $value != '' && $value != 'new') {
404
+ $token = Mage::getModel('mundipagg/cardonfile')->load($value);
405
+
406
+ if ($token->getId() && $token->getEntityId() == $customerId) {
407
+ // Ok
408
+ $info->setAdditionalInformation('CreditCardBrandEnum_' . $key, $token->getCcType());
409
+ } else {
410
+ $error = $helper->__('Token not found');
411
+
412
+ //Log error
413
+ Mage::log($error, null, 'Uecommerce_Mundipagg.log');
414
+
415
+ Mage::throwException($error);
416
+ }
417
+ }
418
+ }
419
+ }
420
+
421
+ return $this;
422
+ }
423
+
424
+ /**
425
+ * Prepare info instance for save
426
+ *
427
+ * @return Mage_Payment_Model_Abstract
428
+ */
429
+ public function prepareSave() {
430
+ $info = $this->getInfoInstance();
431
+ if ($this->_canSaveCc) {
432
+ $info->setCcNumberEnc($info->encrypt($info->getCcNumber()));
433
+ }
434
+
435
+ $info->setCcNumber(null);
436
+
437
+ return $this;
438
+ }
439
+
440
+ /**
441
+ * Get payment quote
442
+ */
443
+ public function getPayment() {
444
+ return $this->getQuote()->getPayment();
445
+ }
446
+
447
+ /**
448
+ * Get Modulo session namespace
449
+ *
450
+ * @return Uecommerce_Mundipagg_Model_Session
451
+ */
452
+ public function getSession() {
453
+ return Mage::getSingleton('mundipagg/session');
454
+ }
455
+
456
+ /**
457
+ * Get checkout session namespace
458
+ *
459
+ * @return Mage_Checkout_Model_Session
460
+ */
461
+ public function getCheckout() {
462
+ return Mage::getSingleton('checkout/session');
463
+ }
464
+
465
+ /**
466
+ * Get current quote
467
+ *
468
+ * @return Mage_Sales_Model_Quote
469
+ */
470
+ public function getQuote() {
471
+ return $this->getCheckout()->getQuote();
472
+ }
473
+
474
+ /**
475
+ * Check order availability
476
+ *
477
+ * @return bool
478
+ */
479
+ public function canOrder() {
480
+ return $this->_canOrder;
481
+ }
482
+
483
+ /**
484
+ * Check authorize availability
485
+ *
486
+ * @return bool
487
+ */
488
+ public function canAuthorize() {
489
+ return $this->_canAuthorize;
490
+ }
491
+
492
+ /**
493
+ * Check capture availability
494
+ *
495
+ * @return bool
496
+ */
497
+ public function canCapture() {
498
+ return $this->_canCapture;
499
+ }
500
+
501
+ /**
502
+ * Instantiate state and set it to state object
503
+ *
504
+ * @param string $paymentAction
505
+ * @param Varien_Object
506
+ */
507
+ public function initialize($paymentAction, $stateObject) {
508
+ // TODO move initialize method to appropriate model (Boleto, Creditcard ...)
509
+ $paymentAction = $this->getPaymentAction();
510
+
511
+ switch ($paymentAction) {
512
+ case 'order':
513
+ $this->setCreditCardOperationEnum('AuthAndCapture');
514
+ break;
515
+
516
+ case 'authorize':
517
+ $this->setCreditCardOperationEnum('AuthOnly');
518
+ break;
519
+
520
+ case 'authorize_capture':
521
+ $this->setCreditCardOperationEnum('AuthAndCaptureWithDelay');
522
+ break;
523
+ }
524
+
525
+ $mageVersion = Mage::helper('mundipagg/version')->convertVersionToCommunityVersion(Mage::getVersion());
526
+
527
+ if (version_compare($mageVersion, '1.5.0', '<')) {
528
+ $orderAction = 'order';
529
+ } else {
530
+ $orderAction = Mage_Payment_Model_Method_Abstract::ACTION_ORDER;
531
+ }
532
+
533
+ $payment = $this->getInfoInstance();
534
+ $order = $payment->getOrder();
535
+
536
+ // If payment method is Boleto Bancário we call "order" method
537
+ if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_boleto') {
538
+ $this->order($payment, $order->getBaseTotalDue());
539
+
540
+ return $this;
541
+ }
542
+
543
+ // If it's a multi-payment types we force to ACTION_AUTHORIZE
544
+ $num = Mage::helper('mundipagg')->getCreditCardsNumber($payment->getAdditionalInformation('PaymentMethod'));
545
+
546
+ if ($num > 1) {
547
+ $paymentAction = Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE;
548
+ }
549
+
550
+ switch ($paymentAction) {
551
+ case Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE:
552
+ $payment->authorize($payment, $order->getBaseTotalDue());
553
+ break;
554
+
555
+ case Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE_CAPTURE:
556
+ $payment->authorize($payment, $order->getBaseTotalDue());
557
+ break;
558
+
559
+ case $orderAction:
560
+ $this->order($payment, $order->getBaseTotalDue());
561
+ break;
562
+
563
+ default:
564
+ $this->order($payment, $order->getBaseTotalDue());
565
+ break;
566
+ }
567
+ }
568
+
569
+ /**
570
+ * Authorize payment abstract method
571
+ *
572
+ * @param Varien_Object $payment
573
+ * @param float $amount
574
+ *
575
+ * @return Mage_Payment_Model_Abstract
576
+ */
577
+ public function authorize(Varien_Object $payment, $amount) {
578
+ try {
579
+ if (!$this->canAuthorize()) {
580
+ Mage::throwException(Mage::helper('payment')->__('Authorize action is not available.'));
581
+ }
582
+
583
+ // Load order
584
+ $order = $payment->getOrder();
585
+
586
+ // Proceed to authorization on Gateway
587
+ $resultPayment = $this->doPayment($payment, $order);
588
+
589
+ // We record transaction(s)
590
+ if (isset($resultPayment['result'])) {
591
+ $xml = $resultPayment['result'];
592
+ $json = json_encode($xml);
593
+
594
+ $resultPayment['result'] = array();
595
+ $resultPayment['result'] = json_decode($json, true);
596
+
597
+ if (isset($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult)) {
598
+ if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
599
+ $trans = $resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
600
+
601
+ $transaction = $this->_addTransaction($payment, $trans['TransactionKey'], Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH, $trans);
602
+ } else {
603
+ foreach ($resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
604
+ $transaction = $this->_addTransaction($payment, $trans['TransactionKey'], Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH, $trans, $key);
605
+ }
606
+ }
607
+ }
608
+ }
609
+
610
+ // Return
611
+ if (isset($resultPayment['error'])) {
612
+ try {
613
+ $payment->setSkipOrderProcessing(true)->save();
614
+
615
+ Mage::throwException(Mage::helper('mundipagg')->__($resultPayment['ErrorDescription']));
616
+ } catch (Exception $e) {
617
+ Mage::logException($e);
618
+
619
+ return $this;
620
+ }
621
+ } else {
622
+ // Send new order email when not in admin
623
+ if (Mage::app()->getStore()->getCode() != 'admin') {
624
+ $order->sendNewOrderEmail();
625
+ }
626
+
627
+ if (isset($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult)) {
628
+ $creditCardTransactionResultCollection = $xml->CreditCardTransactionResultCollection->CreditCardTransactionResult;
629
+
630
+ // We can capture only if:
631
+ // 1. Multiple Credit Cards Payment
632
+ // 2. Anti fraud is disabled
633
+ // 3. Payment action is "AuthorizeAndCapture"
634
+ if (
635
+ count($creditCardTransactionResultCollection) > 1 &&
636
+ $this->getAntiFraud() == 0 &&
637
+ $this->getPaymentAction() == 'order' &&
638
+ $order->getPaymentAuthorizationAmount() == $order->getGrandTotal()
639
+ ) {
640
+ $this->captureAndcreateInvoice($payment);
641
+ }
642
+ }
643
+ }
644
+
645
+ return $this;
646
+
647
+ } catch (Exception $e) {
648
+ Mage::logException($e);
649
+ }
650
+ }
651
+
652
+ /**
653
+ * Capture payment abstract method
654
+ *
655
+ * @param Varien_Object $payment
656
+ * @param float $amount
657
+ *
658
+ * @return Mage_Payment_Model_Abstract
659
+ */
660
+ public function capture(Varien_Object $payment, $amount) {
661
+ $helper = Mage::helper('payment');
662
+
663
+ if (!$this->canCapture()) {
664
+ Mage::throwException($helper->__('Capture action is not available.'));
665
+ }
666
+
667
+ if ($payment->getAdditionalInformation('PaymentMethod') == 'mundipagg_boleto') {
668
+ Mage::throwException($helper->__('You cannot capture Boleto Bancário.'));
669
+ }
670
+
671
+ if ($this->getAntiFraud() == 1) {
672
+ Mage::throwException($helper->__('You cannot capture having anti fraud activated.'));
673
+ }
674
+
675
+ // Already captured
676
+ if ($payment->getAdditionalInformation('CreditCardTransactionStatusEnum') == 'Captured' || $payment->getAdditionalInformation('CreditCardTransactionStatus') == 'Captured') {
677
+ return $this;
678
+ }
679
+
680
+ // Prepare data in order to capture
681
+ if ($payment->getAdditionalInformation('OrderKey')) {
682
+ $transactions = Mage::getModel('sales/order_payment_transaction')
683
+ ->getCollection()
684
+ ->addAttributeToFilter('order_id', array('eq' => $payment->getOrder()->getEntityId()))
685
+ ->addAttributeToFilter('txn_type', array('eq' => 'authorization'));
686
+
687
+ foreach ($transactions as $key => $transaction) {
688
+ $TransactionKey = $transaction->getAdditionalInformation('TransactionKey');
689
+ $TransactionReference = $transaction->getAdditionalInformation('TransactionReference');
690
+ }
691
+
692
+ // $data['CreditCardTransactionCollection']['AmountInCents'] = $payment->getOrder()->getBaseGrandTotal() * 100;
693
+ // $data['CreditCardTransactionCollection']['TransactionKey'] = $TransactionKey;
694
+ // $data['CreditCardTransactionCollection']['TransactionReference'] = $TransactionReference;
695
+ $orderkeys = (array)$payment->getAdditionalInformation('OrderKey');
696
+
697
+ foreach ($orderkeys as $orderkey) {
698
+ $data['OrderKey'] = $orderkey;
699
+ $data['ManageOrderOperationEnum'] = 'Capture';
700
+
701
+ //Call Gateway Api
702
+ $api = Mage::getModel('mundipagg/api');
703
+
704
+ $capture = $api->manageOrderRequest($data, $this);
705
+
706
+ // Xml
707
+ $xml = $capture['result'];
708
+ $json = json_encode($xml);
709
+
710
+ $capture['result'] = array();
711
+ $capture['result'] = json_decode($json, true);
712
+
713
+ // Save transactions
714
+ if (isset($capture['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'])) {
715
+ if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
716
+ $trans = $capture['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
717
+
718
+ $this->_addTransaction($payment, $trans['TransactionKey'], Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE, $trans);
719
+ } else {
720
+ $CapturedAmountInCents = 0;
721
+
722
+ foreach ($capture['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
723
+ $TransactionKey = $trans['TransactionKey'];
724
+ $CapturedAmountInCents += $trans['CapturedAmountInCents'];
725
+ }
726
+
727
+ $trans = array();
728
+ $trans['CapturedAmountInCents'] = $CapturedAmountInCents;
729
+ $trans['Success'] = true;
730
+
731
+ $this->_addTransaction($payment, $TransactionKey, Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE, $trans);
732
+ }
733
+ } else {
734
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
735
+
736
+ return false;
737
+ }
738
+ }
739
+ } else {
740
+ Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
741
+
742
+ return false;
743
+ }
744
+ }
745
+
746
+ /**
747
+ * Capture payment abstract method
748
+ *
749
+ * @param Varien_Object $payment
750
+ * @param float $amount
751
+ *
752
+ * @return Mage_Payment_Model_Abstract
753
+ */
754
+ public function captureAndcreateInvoice(Varien_Object $payment) {
755
+ $order = $payment->getOrder();
756
+
757
+ // Capture
758
+ $capture = $this->capture($payment, $order->getGrandTotal());
759
+
760
+ // Error
761
+ if (!$capture) {
762
+ return $this;
763
+ }
764
+
765
+ // Create invoice
766
+ $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice(array());
767
+ $invoice->register();
768
+
769
+ $invoice->setCanVoidFlag(true);
770
+ $invoice->getOrder()->setIsInProcess(true);
771
+ $invoice->setState(2);
772
+
773
+ if (Mage::helper('sales')->canSendNewInvoiceEmail($order->getStoreId())) {
774
+ $invoice->setEmailSent(true);
775
+ $invoice->sendEmail();
776
+ }
777
+
778
+ $invoice->save();
779
+
780
+ $order->setBaseTotalPaid($order->getBaseGrandTotal());
781
+ $order->setTotalPaid($order->getBaseGrandTotal());
782
+ $order->addStatusHistoryComment('Captured online amount of R$' . $order->getBaseGrandTotal(), false);
783
+ $order->save();
784
+
785
+ return $this;
786
+ }
787
+
788
+ /**
789
+ * Order payment abstract method
790
+ *
791
+ * @param Varien_Object $payment
792
+ * @param float $amount
793
+ *
794
+ * @return Mage_Payment_Model_Abstract
795
+ */
796
+ public function order(Varien_Object $payment, $amount) {
797
+ if (!$this->canOrder()) {
798
+ Mage::throwException(Mage::helper('payment')->__('Order action is not available.'));
799
+ }
800
+
801
+ // Load order
802
+ $order = $payment->getOrder();
803
+
804
+ $order = Mage::getModel('sales/order')->loadByIncrementId($order->getRealOrderId());
805
+
806
+ // Proceed to payment on Gateway
807
+ $resultPayment = $this->doPayment($payment, $order);
808
+
809
+ // Return error
810
+ if (isset($resultPayment['error'])) {
811
+ try {
812
+ $mageVersion = Mage::helper('mundipagg/version')->convertVersionToCommunityVersion(Mage::getVersion());
813
+
814
+ if (version_compare($mageVersion, '1.5.0', '<')) {
815
+ $transactionType = 'payment';
816
+ } else {
817
+ $transactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER;
818
+ }
819
+
820
+ // Xml
821
+ $xml = $resultPayment['result'];
822
+ $json = json_encode($xml);
823
+
824
+ $resultPayment['result'] = array();
825
+ $resultPayment['result'] = json_decode($json, true);
826
+
827
+ // We record transaction(s)
828
+ if (isset($resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'])) {
829
+ if (count($resultPayment['result']['CreditCardTransactionResultCollection']) == 1) {
830
+ $trans = $resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
831
+
832
+ $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
833
+ } else {
834
+ foreach ($resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
835
+ $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans, $key);
836
+ }
837
+ }
838
+ }
839
+
840
+ if (isset($resultPayment['ErrorItemCollection'])) {
841
+ if (count($resultPayment['ErrorItemCollection']) == 1) {
842
+ foreach ($resultPayment['ErrorItemCollection']['ErrorItem'] as $key => $value) {
843
+ $payment->setAdditionalInformation($key, $value)->save();
844
+ }
845
+ } else {
846
+ foreach ($resultPayment['ErrorItemCollection'] as $key1 => $error) {
847
+ foreach ($error as $key2 => $value) {
848
+ $payment->setAdditionalInformation($key1 . '_' . $key2, $value)->save();
849
+ }
850
+ }
851
+ }
852
+ }
853
+
854
+ $payment->setSkipOrderProcessing(true)->save();
855
+
856
+ if (isset($resultPayment['ErrorDescription'])) {
857
+ $order->addStatusHistoryComment(Mage::helper('mundipagg')->__(htmlspecialchars_decode($resultPayment['ErrorDescription'])));
858
+ $order->save();
859
+
860
+ Mage::throwException(Mage::helper('mundipagg')->__($resultPayment['ErrorDescription']));
861
+ } else {
862
+ Mage::throwException(Mage::helper('mundipagg')->__('Erro'));
863
+ }
864
+ } catch (Exception $e) {
865
+ return $this;
866
+ }
867
+ } else {
868
+ if (isset($resultPayment['message'])) {
869
+ $mageVersion = Mage::helper('mundipagg/version')->convertVersionToCommunityVersion(Mage::getVersion());
870
+
871
+ if (version_compare($mageVersion, '1.5.0', '<')) {
872
+ $transactionType = 'payment';
873
+ } else {
874
+ $transactionType = Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER;
875
+ }
876
+
877
+ // Xml
878
+ $xml = $resultPayment['result'];
879
+ $json = json_encode($xml);
880
+
881
+ $resultPayment['result'] = array();
882
+ $resultPayment['result'] = json_decode($json, true);
883
+
884
+ switch ($resultPayment['message']) {
885
+ // Boleto
886
+ case 0:
887
+ $payment->setAdditionalInformation('BoletoUrl', $resultPayment['result']['BoletoTransactionResultCollection']['BoletoTransactionResult']['BoletoUrl']);
888
+
889
+ // In order to show "Print Boleto" link in order email
890
+ $order->getPayment()->setAdditionalInformation('BoletoUrl', $resultPayment['result']['BoletoTransactionResultCollection']['BoletoTransactionResult']['BoletoUrl']);
891
+
892
+ // We record transaction(s)
893
+ if (count($resultPayment['result']['BoletoTransactionResultCollection']) == 1) {
894
+ $trans = $resultPayment['result']['BoletoTransactionResultCollection']['BoletoTransactionResult'];
895
+
896
+ $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
897
+ } else {
898
+ foreach ($resultPayment['result']['BoletoTransactionResultCollection']['BoletoTransactionResult'] as $key => $trans) {
899
+ $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans, $key);
900
+ }
901
+ }
902
+
903
+ $payment->setTransactionId($this->_transactionId);
904
+
905
+ $payment->save();
906
+
907
+ // Send new order email when not in admin
908
+ if (Mage::app()->getStore()->getCode() != 'admin') {
909
+ $order->sendNewOrderEmail();
910
+ }
911
+
912
+ break;
913
+
914
+ // Credit Card
915
+ case 1:
916
+ // We record transaction(s)
917
+ if (count($resultPayment['result']['CreditCardTransactionResultCollection']) == 1) {
918
+ $trans = $resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
919
+ if (array_key_exists('TransactionKey', $trans)) {
920
+ $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
921
+ }
922
+ } else {
923
+ foreach ($resultPayment['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
924
+ if (array_key_exists('TransactionKey', $trans)) {
925
+ $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans, $key);
926
+ }
927
+ }
928
+ }
929
+
930
+ // Send new order email when not in admin
931
+ if (Mage::app()->getStore()->getCode() != 'admin') {
932
+ $order->sendNewOrderEmail();
933
+ }
934
+
935
+ // Invoice
936
+ $order = $payment->getOrder();
937
+
938
+ if (!$order->canInvoice()) {
939
+ // Log error
940
+ Mage::logException(Mage::helper('core')->__('Cannot create an invoice.'));
941
+
942
+ Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
943
+ }
944
+
945
+ // Create invoice
946
+ $invoice = Mage::getModel('sales/service_order', $payment->getOrder())->prepareInvoice(array());
947
+ $invoice->register();
948
+
949
+ // Set capture case to offline and register the invoice.
950
+ $invoice->setTransactionId($this->_transactionId);
951
+ $invoice->setCanVoidFlag(true);
952
+ $invoice->getOrder()->setIsInProcess(true);
953
+ $invoice->setState(2);
954
+
955
+ // Send invoice if enabled
956
+ if (Mage::helper('sales')->canSendNewInvoiceEmail($order->getStoreId())) {
957
+ $invoice->setEmailSent(true);
958
+ $invoice->sendEmail();
959
+ }
960
+
961
+ $invoice->save();
962
+
963
+ $order->setBaseTotalPaid($order->getBaseGrandTotal());
964
+ $order->setTotalPaid($order->getBaseGrandTotal());
965
+ $order->addStatusHistoryComment('Captured online amount of R$' . $order->getBaseGrandTotal(), false);
966
+ $order->save();
967
+
968
+ $payment->setLastTransId($this->_transactionId);
969
+ $payment->save();
970
+
971
+ break;
972
+
973
+ // Debit
974
+ case 4:
975
+ // We record transaction
976
+ $trans = $resultPayment['result'];
977
+
978
+ $this->_addTransaction($payment, $trans['TransactionKey'], $transactionType, $trans);
979
+ break;
980
+ }
981
+ }
982
+
983
+ return $this;
984
+ }
985
+ }
986
+
987
+ /**
988
+ * Proceed to payment
989
+ * @param object $order
990
+ */
991
+ public function doPayment($payment, $order) {
992
+ try {
993
+ $session = Mage::getSingleton('checkout/session');
994
+ $mundipaggData = $session->getMundipaggData();
995
+
996
+ //Post data
997
+ $postData = Mage::app()->getRequest()->getPost();
998
+
999
+ // Get customer taxvat
1000
+ $taxvat = '';
1001
+
1002
+ if ($order->getCustomerTaxvat() == '') {
1003
+ $customerId = $order->getCustomerId();
1004
+
1005
+ if ($customerId) {
1006
+ $customer = Mage::getModel('customer/customer')->load($customerId);
1007
+ $taxvat = $customer->getTaxvat();
1008
+ }
1009
+
1010
+ if ($taxvat != '') {
1011
+ $order->setCustomerTaxvat($taxvat)->save();
1012
+ }
1013
+ } else {
1014
+ $taxvat = $order->getCustomerTaxvat();
1015
+ }
1016
+
1017
+ // Data to pass to api
1018
+ $data['customer_id'] = $order->getCustomerId();
1019
+ $data['address_id'] = $order->getBillingAddress()->getCustomerAddressId();
1020
+ $data['payment_method'] = isset($postData['payment']['method']) ? $postData['payment']['method'] : $mundipaggData['method'];
1021
+ $type = $data['payment_method'];
1022
+
1023
+ // 1 or more Credit Cards Payment
1024
+ if ($data['payment_method'] != 'mundipagg_boleto' && $data['payment_method'] != 'mundipagg_debit') {
1025
+ $helper = Mage::helper('mundipagg');
1026
+ $num = $helper->getCreditCardsNumber($type);
1027
+ $method = $helper->getPaymentMethod($num);
1028
+
1029
+ if ($num == 0) {
1030
+ $num = 1;
1031
+ }
1032
+
1033
+ for ($i = 1; $i <= $num; $i++) {
1034
+ // New Credit Card
1035
+ if (
1036
+ !isset($postData['payment'][$method . '_token_' . $num . '_' . $i]) ||
1037
+ (isset($postData['payment'][$method . '_token_' . $num . '_' . $i]) && $postData['payment'][$method . '_token_' . $num . '_' . $i] == 'new')
1038
+ ) {
1039
+ $data['payment'][$i]['HolderName'] = isset($postData['payment'][$method . '_cc_holder_name_' . $num . '_' . $i]) ? $postData['payment'][$method . '_cc_holder_name_' . $num . '_' . $i] : $mundipaggData[$method . '_cc_holder_name_' . $num . '_' . $i];
1040
+ $data['payment'][$i]['CreditCardNumber'] = isset($postData['payment'][$method . '_' . $num . '_' . $i . '_cc_number']) ? $postData['payment'][$method . '_' . $num . '_' . $i . '_cc_number'] : $mundipaggData[$method . '_' . $num . '_' . $i . '_cc_number'];
1041
+ $data['payment'][$i]['ExpMonth'] = isset($postData['payment'][$method . '_expirationMonth_' . $num . '_' . $i]) ? $postData['payment'][$method . '_expirationMonth_' . $num . '_' . $i] : $mundipaggData[$method . '_expirationMonth_' . $num . '_' . $i];
1042
+ $data['payment'][$i]['ExpYear'] = isset($postData['payment'][$method . '_expirationYear_' . $num . '_' . $i]) ? $postData['payment'][$method . '_expirationYear_' . $num . '_' . $i] : $mundipaggData[$method . '_expirationYear_' . $num . '_' . $i];
1043
+ $data['payment'][$i]['SecurityCode'] = isset($postData['payment'][$method . '_cc_cid_' . $num . '_' . $i]) ? $postData['payment'][$method . '_cc_cid_' . $num . '_' . $i] : $mundipaggData[$method . '_cc_cid_' . $num . '_' . $i];
1044
+ $data['payment'][$i]['CreditCardBrandEnum'] = Mage::helper('mundipagg')->issuer(isset($postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type']) ? $postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type'] : $mundipaggData[$method . '_' . $num . '_' . $i . '_cc_type']);
1045
+ $data['payment'][$i]['InstallmentCount'] = isset($postData['payment'][$method . '_new_credito_parcelamento_' . $num . '_' . $i]) ? $postData['payment'][$method . '_new_credito_parcelamento_' . $num . '_' . $i] : 1;
1046
+ $data['payment'][$i]['token'] = isset($postData['payment'][$method . '_save_token_' . $num . '_' . $i]) ? $postData['payment'][$method . '_save_token_' . $num . '_' . $i] : null;
1047
+
1048
+ if (isset($postData['payment'][$method . '_new_value_' . $num . '_' . $i]) && $postData['payment'][$method . '_new_value_' . $num . '_' . $i] != '') {
1049
+ $data['payment'][$i]['AmountInCents'] = str_replace(',', '.', $postData['payment'][$method . '_new_value_' . $num . '_' . $i]);
1050
+ $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] + Mage::helper('mundipagg/installments')->getInterestForCard($data['payment'][$i]['InstallmentCount'], isset($postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type']) ? $postData['payment'][$method . '_' . $num . '_' . $i . '_cc_type'] : $mundipaggData[$method . '_' . $num . '_' . $i . '_cc_type'], $data['payment'][$i]['AmountInCents']);
1051
+
1052
+ $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] * 100;
1053
+ } else {
1054
+ if (!isset($postData['partial'])) {
1055
+ $data['payment'][$i]['AmountInCents'] = $order->getGrandTotal() * 100;
1056
+ } else { // If partial payment we deduct authorized amount already processed
1057
+ if (Mage::getSingleton('checkout/session')->getAuthorizedAmount()) {
1058
+ $data['payment'][$i]['AmountInCents'] = ($order->getGrandTotal()) * 100 - Mage::getSingleton('checkout/session')->getAuthorizedAmount() * 100;
1059
+ } else {
1060
+ $data['payment'][$i]['AmountInCents'] = ($order->getGrandTotal()) * 100;
1061
+ }
1062
+ }
1063
+ }
1064
+
1065
+ $data['payment'][$i]['TaxDocumentNumber'] = isset($postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i]) ? $postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i] : $taxvat;
1066
+
1067
+ } else { // Token
1068
+ $data['payment'][$i]['card_on_file_id'] = isset($postData['payment'][$method . '_token_' . $num . '_' . $i]) ? $postData['payment'][$method . '_token_' . $num . '_' . $i] : $mundipaggData[$method . '_token_' . $num . '_' . $i];
1069
+ $data['payment'][$i]['InstallmentCount'] = isset($postData['payment'][$method . '_credito_parcelamento_' . $num . '_' . $i]) ? $postData['payment'][$method . '_credito_parcelamento_' . $num . '_' . $i] : 1;
1070
+
1071
+ if (isset($postData['payment'][$method . '_value_' . $num . '_' . $i]) && $postData['payment'][$method . '_value_' . $num . '_' . $i] != '') {
1072
+ $data['payment'][$i]['AmountInCents'] = str_replace(',', '.', $postData['payment'][$method . '_value_' . $num . '_' . $i]);
1073
+ $cardonFile = Mage::getModel('mundipagg/cardonfile')->load($postData['payment'][$method . '_token_' . $num . '_' . $i]);
1074
+ $tokenCctype = Mage::getSingleton('mundipagg/source_cctypes')->getCcTypeForLabel($cardonFile->getCcType());
1075
+ $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] + Mage::helper('mundipagg/installments')->getInterestForCard($data['payment'][$i]['InstallmentCount'], $tokenCctype, $data['payment'][$i]['AmountInCents']);
1076
+ $data['payment'][$i]['AmountInCents'] = $data['payment'][$i]['AmountInCents'] * 100;
1077
+
1078
+ } else {
1079
+ if (!isset($postData['partial'])) {
1080
+ $data['payment'][$i]['AmountInCents'] = $order->getGrandTotal() * 100;
1081
+ } else { // If partial payment we deduct authorized amount already processed
1082
+ if (Mage::getSingleton('checkout/session')->getAuthorizedAmount()) {
1083
+ $data['payment'][$i]['AmountInCents'] = ($order->getGrandTotal()) * 100 - Mage::getSingleton('checkout/session')->getAuthorizedAmount() * 100;
1084
+ } else {
1085
+ $data['payment'][$i]['AmountInCents'] = $order->getGrandTotal() * 100;
1086
+ }
1087
+ }
1088
+ }
1089
+
1090
+ $data['payment'][$i]['TaxDocumentNumber'] = isset($postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i]) ? $postData['payment'][$method . '_cc_taxvat_' . $num . '_' . $i] : $taxvat;
1091
+ }
1092
+
1093
+ if (Mage::helper('mundipagg')->validateCPF($data['payment'][$i]['TaxDocumentNumber'])) {
1094
+ $data['PersonTypeEnum'] = 'Person';
1095
+ $data['TaxDocumentTypeEnum'] = 'CPF';
1096
+ $data['TaxDocumentNumber'] = $data['payment'][$i]['TaxDocumentNumber'];
1097
+ }
1098
+
1099
+ // We verify if a CNPJ is informed
1100
+ if (Mage::helper('mundipagg')->validateCNPJ($data['payment'][$i]['TaxDocumentNumber'])) {
1101
+ $data['PersonTypeEnum'] = 'Company';
1102
+ $data['TaxDocumentTypeEnum'] = 'CNPJ';
1103
+ $data['TaxDocumentNumber'] = $data['payment'][$i]['TaxDocumentNumber'];
1104
+ }
1105
+ }
1106
+ }
1107
+
1108
+ // Boleto Payment
1109
+ if ($data['payment_method'] == 'mundipagg_boleto') {
1110
+ $data['TaxDocumentNumber'] = isset($postData['payment']['boleto_taxvat']) ? $postData['payment']['boleto_taxvat'] : $taxvat;
1111
+ $data['boleto_parcelamento'] = isset($postData['payment']['boleto_parcelamento']) ? $postData['payment']['boleto_parcelamento'] : 1;
1112
+ $data['boleto_dates'] = isset($postData['payment']['boleto_dates']) ? $postData['payment']['boleto_dates'] : null;
1113
+
1114
+ // We verify if a CPF is informed
1115
+ if (Mage::helper('mundipagg')->validateCPF($data['TaxDocumentNumber'])) {
1116
+ $data['PersonTypeEnum'] = 'Person';
1117
+ $data['TaxDocumentTypeEnum'] = 'CPF';
1118
+ }
1119
+
1120
+ // We verify if a CNPJ is informed
1121
+ if (Mage::helper('mundipagg')->validateCNPJ($data['TaxDocumentNumber'])) {
1122
+ $data['PersonTypeEnum'] = 'Company';
1123
+ $data['TaxDocumentTypeEnum'] = 'CNPJ';
1124
+ }
1125
+ }
1126
+
1127
+ // Debit Payment
1128
+ if ($data['payment_method'] == 'mundipagg_debit') {
1129
+ $data['TaxDocumentNumber'] = isset($postData['payment']['taxvat']) ? $postData['payment']['taxvat'] : $taxvat;
1130
+ $data['Bank'] = isset($postData['payment']['mundipagg_debit']) ? $postData['payment']['mundipagg_debit'] : $mundipaggData['mundipagg_debit'];
1131
+
1132
+ // We verify if a CPF is informed
1133
+ if (Mage::helper('mundipagg')->validateCPF($data['TaxDocumentNumber'])) {
1134
+ $data['PersonTypeEnum'] = 'Person';
1135
+ $data['TaxDocumentTypeEnum'] = 'CPF';
1136
+ }
1137
+
1138
+ // We verify if a CNPJ is informed
1139
+ if (Mage::helper('mundipagg')->validateCNPJ($data['TaxDocumentNumber'])) {
1140
+ $data['PersonTypeEnum'] = 'Company';
1141
+ $data['TaxDocumentTypeEnum'] = 'CNPJ';
1142
+ }
1143
+ }
1144
+
1145
+ // Unset MundipaggData data
1146
+ $session->setMundipaggData();
1147
+
1148
+ // Api
1149
+ $api = Mage::getModel('mundipagg/api');
1150
+ $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1151
+
1152
+ // Get approval request from gateway
1153
+ switch ($type) {
1154
+ case 'mundipagg_boleto':
1155
+ $approvalRequest = $api->boletoTransaction($order, $data, $this);
1156
+ break;
1157
+
1158
+ case 'mundipagg_debit':
1159
+ $approvalRequest = $api->debitTransaction($order, $data, $this);
1160
+ break;
1161
+
1162
+ case $type:
1163
+ $approvalRequest = $api->creditCardTransaction($order, $data, $this);
1164
+ break;
1165
+ }
1166
+
1167
+ // Set some data from Mundipagg
1168
+ $payment = $this->setPaymentAdditionalInformation($approvalRequest, $payment);
1169
+ $authorizedAmount = $order->getPaymentAuthorizationAmount();
1170
+
1171
+ if (is_null($authorizedAmount)) {
1172
+ $authorizedAmount = 0;
1173
+ }
1174
+
1175
+ // Payment gateway error
1176
+ if (isset($approvalRequest['error'])) {
1177
+
1178
+ if (isset($approvalRequest['ErrorItemCollection'])) {
1179
+ $errorItemCollection = $approvalRequest['ErrorItemCollection'];
1180
+
1181
+ if (isset($errorItemCollection['ErrorItem']['ErrorCode'])) {
1182
+ $errorCode = $errorItemCollection['ErrorItem']['ErrorCode'];
1183
+
1184
+ if ($errorCode == '504') {
1185
+ $statusWithError = Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum::WITH_ERROR;
1186
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess($statusWithError);
1187
+
1188
+ return $approvalRequest;
1189
+ }
1190
+ }
1191
+ }
1192
+
1193
+ if (isset($approvalRequest['ErrorCode']) && $approvalRequest['ErrorCode'] == 'multi') {
1194
+ // Partial payment
1195
+
1196
+ // We set authorized amount
1197
+ $orderGrandTotal = $order->getGrandTotal();
1198
+
1199
+ foreach ($approvalRequest['result']->CreditCardTransactionResultCollection->CreditCardTransactionResult as $key => $result) {
1200
+ if ($result->Success == true) {
1201
+ $authorizedAmount += $result->AuthorizedAmountInCents * 0.01;
1202
+ }
1203
+ }
1204
+
1205
+ // If authorized amount is the same as order grand total we can show success page
1206
+ $epsilon = 0.1;
1207
+
1208
+ if ($authorizedAmount != 0) {
1209
+ if (($orderGrandTotal - $authorizedAmount) <= $epsilon) {
1210
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1211
+ Mage::getSingleton('checkout/session')->setAuthorizedAmount();
1212
+
1213
+ } else {
1214
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('partial');
1215
+ Mage::getSingleton('checkout/session')->setAuthorizedAmount($authorizedAmount);
1216
+ }
1217
+
1218
+ $order->setPaymentAuthorizationAmount($authorizedAmount);
1219
+ $order->save();
1220
+
1221
+ } else {
1222
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
1223
+ }
1224
+ } else {
1225
+ $this->offlineRetryCancelOrSuccessOrder($order->getIncrementId());
1226
+ }
1227
+
1228
+ return $approvalRequest;
1229
+ }
1230
+
1231
+ switch ($approvalRequest['message']) {
1232
+ // BoletoBancario
1233
+ case 0:
1234
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1235
+ break;
1236
+
1237
+ // 1CreditCards
1238
+ case 1: // AuthAndCapture
1239
+ case 2: // AuthOnly
1240
+ case 3: // AuthAndCaptureWithDelay
1241
+ // We set authorized amount in session
1242
+ $orderGrandTotal = $order->getGrandTotal();
1243
+ $xml = $approvalRequest['result'];
1244
+
1245
+ if (isset($xml->OrderResult)) {
1246
+ $orderResult = $xml->OrderResult;
1247
+ }
1248
+
1249
+ if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
1250
+ $result = $xml->CreditCardTransactionResultCollection->CreditCardTransactionResult;
1251
+
1252
+ if ($result->Success == true) {
1253
+ $authorizedAmount += $result->AuthorizedAmountInCents * 0.01;
1254
+ }
1255
+ } else {
1256
+ foreach ($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult as $key => $result) {
1257
+ if ($result->Success == true) {
1258
+ $authorizedAmount += $result->AuthorizedAmountInCents * 0.01;
1259
+ }
1260
+ }
1261
+ }
1262
+
1263
+ // If authorized amount is the same as order grand total we can show success page
1264
+ $epsilon = 0.1;
1265
+
1266
+ if (($orderGrandTotal - $authorizedAmount) <= $epsilon) {
1267
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1268
+ Mage::getSingleton('checkout/session')->setAuthorizedAmount();
1269
+
1270
+ if ($orderGrandTotal < $authorizedAmount) {
1271
+ $interestInformation = $payment->getAdditionalInformation('mundipagg_interest_information');
1272
+ $newInterestInformation = array();
1273
+
1274
+ if (count($interestInformation)) {
1275
+ $newInterest = 0;
1276
+
1277
+ foreach ($interestInformation as $key => $ii) {
1278
+ if (strpos($key, 'partial') !== false) {
1279
+ if ($ii->hasValue()) {
1280
+ $newInterest += (float)($ii->getInterest());
1281
+ }
1282
+ }
1283
+
1284
+ }
1285
+ }
1286
+ $this->addInterestToOrder($order, $newInterest);
1287
+ }
1288
+
1289
+ } else {
1290
+ if ($authorizedAmount != 0) {
1291
+ if (($orderGrandTotal - $authorizedAmount) >= $epsilon) {
1292
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('partial');
1293
+ Mage::getSingleton('checkout/session')->setAuthorizedAmount($authorizedAmount);
1294
+
1295
+ $interestInformation = $payment->getAdditionalInformation('mundipagg_interest_information');
1296
+ $unauthorizedAmount = (float)($orderGrandTotal - $authorizedAmount);
1297
+ $newInterestInformation = array();
1298
+
1299
+ if (count($interestInformation)) {
1300
+ foreach ($interestInformation as $key => $ii) {
1301
+
1302
+ if ($ii->hasValue()) {
1303
+ if ((float)($ii->getValue() + $ii->getInterest()) == (float)trim($unauthorizedAmount)) {
1304
+ $this->removeInterestToOrder($order, $ii->getInterest());
1305
+ } else {
1306
+ $newInterestInformation[$key] = $ii;
1307
+ }
1308
+ } else {
1309
+ if (($order->getGrandTotal() + $order->getMundipaggInterest()) == $unauthorizedAmount) {
1310
+ $this->removeInterestToOrder($order, $ii->getInterest());
1311
+ } else {
1312
+ $newInterestInformation[$key] = $ii;
1313
+ }
1314
+ }
1315
+ }
1316
+
1317
+ $payment->setAdditionalInformation('mundipagg_interest_information', $newInterestInformation);
1318
+ }
1319
+ }
1320
+ } else {
1321
+ $this->offlineRetryCancelOrSuccessOrder($order->getIncrementId());
1322
+ }
1323
+ }
1324
+
1325
+ // Session
1326
+ $xml = simplexml_load_string($approvalRequest['result']);
1327
+ $json = json_encode($xml);
1328
+ $dataR = array();
1329
+ $dataR = json_decode($json, true);
1330
+
1331
+ // Transaction
1332
+ $transactionKey = isset($dataR['CreditCardTransactionResultCollection']['CreditCardTransactionResult']['TransactionKey']) ? $dataR['CreditCardTransactionResultCollection']['CreditCardTransactionResult']['TransactionKey'] : null;
1333
+ $creditCardTransactionStatusEnum = isset($dataR['CreditCardTransactionResultCollection']['CreditCardTransactionResult']['CreditCardTransactionStatus']) ? $dataR['CreditCardTransactionResultCollection']['CreditCardTransactionResult']['CreditCardTransactionStatus'] : null;
1334
+
1335
+ try {
1336
+ if ($transactionKey != null) {
1337
+ $this->_transactionId = $transactionKey;
1338
+
1339
+ $payment->setTransactionId($this->_transactionId);
1340
+ $payment->save();
1341
+ }
1342
+ } catch (Exception $e) {
1343
+ $helperLog->error($e->getMessage());
1344
+ continue;
1345
+ }
1346
+ break;
1347
+
1348
+ // Debit
1349
+ case 4:
1350
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('debit');
1351
+ Mage::getSingleton('checkout/session')->setBankRedirectUrl($approvalRequest['result']['BankRedirectUrl']);
1352
+ break;
1353
+ }
1354
+
1355
+ if (isset($orderResult)) {
1356
+ $newOrderKey = (string)$orderResult->OrderKey;
1357
+ $orderPayment = $order->getPayment();
1358
+ $orderKeys = (array)$orderPayment->getAdditionalInformation('OrderKey');
1359
+
1360
+ if (is_null($orderKeys) || !is_array($orderKeys)) {
1361
+ $orderKeys = array();
1362
+ }
1363
+
1364
+ if (!in_array($newOrderKey, $orderKeys)) {
1365
+ $orderKeys[] = $newOrderKey;
1366
+ }
1367
+
1368
+ $orderPayment->setAdditionalInformation('OrderKey', $orderKeys);
1369
+ $orderPayment->save();
1370
+ }
1371
+
1372
+ $order->setPaymentAuthorizationAmount($authorizedAmount);
1373
+ $order->save();
1374
+
1375
+ if ($authorizedAmount == $order->getGrandTotal()) {
1376
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1377
+ }
1378
+
1379
+ return $approvalRequest;
1380
+
1381
+ } catch (Exception $e) {
1382
+ //Api
1383
+ $api = Mage::getModel('mundipagg/api');
1384
+
1385
+ //Log error
1386
+ Mage::logException($e);
1387
+
1388
+ //Mail error
1389
+ $api->mailError(print_r($e->getMessage(), 1));
1390
+ }
1391
+ }
1392
+
1393
+ private function setPaymentAdditionalInformation($approvalRequest, $payment) {
1394
+ if (isset($approvalRequest['ErrorCode'])) {
1395
+ $payment->setAdditionalInformation('ErrorCode', $approvalRequest['ErrorCode']);
1396
+ }
1397
+
1398
+ if (isset($approvalRequest['ErrorDescription'])) {
1399
+ $payment->setAdditionalInformation('ErrorDescription', $approvalRequest['ErrorDescription']);
1400
+ }
1401
+
1402
+ if (isset($approvalRequest['OrderKey'])) {
1403
+ $payment->setAdditionalInformation('OrderKey', $approvalRequest['OrderKey']);
1404
+ }
1405
+
1406
+ if (isset($approvalRequest['OrderReference'])) {
1407
+ $payment->setAdditionalInformation('OrderReference', $approvalRequest['OrderReference']);
1408
+ }
1409
+
1410
+ if (isset($approvalRequest['CreateDate'])) {
1411
+ $payment->setAdditionalInformation('CreateDate', $approvalRequest['CreateDate']);
1412
+ }
1413
+
1414
+ if (isset($approvalRequest['OrderStatusEnum'])) {
1415
+ $payment->setAdditionalInformation('OrderStatusEnum', $approvalRequest['OrderStatusEnum']);
1416
+ }
1417
+
1418
+ if (isset($approvalRequest['TransactionKey'])) {
1419
+ $payment->setAdditionalInformation('TransactionKey', $approvalRequest['TransactionKey']);
1420
+ }
1421
+
1422
+ if (isset($approvalRequest['OnlineDebitStatus'])) {
1423
+ $payment->setAdditionalInformation('OnlineDebitStatus', $approvalRequest['OnlineDebitStatus']);
1424
+ }
1425
+
1426
+ if (isset($approvalRequest['TransactionKeyToBank'])) {
1427
+ $payment->setAdditionalInformation('TransactionKeyToBank', $approvalRequest['TransactionKeyToBank']);
1428
+ }
1429
+
1430
+ if (isset($approvalRequest['TransactionReference'])) {
1431
+ $payment->setAdditionalInformation('TransactionReference', $approvalRequest['TransactionReference']);
1432
+ }
1433
+
1434
+ if (array_key_exists('isRecurrency', $approvalRequest)) {
1435
+ $payment->setAdditionalInformation('isRecurrency', $approvalRequest['isRecurrency']);
1436
+ }
1437
+
1438
+ return $payment;
1439
+ }
1440
+
1441
+ /**
1442
+ * Set capture transaction ID and enable Void to invoice for informational purposes
1443
+ * @param Mage_Sales_Model_Order_Invoice $invoice
1444
+ * @param Mage_Sales_Model_Order_Payment $payment
1445
+ * @return Mage_Payment_Model_Method_Abstract
1446
+ */
1447
+ public function processInvoice($invoice, $payment) {
1448
+ if ($payment->getLastTransId()) {
1449
+ $invoice->setTransactionId($payment->getLastTransId());
1450
+ $invoice->setCanVoidFlag(true);
1451
+
1452
+ if (Mage::helper('sales')->canSendNewInvoiceEmail($payment->getOrder()->getStoreId())) {
1453
+ $invoice->setEmailSent(true);
1454
+ $invoice->sendEmail();
1455
+ }
1456
+
1457
+ return $this;
1458
+ }
1459
+
1460
+ return false;
1461
+ }
1462
+
1463
+ /**
1464
+ * Check void availability
1465
+ *
1466
+ * @return bool
1467
+ */
1468
+ public function canVoid(Varien_Object $payment) {
1469
+ if ($payment instanceof Mage_Sales_Model_Order_Creditmemo) {
1470
+ return false;
1471
+ }
1472
+
1473
+ return $this->_canVoid;
1474
+ }
1475
+
1476
+ public function void(Varien_Object $payment) {
1477
+ if (!$this->canVoid($payment)) {
1478
+ Mage::throwException(Mage::helper('payment')->__('Void action is not available.'));
1479
+ }
1480
+
1481
+ //Prepare data in order to void
1482
+ if ($payment->getAdditionalInformation('OrderKey')) {
1483
+ $transactions = Mage::getModel('sales/order_payment_transaction')
1484
+ ->getCollection()
1485
+ ->addAttributeToFilter('order_id', array('eq' => $payment->getOrder()->getEntityId()));
1486
+
1487
+ foreach ($transactions as $key => $transaction) {
1488
+ $TransactionKey = $transaction->getAdditionalInformation('TransactionKey');
1489
+ $TransactionReference = $transaction->getAdditionalInformation('TransactionReference');
1490
+ }
1491
+
1492
+ // $data['CreditCardTransactionCollection']['AmountInCents'] = $payment->getOrder()->getBaseGrandTotal() * 100;
1493
+ // $data['CreditCardTransactionCollection']['TransactionKey'] = $TransactionKey;
1494
+ // $data['CreditCardTransactionCollection']['TransactionReference'] = $TransactionReference;
1495
+ // $data['OrderKey'] = $payment->getAdditionalInformation('OrderKey');
1496
+ $orderkeys = $payment->getAdditionalInformation('OrderKey');
1497
+
1498
+ if (!is_array($orderkeys)) {
1499
+ // $errMsg = "Impossible to capture: orderkeys must be an array";
1500
+ // $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1501
+ //
1502
+ // $helperLog->error($errMsg);
1503
+ // Mage::throwException($errMsg);
1504
+ $orderkeys = array($orderkeys);
1505
+ }
1506
+
1507
+ foreach ($orderkeys as $orderkey) {
1508
+ $data['ManageOrderOperationEnum'] = 'Cancel';
1509
+ $data['OrderKey'] = $orderkey;
1510
+
1511
+ //Call Gateway Api
1512
+ $api = Mage::getModel('mundipagg/api');
1513
+
1514
+ $void = $api->manageOrderRequest($data, $this);
1515
+
1516
+ // Xml
1517
+ $xml = $void['result'];
1518
+ $json = json_encode($xml);
1519
+
1520
+ $void['result'] = array();
1521
+ $void['result'] = json_decode($json, true);
1522
+
1523
+ // We record transaction(s)
1524
+ if (count($void['result']['CreditCardTransactionResultCollection']) > 0) {
1525
+ if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
1526
+ $trans = $void['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
1527
+
1528
+ $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans);
1529
+ } else {
1530
+ foreach ($void['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
1531
+ $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans, $key);
1532
+ }
1533
+ }
1534
+ }
1535
+
1536
+ if (isset($void['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'])) {
1537
+ $order = $payment->getOrder();
1538
+ $order->setBaseDiscountRefunded($order->getBaseDiscountInvoiced());
1539
+ $order->setBaseShippingRefunded($order->getBaseShippingAmount());
1540
+ $order->setBaseShippingTaxRefunded($order->getBaseShippingTaxInvoiced());
1541
+ $order->setBaseSubtotalRefunded($order->getBaseSubtotalInvoiced());
1542
+ $order->setBaseTaxRefunded($order->getBaseTaxInvoiced());
1543
+ $order->setBaseTotalOnlineRefunded($order->getBaseGrandTotal());
1544
+ $order->setDiscountRefunded($order->getDiscountInvoiced());
1545
+ $order->setShippinRefunded($order->getShippingInvoiced());
1546
+ $order->setShippinTaxRefunded($order->getShippingTaxAmount());
1547
+ $order->setSubtotalRefunded($order->getSubtotalInvoiced());
1548
+ $order->setTaxRefunded($order->getTaxInvoiced());
1549
+ $order->setTotalOnlineRefunded($order->getBaseGrandTotal());
1550
+ $order->setTotalRefunded($order->getBaseGrandTotal());
1551
+ $order->save();
1552
+
1553
+ return $this;
1554
+ } else {
1555
+ $error = Mage::helper('mundipagg')->__('Unable to void order.');
1556
+
1557
+ //Log error
1558
+ Mage::log($error, null, 'Uecommerce_Mundipagg.log');
1559
+
1560
+ Mage::throwException($error);
1561
+ }
1562
+ }
1563
+ } else {
1564
+ Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
1565
+ }
1566
+ }
1567
+
1568
+ /**
1569
+ * Check refund availability
1570
+ *
1571
+ * @return bool
1572
+ */
1573
+ public function canRefund() {
1574
+ return $this->_canRefund;
1575
+ }
1576
+
1577
+ /**
1578
+ * Set refund transaction id to payment object for informational purposes
1579
+ * Candidate to be deprecated:
1580
+ * there can be multiple refunds per payment, thus payment.refund_transactionId doesn't make big sense
1581
+ *
1582
+ * @param Mage_Sales_Model_Order_Invoice $invoice
1583
+ * @param Mage_Sales_Model_Order_Payment $payment
1584
+ * @return Mage_Payment_Model_Method_Abstract
1585
+ */
1586
+ public function processBeforeRefund($invoice, $payment) {
1587
+ $payment->setRefundTransactionId($invoice->getTransactionId());
1588
+
1589
+ return $this;
1590
+ }
1591
+
1592
+ /**
1593
+ * Refund specified amount for payment
1594
+ *
1595
+ * @param Varien_Object $payment
1596
+ * @param float $amount
1597
+ *
1598
+ * @return Mage_Payment_Model_Abstract
1599
+ */
1600
+ public function refund(Varien_Object $payment, $amount) {
1601
+ if (!$this->canRefund()) {
1602
+ Mage::throwException(Mage::helper('payment')->__('Refund action is not available.'));
1603
+ }
1604
+
1605
+ //Prepare data in order to refund
1606
+ if ($payment->getAdditionalInformation('OrderKey')) {
1607
+ $data['OrderKey'] = $payment->getAdditionalInformation('OrderKey');
1608
+ $data['ManageOrderOperationEnum'] = 'Void';
1609
+
1610
+ //Call Gateway Api
1611
+ $api = Mage::getModel('mundipagg/api');
1612
+
1613
+ $refund = $api->manageOrderRequest($data, $this);
1614
+
1615
+ // Xml
1616
+ $xml = $refund['result'];
1617
+ $json = json_encode($xml);
1618
+
1619
+ $refund['result'] = array();
1620
+ $refund['result'] = json_decode($json, true);
1621
+
1622
+ // We record transaction(s)
1623
+ if (count($refund['result']['CreditCardTransactionResultCollection']) > 0) {
1624
+ if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
1625
+ $trans = $refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'];
1626
+
1627
+ $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans);
1628
+ } else {
1629
+ foreach ($refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
1630
+ $this->_addTransaction($payment, $trans['TransactionKey'], 'void', $trans, $key);
1631
+ }
1632
+ }
1633
+ }
1634
+
1635
+ if (isset($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult)) {
1636
+ if (count($xml->CreditCardTransactionResultCollection->CreditCardTransactionResult) == 1) {
1637
+ $capturedAmountInCents = $manageOrderResult->CreditCardTransactionResultCollection->CreditCardTransactionResult->CapturedAmountInCents;
1638
+ } else {
1639
+ $capturedAmountInCents = 0;
1640
+
1641
+ foreach ($refund['result']['CreditCardTransactionResultCollection']['CreditCardTransactionResult'] as $key => $trans) {
1642
+ $capturedAmountInCents += $trans['CapturedAmountInCents'];
1643
+ }
1644
+ }
1645
+
1646
+ $order = $payment->getOrder();
1647
+ $order->setBaseDiscountRefunded($order->getBaseDiscountInvoiced());
1648
+ $order->setBaseShippingRefunded($order->getBaseShippingAmount());
1649
+ $order->setBaseShippingTaxRefunded($order->getBaseShippingTaxInvoiced());
1650
+ $order->setBaseSubtotalRefunded($order->getBaseSubtotalInvoiced());
1651
+ $order->setBaseTaxRefunded($order->getBaseTaxInvoiced());
1652
+ $order->setBaseTotalOnlineRefunded($capturedAmountInCents * 0.01);
1653
+ $order->setDiscountRefunded($order->getDiscountInvoiced());
1654
+ $order->setShippinRefunded($order->getShippingInvoiced());
1655
+ $order->setShippinTaxRefunded($order->getShippingTaxAmount());
1656
+ $order->setSubtotalRefunded($order->getSubtotalInvoiced());
1657
+ $order->setTaxRefunded($order->getTaxInvoiced());
1658
+ $order->setTotalOnlineRefunded($capturedAmountInCents * 0.01);
1659
+ $order->setTotalRefunded($capturedAmountInCents * 0.01);
1660
+ $order->save();
1661
+
1662
+ return $this;
1663
+ } else {
1664
+ $error = Mage::helper('mundipagg')->__('Unable to refund order.');
1665
+
1666
+ //Log error
1667
+ Mage::log($error, null, 'Uecommerce_Mundipagg.log');
1668
+
1669
+ Mage::throwException($error);
1670
+ }
1671
+ } else {
1672
+ Mage::throwException(Mage::helper('mundipagg')->__('No OrderKey found.'));
1673
+ }
1674
+ }
1675
+
1676
+ /**
1677
+ * Validate
1678
+ */
1679
+ public function validate() {
1680
+ parent::validate();
1681
+
1682
+ $currencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
1683
+
1684
+ if (!in_array($currencyCode, $this->_allowCurrencyCode)) {
1685
+ Mage::throwException(Mage::helper('payment')->__('Selected currency code (' . $currencyCode . ') is not compatabile with Mundipagg'));
1686
+ }
1687
+
1688
+ $info = $this->getInfoInstance();
1689
+
1690
+ $errorMsg = array();
1691
+
1692
+ // Check if we are dealing with a new Credit Card
1693
+ $isToken = $info->getAdditionalInformation('mundipagg_creditcard_token_1_1');
1694
+
1695
+ if ($info->getAdditionalInformation('PaymentMethod') == 'mundipagg_creditcard' && ($isToken == '' || $isToken == 'new')) {
1696
+ $availableTypes = $this->getCcTypes();
1697
+
1698
+ $ccNumber = $info->getCcNumber();
1699
+
1700
+ // refresh quote to remove promotions from others payment methods
1701
+ try {
1702
+ $this->getQuote()->save();
1703
+
1704
+ } catch (Exception $e) {
1705
+ $errorMsg[] = $e->getMessage();
1706
+
1707
+ }
1708
+
1709
+ // remove credit card number delimiters such as "-" and space
1710
+ $ccNumber = preg_replace('/[\-\s]+/', '', $ccNumber);
1711
+ $info->setCcNumber($ccNumber);
1712
+
1713
+ if (in_array($info->getCcType(), $availableTypes)) {
1714
+ if (!Mage::helper('mundipagg')->validateCcNum($ccNumber) && $info->getCcType() != 'HI') {
1715
+ $errorMsg[] = Mage::helper('payment')->__('Invalid Credit Card Number');
1716
+ }
1717
+ } else {
1718
+ $errorMsg[] = Mage::helper('payment')->__('Credit card type is not allowed for this payment method.');
1719
+ }
1720
+
1721
+ if (!$info->getCcType()) {
1722
+ $errorMsg[] = Mage::helper('payment')->__('Please select your credit card type.');
1723
+ }
1724
+
1725
+ if (!$info->getCcOwner()) {
1726
+ $errorMsg[] = Mage::helper('payment')->__('Please enter your credit card holder name.');
1727
+ }
1728
+
1729
+ if ($info->getCcType() && $info->getCcType() != 'SS' && !Mage::helper('mundipagg')->validateExpDate('20' . $info->getCcExpYear(), $info->getCcExpMonth())) {
1730
+ $errorMsg[] = Mage::helper('payment')->__('Incorrect credit card expiration date.');
1731
+ }
1732
+ }
1733
+
1734
+ if ($errorMsg) {
1735
+ $json = json_encode($errorMsg);
1736
+ Mage::throwException($json);
1737
+ }
1738
+
1739
+ return $this;
1740
+ }
1741
+
1742
+ /**
1743
+ * Redirect Url
1744
+ *
1745
+ * @return void
1746
+ */
1747
+ public function getOrderPlaceRedirectUrl() {
1748
+ $statusWithError = Uecommerce_Mundipagg_Model_Enum_CreditCardTransactionStatusEnum::WITH_ERROR;
1749
+
1750
+ switch (Mage::getSingleton('checkout/session')->getApprovalRequestSuccess()) {
1751
+ case 'debit':
1752
+ $redirectUrl = Mage::getSingleton('checkout/session')->getBankRedirectUrl();
1753
+ break;
1754
+
1755
+ case 'success':
1756
+ $redirectUrl = Mage::getUrl('mundipagg/standard/success', array('_secure' => true));
1757
+ break;
1758
+
1759
+ case $statusWithError:
1760
+ $redirectUrl = Mage::getUrl('mundipagg/standard/success', array('_secure' => true));
1761
+ break;
1762
+
1763
+ case 'partial':
1764
+ $redirectUrl = Mage::getUrl('mundipagg/standard/partial', array('_secure' => true));
1765
+ break;
1766
+
1767
+ case 'cancel':
1768
+ $redirectUrl = Mage::getUrl('mundipagg/standard/cancel', array('_secure' => true));
1769
+ break;
1770
+
1771
+ default:
1772
+ $redirectUrl = Mage::getUrl('mundipagg/standard/cancel', array('_secure' => true));
1773
+ break;
1774
+ }
1775
+
1776
+ return $redirectUrl;
1777
+ }
1778
+
1779
+ public function prepare() {
1780
+
1781
+ }
1782
+
1783
+ /**
1784
+ * Get payment methods
1785
+ */
1786
+ public function getPaymentMethods() {
1787
+ $payment_methods = $this->getConfigData('payment_methods');
1788
+
1789
+ if ($payment_methods != '') {
1790
+ $payment_methods = explode(",", $payment_methods);
1791
+ } else {
1792
+ $payment_methods = array();
1793
+ }
1794
+
1795
+ return $payment_methods;
1796
+ }
1797
+
1798
+ /**
1799
+ * CCards
1800
+ */
1801
+ public function getCcTypes() {
1802
+ $ccTypes = Mage::getStoreConfig('payment/mundipagg_standard/cc_types');
1803
+
1804
+ if ($ccTypes != '') {
1805
+ $ccTypes = explode(",", $ccTypes);
1806
+ } else {
1807
+ $ccTypes = array();
1808
+ }
1809
+
1810
+ return $ccTypes;
1811
+ }
1812
+
1813
+ /**
1814
+ * Reset interest
1815
+ */
1816
+ public function resetInterest($info) {
1817
+ if ($info->getQuote()->getMundipaggInterest() > 0 || $info->getQuote()->getMundipaggBaseInterest() > 0) {
1818
+ $info->getQuote()->setMundipaggInterest(0.0);
1819
+ $info->getQuote()->setMundipaggBaseInterest(0.0);
1820
+ $info->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
1821
+ $info->getQuote()->save();
1822
+ }
1823
+
1824
+ return $info;
1825
+ }
1826
+
1827
+ /**
1828
+ * Apply interest
1829
+ */
1830
+ public function applyInterest($info, $interest) {
1831
+ $info->getQuote()->setMundipaggInterest($info->getQuote()->getStore()->convertPrice($interest, false));
1832
+ $info->getQuote()->setMundipaggBaseInterest($interest);
1833
+ $info->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
1834
+ $info->getQuote()->save();
1835
+ }
1836
+
1837
+ /**
1838
+ * Remove interest to order when the total is not allowed.
1839
+ *
1840
+ * @param Mage_Sales_Model_Order $order
1841
+ * @param float $interest
1842
+ */
1843
+ protected function removeInterestToOrder(Mage_Sales_Model_Order $order, $interest) {
1844
+ $mundipaggInterest = $order->getMundipaggInterest();
1845
+ $setInterest = (float)($mundipaggInterest - $interest);
1846
+ $order->setMundipaggInterest(($setInterest) ? $setInterest : 0);
1847
+ $order->setMundipaggBaseInterest(($setInterest) ? $setInterest : 0);
1848
+ $order->setGrandTotal(($order->getGrandTotal() - $interest));
1849
+ $order->setBaseGrandTotal(($order->getBaseGrandTotal() - $interest));
1850
+ $order->save();
1851
+ $info = $this->getInfoInstance();
1852
+ $info->setPaymentInterest(($info->getPaymentInterest() - $setInterest));
1853
+ $info->save();
1854
+
1855
+ }
1856
+
1857
+ /**
1858
+ * Add interest to order
1859
+ */
1860
+ protected function addInterestToOrder(Mage_Sales_Model_Order $order, $interest) {
1861
+ $mundipaggInterest = $order->getMundipaggInterest();
1862
+ $setInterest = (float)($mundipaggInterest + $interest);
1863
+ $order->setMundipaggInterest(($setInterest) ? $setInterest : 0);
1864
+ $order->setMundipaggBaseInterest(($setInterest) ? $setInterest : 0);
1865
+ $order->setGrandTotal(($order->getGrandTotal() + $interest));
1866
+ $order->setBaseGrandTotal(($order->getBaseGrandTotal() + $interest));
1867
+ $order->save();
1868
+ }
1869
+
1870
+ /**
1871
+ * Add payment transaction
1872
+ *
1873
+ * @param Mage_Sales_Model_Order_Payment $payment
1874
+ * @param string $transactionId
1875
+ * @param string $transactionType
1876
+ * @param array $transactionAdditionalInfo
1877
+ * @return null|Mage_Sales_Model_Order_Payment_Transaction
1878
+ */
1879
+ public function _addTransaction(Mage_Sales_Model_Order_Payment $payment, $transactionId, $transactionType, $transactionAdditionalInfo, $num = 0) {
1880
+ // Num
1881
+ $num = $num + 1;
1882
+
1883
+ // Transaction
1884
+ $transaction = Mage::getModel('sales/order_payment_transaction');
1885
+ $transaction->setOrderPaymentObject($payment);
1886
+
1887
+ $transaction = $transaction->loadByTxnId($transactionId . '-' . $transactionType);
1888
+
1889
+ $transaction->setTxnType($transactionType);
1890
+ $transaction->setTxnId($transactionId . '-' . $transactionType);
1891
+
1892
+ if ($transactionType == 'authorization') {
1893
+ if ($transactionAdditionalInfo['CreditCardTransactionStatus'] == 'AuthorizedPendingCapture') {
1894
+ $transaction->setIsClosed(0);
1895
+ }
1896
+
1897
+ if ($transactionAdditionalInfo['CreditCardTransactionStatus'] == 'NotAuthorized') {
1898
+ $transaction->setIsClosed(1);
1899
+ }
1900
+ }
1901
+
1902
+ foreach ($transactionAdditionalInfo as $transKey => $value) {
1903
+
1904
+ if (!is_array($value)) {
1905
+ $transaction->setAdditionalInformation($transKey, htmlspecialchars_decode($value));
1906
+ $payment->setAdditionalInformation($num . '_' . $transKey, htmlspecialchars_decode($value));
1907
+
1908
+ } else {
1909
+
1910
+ if (empty($value)) {
1911
+ $transaction->setAdditionalInformation($transKey, '');
1912
+ $payment->setAdditionalInformation($num . '_' . $transKey, '');
1913
+
1914
+ } else {
1915
+ foreach ($value as $key2 => $value2) {
1916
+ $transaction->setAdditionalInformation($key2, htmlspecialchars_decode($value2));
1917
+ $payment->setAdditionalInformation($num . '_' . $key2, htmlspecialchars_decode($value2));
1918
+ }
1919
+ }
1920
+ }
1921
+ }
1922
+
1923
+ return $transaction->save();
1924
+ }
1925
+
1926
+ /**
1927
+ * Cancel order or not if is in offline retry time
1928
+ *
1929
+ * @author Ruan Azevedo <razevedo@mundipagg.com>
1930
+ * @since 2016-06-21
1931
+ * @param string $orderIncrementId
1932
+ */
1933
+ private function offlineRetryCancelOrSuccessOrder($orderIncrementId) {
1934
+ $offlineRetryIsEnabled = Uecommerce_Mundipagg_Model_Offlineretry::offlineRetryIsEnabled();
1935
+ $helperLog = new Uecommerce_Mundipagg_Helper_Log(__METHOD__);
1936
+ $logLabel = "Order #{$orderIncrementId}";
1937
+
1938
+ if ($offlineRetryIsEnabled == false) {
1939
+ $helperLog->info("{$logLabel} | Payment not authorized and store don't have offline retry, order will be canceled.");
1940
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
1941
+
1942
+ return;
1943
+ }
1944
+
1945
+ $api = new Uecommerce_Mundipagg_Model_Api();
1946
+
1947
+ if ($api->orderIsInOfflineRetry($orderIncrementId)) {
1948
+ $message = "{$logLabel} | payment not authorized but order is in offline retry yet, not cancel.";
1949
+
1950
+ $helperLog->info($message);
1951
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('success');
1952
+
1953
+ }/* else {
1954
+ $helperLog->info("{$logLabel} | Payment not authorized and order is not on offline retry.");
1955
+ Mage::getSingleton('checkout/session')->setApprovalRequestSuccess('cancel');
1956
+ }*/
1957
+ }
1958
+
1959
+ /**
1960
+ * @param Mage_Sales_Model_Order $order
1961
+ * @throws Exception
1962
+ */
1963
+ public static function transactionWithError(Mage_Sales_Model_Order $order, $comment = true) {
1964
+ try {
1965
+ if ($comment) {
1966
+ $order->setState(
1967
+ 'pending',
1968
+ 'mundipagg_with_error',
1969
+ 'With Error',
1970
+ false
1971
+ );
1972
+ } else {
1973
+ $order->setStatus('mundipagg_with_error');
1974
+ }
1975
+
1976
+ $order->save();
1977
+
1978
+ } catch (Exception $e) {
1979
+ $errMsg = "Unable to modify order status to 'mundipagg_with_error: {$e->getMessage()}";
1980
+
1981
+ throw new Exception($errMsg);
1982
+ }
1983
+ }
1984
+
1985
  }
app/code/community/Uecommerce/Mundipagg/data/mundipagg_setup/data-upgrade-2.9.1-2.9.2.php ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /*
4
+ * Disabled payment methods of more than 1 creditcard.
5
+ * Required because version 2.9.2 implement a new admin validation with this payment methods
6
+ *
7
+ */
8
+ Mage::getConfig()->saveConfig('payment/mundipagg_twocreditcards/active', '0');
9
+ Mage::getConfig()->saveConfig('payment/mundipagg_threecreditcards/active', '0');
10
+ Mage::getConfig()->saveConfig('payment/mundipagg_fourcreditcards/active', '0');
11
+ Mage::getConfig()->saveConfig('payment/mundipagg_fivecreditcards/active', '0');
app/code/community/Uecommerce/Mundipagg/etc/config.xml CHANGED
@@ -1,336 +1,336 @@
1
- <?xml version="1.0"?>
2
- <config>
3
- <modules>
4
- <Uecommerce_Mundipagg>
5
- <version>2.9.1</version>
6
- </Uecommerce_Mundipagg>
7
- </modules>
8
-
9
- <global>
10
- <models>
11
- <mundipagg>
12
- <class>Uecommerce_Mundipagg_Model</class>
13
- <resourceModel>mundipagg_resource</resourceModel>
14
- </mundipagg>
15
- <mundipagg_resource>
16
- <class>Uecommerce_Mundipagg_Model_Resource</class>
17
- <entities>
18
- <mundipagg_customers>
19
- <table>mundipagg_customers</table>
20
- </mundipagg_customers>
21
- <mundipagg_card_on_file>
22
- <table>mundipagg_card_on_file</table>
23
- </mundipagg_card_on_file>
24
- <mundipagg_offline_retry>
25
- <table>mundipagg_offline_retry</table>
26
- </mundipagg_offline_retry>
27
- </entities>
28
- </mundipagg_resource>
29
- </models>
30
-
31
- <events>
32
- <controller_action_predispatch>
33
- <observers>
34
- <sessionUpdate>
35
- <class>Uecommerce_Mundipagg_Model_Observer</class>
36
- <method>sessionUpdate</method>
37
- </sessionUpdate>
38
- </observers>
39
- </controller_action_predispatch>
40
- <payment_method_is_active>
41
- <observers>
42
- <removePaymentMethods>
43
- <class>Uecommerce_Mundipagg_Model_Observer</class>
44
- <method>removePaymentMethods</method>
45
- </removePaymentMethods>
46
- </observers>
47
- </payment_method_is_active>
48
- <sales_order_place_after>
49
- <observers>
50
- <onhold_order>
51
- <class>Uecommerce_Mundipagg_Model_Observer</class>
52
- <method>updateStatus</method>
53
- </onhold_order>
54
- </observers>
55
- </sales_order_place_after>
56
- <controller_action_postdispatch_checkout_onepage_savePayment>
57
- <observers>
58
- <removeInterest>
59
- <class>Uecommerce_Mundipagg_Model_Observer</class>
60
- <method>removeInterest</method>
61
- </removeInterest>
62
- </observers>
63
- </controller_action_postdispatch_checkout_onepage_savePayment>
64
- <payment_method_is_active>
65
- <observers>
66
- <checkForRecurrency>
67
- <class>Uecommerce_Mundipagg_Model_Observer</class>
68
- <method>checkForRecurrency</method>
69
- </checkForRecurrency>
70
- </observers>
71
- </payment_method_is_active>
72
- <sales_quote_collect_totals_after>
73
- <observers>
74
- <mundipagg_discount_partial>
75
- <type>singleton</type>
76
- <class>Uecommerce_Mundipagg_Model_Observer</class>
77
- <method>addDiscountWhenPartial</method>
78
- </mundipagg_discount_partial>
79
- </observers>
80
- </sales_quote_collect_totals_after>
81
- <order_cancel_after>
82
- <observers>
83
- <delete_offline_retry_data_from_canceled_order>
84
- <type>singleton</type>
85
- <class>Uecommerce_Mundipagg_Model_Observer</class>
86
- <method>canceledOrder</method>
87
- </delete_offline_retry_data_from_canceled_order>
88
- </observers>
89
- </order_cancel_after>
90
- </events>
91
-
92
- <resources>
93
- <mundipagg_setup>
94
- <setup>
95
- <module>Uecommerce_Mundipagg</module>
96
- <class>Uecommerce_Mundipagg_Model_Resource_Setup</class>
97
- </setup>
98
- <connection>
99
- <use>core_setup</use>
100
- </connection>
101
- </mundipagg_setup>
102
- <mundipagg_write>
103
- <connection>
104
- <use>core_write</use>
105
- </connection>
106
- </mundipagg_write>
107
- <mundipagg_read>
108
- <connection>
109
- <use>core_read</use>
110
- </connection>
111
- </mundipagg_read>
112
- </resources>
113
-
114
- <blocks>
115
- <mundipagg>
116
- <class>Uecommerce_Mundipagg_Block</class>
117
- </mundipagg>
118
- <adminhtml>
119
- <rewrite>
120
- <sales_transactions_detail_grid>Uecommerce_Mundipagg_Block_Adminhtml_Sales_Transactions_Detail_Grid</sales_transactions_detail_grid>
121
- <sales_order_totals>Uecommerce_Mundipagg_Block_Adminhtml_Sales_Order_Totals</sales_order_totals>
122
- <sales_order_invoice_totals>Uecommerce_Mundipagg_Block_Adminhtml_Sales_Order_Invoice_Totals</sales_order_invoice_totals>
123
- <sales_order_creditmemo_totals>Uecommerce_Mundipagg_Block_Adminhtml_Sales_Order_Creditmemo_Totals</sales_order_creditmemo_totals>
124
- </rewrite>
125
- </adminhtml>
126
- <sales>
127
- <rewrite>
128
- <order_totals>Uecommerce_Mundipagg_Block_Sales_Order_Totals</order_totals>
129
- <order_invoice_totals>Uecommerce_Mundipagg_Block_Sales_Order_Invoice_Totals</order_invoice_totals>
130
- <order_creditmemo_totals>Uecommerce_Mundipagg_Block_Sales_Order_Creditmemo_Totals</order_creditmemo_totals>
131
- </rewrite>
132
- </sales>
133
- <checkout>
134
- <rewrite>
135
- <onepage_payment_methods>Uecommerce_Mundipagg_Block_Checkout_Onepage_Payment_Methods</onepage_payment_methods>
136
- </rewrite>
137
- </checkout>
138
- </blocks>
139
-
140
- <helpers>
141
- <mundipagg>
142
- <class>Uecommerce_Mundipagg_Helper</class>
143
- </mundipagg>
144
- </helpers>
145
-
146
- <sales>
147
- <quote>
148
- <totals>
149
- <mundipagg_interest>
150
- <class>Uecommerce_Mundipagg_Model_Quote_Address_Interest</class>
151
- <after>shipping</after>
152
- <before>grand_total</before>
153
- </mundipagg_interest>
154
- </totals>
155
- </quote>
156
- <order>
157
- <totals>
158
- <mundipagg_interest>
159
- <class>Uecommerce_Mundipagg_Model_Quote_Address_Interest</class>
160
- <after>shipping</after>
161
- <before>grand_total</before>
162
- </mundipagg_interest>
163
- </totals>
164
- </order>
165
- <order_invoice>
166
- <totals>
167
- <your_total>
168
- <class>Uecommerce_Mundipagg_Model_Order_Invoice_Interest</class>
169
- <after>shipping</after>
170
- <before>grand_total</before>
171
- </your_total>
172
- </totals>
173
- </order_invoice>
174
- </sales>
175
-
176
- <fieldsets>
177
- <sales_convert_quote_address>
178
- <mundipagg_interest>
179
- <to_order>*</to_order>
180
- </mundipagg_interest>
181
- <mundipagg_base_interest>
182
- <to_order>*</to_order>
183
- </mundipagg_base_interest>
184
- </sales_convert_quote_address>
185
- <sales_convert_order>
186
- <mundipagg_interest>
187
- <to_invoice>*</to_invoice>
188
- <to_shipment>*</to_shipment>
189
- <to_cm>*</to_cm>
190
- </mundipagg_interest>
191
- <mundipagg_base_interest>
192
- <to_invoice>*</to_invoice>
193
- <to_shipment>*</to_shipment>
194
- <to_cm>*</to_cm>
195
- </mundipagg_base_interest>
196
- </sales_convert_order>
197
- </fieldsets>
198
- </global>
199
-
200
- <frontend>
201
- <routers>
202
- <mundipagg>
203
- <use>standard</use>
204
- <args>
205
- <module>Uecommerce_Mundipagg</module>
206
- <frontName>mundipagg</frontName>
207
- </args>
208
- </mundipagg>
209
- </routers>
210
- <translate>
211
- <modules>
212
- <mundipagg>
213
- <files>
214
- <default>Uecommerce_Mundipagg.csv</default>
215
- </files>
216
- </mundipagg>
217
- </modules>
218
- </translate>
219
- <layout>
220
- <updates>
221
- <mundipagg module="Uecommerce_Mundipagg">
222
- <file>mundipagg.xml</file>
223
- </mundipagg>
224
- </updates>
225
- </layout>
226
- </frontend>
227
-
228
- <adminhtml>
229
- <translate>
230
- <modules>
231
- <mundipagg>
232
- <files>
233
- <default>Uecommerce_Mundipagg.csv</default>
234
- </files>
235
- </mundipagg>
236
- </modules>
237
- </translate>
238
- <layout>
239
- <updates>
240
- <mundipagg module="Uecommerce_Mundipagg">
241
- <file>mundipagg.xml</file>
242
- </mundipagg>
243
- </updates>
244
- </layout>
245
- </adminhtml>
246
- <admin>
247
- <routers>
248
- <adminhtml>
249
- <args>
250
- <modules>
251
- <mundipagg after="Mage_Adminhtml">Uecommerce_Mundipagg_Adminhtml</mundipagg>
252
- </modules>
253
- </args>
254
- </adminhtml>
255
- </routers>
256
- </admin>
257
-
258
- <default>
259
- <payment>
260
- <mundipagg_standard>
261
- <model>mundipagg/standard</model>
262
- <apiUrlStaging>https://sandbox.mundipaggone.com/sale/</apiUrlStaging>
263
- <apiUrlProduction>https://transactionv2.mundipaggone.com/Sale/</apiUrlProduction>
264
- <antifraud>0</antifraud>
265
- <debug>1</debug>
266
- <payment_action>order</payment_action>
267
- <save_cardonfile>1</save_cardonfile>
268
- <delivery_deadline>5</delivery_deadline>
269
- <shipping_company>Correios</shipping_company>
270
- <environment_fcontrol>1</environment_fcontrol>
271
- <antifraud_minimum_clearsale>0.00</antifraud_minimum_clearsale>
272
- <antifraud_minimum_fcontrol>0.00</antifraud_minimum_fcontrol>
273
- <antifraud_minimum_stone>0.00</antifraud_minimum_stone>
274
- </mundipagg_standard>
275
- <mundipagg_creditcardoneinstallment>
276
- <model>mundipagg/creditcardoneinstallment</model>
277
- <active>0</active>
278
- <title><![CDATA[Cartão de Crédito à vista]]></title>
279
- <allowspecific>0</allowspecific>
280
- <payment_action>authorize</payment_action>
281
- </mundipagg_creditcardoneinstallment>
282
- <mundipagg_creditcard>
283
- <model>mundipagg/creditcard</model>
284
- <active>0</active>
285
- <title><![CDATA[Cartão de Crédito]]></title>
286
- <allowspecific>0</allowspecific>
287
- <payment_action>authorize</payment_action>
288
- </mundipagg_creditcard>
289
- <mundipagg_twocreditcards>
290
- <model>mundipagg/twocreditcards</model>
291
- <active>0</active>
292
- <title><![CDATA[2 Cartões de Crédito]]></title>
293
- <allowspecific>0</allowspecific>
294
- <payment_action>authorize</payment_action>
295
- </mundipagg_twocreditcards>
296
- <mundipagg_threecreditcards>
297
- <model>mundipagg/threecreditcards</model>
298
- <active>0</active>
299
- <title><![CDATA[3 Cartões de Crédito]]></title>
300
- <allowspecific>0</allowspecific>
301
- <payment_action>authorize</payment_action>
302
- </mundipagg_threecreditcards>
303
- <mundipagg_fourcreditcards>
304
- <model>mundipagg/fourcreditcards</model>
305
- <active>0</active>
306
- <title><![CDATA[4 Cartões de Crédito]]></title>
307
- <allowspecific>0</allowspecific>
308
- <payment_action>authorize</payment_action>
309
- </mundipagg_fourcreditcards>
310
- <mundipagg_fivecreditcards>
311
- <model>mundipagg/fivecreditcards</model>
312
- <active>0</active>
313
- <title><![CDATA[5 Cartões de Crédito]]></title>
314
- <allowspecific>0</allowspecific>
315
- <payment_action>authorize</payment_action>
316
- </mundipagg_fivecreditcards>
317
- <mundipagg_boleto>
318
- <model>mundipagg/boleto</model>
319
- <active>0</active>
320
- <title><![CDATA[Boleto]]></title>
321
- <dias_validade_boleto>3</dias_validade_boleto>
322
- <allowspecific>0</allowspecific>
323
- <payment_action>authorize</payment_action>
324
- </mundipagg_boleto>
325
- <mundipagg_debit>
326
- <model>mundipagg/debit</model>
327
- <active>0</active>
328
- <title><![CDATA[Débito]]></title>
329
- <apiDebitUrl>https://api.mundipaggone.com/Order/OnlineDebit/</apiDebitUrl>
330
- <apiDebitStagingUrl>https://apisandbox.mundipaggone.com/Order/OnlineDebit/</apiDebitStagingUrl>
331
- <allowspecific>0</allowspecific>
332
- <payment_action>authorize</payment_action>
333
- </mundipagg_debit>
334
- </payment>
335
- </default>
336
- </config>
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <modules>
4
+ <Uecommerce_Mundipagg>
5
+ <version>2.9.2</version>
6
+ </Uecommerce_Mundipagg>
7
+ </modules>
8
+
9
+ <global>
10
+ <models>
11
+ <mundipagg>
12
+ <class>Uecommerce_Mundipagg_Model</class>
13
+ <resourceModel>mundipagg_resource</resourceModel>
14
+ </mundipagg>
15
+ <mundipagg_resource>
16
+ <class>Uecommerce_Mundipagg_Model_Resource</class>
17
+ <entities>
18
+ <mundipagg_customers>
19
+ <table>mundipagg_customers</table>
20
+ </mundipagg_customers>
21
+ <mundipagg_card_on_file>
22
+ <table>mundipagg_card_on_file</table>
23
+ </mundipagg_card_on_file>
24
+ <mundipagg_offline_retry>
25
+ <table>mundipagg_offline_retry</table>
26
+ </mundipagg_offline_retry>
27
+ </entities>
28
+ </mundipagg_resource>
29
+ </models>
30
+
31
+ <events>
32
+ <controller_action_predispatch>
33
+ <observers>
34
+ <sessionUpdate>
35
+ <class>Uecommerce_Mundipagg_Model_Observer</class>
36
+ <method>sessionUpdate</method>
37
+ </sessionUpdate>
38
+ </observers>
39
+ </controller_action_predispatch>
40
+ <payment_method_is_active>
41
+ <observers>
42
+ <removePaymentMethods>
43
+ <class>Uecommerce_Mundipagg_Model_Observer</class>
44
+ <method>removePaymentMethods</method>
45
+ </removePaymentMethods>
46
+ </observers>
47
+ </payment_method_is_active>
48
+ <sales_order_place_after>
49
+ <observers>
50
+ <onhold_order>
51
+ <class>Uecommerce_Mundipagg_Model_Observer</class>
52
+ <method>updateStatus</method>
53
+ </onhold_order>
54
+ </observers>
55
+ </sales_order_place_after>
56
+ <controller_action_postdispatch_checkout_onepage_savePayment>
57
+ <observers>
58
+ <removeInterest>
59
+ <class>Uecommerce_Mundipagg_Model_Observer</class>
60
+ <method>removeInterest</method>
61
+ </removeInterest>
62
+ </observers>
63
+ </controller_action_postdispatch_checkout_onepage_savePayment>
64
+ <payment_method_is_active>
65
+ <observers>
66
+ <checkForRecurrency>
67
+ <class>Uecommerce_Mundipagg_Model_Observer</class>
68
+ <method>checkForRecurrency</method>
69
+ </checkForRecurrency>
70
+ </observers>
71
+ </payment_method_is_active>
72
+ <sales_quote_collect_totals_after>
73
+ <observers>
74
+ <mundipagg_discount_partial>
75
+ <type>singleton</type>
76
+ <class>Uecommerce_Mundipagg_Model_Observer</class>
77
+ <method>addDiscountWhenPartial</method>
78
+ </mundipagg_discount_partial>
79
+ </observers>
80
+ </sales_quote_collect_totals_after>
81
+ <order_cancel_after>
82
+ <observers>
83
+ <delete_offline_retry_data_from_canceled_order>
84
+ <type>singleton</type>
85
+ <class>Uecommerce_Mundipagg_Model_Observer</class>
86
+ <method>canceledOrder</method>
87
+ </delete_offline_retry_data_from_canceled_order>
88
+ </observers>
89
+ </order_cancel_after>
90
+ </events>
91
+
92
+ <resources>
93
+ <mundipagg_setup>
94
+ <setup>
95
+ <module>Uecommerce_Mundipagg</module>
96
+ <class>Uecommerce_Mundipagg_Model_Resource_Setup</class>
97
+ </setup>
98
+ <connection>
99
+ <use>core_setup</use>
100
+ </connection>
101
+ </mundipagg_setup>
102
+ <mundipagg_write>
103
+ <connection>
104
+ <use>core_write</use>
105
+ </connection>
106
+ </mundipagg_write>
107
+ <mundipagg_read>
108
+ <connection>
109
+ <use>core_read</use>
110
+ </connection>
111
+ </mundipagg_read>
112
+ </resources>
113
+
114
+ <blocks>
115
+ <mundipagg>
116
+ <class>Uecommerce_Mundipagg_Block</class>
117
+ </mundipagg>
118
+ <adminhtml>
119
+ <rewrite>
120
+ <sales_transactions_detail_grid>Uecommerce_Mundipagg_Block_Adminhtml_Sales_Transactions_Detail_Grid</sales_transactions_detail_grid>
121
+ <sales_order_totals>Uecommerce_Mundipagg_Block_Adminhtml_Sales_Order_Totals</sales_order_totals>
122
+ <sales_order_invoice_totals>Uecommerce_Mundipagg_Block_Adminhtml_Sales_Order_Invoice_Totals</sales_order_invoice_totals>
123
+ <sales_order_creditmemo_totals>Uecommerce_Mundipagg_Block_Adminhtml_Sales_Order_Creditmemo_Totals</sales_order_creditmemo_totals>
124
+ </rewrite>
125
+ </adminhtml>
126
+ <sales>
127
+ <rewrite>
128
+ <order_totals>Uecommerce_Mundipagg_Block_Sales_Order_Totals</order_totals>
129
+ <order_invoice_totals>Uecommerce_Mundipagg_Block_Sales_Order_Invoice_Totals</order_invoice_totals>
130
+ <order_creditmemo_totals>Uecommerce_Mundipagg_Block_Sales_Order_Creditmemo_Totals</order_creditmemo_totals>
131
+ </rewrite>
132
+ </sales>
133
+ <checkout>
134
+ <rewrite>
135
+ <onepage_payment_methods>Uecommerce_Mundipagg_Block_Checkout_Onepage_Payment_Methods</onepage_payment_methods>
136
+ </rewrite>
137
+ </checkout>
138
+ </blocks>
139
+
140
+ <helpers>
141
+ <mundipagg>
142
+ <class>Uecommerce_Mundipagg_Helper</class>
143
+ </mundipagg>
144
+ </helpers>
145
+
146
+ <sales>
147
+ <quote>
148
+ <totals>
149
+ <mundipagg_interest>
150
+ <class>Uecommerce_Mundipagg_Model_Quote_Address_Interest</class>
151
+ <after>shipping</after>
152
+ <before>grand_total</before>
153
+ </mundipagg_interest>
154
+ </totals>
155
+ </quote>
156
+ <order>
157
+ <totals>
158
+ <mundipagg_interest>
159
+ <class>Uecommerce_Mundipagg_Model_Quote_Address_Interest</class>
160
+ <after>shipping</after>
161
+ <before>grand_total</before>
162
+ </mundipagg_interest>
163
+ </totals>
164
+ </order>
165
+ <order_invoice>
166
+ <totals>
167
+ <your_total>
168
+ <class>Uecommerce_Mundipagg_Model_Order_Invoice_Interest</class>
169
+ <after>shipping</after>
170
+ <before>grand_total</before>
171
+ </your_total>
172
+ </totals>
173
+ </order_invoice>
174
+ </sales>
175
+
176
+ <fieldsets>
177
+ <sales_convert_quote_address>
178
+ <mundipagg_interest>
179
+ <to_order>*</to_order>
180
+ </mundipagg_interest>
181
+ <mundipagg_base_interest>
182
+ <to_order>*</to_order>
183
+ </mundipagg_base_interest>
184
+ </sales_convert_quote_address>
185
+ <sales_convert_order>
186
+ <mundipagg_interest>
187
+ <to_invoice>*</to_invoice>
188
+ <to_shipment>*</to_shipment>
189
+ <to_cm>*</to_cm>
190
+ </mundipagg_interest>
191
+ <mundipagg_base_interest>
192
+ <to_invoice>*</to_invoice>
193
+ <to_shipment>*</to_shipment>
194
+ <to_cm>*</to_cm>
195
+ </mundipagg_base_interest>
196
+ </sales_convert_order>
197
+ </fieldsets>
198
+ </global>
199
+
200
+ <frontend>
201
+ <routers>
202
+ <mundipagg>
203
+ <use>standard</use>
204
+ <args>
205
+ <module>Uecommerce_Mundipagg</module>
206
+ <frontName>mundipagg</frontName>
207
+ </args>
208
+ </mundipagg>
209
+ </routers>
210
+ <translate>
211
+ <modules>
212
+ <mundipagg>
213
+ <files>
214
+ <default>Uecommerce_Mundipagg.csv</default>
215
+ </files>
216
+ </mundipagg>
217
+ </modules>
218
+ </translate>
219
+ <layout>
220
+ <updates>
221
+ <mundipagg module="Uecommerce_Mundipagg">
222
+ <file>mundipagg.xml</file>
223
+ </mundipagg>
224
+ </updates>
225
+ </layout>
226
+ </frontend>
227
+
228
+ <adminhtml>
229
+ <translate>
230
+ <modules>
231
+ <mundipagg>
232
+ <files>
233
+ <default>Uecommerce_Mundipagg.csv</default>
234
+ </files>
235
+ </mundipagg>
236
+ </modules>
237
+ </translate>
238
+ <layout>
239
+ <updates>
240
+ <mundipagg module="Uecommerce_Mundipagg">
241
+ <file>mundipagg.xml</file>
242
+ </mundipagg>
243
+ </updates>
244
+ </layout>
245
+ </adminhtml>
246
+ <admin>
247
+ <routers>
248
+ <adminhtml>
249
+ <args>
250
+ <modules>
251
+ <mundipagg after="Mage_Adminhtml">Uecommerce_Mundipagg_Adminhtml</mundipagg>
252
+ </modules>
253
+ </args>
254
+ </adminhtml>
255
+ </routers>
256
+ </admin>
257
+
258
+ <default>
259
+ <payment>
260
+ <mundipagg_standard>
261
+ <model>mundipagg/standard</model>
262
+ <apiUrlStaging>https://sandbox.mundipaggone.com/sale/</apiUrlStaging>
263
+ <apiUrlProduction>https://transactionv2.mundipaggone.com/Sale/</apiUrlProduction>
264
+ <antifraud>0</antifraud>
265
+ <debug>1</debug>
266
+ <payment_action>order</payment_action>
267
+ <save_cardonfile>1</save_cardonfile>
268
+ <delivery_deadline>5</delivery_deadline>
269
+ <shipping_company>Correios</shipping_company>
270
+ <environment_fcontrol>1</environment_fcontrol>
271
+ <antifraud_minimum_clearsale>0.00</antifraud_minimum_clearsale>
272
+ <antifraud_minimum_fcontrol>0.00</antifraud_minimum_fcontrol>
273
+ <antifraud_minimum_stone>0.00</antifraud_minimum_stone>
274
+ </mundipagg_standard>
275
+ <mundipagg_creditcardoneinstallment>
276
+ <model>mundipagg/creditcardoneinstallment</model>
277
+ <active>0</active>
278
+ <title><![CDATA[Cartão de Crédito à vista]]></title>
279
+ <allowspecific>0</allowspecific>
280
+ <payment_action>authorize</payment_action>
281
+ </mundipagg_creditcardoneinstallment>
282
+ <mundipagg_creditcard>
283
+ <model>mundipagg/creditcard</model>
284
+ <active>0</active>
285
+ <title><![CDATA[Cartão de Crédito]]></title>
286
+ <allowspecific>0</allowspecific>
287
+ <payment_action>authorize</payment_action>
288
+ </mundipagg_creditcard>
289
+ <mundipagg_twocreditcards>
290
+ <model>mundipagg/twocreditcards</model>
291
+ <active>0</active>
292
+ <title><![CDATA[2 Cartões de Crédito]]></title>
293
+ <allowspecific>0</allowspecific>
294
+ <payment_action>authorize</payment_action>
295
+ </mundipagg_twocreditcards>
296
+ <mundipagg_threecreditcards>
297
+ <model>mundipagg/threecreditcards</model>
298
+ <active>0</active>
299
+ <title><![CDATA[3 Cartões de Crédito]]></title>
300
+ <allowspecific>0</allowspecific>
301
+ <payment_action>authorize</payment_action>
302
+ </mundipagg_threecreditcards>
303
+ <mundipagg_fourcreditcards>
304
+ <model>mundipagg/fourcreditcards</model>
305
+ <active>0</active>
306
+ <title><![CDATA[4 Cartões de Crédito]]></title>
307
+ <allowspecific>0</allowspecific>
308
+ <payment_action>authorize</payment_action>
309
+ </mundipagg_fourcreditcards>
310
+ <mundipagg_fivecreditcards>
311
+ <model>mundipagg/fivecreditcards</model>
312
+ <active>0</active>
313
+ <title><![CDATA[5 Cartões de Crédito]]></title>
314
+ <allowspecific>0</allowspecific>
315
+ <payment_action>authorize</payment_action>
316
+ </mundipagg_fivecreditcards>
317
+ <mundipagg_boleto>
318
+ <model>mundipagg/boleto</model>
319
+ <active>0</active>
320
+ <title><![CDATA[Boleto]]></title>
321
+ <dias_validade_boleto>3</dias_validade_boleto>
322
+ <allowspecific>0</allowspecific>
323
+ <payment_action>authorize</payment_action>
324
+ </mundipagg_boleto>
325
+ <mundipagg_debit>
326
+ <model>mundipagg/debit</model>
327
+ <active>0</active>
328
+ <title><![CDATA[Débito]]></title>
329
+ <apiDebitUrl>https://api.mundipaggone.com/Order/OnlineDebit/</apiDebitUrl>
330
+ <apiDebitStagingUrl>https://apisandbox.mundipaggone.com/Order/OnlineDebit/</apiDebitStagingUrl>
331
+ <allowspecific>0</allowspecific>
332
+ <payment_action>authorize</payment_action>
333
+ </mundipagg_debit>
334
+ </payment>
335
+ </default>
336
+ </config>
app/code/community/Uecommerce/Mundipagg/etc/system.xml CHANGED
@@ -1,1118 +1,1119 @@
1
- <?xml version="1.0"?>
2
- <config>
3
- <sections>
4
- <payment translate="label" module="payment">
5
- <groups>
6
- <mundipagg_standard type="group" translate="label">
7
- <label><![CDATA[MundiPagg]]></label>
8
- <sort_order>420</sort_order>
9
- <show_in_default>1</show_in_default>
10
- <show_in_website>1</show_in_website>
11
- <show_in_store>1</show_in_store>
12
- <comment>
13
- <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
14
-
15
- <fields>
16
- <heading_basic_config translate="label">
17
- <label>Module Basic Configuration</label>
18
- <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
19
- <sort_order>0</sort_order>
20
- <show_in_default>1</show_in_default>
21
- <show_in_website>1</show_in_website>
22
- <show_in_store>0</show_in_store>
23
- </heading_basic_config>
24
-
25
- <version translate="label">
26
- <label>Version</label>
27
- <frontend_type>select</frontend_type>
28
- <frontend_model>Uecommerce_Mundipagg_Block_Adminhtml_Version</frontend_model>
29
- <sort_order>1</sort_order>
30
- <show_in_default>1</show_in_default>
31
- <show_in_website>1</show_in_website>
32
- <show_in_store>1</show_in_store>
33
- </version>
34
-
35
- <environment translate="label">
36
- <label>Environment</label>
37
- <frontend_type>select</frontend_type>
38
- <source_model>Uecommerce_Mundipagg_Model_Source_Environment</source_model>
39
- <sort_order>2</sort_order>
40
- <show_in_default>1</show_in_default>
41
- <show_in_website>1</show_in_website>
42
- <show_in_store>1</show_in_store>
43
- <comment>
44
- <![CDATA[<b>Sandbox</b> = ambiente de teste<br/><b>Production</b> = ambiente de produção]]></comment>
45
- </environment>
46
-
47
- <apiUrlStaging translate="label">
48
- <label>API URL Sandbox</label>
49
- <frontend_type>text</frontend_type>
50
- <sort_order>3</sort_order>
51
- <backend_model>mundipagg/urlvalidation</backend_model>
52
- <depends>
53
- <environment>development</environment>
54
- </depends>
55
- <show_in_default>1</show_in_default>
56
- <show_in_website>1</show_in_website>
57
- <show_in_store>1</show_in_store>
58
- </apiUrlStaging>
59
-
60
- <merchantKeyStaging translate="label">
61
- <label>MerchantKey Sandbox</label>
62
- <frontend_type>text</frontend_type>
63
- <sort_order>4</sort_order>
64
- <depends>
65
- <environment>development</environment>
66
- </depends>
67
- <show_in_default>1</show_in_default>
68
- <show_in_website>1</show_in_website>
69
- <show_in_store>1</show_in_store>
70
- </merchantKeyStaging>
71
-
72
- <apiUrlProduction translate="label">
73
- <label>API URL Production</label>
74
- <frontend_type>text</frontend_type>
75
- <sort_order>3</sort_order>
76
- <backend_model>mundipagg/urlvalidation</backend_model>
77
- <depends>
78
- <environment>production</environment>
79
- </depends>
80
- <show_in_default>1</show_in_default>
81
- <show_in_website>1</show_in_website>
82
- <show_in_store>1</show_in_store>
83
- </apiUrlProduction>
84
-
85
- <merchantKeyProduction translate="label">
86
- <label>MerchantKey Production</label>
87
- <frontend_type>text</frontend_type>
88
- <sort_order>4</sort_order>
89
- <depends>
90
- <environment>production</environment>
91
- </depends>
92
- <show_in_default>1</show_in_default>
93
- <show_in_website>1</show_in_website>
94
- <show_in_store>1</show_in_store>
95
- </merchantKeyProduction>
96
-
97
- <debug translate="label">
98
- <label>Logs</label>
99
- <frontend_type>select</frontend_type>
100
- <source_model>adminhtml/system_config_source_yesno</source_model>
101
- <backend_model>Uecommerce_Mundipagg_Model_Adminvalidators_Debug</backend_model>
102
- <sort_order>5</sort_order>
103
- <show_in_default>1</show_in_default>
104
- <show_in_website>1</show_in_website>
105
- <show_in_store>1</show_in_store>
106
- <comment>
107
- <![CDATA[Grava o retorno da MundiPagg nos logs do Magento. Habilitar esta opção irá habilitar os logs do Magento (System -> Configuration -> Advanced -> Developer -> Log Settings -> Yes)]]></comment>
108
- </debug>
109
-
110
- <payment_action translate="label">
111
- <label>Payment Action</label>
112
- <frontend_type>select</frontend_type>
113
- <source_model>Uecommerce_Mundipagg_Model_Source_PaymentAction</source_model>
114
- <sort_order>6</sort_order>
115
- <show_in_default>1</show_in_default>
116
- <show_in_website>1</show_in_website>
117
- <show_in_store>1</show_in_store>
118
- <comment>
119
- <![CDATA[<b>AuthOnly</b> = Autorizar<br/><b>AuthAndCapture</b> = Autorizar e capturar]]></comment>
120
- </payment_action>
121
-
122
- <heading_anti_fraud translate="label">
123
- <label>Anti fraud</label>
124
- <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
125
- <sort_order>7</sort_order>
126
- <show_in_default>1</show_in_default>
127
- <show_in_website>1</show_in_website>
128
- <show_in_store>0</show_in_store>
129
- </heading_anti_fraud>
130
-
131
- <antifraud translate="label">
132
- <label>Enabled</label>
133
- <frontend_type>select</frontend_type>
134
- <source_model>adminhtml/system_config_source_yesno</source_model>
135
- <sort_order>8</sort_order>
136
- <show_in_default>1</show_in_default>
137
- <show_in_website>1</show_in_website>
138
- <show_in_store>1</show_in_store>
139
- </antifraud>
140
-
141
- <antifraud_provider translate="label">
142
- <label>Anti Fraud Provider</label>
143
- <frontend_type>select</frontend_type>
144
- <source_model>Uecommerce_Mundipagg_Model_Source_Antifraud</source_model>
145
- <backend_model>mundipagg/providervalidation</backend_model>
146
- <sort_order>9</sort_order>
147
- <depends>
148
- <antifraud>1</antifraud>
149
- </depends>
150
- <validates>required-entry</validates>
151
- <show_in_default>1</show_in_default>
152
- <show_in_website>1</show_in_website>
153
- <show_in_store>1</show_in_store>
154
- </antifraud_provider>
155
-
156
- <antifraud_minimum_clearsale>
157
- <label>Order Minimum Value</label>
158
- <frontend_type>text</frontend_type>
159
- <backend_model>Uecommerce_Mundipagg_Model_Adminvalidators_Antifraud_Minval</backend_model>
160
- <depends>
161
- <antifraud>1</antifraud>
162
- <antifraud_provider>1</antifraud_provider>
163
- </depends>
164
- <sort_order>10</sort_order>
165
- <show_in_default>1</show_in_default>
166
- <show_in_website>1</show_in_website>
167
- <show_in_store>1</show_in_store>
168
- <comment>Valid formats: 0.00 - 0,00</comment>
169
- </antifraud_minimum_clearsale>
170
-
171
- <antifraud_minimum_fcontrol>
172
- <label>Order Minimum Value</label>
173
- <frontend_type>text</frontend_type>
174
- <backend_model>Uecommerce_Mundipagg_Model_Adminvalidators_Antifraud_Minval</backend_model>
175
- <depends>
176
- <antifraud>1</antifraud>
177
- <antifraud_provider>2</antifraud_provider>
178
- </depends>
179
- <sort_order>10</sort_order>
180
- <show_in_default>1</show_in_default>
181
- <show_in_website>1</show_in_website>
182
- <show_in_store>1</show_in_store>
183
- <comment>Valid formats: 0.00 - 0,00</comment>
184
- </antifraud_minimum_fcontrol>
185
-
186
- <antifraud_minimum_stone>
187
- <label>Order Minimum Value</label>
188
- <frontend_type>text</frontend_type>
189
- <backend_model>Uecommerce_Mundipagg_Model_Adminvalidators_Antifraud_Minval</backend_model>
190
- <depends>
191
- <antifraud>1</antifraud>
192
- <antifraud_provider>3</antifraud_provider>
193
- </depends>
194
- <sort_order>10</sort_order>
195
- <show_in_default>1</show_in_default>
196
- <show_in_website>1</show_in_website>
197
- <show_in_store>1</show_in_store>
198
- <comment>Valid formats: 0.00 - 0,00</comment>
199
- </antifraud_minimum_stone>
200
-
201
- <fingerprint translate="label">
202
- <label>Fingerprint</label>
203
- <frontend_type>select</frontend_type>
204
- <source_model>adminhtml/system_config_source_yesno</source_model>
205
- <depends>
206
- <antifraud>1</antifraud>
207
- </depends>
208
- <sort_order>11</sort_order>
209
- <show_in_default>1</show_in_default>
210
- <show_in_website>1</show_in_website>
211
- <show_in_store>1</show_in_store>
212
- </fingerprint>
213
-
214
- <environment_fcontrol translate="label">
215
- <label>Fingerprint environment</label>
216
- <frontend_type>select</frontend_type>
217
- <source_model>Uecommerce_Mundipagg_Model_Source_FControlEnvironment</source_model>
218
- <depends>
219
- <antifraud>1</antifraud>
220
- <antifraud_provider>2</antifraud_provider>
221
- <fingerprint>1</fingerprint>
222
- </depends>
223
- <sort_order>12</sort_order>
224
- <show_in_default>1</show_in_default>
225
- <show_in_website>1</show_in_website>
226
- <show_in_store>1</show_in_store>
227
- </environment_fcontrol>
228
-
229
- <fcontrol_key_sandbox translate="label">
230
- <label>FControl sandbox key</label>
231
- <frontend_type>text</frontend_type>
232
- <sort_order>13</sort_order>
233
- <depends>
234
- <antifraud>1</antifraud>
235
- <antifraud_provider>2</antifraud_provider>
236
- <fingerprint>1</fingerprint>
237
- <environment_fcontrol>1</environment_fcontrol>
238
- </depends>
239
- <show_in_default>1</show_in_default>
240
- <show_in_website>1</show_in_website>
241
- <show_in_store>1</show_in_store>
242
- <comment>Chave informada pela FControl</comment>
243
- </fcontrol_key_sandbox>
244
-
245
- <fcontrol_key_production translate="label">
246
- <label>FControl production key</label>
247
- <frontend_type>text</frontend_type>
248
- <sort_order>13</sort_order>
249
- <depends>
250
- <antifraud>1</antifraud>
251
- <antifraud_provider>2</antifraud_provider>
252
- <environment_fcontrol>2</environment_fcontrol>
253
- </depends>
254
- <show_in_default>1</show_in_default>
255
- <show_in_website>1</show_in_website>
256
- <show_in_store>1</show_in_store>
257
- <comment>Chave informada pela FControl</comment>
258
- </fcontrol_key_production>
259
-
260
- <clearsale_entitycode translate="label">
261
- <label>EntityCode</label>
262
- <frontend_type>text</frontend_type>
263
- <sort_order>12</sort_order>
264
- <depends>
265
- <antifraud>1</antifraud>
266
- <antifraud_provider>1</antifraud_provider>
267
- <fingerprint>1</fingerprint>
268
- </depends>
269
- <show_in_default>1</show_in_default>
270
- <show_in_website>1</show_in_website>
271
- <show_in_store>1</show_in_store>
272
- <comment>Chave informada pela Clearsale</comment>
273
- </clearsale_entitycode>
274
-
275
- <stone_entitycode translate="label">
276
- <label>EntityCode</label>
277
- <frontend_type>text</frontend_type>
278
- <sort_order>12</sort_order>
279
- <depends>
280
- <antifraud>1</antifraud>
281
- <antifraud_provider>3</antifraud_provider>
282
- <fingerprint>1</fingerprint>
283
- </depends>
284
- <show_in_default>1</show_in_default>
285
- <show_in_website>1</show_in_website>
286
- <show_in_store>1</show_in_store>
287
- <comment>Chave informada pela Stone</comment>
288
- </stone_entitycode>
289
-
290
- <clearsale_app translate="label">
291
- <label>AppKey</label>
292
- <frontend_type>text</frontend_type>
293
- <sort_order>13</sort_order>
294
- <depends>
295
- <antifraud>1</antifraud>
296
- <antifraud_provider>1</antifraud_provider>
297
- <fingerprint>1</fingerprint>
298
- </depends>
299
- <show_in_default>1</show_in_default>
300
- <show_in_website>1</show_in_website>
301
- <show_in_store>1</show_in_store>
302
- <comment>codigo informado pela Clearsale</comment>
303
- </clearsale_app>
304
-
305
- <stone_app translate="label">
306
- <label>AppKey</label>
307
- <frontend_type>text</frontend_type>
308
- <sort_order>13</sort_order>
309
- <depends>
310
- <antifraud>1</antifraud>
311
- <antifraud_provider>3</antifraud_provider>
312
- <fingerprint>1</fingerprint>
313
- </depends>
314
- <show_in_default>1</show_in_default>
315
- <show_in_website>1</show_in_website>
316
- <show_in_store>1</show_in_store>
317
- <comment>codigo informado pela Stone</comment>
318
- </stone_app>
319
-
320
- <heading_installments translate="label">
321
- <label>Credit Card Basic Configuration</label>
322
- <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
323
- <sort_order>14</sort_order>
324
- <show_in_default>1</show_in_default>
325
- <show_in_website>1</show_in_website>
326
- <show_in_store>0</show_in_store>
327
- </heading_installments>
328
-
329
- <cc_types translate="label">
330
- <label>Credit Card Issuers</label>
331
- <frontend_type>multiselect</frontend_type>
332
- <source_model>Uecommerce_Mundipagg_Model_Source_Cctypes</source_model>
333
- <sort_order>15</sort_order>
334
- <show_in_default>1</show_in_default>
335
- <show_in_website>1</show_in_website>
336
- <show_in_store>1</show_in_store>
337
- <comment><![CDATA[Escolha as bandeiras que você aceita na sua loja]]></comment>
338
- </cc_types>
339
-
340
- <save_cardonfile translate="label">
341
- <label>Instant Buy</label>
342
- <frontend_type>select</frontend_type>
343
- <source_model>adminhtml/system_config_source_yesno</source_model>
344
- <sort_order>16</sort_order>
345
- <show_in_default>1</show_in_default>
346
- <show_in_website>1</show_in_website>
347
- <show_in_store>1</show_in_store>
348
- <comment><![CDATA[Enable customer to save his cards for future purchases.Creditcard numbers are saved in Mundipagg, the store only save a token to the customer card.]]></comment>
349
- </save_cardonfile>
350
-
351
- <enable_installments translate="label">
352
- <label>Installment</label>
353
- <frontend_type>select</frontend_type>
354
- <source_model>adminhtml/system_config_source_yesno</source_model>
355
- <sort_order>17</sort_order>
356
- <show_in_default>1</show_in_default>
357
- <show_in_website>1</show_in_website>
358
- <show_in_store>1</show_in_store>
359
- </enable_installments>
360
-
361
- <display_total>
362
- <label>Exibir total com juros ao lado das parcelas?</label>
363
- <frontend_type>select</frontend_type>
364
- <source_model>adminhtml/system_config_source_yesno</source_model>
365
- <sort_order>18</sort_order>
366
- <depends>
367
- <enable_installments>1</enable_installments>
368
- </depends>
369
- <show_in_default>1</show_in_default>
370
- <show_in_website>1</show_in_website>
371
- <show_in_store>1</show_in_store>
372
- </display_total>
373
-
374
- <product_pages_installment_default>
375
- <label>Qual parcelamento exibir na página do produto?</label>
376
- <frontend_type>select</frontend_type>
377
- <source_model>Uecommerce_Mundipagg_Model_Source_CctypeProductInstallments</source_model>
378
- <sort_order>19</sort_order>
379
- <depends>
380
- <enable_installments>1</enable_installments>
381
- </depends>
382
- <show_in_default>1</show_in_default>
383
- <show_in_website>1</show_in_website>
384
- <show_in_store>1</show_in_store>
385
- </product_pages_installment_default>
386
-
387
- <installments translate="label">
388
- <label>Installments default</label>
389
- <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
390
- <backend_model>mundipagg/system_config_backend_installments</backend_model>
391
- <sort_order>20</sort_order>
392
- <depends>
393
- <enable_installments>1</enable_installments>
394
- </depends>
395
- <show_in_default>1</show_in_default>
396
- <show_in_website>1</show_in_website>
397
- <show_in_store>1</show_in_store>
398
- </installments>
399
-
400
- <installments_VI translate="label">
401
- <label>Installments for Visa</label>
402
- <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
403
- <backend_model>mundipagg/system_config_backend_installments</backend_model>
404
- <sort_order>21</sort_order>
405
- <show_in_default>1</show_in_default>
406
- <show_in_website>1</show_in_website>
407
- <show_in_store>1</show_in_store>
408
- </installments_VI>
409
-
410
- <installments_MC translate="label">
411
- <label>Installments for Mastercard</label>
412
- <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
413
- <backend_model>mundipagg/system_config_backend_installments</backend_model>
414
- <sort_order>22</sort_order>
415
- <show_in_default>1</show_in_default>
416
- <show_in_website>1</show_in_website>
417
- <show_in_store>1</show_in_store>
418
- </installments_MC>
419
-
420
- <installments_AE translate="label">
421
- <label>Installments for Amex</label>
422
- <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
423
- <backend_model>mundipagg/system_config_backend_installments</backend_model>
424
- <sort_order>23</sort_order>
425
- <show_in_default>1</show_in_default>
426
- <show_in_website>1</show_in_website>
427
- <show_in_store>1</show_in_store>
428
- </installments_AE>
429
-
430
- <installments_DI translate="label">
431
- <label>Installments for Diners</label>
432
- <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
433
- <backend_model>mundipagg/system_config_backend_installments</backend_model>
434
- <sort_order>24</sort_order>
435
- <show_in_default>1</show_in_default>
436
- <show_in_website>1</show_in_website>
437
- <show_in_store>1</show_in_store>
438
- <comments>This is the fallback if specific credit card type has no installments configured
439
- </comments>
440
- </installments_DI>
441
-
442
- <installments_EL translate="label">
443
- <label>Installments for Elo</label>
444
- <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
445
- <backend_model>mundipagg/system_config_backend_installments</backend_model>
446
- <sort_order>25</sort_order>
447
- <show_in_default>1</show_in_default>
448
- <show_in_website>1</show_in_website>
449
- <show_in_store>1</show_in_store>
450
-
451
- </installments_EL>
452
-
453
- <installments_HI translate="label">
454
- <label>Installments for Hipercard</label>
455
- <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
456
- <backend_model>mundipagg/system_config_backend_installments</backend_model>
457
- <sort_order>26</sort_order>
458
- <show_in_default>1</show_in_default>
459
- <show_in_website>1</show_in_website>
460
- <show_in_store>1</show_in_store>
461
- </installments_HI>
462
-
463
- <offline_retry_heading translate="label">
464
- <label>Offline Retry</label>
465
- <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
466
- <sort_order>27</sort_order>
467
- <show_in_default>1</show_in_default>
468
- <show_in_website>1</show_in_website>
469
- <show_in_store>0</show_in_store>
470
- </offline_retry_heading>
471
-
472
- <offline_retry_enabled translate="label">
473
- <label>Enabled</label>
474
- <frontend_type>select</frontend_type>
475
- <source_model>adminhtml/system_config_source_yesno</source_model>
476
- <sort_order>28</sort_order>
477
- <show_in_default>1</show_in_default>
478
- <show_in_website>1</show_in_website>
479
- <show_in_store>0</show_in_store>
480
- </offline_retry_enabled>
481
-
482
- <delayed_retry_max_time translate="label">
483
- <label>Max time to retry in minutes</label>
484
- <frontend_type>text</frontend_type>
485
- <sort_order>29</sort_order>
486
- <depends>
487
- <offline_retry_enabled>1</offline_retry_enabled>
488
- </depends>
489
- <show_in_default>1</show_in_default>
490
- <show_in_website>1</show_in_website>
491
- <show_in_store>0</show_in_store>
492
- <comment>Max time to wait for an authorization. After this, the order will be cancelled.</comment>
493
- </delayed_retry_max_time>
494
-
495
- <heading_extras translate="label">
496
- <label>Extras</label>
497
- <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
498
- <sort_order>30</sort_order>
499
- <show_in_default>1</show_in_default>
500
- <show_in_website>1</show_in_website>
501
- <show_in_store>0</show_in_store>
502
- </heading_extras>
503
-
504
- <shipping_company>
505
- <label>Frete Padrão</label>
506
- <frontend_type>text</frontend_type>
507
- <sort_order>31</sort_order>
508
- <show_in_default>1</show_in_default>
509
- <show_website>1</show_website>
510
- <show_in_store>1</show_in_store>
511
- <comment><![CDATA[Empresa que realiza as entregas]]></comment>
512
- </shipping_company>
513
-
514
- <delivery_deadline translate="label">
515
- <label>Média de prazo de entrega</label>
516
- <frontend_type>text</frontend_type>
517
- <sort_order>32</sort_order>
518
- <show_in_default>1</show_in_default>
519
- <show_in_website>1</show_in_website>
520
- <show_in_store>1</show_in_store>
521
- <comment><![CDATA[Quantidade de dias em média para entrega de seus produtos.]]></comment>
522
- </delivery_deadline>
523
-
524
- <cielo_sku translate="label">
525
- <label>SKU produto de teste de R$1,00 da Cielo</label>
526
- <frontend_type>text</frontend_type>
527
- <sort_order>34</sort_order>
528
- <show_in_default>1</show_in_default>
529
- <show_in_website>1</show_in_website>
530
- <show_in_store>1</show_in_store>
531
- <comment>
532
- <![CDATA[SKU do produto de teste da Cielo para forçar o pagamento pela Cielo durante a homologação]]></comment>
533
- </cielo_sku>
534
- </fields>
535
- </mundipagg_standard>
536
-
537
- <mundipagg_creditcard type="group" translate="label">
538
- <label><![CDATA[MundiPagg - Cartão de Crédito]]></label>
539
- <sort_order>430</sort_order>
540
- <show_in_default>1</show_in_default>
541
- <show_in_website>1</show_in_website>
542
- <show_in_store>1</show_in_store>
543
- <comment>
544
- <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
545
- <fields>
546
- <active translate="label">
547
- <label>Enabled</label>
548
- <frontend_type>select</frontend_type>
549
- <source_model>adminhtml/system_config_source_yesno</source_model>
550
- <sort_order>1</sort_order>
551
- <show_in_default>1</show_in_default>
552
- <show_in_website>1</show_in_website>
553
- <show_in_store>1</show_in_store>
554
- </active>
555
-
556
- <title translate="label">
557
- <label>Title</label>
558
- <frontend_type>text</frontend_type>
559
- <sort_order>2</sort_order>
560
- <show_in_default>1</show_in_default>
561
- <show_in_website>1</show_in_website>
562
- <show_in_store>1</show_in_store>
563
- <comment>
564
- <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
565
- </title>
566
-
567
- <allowspecific translate="label">
568
- <label>Payment from Applicable Countries</label>
569
- <frontend_type>allowspecific</frontend_type>
570
- <sort_order>60</sort_order>
571
- <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
572
- <show_in_default>1</show_in_default>
573
- <show_in_website>1</show_in_website>
574
- <show_in_store>1</show_in_store>
575
- </allowspecific>
576
-
577
- <specificcountry translate="label">
578
- <label>Payment from Specific Countries</label>
579
- <frontend_type>multiselect</frontend_type>
580
- <sort_order>61</sort_order>
581
- <source_model>adminhtml/system_config_source_country</source_model>
582
- <show_in_default>1</show_in_default>
583
- <show_in_website>1</show_in_website>
584
- <show_in_store>1</show_in_store>
585
- </specificcountry>
586
-
587
- <min_order_total translate="label">
588
- <label>Min Order Total</label>
589
- <frontend_type>text</frontend_type>
590
- <sort_order>70</sort_order>
591
- <show_in_default>1</show_in_default>
592
- <show_in_website>1</show_in_website>
593
- <show_in_store>1</show_in_store>
594
- <frontend_class>validate-number</frontend_class>
595
- </min_order_total>
596
-
597
- <max_order_total translate="label">
598
- <label>Max Order Total</label>
599
- <frontend_type>text</frontend_type>
600
- <sort_order>80</sort_order>
601
- <show_in_default>1</show_in_default>
602
- <show_in_website>1</show_in_website>
603
- <show_in_store>1</show_in_store>
604
- <frontend_class>validate-number</frontend_class>
605
- </max_order_total>
606
-
607
- <sort_order translate="label">
608
- <label>Sort Order</label>
609
- <frontend_type>text</frontend_type>
610
- <sort_order>100</sort_order>
611
- <show_in_default>1</show_in_default>
612
- <show_in_website>1</show_in_website>
613
- <show_in_store>1</show_in_store>
614
- <frontend_class>validate-number</frontend_class>
615
- </sort_order>
616
- </fields>
617
- </mundipagg_creditcard>
618
- <mundipagg_twocreditcards type="group" translate="label">
619
- <label><![CDATA[MundiPagg - 2 Cartões de Crédito]]></label>
620
- <sort_order>440</sort_order>
621
- <show_in_default>1</show_in_default>
622
- <show_in_website>1</show_in_website>
623
- <show_in_store>1</show_in_store>
624
- <comment>
625
- <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
626
- <fields>
627
- <active translate="label">
628
- <label>Enabled</label>
629
- <frontend_type>select</frontend_type>
630
- <source_model>adminhtml/system_config_source_yesno</source_model>
631
- <sort_order>1</sort_order>
632
- <show_in_default>1</show_in_default>
633
- <show_in_website>1</show_in_website>
634
- <show_in_store>1</show_in_store>
635
- </active>
636
-
637
- <title translate="label">
638
- <label>Title</label>
639
- <frontend_type>text</frontend_type>
640
- <sort_order>2</sort_order>
641
- <show_in_default>1</show_in_default>
642
- <show_in_website>1</show_in_website>
643
- <show_in_store>1</show_in_store>
644
- <comment>
645
- <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
646
- </title>
647
-
648
- <allowspecific translate="label">
649
- <label>Payment from Applicable Countries</label>
650
- <frontend_type>allowspecific</frontend_type>
651
- <sort_order>60</sort_order>
652
- <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
653
- <show_in_default>1</show_in_default>
654
- <show_in_website>1</show_in_website>
655
- <show_in_store>1</show_in_store>
656
- </allowspecific>
657
-
658
- <specificcountry translate="label">
659
- <label>Payment from Specific Countries</label>
660
- <frontend_type>multiselect</frontend_type>
661
- <sort_order>61</sort_order>
662
- <source_model>adminhtml/system_config_source_country</source_model>
663
- <show_in_default>1</show_in_default>
664
- <show_in_website>1</show_in_website>
665
- <show_in_store>1</show_in_store>
666
- </specificcountry>
667
-
668
- <min_order_total translate="label">
669
- <label>Min Order Total</label>
670
- <frontend_type>text</frontend_type>
671
- <sort_order>70</sort_order>
672
- <show_in_default>1</show_in_default>
673
- <show_in_website>1</show_in_website>
674
- <show_in_store>1</show_in_store>
675
- <frontend_class>validate-number</frontend_class>
676
- </min_order_total>
677
-
678
- <max_order_total translate="label">
679
- <label>Max Order Total</label>
680
- <frontend_type>text</frontend_type>
681
- <sort_order>80</sort_order>
682
- <show_in_default>1</show_in_default>
683
- <show_in_website>1</show_in_website>
684
- <show_in_store>1</show_in_store>
685
- <frontend_class>validate-number</frontend_class>
686
- </max_order_total>
687
-
688
- <sort_order translate="label">
689
- <label>Sort Order</label>
690
- <frontend_type>text</frontend_type>
691
- <sort_order>100</sort_order>
692
- <show_in_default>1</show_in_default>
693
- <show_in_website>1</show_in_website>
694
- <show_in_store>1</show_in_store>
695
- <frontend_class>validate-number</frontend_class>
696
- </sort_order>
697
- </fields>
698
- </mundipagg_twocreditcards>
699
- <mundipagg_threecreditcards type="group" translate="label">
700
- <label><![CDATA[MundiPagg - 3 Cartões de Crédito]]></label>
701
- <sort_order>450</sort_order>
702
- <show_in_default>1</show_in_default>
703
- <show_in_website>1</show_in_website>
704
- <show_in_store>1</show_in_store>
705
- <comment>
706
- <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
707
- <fields>
708
- <active translate="label">
709
- <label>Enabled</label>
710
- <frontend_type>select</frontend_type>
711
- <source_model>adminhtml/system_config_source_yesno</source_model>
712
- <sort_order>1</sort_order>
713
- <show_in_default>1</show_in_default>
714
- <show_in_website>1</show_in_website>
715
- <show_in_store>1</show_in_store>
716
- </active>
717
-
718
- <title translate="label">
719
- <label>Title</label>
720
- <frontend_type>text</frontend_type>
721
- <sort_order>2</sort_order>
722
- <show_in_default>1</show_in_default>
723
- <show_in_website>1</show_in_website>
724
- <show_in_store>1</show_in_store>
725
- <comment>
726
- <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
727
- </title>
728
-
729
- <allowspecific translate="label">
730
- <label>Payment from Applicable Countries</label>
731
- <frontend_type>allowspecific</frontend_type>
732
- <sort_order>60</sort_order>
733
- <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
734
- <show_in_default>1</show_in_default>
735
- <show_in_website>1</show_in_website>
736
- <show_in_store>1</show_in_store>
737
- </allowspecific>
738
-
739
- <specificcountry translate="label">
740
- <label>Payment from Specific Countries</label>
741
- <frontend_type>multiselect</frontend_type>
742
- <sort_order>61</sort_order>
743
- <source_model>adminhtml/system_config_source_country</source_model>
744
- <show_in_default>1</show_in_default>
745
- <show_in_website>1</show_in_website>
746
- <show_in_store>1</show_in_store>
747
- </specificcountry>
748
-
749
- <min_order_total translate="label">
750
- <label>Min Order Total</label>
751
- <frontend_type>text</frontend_type>
752
- <sort_order>70</sort_order>
753
- <show_in_default>1</show_in_default>
754
- <show_in_website>1</show_in_website>
755
- <show_in_store>1</show_in_store>
756
- <frontend_class>validate-number</frontend_class>
757
- </min_order_total>
758
-
759
- <max_order_total translate="label">
760
- <label>Max Order Total</label>
761
- <frontend_type>text</frontend_type>
762
- <sort_order>80</sort_order>
763
- <show_in_default>1</show_in_default>
764
- <show_in_website>1</show_in_website>
765
- <show_in_store>1</show_in_store>
766
- <frontend_class>validate-number</frontend_class>
767
- </max_order_total>
768
-
769
- <sort_order translate="label">
770
- <label>Sort Order</label>
771
- <frontend_type>text</frontend_type>
772
- <sort_order>100</sort_order>
773
- <show_in_default>1</show_in_default>
774
- <show_in_website>1</show_in_website>
775
- <show_in_store>1</show_in_store>
776
- <frontend_class>validate-number</frontend_class>
777
- </sort_order>
778
- </fields>
779
- </mundipagg_threecreditcards>
780
- <mundipagg_fourcreditcards type="group" translate="label">
781
- <label><![CDATA[MundiPagg - 4 Cartões de Crédito]]></label>
782
- <sort_order>460</sort_order>
783
- <show_in_default>1</show_in_default>
784
- <show_in_website>1</show_in_website>
785
- <show_in_store>1</show_in_store>
786
- <comment>
787
- <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
788
- <fields>
789
- <active translate="label">
790
- <label>Enabled</label>
791
- <frontend_type>select</frontend_type>
792
- <source_model>adminhtml/system_config_source_yesno</source_model>
793
- <sort_order>1</sort_order>
794
- <show_in_default>1</show_in_default>
795
- <show_in_website>1</show_in_website>
796
- <show_in_store>1</show_in_store>
797
- </active>
798
-
799
- <title translate="label">
800
- <label>Title</label>
801
- <frontend_type>text</frontend_type>
802
- <sort_order>2</sort_order>
803
- <show_in_default>1</show_in_default>
804
- <show_in_website>1</show_in_website>
805
- <show_in_store>1</show_in_store>
806
- <comment>
807
- <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
808
- </title>
809
-
810
- <allowspecific translate="label">
811
- <label>Payment from Applicable Countries</label>
812
- <frontend_type>allowspecific</frontend_type>
813
- <sort_order>60</sort_order>
814
- <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
815
- <show_in_default>1</show_in_default>
816
- <show_in_website>1</show_in_website>
817
- <show_in_store>1</show_in_store>
818
- </allowspecific>
819
-
820
- <specificcountry translate="label">
821
- <label>Payment from Specific Countries</label>
822
- <frontend_type>multiselect</frontend_type>
823
- <sort_order>61</sort_order>
824
- <source_model>adminhtml/system_config_source_country</source_model>
825
- <show_in_default>1</show_in_default>
826
- <show_in_website>1</show_in_website>
827
- <show_in_store>1</show_in_store>
828
- </specificcountry>
829
-
830
- <min_order_total translate="label">
831
- <label>Min Order Total</label>
832
- <frontend_type>text</frontend_type>
833
- <sort_order>70</sort_order>
834
- <show_in_default>1</show_in_default>
835
- <show_in_website>1</show_in_website>
836
- <show_in_store>1</show_in_store>
837
- <frontend_class>validate-number</frontend_class>
838
- </min_order_total>
839
-
840
- <max_order_total translate="label">
841
- <label>Max Order Total</label>
842
- <frontend_type>text</frontend_type>
843
- <sort_order>80</sort_order>
844
- <show_in_default>1</show_in_default>
845
- <show_in_website>1</show_in_website>
846
- <show_in_store>1</show_in_store>
847
- <frontend_class>validate-number</frontend_class>
848
- </max_order_total>
849
-
850
- <sort_order translate="label">
851
- <label>Sort Order</label>
852
- <frontend_type>text</frontend_type>
853
- <sort_order>100</sort_order>
854
- <show_in_default>1</show_in_default>
855
- <show_in_website>1</show_in_website>
856
- <show_in_store>1</show_in_store>
857
- <frontend_class>validate-number</frontend_class>
858
- </sort_order>
859
- </fields>
860
- </mundipagg_fourcreditcards>
861
- <mundipagg_fivecreditcards type="group" translate="label">
862
- <label><![CDATA[MundiPagg - 5 Cartões de Crédito]]></label>
863
- <sort_order>470</sort_order>
864
- <show_in_default>1</show_in_default>
865
- <show_in_website>1</show_in_website>
866
- <show_in_store>1</show_in_store>
867
- <comment>
868
- <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
869
- <fields>
870
- <active translate="label">
871
- <label>Enabled</label>
872
- <frontend_type>select</frontend_type>
873
- <source_model>adminhtml/system_config_source_yesno</source_model>
874
- <sort_order>1</sort_order>
875
- <show_in_default>1</show_in_default>
876
- <show_in_website>1</show_in_website>
877
- <show_in_store>1</show_in_store>
878
- </active>
879
-
880
- <title translate="label">
881
- <label>Title</label>
882
- <frontend_type>text</frontend_type>
883
- <sort_order>2</sort_order>
884
- <show_in_default>1</show_in_default>
885
- <show_in_website>1</show_in_website>
886
- <show_in_store>1</show_in_store>
887
- <comment>
888
- <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
889
- </title>
890
-
891
- <allowspecific translate="label">
892
- <label>Payment from Applicable Countries</label>
893
- <frontend_type>allowspecific</frontend_type>
894
- <sort_order>60</sort_order>
895
- <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
896
- <show_in_default>1</show_in_default>
897
- <show_in_website>1</show_in_website>
898
- <show_in_store>1</show_in_store>
899
- </allowspecific>
900
-
901
- <specificcountry translate="label">
902
- <label>Payment from Specific Countries</label>
903
- <frontend_type>multiselect</frontend_type>
904
- <sort_order>61</sort_order>
905
- <source_model>adminhtml/system_config_source_country</source_model>
906
- <show_in_default>1</show_in_default>
907
- <show_in_website>1</show_in_website>
908
- <show_in_store>1</show_in_store>
909
- </specificcountry>
910
-
911
- <min_order_total translate="label">
912
- <label>Min Order Total</label>
913
- <frontend_type>text</frontend_type>
914
- <sort_order>70</sort_order>
915
- <show_in_default>1</show_in_default>
916
- <show_in_website>1</show_in_website>
917
- <show_in_store>1</show_in_store>
918
- <frontend_class>validate-number</frontend_class>
919
- </min_order_total>
920
-
921
- <max_order_total translate="label">
922
- <label>Max Order Total</label>
923
- <frontend_type>text</frontend_type>
924
- <sort_order>80</sort_order>
925
- <show_in_default>1</show_in_default>
926
- <show_in_website>1</show_in_website>
927
- <show_in_store>1</show_in_store>
928
- <frontend_class>validate-number</frontend_class>
929
- </max_order_total>
930
-
931
- <sort_order translate="label">
932
- <label>Sort Order</label>
933
- <frontend_type>text</frontend_type>
934
- <sort_order>100</sort_order>
935
- <show_in_default>1</show_in_default>
936
- <show_in_website>1</show_in_website>
937
- <show_in_store>1</show_in_store>
938
- <frontend_class>validate-number</frontend_class>
939
- </sort_order>
940
- </fields>
941
- </mundipagg_fivecreditcards>
942
- <mundipagg_boleto type="group" translate="label">
943
- <label><![CDATA[MundiPagg - Boleto]]></label>
944
- <sort_order>480</sort_order>
945
- <show_in_default>1</show_in_default>
946
- <show_in_website>1</show_in_website>
947
- <show_in_store>1</show_in_store>
948
- <comment>
949
- <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
950
- <fields>
951
- <active translate="label">
952
- <label>Enabled</label>
953
- <frontend_type>select</frontend_type>
954
- <source_model>adminhtml/system_config_source_yesno</source_model>
955
- <sort_order>1</sort_order>
956
- <show_in_default>1</show_in_default>
957
- <show_in_website>1</show_in_website>
958
- <show_in_store>1</show_in_store>
959
- </active>
960
-
961
- <title translate="label">
962
- <label>Title</label>
963
- <frontend_type>text</frontend_type>
964
- <sort_order>2</sort_order>
965
- <show_in_default>1</show_in_default>
966
- <show_in_website>1</show_in_website>
967
- <show_in_store>1</show_in_store>
968
- <comment>
969
- <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
970
- </title>
971
-
972
- <dias_validade_boleto translate="label">
973
- <label>Boleto - Dias validade</label>
974
- <frontend_type>text</frontend_type>
975
- <validate>validate-digits</validate>
976
- <sort_order>50</sort_order>
977
- <show_in_default>1</show_in_default>
978
- <show_in_website>1</show_in_website>
979
- <show_in_store>1</show_in_store>
980
- <comment><![CDATA[Quantos dias o Boleto será válido para pagamento?]]></comment>
981
- </dias_validade_boleto>
982
-
983
- <instrucoes_caixa translate="label">
984
- <label>Boleto - Instrucões Caixa</label>
985
- <frontend_type>textarea</frontend_type>
986
- <sort_order>51</sort_order>
987
- <show_in_default>1</show_in_default>
988
- <show_in_website>1</show_in_website>
989
- <show_in_store>1</show_in_store>
990
- <comment>
991
- <![CDATA[Texto sobre as instruções caixa customizado por você que irá aparecer nos seus Boletos Bancários]]></comment>
992
- </instrucoes_caixa>
993
-
994
- <allowspecific translate="label">
995
- <label>Payment from Applicable Countries</label>
996
- <frontend_type>allowspecific</frontend_type>
997
- <sort_order>60</sort_order>
998
- <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
999
- <show_in_default>1</show_in_default>
1000
- <show_in_website>1</show_in_website>
1001
- <show_in_store>1</show_in_store>
1002
- </allowspecific>
1003
-
1004
- <specificcountry translate="label">
1005
- <label>Payment from Specific Countries</label>
1006
- <frontend_type>multiselect</frontend_type>
1007
- <sort_order>61</sort_order>
1008
- <source_model>adminhtml/system_config_source_country</source_model>
1009
- <show_in_default>1</show_in_default>
1010
- <show_in_website>1</show_in_website>
1011
- <show_in_store>1</show_in_store>
1012
- </specificcountry>
1013
-
1014
- <sort_order translate="label">
1015
- <label>Sort Order</label>
1016
- <frontend_type>text</frontend_type>
1017
- <sort_order>100</sort_order>
1018
- <show_in_default>1</show_in_default>
1019
- <show_in_website>1</show_in_website>
1020
- <show_in_store>1</show_in_store>
1021
- <frontend_class>validate-number</frontend_class>
1022
- </sort_order>
1023
- </fields>
1024
- </mundipagg_boleto>
1025
- <mundipagg_debit type="group" translate="label">
1026
- <label><![CDATA[MundiPagg - Debit]]></label>
1027
- <sort_order>480</sort_order>
1028
- <show_in_default>1</show_in_default>
1029
- <show_in_website>1</show_in_website>
1030
- <show_in_store>1</show_in_store>
1031
- <comment>
1032
- <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
1033
- <fields>
1034
- <active translate="label">
1035
- <label>Enabled</label>
1036
- <frontend_type>select</frontend_type>
1037
- <source_model>adminhtml/system_config_source_yesno</source_model>
1038
- <sort_order>1</sort_order>
1039
- <show_in_default>1</show_in_default>
1040
- <show_in_website>1</show_in_website>
1041
- <show_in_store>1</show_in_store>
1042
- </active>
1043
-
1044
- <title translate="label">
1045
- <label>Title</label>
1046
- <frontend_type>text</frontend_type>
1047
- <sort_order>2</sort_order>
1048
- <show_in_default>1</show_in_default>
1049
- <show_in_website>1</show_in_website>
1050
- <show_in_store>1</show_in_store>
1051
- <comment>
1052
- <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
1053
- </title>
1054
-
1055
- <debit_types translate="label">
1056
- <label>Debit</label>
1057
- <frontend_type>multiselect</frontend_type>
1058
- <source_model>Uecommerce_Mundipagg_Model_Source_Debit</source_model>
1059
- <sort_order>3</sort_order>
1060
- <show_in_default>1</show_in_default>
1061
- <show_in_website>1</show_in_website>
1062
- <show_in_store>1</show_in_store>
1063
- <comment><![CDATA[Escolha os débitos que você aceita na sua loja]]></comment>
1064
- </debit_types>
1065
-
1066
- <apiDebitUrl translate="label">
1067
- <label>Api Debit URL</label>
1068
- <frontend_type>text</frontend_type>
1069
- <sort_order>4</sort_order>
1070
- <show_in_default>1</show_in_default>
1071
- <show_in_website>1</show_in_website>
1072
- <show_in_store>1</show_in_store>
1073
- </apiDebitUrl>
1074
-
1075
- <apiDebitStagingUrl translate="label">
1076
- <label>Api Debit Staging URL</label>
1077
- <frontend_type>text</frontend_type>
1078
- <sort_order>5</sort_order>
1079
- <show_in_default>1</show_in_default>
1080
- <show_in_website>1</show_in_website>
1081
- <show_in_store>1</show_in_store>
1082
- </apiDebitStagingUrl>
1083
-
1084
- <allowspecific translate="label">
1085
- <label>Payment from Applicable Countries</label>
1086
- <frontend_type>allowspecific</frontend_type>
1087
- <sort_order>6</sort_order>
1088
- <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
1089
- <show_in_default>1</show_in_default>
1090
- <show_in_website>1</show_in_website>
1091
- <show_in_store>1</show_in_store>
1092
- </allowspecific>
1093
-
1094
- <specificcountry translate="label">
1095
- <label>Payment from Specific Countries</label>
1096
- <frontend_type>multiselect</frontend_type>
1097
- <sort_order>7</sort_order>
1098
- <source_model>adminhtml/system_config_source_country</source_model>
1099
- <show_in_default>1</show_in_default>
1100
- <show_in_website>1</show_in_website>
1101
- <show_in_store>1</show_in_store>
1102
- </specificcountry>
1103
-
1104
- <sort_order translate="label">
1105
- <label>Sort Order</label>
1106
- <frontend_type>text</frontend_type>
1107
- <sort_order>8</sort_order>
1108
- <show_in_default>1</show_in_default>
1109
- <show_in_website>1</show_in_website>
1110
- <show_in_store>1</show_in_store>
1111
- <frontend_class>validate-number</frontend_class>
1112
- </sort_order>
1113
- </fields>
1114
- </mundipagg_debit>
1115
- </groups>
1116
- </payment>
1117
- </sections>
 
1118
  </config>
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <sections>
4
+ <payment translate="label" module="payment">
5
+ <groups>
6
+ <mundipagg_standard type="group" translate="label">
7
+ <label><![CDATA[MundiPagg]]></label>
8
+ <sort_order>420</sort_order>
9
+ <show_in_default>1</show_in_default>
10
+ <show_in_website>1</show_in_website>
11
+ <show_in_store>1</show_in_store>
12
+ <comment>
13
+ <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
14
+
15
+ <fields>
16
+ <heading_basic_config translate="label">
17
+ <label>Module Basic Configuration</label>
18
+ <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
19
+ <sort_order>0</sort_order>
20
+ <show_in_default>1</show_in_default>
21
+ <show_in_website>1</show_in_website>
22
+ <show_in_store>0</show_in_store>
23
+ </heading_basic_config>
24
+
25
+ <version translate="label">
26
+ <label>Version</label>
27
+ <frontend_type>select</frontend_type>
28
+ <frontend_model>Uecommerce_Mundipagg_Block_Adminhtml_Version</frontend_model>
29
+ <sort_order>1</sort_order>
30
+ <show_in_default>1</show_in_default>
31
+ <show_in_website>1</show_in_website>
32
+ <show_in_store>1</show_in_store>
33
+ </version>
34
+
35
+ <environment translate="label">
36
+ <label>Environment</label>
37
+ <frontend_type>select</frontend_type>
38
+ <source_model>Uecommerce_Mundipagg_Model_Source_Environment</source_model>
39
+ <sort_order>2</sort_order>
40
+ <show_in_default>1</show_in_default>
41
+ <show_in_website>1</show_in_website>
42
+ <show_in_store>1</show_in_store>
43
+ <comment>
44
+ <![CDATA[<b>Sandbox</b> = ambiente de teste<br/><b>Production</b> = ambiente de produção]]></comment>
45
+ </environment>
46
+
47
+ <apiUrlStaging translate="label">
48
+ <label>API URL Sandbox</label>
49
+ <frontend_type>text</frontend_type>
50
+ <sort_order>3</sort_order>
51
+ <backend_model>mundipagg/urlvalidation</backend_model>
52
+ <depends>
53
+ <environment>development</environment>
54
+ </depends>
55
+ <show_in_default>1</show_in_default>
56
+ <show_in_website>1</show_in_website>
57
+ <show_in_store>1</show_in_store>
58
+ </apiUrlStaging>
59
+
60
+ <merchantKeyStaging translate="label">
61
+ <label>MerchantKey Sandbox</label>
62
+ <frontend_type>text</frontend_type>
63
+ <sort_order>4</sort_order>
64
+ <depends>
65
+ <environment>development</environment>
66
+ </depends>
67
+ <show_in_default>1</show_in_default>
68
+ <show_in_website>1</show_in_website>
69
+ <show_in_store>1</show_in_store>
70
+ </merchantKeyStaging>
71
+
72
+ <apiUrlProduction translate="label">
73
+ <label>API URL Production</label>
74
+ <frontend_type>text</frontend_type>
75
+ <sort_order>3</sort_order>
76
+ <backend_model>mundipagg/urlvalidation</backend_model>
77
+ <depends>
78
+ <environment>production</environment>
79
+ </depends>
80
+ <show_in_default>1</show_in_default>
81
+ <show_in_website>1</show_in_website>
82
+ <show_in_store>1</show_in_store>
83
+ </apiUrlProduction>
84
+
85
+ <merchantKeyProduction translate="label">
86
+ <label>MerchantKey Production</label>
87
+ <frontend_type>text</frontend_type>
88
+ <sort_order>4</sort_order>
89
+ <depends>
90
+ <environment>production</environment>
91
+ </depends>
92
+ <show_in_default>1</show_in_default>
93
+ <show_in_website>1</show_in_website>
94
+ <show_in_store>1</show_in_store>
95
+ </merchantKeyProduction>
96
+
97
+ <debug translate="label">
98
+ <label>Logs</label>
99
+ <frontend_type>select</frontend_type>
100
+ <source_model>adminhtml/system_config_source_yesno</source_model>
101
+ <backend_model>Uecommerce_Mundipagg_Model_Adminvalidators_Debug</backend_model>
102
+ <sort_order>5</sort_order>
103
+ <show_in_default>1</show_in_default>
104
+ <show_in_website>1</show_in_website>
105
+ <show_in_store>1</show_in_store>
106
+ <comment>
107
+ <![CDATA[Grava o retorno da MundiPagg nos logs do Magento. Habilitar esta opção irá habilitar os logs do Magento (System -> Configuration -> Advanced -> Developer -> Log Settings -> Yes)]]></comment>
108
+ </debug>
109
+
110
+ <payment_action translate="label">
111
+ <label>Payment Action</label>
112
+ <frontend_type>select</frontend_type>
113
+ <source_model>Uecommerce_Mundipagg_Model_Source_PaymentAction</source_model>
114
+ <sort_order>6</sort_order>
115
+ <show_in_default>1</show_in_default>
116
+ <show_in_website>1</show_in_website>
117
+ <show_in_store>1</show_in_store>
118
+ <comment>
119
+ <![CDATA[<b>AuthOnly</b> = Autorizar<br/><b>AuthAndCapture</b> = Autorizar e capturar]]></comment>
120
+ </payment_action>
121
+
122
+ <heading_anti_fraud translate="label">
123
+ <label>Anti fraud</label>
124
+ <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
125
+ <sort_order>7</sort_order>
126
+ <show_in_default>1</show_in_default>
127
+ <show_in_website>1</show_in_website>
128
+ <show_in_store>0</show_in_store>
129
+ </heading_anti_fraud>
130
+
131
+ <antifraud translate="label">
132
+ <label>Enabled</label>
133
+ <frontend_type>select</frontend_type>
134
+ <source_model>adminhtml/system_config_source_yesno</source_model>
135
+ <sort_order>8</sort_order>
136
+ <show_in_default>1</show_in_default>
137
+ <show_in_website>1</show_in_website>
138
+ <show_in_store>1</show_in_store>
139
+ </antifraud>
140
+
141
+ <antifraud_provider translate="label">
142
+ <label>Anti Fraud Provider</label>
143
+ <frontend_type>select</frontend_type>
144
+ <source_model>Uecommerce_Mundipagg_Model_Source_Antifraud</source_model>
145
+ <backend_model>mundipagg/providervalidation</backend_model>
146
+ <sort_order>9</sort_order>
147
+ <depends>
148
+ <antifraud>1</antifraud>
149
+ </depends>
150
+ <validates>required-entry</validates>
151
+ <show_in_default>1</show_in_default>
152
+ <show_in_website>1</show_in_website>
153
+ <show_in_store>1</show_in_store>
154
+ </antifraud_provider>
155
+
156
+ <antifraud_minimum_clearsale>
157
+ <label>Order Minimum Value</label>
158
+ <frontend_type>text</frontend_type>
159
+ <backend_model>Uecommerce_Mundipagg_Model_Adminvalidators_Antifraud_Minval</backend_model>
160
+ <depends>
161
+ <antifraud>1</antifraud>
162
+ <antifraud_provider>1</antifraud_provider>
163
+ </depends>
164
+ <sort_order>10</sort_order>
165
+ <show_in_default>1</show_in_default>
166
+ <show_in_website>1</show_in_website>
167
+ <show_in_store>1</show_in_store>
168
+ <comment>Valid formats: 0.00 - 0,00</comment>
169
+ </antifraud_minimum_clearsale>
170
+
171
+ <antifraud_minimum_fcontrol>
172
+ <label>Order Minimum Value</label>
173
+ <frontend_type>text</frontend_type>
174
+ <backend_model>Uecommerce_Mundipagg_Model_Adminvalidators_Antifraud_Minval</backend_model>
175
+ <depends>
176
+ <antifraud>1</antifraud>
177
+ <antifraud_provider>2</antifraud_provider>
178
+ </depends>
179
+ <sort_order>10</sort_order>
180
+ <show_in_default>1</show_in_default>
181
+ <show_in_website>1</show_in_website>
182
+ <show_in_store>1</show_in_store>
183
+ <comment>Valid formats: 0.00 - 0,00</comment>
184
+ </antifraud_minimum_fcontrol>
185
+
186
+ <antifraud_minimum_stone>
187
+ <label>Order Minimum Value</label>
188
+ <frontend_type>text</frontend_type>
189
+ <backend_model>Uecommerce_Mundipagg_Model_Adminvalidators_Antifraud_Minval</backend_model>
190
+ <depends>
191
+ <antifraud>1</antifraud>
192
+ <antifraud_provider>3</antifraud_provider>
193
+ </depends>
194
+ <sort_order>10</sort_order>
195
+ <show_in_default>1</show_in_default>
196
+ <show_in_website>1</show_in_website>
197
+ <show_in_store>1</show_in_store>
198
+ <comment>Valid formats: 0.00 - 0,00</comment>
199
+ </antifraud_minimum_stone>
200
+
201
+ <fingerprint translate="label">
202
+ <label>Fingerprint</label>
203
+ <frontend_type>select</frontend_type>
204
+ <source_model>adminhtml/system_config_source_yesno</source_model>
205
+ <depends>
206
+ <antifraud>1</antifraud>
207
+ </depends>
208
+ <sort_order>11</sort_order>
209
+ <show_in_default>1</show_in_default>
210
+ <show_in_website>1</show_in_website>
211
+ <show_in_store>1</show_in_store>
212
+ </fingerprint>
213
+
214
+ <environment_fcontrol translate="label">
215
+ <label>Fingerprint environment</label>
216
+ <frontend_type>select</frontend_type>
217
+ <source_model>Uecommerce_Mundipagg_Model_Source_FControlEnvironment</source_model>
218
+ <depends>
219
+ <antifraud>1</antifraud>
220
+ <antifraud_provider>2</antifraud_provider>
221
+ <fingerprint>1</fingerprint>
222
+ </depends>
223
+ <sort_order>12</sort_order>
224
+ <show_in_default>1</show_in_default>
225
+ <show_in_website>1</show_in_website>
226
+ <show_in_store>1</show_in_store>
227
+ </environment_fcontrol>
228
+
229
+ <fcontrol_key_sandbox translate="label">
230
+ <label>FControl sandbox key</label>
231
+ <frontend_type>text</frontend_type>
232
+ <sort_order>13</sort_order>
233
+ <depends>
234
+ <antifraud>1</antifraud>
235
+ <antifraud_provider>2</antifraud_provider>
236
+ <fingerprint>1</fingerprint>
237
+ <environment_fcontrol>1</environment_fcontrol>
238
+ </depends>
239
+ <show_in_default>1</show_in_default>
240
+ <show_in_website>1</show_in_website>
241
+ <show_in_store>1</show_in_store>
242
+ <comment>Chave informada pela FControl</comment>
243
+ </fcontrol_key_sandbox>
244
+
245
+ <fcontrol_key_production translate="label">
246
+ <label>FControl production key</label>
247
+ <frontend_type>text</frontend_type>
248
+ <sort_order>13</sort_order>
249
+ <depends>
250
+ <antifraud>1</antifraud>
251
+ <antifraud_provider>2</antifraud_provider>
252
+ <environment_fcontrol>2</environment_fcontrol>
253
+ </depends>
254
+ <show_in_default>1</show_in_default>
255
+ <show_in_website>1</show_in_website>
256
+ <show_in_store>1</show_in_store>
257
+ <comment>Chave informada pela FControl</comment>
258
+ </fcontrol_key_production>
259
+
260
+ <clearsale_entitycode translate="label">
261
+ <label>EntityCode</label>
262
+ <frontend_type>text</frontend_type>
263
+ <sort_order>12</sort_order>
264
+ <depends>
265
+ <antifraud>1</antifraud>
266
+ <antifraud_provider>1</antifraud_provider>
267
+ <fingerprint>1</fingerprint>
268
+ </depends>
269
+ <show_in_default>1</show_in_default>
270
+ <show_in_website>1</show_in_website>
271
+ <show_in_store>1</show_in_store>
272
+ <comment>Chave informada pela Clearsale</comment>
273
+ </clearsale_entitycode>
274
+
275
+ <stone_entitycode translate="label">
276
+ <label>EntityCode</label>
277
+ <frontend_type>text</frontend_type>
278
+ <sort_order>12</sort_order>
279
+ <depends>
280
+ <antifraud>1</antifraud>
281
+ <antifraud_provider>3</antifraud_provider>
282
+ <fingerprint>1</fingerprint>
283
+ </depends>
284
+ <show_in_default>1</show_in_default>
285
+ <show_in_website>1</show_in_website>
286
+ <show_in_store>1</show_in_store>
287
+ <comment>Chave informada pela Stone</comment>
288
+ </stone_entitycode>
289
+
290
+ <clearsale_app translate="label">
291
+ <label>AppKey</label>
292
+ <frontend_type>text</frontend_type>
293
+ <sort_order>13</sort_order>
294
+ <depends>
295
+ <antifraud>1</antifraud>
296
+ <antifraud_provider>1</antifraud_provider>
297
+ <fingerprint>1</fingerprint>
298
+ </depends>
299
+ <show_in_default>1</show_in_default>
300
+ <show_in_website>1</show_in_website>
301
+ <show_in_store>1</show_in_store>
302
+ <comment>codigo informado pela Clearsale</comment>
303
+ </clearsale_app>
304
+
305
+ <stone_app translate="label">
306
+ <label>AppKey</label>
307
+ <frontend_type>text</frontend_type>
308
+ <sort_order>13</sort_order>
309
+ <depends>
310
+ <antifraud>1</antifraud>
311
+ <antifraud_provider>3</antifraud_provider>
312
+ <fingerprint>1</fingerprint>
313
+ </depends>
314
+ <show_in_default>1</show_in_default>
315
+ <show_in_website>1</show_in_website>
316
+ <show_in_store>1</show_in_store>
317
+ <comment>codigo informado pela Stone</comment>
318
+ </stone_app>
319
+
320
+ <heading_installments translate="label">
321
+ <label>Credit Card Basic Configuration</label>
322
+ <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
323
+ <sort_order>14</sort_order>
324
+ <show_in_default>1</show_in_default>
325
+ <show_in_website>1</show_in_website>
326
+ <show_in_store>0</show_in_store>
327
+ </heading_installments>
328
+
329
+ <cc_types translate="label">
330
+ <label>Credit Card Issuers</label>
331
+ <frontend_type>multiselect</frontend_type>
332
+ <source_model>Uecommerce_Mundipagg_Model_Source_Cctypes</source_model>
333
+ <sort_order>15</sort_order>
334
+ <show_in_default>1</show_in_default>
335
+ <show_in_website>1</show_in_website>
336
+ <show_in_store>1</show_in_store>
337
+ <comment><![CDATA[Escolha as bandeiras que você aceita na sua loja]]></comment>
338
+ </cc_types>
339
+
340
+ <save_cardonfile translate="label">
341
+ <label>Instant Buy</label>
342
+ <frontend_type>select</frontend_type>
343
+ <source_model>adminhtml/system_config_source_yesno</source_model>
344
+ <sort_order>16</sort_order>
345
+ <show_in_default>1</show_in_default>
346
+ <show_in_website>1</show_in_website>
347
+ <show_in_store>1</show_in_store>
348
+ <comment><![CDATA[Enable customer to save his cards for future purchases.Creditcard numbers are saved in Mundipagg, the store only save a token to the customer card.]]></comment>
349
+ </save_cardonfile>
350
+
351
+ <enable_installments translate="label">
352
+ <label>Installment</label>
353
+ <frontend_type>select</frontend_type>
354
+ <source_model>adminhtml/system_config_source_yesno</source_model>
355
+ <sort_order>17</sort_order>
356
+ <show_in_default>1</show_in_default>
357
+ <show_in_website>1</show_in_website>
358
+ <show_in_store>1</show_in_store>
359
+ </enable_installments>
360
+
361
+ <display_total>
362
+ <label>Exibir total com juros ao lado das parcelas?</label>
363
+ <frontend_type>select</frontend_type>
364
+ <source_model>adminhtml/system_config_source_yesno</source_model>
365
+ <sort_order>18</sort_order>
366
+ <depends>
367
+ <enable_installments>1</enable_installments>
368
+ </depends>
369
+ <show_in_default>1</show_in_default>
370
+ <show_in_website>1</show_in_website>
371
+ <show_in_store>1</show_in_store>
372
+ </display_total>
373
+
374
+ <product_pages_installment_default>
375
+ <label>Qual parcelamento exibir na página do produto?</label>
376
+ <frontend_type>select</frontend_type>
377
+ <source_model>Uecommerce_Mundipagg_Model_Source_CctypeProductInstallments</source_model>
378
+ <sort_order>19</sort_order>
379
+ <depends>
380
+ <enable_installments>1</enable_installments>
381
+ </depends>
382
+ <show_in_default>1</show_in_default>
383
+ <show_in_website>1</show_in_website>
384
+ <show_in_store>1</show_in_store>
385
+ </product_pages_installment_default>
386
+
387
+ <installments translate="label">
388
+ <label>Installments default</label>
389
+ <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
390
+ <backend_model>mundipagg/system_config_backend_installments</backend_model>
391
+ <sort_order>20</sort_order>
392
+ <depends>
393
+ <enable_installments>1</enable_installments>
394
+ </depends>
395
+ <show_in_default>1</show_in_default>
396
+ <show_in_website>1</show_in_website>
397
+ <show_in_store>1</show_in_store>
398
+ </installments>
399
+
400
+ <installments_VI translate="label">
401
+ <label>Installments for Visa</label>
402
+ <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
403
+ <backend_model>mundipagg/system_config_backend_installments</backend_model>
404
+ <sort_order>21</sort_order>
405
+ <show_in_default>1</show_in_default>
406
+ <show_in_website>1</show_in_website>
407
+ <show_in_store>1</show_in_store>
408
+ </installments_VI>
409
+
410
+ <installments_MC translate="label">
411
+ <label>Installments for Mastercard</label>
412
+ <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
413
+ <backend_model>mundipagg/system_config_backend_installments</backend_model>
414
+ <sort_order>22</sort_order>
415
+ <show_in_default>1</show_in_default>
416
+ <show_in_website>1</show_in_website>
417
+ <show_in_store>1</show_in_store>
418
+ </installments_MC>
419
+
420
+ <installments_AE translate="label">
421
+ <label>Installments for Amex</label>
422
+ <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
423
+ <backend_model>mundipagg/system_config_backend_installments</backend_model>
424
+ <sort_order>23</sort_order>
425
+ <show_in_default>1</show_in_default>
426
+ <show_in_website>1</show_in_website>
427
+ <show_in_store>1</show_in_store>
428
+ </installments_AE>
429
+
430
+ <installments_DI translate="label">
431
+ <label>Installments for Diners</label>
432
+ <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
433
+ <backend_model>mundipagg/system_config_backend_installments</backend_model>
434
+ <sort_order>24</sort_order>
435
+ <show_in_default>1</show_in_default>
436
+ <show_in_website>1</show_in_website>
437
+ <show_in_store>1</show_in_store>
438
+ <comments>This is the fallback if specific credit card type has no installments configured
439
+ </comments>
440
+ </installments_DI>
441
+
442
+ <installments_EL translate="label">
443
+ <label>Installments for Elo</label>
444
+ <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
445
+ <backend_model>mundipagg/system_config_backend_installments</backend_model>
446
+ <sort_order>25</sort_order>
447
+ <show_in_default>1</show_in_default>
448
+ <show_in_website>1</show_in_website>
449
+ <show_in_store>1</show_in_store>
450
+
451
+ </installments_EL>
452
+
453
+ <installments_HI translate="label">
454
+ <label>Installments for Hipercard</label>
455
+ <frontend_model>mundipagg/adminhtml_form_field_installments</frontend_model>
456
+ <backend_model>mundipagg/system_config_backend_installments</backend_model>
457
+ <sort_order>26</sort_order>
458
+ <show_in_default>1</show_in_default>
459
+ <show_in_website>1</show_in_website>
460
+ <show_in_store>1</show_in_store>
461
+ </installments_HI>
462
+
463
+ <offline_retry_heading translate="label">
464
+ <label>Offline Retry</label>
465
+ <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
466
+ <sort_order>27</sort_order>
467
+ <show_in_default>1</show_in_default>
468
+ <show_in_website>1</show_in_website>
469
+ <show_in_store>0</show_in_store>
470
+ </offline_retry_heading>
471
+
472
+ <offline_retry_enabled translate="label">
473
+ <label>Enabled</label>
474
+ <frontend_type>select</frontend_type>
475
+ <source_model>adminhtml/system_config_source_yesno</source_model>
476
+ <backend_model>Uecommerce_Mundipagg_Model_Adminvalidators_Offlineretry</backend_model>
477
+ <sort_order>28</sort_order>
478
+ <show_in_default>1</show_in_default>
479
+ <show_in_website>1</show_in_website>
480
+ <show_in_store>0</show_in_store>
481
+ </offline_retry_enabled>
482
+
483
+ <delayed_retry_max_time translate="label">
484
+ <label>Max time to retry in minutes</label>
485
+ <frontend_type>text</frontend_type>
486
+ <sort_order>29</sort_order>
487
+ <depends>
488
+ <offline_retry_enabled>1</offline_retry_enabled>
489
+ </depends>
490
+ <show_in_default>1</show_in_default>
491
+ <show_in_website>1</show_in_website>
492
+ <show_in_store>0</show_in_store>
493
+ <comment>Max time to wait for an authorization. After this, the order will be cancelled.</comment>
494
+ </delayed_retry_max_time>
495
+
496
+ <heading_extras translate="label">
497
+ <label>Extras</label>
498
+ <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
499
+ <sort_order>30</sort_order>
500
+ <show_in_default>1</show_in_default>
501
+ <show_in_website>1</show_in_website>
502
+ <show_in_store>0</show_in_store>
503
+ </heading_extras>
504
+
505
+ <shipping_company>
506
+ <label>Frete Padrão</label>
507
+ <frontend_type>text</frontend_type>
508
+ <sort_order>31</sort_order>
509
+ <show_in_default>1</show_in_default>
510
+ <show_website>1</show_website>
511
+ <show_in_store>1</show_in_store>
512
+ <comment><![CDATA[Empresa que realiza as entregas]]></comment>
513
+ </shipping_company>
514
+
515
+ <delivery_deadline translate="label">
516
+ <label>Média de prazo de entrega</label>
517
+ <frontend_type>text</frontend_type>
518
+ <sort_order>32</sort_order>
519
+ <show_in_default>1</show_in_default>
520
+ <show_in_website>1</show_in_website>
521
+ <show_in_store>1</show_in_store>
522
+ <comment><![CDATA[Quantidade de dias em média para entrega de seus produtos.]]></comment>
523
+ </delivery_deadline>
524
+
525
+ <cielo_sku translate="label">
526
+ <label>SKU produto de teste de R$1,00 da Cielo</label>
527
+ <frontend_type>text</frontend_type>
528
+ <sort_order>34</sort_order>
529
+ <show_in_default>1</show_in_default>
530
+ <show_in_website>1</show_in_website>
531
+ <show_in_store>1</show_in_store>
532
+ <comment>
533
+ <![CDATA[SKU do produto de teste da Cielo para forçar o pagamento pela Cielo durante a homologação]]></comment>
534
+ </cielo_sku>
535
+ </fields>
536
+ </mundipagg_standard>
537
+
538
+ <mundipagg_creditcard type="group" translate="label">
539
+ <label><![CDATA[MundiPagg - Cartão de Crédito]]></label>
540
+ <sort_order>430</sort_order>
541
+ <show_in_default>1</show_in_default>
542
+ <show_in_website>1</show_in_website>
543
+ <show_in_store>1</show_in_store>
544
+ <comment>
545
+ <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
546
+ <fields>
547
+ <active translate="label">
548
+ <label>Enabled</label>
549
+ <frontend_type>select</frontend_type>
550
+ <source_model>adminhtml/system_config_source_yesno</source_model>
551
+ <sort_order>1</sort_order>
552
+ <show_in_default>1</show_in_default>
553
+ <show_in_website>1</show_in_website>
554
+ <show_in_store>1</show_in_store>
555
+ </active>
556
+
557
+ <title translate="label">
558
+ <label>Title</label>
559
+ <frontend_type>text</frontend_type>
560
+ <sort_order>2</sort_order>
561
+ <show_in_default>1</show_in_default>
562
+ <show_in_website>1</show_in_website>
563
+ <show_in_store>1</show_in_store>
564
+ <comment>
565
+ <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
566
+ </title>
567
+
568
+ <allowspecific translate="label">
569
+ <label>Payment from Applicable Countries</label>
570
+ <frontend_type>allowspecific</frontend_type>
571
+ <sort_order>60</sort_order>
572
+ <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
573
+ <show_in_default>1</show_in_default>
574
+ <show_in_website>1</show_in_website>
575
+ <show_in_store>1</show_in_store>
576
+ </allowspecific>
577
+
578
+ <specificcountry translate="label">
579
+ <label>Payment from Specific Countries</label>
580
+ <frontend_type>multiselect</frontend_type>
581
+ <sort_order>61</sort_order>
582
+ <source_model>adminhtml/system_config_source_country</source_model>
583
+ <show_in_default>1</show_in_default>
584
+ <show_in_website>1</show_in_website>
585
+ <show_in_store>1</show_in_store>
586
+ </specificcountry>
587
+
588
+ <min_order_total translate="label">
589
+ <label>Min Order Total</label>
590
+ <frontend_type>text</frontend_type>
591
+ <sort_order>70</sort_order>
592
+ <show_in_default>1</show_in_default>
593
+ <show_in_website>1</show_in_website>
594
+ <show_in_store>1</show_in_store>
595
+ <frontend_class>validate-number</frontend_class>
596
+ </min_order_total>
597
+
598
+ <max_order_total translate="label">
599
+ <label>Max Order Total</label>
600
+ <frontend_type>text</frontend_type>
601
+ <sort_order>80</sort_order>
602
+ <show_in_default>1</show_in_default>
603
+ <show_in_website>1</show_in_website>
604
+ <show_in_store>1</show_in_store>
605
+ <frontend_class>validate-number</frontend_class>
606
+ </max_order_total>
607
+
608
+ <sort_order translate="label">
609
+ <label>Sort Order</label>
610
+ <frontend_type>text</frontend_type>
611
+ <sort_order>100</sort_order>
612
+ <show_in_default>1</show_in_default>
613
+ <show_in_website>1</show_in_website>
614
+ <show_in_store>1</show_in_store>
615
+ <frontend_class>validate-number</frontend_class>
616
+ </sort_order>
617
+ </fields>
618
+ </mundipagg_creditcard>
619
+ <mundipagg_twocreditcards type="group" translate="label">
620
+ <label><![CDATA[MundiPagg - 2 Cartões de Crédito]]></label>
621
+ <sort_order>440</sort_order>
622
+ <show_in_default>1</show_in_default>
623
+ <show_in_website>1</show_in_website>
624
+ <show_in_store>1</show_in_store>
625
+ <comment>
626
+ <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
627
+ <fields>
628
+ <active translate="label">
629
+ <label>Enabled</label>
630
+ <frontend_type>select</frontend_type>
631
+ <source_model>adminhtml/system_config_source_yesno</source_model>
632
+ <sort_order>1</sort_order>
633
+ <show_in_default>1</show_in_default>
634
+ <show_in_website>1</show_in_website>
635
+ <show_in_store>1</show_in_store>
636
+ </active>
637
+
638
+ <title translate="label">
639
+ <label>Title</label>
640
+ <frontend_type>text</frontend_type>
641
+ <sort_order>2</sort_order>
642
+ <show_in_default>1</show_in_default>
643
+ <show_in_website>1</show_in_website>
644
+ <show_in_store>1</show_in_store>
645
+ <comment>
646
+ <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
647
+ </title>
648
+
649
+ <allowspecific translate="label">
650
+ <label>Payment from Applicable Countries</label>
651
+ <frontend_type>allowspecific</frontend_type>
652
+ <sort_order>60</sort_order>
653
+ <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
654
+ <show_in_default>1</show_in_default>
655
+ <show_in_website>1</show_in_website>
656
+ <show_in_store>1</show_in_store>
657
+ </allowspecific>
658
+
659
+ <specificcountry translate="label">
660
+ <label>Payment from Specific Countries</label>
661
+ <frontend_type>multiselect</frontend_type>
662
+ <sort_order>61</sort_order>
663
+ <source_model>adminhtml/system_config_source_country</source_model>
664
+ <show_in_default>1</show_in_default>
665
+ <show_in_website>1</show_in_website>
666
+ <show_in_store>1</show_in_store>
667
+ </specificcountry>
668
+
669
+ <min_order_total translate="label">
670
+ <label>Min Order Total</label>
671
+ <frontend_type>text</frontend_type>
672
+ <sort_order>70</sort_order>
673
+ <show_in_default>1</show_in_default>
674
+ <show_in_website>1</show_in_website>
675
+ <show_in_store>1</show_in_store>
676
+ <frontend_class>validate-number</frontend_class>
677
+ </min_order_total>
678
+
679
+ <max_order_total translate="label">
680
+ <label>Max Order Total</label>
681
+ <frontend_type>text</frontend_type>
682
+ <sort_order>80</sort_order>
683
+ <show_in_default>1</show_in_default>
684
+ <show_in_website>1</show_in_website>
685
+ <show_in_store>1</show_in_store>
686
+ <frontend_class>validate-number</frontend_class>
687
+ </max_order_total>
688
+
689
+ <sort_order translate="label">
690
+ <label>Sort Order</label>
691
+ <frontend_type>text</frontend_type>
692
+ <sort_order>100</sort_order>
693
+ <show_in_default>1</show_in_default>
694
+ <show_in_website>1</show_in_website>
695
+ <show_in_store>1</show_in_store>
696
+ <frontend_class>validate-number</frontend_class>
697
+ </sort_order>
698
+ </fields>
699
+ </mundipagg_twocreditcards>
700
+ <mundipagg_threecreditcards type="group" translate="label">
701
+ <label><![CDATA[MundiPagg - 3 Cartões de Crédito]]></label>
702
+ <sort_order>450</sort_order>
703
+ <show_in_default>1</show_in_default>
704
+ <show_in_website>1</show_in_website>
705
+ <show_in_store>1</show_in_store>
706
+ <comment>
707
+ <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
708
+ <fields>
709
+ <active translate="label">
710
+ <label>Enabled</label>
711
+ <frontend_type>select</frontend_type>
712
+ <source_model>adminhtml/system_config_source_yesno</source_model>
713
+ <sort_order>1</sort_order>
714
+ <show_in_default>1</show_in_default>
715
+ <show_in_website>1</show_in_website>
716
+ <show_in_store>1</show_in_store>
717
+ </active>
718
+
719
+ <title translate="label">
720
+ <label>Title</label>
721
+ <frontend_type>text</frontend_type>
722
+ <sort_order>2</sort_order>
723
+ <show_in_default>1</show_in_default>
724
+ <show_in_website>1</show_in_website>
725
+ <show_in_store>1</show_in_store>
726
+ <comment>
727
+ <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
728
+ </title>
729
+
730
+ <allowspecific translate="label">
731
+ <label>Payment from Applicable Countries</label>
732
+ <frontend_type>allowspecific</frontend_type>
733
+ <sort_order>60</sort_order>
734
+ <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
735
+ <show_in_default>1</show_in_default>
736
+ <show_in_website>1</show_in_website>
737
+ <show_in_store>1</show_in_store>
738
+ </allowspecific>
739
+
740
+ <specificcountry translate="label">
741
+ <label>Payment from Specific Countries</label>
742
+ <frontend_type>multiselect</frontend_type>
743
+ <sort_order>61</sort_order>
744
+ <source_model>adminhtml/system_config_source_country</source_model>
745
+ <show_in_default>1</show_in_default>
746
+ <show_in_website>1</show_in_website>
747
+ <show_in_store>1</show_in_store>
748
+ </specificcountry>
749
+
750
+ <min_order_total translate="label">
751
+ <label>Min Order Total</label>
752
+ <frontend_type>text</frontend_type>
753
+ <sort_order>70</sort_order>
754
+ <show_in_default>1</show_in_default>
755
+ <show_in_website>1</show_in_website>
756
+ <show_in_store>1</show_in_store>
757
+ <frontend_class>validate-number</frontend_class>
758
+ </min_order_total>
759
+
760
+ <max_order_total translate="label">
761
+ <label>Max Order Total</label>
762
+ <frontend_type>text</frontend_type>
763
+ <sort_order>80</sort_order>
764
+ <show_in_default>1</show_in_default>
765
+ <show_in_website>1</show_in_website>
766
+ <show_in_store>1</show_in_store>
767
+ <frontend_class>validate-number</frontend_class>
768
+ </max_order_total>
769
+
770
+ <sort_order translate="label">
771
+ <label>Sort Order</label>
772
+ <frontend_type>text</frontend_type>
773
+ <sort_order>100</sort_order>
774
+ <show_in_default>1</show_in_default>
775
+ <show_in_website>1</show_in_website>
776
+ <show_in_store>1</show_in_store>
777
+ <frontend_class>validate-number</frontend_class>
778
+ </sort_order>
779
+ </fields>
780
+ </mundipagg_threecreditcards>
781
+ <mundipagg_fourcreditcards type="group" translate="label">
782
+ <label><![CDATA[MundiPagg - 4 Cartões de Crédito]]></label>
783
+ <sort_order>460</sort_order>
784
+ <show_in_default>1</show_in_default>
785
+ <show_in_website>1</show_in_website>
786
+ <show_in_store>1</show_in_store>
787
+ <comment>
788
+ <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
789
+ <fields>
790
+ <active translate="label">
791
+ <label>Enabled</label>
792
+ <frontend_type>select</frontend_type>
793
+ <source_model>adminhtml/system_config_source_yesno</source_model>
794
+ <sort_order>1</sort_order>
795
+ <show_in_default>1</show_in_default>
796
+ <show_in_website>1</show_in_website>
797
+ <show_in_store>1</show_in_store>
798
+ </active>
799
+
800
+ <title translate="label">
801
+ <label>Title</label>
802
+ <frontend_type>text</frontend_type>
803
+ <sort_order>2</sort_order>
804
+ <show_in_default>1</show_in_default>
805
+ <show_in_website>1</show_in_website>
806
+ <show_in_store>1</show_in_store>
807
+ <comment>
808
+ <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
809
+ </title>
810
+
811
+ <allowspecific translate="label">
812
+ <label>Payment from Applicable Countries</label>
813
+ <frontend_type>allowspecific</frontend_type>
814
+ <sort_order>60</sort_order>
815
+ <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
816
+ <show_in_default>1</show_in_default>
817
+ <show_in_website>1</show_in_website>
818
+ <show_in_store>1</show_in_store>
819
+ </allowspecific>
820
+
821
+ <specificcountry translate="label">
822
+ <label>Payment from Specific Countries</label>
823
+ <frontend_type>multiselect</frontend_type>
824
+ <sort_order>61</sort_order>
825
+ <source_model>adminhtml/system_config_source_country</source_model>
826
+ <show_in_default>1</show_in_default>
827
+ <show_in_website>1</show_in_website>
828
+ <show_in_store>1</show_in_store>
829
+ </specificcountry>
830
+
831
+ <min_order_total translate="label">
832
+ <label>Min Order Total</label>
833
+ <frontend_type>text</frontend_type>
834
+ <sort_order>70</sort_order>
835
+ <show_in_default>1</show_in_default>
836
+ <show_in_website>1</show_in_website>
837
+ <show_in_store>1</show_in_store>
838
+ <frontend_class>validate-number</frontend_class>
839
+ </min_order_total>
840
+
841
+ <max_order_total translate="label">
842
+ <label>Max Order Total</label>
843
+ <frontend_type>text</frontend_type>
844
+ <sort_order>80</sort_order>
845
+ <show_in_default>1</show_in_default>
846
+ <show_in_website>1</show_in_website>
847
+ <show_in_store>1</show_in_store>
848
+ <frontend_class>validate-number</frontend_class>
849
+ </max_order_total>
850
+
851
+ <sort_order translate="label">
852
+ <label>Sort Order</label>
853
+ <frontend_type>text</frontend_type>
854
+ <sort_order>100</sort_order>
855
+ <show_in_default>1</show_in_default>
856
+ <show_in_website>1</show_in_website>
857
+ <show_in_store>1</show_in_store>
858
+ <frontend_class>validate-number</frontend_class>
859
+ </sort_order>
860
+ </fields>
861
+ </mundipagg_fourcreditcards>
862
+ <mundipagg_fivecreditcards type="group" translate="label">
863
+ <label><![CDATA[MundiPagg - 5 Cartões de Crédito]]></label>
864
+ <sort_order>470</sort_order>
865
+ <show_in_default>1</show_in_default>
866
+ <show_in_website>1</show_in_website>
867
+ <show_in_store>1</show_in_store>
868
+ <comment>
869
+ <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
870
+ <fields>
871
+ <active translate="label">
872
+ <label>Enabled</label>
873
+ <frontend_type>select</frontend_type>
874
+ <source_model>adminhtml/system_config_source_yesno</source_model>
875
+ <sort_order>1</sort_order>
876
+ <show_in_default>1</show_in_default>
877
+ <show_in_website>1</show_in_website>
878
+ <show_in_store>1</show_in_store>
879
+ </active>
880
+
881
+ <title translate="label">
882
+ <label>Title</label>
883
+ <frontend_type>text</frontend_type>
884
+ <sort_order>2</sort_order>
885
+ <show_in_default>1</show_in_default>
886
+ <show_in_website>1</show_in_website>
887
+ <show_in_store>1</show_in_store>
888
+ <comment>
889
+ <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
890
+ </title>
891
+
892
+ <allowspecific translate="label">
893
+ <label>Payment from Applicable Countries</label>
894
+ <frontend_type>allowspecific</frontend_type>
895
+ <sort_order>60</sort_order>
896
+ <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
897
+ <show_in_default>1</show_in_default>
898
+ <show_in_website>1</show_in_website>
899
+ <show_in_store>1</show_in_store>
900
+ </allowspecific>
901
+
902
+ <specificcountry translate="label">
903
+ <label>Payment from Specific Countries</label>
904
+ <frontend_type>multiselect</frontend_type>
905
+ <sort_order>61</sort_order>
906
+ <source_model>adminhtml/system_config_source_country</source_model>
907
+ <show_in_default>1</show_in_default>
908
+ <show_in_website>1</show_in_website>
909
+ <show_in_store>1</show_in_store>
910
+ </specificcountry>
911
+
912
+ <min_order_total translate="label">
913
+ <label>Min Order Total</label>
914
+ <frontend_type>text</frontend_type>
915
+ <sort_order>70</sort_order>
916
+ <show_in_default>1</show_in_default>
917
+ <show_in_website>1</show_in_website>
918
+ <show_in_store>1</show_in_store>
919
+ <frontend_class>validate-number</frontend_class>
920
+ </min_order_total>
921
+
922
+ <max_order_total translate="label">
923
+ <label>Max Order Total</label>
924
+ <frontend_type>text</frontend_type>
925
+ <sort_order>80</sort_order>
926
+ <show_in_default>1</show_in_default>
927
+ <show_in_website>1</show_in_website>
928
+ <show_in_store>1</show_in_store>
929
+ <frontend_class>validate-number</frontend_class>
930
+ </max_order_total>
931
+
932
+ <sort_order translate="label">
933
+ <label>Sort Order</label>
934
+ <frontend_type>text</frontend_type>
935
+ <sort_order>100</sort_order>
936
+ <show_in_default>1</show_in_default>
937
+ <show_in_website>1</show_in_website>
938
+ <show_in_store>1</show_in_store>
939
+ <frontend_class>validate-number</frontend_class>
940
+ </sort_order>
941
+ </fields>
942
+ </mundipagg_fivecreditcards>
943
+ <mundipagg_boleto type="group" translate="label">
944
+ <label><![CDATA[MundiPagg - Boleto]]></label>
945
+ <sort_order>480</sort_order>
946
+ <show_in_default>1</show_in_default>
947
+ <show_in_website>1</show_in_website>
948
+ <show_in_store>1</show_in_store>
949
+ <comment>
950
+ <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
951
+ <fields>
952
+ <active translate="label">
953
+ <label>Enabled</label>
954
+ <frontend_type>select</frontend_type>
955
+ <source_model>adminhtml/system_config_source_yesno</source_model>
956
+ <sort_order>1</sort_order>
957
+ <show_in_default>1</show_in_default>
958
+ <show_in_website>1</show_in_website>
959
+ <show_in_store>1</show_in_store>
960
+ </active>
961
+
962
+ <title translate="label">
963
+ <label>Title</label>
964
+ <frontend_type>text</frontend_type>
965
+ <sort_order>2</sort_order>
966
+ <show_in_default>1</show_in_default>
967
+ <show_in_website>1</show_in_website>
968
+ <show_in_store>1</show_in_store>
969
+ <comment>
970
+ <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
971
+ </title>
972
+
973
+ <dias_validade_boleto translate="label">
974
+ <label>Boleto - Dias validade</label>
975
+ <frontend_type>text</frontend_type>
976
+ <validate>validate-digits</validate>
977
+ <sort_order>50</sort_order>
978
+ <show_in_default>1</show_in_default>
979
+ <show_in_website>1</show_in_website>
980
+ <show_in_store>1</show_in_store>
981
+ <comment><![CDATA[Quantos dias o Boleto será válido para pagamento?]]></comment>
982
+ </dias_validade_boleto>
983
+
984
+ <instrucoes_caixa translate="label">
985
+ <label>Boleto - Instrucões Caixa</label>
986
+ <frontend_type>textarea</frontend_type>
987
+ <sort_order>51</sort_order>
988
+ <show_in_default>1</show_in_default>
989
+ <show_in_website>1</show_in_website>
990
+ <show_in_store>1</show_in_store>
991
+ <comment>
992
+ <![CDATA[Texto sobre as instruções caixa customizado por você que irá aparecer nos seus Boletos Bancários]]></comment>
993
+ </instrucoes_caixa>
994
+
995
+ <allowspecific translate="label">
996
+ <label>Payment from Applicable Countries</label>
997
+ <frontend_type>allowspecific</frontend_type>
998
+ <sort_order>60</sort_order>
999
+ <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
1000
+ <show_in_default>1</show_in_default>
1001
+ <show_in_website>1</show_in_website>
1002
+ <show_in_store>1</show_in_store>
1003
+ </allowspecific>
1004
+
1005
+ <specificcountry translate="label">
1006
+ <label>Payment from Specific Countries</label>
1007
+ <frontend_type>multiselect</frontend_type>
1008
+ <sort_order>61</sort_order>
1009
+ <source_model>adminhtml/system_config_source_country</source_model>
1010
+ <show_in_default>1</show_in_default>
1011
+ <show_in_website>1</show_in_website>
1012
+ <show_in_store>1</show_in_store>
1013
+ </specificcountry>
1014
+
1015
+ <sort_order translate="label">
1016
+ <label>Sort Order</label>
1017
+ <frontend_type>text</frontend_type>
1018
+ <sort_order>100</sort_order>
1019
+ <show_in_default>1</show_in_default>
1020
+ <show_in_website>1</show_in_website>
1021
+ <show_in_store>1</show_in_store>
1022
+ <frontend_class>validate-number</frontend_class>
1023
+ </sort_order>
1024
+ </fields>
1025
+ </mundipagg_boleto>
1026
+ <mundipagg_debit type="group" translate="label">
1027
+ <label><![CDATA[MundiPagg - Debit]]></label>
1028
+ <sort_order>480</sort_order>
1029
+ <show_in_default>1</show_in_default>
1030
+ <show_in_website>1</show_in_website>
1031
+ <show_in_store>1</show_in_store>
1032
+ <comment>
1033
+ <![CDATA[<br><a href="http://www.mundipagg.com.br" target="_blank"><img title="MundiPagg" alt="MundiPagg" src="/skin/adminhtml/default/default/images/mundipagg/mundi-magento-admin-banner.png"/></a><br><br><br>]]></comment>
1034
+ <fields>
1035
+ <active translate="label">
1036
+ <label>Enabled</label>
1037
+ <frontend_type>select</frontend_type>
1038
+ <source_model>adminhtml/system_config_source_yesno</source_model>
1039
+ <sort_order>1</sort_order>
1040
+ <show_in_default>1</show_in_default>
1041
+ <show_in_website>1</show_in_website>
1042
+ <show_in_store>1</show_in_store>
1043
+ </active>
1044
+
1045
+ <title translate="label">
1046
+ <label>Title</label>
1047
+ <frontend_type>text</frontend_type>
1048
+ <sort_order>2</sort_order>
1049
+ <show_in_default>1</show_in_default>
1050
+ <show_in_website>1</show_in_website>
1051
+ <show_in_store>1</show_in_store>
1052
+ <comment>
1053
+ <![CDATA[Frase que irá aparecer no seu checkout para descrever a forma de pagamento.]]></comment>
1054
+ </title>
1055
+
1056
+ <debit_types translate="label">
1057
+ <label>Debit</label>
1058
+ <frontend_type>multiselect</frontend_type>
1059
+ <source_model>Uecommerce_Mundipagg_Model_Source_Debit</source_model>
1060
+ <sort_order>3</sort_order>
1061
+ <show_in_default>1</show_in_default>
1062
+ <show_in_website>1</show_in_website>
1063
+ <show_in_store>1</show_in_store>
1064
+ <comment><![CDATA[Escolha os débitos que você aceita na sua loja]]></comment>
1065
+ </debit_types>
1066
+
1067
+ <apiDebitUrl translate="label">
1068
+ <label>Api Debit URL</label>
1069
+ <frontend_type>text</frontend_type>
1070
+ <sort_order>4</sort_order>
1071
+ <show_in_default>1</show_in_default>
1072
+ <show_in_website>1</show_in_website>
1073
+ <show_in_store>1</show_in_store>
1074
+ </apiDebitUrl>
1075
+
1076
+ <apiDebitStagingUrl translate="label">
1077
+ <label>Api Debit Staging URL</label>
1078
+ <frontend_type>text</frontend_type>
1079
+ <sort_order>5</sort_order>
1080
+ <show_in_default>1</show_in_default>
1081
+ <show_in_website>1</show_in_website>
1082
+ <show_in_store>1</show_in_store>
1083
+ </apiDebitStagingUrl>
1084
+
1085
+ <allowspecific translate="label">
1086
+ <label>Payment from Applicable Countries</label>
1087
+ <frontend_type>allowspecific</frontend_type>
1088
+ <sort_order>6</sort_order>
1089
+ <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
1090
+ <show_in_default>1</show_in_default>
1091
+ <show_in_website>1</show_in_website>
1092
+ <show_in_store>1</show_in_store>
1093
+ </allowspecific>
1094
+
1095
+ <specificcountry translate="label">
1096
+ <label>Payment from Specific Countries</label>
1097
+ <frontend_type>multiselect</frontend_type>
1098
+ <sort_order>7</sort_order>
1099
+ <source_model>adminhtml/system_config_source_country</source_model>
1100
+ <show_in_default>1</show_in_default>
1101
+ <show_in_website>1</show_in_website>
1102
+ <show_in_store>1</show_in_store>
1103
+ </specificcountry>
1104
+
1105
+ <sort_order translate="label">
1106
+ <label>Sort Order</label>
1107
+ <frontend_type>text</frontend_type>
1108
+ <sort_order>8</sort_order>
1109
+ <show_in_default>1</show_in_default>
1110
+ <show_in_website>1</show_in_website>
1111
+ <show_in_store>1</show_in_store>
1112
+ <frontend_class>validate-number</frontend_class>
1113
+ </sort_order>
1114
+ </fields>
1115
+ </mundipagg_debit>
1116
+ </groups>
1117
+ </payment>
1118
+ </sections>
1119
  </config>
app/design/adminhtml/default/default/layout/mundipagg.xml CHANGED
@@ -1,53 +1,53 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <!--
3
- /**
4
- * Uecommerce
5
- *
6
- * NOTICE OF LICENSE
7
- *
8
- * This source file is subject to the Uecommerce EULA.
9
- * It is also available through the world-wide-web at this URL:
10
- * http://www.uecommerce.com.br/
11
- *
12
- * DISCLAIMER
13
- *
14
- * Do not edit or add to this file if you wish to upgrade the extension
15
- * to newer versions in the future. If you wish to customize the extension
16
- * for your needs please refer to http://www.uecommerce.com.br/ for more information
17
- *
18
- * @category Uecommerce
19
- * @package Uecommerce_Mundipagg
20
- * @copyright Copyright (c) 2012 Uecommerce (http://www.uecommerce.com.br/)
21
- * @license http://www.uecommerce.com.br/
22
- */
23
-
24
- /**
25
- * Mundipagg Payment module
26
- *
27
- * @category Uecommerce
28
- * @package Uecommerce_Mundipagg
29
- * @author Uecommerce Dev Team
30
- */
31
- -->
32
- <layout version="0.1.0">
33
- <default></default>
34
- <adminhtml_sales_order_create_index>
35
- <reference name="head">
36
- <action method="addJs">
37
- <file>uecommerce/mundipagg.js</file>
38
- </action>
39
- </reference>
40
- </adminhtml_sales_order_create_index>
41
-
42
- <adminhtml_catalog_product_edit>
43
- <reference name="head">
44
- <action method="addJs">
45
- <file>uecommerce/jquery-3.1.0.min.js</file>
46
- </action>
47
- <action method="addJs">
48
- <file>uecommerce/recurrency.js</file>
49
- </action>
50
- </reference>
51
- </adminhtml_catalog_product_edit>
52
-
53
  </layout>
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!--
3
+ /**
4
+ * Uecommerce
5
+ *
6
+ * NOTICE OF LICENSE
7
+ *
8
+ * This source file is subject to the Uecommerce EULA.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://www.uecommerce.com.br/
11
+ *
12
+ * DISCLAIMER
13
+ *
14
+ * Do not edit or add to this file if you wish to upgrade the extension
15
+ * to newer versions in the future. If you wish to customize the extension
16
+ * for your needs please refer to http://www.uecommerce.com.br/ for more information
17
+ *
18
+ * @category Uecommerce
19
+ * @package Uecommerce_Mundipagg
20
+ * @copyright Copyright (c) 2012 Uecommerce (http://www.uecommerce.com.br/)
21
+ * @license http://www.uecommerce.com.br/
22
+ */
23
+
24
+ /**
25
+ * Mundipagg Payment module
26
+ *
27
+ * @category Uecommerce
28
+ * @package Uecommerce_Mundipagg
29
+ * @author Uecommerce Dev Team
30
+ */
31
+ -->
32
+ <layout version="0.1.0">
33
+ <default></default>
34
+ <adminhtml_sales_order_create_index>
35
+ <reference name="head">
36
+ <action method="addJs">
37
+ <file>uecommerce/mundipagg.js</file>
38
+ </action>
39
+ </reference>
40
+ </adminhtml_sales_order_create_index>
41
+
42
+ <adminhtml_catalog_product_edit>
43
+ <reference name="head">
44
+ <action method="addJs">
45
+ <file>uecommerce/jquery-3.1.0.min.js</file>
46
+ </action>
47
+ <action method="addJs">
48
+ <file>uecommerce/recurrency.js</file>
49
+ </action>
50
+ </reference>
51
+ </adminhtml_catalog_product_edit>
52
+
53
  </layout>
app/locale/pt_BR/Uecommerce_Mundipagg.csv CHANGED
@@ -1,215 +1,217 @@
1
- "Enabled","Ativar"
2
- "Title","Título"
3
- "Environment","Ambiente"
4
- "Debug","Debug"
5
- "Api URL Staging","Api URL Staging"
6
- "merchantKey Staging","merchantKey Staging"
7
- "Api URL Production","Api URL Produção"
8
- "merchantKey Production","merchantKey Produção"
9
- "Payment Action","Tipo de operação"
10
- "Payment Methods","Métodos de pagamento"
11
- "Return message AuthOnly","Mensagem de retorno de AuthOnly"
12
- "Return message AuthAndCaptureWithDelay","Mensagem de retorno de AuthAndCaptureWithDelay"
13
- "Credit Card Issuers","Bandeiras"
14
- "Payment from Applicable Countries","Pagamento autorizado para os paises"
15
- "Payment from Specific Countries","Pagamento específico dos paises"
16
- "AuthOnly","AuthOnly"
17
- "AuthAndCapture","AuthAndCapture"
18
- "AuthAndCaptureWithDelay","AuthAndCaptureWithDelay"
19
- "Credit Card","Cartão de Crédito"
20
- "1 Credit Card","Cartão de Crédito"
21
- "2 Credit Cards","2 Cartões de Crédito"
22
- "3 Credit Cards","3 Cartões de Crédito"
23
- "4 Credit Cards","4 Cartões de Crédito"
24
- "5 Credit Cards","5 Cartões de Crédito"
25
- "Pay with 1 Credit Card","Pagar com 1 Cartão de Crédito"
26
- "Pay with 2 Credit Cards","Pagar com 2 Cartões de Crédito"
27
- "Pay with 3 Credit Cards","Pagar com 3 Cartões de Crédito"
28
- "Pay with 4 Credit Cards","Pagar com 4 Cartões de Crédito"
29
- "Pay with 5 Credit Cards","Pagar com 5 Cartões de Crédito"
30
- "Boleto Bancário","Boleto Bancário"
31
- "CreditCard","Cartão de Crédito"
32
- "BoletoBancario","Boleto Bancário"
33
- "Visa","Visa"
34
- "Mastercard","Mastercard"
35
- "American Express","American Express"
36
- "Diners","Diners"
37
- "Select a payment method from backoffice","Selecione uma forma de pagamento no backoffice"
38
- "A vista","A vista"
39
- "Total:","Total:"
40
- "Select a Credit Card or add a new one","Selecione um Cartão de Crédito ou adicione um novo"
41
- "New Credit Card","Novo Cartão de Crédito"
42
- "Credit Card Holder name","Nome completo no Cartão de Crédito"
43
- "Credit Card Number","Número do Cartão de Crédito"
44
- "Expiration date","Data de expiração do Cartão de Crédito"
45
- "Month","Mês"
46
- "January","Janeiro"
47
- "February","Fevereiro"
48
- "March","Março"
49
- "April","Abril"
50
- "May","Maio"
51
- "June","Junho"
52
- "July","Julho"
53
- "August","Agosto"
54
- "September","Setembro"
55
- "October","Outubro"
56
- "November","Novembro"
57
- "December","Dezembro"
58
- "Year","Ano"
59
- "Card Verification Number","Código de segurança"
60
- "What is this?","O que é?"
61
- "Credit options","Parcelar em"
62
- "Total","Total"
63
- "Boleto Bancârio","Boleto Bancário"
64
- "Save Card On File","Usar este Cartão para futuras compras"
65
- "Card already exists on file.","Esse Cartão de Crédito já existe no arquivo."
66
- "CreditCard","Cartão de Crédito"
67
- "1CreditCardsOneInstallment","Cartão de Crédito a vista"
68
- "1CreditCards","Cartão de Crédito"
69
- "2CreditCards","2 Cartões de Crédito"
70
- "3CreditCards","3 Cartões de Crédito"
71
- "4CreditCards","4 Cartões de Crédito"
72
- "5CreditCards","5 Cartões de Crédito"
73
- "mundipagg_creditcardoneinstallment","Cartão de Crédito a vista"
74
- "mundipagg_creditcard","Cartão de Crédito"
75
- "mundipagg_twocreditcards","2 Cartões de Crédito"
76
- "mundipagg_threecreditcards","3 Cartões de Crédito"
77
- "mundipagg_fourcreditcards","4 Cartões de Crédito"
78
- "mundipagg_fivecreditcards","5 Cartões de Crédito"
79
- "mundipagg_boleto","Boleto Bancário"
80
- "mundipagg_debit","Débito"
81
- "Denied","Negado"
82
- "Holder instituition error","Erro instituição titular"
83
- "Parameters sent error","Dados enviados errados"
84
- "Credentials error","Senha errada"
85
- "Internal Error","Erro interno"
86
- "for","para"
87
- "Payment error","A transação não foi aprovada."
88
- "Payment ok","A transação foi aprovada."
89
- "Method","Método"
90
- "Payment Method","Método de pagamento"
91
- "OrderKey","Chave do pedido"
92
- "OrderKeys","Chaves do pedido"
93
- "Credit Card Issuer","Bandeira"
94
- "Transaction Status","Status da transação"
95
- "AuthorizedPendingCapture","AuthorizedPendingCapture"
96
- "NotAuthorized","NotAuthorized"
97
- "ChargebackPreview","ChargebackPreview"
98
- "RefundPreview","RefundPreview"
99
- "DepositPreview","DepositPreview"
100
- "Captured","Capturado"
101
- "PartialCapture","Capturado partialmente"
102
- "Refunded","Reembolsado"
103
- "Voided","Estornado"
104
- "Deposited","Depositado"
105
- "OpenedPendindAuth","Aberto pendente de autorização"
106
- "Chargedback","Charged back"
107
- "WithError","Com erro"
108
- "Invalid","Inválido"
109
- "PendingVoid","Aguardando estorno"
110
- "PartialAuthorize","Autorizado parcialmente"
111
- "PartialRefund","Reembolsado parcialmente"
112
- "Order status is: Opened","Status do pedido: Aberto"
113
- "Order status is: Closed","Status do pedido: Fechado"
114
- "Order status is: Paid","Status do pedido: Pago"
115
- "Order status is: Overpaid","Status do pedido: Pago a mais"
116
- "Order status is: Canceled","Status do pedido: Cancelado"
117
- "Order status is: PartialPaid","Status do pedido: Pago parcialmente"
118
- "No OrderKey found.","Chave do pedido não encontrada."
119
- "Waiting for Boleto Bancário payment","Aguardando pagamento do Boleto Bancário"
120
- "InstallmentCount","Parcela"
121
- "InstallmentsCount","Parcelas"
122
- "Print your boleto after you have placed your order.","Imprima o boleto bancário após a finalização do pedido."
123
- "<a href=""%s"" target=""_blank"">Click here to print</a> a copy of your order confirmation.","<a href=""%s"" target=""_blank"">Clique aqui para imprimir</a> a confirmação do pedido."
124
- "Your order has not been paid yet. <a href=""%s"" target=""_blank"">Click here to print</a> your Boleto Bancário.","<a href=""%s"" target=""_blank"">Clique aqui para imprimir</a> seu Boleto Bancário."
125
- "Print boleto","Imprimir boleto"
126
- "Print boleto nº","Imprimir boleto nº"
127
- "Payment boleto nº","Payment date boleto nº"
128
- "Value (Ex: 100,50)","Valor a passar neste Cartão (Ex: 100,50)"
129
- "Installments does not match with quote.","Soma dos valores por Cartão não coincidem."
130
- "Order partially authorized","Pedido parcialmente autorizado"
131
- "Order total:","Valor total do pedido:"
132
- "Amount authorized:","Total autorizado:"
133
- "Rest to pay:","Falta a autorizar:"
134
- "on Credit Card nº","no Cartão de Crédito nº"
135
- "authorized","autorizado"
136
- "not authorized","não autorizado"
137
- "Choose a payment method above to complete your order","Escolha um método de pagamento abaixo para concluir seu pedido"
138
- "Order cancelled","Pedido cancelado"
139
- "You cannot capture having ClearSale activated.","Você tem ClearSale ativado, seu pedido será analisado pelo mesmo."
140
- "You cannot capture Boleto Bancário.","Você não pode capturar um Boleto Bancário, o pagamento será notificado pela sua URL de retorno."
141
- "Try again!","Tente novamente por favor."
142
- "Address_2","Número"
143
- "Address_3","Bairro"
144
- "CPF or CNPJ is invalid","O CPF ou CNPJ informado é inválido"
145
- "Grand Total","Valor Total"
146
- "click to update","clique para atualizar"
147
- "Product Name","Produto"
148
- "Price","Valor"
149
- "Qty","Qtd"
150
- "Order #%s - %s","Pedido #%s - %s"
151
- "Order Date: %s","Data do pedido: %s"
152
- "Billing Address","Endereço de Cobrança"
153
- "Shipping Address","Endereço de Envio"
154
- "Shipping Method","Método de Envio"
155
- "Shipping & Handling","Envio"
156
- "Discount","Desconto"
157
- "Continue Shopping","Continuar comprando"
158
- "Unable to capture order.","Impossível capturar o pedido."
159
- "Unable to void order.","Impossível cancelar o pedido."
160
- "Unable to refund order.","Impossível estornar o pedido."
161
- "Interest","Juros Cartões"
162
- "Installments default","Parcelamentos Padrões"
163
- "Add Installment Boundary","Adicionar Parcela"
164
- "Amount (incl.)","Total 'Até' - (menor ou igual)"
165
- "Maximum Number of Installments","Número da Parcela"
166
- "Interest Rate (%)","Taxa de Juros (%)"
167
- "Installments and Interest","Parcelamentos e Juros"
168
- "Installments for Visa","Parcelamentos para Visa"
169
- "Installments for Mastercard","Parcelamentos para Mastercard"
170
- "Installments for Amex","Parcelamentos para Amex"
171
- "Installments for Diners","Parcelamentos para Diners"
172
- "Installments for Elo","Parcelamentos para Elo"
173
- "Installments for Hipercard","Parcelamentos para Hipercard"
174
- "The flag is automatically selected after entering the credit card number below.","A bandeira será selecionada automaticamente após digitar o Número do Cartão de Crédito abaixo."
175
- "The taxvat is invalid","O CPF ou CNPJ informado é inválido"
176
- "Check the values to pass on each card","Confira os valores a passar em cada cartão"
177
- "Expiration date of the incorrect card","Data de expiração do Cartão incorreta"
178
- "Total amount with interest: USD{%%%}","<b>Valor total c/ juros: </b>R${%%%}"
179
- "with interest","c/ juros"
180
- "without interest","s/ juros"
181
- "Daily","Diário"
182
- "Weekly","Semanal"
183
- "Monthly","Mensal"
184
- "Yearly","Anual"
185
- "Quarterly","Trimestral"
186
- "Biannual","Semestral"
187
- "it is not possible to divide by %s times","Não é possível dividir em %s vezes"
188
- "Probably you had not installed the old version.","Provavelmente você não tinha instalado a versão antiga."
189
- "The old settings have been successfully restored! Please check and make tests in your store.","As configurações antigas foram restauradas com sucesso! Por favor, verifique e fazer testes em sua loja."
190
- "Set old settings","Resetar configurações antigas"
191
- "If you just update the module and its old version is below 2.0.0, you can click this button to generate the installments as were set in the old version of the module.","Se você acabou de atualizar o módulo e sua versão antiga está abaixo 2.0.0, você pode clicar neste botão para gerar as parcelas como foram definidas na versão antiga do módulo."
192
- "If you have already set manually, CAUTION! This function will reset all installments.","Se você já tiver configurado manualmente, CUIDADO! Esta função irá repor todas as parcelas."
193
- "Environment FControl","Ambiente FControl"
194
- "FControl sandbox key","Chave FControl sandbox"
195
- "FControl production key","Chave FControl produção"
196
- "Production","Produção"
197
- "Max time to retry in minutes","Tempo máximo para retentativa em minutos"
198
- "Max time to wait for an authorization. After this, the order will be cancelled.","Tempo máximo para esperar por uma autorização. Após este prazo, pedido será cancelado."
199
- "Fingerprint environment","Ambiente fingerprint"
200
- "Unable to save product configuration","Não foi possível salvar a configuração do produto"
201
- "Internal error","Erro interno"
202
- "With Error","Com erro"
203
- "Anti fraud","Antifraude"
204
- "Yes","Sim"
205
- "No","Não"
206
- "Module Basic Configuration","Configuração Básica do Módulo"
207
- "Credit Card Basic Configuration","Configuração Básica - Cartão de Crédito"
208
- "Installment","Parcelamento"
209
- "Enable customer to save his cards for future purchases.Creditcard numbers are saved in Mundipagg, the store only save a token to the customer card.","Possibilita o cliente salvar seus cartões para compras futuras. Os números de cartão são salvos na Mundipagg, a loja armazena apenas um token do cartão."
210
- "Version","Versão"
211
- "Anti Fraud Provider","Fornecedor Anti-fraude"
212
- "Order Minimum Value","Valor Mínimo do Pedido"
213
- "Order minimum value for antifraud %s can't be negative","Valor mínimo do pedido para o antifraude %s não pode ser negativo"
214
- "Valid formats: 0.00 - 0,00","Formatos válidos: 0,00 - 0.00"
215
- "Order minimum value '%s' for antifraud %s isn't in the valid format","Valor mínimo do carrinho '%s' informado para o antifraude %s não está no formato válido"
 
 
1
+ "Enabled","Ativar"
2
+ "Title","Título"
3
+ "Environment","Ambiente"
4
+ "Debug","Debug"
5
+ "Api URL Staging","Api URL Staging"
6
+ "merchantKey Staging","merchantKey Staging"
7
+ "Api URL Production","Api URL Produção"
8
+ "merchantKey Production","merchantKey Produção"
9
+ "Payment Action","Tipo de operação"
10
+ "Payment Methods","Métodos de pagamento"
11
+ "Return message AuthOnly","Mensagem de retorno de AuthOnly"
12
+ "Return message AuthAndCaptureWithDelay","Mensagem de retorno de AuthAndCaptureWithDelay"
13
+ "Credit Card Issuers","Bandeiras"
14
+ "Payment from Applicable Countries","Pagamento autorizado para os paises"
15
+ "Payment from Specific Countries","Pagamento específico dos paises"
16
+ "AuthOnly","AuthOnly"
17
+ "AuthAndCapture","AuthAndCapture"
18
+ "AuthAndCaptureWithDelay","AuthAndCaptureWithDelay"
19
+ "Credit Card","Cartão de Crédito"
20
+ "1 Credit Card","Cartão de Crédito"
21
+ "2 Credit Cards","2 Cartões de Crédito"
22
+ "3 Credit Cards","3 Cartões de Crédito"
23
+ "4 Credit Cards","4 Cartões de Crédito"
24
+ "5 Credit Cards","5 Cartões de Crédito"
25
+ "Pay with 1 Credit Card","Pagar com 1 Cartão de Crédito"
26
+ "Pay with 2 Credit Cards","Pagar com 2 Cartões de Crédito"
27
+ "Pay with 3 Credit Cards","Pagar com 3 Cartões de Crédito"
28
+ "Pay with 4 Credit Cards","Pagar com 4 Cartões de Crédito"
29
+ "Pay with 5 Credit Cards","Pagar com 5 Cartões de Crédito"
30
+ "Boleto Bancário","Boleto Bancário"
31
+ "CreditCard","Cartão de Crédito"
32
+ "BoletoBancario","Boleto Bancário"
33
+ "Visa","Visa"
34
+ "Mastercard","Mastercard"
35
+ "American Express","American Express"
36
+ "Diners","Diners"
37
+ "Select a payment method from backoffice","Selecione uma forma de pagamento no backoffice"
38
+ "A vista","A vista"
39
+ "Total:","Total:"
40
+ "Select a Credit Card or add a new one","Selecione um Cartão de Crédito ou adicione um novo"
41
+ "New Credit Card","Novo Cartão de Crédito"
42
+ "Credit Card Holder name","Nome completo no Cartão de Crédito"
43
+ "Credit Card Number","Número do Cartão de Crédito"
44
+ "Expiration date","Data de expiração do Cartão de Crédito"
45
+ "Month","Mês"
46
+ "January","Janeiro"
47
+ "February","Fevereiro"
48
+ "March","Março"
49
+ "April","Abril"
50
+ "May","Maio"
51
+ "June","Junho"
52
+ "July","Julho"
53
+ "August","Agosto"
54
+ "September","Setembro"
55
+ "October","Outubro"
56
+ "November","Novembro"
57
+ "December","Dezembro"
58
+ "Year","Ano"
59
+ "Card Verification Number","Código de segurança"
60
+ "What is this?","O que é?"
61
+ "Credit options","Parcelar em"
62
+ "Total","Total"
63
+ "Boleto Bancârio","Boleto Bancário"
64
+ "Save Card On File","Usar este Cartão para futuras compras"
65
+ "Card already exists on file.","Esse Cartão de Crédito já existe no arquivo."
66
+ "CreditCard","Cartão de Crédito"
67
+ "1CreditCardsOneInstallment","Cartão de Crédito a vista"
68
+ "1CreditCards","Cartão de Crédito"
69
+ "2CreditCards","2 Cartões de Crédito"
70
+ "3CreditCards","3 Cartões de Crédito"
71
+ "4CreditCards","4 Cartões de Crédito"
72
+ "5CreditCards","5 Cartões de Crédito"
73
+ "mundipagg_creditcardoneinstallment","Cartão de Crédito a vista"
74
+ "mundipagg_creditcard","Cartão de Crédito"
75
+ "mundipagg_twocreditcards","2 Cartões de Crédito"
76
+ "mundipagg_threecreditcards","3 Cartões de Crédito"
77
+ "mundipagg_fourcreditcards","4 Cartões de Crédito"
78
+ "mundipagg_fivecreditcards","5 Cartões de Crédito"
79
+ "mundipagg_boleto","Boleto Bancário"
80
+ "mundipagg_debit","Débito"
81
+ "Denied","Negado"
82
+ "Holder instituition error","Erro instituição titular"
83
+ "Parameters sent error","Dados enviados errados"
84
+ "Credentials error","Senha errada"
85
+ "Internal Error","Erro interno"
86
+ "for","para"
87
+ "Payment error","A transação não foi aprovada."
88
+ "Payment ok","A transação foi aprovada."
89
+ "Method","Método"
90
+ "Payment Method","Método de pagamento"
91
+ "OrderKey","Chave do pedido"
92
+ "OrderKeys","Chaves do pedido"
93
+ "Credit Card Issuer","Bandeira"
94
+ "Transaction Status","Status da transação"
95
+ "AuthorizedPendingCapture","AuthorizedPendingCapture"
96
+ "NotAuthorized","NotAuthorized"
97
+ "ChargebackPreview","ChargebackPreview"
98
+ "RefundPreview","RefundPreview"
99
+ "DepositPreview","DepositPreview"
100
+ "Captured","Capturado"
101
+ "PartialCapture","Capturado partialmente"
102
+ "Refunded","Reembolsado"
103
+ "Voided","Estornado"
104
+ "Deposited","Depositado"
105
+ "OpenedPendindAuth","Aberto pendente de autorização"
106
+ "Chargedback","Charged back"
107
+ "WithError","Com erro"
108
+ "Invalid","Inválido"
109
+ "PendingVoid","Aguardando estorno"
110
+ "PartialAuthorize","Autorizado parcialmente"
111
+ "PartialRefund","Reembolsado parcialmente"
112
+ "Order status is: Opened","Status do pedido: Aberto"
113
+ "Order status is: Closed","Status do pedido: Fechado"
114
+ "Order status is: Paid","Status do pedido: Pago"
115
+ "Order status is: Overpaid","Status do pedido: Pago a mais"
116
+ "Order status is: Canceled","Status do pedido: Cancelado"
117
+ "Order status is: PartialPaid","Status do pedido: Pago parcialmente"
118
+ "No OrderKey found.","Chave do pedido não encontrada."
119
+ "Waiting for Boleto Bancário payment","Aguardando pagamento do Boleto Bancário"
120
+ "InstallmentCount","Parcela"
121
+ "InstallmentsCount","Parcelas"
122
+ "Print your boleto after you have placed your order.","Imprima o boleto bancário após a finalização do pedido."
123
+ "<a href=""%s"" target=""_blank"">Click here to print</a> a copy of your order confirmation.","<a href=""%s"" target=""_blank"">Clique aqui para imprimir</a> a confirmação do pedido."
124
+ "Your order has not been paid yet. <a href=""%s"" target=""_blank"">Click here to print</a> your Boleto Bancário.","<a href=""%s"" target=""_blank"">Clique aqui para imprimir</a> seu Boleto Bancário."
125
+ "Print boleto","Imprimir boleto"
126
+ "Print boleto nº","Imprimir boleto nº"
127
+ "Payment boleto nº","Payment date boleto nº"
128
+ "Value (Ex: 100,50)","Valor a passar neste Cartão (Ex: 100,50)"
129
+ "Installments does not match with quote.","Soma dos valores por Cartão não coincidem."
130
+ "Order partially authorized","Pedido parcialmente autorizado"
131
+ "Order total:","Valor total do pedido:"
132
+ "Amount authorized:","Total autorizado:"
133
+ "Rest to pay:","Falta a autorizar:"
134
+ "on Credit Card nº","no Cartão de Crédito nº"
135
+ "authorized","autorizado"
136
+ "not authorized","não autorizado"
137
+ "Choose a payment method above to complete your order","Escolha um método de pagamento abaixo para concluir seu pedido"
138
+ "Order cancelled","Pedido cancelado"
139
+ "You cannot capture having ClearSale activated.","Você tem ClearSale ativado, seu pedido será analisado pelo mesmo."
140
+ "You cannot capture Boleto Bancário.","Você não pode capturar um Boleto Bancário, o pagamento será notificado pela sua URL de retorno."
141
+ "Try again!","Tente novamente por favor."
142
+ "Address_2","Número"
143
+ "Address_3","Bairro"
144
+ "CPF or CNPJ is invalid","O CPF ou CNPJ informado é inválido"
145
+ "Grand Total","Valor Total"
146
+ "click to update","clique para atualizar"
147
+ "Product Name","Produto"
148
+ "Price","Valor"
149
+ "Qty","Qtd"
150
+ "Order #%s - %s","Pedido #%s - %s"
151
+ "Order Date: %s","Data do pedido: %s"
152
+ "Billing Address","Endereço de Cobrança"
153
+ "Shipping Address","Endereço de Envio"
154
+ "Shipping Method","Método de Envio"
155
+ "Shipping & Handling","Envio"
156
+ "Discount","Desconto"
157
+ "Continue Shopping","Continuar comprando"
158
+ "Unable to capture order.","Impossível capturar o pedido."
159
+ "Unable to void order.","Impossível cancelar o pedido."
160
+ "Unable to refund order.","Impossível estornar o pedido."
161
+ "Interest","Juros Cartões"
162
+ "Installments default","Parcelamentos Padrões"
163
+ "Add Installment Boundary","Adicionar Parcela"
164
+ "Amount (incl.)","Total 'Até' - (menor ou igual)"
165
+ "Maximum Number of Installments","Número da Parcela"
166
+ "Interest Rate (%)","Taxa de Juros (%)"
167
+ "Installments and Interest","Parcelamentos e Juros"
168
+ "Installments for Visa","Parcelamentos para Visa"
169
+ "Installments for Mastercard","Parcelamentos para Mastercard"
170
+ "Installments for Amex","Parcelamentos para Amex"
171
+ "Installments for Diners","Parcelamentos para Diners"
172
+ "Installments for Elo","Parcelamentos para Elo"
173
+ "Installments for Hipercard","Parcelamentos para Hipercard"
174
+ "The flag is automatically selected after entering the credit card number below.","A bandeira será selecionada automaticamente após digitar o Número do Cartão de Crédito abaixo."
175
+ "The taxvat is invalid","O CPF ou CNPJ informado é inválido"
176
+ "Check the values to pass on each card","Confira os valores a passar em cada cartão"
177
+ "Expiration date of the incorrect card","Data de expiração do Cartão incorreta"
178
+ "Total amount with interest: USD{%%%}","<b>Valor total c/ juros: </b>R${%%%}"
179
+ "with interest","c/ juros"
180
+ "without interest","s/ juros"
181
+ "Daily","Diário"
182
+ "Weekly","Semanal"
183
+ "Monthly","Mensal"
184
+ "Yearly","Anual"
185
+ "Quarterly","Trimestral"
186
+ "Biannual","Semestral"
187
+ "it is not possible to divide by %s times","Não é possível dividir em %s vezes"
188
+ "Probably you had not installed the old version.","Provavelmente você não tinha instalado a versão antiga."
189
+ "The old settings have been successfully restored! Please check and make tests in your store.","As configurações antigas foram restauradas com sucesso! Por favor, verifique e fazer testes em sua loja."
190
+ "Set old settings","Resetar configurações antigas"
191
+ "If you just update the module and its old version is below 2.0.0, you can click this button to generate the installments as were set in the old version of the module.","Se você acabou de atualizar o módulo e sua versão antiga está abaixo 2.0.0, você pode clicar neste botão para gerar as parcelas como foram definidas na versão antiga do módulo."
192
+ "If you have already set manually, CAUTION! This function will reset all installments.","Se você já tiver configurado manualmente, CUIDADO! Esta função irá repor todas as parcelas."
193
+ "Environment FControl","Ambiente FControl"
194
+ "FControl sandbox key","Chave FControl sandbox"
195
+ "FControl production key","Chave FControl produção"
196
+ "Production","Produção"
197
+ "Max time to retry in minutes","Tempo máximo para retentativa em minutos"
198
+ "Max time to wait for an authorization. After this, the order will be cancelled.","Tempo máximo para esperar por uma autorização. Após este prazo, pedido será cancelado."
199
+ "Fingerprint environment","Ambiente fingerprint"
200
+ "Unable to save product configuration","Não foi possível salvar a configuração do produto"
201
+ "Internal error","Erro interno"
202
+ "With Error","Com erro"
203
+ "Anti fraud","Antifraude"
204
+ "Yes","Sim"
205
+ "No","Não"
206
+ "Module Basic Configuration","Configuração Básica do Módulo"
207
+ "Credit Card Basic Configuration","Configuração Básica - Cartão de Crédito"
208
+ "Installment","Parcelamento"
209
+ "Enable customer to save his cards for future purchases.Creditcard numbers are saved in Mundipagg, the store only save a token to the customer card.","Possibilita o cliente salvar seus cartões para compras futuras. Os números de cartão são salvos na Mundipagg, a loja armazena apenas um token do cartão."
210
+ "Version","Versão"
211
+ "Anti Fraud Provider","Fornecedor Anti-fraude"
212
+ "Order Minimum Value","Valor Mínimo do Pedido"
213
+ "Order minimum value for antifraud %s can't be negative","Valor mínimo do pedido para o antifraude %s não pode ser negativo"
214
+ "Valid formats: 0.00 - 0,00","Formatos válidos: 0,00 - 0.00"
215
+ "Order minimum value '%s' for antifraud %s isn't in the valid format","Valor mínimo do carrinho '%s' informado para o antifraude %s não está no formato válido"
216
+ "Offline Retry","Retentativa Offline"
217
+ "Offline retry can't be used with more than 1 creditcard payment method yet. This feature will be available comming soon.","A retentativa offline ainda não pode ser utilizada em conjunto com métodos de pagamento de mais de 1 cartão. Funcionalidade será disponibilizada em versões futuras do módulo Mundipagg."
js/uecommerce/mundipagg.js CHANGED
@@ -1,872 +1,876 @@
1
- function validaCPF(cpf,pType) {
2
- if (Validation.get('IsEmpty').test(cpf)) {
3
- return false;
4
- }
5
-
6
- var valid = true;
7
- var cpf = cpf.replace(/[.\//-]/g,'');
8
-
9
- if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
10
- valid = false;
11
- add = 0;
12
- for (i=0; i < 9; i ++)
13
- add += parseInt(cpf.charAt(i)) * (10 - i);
14
- rev = 11 - (add % 11);
15
- if (rev == 10 || rev == 11)
16
- rev = 0;
17
- if (rev != parseInt(cpf.charAt(9)))
18
- valid = false;
19
- add = 0;
20
- for (i = 0; i < 10; i ++)
21
- add += parseInt(cpf.charAt(i)) * (11 - i);
22
- rev = 11 - (add % 11);
23
- if (rev == 10 || rev == 11)
24
- rev = 0;
25
- if (rev != parseInt(cpf.charAt(10)))
26
- valid = false;
27
-
28
- if(valid) {
29
- return true;
30
- }
31
-
32
- if (cpf.length >= 14) {
33
- if ( cpf.substring(12,14) == checkCNPJ( cpf.substring(0,12) ) ) {
34
- return true;
35
- }
36
- }
37
-
38
- return false;
39
- }
40
-
41
- function checkCNPJ(vCNPJ) {
42
- var mControle = "";
43
- var aTabCNPJ = new Array(5,4,3,2,9,8,7,6,5,4,3,2);
44
- for (i = 1 ; i <= 2 ; i++) {
45
- mSoma = 0;
46
- for (j = 0 ; j < vCNPJ.length ; j++)
47
- mSoma = mSoma + (vCNPJ.substring(j,j+1) * aTabCNPJ[j]);
48
- if (i == 2 ) mSoma = mSoma + ( 2 * mDigito );
49
- mDigito = ( mSoma * 10 ) % 11;
50
- if (mDigito == 10 ) mDigito = 0;
51
- mControle1 = mControle ;
52
- mControle = mDigito;
53
- aTabCNPJ = new Array(6,5,4,3,2,9,8,7,6,5,4,3);
54
- }
55
-
56
- return( (mControle1 * 10) + mControle );
57
- }
58
-
59
- Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
60
- var n = this,
61
- decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
62
- decSeparator = decSeparator == undefined ? "." : decSeparator,
63
- thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
64
- sign = n < 0 ? "-" : "",
65
- i = parseFloat(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
66
- j = (j = i.length) > 3 ? j % 3 : 0;
67
- return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
68
- };
69
-
70
- function remove_characters(event) {
71
- /* Allow: backspace, delete, tab, escape, and enter */
72
- if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
73
- /* Allow: Ctrl+A */
74
- (event.keyCode == 65 && event.ctrlKey === true) ||
75
- /* Allow: home, end, left, right */
76
- (event.keyCode >= 35 && event.keyCode <= 39)) {
77
- /* let it happen, don't do anything */
78
- return;
79
- } else {
80
- /* Ensure that it is a number and stop the keypress */
81
- if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
82
- event.preventDefault();
83
- }
84
- }
85
- }
86
-
87
- function selectCredcard(ele){
88
- var check = checkCredcardType(ele.value);
89
-
90
- ele.up(2).previous().select('.cc_brand_types').each(function(el) {
91
- el.removeClassName('active');
92
- });
93
-
94
- var id = ele.id;
95
-
96
- var realId = id
97
- .replace('mundipagg_creditcard','')
98
- .replace('mundipagg_twocreditcards_','')
99
- .replace('mundipagg_threecreditcards_','')
100
- .replace('mundipagg_fourcreditcards_','')
101
- .replace('mundipagg_fivecreditcards_','')
102
- .replace('_cc_number','');
103
-
104
- var cardType = id.replace('mundipagg_','').replace('_cc_number','').replace('_'+realId,'');
105
-
106
- if(check){
107
- var parentElement = ele.up(2).previous().select('li');
108
-
109
- parentElement.each(function(element){
110
- var inpt = element.select('input')[0];
111
-
112
- if( inpt.value == check){
113
- inpt.click();
114
- inpt.previous().addClassName('active');
115
-
116
- if(window.isInstallmentsEnabled) {
117
- if (window[realId] != check) {
118
- window[realId] = check;
119
- window['brand_' + realId] = check;
120
-
121
- selects = ele.up(3).select('select');
122
- selects.each(function (select) {
123
- if (select.name.indexOf('parcelamento') != -1) {
124
- installmentElement = select;
125
- }
126
- });
127
-
128
- if (window['installmentElement'] != undefined) {
129
- window['select_html_' + realId] = installmentElement.innerHTML;
130
- window['select_' + realId] = installmentElement;
131
-
132
- if ($('mundipagg_' + cardType + '_new_value_' + realId) != undefined) {
133
- if ($('mundipagg_' + cardType + '_new_value_' + realId).value == '') {
134
- updateInstallments(check, installmentElement);
135
- } else {
136
- updateInstallments(check, installmentElement, $('mundipagg_' + cardType + '_new_value_' + realId).value);
137
- }
138
- } else {
139
- updateInstallments(check, installmentElement);
140
- }
141
- }
142
- }
143
- }
144
- }
145
- });
146
- }else{
147
- if (window[realId] != undefined) {
148
- window[realId] = undefined;
149
- if ($('mundipagg_'+cardType+'_new_value_' + realId) != undefined) {
150
- totalValue = $('mundipagg_'+cardType+'_new_value_' + realId).value;
151
- } else {
152
- totalValue = '';
153
- }
154
- if (window['select_' + realId] != undefined && totalValue == '') {
155
- window['select_' + realId].innerHTML = window['select_html_' + realId];
156
- } else {
157
- if (window.installmentElement !== undefined) {
158
- updateInstallments(0, installmentElement, $('mundipagg_'+cardType+'_new_value_' + realId).value);
159
- }
160
- }
161
- }
162
- }
163
- }
164
-
165
- /**
166
- * Javascript method based on helper Mundipagg: https://github.com/mundipagg/mundipagg-one-php/blob/master/lib/One/Helper/CreditCardHelper.php
167
- *
168
- * @param string cardNumber Número do cartão
169
- * @return string Bandeira do cartão
170
- */
171
- function checkCredcardType(cardNumber){
172
- var flag = false;
173
- /* Extrai somente números do cartão (Note: Not only draw numbers, letters as well).*/
174
- cardNumber = cardNumber.toString().replace(/[^0-9a-zA-Z ]/g,'');
175
-
176
- if(inArray(cardNumber.substring(0,6),['401178','401179', '504175', '509002', '509003', '438935', '457631',
177
- '451416', '457632', '431274', '438935', '451416', '457393', '457631', '457632', '504175', '506726',
178
- '506727', '506739', '506741', '506742', '506744', '506747', '506748', '506778', '627780', '636297',
179
- '636368', '636369', '636297', '637095']) ||
180
- isBetween(cardNumber.substring(0,6), '650031', '650033') ||
181
- isBetween(cardNumber.substring(0,6), '650035', '650051') ||
182
- isBetween(cardNumber.substring(0,6), '650405', '650439') ||
183
- isBetween(cardNumber.substring(0,6), '650485', '650538') ||
184
- isBetween(cardNumber.substring(0,6), '650541', '650598') ||
185
- isBetween(cardNumber.substring(0,6), '650700', '650718') ||
186
- isBetween(cardNumber.substring(0,6), '650720', '650727') ||
187
- isBetween(cardNumber.substring(0,6), '650901', '650920') ||
188
- isBetween(cardNumber.substring(0,6), '506699', '506778') ||
189
- isBetween(cardNumber.substring(0,6), '651652', '651679') ||
190
- isBetween(cardNumber.substring(0,6), '509000', '509999') ||
191
- isBetween(cardNumber.substring(0,6), '655000', '655019') ||
192
- isBetween(cardNumber.substring(0,6), '655021', '655058')
193
- ){
194
- flag = 'EL';
195
- }
196
- else if(cardNumber.substring(0,4) == '6011' || cardNumber.substring(0,3) == '622' || inArray(cardNumber.substring(0,2), ['64', '65'])){
197
- /* Flag not implemented in the module yet.*/
198
- flag = 'discover';
199
- }
200
- else if(inArray(cardNumber.substring(0,3), ['301', '305']) || inArray(cardNumber.substring(0,2),['36', '38'])){
201
- flag = 'DI';
202
- }
203
- else if(inArray(cardNumber.substring(0,2), ['34', '37'])){
204
- flag = 'AE';
205
- }
206
- else if(cardNumber.substring(0,2) == '50'){
207
- /* Flag not implemented in the module yet.*/
208
- flag = 'aura';
209
- }
210
- else if(inArray(cardNumber.substring(0,2),['38', '60'])){
211
- flag = 'HI';
212
- }
213
- else if(cardNumber[0] == '4'){
214
- flag = 'VI';
215
- }
216
- else if(cardNumber[0] == '5'){
217
- flag = 'MC';
218
- }
219
-
220
- return flag;
221
- }
222
-
223
- /**
224
- * Javascript method inArray equivalent PHP
225
- */
226
- function inArray(neddle, arraySearch){
227
- return arraySearch.filter(function(item){return item == neddle;}).length;
228
- }
229
-
230
- function isBetween(neddle, first, last)
231
- {
232
- return (neddle >= first && neddle <= last);
233
- }
234
-
235
- function updateInstallments(ccType, element ,total) {
236
- if(window['admin_area_url'] == undefined) {
237
- var url = window.installmentsandinterestUrl;
238
- } else {
239
- var url = window['admin_area_url_installments_and_interest'];
240
- }
241
-
242
- /* Force select */
243
- document.getElementById(element.id).selectedIndex = element.value - 1;
244
-
245
- /* Get actual parcel */
246
- var parcel = element.value;
247
-
248
- if(!total) {
249
- total = $('baseGrandTotal').value;
250
- }
251
-
252
- if(window.ajax_loader_mundipagg_img != undefined) {
253
- mundipagg_img = window.ajax_loader_mundipagg_img;
254
- } else {
255
- mundipagg_img = window.ajaxLoaderGif;
256
- }
257
-
258
- loading = new Element('img', {src:mundipagg_img});
259
- loading.addClassName('mundipagg_reload');
260
-
261
- element.insert({
262
- 'after':loading
263
- });
264
-
265
- element.options.length = 0;
266
-
267
- var id = element.id.replace('_new_credito_parcelamento','')+'_cc_number';
268
-
269
- new Ajax.Request(url,{
270
- method:'post',
271
- parameters:{cctype:ccType,total:total},
272
- onSuccess:function(response) {
273
- var res = JSON.parse(response.responseText);
274
-
275
- if(res['installments'] != undefined) {
276
- i=0;
277
-
278
- if(res.installments.length == 1) {
279
- element.options[0] = new Option(res.installments[0],0,false,false);
280
- } else {
281
- for(key in res.installments) {
282
- if(/^-?[\d.]+(?:e-?\d+)?$/.test(key)) {
283
- /* Set option as selected */
284
- if(key == parcel) {
285
- var selected = true;
286
- } else {
287
- var selected = false;
288
- }
289
-
290
- element.options[i] = new Option(res.installments[key],key,selected,false);
291
-
292
- /* Select option */
293
- if(key == parcel) {
294
- document.getElementById(element.id).selectedIndex = key - 1;
295
- }
296
-
297
- i++;
298
- }
299
- }
300
- }
301
-
302
- if(res['brand'] != undefined) {
303
- window['brand_' + id.replace('mundipagg_twocreditcards_', '').replace('_cc_number', '')] = res.brand;
304
- }
305
- } else {
306
- window['select_'+id].innerHTML = window['select_html_'+id];
307
- window['brand_'+id.replace('mundipagg_twocreditcards_','').replace('_cc_number','')] = undefined;
308
- }
309
-
310
- $$('.mundipagg_reload')[0].remove();
311
-
312
- if($('order-billing_method') != undefined) {
313
- var data = {};
314
- this.loadArea(['totals'], true, data);
315
- }
316
- }
317
- });
318
- }
319
-
320
- function remove_special_characters(event) {
321
- /* Allow: backspace, delete, tab, escape, comma, enter and decimal point */
322
- if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 188 || event.keyCode == 13 || event.keyCode == 110 ||
323
- /* Allow: Ctrl+A */
324
- (event.keyCode == 65 && event.ctrlKey === true) ||
325
- /* Allow: home, end, left, right */
326
- (event.keyCode >= 35 && event.keyCode <= 39)) {
327
- /* let it happen, don't do anything */
328
- return;
329
- } else {
330
- /* Ensure that it is a number and stop the keypress */
331
- if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
332
- event.preventDefault();
333
- }
334
- }
335
- }
336
-
337
- if(Validation) {
338
- Validation.add('validar_cpf', 'The taxvat is invalid', function(v){return validaCPF(v,0);});
339
-
340
- /**
341
- * Hash with credit card types which can be simply extended in payment modules
342
- * 0 - regexp for card number
343
- * 1 - regexp for cvn
344
- * 2 - check or not credit card number trough Luhn algorithm by
345
- * function validateCreditCard which you can find above in this file
346
- */
347
- Validation.creditCartTypes = $H({
348
- 'VI': [new RegExp('^4[0-9]{12}([0-9]{3})?$'), new RegExp('^[0-9]{3}$'), true],
349
- 'MC': [new RegExp('^5[1-5][0-9]{14}$'), new RegExp('^[0-9]{3}$'), true],
350
- 'AE': [new RegExp('^3[47][0-9]{13}$'), new RegExp('^[0-9]{4}$'), true],
351
- 'DI': [false, new RegExp('^[0-9]{3}$'), true],
352
- 'OT': [false, new RegExp('^([0-9]{3}|[0-9]{4})?$'), false],
353
- 'EL': [false, new RegExp('^([0-9]{3})?$'), true],
354
- 'HI': [false, new RegExp('^([0-9]{3})?$'), false]
355
- });
356
-
357
- Validation.add('check_values', 'Check the values to pass on each card', function(){return check_values();});
358
-
359
- Validation.add('validate-cc-exp-cus', 'Expiration date of the incorrect card', function(v,elm){return verify_cc_expiration_date(v,elm);});
360
- }
361
-
362
- function verify_cc_expiration_date(v,elm) {
363
- var ccExpMonth = v;
364
- var ccExpYear = $(elm.id.substr(0,elm.id.indexOf('_expirationMonth')) + '_expirationYear').value;
365
- var currentTime = new Date();
366
- var currentMonth = currentTime.getMonth() + 1;
367
- var currentYear = currentTime.getFullYear();
368
- if (ccExpMonth < currentMonth && ccExpYear == currentYear) {
369
- return false;
370
- }
371
- return true;
372
- }
373
-
374
- function token_or_not(num,c,field) {
375
- var type = $$('input[name="payment\\[method\\]"]:checked').first().value;
376
-
377
- if( document.getElementById(type+'_token_'+num+'_'+c).value == 'new' ) {
378
- /* Remove disable fields */
379
- $(type+'_'+num+'_'+c+'_cc_type').enable();
380
- $(type+'_'+num+'_'+c+'_cc_number').enable();
381
- $(type+'_cc_holder_name_'+num+'_'+c).enable();
382
- $(type+'_expirationMonth_'+num+'_'+c).enable();
383
- $(type+'_expirationYear_'+num+'_'+c).enable();
384
- $(type+'_cc_cid_'+num+'_'+c).enable();
385
-
386
- if(document.getElementById(type+'_new_credito_parcelamento_'+num+'_'+c)!= null) {
387
- $(type+'_new_credito_parcelamento_'+num+'_'+c).enable();
388
- }
389
-
390
- if(document.getElementById(type+'_new_value_'+num+'_'+c)!= null) {
391
- $(type+'_new_value_'+num+'_'+c).enable();
392
- }
393
-
394
- /* Show new credit card fields */
395
- $(type+'_new_credit_card_'+num+'_'+c).show();
396
-
397
- if($('parcelamento_'+num+'_'+c) != null) {
398
- $('parcelamento_' + num + '_' + c).hide();
399
- }
400
- if(document.getElementById('value_'+num+'_'+c)!= null) {
401
- $('value_'+num+'_'+c).hide();
402
- }
403
- } else {
404
- /* Disable fields */
405
- $(type+'_'+num+'_'+c+'_cc_type').disable();
406
- $(type+'_'+num+'_'+c+'_cc_number').disable();
407
- $(type+'_cc_holder_name_'+num+'_'+c).disable();
408
- $(type+'_expirationMonth_'+num+'_'+c).disable();
409
- $(type+'_expirationYear_'+num+'_'+c).disable();
410
- $(type+'_cc_cid_'+num+'_'+c).disable();
411
-
412
- if(document.getElementById(type+'_new_credito_parcelamento_'+num+'_'+c)!= null) {
413
- $(type+'_new_credito_parcelamento_'+num+'_'+c).disable();
414
- }
415
-
416
- if(document.getElementById(type+'_new_value_'+num+'_'+c)!= null) {
417
- $(type+'_new_value_'+num+'_'+c).disable();
418
- }
419
-
420
- /* Hide new credit card fields */
421
- $(type+'_new_credit_card_'+num+'_'+c).hide();
422
-
423
- if($('parcelamento_'+num+'_'+c) != null) {
424
- $('parcelamento_' + num + '_' + c).show();
425
- }
426
-
427
- if(document.getElementById('value_'+num+'_'+c)!= null) {
428
- $('value_'+num+'_'+c).show();
429
- }
430
- group = '.'+field.readAttribute('data');
431
-
432
- field.select('option').each(function(opt){
433
- if(opt.value == field.value){
434
- if(opt.readAttribute('data')){
435
- grandTotal = 0;
436
-
437
- fieldValue = field.up(3).select(group+'.check_values')[0];
438
- if(fieldValue != undefined) {
439
- grandTotal = fieldValue.value;
440
- }
441
- if(field.up(3).select(group+'.installment-token')[0] != undefined) {
442
- updateInstallments(opt.readAttribute('data'), field.up(3).select(group + '.installment-token')[0], grandTotal);
443
- }
444
- }
445
- }
446
- });
447
- }
448
- }
449
-
450
- function cc_cid(field, num, c) {
451
- var type = $$('input[name="payment\\[method\\]"]:checked').first().value;
452
- var cc_cid = document.getElementById(type+'_cc_cid_'+num+'_'+c);
453
-
454
- if(field.value == 'AE') {
455
- cc_cid.removeClassName('minimum-length-3');
456
- cc_cid.removeClassName('maximum-length-3');
457
- cc_cid.addClassName('minimum-length-4');
458
- cc_cid.addClassName('maximum-length-4');
459
- } else {
460
- cc_cid.removeClassName('minimum-length-4');
461
- cc_cid.removeClassName('maximum-length-4');
462
- cc_cid.addClassName('minimum-length-3');
463
- cc_cid.addClassName('maximum-length-3');
464
- }
465
- }
466
-
467
- function hide_methods(dont_hide) {
468
- if(document.getElementById('1CreditCardsOneInstallment')!= null && dont_hide != '1CreditCardsOneInstallment'){
469
- document.getElementById('1CreditCardsOneInstallment').style.display='none';
470
- }
471
-
472
- if(document.getElementById('1CreditCards')!= null && dont_hide != '1CreditCards'){
473
- document.getElementById('1CreditCards').style.display='none';
474
- }
475
-
476
- if(document.getElementById('2CreditCards')!= null && dont_hide != '2CreditCards'){
477
- document.getElementById('2CreditCards').style.display='none';
478
- }
479
-
480
- if(document.getElementById('3CreditCards')!= null && dont_hide != '3CreditCards'){
481
- document.getElementById('3CreditCards').style.display='none';
482
- }
483
-
484
- if(document.getElementById('4CreditCards')!= null && dont_hide != '4CreditCards'){
485
- document.getElementById('4CreditCards').style.display='none';
486
- }
487
-
488
- if(document.getElementById('5CreditCards')!= null && dont_hide != '5CreditCards'){
489
- document.getElementById('5CreditCards').style.display='none';
490
- }
491
-
492
- if(document.getElementById('BoletoBancario')!= null && dont_hide != 'BoletoBancario'){
493
- document.getElementById('BoletoBancario').style.display='none';
494
- }
495
-
496
- $(dont_hide).show();
497
- }
498
-
499
- function hide_methods_admin(dont_hide) {
500
- if(document.getElementById('1CreditCardsOneInstallment')!= null && dont_hide != '1CreditCardsOneInstallment'){
501
- document.getElementById('1CreditCardsOneInstallment').style.display='none';
502
- }
503
-
504
- if(document.getElementById('1CreditCards')!= null && dont_hide != '1CreditCards'){
505
- document.getElementById('1CreditCards').style.display='none';
506
- }
507
-
508
- if(document.getElementById('2CreditCards')!= null && dont_hide != '2CreditCards'){
509
- document.getElementById('2CreditCards').style.display='none';
510
- }
511
-
512
- if(document.getElementById('3CreditCards')!= null && dont_hide != '3CreditCards'){
513
- document.getElementById('3CreditCards').style.display='none';
514
- }
515
-
516
- if(document.getElementById('4CreditCards')!= null && dont_hide != '4CreditCards'){
517
- document.getElementById('4CreditCards').style.display='none';
518
- }
519
-
520
- if(document.getElementById('5CreditCards')!= null && dont_hide != '5CreditCards'){
521
- document.getElementById('5CreditCards').style.display='none';
522
- }
523
-
524
- if(document.getElementById('BoletoBancario')!= null && dont_hide != 'BoletoBancario'){
525
- document.getElementById('BoletoBancario').style.display='none';
526
- }
527
-
528
- $(dont_hide).show();
529
- }
530
-
531
- function calculateInstallmentValue(field, num, c, url) {
532
- var type = $$('input[name="payment\\[method\\]"]:checked').first().value;
533
-
534
- var total = $('baseGrandTotal').value;
535
- if($('partial') != undefined){
536
- total = String(quoteBaseGrandTotal);
537
- }
538
- var total_oc = parseFloat(total.replace(',','.'));
539
- var field_id = type + '_credito_parcelamento_' + num + '_' + c;
540
- var field_id_new = type + '_new_credito_parcelamento_' + num + '_' + c;
541
- var rest = '';
542
- var response = '';
543
- var vfield = field.value;
544
- var vfield_oc = parseFloat(vfield.replace(',', '.'));
545
-
546
-
547
-
548
- if(vfield_oc >= total_oc) {
549
- vfield_oc = total_oc - (total_oc - 0.01);
550
- }
551
-
552
- if(parseFloat(vfield_oc)) {
553
- selects = field.up(3).select('select');
554
-
555
- selects.each(function(select){
556
- if(select.name.indexOf('parcelamento') != -1){
557
- installmentElement = select;
558
- }
559
- });
560
-
561
- var id = field.id;
562
- var realId = id
563
- .replace('mundipagg_creditcard','')
564
- .replace('mundipagg_twocreditcards_','')
565
- .replace('mundipagg_threecreditcards_','')
566
- .replace('mundipagg_fourcreditcards_','')
567
- .replace('mundipagg_fivecreditcards_','')
568
- .replace('_cc_number','')
569
- .replace('value_','');
570
- window['brand_'+realId] = undefined;
571
-
572
- if($('parcelamento_'+realId) != undefined){
573
-
574
- installmentElement = $('parcelamento_'+realId).select('select')[0];
575
- field.up(3).previous().select('.tokens')[0].select('option').each(function(opt){
576
- if(opt.selected){
577
- window['brand_'+realId] = opt.readAttribute('data');
578
- }
579
- });
580
- }
581
-
582
- var cardType = id.replace('mundipagg_','').replace('_cc_number','').replace('_'+realId,'');
583
-
584
- if(window['installmentElement'] != undefined) {
585
- window['select_html_' + realId] = installmentElement.innerHTML;
586
- window['select_' + realId] = installmentElement;
587
- if (window['brand_' + realId] != undefined) {
588
- updateInstallments(window['brand_' + realId], installmentElement, vfield_oc);
589
- } else {
590
- var brand = field.up(3).select('.cc_brand_types.active')[0];
591
- if (brand != undefined) {
592
- window['brand_' + realId] = brand.next().value;
593
- updateInstallments(window['brand_' + realId], installmentElement, vfield_oc);
594
- } else {
595
- updateInstallments(0, installmentElement, vfield_oc);
596
- }
597
-
598
- }
599
- }
600
-
601
- /* If more than 2 decimals we reduce to 2 */
602
- $(field).value = (vfield_oc.toFixed(2)).replace('.',',');
603
-
604
- /* If two Credit Cards we can deduct second credit card installments */
605
- if(type == 'mundipagg_twocreditcards' && num == 2) {
606
- new_value_oc = (total.replace(',', '.') - vfield_oc).toFixed(2);
607
- new_value = String(new_value_oc).replace('.',',');
608
-
609
- if(c != 2) {
610
- if( typeof($$('#mundipagg_twocreditcards_value_2_2')[0]) != 'undefined') {
611
- $$('#mundipagg_twocreditcards_value_2_2')[0].value = new_value;
612
- }
613
-
614
- $$('#mundipagg_twocreditcards_new_value_2_2')[0].value = new_value;
615
- selects = $$('#mundipagg_twocreditcards_new_value_2_2')[0].up(3).select('select');
616
- installmentElement = undefined;
617
- selects.each(function(select){
618
- if(select.name.indexOf('parcelamento') != -1){
619
- installmentElement = select;
620
- }
621
- });
622
- if($('parcelamento_2_2') != undefined && window['installmentElement'] == undefined){
623
- installmentElement = $('parcelamento_2_2').select('select')[0];
624
-
625
- }
626
- if($('parcelamento_2_2') != undefined){
627
- $('mundipagg_twocreditcards_token_2_2').select('option').each(function(opt){
628
- if(opt.selected){
629
- window['brand_2_2'] = opt.readAttribute('data');
630
-
631
- }
632
- });
633
- }
634
-
635
- if(window['installmentElement'] != undefined) {
636
- window['select_html_2_2'] = installmentElement.innerHTML;
637
- window['select_2_2'] = installmentElement;
638
-
639
- if (window['brand_2_2'] != undefined) {
640
- updateInstallments(window['brand_2_2'], installmentElement, new_value);
641
-
642
- if ($('parcelamento_2_2') != undefined) {
643
-
644
- updateInstallments(window['brand_2_2'], $('parcelamento_2_2').select('select')[0], new_value);
645
- }
646
- } else {
647
-
648
- updateInstallments(0, installmentElement, new_value);
649
- if ($('parcelamento_2_2') != undefined) {
650
- updateInstallments(0, $('parcelamento_2_2').select('select')[0], new_value);
651
- }
652
- }
653
- }
654
- }
655
-
656
- if(c != 1) {
657
- if( typeof($$('#mundipagg_twocreditcards_value_2_1')[0]) != 'undefined') {
658
- $$('#mundipagg_twocreditcards_value_2_1')[0].value = new_value;
659
- }
660
-
661
- $$('#mundipagg_twocreditcards_new_value_2_1')[0].value = new_value;
662
- selects = $$('#mundipagg_twocreditcards_new_value_2_1')[0].up(3).select('select');
663
- installmentElement = undefined;
664
- selects.each(function(select){
665
- if(select.name.indexOf('parcelamento') != -1){
666
- installmentElement = select;
667
- }
668
- });
669
-
670
- if($('parcelamento_2_1') != undefined && window['installmentElement'] == undefined){
671
- installmentElement = $('parcelamento_2_1').select('select')[0];
672
-
673
- }
674
- if($('parcelamento_2_1') != undefined){
675
- $('mundipagg_twocreditcards_token_2_1').select('option').each(function(opt){
676
- if(opt.selected){
677
- window['brand_2_1'] = opt.readAttribute('data');
678
- }
679
- });
680
- }
681
-
682
- if(window['installmentElement'] != undefined) {
683
- window['select_html_2_1'] = installmentElement.innerHTML;
684
- window['select_2_1'] = installmentElement;
685
-
686
- if (window['brand_2_1'] != undefined) {
687
- updateInstallments(window['brand_2_1'], installmentElement, new_value);
688
- if ($('parcelamento_2_1') != undefined) {
689
-
690
- updateInstallments(window['brand_2_1'], $('parcelamento_2_1').select('select')[0], new_value);
691
- }
692
- } else {
693
- updateInstallments(0, installmentElement, new_value);
694
- if ($('parcelamento_2_1') != undefined) {
695
- updateInstallments(0, $('parcelamento_2_1').select('select')[0], new_value);
696
- }
697
- }
698
- }
699
- }
700
- }
701
- }
702
- }
703
-
704
- function installments(field, field_new, num, c, val, url) {
705
- if(!isNaN(parseFloat(val)) && isFinite(val) && val > 0) {
706
- new Ajax.Request(url + 'mundipagg/standard/installments', {
707
- method: 'post',
708
- parameters: {val: val},
709
- onSuccess: function(response) {
710
- if (200 == response.status){
711
- var result = eval("(" + response.responseText + ")");
712
-
713
- var installments = result.qtdParcelasMax;
714
- var currencySymbol = result.currencySymbol;
715
-
716
- if(installments != null) {
717
- if(document.getElementById(field) != null) {
718
- document.getElementById(field).options.length = 0;
719
- }
720
-
721
- if(document.getElementById(field_new) != null) {
722
- document.getElementById(field_new).options.length = 0;
723
- }
724
-
725
- for(var i = 1;i<=installments;i++) {
726
- var amount = val / i;
727
- amount = (amount.toFixed(2)).replace('.',',');
728
-
729
- if(i == 1) {
730
- var label = i + 'x de ' + currencySymbol + amount;
731
- } else {
732
- var label = i + 'x de ' + currencySymbol + amount + " sem juros";
733
- }
734
-
735
- if(document.getElementById(field) != null) {
736
- $(field).options[$(field).options.length] = new Option(label, i);
737
- }
738
-
739
- if(document.getElementById(field_new) != null) {
740
- $(field_new).options[$(field_new).options.length] = new Option(label, i);
741
- }
742
- }
743
- } else {
744
- if(document.getElementById(field) != null) {
745
- document.getElementById(field).options.length = 0;
746
- }
747
- }
748
- }
749
- },
750
- onFailure: function(response) {
751
- alert('Por favor tente novamente!');
752
- }
753
- });
754
- }
755
- }
756
-
757
- function check_values() {
758
- var method = $$('input[name="payment\\[method\\]"]:checked').first().value;
759
- var type = $$('#mundipagg_type:enabled')[0].value;
760
- var num = type[0].substring(0, 1);
761
- var total = ($('baseGrandTotal').value).replace(',','.');
762
- var total_fields = 0.00;
763
- var total_fields_new = 0.00;
764
-
765
- for(var i=1;i<=num;i++){
766
- if(document.getElementById(method+'_value_'+ num +'_'+ i) != null) {
767
- var fieldv = ($(method+'_value_'+ num +'_'+ i).value).replace(',','.');
768
-
769
- total_fields = parseFloat(fieldv) + parseFloat(total_fields);
770
- }
771
-
772
- if(document.getElementById(method+'_new_value_'+ num +'_'+ i) != null) {
773
- var fieldv_new = ($(method+'_new_value_'+ num +'_'+ i).value).replace(',','.');
774
-
775
- total_fields_new = parseFloat(fieldv_new) + parseFloat(total_fields_new);
776
- }
777
- }
778
-
779
- if( (Math.abs(total - total_fields) < 0.000001) && (Math.abs(total - total_fields_new) < 0.000001) ) {
780
- return false;
781
- }
782
-
783
- return true;
784
- }
785
-
786
- function setCcType(field, code, num, c, issuer)
787
- {
788
- $$('#' + code + '_' + num + '_' + c + '_cc_type')[0].value = issuer;
789
- $(code + '_' + num + '_' + c + '_credito_instituicao_' + issuer).checked=true
790
-
791
- field = $(code + '_' + num + '_' + c + '_credito_instituicao_' + issuer);
792
-
793
- cc_cid(field, num, c)
794
- }
795
-
796
- function setTotalInterestHtml(field){
797
- var container = field.up(5);
798
- var totalFieldElement = container.select('div')[0];
799
- var totalFieldValue = parseFloat(totalFieldElement.innerHTML.replace(/\s/g, "").replace('<b>ValorTotal:</b>','').replace('R$','').replace('.','').replace(',','.'));
800
- var containerSelects = container.select('select');
801
- var template = '<div class="total_juros">'+Translator.translate('Total amount with interest: USD{%%%}')+'</div>';
802
- var totalInterest = 0;
803
-
804
- containerSelects.each(function(select){
805
- if(select.readAttribute('id').indexOf('credito_parcelamento') != -1){
806
- if(window.getComputedStyle(select.up(3)).getPropertyValue('display') == 'block'){
807
- var selectedText = select.options[select.selectedIndex].text;
808
- if(selectedText.indexOf('Total') != -1){
809
- realCurrentInterest = 0;
810
- newTotalInterest = parseFloat(selectedText.substring(selectedText.indexOf('Total'), selectedText.length).replace('Total: R$','').replace(')','').replace(/\s/g, "").replace('.','').replace(',','.'));
811
- if($(select.readAttribute('id').replace('credito_parcelamento','value')) != undefined) {
812
- currentValueField = parseFloat($(select.readAttribute('id').replace('credito_parcelamento', 'value')).value.replace('.','').replace(',', '.'));
813
- }else{
814
- currentValueField = NaN;
815
- }
816
-
817
- if(!isNaN(currentValueField)){
818
- realCurrentInterest = parseFloat(newTotalInterest - currentValueField );
819
- totalInterest = parseFloat(totalInterest + parseFloat(realCurrentInterest));
820
- }else{
821
- realCurrentInterest = parseFloat(newTotalInterest - totalFieldValue);
822
- totalInterest = parseFloat(totalInterest + parseFloat(realCurrentInterest));
823
- }
824
- }
825
- }
826
- }
827
- });
828
-
829
- if(Object.keys(totalFieldElement.select('.total_juros')).length){
830
- totalFieldElement.select('.total_juros')[0].remove();
831
- }
832
-
833
- if(totalInterest > 0){
834
- var strNumber = parseFloat(totalFieldValue + totalInterest).toFixed(2);
835
- while (strNumber.match(/^\d{4}/)){
836
- strNumber = strNumber.replace(/(\d)(\d{3}(\.|$))/, '$1.$2');
837
- }
838
- strNumber = strNumber.substring(0,parseInt(strNumber.length - 3))+','+strNumber.substring(parseInt(strNumber.length - 2), strNumber.length);
839
- totalFieldElement.insert(template.replace('{%%%}',strNumber));
840
- }
841
- }
842
-
843
- function checkInstallments(field, url)
844
- {
845
- if ($('onestepcheckout-form') == null) {
846
- params = $('co-payment-form').serialize(true);
847
- } else {
848
- params = $('onestepcheckout-form').serialize(true);
849
- }
850
-
851
- if(window['mundipaggTotalInterest'] == undefined) {
852
- window.mundipaggTotalInterest = 0;
853
- }
854
-
855
- setTotalInterestHtml(field);
856
-
857
- new Ajax.Request(url + 'checkout/onepage/savePayment', {
858
- method: 'post',
859
- parameters: params,
860
- onSuccess: function(response) {
861
- if (200 == response.status){
862
- var result = eval("(" + response.responseText + ")");
863
- }
864
- },
865
- onFailure: function(response) {
866
- console.log('failed');
867
- },
868
- onComplete: function(response) {
869
-
870
- }
871
- });
872
- }
 
 
 
 
1
+ function validaCPF(cpf, pType) {
2
+ if (Validation.get('IsEmpty').test(cpf)) {
3
+ return false;
4
+ }
5
+
6
+ var valid = true;
7
+ var cpf = cpf.replace(/[.\//-]/g, '');
8
+
9
+ if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
10
+ valid = false;
11
+ add = 0;
12
+ for (i = 0; i < 9; i++)
13
+ add += parseInt(cpf.charAt(i)) * (10 - i);
14
+ rev = 11 - (add % 11);
15
+ if (rev == 10 || rev == 11)
16
+ rev = 0;
17
+ if (rev != parseInt(cpf.charAt(9)))
18
+ valid = false;
19
+ add = 0;
20
+ for (i = 0; i < 10; i++)
21
+ add += parseInt(cpf.charAt(i)) * (11 - i);
22
+ rev = 11 - (add % 11);
23
+ if (rev == 10 || rev == 11)
24
+ rev = 0;
25
+ if (rev != parseInt(cpf.charAt(10)))
26
+ valid = false;
27
+
28
+ if (valid) {
29
+ return true;
30
+ }
31
+
32
+ if (cpf.length >= 14) {
33
+ if (cpf.substring(12, 14) == checkCNPJ(cpf.substring(0, 12))) {
34
+ return true;
35
+ }
36
+ }
37
+
38
+ return false;
39
+ }
40
+
41
+ function checkCNPJ(vCNPJ) {
42
+ var mControle = "";
43
+ var aTabCNPJ = new Array(5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2);
44
+ for (i = 1; i <= 2; i++) {
45
+ mSoma = 0;
46
+ for (j = 0; j < vCNPJ.length; j++)
47
+ mSoma = mSoma + (vCNPJ.substring(j, j + 1) * aTabCNPJ[j]);
48
+ if (i == 2) mSoma = mSoma + ( 2 * mDigito );
49
+ mDigito = ( mSoma * 10 ) % 11;
50
+ if (mDigito == 10) mDigito = 0;
51
+ mControle1 = mControle;
52
+ mControle = mDigito;
53
+ aTabCNPJ = new Array(6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3);
54
+ }
55
+
56
+ return ( (mControle1 * 10) + mControle );
57
+ }
58
+
59
+ Number.prototype.formatMoney = function (decPlaces, thouSeparator, decSeparator) {
60
+ var n = this,
61
+ decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
62
+ decSeparator = decSeparator == undefined ? "." : decSeparator,
63
+ thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
64
+ sign = n < 0 ? "-" : "",
65
+ i = parseFloat(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
66
+ j = (j = i.length) > 3 ? j % 3 : 0;
67
+ return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
68
+ };
69
+
70
+ function remove_characters(event) {
71
+ /* Allow: backspace, delete, tab, escape, and enter */
72
+ if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
73
+ /* Allow: Ctrl+A */
74
+ (event.keyCode == 65 && event.ctrlKey === true) ||
75
+ /* Allow: home, end, left, right */
76
+ (event.keyCode >= 35 && event.keyCode <= 39)) {
77
+ /* let it happen, don't do anything */
78
+ return;
79
+ } else {
80
+ /* Ensure that it is a number and stop the keypress */
81
+ if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
82
+ event.preventDefault();
83
+ }
84
+ }
85
+ }
86
+
87
+ function selectCredcard(ele) {
88
+ var check = checkCredcardType(ele.value);
89
+
90
+ ele.up(2).previous().select('.cc_brand_types').each(function (el) {
91
+ el.removeClassName('active');
92
+ });
93
+
94
+ var id = ele.id;
95
+
96
+ var realId = id
97
+ .replace('mundipagg_creditcard', '')
98
+ .replace('mundipagg_twocreditcards_', '')
99
+ .replace('mundipagg_threecreditcards_', '')
100
+ .replace('mundipagg_fourcreditcards_', '')
101
+ .replace('mundipagg_fivecreditcards_', '')
102
+ .replace('_cc_number', '');
103
+
104
+ var cardType = id.replace('mundipagg_', '').replace('_cc_number', '').replace('_' + realId, '');
105
+
106
+ if (check) {
107
+ var parentElement = ele.up(2).previous().select('li');
108
+
109
+ parentElement.each(function (element) {
110
+ var inpt = element.select('input')[0];
111
+
112
+ if (inpt.value == check) {
113
+ inpt.click();
114
+ inpt.previous().addClassName('active');
115
+
116
+ if (window.isInstallmentsEnabled) {
117
+ if (window[realId] != check) {
118
+ window[realId] = check;
119
+ window['brand_' + realId] = check;
120
+
121
+ selects = ele.up(3).select('select');
122
+ selects.each(function (select) {
123
+ if (select.name.indexOf('parcelamento') != -1) {
124
+ installmentElement = select;
125
+ }
126
+ });
127
+
128
+ if (window['installmentElement'] != undefined) {
129
+ window['select_html_' + realId] = installmentElement.innerHTML;
130
+ window['select_' + realId] = installmentElement;
131
+
132
+ if ($('mundipagg_' + cardType + '_new_value_' + realId) != undefined) {
133
+ if ($('mundipagg_' + cardType + '_new_value_' + realId).value == '') {
134
+ updateInstallments(check, installmentElement);
135
+ } else {
136
+ updateInstallments(check, installmentElement, $('mundipagg_' + cardType + '_new_value_' + realId).value);
137
+ }
138
+ } else {
139
+ updateInstallments(check, installmentElement);
140
+ }
141
+ }
142
+ }
143
+ }
144
+ }
145
+ });
146
+ } else {
147
+ if (window[realId] != undefined) {
148
+ window[realId] = undefined;
149
+ if ($('mundipagg_' + cardType + '_new_value_' + realId) != undefined) {
150
+ totalValue = $('mundipagg_' + cardType + '_new_value_' + realId).value;
151
+ } else {
152
+ totalValue = '';
153
+ }
154
+ if (window['select_' + realId] != undefined && totalValue == '') {
155
+ window['select_' + realId].innerHTML = window['select_html_' + realId];
156
+ } else {
157
+ if (window.installmentElement !== undefined) {
158
+ updateInstallments(0, installmentElement, $('mundipagg_' + cardType + '_new_value_' + realId).value);
159
+ }
160
+ }
161
+ }
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Javascript method based on helper Mundipagg: https://github.com/mundipagg/mundipagg-one-php/blob/master/lib/One/Helper/CreditCardHelper.php
167
+ *
168
+ * @param string cardNumber Número do cartão
169
+ * @return string Bandeira do cartão
170
+ */
171
+ function checkCredcardType(cardNumber) {
172
+ var flag = false;
173
+ /* Extrai somente números do cartão (Note: Not only draw numbers, letters as well).*/
174
+ cardNumber = cardNumber.toString().replace(/[^0-9a-zA-Z ]/g, '');
175
+
176
+ if (inArray(cardNumber.substring(0, 6), ['401178', '401179', '504175', '509002', '509003', '438935', '457631',
177
+ '451416', '457632', '431274', '438935', '451416', '457393', '457631', '457632', '504175', '506726',
178
+ '506727', '506739', '506741', '506742', '506744', '506747', '506748', '506778', '627780', '636297',
179
+ '636368', '636369', '636297', '637095']) ||
180
+ isBetween(cardNumber.substring(0, 6), '650031', '650033') ||
181
+ isBetween(cardNumber.substring(0, 6), '650035', '650051') ||
182
+ isBetween(cardNumber.substring(0, 6), '650405', '650439') ||
183
+ isBetween(cardNumber.substring(0, 6), '650485', '650538') ||
184
+ isBetween(cardNumber.substring(0, 6), '650541', '650598') ||
185
+ isBetween(cardNumber.substring(0, 6), '650700', '650718') ||
186
+ isBetween(cardNumber.substring(0, 6), '650720', '650727') ||
187
+ isBetween(cardNumber.substring(0, 6), '650901', '650920') ||
188
+ isBetween(cardNumber.substring(0, 6), '506699', '506778') ||
189
+ isBetween(cardNumber.substring(0, 6), '651652', '651679') ||
190
+ isBetween(cardNumber.substring(0, 6), '509000', '509999') ||
191
+ isBetween(cardNumber.substring(0, 6), '655000', '655019') ||
192
+ isBetween(cardNumber.substring(0, 6), '655021', '655058')
193
+ ) {
194
+ flag = 'EL';
195
+ }
196
+ else if (cardNumber.substring(0, 4) == '6011' || cardNumber.substring(0, 3) == '622' || inArray(cardNumber.substring(0, 2), ['64', '65'])) {
197
+ /* Flag not implemented in the module yet.*/
198
+ flag = 'discover';
199
+ }
200
+ else if (inArray(cardNumber.substring(0, 3), ['301', '305']) || inArray(cardNumber.substring(0, 2), ['36', '38'])) {
201
+ flag = 'DI';
202
+ }
203
+ else if (inArray(cardNumber.substring(0, 2), ['34', '37'])) {
204
+ flag = 'AE';
205
+ }
206
+ else if (cardNumber.substring(0, 2) == '50') {
207
+ /* Flag not implemented in the module yet.*/
208
+ flag = 'aura';
209
+ }
210
+ else if (inArray(cardNumber.substring(0, 2), ['38', '60'])) {
211
+ flag = 'HI';
212
+ }
213
+ else if (cardNumber[0] == '4') {
214
+ flag = 'VI';
215
+ }
216
+ else if (cardNumber[0] == '5' || cardNumber[0] == '2') {
217
+ flag = 'MC';
218
+ }
219
+
220
+ return flag;
221
+ }
222
+
223
+ /**
224
+ * Javascript method inArray equivalent PHP
225
+ */
226
+ function inArray(neddle, arraySearch) {
227
+ return arraySearch.filter(function (item) {
228
+ return item == neddle;
229
+ }).length;
230
+ }
231
+
232
+ function isBetween(neddle, first, last) {
233
+ return (neddle >= first && neddle <= last);
234
+ }
235
+
236
+ function updateInstallments(ccType, element, total) {
237
+ if (window['admin_area_url'] == undefined) {
238
+ var url = window.installmentsandinterestUrl;
239
+ } else {
240
+ var url = window['admin_area_url_installments_and_interest'];
241
+ }
242
+
243
+ /* Force select */
244
+ document.getElementById(element.id).selectedIndex = element.value - 1;
245
+
246
+ /* Get actual parcel */
247
+ var parcel = element.value;
248
+
249
+ if (!total) {
250
+ total = $('baseGrandTotal').value;
251
+ }
252
+
253
+ if (window.ajax_loader_mundipagg_img != undefined) {
254
+ mundipagg_img = window.ajax_loader_mundipagg_img;
255
+ } else {
256
+ mundipagg_img = window.ajaxLoaderGif;
257
+ }
258
+
259
+ loading = new Element('img', {src: mundipagg_img});
260
+ loading.addClassName('mundipagg_reload');
261
+
262
+ element.insert({
263
+ 'after': loading
264
+ });
265
+
266
+ element.options.length = 0;
267
+
268
+ var id = element.id.replace('_new_credito_parcelamento', '') + '_cc_number';
269
+
270
+ new Ajax.Request(url, {
271
+ method: 'post',
272
+ parameters: {cctype: ccType, total: total},
273
+ onSuccess: function (response) {
274
+ var res = JSON.parse(response.responseText);
275
+
276
+ if (res['installments'] != undefined) {
277
+ i = 0;
278
+
279
+ if (res.installments.length == 1) {
280
+ element.options[0] = new Option(res.installments[0], 0, false, false);
281
+ } else {
282
+ for (key in res.installments) {
283
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(key)) {
284
+ /* Set option as selected */
285
+ if (key == parcel) {
286
+ var selected = true;
287
+ } else {
288
+ var selected = false;
289
+ }
290
+
291
+ element.options[i] = new Option(res.installments[key], key, selected, false);
292
+
293
+ /* Select option */
294
+ if (key == parcel) {
295
+ document.getElementById(element.id).selectedIndex = key - 1;
296
+ }
297
+
298
+ i++;
299
+ }
300
+ }
301
+ }
302
+
303
+ if (res['brand'] != undefined) {
304
+ window['brand_' + id.replace('mundipagg_twocreditcards_', '').replace('_cc_number', '')] = res.brand;
305
+ }
306
+ } else {
307
+ window['select_' + id].innerHTML = window['select_html_' + id];
308
+ window['brand_' + id.replace('mundipagg_twocreditcards_', '').replace('_cc_number', '')] = undefined;
309
+ }
310
+
311
+ $$('.mundipagg_reload')[0].remove();
312
+
313
+ if ($('order-billing_method') != undefined) {
314
+ var data = {};
315
+ this.loadArea(['totals'], true, data);
316
+ }
317
+ }
318
+ });
319
+ }
320
+
321
+ function remove_special_characters(event) {
322
+ /* Allow: backspace, delete, tab, escape, comma, enter and decimal point */
323
+ if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 188 || event.keyCode == 13 || event.keyCode == 110 ||
324
+ /* Allow: Ctrl+A */
325
+ (event.keyCode == 65 && event.ctrlKey === true) ||
326
+ /* Allow: home, end, left, right */
327
+ (event.keyCode >= 35 && event.keyCode <= 39)) {
328
+ /* let it happen, don't do anything */
329
+ return;
330
+ } else {
331
+ /* Ensure that it is a number and stop the keypress */
332
+ if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
333
+ event.preventDefault();
334
+ }
335
+ }
336
+ }
337
+
338
+ if (Validation) {
339
+ Validation.add('validar_cpf', 'The taxvat is invalid', function (v) {
340
+ return validaCPF(v, 0);
341
+ });
342
+
343
+ /**
344
+ * Hash with credit card types which can be simply extended in payment modules
345
+ * 0 - regexp for card number
346
+ * 1 - regexp for cvn
347
+ * 2 - check or not credit card number trough Luhn algorithm by
348
+ * function validateCreditCard which you can find above in this file
349
+ */
350
+ Validation.creditCartTypes = $H({
351
+ 'VI': [new RegExp('^4[0-9]{12}([0-9]{3})?$'), new RegExp('^[0-9]{3}$'), true],
352
+ 'MC': [new RegExp('^5[1-5][0-9]{14}$'), new RegExp('^[0-9]{3}$'), true],
353
+ 'AE': [new RegExp('^3[47][0-9]{13}$'), new RegExp('^[0-9]{4}$'), true],
354
+ 'DI': [false, new RegExp('^[0-9]{3}$'), true],
355
+ 'OT': [false, new RegExp('^([0-9]{3}|[0-9]{4})?$'), false],
356
+ 'EL': [false, new RegExp('^([0-9]{3})?$'), true],
357
+ 'HI': [false, new RegExp('^([0-9]{3})?$'), false]
358
+ });
359
+
360
+ Validation.add('check_values', 'Check the values to pass on each card', function () {
361
+ return check_values();
362
+ });
363
+
364
+ Validation.add('validate-cc-exp-cus', 'Expiration date of the incorrect card', function (v, elm) {
365
+ return verify_cc_expiration_date(v, elm);
366
+ });
367
+ }
368
+
369
+ function verify_cc_expiration_date(v, elm) {
370
+ var ccExpMonth = v;
371
+ var ccExpYear = $(elm.id.substr(0, elm.id.indexOf('_expirationMonth')) + '_expirationYear').value;
372
+ var currentTime = new Date();
373
+ var currentMonth = currentTime.getMonth() + 1;
374
+ var currentYear = currentTime.getFullYear();
375
+ if (ccExpMonth < currentMonth && ccExpYear == currentYear) {
376
+ return false;
377
+ }
378
+ return true;
379
+ }
380
+
381
+ function token_or_not(num, c, field) {
382
+ var type = $$('input[name="payment\\[method\\]"]:checked').first().value;
383
+
384
+ if (document.getElementById(type + '_token_' + num + '_' + c).value == 'new') {
385
+ /* Remove disable fields */
386
+ $(type + '_' + num + '_' + c + '_cc_type').enable();
387
+ $(type + '_' + num + '_' + c + '_cc_number').enable();
388
+ $(type + '_cc_holder_name_' + num + '_' + c).enable();
389
+ $(type + '_expirationMonth_' + num + '_' + c).enable();
390
+ $(type + '_expirationYear_' + num + '_' + c).enable();
391
+ $(type + '_cc_cid_' + num + '_' + c).enable();
392
+
393
+ if (document.getElementById(type + '_new_credito_parcelamento_' + num + '_' + c) != null) {
394
+ $(type + '_new_credito_parcelamento_' + num + '_' + c).enable();
395
+ }
396
+
397
+ if (document.getElementById(type + '_new_value_' + num + '_' + c) != null) {
398
+ $(type + '_new_value_' + num + '_' + c).enable();
399
+ }
400
+
401
+ /* Show new credit card fields */
402
+ $(type + '_new_credit_card_' + num + '_' + c).show();
403
+
404
+ if ($('parcelamento_' + num + '_' + c) != null) {
405
+ $('parcelamento_' + num + '_' + c).hide();
406
+ }
407
+ if (document.getElementById('value_' + num + '_' + c) != null) {
408
+ $('value_' + num + '_' + c).hide();
409
+ }
410
+ } else {
411
+ /* Disable fields */
412
+ $(type + '_' + num + '_' + c + '_cc_type').disable();
413
+ $(type + '_' + num + '_' + c + '_cc_number').disable();
414
+ $(type + '_cc_holder_name_' + num + '_' + c).disable();
415
+ $(type + '_expirationMonth_' + num + '_' + c).disable();
416
+ $(type + '_expirationYear_' + num + '_' + c).disable();
417
+ $(type + '_cc_cid_' + num + '_' + c).disable();
418
+
419
+ if (document.getElementById(type + '_new_credito_parcelamento_' + num + '_' + c) != null) {
420
+ $(type + '_new_credito_parcelamento_' + num + '_' + c).disable();
421
+ }
422
+
423
+ if (document.getElementById(type + '_new_value_' + num + '_' + c) != null) {
424
+ $(type + '_new_value_' + num + '_' + c).disable();
425
+ }
426
+
427
+ /* Hide new credit card fields */
428
+ $(type + '_new_credit_card_' + num + '_' + c).hide();
429
+
430
+ if ($('parcelamento_' + num + '_' + c) != null) {
431
+ $('parcelamento_' + num + '_' + c).show();
432
+ }
433
+
434
+ if (document.getElementById('value_' + num + '_' + c) != null) {
435
+ $('value_' + num + '_' + c).show();
436
+ }
437
+ group = '.' + field.readAttribute('data');
438
+
439
+ field.select('option').each(function (opt) {
440
+ if (opt.value == field.value) {
441
+ if (opt.readAttribute('data')) {
442
+ grandTotal = 0;
443
+
444
+ fieldValue = field.up(3).select(group + '.check_values')[0];
445
+ if (fieldValue != undefined) {
446
+ grandTotal = fieldValue.value;
447
+ }
448
+ if (field.up(3).select(group + '.installment-token')[0] != undefined) {
449
+ updateInstallments(opt.readAttribute('data'), field.up(3).select(group + '.installment-token')[0], grandTotal);
450
+ }
451
+ }
452
+ }
453
+ });
454
+ }
455
+ }
456
+
457
+ function cc_cid(field, num, c) {
458
+ var type = $$('input[name="payment\\[method\\]"]:checked').first().value;
459
+ var cc_cid = document.getElementById(type + '_cc_cid_' + num + '_' + c);
460
+
461
+ if (field.value == 'AE') {
462
+ cc_cid.removeClassName('minimum-length-3');
463
+ cc_cid.removeClassName('maximum-length-3');
464
+ cc_cid.addClassName('minimum-length-4');
465
+ cc_cid.addClassName('maximum-length-4');
466
+ } else {
467
+ cc_cid.removeClassName('minimum-length-4');
468
+ cc_cid.removeClassName('maximum-length-4');
469
+ cc_cid.addClassName('minimum-length-3');
470
+ cc_cid.addClassName('maximum-length-3');
471
+ }
472
+ }
473
+
474
+ function hide_methods(dont_hide) {
475
+ if (document.getElementById('1CreditCardsOneInstallment') != null && dont_hide != '1CreditCardsOneInstallment') {
476
+ document.getElementById('1CreditCardsOneInstallment').style.display = 'none';
477
+ }
478
+
479
+ if (document.getElementById('1CreditCards') != null && dont_hide != '1CreditCards') {
480
+ document.getElementById('1CreditCards').style.display = 'none';
481
+ }
482
+
483
+ if (document.getElementById('2CreditCards') != null && dont_hide != '2CreditCards') {
484
+ document.getElementById('2CreditCards').style.display = 'none';
485
+ }
486
+
487
+ if (document.getElementById('3CreditCards') != null && dont_hide != '3CreditCards') {
488
+ document.getElementById('3CreditCards').style.display = 'none';
489
+ }
490
+
491
+ if (document.getElementById('4CreditCards') != null && dont_hide != '4CreditCards') {
492
+ document.getElementById('4CreditCards').style.display = 'none';
493
+ }
494
+
495
+ if (document.getElementById('5CreditCards') != null && dont_hide != '5CreditCards') {
496
+ document.getElementById('5CreditCards').style.display = 'none';
497
+ }
498
+
499
+ if (document.getElementById('BoletoBancario') != null && dont_hide != 'BoletoBancario') {
500
+ document.getElementById('BoletoBancario').style.display = 'none';
501
+ }
502
+
503
+ $(dont_hide).show();
504
+ }
505
+
506
+ function hide_methods_admin(dont_hide) {
507
+ if (document.getElementById('1CreditCardsOneInstallment') != null && dont_hide != '1CreditCardsOneInstallment') {
508
+ document.getElementById('1CreditCardsOneInstallment').style.display = 'none';
509
+ }
510
+
511
+ if (document.getElementById('1CreditCards') != null && dont_hide != '1CreditCards') {
512
+ document.getElementById('1CreditCards').style.display = 'none';
513
+ }
514
+
515
+ if (document.getElementById('2CreditCards') != null && dont_hide != '2CreditCards') {
516
+ document.getElementById('2CreditCards').style.display = 'none';
517
+ }
518
+
519
+ if (document.getElementById('3CreditCards') != null && dont_hide != '3CreditCards') {
520
+ document.getElementById('3CreditCards').style.display = 'none';
521
+ }
522
+
523
+ if (document.getElementById('4CreditCards') != null && dont_hide != '4CreditCards') {
524
+ document.getElementById('4CreditCards').style.display = 'none';
525
+ }
526
+
527
+ if (document.getElementById('5CreditCards') != null && dont_hide != '5CreditCards') {
528
+ document.getElementById('5CreditCards').style.display = 'none';
529
+ }
530
+
531
+ if (document.getElementById('BoletoBancario') != null && dont_hide != 'BoletoBancario') {
532
+ document.getElementById('BoletoBancario').style.display = 'none';
533
+ }
534
+
535
+ $(dont_hide).show();
536
+ }
537
+
538
+ function calculateInstallmentValue(field, num, c, url) {
539
+ var type = $$('input[name="payment\\[method\\]"]:checked').first().value;
540
+
541
+ var total = $('baseGrandTotal').value;
542
+ if ($('partial') != undefined) {
543
+ total = String(quoteBaseGrandTotal);
544
+ }
545
+ var total_oc = parseFloat(total.replace(',', '.'));
546
+ var field_id = type + '_credito_parcelamento_' + num + '_' + c;
547
+ var field_id_new = type + '_new_credito_parcelamento_' + num + '_' + c;
548
+ var rest = '';
549
+ var response = '';
550
+ var vfield = field.value;
551
+ var vfield_oc = parseFloat(vfield.replace(',', '.'));
552
+
553
+
554
+ if (vfield_oc >= total_oc) {
555
+ vfield_oc = total_oc - (total_oc - 0.01);
556
+ }
557
+
558
+ if (parseFloat(vfield_oc)) {
559
+ selects = field.up(3).select('select');
560
+
561
+ selects.each(function (select) {
562
+ if (select.name.indexOf('parcelamento') != -1) {
563
+ installmentElement = select;
564
+ }
565
+ });
566
+
567
+ var id = field.id;
568
+ var realId = id
569
+ .replace('mundipagg_creditcard', '')
570
+ .replace('mundipagg_twocreditcards_', '')
571
+ .replace('mundipagg_threecreditcards_', '')
572
+ .replace('mundipagg_fourcreditcards_', '')
573
+ .replace('mundipagg_fivecreditcards_', '')
574
+ .replace('_cc_number', '')
575
+ .replace('value_', '');
576
+ window['brand_' + realId] = undefined;
577
+
578
+ if ($('parcelamento_' + realId) != undefined) {
579
+
580
+ installmentElement = $('parcelamento_' + realId).select('select')[0];
581
+ field.up(3).previous().select('.tokens')[0].select('option').each(function (opt) {
582
+ if (opt.selected) {
583
+ window['brand_' + realId] = opt.readAttribute('data');
584
+ }
585
+ });
586
+ }
587
+
588
+ var cardType = id.replace('mundipagg_', '').replace('_cc_number', '').replace('_' + realId, '');
589
+
590
+ if (window['installmentElement'] != undefined) {
591
+ window['select_html_' + realId] = installmentElement.innerHTML;
592
+ window['select_' + realId] = installmentElement;
593
+ if (window['brand_' + realId] != undefined) {
594
+ updateInstallments(window['brand_' + realId], installmentElement, vfield_oc);
595
+ } else {
596
+ var brand = field.up(3).select('.cc_brand_types.active')[0];
597
+ if (brand != undefined) {
598
+ window['brand_' + realId] = brand.next().value;
599
+ updateInstallments(window['brand_' + realId], installmentElement, vfield_oc);
600
+ } else {
601
+ updateInstallments(0, installmentElement, vfield_oc);
602
+ }
603
+
604
+ }
605
+ }
606
+
607
+ /* If more than 2 decimals we reduce to 2 */
608
+ $(field).value = (vfield_oc.toFixed(2)).replace('.', ',');
609
+
610
+ /* If two Credit Cards we can deduct second credit card installments */
611
+ if (type == 'mundipagg_twocreditcards' && num == 2) {
612
+ new_value_oc = (total.replace(',', '.') - vfield_oc).toFixed(2);
613
+ new_value = String(new_value_oc).replace('.', ',');
614
+
615
+ if (c != 2) {
616
+ if (typeof($$('#mundipagg_twocreditcards_value_2_2')[0]) != 'undefined') {
617
+ $$('#mundipagg_twocreditcards_value_2_2')[0].value = new_value;
618
+ }
619
+
620
+ $$('#mundipagg_twocreditcards_new_value_2_2')[0].value = new_value;
621
+ selects = $$('#mundipagg_twocreditcards_new_value_2_2')[0].up(3).select('select');
622
+ installmentElement = undefined;
623
+ selects.each(function (select) {
624
+ if (select.name.indexOf('parcelamento') != -1) {
625
+ installmentElement = select;
626
+ }
627
+ });
628
+ if ($('parcelamento_2_2') != undefined && window['installmentElement'] == undefined) {
629
+ installmentElement = $('parcelamento_2_2').select('select')[0];
630
+
631
+ }
632
+ if ($('parcelamento_2_2') != undefined) {
633
+ $('mundipagg_twocreditcards_token_2_2').select('option').each(function (opt) {
634
+ if (opt.selected) {
635
+ window['brand_2_2'] = opt.readAttribute('data');
636
+
637
+ }
638
+ });
639
+ }
640
+
641
+ if (window['installmentElement'] != undefined) {
642
+ window['select_html_2_2'] = installmentElement.innerHTML;
643
+ window['select_2_2'] = installmentElement;
644
+
645
+ if (window['brand_2_2'] != undefined) {
646
+ updateInstallments(window['brand_2_2'], installmentElement, new_value);
647
+
648
+ if ($('parcelamento_2_2') != undefined) {
649
+
650
+ updateInstallments(window['brand_2_2'], $('parcelamento_2_2').select('select')[0], new_value);
651
+ }
652
+ } else {
653
+
654
+ updateInstallments(0, installmentElement, new_value);
655
+ if ($('parcelamento_2_2') != undefined) {
656
+ updateInstallments(0, $('parcelamento_2_2').select('select')[0], new_value);
657
+ }
658
+ }
659
+ }
660
+ }
661
+
662
+ if (c != 1) {
663
+ if (typeof($$('#mundipagg_twocreditcards_value_2_1')[0]) != 'undefined') {
664
+ $$('#mundipagg_twocreditcards_value_2_1')[0].value = new_value;
665
+ }
666
+
667
+ $$('#mundipagg_twocreditcards_new_value_2_1')[0].value = new_value;
668
+ selects = $$('#mundipagg_twocreditcards_new_value_2_1')[0].up(3).select('select');
669
+ installmentElement = undefined;
670
+ selects.each(function (select) {
671
+ if (select.name.indexOf('parcelamento') != -1) {
672
+ installmentElement = select;
673
+ }
674
+ });
675
+
676
+ if ($('parcelamento_2_1') != undefined && window['installmentElement'] == undefined) {
677
+ installmentElement = $('parcelamento_2_1').select('select')[0];
678
+
679
+ }
680
+ if ($('parcelamento_2_1') != undefined) {
681
+ $('mundipagg_twocreditcards_token_2_1').select('option').each(function (opt) {
682
+ if (opt.selected) {
683
+ window['brand_2_1'] = opt.readAttribute('data');
684
+ }
685
+ });
686
+ }
687
+
688
+ if (window['installmentElement'] != undefined) {
689
+ window['select_html_2_1'] = installmentElement.innerHTML;
690
+ window['select_2_1'] = installmentElement;
691
+
692
+ if (window['brand_2_1'] != undefined) {
693
+ updateInstallments(window['brand_2_1'], installmentElement, new_value);
694
+ if ($('parcelamento_2_1') != undefined) {
695
+
696
+ updateInstallments(window['brand_2_1'], $('parcelamento_2_1').select('select')[0], new_value);
697
+ }
698
+ } else {
699
+ updateInstallments(0, installmentElement, new_value);
700
+ if ($('parcelamento_2_1') != undefined) {
701
+ updateInstallments(0, $('parcelamento_2_1').select('select')[0], new_value);
702
+ }
703
+ }
704
+ }
705
+ }
706
+ }
707
+ }
708
+ }
709
+
710
+ function installments(field, field_new, num, c, val, url) {
711
+ if (!isNaN(parseFloat(val)) && isFinite(val) && val > 0) {
712
+ new Ajax.Request(url + 'mundipagg/standard/installments', {
713
+ method: 'post',
714
+ parameters: {val: val},
715
+ onSuccess: function (response) {
716
+ if (200 == response.status) {
717
+ var result = eval("(" + response.responseText + ")");
718
+
719
+ var installments = result.qtdParcelasMax;
720
+ var currencySymbol = result.currencySymbol;
721
+
722
+ if (installments != null) {
723
+ if (document.getElementById(field) != null) {
724
+ document.getElementById(field).options.length = 0;
725
+ }
726
+
727
+ if (document.getElementById(field_new) != null) {
728
+ document.getElementById(field_new).options.length = 0;
729
+ }
730
+
731
+ for (var i = 1; i <= installments; i++) {
732
+ var amount = val / i;
733
+ amount = (amount.toFixed(2)).replace('.', ',');
734
+
735
+ if (i == 1) {
736
+ var label = i + 'x de ' + currencySymbol + amount;
737
+ } else {
738
+ var label = i + 'x de ' + currencySymbol + amount + " sem juros";
739
+ }
740
+
741
+ if (document.getElementById(field) != null) {
742
+ $(field).options[$(field).options.length] = new Option(label, i);
743
+ }
744
+
745
+ if (document.getElementById(field_new) != null) {
746
+ $(field_new).options[$(field_new).options.length] = new Option(label, i);
747
+ }
748
+ }
749
+ } else {
750
+ if (document.getElementById(field) != null) {
751
+ document.getElementById(field).options.length = 0;
752
+ }
753
+ }
754
+ }
755
+ },
756
+ onFailure: function (response) {
757
+ alert('Por favor tente novamente!');
758
+ }
759
+ });
760
+ }
761
+ }
762
+
763
+ function check_values() {
764
+ var method = $$('input[name="payment\\[method\\]"]:checked').first().value;
765
+ var type = $$('#mundipagg_type:enabled')[0].value;
766
+ var num = type[0].substring(0, 1);
767
+ var total = ($('baseGrandTotal').value).replace(',', '.');
768
+ var total_fields = 0.00;
769
+ var total_fields_new = 0.00;
770
+
771
+ for (var i = 1; i <= num; i++) {
772
+ if (document.getElementById(method + '_value_' + num + '_' + i) != null) {
773
+ var fieldv = ($(method + '_value_' + num + '_' + i).value).replace(',', '.');
774
+
775
+ total_fields = parseFloat(fieldv) + parseFloat(total_fields);
776
+ }
777
+
778
+ if (document.getElementById(method + '_new_value_' + num + '_' + i) != null) {
779
+ var fieldv_new = ($(method + '_new_value_' + num + '_' + i).value).replace(',', '.');
780
+
781
+ total_fields_new = parseFloat(fieldv_new) + parseFloat(total_fields_new);
782
+ }
783
+ }
784
+
785
+ if ((Math.abs(total - total_fields) < 0.000001) && (Math.abs(total - total_fields_new) < 0.000001)) {
786
+ return false;
787
+ }
788
+
789
+ return true;
790
+ }
791
+
792
+ function setCcType(field, code, num, c, issuer) {
793
+ $$('#' + code + '_' + num + '_' + c + '_cc_type')[0].value = issuer;
794
+ $(code + '_' + num + '_' + c + '_credito_instituicao_' + issuer).checked = true
795
+
796
+ field = $(code + '_' + num + '_' + c + '_credito_instituicao_' + issuer);
797
+
798
+ cc_cid(field, num, c)
799
+ }
800
+
801
+ function setTotalInterestHtml(field) {
802
+ var container = field.up(5);
803
+ var totalFieldElement = container.select('div')[0];
804
+ var totalFieldValue = parseFloat(totalFieldElement.innerHTML.replace(/\s/g, "").replace('<b>ValorTotal:</b>', '').replace('R$', '').replace('.', '').replace(',', '.'));
805
+ var containerSelects = container.select('select');
806
+ var template = '<div class="total_juros">' + Translator.translate('Total amount with interest: USD{%%%}') + '</div>';
807
+ var totalInterest = 0;
808
+
809
+ containerSelects.each(function (select) {
810
+ if (select.readAttribute('id').indexOf('credito_parcelamento') != -1) {
811
+ if (window.getComputedStyle(select.up(3)).getPropertyValue('display') == 'block') {
812
+ var selectedText = select.options[select.selectedIndex].text;
813
+ if (selectedText.indexOf('Total') != -1) {
814
+ realCurrentInterest = 0;
815
+ newTotalInterest = parseFloat(selectedText.substring(selectedText.indexOf('Total'), selectedText.length).replace('Total: R$', '').replace(')', '').replace(/\s/g, "").replace('.', '').replace(',', '.'));
816
+ if ($(select.readAttribute('id').replace('credito_parcelamento', 'value')) != undefined) {
817
+ currentValueField = parseFloat($(select.readAttribute('id').replace('credito_parcelamento', 'value')).value.replace('.', '').replace(',', '.'));
818
+ } else {
819
+ currentValueField = NaN;
820
+ }
821
+
822
+ if (!isNaN(currentValueField)) {
823
+ realCurrentInterest = parseFloat(newTotalInterest - currentValueField);
824
+ totalInterest = parseFloat(totalInterest + parseFloat(realCurrentInterest));
825
+ } else {
826
+ realCurrentInterest = parseFloat(newTotalInterest - totalFieldValue);
827
+ totalInterest = parseFloat(totalInterest + parseFloat(realCurrentInterest));
828
+ }
829
+ }
830
+ }
831
+ }
832
+ });
833
+
834
+ if (Object.keys(totalFieldElement.select('.total_juros')).length) {
835
+ totalFieldElement.select('.total_juros')[0].remove();
836
+ }
837
+
838
+ if (totalInterest > 0) {
839
+ var strNumber = parseFloat(totalFieldValue + totalInterest).toFixed(2);
840
+ while (strNumber.match(/^\d{4}/)) {
841
+ strNumber = strNumber.replace(/(\d)(\d{3}(\.|$))/, '$1.$2');
842
+ }
843
+ strNumber = strNumber.substring(0, parseInt(strNumber.length - 3)) + ',' + strNumber.substring(parseInt(strNumber.length - 2), strNumber.length);
844
+ totalFieldElement.insert(template.replace('{%%%}', strNumber));
845
+ }
846
+ }
847
+
848
+ function checkInstallments(field, url) {
849
+ if ($('onestepcheckout-form') == null) {
850
+ params = $('co-payment-form').serialize(true);
851
+ } else {
852
+ params = $('onestepcheckout-form').serialize(true);
853
+ }
854
+
855
+ if (window['mundipaggTotalInterest'] == undefined) {
856
+ window.mundipaggTotalInterest = 0;
857
+ }
858
+
859
+ setTotalInterestHtml(field);
860
+
861
+ new Ajax.Request(url + 'checkout/onepage/savePayment', {
862
+ method: 'post',
863
+ parameters: params,
864
+ onSuccess: function (response) {
865
+ if (200 == response.status) {
866
+ var result = eval("(" + response.responseText + ")");
867
+ }
868
+ },
869
+ onFailure: function (response) {
870
+ console.log('failed');
871
+ },
872
+ onComplete: function (response) {
873
+
874
+ }
875
+ });
876
+ }
package.xml CHANGED
@@ -1,7 +1,7 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Mundipagg_Integracao</name>
4
- <version>2.9.1</version>
5
  <stability>stable</stability>
6
  <license>MIT</license>
7
  <channel>community</channel>
@@ -12,11 +12,11 @@ Mundipagg payment gateway integration.</summary>
12
  <description>Com esta extens&#xE3;o voc&#xEA; poder&#xE1; integrar sua loja Magento com o gateway de pagamentos MundiPagg.&#xD;
13
  &#xD;
14
  With this extension you can process payments through brazilian payment gateway Mundipagg</description>
15
- <notes>Antifraud minimum value config renamed</notes>
16
  <authors><author><name>MundiPagg</name><user>MundiPagg</user><email>mundi@mundipagg.com</email></author></authors>
17
- <date>2016-10-24</date>
18
- <time>16:57:08</time>
19
- <contents><target name="magecommunity"><dir name="Uecommerce"><dir name="Mundipagg"><dir name="Block"><dir name="Adminhtml"><dir name="Form"><dir name="Field"><file name="Installments.php" hash="ec8343e197cb194d978400bbdf64d446"/></dir></dir><dir name="Sales"><dir name="Order"><dir name="Creditmemo"><file name="Totals.php" hash="2140a7836eaa57e03727433ccddf93d6"/></dir><dir name="Invoice"><file name="Totals.php" hash="ee304d9034ae0763e5db464f933b8c27"/><file name="View.php" hash="b0e3c170cd0184a5dfbe4fa7a486b471"/></dir><file name="Totals.php" hash="71b20a4c0022c14a5f7f8d008aabe1da"/></dir><dir name="Transactions"><dir name="Detail"><file name="Grid.php" hash="d67911c431587e4327eec95540cf548a"/></dir></dir></dir><dir name="System"><dir name="Config"><dir name="Form"><file name="Button.php" hash="aa40a974b89c92ea9652c42e093d16f9"/></dir></dir></dir><file name="Version.php" hash="e3a89823e48e7a526a3afe8ce8c0d0ee"/></dir><dir name="Checkout"><dir name="Onepage"><dir name="Payment"><file name="Methods.php" hash="c903e413c47e3dea87ec09d609543a27"/></dir></dir></dir><file name="Info.php" hash="c5743b8887caffc12ee2b502d7256101"/><file name="Parcelamento.php" hash="bbfad3557dd7c29e2a21a213cf915e0c"/><dir name="Sales"><dir name="Order"><dir name="Creditmemo"><file name="Totals.php" hash="be3e89b0e2f008fcc0293286d44df7da"/></dir><dir name="Invoice"><file name="Totals.php" hash="a39c41f45ef44b72d15cfd12fea4e9c6"/></dir><file name="Totals.php" hash="6f56aa360f48c715b30afd4e5cd4ddfa"/></dir></dir><dir name="Standard"><file name="Boleto.php" hash="4471015b8a82311f84e52e774460bf38"/><file name="Cancel.php" hash="095eaf31c6567fad440279aeb2994caa"/><file name="Debit.php" hash="c707d9572b6079457b9265cc09c920c6"/><file name="Fcancel.php" hash="4bc5b0fb68fb7fd11159788eafe958af"/><file name="Form.php" hash="0f7f97654c5e819ac178e5d888fae6ee"/><file name="Partial.php" hash="fb5877a8f6c56ac1d6fc48eb864d8e60"/><file name="Redirect.php" hash="70f576c8d64c25e3ce627f6c36b2ff41"/><file name="Success.php" hash="b1b0bef88ed350d703da0e314ffad565"/></dir></dir><dir name="Controller"><file name="Abstract.php" hash="91d5069c18069fcb2a0a436fb768a194"/></dir><dir name="Helper"><file name="Data.php" hash="e3aa0259de7e23ccd15023a73de630b0"/><file name="Installments.php" hash="d95d76587b1af78b0925bbbaf9fc9765"/><file name="Log.php" hash="3417e640be10aac6c3936a56364eb692"/><file name="Util.php" hash="e5c9d9329da5b00b476c352990e413c7"/><file name="Version.php" hash="00066d5bf31a7c49db004f2bd0d5c462"/></dir><dir name="Model"><dir name="Adminvalidators"><dir name="Antifraud"><file name="Minval.php" hash="40a49fef644e180b50c896e9dab34c76"/></dir><file name="Debug.php" hash="80bedd2d18fc0ad3888208d7255048cf"/></dir><file name="Api.php" hash="86b8193a8b6b4f37977b0a52b42de36b"/><file name="Boleto.php" hash="a7da1d58eb0fccb53eae51ba97d93dc5"/><file name="Cardonfile.php" hash="98395928a16313f8b4127e4e210cf953"/><file name="Creditcard.php" hash="007a43e7530ea5471b6a9aaa5405ce21"/><file name="Creditcardoneinstallment.php" hash="2e4222fd04dbc4f5ee116d4d7f4eae04"/><dir name="Customer"><file name="Session.php" hash="7f15498648de23cf4feb5143071ec260"/></dir><file name="Customers.php" hash="a779e96a969b83d1b38df351eb4670d0"/><file name="Debit.php" hash="8a3387bf74b1f03b9614fbdb64ab9dd5"/><dir name="Enum"><file name="BoletoTransactionStatusEnum.php" hash="3fed0a36bb76497b85c50016af34d47a"/><file name="CreditCardTransactionStatusEnum.php" hash="4546716f63e6df57061b222002157ccd"/><file name="OrderStatusEnum.php" hash="fd42020aab9d5507b5e0c26957cd1abb"/><file name="TransactionTypeEnum.php" hash="52fc4049a9f2b120ad3ed99e296268f9"/></dir><file name="Fivecreditcards.php" hash="6975e6170345bb3f20fde79ae40b81fe"/><file name="Fourcreditcards.php" hash="2da3d901173c19e53a96adb197b1533a"/><file name="Observer.php" hash="2295c195391a3d68fd8fd7c7c2dba032"/><file name="Offlineretry.php" hash="394849df4873908dd43d3c15f75dc9d0"/><dir name="Order"><dir name="Invoice"><file name="Interest.php" hash="6bba5e87bae1a7ee94a827819b2ea4ce"/></dir><file name="Payment.php" hash="b1ab4478ab967cb6fb04b380e609cf4d"/></dir><file name="Providervalidation.php" hash="4906944bae20e3f683d6e5c4ba5304e3"/><dir name="Quote"><dir name="Address"><file name="Interest.php" hash="93aa0189a8556597697dbb239dbf3be7"/></dir></dir><file name="Recurrency.php" hash="10744874b30361f54d18c4f7affee99f"/><dir name="Resource"><dir name="Cardonfile"><file name="Collection.php" hash="7b7d13bc6d7be8e5e1c5f945d59117f6"/></dir><file name="Cardonfile.php" hash="47d0107a9b1c3415aaf8784298361e84"/><dir name="Customers"><file name="Collection.php" hash="6caadd817abbcda527ba6d102585f2ff"/></dir><file name="Customers.php" hash="f50289a4c8362ddf7a79e4aa7c8a6387"/><dir name="Offlineretry"><file name="Collection.php" hash="80f0689c66a30110e68c2fdafb3014a8"/></dir><file name="Offlineretry.php" hash="08c804fd3b001f4f3ac19ebbcfca59fb"/><file name="Setup.php" hash="42bda31d8497e1b0983775e17f7325a5"/></dir><dir name="Source"><file name="Antifraud.php" hash="8362e0bb2209bbf904a7f9b2edd59cee"/><file name="Banks.php" hash="b5d456a807cdf750a6458144e955cf2c"/><file name="CctypeProductInstallments.php" hash="7837f6865c905ba8f5393d080ebc1b3d"/><file name="Cctypes.php" hash="b55eb988a6a09f24b1088f15644961d0"/><file name="Debit.php" hash="9366bc3b900cf96ad5d2bce7e8d93ba7"/><file name="Environment.php" hash="f22bf02692c02d3f8859601ccf9cf90c"/><file name="FControlEnvironment.php" hash="5159f6e4d86ee9d280285b7198fa01e9"/><file name="Frequency.php" hash="7864991042d0ec3fd5920d9047127b14"/><file name="Installments.php" hash="b04c05b92f7b8b5c025f23aad4457917"/><file name="PaymentAction.php" hash="c16639be23fd85c285f474922fd528a7"/><file name="PaymentMethods.php" hash="e12514ad00bf3fe3fb4e569b11da2c10"/></dir><file name="Standard.php" hash="291b8b602ef7cd16607769646cdd21e4"/><dir name="System"><dir name="Config"><dir name="Backend"><file name="Installments.php" hash="f0901bf05acd0b2c3fda41965f949583"/></dir></dir></dir><file name="Threecreditcards.php" hash="73fcdc4ef1dd38128b60454f90184ff5"/><file name="Twocreditcards.php" hash="c010f631d556a08d2d1aa65dc6b60703"/><file name="Urlvalidation.php" hash="e3ccd751eea54e282d30624192537cd8"/><file name=".DS_Store" hash="194577a7e20bdcc7afbb718f502c134c"/></dir><dir name="Test"><dir name="Selenium"><file name="Abstract.php" hash="caf0cd5ca47b13fb00be4230d1bb9132"/><file name="BoletoTest.php" hash="0718dc551376686dc6daaa3b57ddd1f9"/><dir name="CcTypes"><file name="CreditcardTest.php" hash="fde35369e57eb70f29f8defe1d7f06af"/><file name="CreditcardoneinstallmentTest.php" hash="cabcf9a3f56497e32679c1d2d063a6d7"/><file name="FivecreditcardsTest.php" hash="a903b89e20b9e754df7ed22dc9e8eecf"/><file name="FourcheditcardsTest.php" hash="3619a03b24af1a768cbc87be430b4323"/><file name="ThreecreditcardsTest.php" hash="d59c7b8a7de6320cff170e435fbe6e9e"/><file name="TwocreditcardsTest.php" hash="58db59f790aa7c65a324e6a552c2e05c"/></dir><file name="CcTypes.php" hash="fdb1cb980444a4cd35ace6543b9f335e"/><file name="DebitTest.php" hash="1409a8f2de15e13792dcba2099a887cc"/></dir></dir><dir name="controllers"><dir name="Adminhtml"><file name="IndexController.php" hash="e5a51c9660f704bcbfb302d34493a5a6"/></dir><file name="ClearsaleController.php" hash="bc06365f0d577d66228d9f0c3e471089"/><file name="FcontrolController.php" hash="1af534f1cdadbfdbe702aed12c7a2e1d"/><file name="StandardController.php" hash="d1e10eb258d4dc0fd43ff64d6e636385"/><file name="StoneController.php" hash="80c6f59a868ac82fc22bcf586bbecfdd"/></dir><dir name="etc"><file name="config.xml" hash="2e57b980952d143e3d6871cf4381c8aa"/><file name="jstranslator.xml" hash="8b1ea10d9b3072a795567dba6dae938c"/><file name="system.xml" hash="792d57b9363f91332bb6388994d132dc"/><file name="wsdl.xml" hash="a59b87019a8bdb03d97191e2d06be325"/><file name="xtest.xml" hash="b34ee3b6e37a890b73374b5ea3a1c40f"/></dir><dir name="sql"><dir name="mundipagg_setup"><file name="install-0.3.0.php" hash="ede73bb07d71fec55340c4249ff4a258"/><file name="mysql4-upgrade-0.3.0-0.3.5.php" hash="d3c200cce4a814feaa0858c0c8abd928"/><file name="mysql4-upgrade-0.3.5-0.4.0.php" hash="297f1b37b7703f7a0d621d227c8cbeb9"/><file name="mysql4-upgrade-0.3.5-1.0.1.php" hash="d22a0a81e392885433ca58dc196c2a86"/><file name="mysql4-upgrade-0.4.0-1.0.1.php" hash="297f1b37b7703f7a0d621d227c8cbeb9"/><file name="mysql4-upgrade-0.4.1-0.4.2.php" hash="4a2962a1eb974c75e153f48cc77f00d4"/><file name="mysql4-upgrade-0.4.1-1.0.1.php" hash="d22a0a81e392885433ca58dc196c2a86"/><file name="mysql4-upgrade-1.0.0-1.0.1.php" hash="297f1b37b7703f7a0d621d227c8cbeb9"/><file name="mysql4-upgrade-1.0.1-1.0.2.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.10-1.0.11.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.11-2.0.0.php" hash="83c95c6060bb8678be3b8944a6823fd9"/><file name="mysql4-upgrade-1.0.2-1.0.3.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.3-1.0.4.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.4-1.0.5.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.5-1.0.6.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.6-1.0.7.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.7-1.0.8.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.8-1.0.9.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.9-1.0.10.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.0-2.0.1.php" hash="a437df63647a52381ed5e056ccbb0cff"/><file name="mysql4-upgrade-2.0.0-2.1.0.php" hash="30dc2c3c763893d3bac6b9fde0c56477"/><file name="mysql4-upgrade-2.0.1-2.0.2.php" hash="4959ae51e69913d8ac642bc2ab848464"/><file name="mysql4-upgrade-2.0.2-2.0.3.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.3-2.0.4.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.4-2.0.5.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.5-2.0.6.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.6-2.0.7.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.7-2.0.8.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.8-2.0.9.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.9-2.1.0.php" hash="3488f42f3d9e6a57ce4176c0a7954171"/><file name="mysql4-upgrade-2.1.2-2.1.3.php" hash="7d7823cb555a32295d179a96e2bf987a"/><file name="mysql4-upgrade-2.5.7-2.5.8.php" hash="45c4f1fd5336b7ce578c672e8f1d57b0"/><file name="mysql4-upgrade-2.5.8-2.6.0.php" hash="bf06e3d6ab5fa0c89629385db4231006"/><file name="mysql4-upgrade-2.7.4-2.8.0.php" hash="c53fbd135b7735b7bbe90e5c4c11e5b2"/></dir></dir></dir></dir></target><target name="magedesign"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="layout"><file name="mundipagg.xml" hash="8d4357846320760a16aaaf4e1bca673d"/></dir><dir name="template"><dir name="mundipagg"><file name="boleto.phtml" hash="11cc5b254644727d6bdded8a834965c7"/><file name="form.phtml" hash="566e1838cab471ce41a1f74156e3b3bf"/><dir name="payment"><dir name="info"><file name="mundipagg.phtml" hash="bd5b27bef9e968794b50aa2543cd3d6a"/></dir></dir><dir name="system"><dir name="config"><file name="button.phtml" hash="6a7f6c88cf156d31d34a818ac37bd158"/></dir></dir></dir></dir></dir></dir></dir><dir name="frontend"><dir name="base"><dir name="default"><dir name="layout"><file name="mundipagg.xml" hash="0dc6cc39164b57626ccf7a429bbbf3d7"/></dir><dir name="template"><dir name="mundipagg"><dir name="antifraud"><file name="clearsale.phtml" hash="088a189dd94401f39c90ad0a1471994f"/><file name="fcontrol.phtml" hash="8fe2da3913bd18a20f35235533080ab8"/><file name="stone.phtml" hash="681ddf22694c725bb6e84e79681936fa"/></dir><file name="boleto.phtml" hash="dc31735a2753812d36e3080bf5b01ac2"/><file name="cancel.phtml" hash="540639b1ccd698397286f668bbf23746"/><file name="debit.phtml" hash="78f60f0227e99ff0c1d7dbf6bd5aa202"/><file name="extras.phtml" hash="f3eba84e971e890922141d90f6bdd53f"/><file name="fcancel.phtml" hash="9ce1d7634acf519669e21978b41aa277"/><file name="form.phtml" hash="faff82dad9768f016f81648aa8b9b800"/><file name="parcelamento.phtml" hash="56a89503637e5ad753b0d410f2f5c7ad"/><file name="partial.phtml" hash="65b07a14ff67c7413405117a6f95c2be"/><dir name="payment"><dir name="info"><file name="mundipagg.phtml" hash="c110a21db08013d38add1b79977350e4"/></dir></dir><file name="redirect.phtml" hash="a8a1123eab776934c64f57b4f9cfd517"/><file name="success.phtml" hash="7afd82f246fdf50f9a72ebb15086a2b6"/><file name="totals.phtml" hash="5a78aa3fe60d4b13bf8451f23bb9edd9"/></dir></dir></dir></dir><dir name="rwd"><dir name="default"><dir name="template"><dir name="mundipagg"><file name="debit.phtml" hash="4d2ae58447d3893499556ae068f800f8"/><file name="form.phtml" hash="dd83f04f33982e17fdea1713a3eb1b3a"/></dir></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Uecommerce_Mundipagg.xml" hash="b292eeabde8e2cd06db0c31aff54fd98"/></dir></target><target name="mage"><dir name="js"><dir name="uecommerce"><dir name="fcontrol"><file name="fingerprint-fcontrol.js" hash="33409e94c34847788fabbb3a5b038fd0"/><file name="fingerprint-sandbox.js" hash="5a55fed60e1501b2317ba445c656e46c"/><file name="hmlg-fcontrol-ed.min.js" hash="b8b6c945111b6edd7a90df2f5d3ff5cd"/><file name="script-fingerprint-fcontrol-prod.js" hash="702fd8905520a868b71ab1156297c969"/></dir><file name="jquery-3.1.0.min.js" hash="05e51b1db558320f1939f9789ccf5c8f"/><file name="mundipagg.js" hash="c887a21c210250da640bafce773e43ab"/><file name="recurrency.js" hash="6c0db9f70fea794eb55f1db3bd09b4aa"/></dir></dir></target><target name="mageskin"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="images"><dir name="mundipagg"><file name="ajax-loader.gif" hash="7b9776076d5fceef4993b55c9383dedd"/><file name="boleto.jpg" hash="237570c55c811b4b13f73ab92f28e599"/><file name="mundi-magento-admin-banner.png" hash="70ed79656a42a2b4c0291d0a6285fb6d"/></dir></dir></dir></dir></dir><dir name="frontend"><dir name="base"><dir name="default"><dir name="css"><file name="mundipagg.css" hash="90c32001f3a9b858c9506f5135c04972"/></dir><dir name="images"><dir name="mundipagg"><file name="001.png" hash="25d10d6fee7fc3e5dc48021a15de8fb0"/><file name="237.png" hash="cbea9caff342edd9b9b9509bbbbae6fb"/><file name="341.png" hash="3645161fc56322ec34ebfcc006390e5d"/><file name="AE.png" hash="40ea216476033961d50f452bf4bca4df"/><file name="DI.png" hash="0f4264379e7b8ba6b1a30a3d69240ae2"/><file name="EL.png" hash="ad180c308d285f73fc044121cb6aeac0"/><file name="HI.png" hash="c25430ddd8e441cc2fc3ef68219e7668"/><file name="MC.png" hash="836466c092121163320e9e6279f11f8b"/><file name="VBV.jpg" hash="1a7db765956829e80715a299b799f580"/><file name="VBV.png" hash="d6fb7de65fda842f03e2b9fc89d5e6aa"/><file name="VI.png" hash="cc0709d50773fa2815f7bfeb741a4219"/><file name="ajax-loader.gif" hash="7b9776076d5fceef4993b55c9383dedd"/><file name="boleto.jpg" hash="237570c55c811b4b13f73ab92f28e599"/><file name="cc_types.png" hash="fdae60f96ee668354161b5a865b8e7ef"/><file name="cielo_mastercard.png" hash="e2c2af12ea24f1b82490fdcc62fbb871"/><file name="cielo_visa.png" hash="d2f0c660714dc319b73c0dac9c9108d0"/></dir></dir></dir></dir><dir name="default"><dir name="default"><dir name="images"><dir name="mundipagg"><file name="EL.png" hash="ad180c308d285f73fc044121cb6aeac0"/><file name="HI.png" hash="c25430ddd8e441cc2fc3ef68219e7668"/><file name="ae.png" hash="40ea216476033961d50f452bf4bca4df"/><file name="boleto.jpg" hash="237570c55c811b4b13f73ab92f28e599"/><file name="cielo_mastercard.png" hash="e2c2af12ea24f1b82490fdcc62fbb871"/><file name="cielo_visa.png" hash="d2f0c660714dc319b73c0dac9c9108d0"/><file name="di.png" hash="0f4264379e7b8ba6b1a30a3d69240ae2"/><file name="mc.png" hash="836466c092121163320e9e6279f11f8b"/><file name="vi.png" hash="cc0709d50773fa2815f7bfeb741a4219"/></dir></dir></dir></dir></dir></target><target name="magelocale"><dir name="en_US"><file name="Uecommerce_Mundipagg.csv" hash="ae581dc54ea4ada4a9a3c9f4c51f09c7"/></dir><dir name="pt_BR"><file name="Uecommerce_Mundipagg.csv" hash="262089c81308d618c1da89db0ca1a4ce"/></dir></target></contents>
20
  <compatible/>
21
  <dependencies><required><php><min>5.4.0</min><max>7.0.9</max></php></required></dependencies>
22
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Mundipagg_Integracao</name>
4
+ <version>2.9.2</version>
5
  <stability>stable</stability>
6
  <license>MIT</license>
7
  <channel>community</channel>
12
  <description>Com esta extens&#xE3;o voc&#xEA; poder&#xE1; integrar sua loja Magento com o gateway de pagamentos MundiPagg.&#xD;
13
  &#xD;
14
  With this extension you can process payments through brazilian payment gateway Mundipagg</description>
15
+ <notes>Offline retry not authorized transactions fix</notes>
16
  <authors><author><name>MundiPagg</name><user>MundiPagg</user><email>mundi@mundipagg.com</email></author></authors>
17
+ <date>2016-10-27</date>
18
+ <time>13:50:44</time>
19
+ <contents><target name="magecommunity"><dir name="Uecommerce"><dir name="Mundipagg"><dir name="Block"><dir name="Adminhtml"><dir name="Form"><dir name="Field"><file name="Installments.php" hash="ec8343e197cb194d978400bbdf64d446"/></dir></dir><dir name="Sales"><dir name="Order"><dir name="Creditmemo"><file name="Totals.php" hash="2140a7836eaa57e03727433ccddf93d6"/></dir><dir name="Invoice"><file name="Totals.php" hash="ee304d9034ae0763e5db464f933b8c27"/><file name="View.php" hash="b0e3c170cd0184a5dfbe4fa7a486b471"/></dir><file name="Totals.php" hash="71b20a4c0022c14a5f7f8d008aabe1da"/></dir><dir name="Transactions"><dir name="Detail"><file name="Grid.php" hash="d67911c431587e4327eec95540cf548a"/></dir></dir></dir><dir name="System"><dir name="Config"><dir name="Form"><file name="Button.php" hash="aa40a974b89c92ea9652c42e093d16f9"/></dir></dir></dir><file name="Version.php" hash="e3a89823e48e7a526a3afe8ce8c0d0ee"/></dir><dir name="Checkout"><dir name="Onepage"><dir name="Payment"><file name="Methods.php" hash="c903e413c47e3dea87ec09d609543a27"/></dir></dir></dir><file name="Info.php" hash="c5743b8887caffc12ee2b502d7256101"/><file name="Parcelamento.php" hash="bbfad3557dd7c29e2a21a213cf915e0c"/><dir name="Sales"><dir name="Order"><dir name="Creditmemo"><file name="Totals.php" hash="be3e89b0e2f008fcc0293286d44df7da"/></dir><dir name="Invoice"><file name="Totals.php" hash="a39c41f45ef44b72d15cfd12fea4e9c6"/></dir><file name="Totals.php" hash="6f56aa360f48c715b30afd4e5cd4ddfa"/></dir></dir><dir name="Standard"><file name="Boleto.php" hash="4471015b8a82311f84e52e774460bf38"/><file name="Cancel.php" hash="095eaf31c6567fad440279aeb2994caa"/><file name="Debit.php" hash="c707d9572b6079457b9265cc09c920c6"/><file name="Fcancel.php" hash="4bc5b0fb68fb7fd11159788eafe958af"/><file name="Form.php" hash="0f7f97654c5e819ac178e5d888fae6ee"/><file name="Partial.php" hash="fb5877a8f6c56ac1d6fc48eb864d8e60"/><file name="Redirect.php" hash="70f576c8d64c25e3ce627f6c36b2ff41"/><file name="Success.php" hash="b1b0bef88ed350d703da0e314ffad565"/></dir></dir><dir name="Controller"><file name="Abstract.php" hash="91d5069c18069fcb2a0a436fb768a194"/></dir><dir name="Helper"><file name="Data.php" hash="e3aa0259de7e23ccd15023a73de630b0"/><file name="Installments.php" hash="d95d76587b1af78b0925bbbaf9fc9765"/><file name="Log.php" hash="3417e640be10aac6c3936a56364eb692"/><file name="Util.php" hash="e5c9d9329da5b00b476c352990e413c7"/><file name="Version.php" hash="00066d5bf31a7c49db004f2bd0d5c462"/></dir><dir name="Model"><dir name="Adminvalidators"><dir name="Antifraud"><file name="Minval.php" hash="ba762a2ff69c398eee6cea6e6c568875"/></dir><file name="Debug.php" hash="80bedd2d18fc0ad3888208d7255048cf"/><file name="Offlineretry.php" hash="3616008d44d7a3fb8f281749033e27de"/></dir><file name="Api.php" hash="2b4e556bb17fb4ed1fb0211cfb79379e"/><file name="Boleto.php" hash="a7da1d58eb0fccb53eae51ba97d93dc5"/><file name="Cardonfile.php" hash="98395928a16313f8b4127e4e210cf953"/><file name="Creditcard.php" hash="007a43e7530ea5471b6a9aaa5405ce21"/><file name="Creditcardoneinstallment.php" hash="2e4222fd04dbc4f5ee116d4d7f4eae04"/><dir name="Customer"><file name="Session.php" hash="7f15498648de23cf4feb5143071ec260"/></dir><file name="Customers.php" hash="a779e96a969b83d1b38df351eb4670d0"/><file name="Debit.php" hash="8a3387bf74b1f03b9614fbdb64ab9dd5"/><dir name="Enum"><file name="BoletoTransactionStatusEnum.php" hash="3fed0a36bb76497b85c50016af34d47a"/><file name="CreditCardTransactionStatusEnum.php" hash="4546716f63e6df57061b222002157ccd"/><file name="OrderStatusEnum.php" hash="fd42020aab9d5507b5e0c26957cd1abb"/><file name="TransactionTypeEnum.php" hash="52fc4049a9f2b120ad3ed99e296268f9"/></dir><file name="Fivecreditcards.php" hash="6975e6170345bb3f20fde79ae40b81fe"/><file name="Fourcreditcards.php" hash="2da3d901173c19e53a96adb197b1533a"/><file name="Observer.php" hash="91741820fde7657997d442bf3f7ced22"/><file name="Offlineretry.php" hash="394849df4873908dd43d3c15f75dc9d0"/><dir name="Order"><dir name="Invoice"><file name="Interest.php" hash="6bba5e87bae1a7ee94a827819b2ea4ce"/></dir><file name="Payment.php" hash="b1ab4478ab967cb6fb04b380e609cf4d"/></dir><file name="Providervalidation.php" hash="4906944bae20e3f683d6e5c4ba5304e3"/><dir name="Quote"><dir name="Address"><file name="Interest.php" hash="93aa0189a8556597697dbb239dbf3be7"/></dir></dir><file name="Recurrency.php" hash="10744874b30361f54d18c4f7affee99f"/><dir name="Resource"><dir name="Cardonfile"><file name="Collection.php" hash="7b7d13bc6d7be8e5e1c5f945d59117f6"/></dir><file name="Cardonfile.php" hash="47d0107a9b1c3415aaf8784298361e84"/><dir name="Customers"><file name="Collection.php" hash="6caadd817abbcda527ba6d102585f2ff"/></dir><file name="Customers.php" hash="f50289a4c8362ddf7a79e4aa7c8a6387"/><dir name="Offlineretry"><file name="Collection.php" hash="7b8635bc0fa4a0f1f13d33faf4ebf2da"/></dir><file name="Offlineretry.php" hash="d4aa60fb02dc11f399580cd429c211ba"/><file name="Setup.php" hash="42bda31d8497e1b0983775e17f7325a5"/></dir><dir name="Source"><file name="Antifraud.php" hash="8362e0bb2209bbf904a7f9b2edd59cee"/><file name="Banks.php" hash="b5d456a807cdf750a6458144e955cf2c"/><file name="CctypeProductInstallments.php" hash="7837f6865c905ba8f5393d080ebc1b3d"/><file name="Cctypes.php" hash="b55eb988a6a09f24b1088f15644961d0"/><file name="Debit.php" hash="9366bc3b900cf96ad5d2bce7e8d93ba7"/><file name="Environment.php" hash="f22bf02692c02d3f8859601ccf9cf90c"/><file name="FControlEnvironment.php" hash="5159f6e4d86ee9d280285b7198fa01e9"/><file name="Frequency.php" hash="7864991042d0ec3fd5920d9047127b14"/><file name="Installments.php" hash="b04c05b92f7b8b5c025f23aad4457917"/><file name="PaymentAction.php" hash="c16639be23fd85c285f474922fd528a7"/><file name="PaymentMethods.php" hash="e12514ad00bf3fe3fb4e569b11da2c10"/></dir><file name="Standard.php" hash="0dccbd299e68ec04b02ff43c398711fd"/><dir name="System"><dir name="Config"><dir name="Backend"><file name="Installments.php" hash="f0901bf05acd0b2c3fda41965f949583"/></dir></dir></dir><file name="Threecreditcards.php" hash="73fcdc4ef1dd38128b60454f90184ff5"/><file name="Twocreditcards.php" hash="c010f631d556a08d2d1aa65dc6b60703"/><file name="Urlvalidation.php" hash="e3ccd751eea54e282d30624192537cd8"/><file name=".DS_Store" hash="194577a7e20bdcc7afbb718f502c134c"/></dir><dir name="Test"><dir name="Selenium"><file name="Abstract.php" hash="caf0cd5ca47b13fb00be4230d1bb9132"/><file name="BoletoTest.php" hash="0718dc551376686dc6daaa3b57ddd1f9"/><dir name="CcTypes"><file name="CreditcardTest.php" hash="fde35369e57eb70f29f8defe1d7f06af"/><file name="CreditcardoneinstallmentTest.php" hash="cabcf9a3f56497e32679c1d2d063a6d7"/><file name="FivecreditcardsTest.php" hash="a903b89e20b9e754df7ed22dc9e8eecf"/><file name="FourcheditcardsTest.php" hash="3619a03b24af1a768cbc87be430b4323"/><file name="ThreecreditcardsTest.php" hash="d59c7b8a7de6320cff170e435fbe6e9e"/><file name="TwocreditcardsTest.php" hash="58db59f790aa7c65a324e6a552c2e05c"/></dir><file name="CcTypes.php" hash="fdb1cb980444a4cd35ace6543b9f335e"/><file name="DebitTest.php" hash="1409a8f2de15e13792dcba2099a887cc"/></dir></dir><dir name="controllers"><dir name="Adminhtml"><file name="IndexController.php" hash="e5a51c9660f704bcbfb302d34493a5a6"/></dir><file name="ClearsaleController.php" hash="bc06365f0d577d66228d9f0c3e471089"/><file name="FcontrolController.php" hash="1af534f1cdadbfdbe702aed12c7a2e1d"/><file name="StandardController.php" hash="d1e10eb258d4dc0fd43ff64d6e636385"/><file name="StoneController.php" hash="80c6f59a868ac82fc22bcf586bbecfdd"/></dir><dir name="data"><dir name="mundipagg_setup"><file name="data-upgrade-2.9.1-2.9.2.php" hash="1fcfc52de9420c8ba9db9b8f87f8801b"/></dir></dir><dir name="etc"><file name="config.xml" hash="690250e81b49e651c1171bce60f0fc11"/><file name="jstranslator.xml" hash="8b1ea10d9b3072a795567dba6dae938c"/><file name="system.xml" hash="6a02e1e20deeef778eaf971c5231fe45"/><file name="wsdl.xml" hash="a59b87019a8bdb03d97191e2d06be325"/><file name="xtest.xml" hash="b34ee3b6e37a890b73374b5ea3a1c40f"/></dir><dir name="sql"><dir name="mundipagg_setup"><file name="install-0.3.0.php" hash="ede73bb07d71fec55340c4249ff4a258"/><file name="mysql4-upgrade-0.3.0-0.3.5.php" hash="d3c200cce4a814feaa0858c0c8abd928"/><file name="mysql4-upgrade-0.3.5-0.4.0.php" hash="297f1b37b7703f7a0d621d227c8cbeb9"/><file name="mysql4-upgrade-0.3.5-1.0.1.php" hash="d22a0a81e392885433ca58dc196c2a86"/><file name="mysql4-upgrade-0.4.0-1.0.1.php" hash="297f1b37b7703f7a0d621d227c8cbeb9"/><file name="mysql4-upgrade-0.4.1-0.4.2.php" hash="4a2962a1eb974c75e153f48cc77f00d4"/><file name="mysql4-upgrade-0.4.1-1.0.1.php" hash="d22a0a81e392885433ca58dc196c2a86"/><file name="mysql4-upgrade-1.0.0-1.0.1.php" hash="297f1b37b7703f7a0d621d227c8cbeb9"/><file name="mysql4-upgrade-1.0.1-1.0.2.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.10-1.0.11.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.11-2.0.0.php" hash="83c95c6060bb8678be3b8944a6823fd9"/><file name="mysql4-upgrade-1.0.2-1.0.3.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.3-1.0.4.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.4-1.0.5.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.5-1.0.6.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.6-1.0.7.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.7-1.0.8.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.8-1.0.9.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-1.0.9-1.0.10.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.0-2.0.1.php" hash="a437df63647a52381ed5e056ccbb0cff"/><file name="mysql4-upgrade-2.0.0-2.1.0.php" hash="30dc2c3c763893d3bac6b9fde0c56477"/><file name="mysql4-upgrade-2.0.1-2.0.2.php" hash="4959ae51e69913d8ac642bc2ab848464"/><file name="mysql4-upgrade-2.0.2-2.0.3.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.3-2.0.4.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.4-2.0.5.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.5-2.0.6.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.6-2.0.7.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.7-2.0.8.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.8-2.0.9.php" hash="4c18b9eb1e0a08d858dde48280eed2c0"/><file name="mysql4-upgrade-2.0.9-2.1.0.php" hash="3488f42f3d9e6a57ce4176c0a7954171"/><file name="mysql4-upgrade-2.1.2-2.1.3.php" hash="7d7823cb555a32295d179a96e2bf987a"/><file name="mysql4-upgrade-2.5.7-2.5.8.php" hash="45c4f1fd5336b7ce578c672e8f1d57b0"/><file name="mysql4-upgrade-2.5.8-2.6.0.php" hash="bf06e3d6ab5fa0c89629385db4231006"/><file name="mysql4-upgrade-2.7.4-2.8.0.php" hash="c53fbd135b7735b7bbe90e5c4c11e5b2"/></dir></dir></dir></dir></target><target name="magedesign"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="layout"><file name="mundipagg.xml" hash="44efebb50716bbce7cd0cba0a3a68b25"/></dir><dir name="template"><dir name="mundipagg"><file name="boleto.phtml" hash="11cc5b254644727d6bdded8a834965c7"/><file name="form.phtml" hash="566e1838cab471ce41a1f74156e3b3bf"/><dir name="payment"><dir name="info"><file name="mundipagg.phtml" hash="bd5b27bef9e968794b50aa2543cd3d6a"/></dir></dir><dir name="system"><dir name="config"><file name="button.phtml" hash="6a7f6c88cf156d31d34a818ac37bd158"/></dir></dir></dir></dir></dir></dir></dir><dir name="frontend"><dir name="base"><dir name="default"><dir name="layout"><file name="mundipagg.xml" hash="0dc6cc39164b57626ccf7a429bbbf3d7"/></dir><dir name="template"><dir name="mundipagg"><dir name="antifraud"><file name="clearsale.phtml" hash="088a189dd94401f39c90ad0a1471994f"/><file name="fcontrol.phtml" hash="8fe2da3913bd18a20f35235533080ab8"/><file name="stone.phtml" hash="681ddf22694c725bb6e84e79681936fa"/></dir><file name="boleto.phtml" hash="dc31735a2753812d36e3080bf5b01ac2"/><file name="cancel.phtml" hash="540639b1ccd698397286f668bbf23746"/><file name="debit.phtml" hash="78f60f0227e99ff0c1d7dbf6bd5aa202"/><file name="extras.phtml" hash="f3eba84e971e890922141d90f6bdd53f"/><file name="fcancel.phtml" hash="9ce1d7634acf519669e21978b41aa277"/><file name="form.phtml" hash="faff82dad9768f016f81648aa8b9b800"/><file name="parcelamento.phtml" hash="56a89503637e5ad753b0d410f2f5c7ad"/><file name="partial.phtml" hash="65b07a14ff67c7413405117a6f95c2be"/><dir name="payment"><dir name="info"><file name="mundipagg.phtml" hash="c110a21db08013d38add1b79977350e4"/></dir></dir><file name="redirect.phtml" hash="a8a1123eab776934c64f57b4f9cfd517"/><file name="success.phtml" hash="7afd82f246fdf50f9a72ebb15086a2b6"/><file name="totals.phtml" hash="5a78aa3fe60d4b13bf8451f23bb9edd9"/></dir></dir></dir></dir><dir name="rwd"><dir name="default"><dir name="template"><dir name="mundipagg"><file name="debit.phtml" hash="4d2ae58447d3893499556ae068f800f8"/><file name="form.phtml" hash="dd83f04f33982e17fdea1713a3eb1b3a"/></dir></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Uecommerce_Mundipagg.xml" hash="b292eeabde8e2cd06db0c31aff54fd98"/></dir></target><target name="mage"><dir name="js"><dir name="uecommerce"><dir name="fcontrol"><file name="fingerprint-fcontrol.js" hash="33409e94c34847788fabbb3a5b038fd0"/><file name="fingerprint-sandbox.js" hash="5a55fed60e1501b2317ba445c656e46c"/><file name="hmlg-fcontrol-ed.min.js" hash="b8b6c945111b6edd7a90df2f5d3ff5cd"/><file name="script-fingerprint-fcontrol-prod.js" hash="702fd8905520a868b71ab1156297c969"/></dir><file name="jquery-3.1.0.min.js" hash="05e51b1db558320f1939f9789ccf5c8f"/><file name="mundipagg.js" hash="5122c13519345ae5e7c2b9166e4d3c2b"/><file name="recurrency.js" hash="6c0db9f70fea794eb55f1db3bd09b4aa"/></dir></dir></target><target name="mageskin"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="images"><dir name="mundipagg"><file name="ajax-loader.gif" hash="7b9776076d5fceef4993b55c9383dedd"/><file name="boleto.jpg" hash="237570c55c811b4b13f73ab92f28e599"/><file name="mundi-magento-admin-banner.png" hash="70ed79656a42a2b4c0291d0a6285fb6d"/></dir></dir></dir></dir></dir><dir name="frontend"><dir name="base"><dir name="default"><dir name="css"><file name="mundipagg.css" hash="90c32001f3a9b858c9506f5135c04972"/></dir><dir name="images"><dir name="mundipagg"><file name="001.png" hash="25d10d6fee7fc3e5dc48021a15de8fb0"/><file name="237.png" hash="cbea9caff342edd9b9b9509bbbbae6fb"/><file name="341.png" hash="3645161fc56322ec34ebfcc006390e5d"/><file name="AE.png" hash="40ea216476033961d50f452bf4bca4df"/><file name="DI.png" hash="0f4264379e7b8ba6b1a30a3d69240ae2"/><file name="EL.png" hash="ad180c308d285f73fc044121cb6aeac0"/><file name="HI.png" hash="c25430ddd8e441cc2fc3ef68219e7668"/><file name="MC.png" hash="836466c092121163320e9e6279f11f8b"/><file name="VBV.jpg" hash="1a7db765956829e80715a299b799f580"/><file name="VBV.png" hash="d6fb7de65fda842f03e2b9fc89d5e6aa"/><file name="VI.png" hash="cc0709d50773fa2815f7bfeb741a4219"/><file name="ajax-loader.gif" hash="7b9776076d5fceef4993b55c9383dedd"/><file name="boleto.jpg" hash="237570c55c811b4b13f73ab92f28e599"/><file name="cc_types.png" hash="fdae60f96ee668354161b5a865b8e7ef"/><file name="cielo_mastercard.png" hash="e2c2af12ea24f1b82490fdcc62fbb871"/><file name="cielo_visa.png" hash="d2f0c660714dc319b73c0dac9c9108d0"/></dir></dir></dir></dir><dir name="default"><dir name="default"><dir name="images"><dir name="mundipagg"><file name="EL.png" hash="ad180c308d285f73fc044121cb6aeac0"/><file name="HI.png" hash="c25430ddd8e441cc2fc3ef68219e7668"/><file name="ae.png" hash="40ea216476033961d50f452bf4bca4df"/><file name="boleto.jpg" hash="237570c55c811b4b13f73ab92f28e599"/><file name="cielo_mastercard.png" hash="e2c2af12ea24f1b82490fdcc62fbb871"/><file name="cielo_visa.png" hash="d2f0c660714dc319b73c0dac9c9108d0"/><file name="di.png" hash="0f4264379e7b8ba6b1a30a3d69240ae2"/><file name="mc.png" hash="836466c092121163320e9e6279f11f8b"/><file name="vi.png" hash="cc0709d50773fa2815f7bfeb741a4219"/></dir></dir></dir></dir></dir></target><target name="magelocale"><dir name="en_US"><file name="Uecommerce_Mundipagg.csv" hash="ae581dc54ea4ada4a9a3c9f4c51f09c7"/></dir><dir name="pt_BR"><file name="Uecommerce_Mundipagg.csv" hash="8ed4597b72f2ddfa8bcca49b65b9fefb"/></dir></target></contents>
20
  <compatible/>
21
  <dependencies><required><php><min>5.4.0</min><max>7.0.9</max></php></required></dependencies>
22
  </package>