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#x27; . $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
+