MercadoPagoTransparent - Version 2.4.0

Version Notes

- Added Devolutions and Cancellations
- Bug fixes
- Financing cost disable
- Added countries to custom ticket

Download this release

Release Info

Developer MercadoPago
Extension MercadoPagoTransparent
Version 2.4.0
Comparing to
See all releases


Code changes from version 2.3.1 to 2.4.0

Files changed (32) hide show
  1. app/code/community/MercadoPago/Core/Block/Customticket/Form.php +4 -7
  2. app/code/community/MercadoPago/Core/Block/Sales/Order/Totals/Finance/Cost.php +1 -1
  3. app/code/community/MercadoPago/Core/Helper/Data.php +6 -75
  4. app/code/community/MercadoPago/Core/Helper/Response.php +7 -0
  5. app/code/community/MercadoPago/Core/Helper/StatusUpdate.php +311 -0
  6. app/code/community/MercadoPago/Core/Model/Core.php +50 -110
  7. app/code/community/MercadoPago/Core/Model/Custom/Payment.php +2 -2
  8. app/code/community/MercadoPago/Core/Model/Observer.php +321 -31
  9. app/code/community/MercadoPago/Core/Model/Source/Order/Status.php +22 -0
  10. app/code/community/MercadoPago/Core/Model/Source/PaymentMethods.php +1 -1
  11. app/code/community/MercadoPago/Core/Model/Standard/Payment.php +0 -1
  12. app/code/community/MercadoPago/Core/controllers/NotificationsController.php +162 -171
  13. app/code/community/MercadoPago/Core/controllers/SuccessController.php +1 -0
  14. app/code/community/MercadoPago/Core/etc/config.xml +46 -3
  15. app/code/community/MercadoPago/Core/etc/system.xml +77 -0
  16. app/code/community/MercadoPago/MercadoEnvios/Model/Adminhtml/Attribute/Validation/Mapping.php +8 -6
  17. app/code/community/MercadoPago/MercadoEnvios/Model/Observer.php +10 -6
  18. app/code/community/MercadoPago/MercadoEnvios/etc/config.xml +7 -8
  19. app/code/community/MercadoPago/OneStepCheckout/etc/config.xml +1 -1
  20. app/design/frontend/base/default/template/mercadopago/custom/form.phtml +3 -1
  21. app/design/frontend/base/default/template/mercadopago/custom/success.phtml +0 -1
  22. app/design/frontend/base/default/template/mercadopago/custom_ticket/form.phtml +3 -0
  23. app/design/frontend/base/default/template/mercadopago/custom_ticket/success.phtml +0 -1
  24. app/design/frontend/base/default/template/mercadopago/standard/form.phtml +3 -1
  25. app/design/frontend/base/default/template/mercadopago/standard/success.phtml +0 -1
  26. app/locale/en_US/MercadoPago_Core.csv +23 -1
  27. app/locale/es_AR/MercadoPago_Core.csv +23 -1
  28. js/mercadopago/mercadopago.js +3 -1
  29. js/mercadopago/mercadopago_osc.js +3 -1
  30. lib/MercadoPago/Lib/Api.php +3 -2
  31. package.xml +8 -6
  32. skin/frontend/base/default/mercadopago/css/style.css +9 -0
app/code/community/MercadoPago/Core/Block/Customticket/Form.php CHANGED
@@ -27,14 +27,11 @@ class MercadoPago_Core_Block_Customticket_Form
27
28
public function getTicketsOptions()
29
{
30
- $payment_methods = Mage::getModel('mercadopago/core')->getPaymentMethods();
31
- $tickets = array();
32
33
- //percorre todos os payments methods
34
- foreach ($payment_methods['response'] as $pm) {
35
-
36
- //filtra por tickets
37
- if ($pm['payment_type_id'] == "ticket") {
38
$tickets[] = $pm;
39
}
40
}
27
28
public function getTicketsOptions()
29
{
30
+ $paymentMethods = Mage::getModel('mercadopago/core')->getPaymentMethods();
31
+ $tickets = [];
32
33
+ foreach ($paymentMethods['response'] as $pm) {
34
+ if ($pm['payment_type_id'] == 'ticket' || $pm['payment_type_id'] == 'atm') {
35
$tickets[] = $pm;
36
}
37
}
app/code/community/MercadoPago/Core/Block/Sales/Order/Totals/Finance/Cost.php CHANGED
@@ -13,7 +13,7 @@ class MercadoPago_Core_Block_Sales_Order_Totals_Finance_Cost
13
*/
14
public function initTotals()
15
{
16
- if ((float)$this->getSource()->getFinanceCostAmount() == 0) {
17
return $this;
18
}
19
$total = new Varien_Object(array(
13
*/
14
public function initTotals()
15
{
16
+ if ((float)$this->getSource()->getFinanceCostAmount() == 0 || !Mage::getStoreConfigFlag('payment/mercadopago/financing_cost')) {
17
return $this;
18
}
19
$total = new Varien_Object(array(
app/code/community/MercadoPago/Core/Helper/Data.php CHANGED
@@ -27,7 +27,6 @@ class MercadoPago_Core_Helper_Data
27
const PLATFORM_DESKTOP = 'Desktop';
28
const TYPE = 'magento';
29
30
- protected $_statusUpdatedFlag = false;
31
protected $_apiInstance;
32
33
protected $_website;
@@ -45,21 +44,6 @@ class MercadoPago_Core_Helper_Data
45
}
46
}
47
48
- public function isStatusUpdated()
49
- {
50
- return $this->_statusUpdatedFlag;
51
- }
52
-
53
- public function setStatusUpdated($notificationData)
54
- {
55
- $order = Mage::getModel('sales/order')->loadByIncrementId($notificationData["external_reference"]);
56
- $status = $notificationData['status'];
57
- $currentStatus = $order->getPayment()->getAdditionalInformation('status');
58
- if ($status == $currentStatus && $order->getState() === Mage_Sales_Model_Order::STATE_COMPLETE) {
59
- $this->_statusUpdatedFlag = true;
60
- }
61
- }
62
-
63
public function getApiInstance()
64
{
65
if (empty($this->_apiInstance)) {
@@ -122,65 +106,6 @@ class MercadoPago_Core_Helper_Data
122
return $accessToken;
123
}
124
125
- public function getStatusOrder($status)
126
- {
127
- switch ($status) {
128
- case 'approved': {
129
- $status = Mage::getStoreConfig('payment/mercadopago/order_status_approved');
130
- break;
131
- }
132
- case 'refunded': {
133
- $status = Mage::getStoreConfig('payment/mercadopago/order_status_refunded');
134
- break;
135
- }
136
- case 'in_mediation': {
137
- $status = Mage::getStoreConfig('payment/mercadopago/order_status_in_mediation');
138
- break;
139
- }
140
- case 'cancelled': {
141
- $status = Mage::getStoreConfig('payment/mercadopago/order_status_cancelled');
142
- break;
143
- }
144
- case 'rejected': {
145
- $status = Mage::getStoreConfig('payment/mercadopago/order_status_rejected');
146
- break;
147
- }
148
- case 'chargeback': {
149
- $status = Mage::getStoreConfig('payment/mercadopago/order_status_chargeback');
150
- break;
151
- }
152
- default: {
153
- $status = Mage::getStoreConfig('payment/mercadopago/order_status_in_process');
154
- }
155
- }
156
-
157
- return $status;
158
- }
159
-
160
- /**
161
- * Get the assigned state of an order status
162
- *
163
- * @param string $status
164
- */
165
- public function _getAssignedState($status)
166
- {
167
- $item = Mage::getResourceModel('sales/order_status_collection')
168
- ->joinStates()
169
- ->addFieldToFilter('main_table.status', $status);
170
-
171
- return array_pop($item->getItems())->getState();
172
- }
173
-
174
- public function getMessage($status, $payment)
175
- {
176
- $rawMessage = Mage::helper('mercadopago')->__(Mage::helper('mercadopago/statusOrderMessage')->getMessage($status));
177
- $rawMessage .= Mage::helper('mercadopago')->__('<br/> Payment id: %s', $payment['id']);
178
- $rawMessage .= Mage::helper('mercadopago')->__('<br/> Status: %s', $payment['status']);
179
- $rawMessage .= Mage::helper('mercadopago')->__('<br/> Status Detail: %s', $payment['status_detail']);
180
-
181
- return $rawMessage;
182
- }
183
-
184
public function setOrderSubtotals($data, $order)
185
{
186
if (isset($data['total_paid_amount'])) {
@@ -208,6 +133,12 @@ class MercadoPago_Core_Helper_Data
208
$balance = $balance - $transactionAmount - $shippingCost;
209
}
210
211
if (Zend_Locale_Math::round($balance, 4) > 0) {
212
$order->setFinanceCostAmount($balance);
213
$order->setBaseFinanceCostAmount($balance);
27
const PLATFORM_DESKTOP = 'Desktop';
28
const TYPE = 'magento';
29
30
protected $_apiInstance;
31
32
protected $_website;
44
}
45
}
46
47
public function getApiInstance()
48
{
49
if (empty($this->_apiInstance)) {
106
return $accessToken;
107
}
108
109
public function setOrderSubtotals($data, $order)
110
{
111
if (isset($data['total_paid_amount'])) {
133
$balance = $balance - $transactionAmount - $shippingCost;
134
}
135
136
+ if (!Mage::getStoreConfigFlag('payment/mercadopago/financing_cost')) {
137
+ $order->setGrandTotal($order->getGrandTotal() - $balance);
138
+ $order->setBaseGrandTotal($order->getBaseGrandTotal() - $balance);
139
+ return;
140
+ }
141
+
142
if (Zend_Locale_Math::round($balance, 4) > 0) {
143
$order->setFinanceCostAmount($balance);
144
$order->setBaseFinanceCostAmount($balance);
app/code/community/MercadoPago/Core/Helper/Response.php CHANGED
@@ -29,4 +29,11 @@ class MercadoPago_Core_Helper_Response
29
const HTTP_METHOD_NOT_ALLOWED = 405;
30
const HTTP_NOT_ACCEPTABLE = 406;
31
const HTTP_INTERNAL_ERROR = 500;
32
}
29
const HTTP_METHOD_NOT_ALLOWED = 405;
30
const HTTP_NOT_ACCEPTABLE = 406;
31
const HTTP_INTERNAL_ERROR = 500;
32
+
33
+
34
+ const INFO_MERCHANT_ORDER_NOT_FOUND = 'Merchant Order not found';
35
+ const INFO_STATUS_NOT_FINAL = 'Status not final';
36
+ const INFO_EXTERNAL_REFERENCE_NOT_FOUND = 'External reference not found';
37
+
38
+
39
}
app/code/community/MercadoPago/Core/Helper/StatusUpdate.php ADDED
@@ -0,0 +1,311 @@
1
+ <?php
2
+
3
+ class MercadoPago_Core_Helper_StatusUpdate
4
+ extends Mage_Payment_Helper_Data
5
+ {
6
+
7
+ protected $_statusUpdatedFlag = false;
8
+
9
+ /***
10
+ * @var Mage_Sales_Model_Order
11
+ */
12
+ protected $_order = false;
13
+
14
+ protected $_finalStatus = ['rejected', 'cancelled', 'refunded', 'charge_back'];
15
+ protected $_notFinalStatus = ['authorized', 'process', 'in_mediation'];
16
+
17
+ private $_rawMessage;
18
+
19
+ public function isStatusUpdated()
20
+ {
21
+ return $this->_statusUpdatedFlag;
22
+ }
23
+
24
+ public function setStatusUpdated($notificationData, $order)
25
+ {
26
+ $this->_order = $order;
27
+ $status = $notificationData['status'];
28
+ $statusDetail = $notificationData['status_detail'];
29
+ $currentStatus = $this->_order->getPayment()->getAdditionalInformation('status');
30
+ $currentStatusDetail = $this->_order->getPayment()->getAdditionalInformation('status_detail');
31
+ if ($status == $currentStatus && $statusDetail == $currentStatusDetail) {
32
+ $this->_statusUpdatedFlag = true;
33
+ }
34
+ }
35
+
36
+ protected function _updateStatus($status, $message, $statusDetail)
37
+ {
38
+ if ($this->_order->getState() !== Mage_Sales_Model_Order::STATE_COMPLETE) {
39
+ $statusOrder = $this->getStatusOrder($status, $statusDetail);
40
+
41
+ if (isset($statusOrder)) {
42
+ $this->_order->setState($this->_getAssignedState($statusOrder));
43
+ $this->_order->addStatusToHistory($statusOrder, $message, true);
44
+ $this->_order->sendOrderUpdateEmail(true, $message);
45
+ }
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Get the assigned state of an order status
51
+ *
52
+ * @param string $status
53
+ */
54
+ public function _getAssignedState($status)
55
+ {
56
+ $item = Mage::getResourceModel('sales/order_status_collection')
57
+ ->joinStates()
58
+ ->addFieldToFilter('main_table.status', $status);
59
+
60
+ return array_pop($item->getItems())->getState();
61
+ }
62
+
63
+ protected function _generateCreditMemo($payment)
64
+ {
65
+ if ($payment['amount_refunded'] == $payment['total_paid_amount']) {
66
+ $this->_createCreditmemo($payment);
67
+ $this->_order->setForcedCanCreditmemo(false);
68
+ $this->_order->setActionFlag('ship', false);
69
+ $this->_order->save();
70
+ } else {
71
+ $this->_createCreditmemo($payment);
72
+ }
73
+ }
74
+
75
+ protected function _createCreditmemo ($data) {
76
+ /**
77
+ * @var $creditmemo Mage_Sales_Model_Order_Creditmemo
78
+ */
79
+ $this->_order->setExternalRequest(true);
80
+ $serviceModel = Mage::getModel('sales/service_order', $this->_order);
81
+ $baseGrandTotal = $this->_order->getBaseGrandTotal();
82
+ $invoice = array_pop($this->_order->getInvoiceCollection()->setPageSize(1)->setCurPage(1)->load()->getItems());
83
+
84
+ $creditMemos = $this->_order->getCreditmemosCollection()->getItems();
85
+
86
+ $previousRefund = 0;
87
+ foreach ($creditMemos as $creditMemo) {
88
+ $previousRefund = $previousRefund + $creditMemo->getGrandTotal();
89
+ }
90
+
91
+ $amount = $data['amount_refunded'] - $previousRefund;
92
+ if ($amount > 0) {
93
+ if (count($creditMemos) == 0) {
94
+ $adjustment = array('adjustment_positive' => $amount);
95
+ } else {
96
+ $adjustment = array('adjustment_negative' => 0 - $amount);
97
+ }
98
+ $adjustment['qtys'] = -1;
99
+ $creditmemo = $serviceModel->prepareInvoiceCreditmemo($invoice, $adjustment);
100
+ if ($creditmemo) {
101
+ $totalRefunded = $invoice->getBaseTotalRefunded() + $creditmemo->getBaseGrandTotal();
102
+ $this->_order->setShouldCloseParentTransaction($invoice->getBaseGrandTotal() <= $totalRefunded);
103
+ }
104
+
105
+ if ($data['amount_refunded'] == $baseGrandTotal) {
106
+ $this->_order->setExternalType('total');
107
+ $this->_order->getPayment()->refund($creditmemo);
108
+ } else {
109
+ $this->_order->setExternalType('partial');
110
+ }
111
+ $creditmemo->refund();
112
+ Mage::getModel('core/resource_transaction')
113
+ ->addObject($creditmemo)
114
+ ->addObject($this->_order)
115
+ ->save();
116
+ }
117
+ }
118
+
119
+ public function update($payment, $message) {
120
+ $status = $payment['status'];
121
+ $statusDetail = $payment['status_detail'];
122
+
123
+ if ($status == 'approved') {
124
+ Mage::helper('mercadopago')->setOrderSubtotals($payment, $this->_order);
125
+ $this->_createInvoice($this->_order, $message);
126
+ //Associate card to customer
127
+ $additionalInfo = $this->_order->getPayment()->getAdditionalInformation();
128
+ if (isset($additionalInfo['token'])) {
129
+ Mage::getModel('mercadopago/custom_payment')->customerAndCards($additionalInfo['token'], $payment);
130
+ }
131
+ }
132
+
133
+ if (isset($payment['amount_refunded']) && $payment['amount_refunded'] > 0) {
134
+ $this->_generateCreditMemo($payment);
135
+ } elseif ($status == 'cancelled') {
136
+ Mage::register('mercadopago_cancellation', true);
137
+ $this->_order->cancel();
138
+ }
139
+ else {
140
+ //if state is not complete updates according to setting
141
+ $this->_updateStatus($status, $message, $statusDetail);
142
+ }
143
+ return $this->_order->save();
144
+ }
145
+
146
+ public function setStatusOrder($payment)
147
+ {
148
+ $helper = Mage::helper('mercadopago');
149
+
150
+ $status = $this->getStatus($payment);
151
+ $message = $this->getMessage($status, $payment);
152
+ if ($this->isStatusUpdated() && isset ($payment['amount_refunded']) && !($payment['amount_refunded'] > 0)) {
153
+ return ['body' => $message, 'code' => MercadoPago_Core_Helper_Response::HTTP_OK];
154
+ }
155
+
156
+ try {
157
+ $statusSave = $this->update($payment, $message);
158
+
159
+ $helper->log("Update order", 'mercadopago.log', $statusSave->getData());
160
+ $helper->log($message, 'mercadopago.log');
161
+
162
+ return ['body' => $message, 'code' => MercadoPago_Core_Helper_Response::HTTP_OK];
163
+ } catch (Exception $e) {
164
+ $helper->log("error in set order status: " . $e, 'mercadopago.log');
165
+
166
+ return ['body' => $e, 'code' => MercadoPago_Core_Helper_Response::HTTP_BAD_REQUEST];
167
+ }
168
+ }
169
+
170
+ public function getMessage($status, $payment)
171
+ {
172
+ if (!$this->_rawMessage) {
173
+ $rawMessage = Mage::helper('mercadopago')->__(Mage::helper('mercadopago/statusOrderMessage')->getMessage($status));
174
+ $rawMessage .= Mage::helper('mercadopago')->__('<br/> Payment id: %s', $payment['id']);
175
+ $rawMessage .= Mage::helper('mercadopago')->__('<br/> Status: %s', $payment['status']);
176
+ $rawMessage .= Mage::helper('mercadopago')->__('<br/> Status Detail: %s', $payment['status_detail']);
177
+ $this->_rawMessage = $rawMessage;
178
+ }
179
+
180
+ return $this->_rawMessage;
181
+ }
182
+
183
+ public function getStatus($payment)
184
+ {
185
+ $status = $payment['status'];
186
+ if (isset($payment['status_final'])) {
187
+ $status = $payment['status_final'];
188
+ }
189
+
190
+ return $status;
191
+ }
192
+
193
+
194
+ public function getStatusOrder($status, $statusDetail)
195
+ {
196
+ switch ($status) {
197
+ case 'approved': {
198
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_approved');
199
+
200
+ if ($statusDetail == 'partially_refunded' && $this->_order->canCreditMemo()) {
201
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_partially_refunded');
202
+ }
203
+ break;
204
+ }
205
+ case 'refunded': {
206
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_refunded');
207
+ break;
208
+ }
209
+ case 'in_mediation': {
210
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_in_mediation');
211
+ break;
212
+ }
213
+ case 'cancelled': {
214
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_cancelled');
215
+ break;
216
+ }
217
+ case 'rejected': {
218
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_rejected');
219
+ break;
220
+ }
221
+ case 'chargeback': {
222
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_chargeback');
223
+ break;
224
+ }
225
+ default: {
226
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_in_process');
227
+ }
228
+ }
229
+
230
+ return $status;
231
+ }
232
+
233
+ protected function _dateCompare($a, $b)
234
+ {
235
+ $t1 = strtotime($a['value']);
236
+ $t2 = strtotime($b['value']);
237
+
238
+ return $t2 - $t1;
239
+ }
240
+
241
+ /**
242
+ * @param $payments
243
+ * @param $status
244
+ *
245
+ * @return int
246
+ */
247
+ protected function _getLastPaymentIndex($payments, $status)
248
+ {
249
+ $dates = [];
250
+ foreach ($payments as $key => $payment) {
251
+ if (in_array($payment['status'], $status)) {
252
+ $dates[] = ['key' => $key, 'value' => $payment['last_modified']];
253
+ }
254
+ }
255
+ usort($dates, array(get_class($this), "_dateCompare"));
256
+ if ($dates) {
257
+ $lastModified = array_pop($dates);
258
+
259
+ return $lastModified['key'];
260
+ }
261
+
262
+ return 0;
263
+ }
264
+
265
+ /**
266
+ * Returns status that must be set to order, if a not final status exists
267
+ * then the last of this statuses is returned. Else the last of final statuses
268
+ * is returned
269
+ *
270
+ * @param $dataStatus
271
+ * @param $merchantOrder
272
+ *
273
+ * @return string
274
+ */
275
+ public function getStatusFinal($dataStatus, $merchantOrder)
276
+ {
277
+ if (isset($merchantOrder['paid_amount']) && $merchantOrder['total_amount'] == $merchantOrder['paid_amount']) {
278
+ return 'approved';
279
+ }
280
+ $payments = $merchantOrder['payments'];
281
+ $statuses = explode('|', $dataStatus);
282
+ foreach ($statuses as $status) {
283
+ $status = str_replace(' ', '', $status);
284
+ if (in_array($status, $this->_notFinalStatus)) {
285
+ $lastPaymentIndex = $this->_getLastPaymentIndex($payments, $this->_notFinalStatus);
286
+
287
+ return $payments[$lastPaymentIndex]['status'];
288
+ }
289
+ }
290
+
291
+ $lastPaymentIndex = $this->_getLastPaymentIndex($payments, $this->_finalStatus);
292
+
293
+ return $payments[$lastPaymentIndex]['status'];
294
+ }
295
+
296
+ protected function _createInvoice($order, $message)
297
+ {
298
+ if (!$order->hasInvoices()) {
299
+ $invoice = $order->prepareInvoice();
300
+ $invoice->register();
301
+ $invoice->pay();
302
+ Mage::getModel('core/resource_transaction')
303
+ ->addObject($invoice)
304
+ ->addObject($invoice->getOrder())
305
+ ->save();
306
+
307
+ $invoice->sendEmail(true, $message);
308
+ }
309
+ }
310
+
311
+ }
app/code/community/MercadoPago/Core/Model/Core.php CHANGED
@@ -101,7 +101,8 @@ class MercadoPago_Core_Model_Core
101
["field" => "payment_id", "title" => "Payment id (MercadoPago): %s"],
102
["field" => "status", "title" => "Payment Status: %s"],
103
["field" => "status_detail", "title" => "Payment Detail: %s"],
104
- ["field" => "activation_uri", "title" => "Generate Ticket"]
105
];
106
107
foreach ($fields as $field) {
@@ -446,133 +447,72 @@ class MercadoPago_Core_Model_Core
446
return $details_discount;
447
}
448
449
- protected function _createInvoice($order, $message)
450
- {
451
- if (!$order->hasInvoices()) {
452
- $invoice = $order->prepareInvoice();
453
- $invoice->register();
454
- $invoice->pay();
455
- Mage::getModel('core/resource_transaction')
456
- ->addObject($invoice)
457
- ->addObject($invoice->getOrder())
458
- ->save();
459
-
460
- $invoice->sendEmail(true, $message);
461
- }
462
- }
463
-
464
- public function setStatusOrder($payment)
465
{
466
$helper = Mage::helper('mercadopago');
467
- $order = Mage::getModel('sales/order')->loadByIncrementId($payment["external_reference"]);
468
- $status = $payment['status'];
469
470
- if (isset($payment['status_final'])) {
471
- $status = $payment['status_final'];
472
}
473
- $message = $helper->getMessage($status, $payment);
474
- if (Mage::helper('mercadopago')->isStatusUpdated()) {
475
- return ['text' => $message, 'code' => MercadoPago_Core_Helper_Response::HTTP_OK];
476
}
477
478
try {
479
- if ($status == 'approved') {
480
- Mage::helper('mercadopago')->setOrderSubtotals($payment, $order);
481
- $this->_createInvoice($order, $message);
482
- //Associate card to customer
483
- $additionalInfo = $order->getPayment()->getAdditionalInformation();
484
- if (isset($additionalInfo['token'])) {
485
- Mage::getModel('mercadopago/custom_payment')->customerAndCards($additionalInfo['token'], $payment);
486
}
487
488
- } elseif ($status == 'refunded' || $status == 'cancelled') {
489
- //generate credit memo and return items to stock according to setting
490
- $this->_generateCreditMemo($order, $payment);
491
}
492
- //if state is not complete updates according to setting
493
- $this->_updateStatus($order, $helper, $status, $message);
494
495
- $statusSave = $order->save();
496
- $helper->log("Update order", 'mercadopago.log', $statusSave->getData());
497
- $helper->log($message, 'mercadopago.log');
498
499
- return ['text' => $message, 'code' => MercadoPago_Core_Helper_Response::HTTP_OK];
500
} catch (Exception $e) {
501
- $helper->log("error in set order status: " . $e, 'mercadopago.log');
502
-
503
- return ['text' => $e, 'code' => MercadoPago_Core_Helper_Response::HTTP_BAD_REQUEST];
504
- }
505
- }
506
-
507
- protected function _updateStatus($order, $helper, $status, $message)
508
- {
509
- if ($order->getState() !== Mage_Sales_Model_Order::STATE_COMPLETE) {
510
- $statusOrder = $helper->getStatusOrder($status);
511
-
512
513
- $order->setState($helper->_getAssignedState($statusOrder));
514
- $order->addStatusToHistory($statusOrder, $message, true);
515
- $order->sendOrderUpdateEmail(true, $message);
516
}
517
}
518
519
- protected function _generateCreditMemo($order, $payment)
520
{
521
- if (isset($payment['amount_refunded']) && $payment['amount_refunded'] > 0 && $payment['amount_refunded'] == $payment['total_paid_amount']) {
522
- $order->getPayment()->registerRefundNotification($payment['amount_refunded']);
523
- $creditMemo = array_pop($order->getCreditmemosCollection()->setPageSize(1)->setCurPage(1)->load()->getItems());
524
- foreach ($creditMemo->getAllItems() as $creditMemoItem) {
525
- $creditMemoItem->setBackToStock(Mage::helper('cataloginventory')->isAutoReturnEnabled());
526
- }
527
- $creditMemo->save();
528
- $order->cancel();
529
- }
530
-
531
- }
532
-
533
- public function updateOrder($data)
534
- {
535
- Mage::helper('mercadopago')->log("Update Order", 'mercadopago-notification.log');
536
- if (!Mage::helper('mercadopago')->isStatusUpdated()) {
537
-
538
- try {
539
- $order = Mage::getModel('sales/order')->loadByIncrementId($data["external_reference"]);
540
-
541
- $paymentOrder = $order->getPayment();
542
-
543
- $additionalFields = [
544
- 'status',
545
- 'status_detail',
546
- 'payment_id',
547
- 'transaction_amount',
548
- 'cardholderName',
549
- 'installments',
550
- 'statement_descriptor',
551
- 'trunc_card',
552
- 'id'
553
- ];
554
-
555
- foreach ($additionalFields as $field) {
556
- if (isset($data[$field])) {
557
- $paymentOrder->setAdditionalInformation($field, $data[$field]);
558
- }
559
- }
560
-
561
- if (isset($data['payment_method_id'])) {
562
- $paymentOrder->setAdditionalInformation('payment_method', $data['payment_method_id']);
563
- }
564
-
565
- $paymentStatus = $paymentOrder->save();
566
- Mage::helper('mercadopago')->log("Update Payment", 'mercadopago.log', $paymentStatus->getData());
567
-
568
- $statusSave = $order->save();
569
- Mage::helper('mercadopago')->log("Update order", 'mercadopago.log', $statusSave->getData());
570
- } catch (Exception $e) {
571
- Mage::helper('mercadopago')->log("error in update order status: " . $e, 'mercadopago.log');
572
- $this->getResponse()->setBody($e);
573
-
574
- $this->getResponse()->setHttpResponseCode(MercadoPago_Core_Helper_Response::HTTP_BAD_REQUEST);
575
- }
576
}
577
}
578
101
["field" => "payment_id", "title" => "Payment id (MercadoPago): %s"],
102
["field" => "status", "title" => "Payment Status: %s"],
103
["field" => "status_detail", "title" => "Payment Detail: %s"],
104
+ ["field" => "activation_uri", "title" => "Generate Ticket"],
105
+ ["field" => "payment_id_detail", "title" => "Mercado Pago Payment Id: %s"],
106
];
107
108
foreach ($fields as $field) {
447
return $details_discount;
448
}
449
450
+ public function updateOrder($order = null, $data)
451
{
452
$helper = Mage::helper('mercadopago');
453
+ $statusHelper = Mage::helper('mercadopago/statusUpdate');
454
+ $helper->log('Update Order', 'mercadopago-notification.log');
455
456
+ if (!isset($data['external_reference'])) {
457
+ return;
458
}
459
+
460
+ if (!$order) {
461
+ $order = Mage::getModel('sales/order')->loadByIncrementId($data['external_reference']);
462
}
463
+ $paymentOrder = $order->getPayment();
464
+ $this->_saveTransaction($data, $paymentOrder);
465
466
+ if ($statusHelper->isStatusUpdated()) {
467
+ return;
468
+ }
469
try {
470
+ $additionalFields = [
471
+ 'status',
472
+ 'status_detail',
473
+ 'payment_id',
474
+ 'transaction_amount',
475
+ 'cardholderName',
476
+ 'installments',
477
+ 'statement_descriptor',
478
+ 'trunc_card',
479
+ 'id'
480
+ ];
481
+
482
+ foreach ($additionalFields as $field) {
483
+ if (isset($data[$field])) {
484
+ $paymentOrder->setAdditionalInformation($field, $data[$field]);
485
}
486
+ }
487
488
+ if (isset($data['payment_method_id'])) {
489
+ $paymentOrder->setAdditionalInformation('payment_method', $data['payment_method_id']);
490
}
491
492
+ $paymentStatus = $paymentOrder->save();
493
+ $helper->log('Update Payment', 'mercadopago.log', $paymentStatus->getData());
494
495
+ $statusSave = $order->save();
496
+ $helper->log('Update order', 'mercadopago.log', $statusSave->getData());
497
} catch (Exception $e) {
498
+ $helper->log('Error in update order status: ' . $e, 'mercadopago.log');
499
+ $this->getResponse()->setBody($e);
500
501
+ $this->getResponse()->setHttpResponseCode(MercadoPago_Core_Helper_Response::HTTP_BAD_REQUEST);
502
}
503
}
504
505
+ protected function _saveTransaction($data, $paymentOrder)
506
{
507
+ try {
508
+ $paymentOrder->setTransactionId($data['id']);
509
+ $paymentOrder->setParentTransactionId($paymentOrder->getTransactionId());
510
+ $transaction = $paymentOrder->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_PAYMENT, null, true, "");
511
+ $transaction->setAdditionalInformation('raw_details_info', $data);
512
+ $transaction->setIsClosed(true);
513
+ $transaction->save();
514
+ } catch (Exception $e) {
515
+ Mage::helper('mercadopago')->log('error in update order status: ' . $e, 'mercadopago.log');
516
}
517
}
518
app/code/community/MercadoPago/Core/Model/Custom/Payment.php CHANGED
@@ -48,9 +48,9 @@ class MercadoPago_Core_Model_Custom_Payment
48
$payment = $response['response'];
49
//set status
50
$this->getInfoInstance()->setAdditionalInformation('status', $payment['status']);
51
- $this->getInfoInstance()->setAdditionalInformation('status_detail', $payment['status_detail']);
52
$this->getInfoInstance()->setAdditionalInformation('payment_id_detail', $payment['id']);
53
- $stateObject->setState(Mage::helper('mercadopago')->_getAssignedState('pending_payment'));
54
$stateObject->setStatus('pending_payment');
55
$stateObject->setIsNotified(false);
56
48
$payment = $response['response'];
49
//set status
50
$this->getInfoInstance()->setAdditionalInformation('status', $payment['status']);
51
$this->getInfoInstance()->setAdditionalInformation('payment_id_detail', $payment['id']);
52
+ $this->getInfoInstance()->setAdditionalInformation('status_detail', $payment['status_detail']);
53
+ $stateObject->setState(Mage::helper('mercadopago/statusUpdate')->_getAssignedState('pending_payment'));
54
$stateObject->setStatus('pending_payment');
55
$stateObject->setIsNotified(false);
56
app/code/community/MercadoPago/Core/Model/Observer.php CHANGED
@@ -47,7 +47,7 @@ class MercadoPago_Core_Model_Observer
47
];
48
49
private $available_transparent_credit_cart = ['mla', 'mlb', 'mlm', 'mco', 'mlv', 'mlc', 'mpe'];
50
- private $available_transparent_ticket = ['mla', 'mlb', 'mlm'];
51
private $_website;
52
53
const LOG_FILE = 'mercadopago.log';
@@ -84,11 +84,11 @@ class MercadoPago_Core_Model_Observer
84
$country = $this->_website->getConfig('payment/mercadopago/country');
85
86
if (!in_array($country, $this->available_transparent_credit_cart)) {
87
- Mage::getConfig()->saveConfig('payment/mercadopago_custom/active', 0, 'websites', $this->_website->getId());
88
}
89
90
if (!in_array($country, $this->available_transparent_ticket)) {
91
- Mage::getConfig()->saveConfig('payment/mercadopago_customticket/active', 0, 'websites', $this->_website->getId());
92
}
93
}
94
@@ -111,7 +111,7 @@ class MercadoPago_Core_Model_Observer
111
Mage::helper('mercadopago')->log("Banner default need update...", self::LOG_FILE);
112
113
if ($defaultBanner != $currentBanner) {
114
- Mage::getConfig()->saveConfig('payment/' . $typeCheckout . '/banner_checkout', $defaultBanner, 'websites', $this->_website->getId());
115
116
Mage::helper('mercadopago')->log('payment/' . $typeCheckout . '/banner_checkout setted ' . $defaultBanner, self::LOG_FILE);
117
}
@@ -134,35 +134,26 @@ class MercadoPago_Core_Model_Observer
134
Mage::helper('mercadopago')->log("API Users response", self::LOG_FILE, $user);
135
136
if ($user['status'] == 200 && !in_array("test_user", $user['response']['tags'])) {
137
-
138
- switch ($user['response']['site_id']) {
139
- case 'MLA':
140
- $sponsorId = 186172525;
141
- break;
142
- case 'MLB':
143
- $sponsorId = 186175129;
144
- break;
145
- case 'MLM':
146
- $sponsorId = 186175064;
147
- break;
148
- case 'MCO':
149
- $sponsorId = 206959966;
150
- break;
151
- case 'MLC':
152
- $sponsorId = 206959756;
153
- break;
154
- case 'MLV':
155
- $sponsorId = 206960619;
156
- break;
157
- default:
158
- $sponsorId = "";
159
- break;
160
}
161
-
162
- Mage::helper('mercadopago')->log("Sponsor id setted", self::LOG_FILE, $sponsorId);
163
}
164
-
165
- Mage::getConfig()->saveConfig('payment/mercadopago/sponsor_id', $sponsorId, $this->_website->getId());
166
Mage::helper('mercadopago')->log("Sponsor saved", self::LOG_FILE, $sponsorId);
167
}
168
@@ -186,4 +177,303 @@ class MercadoPago_Core_Model_Observer
186
}
187
}
188
}
189
}
47
];
48
49
private $available_transparent_credit_cart = ['mla', 'mlb', 'mlm', 'mco', 'mlv', 'mlc', 'mpe'];
50
+ private $available_transparent_ticket = ['mla', 'mlb', 'mlm', 'mco', 'mlv', 'mlc', 'mpe'];
51
private $_website;
52
53
const LOG_FILE = 'mercadopago.log';
84
$country = $this->_website->getConfig('payment/mercadopago/country');
85
86
if (!in_array($country, $this->available_transparent_credit_cart)) {
87
+ $this->_saveWebsiteConfig('payment/mercadopago_custom/active', 0);
88
}
89
90
if (!in_array($country, $this->available_transparent_ticket)) {
91
+ $this->_saveWebsiteConfig('payment/mercadopago_customticket/active', 0);
92
}
93
}
94
111
Mage::helper('mercadopago')->log("Banner default need update...", self::LOG_FILE);
112
113
if ($defaultBanner != $currentBanner) {
114
+ $this->_saveWebsiteConfig('payment/' . $typeCheckout . '/banner_checkout', $defaultBanner);
115
116
Mage::helper('mercadopago')->log('payment/' . $typeCheckout . '/banner_checkout setted ' . $defaultBanner, self::LOG_FILE);
117
}
134
Mage::helper('mercadopago')->log("API Users response", self::LOG_FILE, $user);
135
136
if ($user['status'] == 200 && !in_array("test_user", $user['response']['tags'])) {
137
+ $sponsors = [
138
+ 'MLA' => 186172525,
139
+ 'MLB' => 186175129,
140
+ 'MLM' => 186175064,
141
+ 'MCO' => 206959966,
142
+ 'MLC' => 206959756,
143
+ 'MLV' => 206960619,
144
+ 'MPE' => 217178514,
145
+ ];
146
+ $countryCode = $user['response']['site_id'];
147
+
148
+ if (isset($sponsors[$countryCode])) {
149
+ $sponsorId = $sponsors[$countryCode];
150
+ } else {
151
+ $sponsorId = "";
152
}
153
+
154
+ Mage::helper('mercadopago')->log("Sponsor id set", self::LOG_FILE, $sponsorId);
155
}
156
+ $this->_saveWebsiteConfig('payment/mercadopago/sponsor_id', $sponsorId);
157
Mage::helper('mercadopago')->log("Sponsor saved", self::LOG_FILE, $sponsorId);
158
}
159
177
}
178
}
179
}
180
+
181
+ protected function _saveWebsiteConfig($path, $value)
182
+ {
183
+ if ($this->_website->getId() == 0) {
184
+ Mage::getConfig()->saveConfig($path, $value);
185
+ } else {
186
+ Mage::getConfig()->saveConfig($path, $value, 'websites', $this->_website->getId());
187
+ }
188
+
189
+ }
190
+
191
+ public function salesOrderBeforeCancel (Varien_Event_Observer $observer) {
192
+ $orderID = (int) $observer->getEvent()->getControllerAction()->getRequest()->getParam('order_id');
193
+ $order = Mage::getModel('sales/order')->load($orderID);
194
+ if ($order->getExternalRequest()) {
195
+ return;
196
+ }
197
+ $orderStatus = $order->getData('status');
198
+ $orderPaymentStatus = $order->getPayment()->getData('additional_information')['status'];
199
+
200
+ $paymentID = $order->getPayment()->getData('additional_information')['id'];
201
+ $paymentMethod = $order->getPayment()->getMethodInstance()->getCode();
202
+
203
+ $isValidBasicData = $this->checkCancelationBasicData ($paymentID, $paymentMethod);
204
+ $isValidaData = $this->checkCancelationData ($orderStatus, $orderPaymentStatus);
205
+
206
+ if ($isValidBasicData && $isValidaData) {
207
+ $clientId = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_CLIENT_ID);
208
+ $clientSecret = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_CLIENT_SECRET);
209
+
210
+ $mp = Mage::helper('mercadopago')->getApiInstance($clientId, $clientSecret);
211
+ $response = null;
212
+
213
+ $access_token = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_ACCESS_TOKEN);
214
+
215
+ if ($paymentMethod == 'mercadopago_standard') {
216
+ $response = $mp->cancel_payment($paymentID);
217
+ } else {
218
+ $data = [
219
+ "status" => 'cancelled',
220
+ ];
221
+ $response = $mp->put("/v1/payments/$paymentID?access_token=$access_token", $data);
222
+ }
223
+
224
+ if ($response['status'] == 200) {
225
+ Mage::register('mercadopago_cancellation', true);
226
+ $this->_getSession()->addSuccess(__('Cancellation made by Mercado Pago'));
227
+ } else {
228
+ $this->_getSession()->addError(__('Failed to make the cancellation by Mercado Pago'));
229
+ $this->_getSession()->addError($response['status'] . ' ' . $response['response']['message']);
230
+ $this->throwCancelationException();
231
+ }
232
+ }
233
+ }
234
+
235
+ protected function checkCancelationBasicData ($paymentID, $paymentMethod) {
236
+
237
+ if ($paymentID == null) {
238
+ return false;
239
+ }
240
+
241
+ if (!($paymentMethod == 'mercadopago_standard' || $paymentMethod == 'mercadopago_custom')) {
242
+ $this->_getSession()->addError(__('Order payment wasn\'t made by Mercado Pago. The cancellation will be made through Magento'));
243
+ return false;
244
+ }
245
+
246
+ $refundAvailable = Mage::getStoreConfig('payment/mercadopago/refund_available');
247
+ if (!$refundAvailable) {
248
+ $this->_getSession()->addError(__('Mercado Pago cancellations are disabled. The cancellation will be made through Magento'));
249
+ return false;
250
+ }
251
+
252
+ return true;
253
+ }
254
+
255
+ protected function checkCancelationData ($orderStatus, $orderPaymentStatus) {
256
+ $isValidaData = true;
257
+
258
+ if (!($orderStatus == 'processing' || $orderStatus == 'pending')) {
259
+ $this->_getSession()->addError(__('You can only make cancellation on orders whose status is Processing or Pending'));
260
+ $isValidaData = false;
261
+ }
262
+
263
+ if (!($orderPaymentStatus == 'pending' || $orderPaymentStatus == 'in_process' || $orderPaymentStatus == 'rejected' )) {
264
+ $this->_getSession()->addError(__('You can only make cancellations on orders whose payment status is Rejected, Pending o In Process'));
265
+ $isValidaData = false;
266
+ }
267
+
268
+ if (!$isValidaData) {
269
+ $this->throwCancelationException();
270
+ }
271
+
272
+ return $isValidaData;
273
+ }
274
+
275
+ protected function throwCancelationException () {
276
+ Mage::register('cancel_exception', true);
277
+ }
278
+
279
+ protected function _getSession() {
280
+ return Mage::getSingleton('adminhtml/session');
281
+ }
282
+
283
+ public function salesOrderAfterCancel (Varien_Event_Observer $observer) {
284
+ $mpCancellation = Mage::registry('mercadopago_cancellation');
285
+ if ($mpCancellation) {
286
+ $order = $observer->getData('order');
287
+ Mage::unregister('mercadopago_cancellation');
288
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_cancelled');
289
+ $order->setState($status, true);
290
+ }
291
+ }
292
+
293
+ public function salesOrderBeforeSave () {
294
+ $cancelException = Mage::registry('cancel_exception');
295
+ if ($cancelException) {
296
+ Mage::unregister('cancel_exception');
297
+ Mage::throwException(Mage::helper('mercadopago')->__('Mercado Pago - Cancellation not made'));
298
+ }
299
+ }
300
+
301
+ /**
302
+ * @param Varien_Event_Observer $observer
303
+ */
304
+
305
+ public function creditMemoRefundBeforeSave (Varien_Event_Observer $observer)
306
+ {
307
+ $creditMemo = $observer->getData('creditmemo');
308
+ $order = $creditMemo->getOrder();
309
+ if ($order->getExternalRequest()) {
310
+ return; // si la peticion de crear un credit memo viene de mercado pago, no hace falta mandar el request nuevamente
311
+ }
312
+
313
+ $orderStatus = $order->getData('status');
314
+ $orderPaymentStatus = $order->getPayment()->getData('additional_information')['status'];
315
+ $payment = $order->getPayment();
316
+ $paymentID = $order->getPayment()->getData('additional_information')['payment_id_detail'];
317
+ $paymentMethod = $order->getPayment()->getMethodInstance()->getCode();
318
+ $orderStatusHistory = $order->getAllStatusHistory();
319
+ $isCreditCardPayment = ($order->getPayment()->getData('additional_information')['installments'] != null ? true : false);
320
+
321
+ $paymentDate = null;
322
+ foreach ($orderStatusHistory as $status) {
323
+ if (strpos($status->getComment(), 'The payment was approved') !== false) {
324
+ $paymentDate = $status->getCreatedAt();
325
+ break;
326
+ }
327
+ }
328
+ $isValidBasicData = $this->checkRefundBasicData ($paymentMethod, $paymentDate);
329
+ $isValidaData = $this->checkRefundData ($isCreditCardPayment,
330
+ $orderStatus,
331
+ $orderPaymentStatus,
332
+ $paymentDate,
333
+ $order);
334
+
335
+ $isTotalRefund = $payment->getAmountPaid() == $payment->getAmountRefunded();
336
+ if ($isValidBasicData && $isValidaData) {
337
+ $this->sendRefundRequest($order, $creditMemo, $paymentMethod, $isTotalRefund, $paymentID);
338
+ }
339
+
340
+ }
341
+
342
+ protected function checkRefundBasicData ($paymentMethod, $paymentDate) {
343
+ $refundAvailable = Mage::getStoreConfig('payment/mercadopago/refund_available');
344
+
345
+ if ($paymentDate == null) {
346
+ $this->_getSession()->addError(__('No payment is recorded. You can\'t make a refund on a unpaid order'));
347
+ return false;
348
+ }
349
+
350
+ if (!($paymentMethod == 'mercadopago_standard' || $paymentMethod == 'mercadopago_custom')) {
351
+ $this->_getSession()->addError(__('Order payment wasn\'t made by Mercado Pago. The refund will be made through Magento'));
352
+ return false;
353
+ }
354
+
355
+ if (!$refundAvailable) {
356
+ $this->_getSession()->addError(__('Mercado Pago refunds are disabled. The refund will be made through Magento'));
357
+ return false;
358
+ }
359
+
360
+ return true;
361
+ }
362
+
363
+ protected function checkRefundData ($isCreditCardPayment,
364
+ $orderStatus,
365
+ $orderPaymentStatus,
366
+ $paymentDate,
367
+ $order)
368
+ {
369
+
370
+ $maxDays = (int) Mage::getStoreConfig('payment/mercadopago/maximum_days_refund');
371
+ $maxRefunds = (int) Mage::getStoreConfig('payment/mercadopago/maximum_partial_refunds');
372
+
373
+ $isValidaData = true;
374
+
375
+ if (!$isCreditCardPayment) {
376
+ $this->_getSession()->addError(__('You can only refund orders paid by credit card'));
377
+ $isValidaData = false;
378
+ }
379
+
380
+ if (!($orderStatus == 'processing' || $orderStatus == 'completed')) {
381
+ $this->_getSession()->addError(__('You can only make refunds on orders whose status is Processing or Completed'));
382
+ $isValidaData = false;
383
+ }
384
+
385
+ if (!($orderPaymentStatus == 'approved')) {
386
+ $this->_getSession()->addError(__('You can only make refunds on orders whose payment status Approved'));
387
+ $isValidaData = false;
388
+ }
389
+
390
+ if (!($this->daysSince($paymentDate) < $maxDays)) {
391
+ $this->_getSession()->addError(__('Refunds are accepted up to ') .
392
+ $maxDays . __(' days after payment approval. The current order exceeds the limit set'));
393
+ $isValidaData = false;
394
+ }
395
+
396
+ if (!(count($order->getCreditmemosCollection()->getItems()) < $maxRefunds)) {
397
+ $isValidaData = false;
398
+ $this->_getSession()->addError(__('You can only make ' . $maxRefunds . ' partial refunds on the same order'));
399
+ }
400
+
401
+ if (!$isValidaData) {
402
+ $this->throwRefundException();
403
+ }
404
+
405
+ return $isValidaData;
406
+ }
407
+
408
+ protected function sendRefundRequest ($order, $creditMemo, $paymentMethod, $isTotalRefund, $paymentID) {
409
+ $clientId = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_CLIENT_ID);
410
+ $clientSecret = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_CLIENT_SECRET);
411
+
412
+ $mp = Mage::helper('mercadopago')->getApiInstance($clientId, $clientSecret);
413
+ $response = null;
414
+ $amount = $creditMemo->getGrandTotal();
415
+ $access_token = Mage::getStoreConfig(MercadoPago_Core_Helper_Data::XML_PATH_ACCESS_TOKEN);
416
+ if ($paymentMethod == 'mercadopago_standard') {
417
+ if ($isTotalRefund) {
418
+ $response = $mp->refund_payment($paymentID);
419
+ $order->setMercadoPagoRefundType('total');
420
+ } else {
421
+ $order->setMercadoPagoRefundType('partial');
422
+ $metadata = [
423
+ "reason" => '',
424
+ "external_reference" => $order->getIncrementId(),
425
+ ];
426
+ $params = [
427
+ "amount" => $amount,
428
+ "metadata" => $metadata,
429
+ ];
430
+ $response = $mp->post("/collections/$paymentID/refunds?access_token=$access_token", $params);
431
+ }
432
+ } else {
433
+ if ($isTotalRefund) {
434
+ $response = $mp->post("/v1/payments/$paymentID/refunds?access_token=$access_token");
435
+ } else {
436
+ $params = [
437
+ "amount" => $amount,
438
+ ];
439
+ $response = $mp->post("/v1/payments/$paymentID/refunds?access_token=$access_token", $params);
440
+ }
441
+ }
442
+
443
+ if ($response['status'] == 201 || $response['status'] == 200) {
444
+ $order->setMercadoPagoRefund(true);
445
+ $this->_getSession()->addSuccess(__('Refund made by Mercado Pago'));
446
+ } else {
447
+ $this->_getSession()->addError(__('Failed to make the refund by Mercado Pago'));
448
+ $this->_getSession()->addError($response['status'] . ' ' . $response['response']['message']);
449
+ $this->throwRefundException();
450
+ }
451
+ }
452
+
453
+ protected function throwRefundException () {
454
+ Mage::throwException(Mage::helper('mercadopago')->__('Mercado Pago - Refund not made'));
455
+ }
456
+
457
+ private function daysSince($date)
458
+ {
459
+ $now = Mage::getModel('core/date')->timestamp(time());
460
+ $date = strtotime ($date);
461
+ return (abs($now - $date) / 86400);
462
+ }
463
+
464
+ public function creditMemoRefundAfterSave (Varien_Event_Observer $observer)
465
+ {
466
+ $creditMemo = $observer->getData('creditmemo');
467
+
468
+ $status = Mage::getStoreConfig('payment/mercadopago/order_status_refunded');
469
+
470
+ $order = $creditMemo->getOrder();
471
+ if ($order->getMercadoPagoRefund() || $order->getExternalRequest()) {
472
+ if ($order->getMercadoPagoRefundType() == 'partial' || $order->getExternalType() == 'partial') {
473
+ if ($order->getState() != $status) {
474
+ $order->setState($status, true);
475
+ }
476
+ }
477
+ }
478
+ }
479
}
app/code/community/MercadoPago/Core/Model/Source/Order/Status.php CHANGED
@@ -15,4 +15,26 @@ class MercadoPago_Core_Model_Source_Order_Status extends Mage_Adminhtml_Model_Sy
15
Mage_Sales_Model_Order::STATE_HOLDED,
16
);
17
18
}
15
Mage_Sales_Model_Order::STATE_HOLDED,
16
);
17
18
+ public function toOptionArray()
19
+ {
20
+ if ($this->_stateStatuses) {
21
+ $statuses = Mage::getSingleton('sales/order_config')->getStateStatuses($this->_stateStatuses);
22
+ }
23
+ else {
24
+ $statuses = Mage::getSingleton('sales/order_config')->getStatuses();
25
+ }
26
+ $options = array();
27
+ $options[] = array(
28
+ 'value' => '',
29
+ 'label' => Mage::helper('adminhtml')->__('-- No Status Change --')
30
+ );
31
+ foreach ($statuses as $code=>$label) {
32
+ $options[] = array(
33
+ 'value' => $code,
34
+ 'label' => $label
35
+ );
36
+ }
37
+ return $options;
38
+ }
39
+
40
}
app/code/community/MercadoPago/Core/Model/Source/PaymentMethods.php CHANGED
@@ -47,7 +47,7 @@ class MercadoPago_Core_Model_Source_PaymentMethods
47
48
$helper->log("API payment methods", 'mercadopago.log', $response);
49
50
- if (isset($response['error'])) {
51
return $methods;
52
}
53
47
48
$helper->log("API payment methods", 'mercadopago.log', $response);
49
50
+ if (isset($response['error']) || !isset($response['response'])) {
51
return $methods;
52
}
53
app/code/community/MercadoPago/Core/Model/Standard/Payment.php CHANGED
@@ -255,7 +255,6 @@ class MercadoPago_Core_Model_Standard_Payment
255
if (empty($paramsShipment)) {
256
$paramsShipment = $params->getData();
257
$paramsShipment['cost'] = (float)$order->getBaseShippingAmount();
258
- $paramsShipment['mode'] = 'custom';
259
}
260
$paramsShipment['receiver_address'] = $this->getReceiverAddress($shippingAddress);
261
return $paramsShipment;
255
if (empty($paramsShipment)) {
256
$paramsShipment = $params->getData();
257
$paramsShipment['cost'] = (float)$order->getBaseShippingAmount();
258
}
259
$paramsShipment['receiver_address'] = $this->getReceiverAddress($shippingAddress);
260
return $paramsShipment;
app/code/community/MercadoPago/Core/controllers/NotificationsController.php CHANGED
@@ -17,116 +17,173 @@
17
class MercadoPago_Core_NotificationsController
18
extends Mage_Core_Controller_Front_Action
19
{
20
- protected $_return = null;
21
- protected $_order = null;
22
- protected $_order_id = null;
23
- protected $_mpcartid = null;
24
- protected $_sendemail = false;
25
- protected $_hash = null;
26
- protected $_finalStatus = ['rejected', 'cancelled', 'refunded', 'charge_back'];
27
- protected $_notFinalStatus = ['authorized', 'process', 'in_mediation'];
28
29
const LOG_FILE = 'mercadopago-notification.log';
30
31
- protected function _getDataPayments($merchantOrder)
32
{
33
- $core = Mage::getModel('mercadopago/core');
34
- $data = array();
35
- foreach ($merchantOrder['payments'] as $payment) {
36
- $data = $this->_getFormattedPaymentData($payment['id'], $core, $data);
37
}
38
39
- return $data;
40
- }
41
42
- protected function _getFormattedPaymentData($paymentId, $core, $data = [])
43
- {
44
- $response = $core->getPayment($paymentId);
45
- $payment = $response['response']['collection'];
46
47
- return $this->formatArrayPayment($data, $payment);
48
}
49
50
- protected function _dateCompare($a, $b)
51
{
52
- $t1 = strtotime($a['value']);
53
- $t2 = strtotime($b['value']);
54
55
- return $t2 - $t1;
56
- }
57
58
- /**
59
- * @param $payments
60
- * @param $status
61
- *
62
- * @return int
63
- */
64
- protected function _getLastPaymentIndex($payments, $status)
65
- {
66
- $dates = [];
67
- foreach ($payments as $key => $payment) {
68
- if (in_array($payment['status'], $status)) {
69
- $dates[] = ['key' => $key, 'value' => $payment['last_modified']];
70
}
71
}
72
- usort($dates, array(get_class($this), "_dateCompare"));
73
- if ($dates) {
74
- $lastModified = array_pop($dates);
75
76
- return $lastModified['key'];
77
}
78
79
- return 0;
80
}
81
82
- /**
83
- * Returns status that must be set to order, if a not final status exists
84
- * then the last of this statuses is returned. Else the last of final statuses
85
- * is returned
86
- *
87
- * @param $dataStatus
88
- * @param $merchantOrder
89
- *
90
- * @return string
91
- */
92
- protected function getStatusFinal($dataStatus, $merchantOrder)
93
{
94
- if (isset($merchantOrder['paid_amount']) && $merchantOrder['total_amount'] == $merchantOrder['paid_amount']) {
95
- return 'approved';
96
- }
97
- $payments = $merchantOrder['payments'];
98
- $statuses = explode('|', $dataStatus);
99
- foreach ($statuses as $status) {
100
- $status = str_replace(' ', '', $status);
101
- if (in_array($status, $this->_notFinalStatus)) {
102
- $lastPaymentIndex = $this->_getLastPaymentIndex($payments, $this->_notFinalStatus);
103
-
104
- return $payments[$lastPaymentIndex]['status'];
105
- }
106
}
107
108
- $lastPaymentIndex = $this->_getLastPaymentIndex($payments, $this->_finalStatus);
109
110
- return $payments[$lastPaymentIndex]['status'];
111
}
112
113
- protected function _responseLog($helper)
114
{
115
- $helper->log("Http code", self::LOG_FILE, $this->getResponse()->getHttpResponseCode());
116
}
117
118
- protected function _shipmentExists($shipmentData, $merchantOrder)
119
{
120
- return (!empty($shipmentData) && !empty($merchantOrder));
121
}
122
123
- protected function _getShipmentsArray($merchantOrder)
124
{
125
- return (isset($merchantOrder['shipments'][0])) ? $merchantOrder['shipments'][0] : [];
126
}
127
128
- protected function _isValidResponse($response)
129
{
130
return ($response['status'] == 200 || $response['status'] == 201);
131
}
132
@@ -135,127 +192,61 @@ class MercadoPago_Core_NotificationsController
135
return (empty($p1) || empty($p2));
136
}
137
138
- public function standardAction()
139
{
140
- $request = $this->getRequest();
141
- //notification received
142
- $helper = Mage::helper('mercadopago');
143
- $shipmentData = '';
144
- $merchantOrder = '';
145
- $helper->log("Standard Received notification", self::LOG_FILE, $request->getParams());
146
- $core = Mage::getModel('mercadopago/core');
147
-
148
- $id = $request->getParam('id');
149
- $topic = $request->getParam('topic');
150
- if ($this->_emptyParams($id, $topic)) {
151
- $helper->log("Merchant Order not found", self::LOG_FILE, $request->getParams());
152
- $this->getResponse()->setBody("Merchant Order not found");
153
- $this->getResponse()->setHttpResponseCode(MercadoPago_Core_Helper_Response::HTTP_NOT_FOUND);
154
-
155
- return;
156
}
157
158
- if ($topic == 'merchant_order') {
159
- $response = $core->getMerchantOrder($id);
160
- $helper->log("Return merchant_order", self::LOG_FILE, $response);
161
- if (!$this->_isValidResponse($response)) {
162
- $this->_responseLog($helper);
163
-
164
- return;
165
- }
166
- $merchantOrder = $response['response'];
167
- if (count($merchantOrder['payments']) == 0) {
168
- $this->_responseLog($helper);
169
-
170
- return;
171
- }
172
- $data = $this->_getDataPayments($merchantOrder);
173
- $statusFinal = $this->getStatusFinal($data['status'], $merchantOrder);
174
- $shipmentData = $this->_getShipmentsArray($merchantOrder);
175
- } elseif ($topic == 'payment') {
176
- $data = $this->_getFormattedPaymentData($id, $core);
177
- $statusFinal = $data['status'];
178
- } else {
179
- $this->_responseLog($helper);
180
181
- return;
182
- }
183
184
- $helper->log("Update Order", self::LOG_FILE);
185
- $helper->setStatusUpdated($data);
186
- $core->updateOrder($data);
187
- if ($this->_shipmentExists($shipmentData, $merchantOrder)) {
188
Mage::dispatchEvent('mercadopago_standard_notification_before_set_status',
189
- array('shipmentData' => $shipmentData,
190
- 'orderId' => $merchantOrder['external_reference'])
191
);
192
}
193
- if ($statusFinal != false) {
194
- $data['status_final'] = $statusFinal;
195
- $helper->log("Received Payment data", self::LOG_FILE, $data);
196
- $setStatusResponse = $core->setStatusOrder($data);
197
- $this->getResponse()->setBody($setStatusResponse['text']);
198
- $this->getResponse()->setHttpResponseCode($setStatusResponse['code']);
199
- } else {
200
- $this->getResponse()->setBody("Status not final");
201
- $this->getResponse()->setHttpResponseCode(MercadoPago_Core_Helper_Response::HTTP_OK);
202
- }
203
204
- if ($this->_shipmentExists($shipmentData, $merchantOrder)) {
205
Mage::dispatchEvent('mercadopago_standard_notification_received',
206
- array('payment' => $data,
207
- 'merchant_order' => $merchantOrder)
208
);
209
}
210
-
211
-
212
- $this->_responseLog($helper);
213
}
214
215
- public function customAction()
216
{
217
- $request = $this->getRequest();
218
- Mage::helper('mercadopago')->log("Custom Received notification", self::LOG_FILE, $request->getParams());
219
-
220
- $core = Mage::getModel('mercadopago/core');
221
-
222
- $dataId = $request->getParam('data_id');
223
- $type = $request->getParam('type');
224
- if (!empty($dataId) && $type == 'payment') {
225
- $response = $core->getPaymentV1($dataId);
226
- Mage::helper('mercadopago')->log("Return payment", self::LOG_FILE, $response);
227
-
228
- if ($response['status'] == 200 || $response['status'] == 201) {
229
- $payment = $response['response'];
230
-
231
- $payment = Mage::helper('mercadopago')->setPayerInfo($payment);
232
-
233
- Mage::helper('mercadopago')->log("Update Order", self::LOG_FILE);
234
- Mage::helper('mercadopago')->setStatusUpdated($payment);
235
- $core->updateOrder($payment);
236
- $setStatusResponse = $core->setStatusOrder($payment);
237
- $this->getResponse()->setBody($setStatusResponse['text']);
238
- $this->getResponse()->setHttpResponseCode($setStatusResponse['code']);
239
- Mage::helper('mercadopago')->log("Http code", self::LOG_FILE, $this->getResponse()->getHttpResponseCode());
240
-
241
- return;
242
- }
243
}
244
245
- Mage::helper('mercadopago')->log("Payment not found", self::LOG_FILE, $request->getParams());
246
- $this->getResponse()->getBody("Payment not found");
247
- $this->getResponse()->setHttpResponseCode(MercadoPago_Core_Helper_Response::HTTP_NOT_FOUND);
248
- Mage::helper('mercadopago')->log("Http code", self::LOG_FILE, $this->getResponse()->getHttpResponseCode());
249
}
250
251
public function formatArrayPayment($data, $payment)
252
{
253
Mage::helper('mercadopago')->log("Format Array", self::LOG_FILE);
254
255
- $fields = array(
256
"status",
257
"status_detail",
258
- "id",
259
"payment_method_id",
260
"transaction_amount",
261
"total_paid_amount",
@@ -263,7 +254,7 @@ class MercadoPago_Core_NotificationsController
263
"installments",
264
"shipping_cost",
265
"amount_refunded",
266
- );
267
268
foreach ($fields as $field) {
269
if (isset($payment[$field])) {
17
class MercadoPago_Core_NotificationsController
18
extends Mage_Core_Controller_Front_Action
19
{
20
+
21
+ protected $_requestData = [];
22
+ protected $_merchantOrder = [];
23
+ protected $_paymentData = [];
24
+ protected $_core;
25
+ protected $_helper;
26
+ protected $_statusHelper;
27
+ protected $_order;
28
+ protected $_shipmentData;
29
+ protected $_statusFinal;
30
31
const LOG_FILE = 'mercadopago-notification.log';
32
33
+
34
+ public function standardAction()
35
{
36
+ $this->_requestData = $this->getRequest()->getParams();
37
+ //notification received
38
+ $this->_helper = Mage::helper('mercadopago');
39
+ $this->_core = Mage::getModel('mercadopago/core');
40
+ $this->_statusHelper = Mage::helper('mercadopago/statusUpdate');
41
+ $this->_shipmentData = '';
42
+
43
+ $this->_helper->log('Standard Received notification', self::LOG_FILE, $this->_requestData);
44
+ if ($this->_emptyParams($this->_getRequestData('id'), $this->_getRequestData('topic'))) {
45
+
46
+ return;
47
}
48
+ switch ($this->_getRequestData('topic')) {
49
+ case 'merchant_order':
50
+ if (!$this->_handleMerchantOrder()) {
51
+ return;
52
+ }
53
+ break;
54
+ case 'payment':
55
+ $this->_paymentData = $this->_getFormattedPaymentData($this->_getRequestData('id'));
56
+ $this->_statusFinal = $this->_paymentData['status'];
57
+ break;
58
+ default:
59
+ $this->_responseLog();
60
61
+ return;
62
+ }
63
+ $this->_order = Mage::getModel('sales/order')->loadByIncrementId($this->_paymentData["external_reference"]);
64
+ if (!$this->_orderExists()) {
65
+ return;
66
+ }
67
68
+ $this->_helper->log('Update Order', self::LOG_FILE);
69
+ $this->_statusHelper->setStatusUpdated($this->_paymentData, $this->_order);
70
+ $this->_core->updateOrder($this->_order, $this->_paymentData);
71
+ $this->_dispatchBeforeSetEvent();
72
73
+ if ($this->_statusFinal != false) {
74
+ $this->_paymentData['status_final'] = $this->_statusFinal;
75
+ $this->_helper->log('Received Payment data', self::LOG_FILE, $this->_paymentData);
76
+ $setStatusResponse = $this->_statusHelper->setStatusOrder($this->_paymentData);
77
+ $this->_setResponse($setStatusResponse['body'], $setStatusResponse['code']);
78
+ } else {
79
+ $this->_setResponse(MercadoPago_Core_Helper_Response::INFO_STATUS_NOT_FINAL, MercadoPago_Core_Helper_Response::HTTP_OK);
80
+ }
81
+
82
+ $this->_dispatchNotificationEvent();
83
+ $this->_responseLog();
84
}
85
86
+ public function customAction()
87
{
88
+ $request = $this->getRequest();
89
+ $this->_helper = Mage::helper('mercadopago');
90
+ $this->_core = Mage::getModel('mercadopago/core');
91
+ $this->_statusHelper = Mage::helper('mercadopago/statusUpdate');
92
+ $this->_helper->log('Custom Received notification', self::LOG_FILE, $request->getParams());
93
+ $dataId = $request->getParam('data_id');
94
+ $type = $request->getParam('type');
95
+ if (!empty($dataId) && $type == 'payment') {
96
+ $response = $this->_core->getPaymentV1($dataId);
97
+ $this->_helper->log('Return payment', self::LOG_FILE, $response);
98
99
+ if ($this->_isValidResponse($response)) {
100
+ $payment = $response['response'];
101
102
+ $payment = $this->_helper->setPayerInfo($payment);
103
+ $this->_order = Mage::getModel('sales/order')->loadByIncrementId($payment['external_reference']);
104
+ if (!$this->_orderExists()) {
105
+ return;
106
+ }
107
+ $this->_helper->log('Update Order', self::LOG_FILE);
108
+ $this->_statusHelper->setStatusUpdated($payment, $this->_order);
109
+ $this->_core->updateOrder($this->_order, $payment);
110
+ $setStatusResponse = $this->_statusHelper->setStatusOrder($payment);
111
+ $this->_setResponse($setStatusResponse['body'], $setStatusResponse['code']);
112
+ $this->_helper->log('Http code', self::LOG_FILE, $this->getResponse()->getHttpResponseCode());
113
+
114
+ return;
115
}
116
}
117
118
+ $this->_helper->log('Payment not found', self::LOG_FILE, $request->getParams());
119
+ $this->_setResponse('Payment not found', MercadoPago_Core_Helper_Response::HTTP_NOT_FOUND);
120
+ $this->_helper->log('Http code', self::LOG_FILE, $this->getResponse()->getHttpResponseCode());
121
+ }
122
+
123
+ protected function _handleMerchantOrder()
124
+ {
125
+ $merchantOrder = $this->_core->getMerchantOrder($this->_getRequestData('id'));
126
+ $this->_helper->log('Return merchant_order', self::LOG_FILE, $merchantOrder);
127
+ if (!$this->_isValidMerchantOrder($merchantOrder)) {
128
+ $this->_helper->log(MercadoPago_Core_Helper_Response::INFO_MERCHANT_ORDER_NOT_FOUND, self::LOG_FILE, $this->_requestData);
129
+ $this->_setResponse(MercadoPago_Core_Helper_Response::INFO_MERCHANT_ORDER_NOT_FOUND, MercadoPago_Core_Helper_Response::HTTP_NOT_FOUND);
130
+
131
+ return false;
132
}
133
134
+ $this->_paymentData = $this->_getDataPayments();
135
+ $this->_statusFinal = $this->_statusHelper->getStatusFinal($this->_paymentData['status'], $this->_merchantOrder);
136
+ $this->_shipmentData = $this->_getShipmentsArray();
137
+
138
+ return true;
139
}
140
141
+ protected function _getDataPayments()
142
{
143
+ $data = array();
144
+ foreach ($this->_merchantOrder['payments'] as $payment) {
145
+ $data = $this->_getFormattedPaymentData($payment['id'], $data);
146
}
147
148
+ return $data;
149
+ }
150
+
151
+ protected function _getFormattedPaymentData($paymentId, $data = [])
152
+ {
153
+ $response = $this->_core->getPayment($paymentId);
154
+ $payment = $response['response']['collection'];
155
156
+ return $this->formatArrayPayment($data, $payment);
157
}
158
159
+ protected function _responseLog()
160
{
161
+ $this->_helper->log("Http code", self::LOG_FILE, $this->getResponse()->getHttpResponseCode());
162
}
163
164
+ protected function _shipmentExists($shipmentData)
165
{
166
+ return (!empty($shipmentData) && !empty($this->merchantOrder));
167
}
168
169
+ protected function _getShipmentsArray()
170
{
171
+ return (isset($this->_merchantOrder['shipments'][0])) ? $this->_merchantOrder['shipments'][0] : [];
172
}
173
174
+ protected function _isValidMerchantOrder($merchantOrder)
175
{
176
+ $this->_merchantOrder = $merchantOrder['response'];
177
+ if ($this->_isValidResponse($merchantOrder) && count($this->_merchantOrder['payments']) > 0) {
178
+ $this->_responseLog();
179
+
180
+ return true;
181
+ }
182
+
183
+ return false;
184
+ }
185
+
186
+ protected function _isValidResponse($response) {
187
return ($response['status'] == 200 || $response['status'] == 201);
188
}
189
192
return (empty($p1) || empty($p2));
193
}
194
195
+ protected function _orderExists()
196
{
197
+ if ($this->_order->getId()) {
198
+ return true;
199
}
200
+ $this->_helper->log(MercadoPago_Core_Helper_Response::INFO_EXTERNAL_REFERENCE_NOT_FOUND, self::LOG_FILE, $this->_requestData);
201
+ $this->_setResponse(MercadoPago_Core_Helper_Response::INFO_EXTERNAL_REFERENCE_NOT_FOUND, MercadoPago_Core_Helper_Response::HTTP_NOT_FOUND);
202
203
+ return false;
204
+ }
205
206
+ protected function _setResponse($body, $code)
207
+ {
208
+ $this->getResponse()->setBody($body);
209
+ $this->getResponse()->setHttpResponseCode($code);
210
+ }
211
212
+ protected function _dispatchBeforeSetEvent()
213
+ {
214
+ if ($this->_shipmentExists($this->_shipmentData)) {
215
Mage::dispatchEvent('mercadopago_standard_notification_before_set_status',
216
+ ['shipmentData' => $this->_shipmentData,
217
+ 'orderId' => $this->_merchantOrder['external_reference']]
218
);
219
}
220
+ }
221
222
+ protected function _dispatchNotificationEvent()
223
+ {
224
+ if ($this->_shipmentExists($this->_shipmentData)) {
225
Mage::dispatchEvent('mercadopago_standard_notification_received',
226
+ ['payment' => $this->_paymentData,
227
+ 'merchant_order' => $this->_merchantOrder]
228
);
229
}
230
}
231
232
+ protected function _getRequestData($key = null)
233
{
234
+ if (null === $key) {
235
+ return $this->_requestData;
236
}
237
238
+ return isset($this->_requestData[$key]) ? $this->_requestData[$key] : null;
239
}
240
241
+
242
public function formatArrayPayment($data, $payment)
243
{
244
Mage::helper('mercadopago')->log("Format Array", self::LOG_FILE);
245
246
+ $fields = [
247
"status",
248
"status_detail",
249
+ "payment_id_detail",
250
"payment_method_id",
251
"transaction_amount",
252
"total_paid_amount",
254
"installments",
255
"shipping_cost",
256
"amount_refunded",
257
+ ];
258
259
foreach ($fields as $field) {
260
if (isset($payment[$field])) {
app/code/community/MercadoPago/Core/controllers/SuccessController.php CHANGED
@@ -70,6 +70,7 @@ class MercadoPago_Core_SuccessController
70
$this->loadLayout(['default', $checkoutTypeHandle]);
71
72
$this->_initLayoutMessages('core/session');
73
74
$this->renderLayout();
75
}
70
$this->loadLayout(['default', $checkoutTypeHandle]);
71
72
$this->_initLayoutMessages('core/session');
73
+ Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($this->getOrder()->getId())));
74
75
$this->renderLayout();
76
}
app/code/community/MercadoPago/Core/etc/config.xml CHANGED
@@ -18,7 +18,7 @@
18
<config>
19
<modules>
20
<MercadoPago_Core>
21
- <version>2.2.0</version>
22
</MercadoPago_Core>
23
</modules>
24
@@ -57,6 +57,51 @@
57
</observer>
58
</observers>
59
</admin_system_config_changed_section_payment>
60
</events>
61
<sales>
62
<quote>
@@ -97,8 +142,6 @@
97
98
<fieldsets>
99
<sales_convert_quote_address>
100
- <finance_cost_amount><to_order>*</to_order></finance_cost_amount>
101
- <base_finance_cost_amount><to_order>*</to_order></base_finance_cost_amount>
102
<discount_coupon_amount><to_order>*</to_order></discount_coupon_amount>
103
<base_discount_coupon_amount><to_order>*</to_order></base_discount_coupon_amount>
104
</sales_convert_quote_address>
18
<config>
19
<modules>
20
<MercadoPago_Core>
21
+ <version>2.4.0</version>
22
</MercadoPago_Core>
23
</modules>
24
57
</observer>
58
</observers>
59
</admin_system_config_changed_section_payment>
60
+
61
+ <controller_action_predispatch_adminhtml_sales_order_cancel>
62
+ <observers>
63
+ <observer>
64
+ <class>MercadoPago_Core_Model_Observer</class>
65
+ <method>salesOrderBeforeCancel</method>
66
+ </observer>
67
+ </observers>
68
+ </controller_action_predispatch_adminhtml_sales_order_cancel>
69
+
70
+ <order_cancel_after>
71
+ <observers>
72
+ <observer>
73
+ <class>MercadoPago_Core_Model_Observer</class>
74
+ <method>salesOrderAfterCancel</method>
75
+ </observer>
76
+ </observers>
77
+ </order_cancel_after>
78
+
79
+ <sales_order_save_before>
80
+ <observers>
81
+ <observer>
82
+ <class>MercadoPago_Core_Model_Observer</class>
83
+ <method>salesOrderBeforeSave</method>
84
+ </observer>
85
+ </observers>
86
+ </sales_order_save_before>
87
+
88
+ <sales_order_creditmemo_save_before>
89
+ <observers>
90
+ <observer>
91
+ <class>MercadoPago_Core_Model_Observer</class>
92
+ <method>creditMemoRefundBeforeSave</method>
93
+ </observer>
94
+ </observers>
95
+ </sales_order_creditmemo_save_before>
96
+
97
+ <sales_order_creditmemo_save_after>
98
+ <observers>
99
+ <observer>
100
+ <class>MercadoPago_Core_Model_Observer</class>
101
+ <method>creditMemoRefundAfterSave</method>
102
+ </observer>
103
+ </observers>
104
+ </sales_order_creditmemo_save_after>
105
</events>
106
<sales>
107
<quote>
142
143
<fieldsets>
144
<sales_convert_quote_address>
145
<discount_coupon_amount><to_order>*</to_order></discount_coupon_amount>
146
<base_discount_coupon_amount><to_order>*</to_order></base_discount_coupon_amount>
147
</sales_convert_quote_address>
app/code/community/MercadoPago/Core/etc/system.xml CHANGED
@@ -56,6 +56,25 @@
56
<show_in_website>1</show_in_website>
57
<show_in_store>1</show_in_store>
58
</order_status_approved>
59
<order_status_refunded translate="label">
60
<label>Choose the status of refunded orders</label>
61
<comment>To manage the status available go to System > Order Statuses</comment>
@@ -116,6 +135,16 @@
116
<show_in_website>1</show_in_website>
117
<show_in_store>1</show_in_store>
118
</order_status_chargeback>
119
<use_successpage_mp translate="label comment">
120
<label>Use Mercado Pago success page</label>
121
<frontend_type>select</frontend_type>
@@ -126,6 +155,16 @@
126
<show_in_store>0</show_in_store>
127
<comment>If set this config with NO, magento success page will be used</comment>
128
</use_successpage_mp>
129
<logs translate="label">
130
<label>Logs</label>
131
<frontend_type>select</frontend_type>
@@ -146,6 +185,16 @@
146
<show_in_store>0</show_in_store>
147
<comment>Enable to display actual error messages to frontend users (not recommended on production environment)</comment>
148
</debug_mode>
149
</fields>
150
</mercadopago>
151
@@ -179,6 +228,7 @@
179
<a href="https://www.mercadopago.com/mlm/account/credentials" target="_blank">Mexico</a>
180
<a href="https://www.mercadopago.com/mlv/account/credentials" target="_blank">Venezuela</a>
181
<a href="https://www.mercadopago.com/mlc/account/credentials" target="_blank">Chile</a>
182
]]>
183
</comment>
184
</access_token>
@@ -258,6 +308,15 @@
258
<show_in_website>1</show_in_website>
259
<show_in_store>0</show_in_store>
260
</coupon_mercadopago>
261
262
</fields>
263
</mercadopago_custom>
@@ -314,6 +373,15 @@
314
<show_in_website>1</show_in_website>
315
<show_in_store>0</show_in_store>
316
</coupon_mercadopago>
317
318
</fields>
319
</mercadopago_customticket>
@@ -454,6 +522,15 @@
454
<show_in_store>0</show_in_store>
455
<comment>Enable to test checkout with real credit cards. For further information check this link: <![CDATA[<a href="https://www.mercadopago.com.ar/developers/en/solutions/payments/basic-checkout/test/basic-sandbox/" target="_blank">Basic Checkout Sandbox</a>]]></comment>
456
</sandbox_mode>
457
</fields>
458
</mercadopago_standard>
459
</fields>
56
<show_in_website>1</show_in_website>
57
<show_in_store>1</show_in_store>
58
</order_status_approved>
59
+ <refund_available translate="label">
60
+ <label>Refund Available</label>
61
+ <frontend_type>select</frontend_type>
62
+ <source_model>adminhtml/system_config_source_yesno</source_model>
63
+ <sort_order>75</sort_order>
64
+ <show_in_default>1</show_in_default>
65
+ <show_in_website>1</show_in_website>
66
+ <show_in_store>1</show_in_store>
67
+ </refund_available>
68
+ <maximum_partial_refunds translate="label comment">
69
+ <label>Maximum amount of partial refunds on the same order</label>
70
+ <frontend_type>text</frontend_type>
71
+ <sort_order>76</sort_order>
72
+ <show_in_default>1</show_in_default>
73
+ <show_in_website>1</show_in_website>
74
+ <show_in_store>1</show_in_store>
75
+ <frontend_class>validate-number-range number-range-1-20</frontend_class>
76
+ <comment>It must be a number between 1 and 20</comment>
77
+ </maximum_partial_refunds>
78
<order_status_refunded translate="label">
79
<label>Choose the status of refunded orders</label>
80
<comment>To manage the status available go to System > Order Statuses</comment>
135
<show_in_website>1</show_in_website>
136
<show_in_store>1</show_in_store>
137
</order_status_chargeback>
138
+ <order_status_partially_refunded translate="label">
139
+ <label>Choose the status when payment was partially refunded</label>
140
+ <comment>To manage the status available go to System > Order Statuses</comment>
141
+ <frontend_type>select</frontend_type>
142
+ <source_model>mercadopago/source_order_status</source_model>
143
+ <sort_order>130</sort_order>
144
+ <show_in_default>1</show_in_default>
145
+ <show_in_website>1</show_in_website>
146
+ <show_in_store>1</show_in_store>
147
+ </order_status_partially_refunded>
148
<use_successpage_mp translate="label comment">
149
<label>Use Mercado Pago success page</label>
150
<frontend_type>select</frontend_type>
155
<show_in_store>0</show_in_store>
156
<comment>If set this config with NO, magento success page will be used</comment>
157
</use_successpage_mp>
158
+ <maximum_days_refund translate="label comment">
159
+ <label>Maximum amount of days until refund is not accepted</label>
160
+ <frontend_type>text</frontend_type>
161
+ <sort_order>136</sort_order>
162
+ <show_in_default>1</show_in_default>
163
+ <show_in_website>1</show_in_website>
164
+ <show_in_store>0</show_in_store>
165
+ <frontend_class>validate-number-range number-range-1-90</frontend_class>
166
+ <comment>It must be a number between 1 and 90</comment>
167
+ </maximum_days_refund>
168
<logs translate="label">
169
<label>Logs</label>
170
<frontend_type>select</frontend_type>
185
<show_in_store>0</show_in_store>
186
<comment>Enable to display actual error messages to frontend users (not recommended on production environment)</comment>
187
</debug_mode>
188
+ <financing_cost translate="label">
189
+ <label>Calculate Financing Cost</label>
190
+ <frontend_type>select</frontend_type>
191
+ <source_model>adminhtml/system_config_source_yesno</source_model>
192
+ <sort_order>150</sort_order>
193
+ <show_in_default>1</show_in_default>
194
+ <show_in_website>0</show_in_website>
195
+ <show_in_store>0</show_in_store>
196
+ <comment></comment>
197
+ </financing_cost>
198
</fields>
199
</mercadopago>
200
228
<a href="https://www.mercadopago.com/mlm/account/credentials" target="_blank">Mexico</a>
229
<a href="https://www.mercadopago.com/mlv/account/credentials" target="_blank">Venezuela</a>
230
<a href="https://www.mercadopago.com/mlc/account/credentials" target="_blank">Chile</a>
231
+ <a href="https://www.mercadopago.com/mpe/account/credentials" target="_blank">Peru</a>
232
]]>
233
</comment>
234
</access_token>
308
<show_in_website>1</show_in_website>
309
<show_in_store>0</show_in_store>
310
</coupon_mercadopago>
311
+ <communication translate="label">
312
+ <label>Custom Message</label>
313
+ <frontend_type>textarea</frontend_type>
314
+ <sort_order>90</sort_order>
315
+ <show_in_default>1</show_in_default>
316
+ <show_in_website>1</show_in_website>
317
+ <show_in_store>0</show_in_store>
318
+ <comment>Custom message to display in checkout</comment>
319
+ </communication>
320
321
</fields>
322
</mercadopago_custom>
373
<show_in_website>1</show_in_website>
374
<show_in_store>0</show_in_store>
375
</coupon_mercadopago>
376
+ <communication translate="label">
377
+ <label>Custom Message</label>
378
+ <frontend_type>textarea</frontend_type>
379
+ <sort_order>60</sort_order>
380
+ <show_in_default>1</show_in_default>
381
+ <show_in_website>1</show_in_website>
382
+ <show_in_store>0</show_in_store>
383
+ <comment>Custom message to display in checkout</comment>
384
+ </communication>
385
386
</fields>
387
</mercadopago_customticket>
522
<show_in_store>0</show_in_store>
523
<comment>Enable to test checkout with real credit cards. For further information check this link: <![CDATA[<a href="https://www.mercadopago.com.ar/developers/en/solutions/payments/basic-checkout/test/basic-sandbox/" target="_blank">Basic Checkout Sandbox</a>]]></comment>
524
</sandbox_mode>
525
+ <communication translate="label">
526
+ <label>Custom Message</label>
527
+ <frontend_type>textarea</frontend_type>
528
+ <sort_order>170</sort_order>
529
+ <show_in_default>1</show_in_default>
530
+ <show_in_website>1</show_in_website>
531
+ <show_in_store>0</show_in_store>
532
+ <comment>Custom message to display in checkout</comment>
533
+ </communication>
534
</fields>
535
</mercadopago_standard>
536
</fields>
app/code/community/MercadoPago/MercadoEnvios/Model/Adminhtml/Attribute/Validation/Mapping.php CHANGED
@@ -8,15 +8,17 @@ class MercadoPago_MercadoEnvios_Model_Adminhtml_Attribute_Validation_Mapping
8
{
9
$mappingValues = $this->getValue(); //get the value from our config
10
$attributeCodes = [];
11
12
- foreach ($mappingValues as $value) {
13
- if (in_array($value['attribute_code'], $attributeCodes)) {
14
- Mage::throwException(Mage::helper('mercadopago')->__("Cannot repeat Magento Product size attributes"));
15
- }
16
17
- $attributeCodes[] = $value['attribute_code'];
18
}
19
-
20
return parent::save();
21
}
22
}
8
{
9
$mappingValues = $this->getValue(); //get the value from our config
10
$attributeCodes = [];
11
+ $website = Mage::helper('mercadopago')->getAdminSelectedWebsite();
12
13
+ if ($website->getConfig('carriers/mercadoenvios/active')) {
14
+ foreach ($mappingValues as $value) {
15
+ if (in_array($value['attribute_code'], $attributeCodes)) {
16
+ Mage::throwException(Mage::helper('mercadopago')->__("Cannot repeat Magento Product size attributes"));
17
+ }
18
19
+ $attributeCodes[] = $value['attribute_code'];
20
+ }
21
}
22
return parent::save();
23
}
24
}
app/code/community/MercadoPago/MercadoEnvios/Model/Observer.php CHANGED
@@ -39,12 +39,17 @@ class MercadoPago_MercadoEnvios_Model_Observer
39
public function addPrintButton($observer)
40
{
41
$block = $observer->getBlock();
42
-
43
if ($block instanceof Mage_Adminhtml_Block_Sales_Order_Shipment_View) {
44
- $shipmentId = Mage::app()->getRequest()->getParam('shipment_id');
45
$block->addButton('print_shipment_label', array(
46
'label' => 'Print shipping label',
47
- 'onclick' => 'window.open(\' ' . Mage::helper('mercadopago_mercadoenvios')->getTrackingPrintUrl($shipmentId) . '\')',
48
'class' => 'go'
49
));
50
}
@@ -123,6 +128,7 @@ class MercadoPago_MercadoEnvios_Model_Observer
123
$order = $observer->getOrder();
124
$method = $order->getShippingMethod();
125
$shippingCost = $order->getBaseShippingAmount();
126
if (Mage::helper('mercadopago_mercadoenvios')->isMercadoEnviosMethod($method)) {
127
$shippingAddress = $order->getShippingAddress();
128
$zipCode = $shippingAddress->getPostcode();
@@ -138,9 +144,7 @@ class MercadoPago_MercadoEnvios_Model_Observer
138
$paramsME['free_methods'] = [['id' => intval($defaultShippingId)]];
139
}
140
}
141
- if (!empty($shippingCost)) {
142
- $paramsME['cost'] = (float)$order->getBaseShippingAmount();
143
- }
144
$observer->getParams()->setValues($paramsME);
145
Mage::helper('mercadopago_mercadoenvios')->log('REQUEST SHIPMENT ME: ', $paramsME, Zend_Log::INFO);
146
39
public function addPrintButton($observer)
40
{
41
$block = $observer->getBlock();
42
if ($block instanceof Mage_Adminhtml_Block_Sales_Order_Shipment_View) {
43
+ $helper = Mage::helper('mercadopago_mercadoenvios');
44
+ $shipment = Mage::registry('current_shipment');
45
+ $shippingCode = Mage::getModel('sales/order')->load($shipment->getOrderId())->getShippingMethod();
46
+ if (!$helper->isMercadoEnviosMethod($shippingCode)) {
47
+ return;
48
+ }
49
+ $shipmentId = $shipment->getId();
50
$block->addButton('print_shipment_label', array(
51
'label' => 'Print shipping label',
52
+ 'onclick' => 'window.open(\' ' . $helper->getTrackingPrintUrl($shipmentId) . '\')',
53
'class' => 'go'
54
));
55
}
128
$order = $observer->getOrder();
129
$method = $order->getShippingMethod();
130
$shippingCost = $order->getBaseShippingAmount();
131
+ $paramsME = [];
132
if (Mage::helper('mercadopago_mercadoenvios')->isMercadoEnviosMethod($method)) {
133
$shippingAddress = $order->getShippingAddress();
134
$zipCode = $shippingAddress->getPostcode();
144
$paramsME['free_methods'] = [['id' => intval($defaultShippingId)]];
145
}
146
}
147
+
148
$observer->getParams()->setValues($paramsME);
149
Mage::helper('mercadopago_mercadoenvios')->log('REQUEST SHIPMENT ME: ', $paramsME, Zend_Log::INFO);
150
app/code/community/MercadoPago/MercadoEnvios/etc/config.xml CHANGED
@@ -2,7 +2,7 @@
2
<config>
3
<modules>
4
<MercadoPago_MercadoEnvios>
5
- <version>2.2.0</version>
6
</MercadoPago_MercadoEnvios>
7
</modules>
8
<frontend>
@@ -75,7 +75,7 @@
75
<observers>
76
<paymentfilter_payment_method_is_active>
77
<type>singleton</type>
78
- <class>MercadoPago_MercadoEnvios_Model_Observer</class>
79
<method>filterActivePaymentMethods</method>
80
</paymentfilter_payment_method_is_active>
81
</observers>
@@ -83,11 +83,11 @@
83
<admin_system_config_changed_section_payment>
84
<observers>
85
<payment_section_observer>
86
- <class>MercadoPago_MercadoEnvios_Model_Observer</class>
87
<method>checkAndValidateData</method>
88
</payment_section_observer>
89
<payment_section_observer_shipping_method>
90
- <class>MercadoPago_MercadoEnvios_Model_Observer</class>
91
<method>validateShippingMethod</method>
92
</payment_section_observer_shipping_method>
93
</observers>
@@ -95,7 +95,7 @@
95
<admin_system_config_changed_section_carriers>
96
<observers>
97
<payment_section_observer_shipping_method>
98
- <class>MercadoPago_MercadoEnvios_Model_Observer</class>
99
<method>validateShippingMethod</method>
100
</payment_section_observer_shipping_method>
101
</observers>
@@ -110,12 +110,11 @@
110
<observers>
111
<mercadopago_mercadoenvios>
112
<type>singleton</type>
113
- <class>MercadoPago_MercadoEnvios_Model_Observer</class>
114
<method>addPrintButton</method>
115
</mercadopago_mercadoenvios>
116
</observers>
117
</adminhtml_widget_container_html_before>
118
-
119
</events>
120
</adminhtml>
121
@@ -126,7 +125,7 @@
126
<title>MercadoEnvĂ­os</title>
127
<model>MercadoPago_MercadoEnvios_Model_Shipping_Carrier_MercadoEnvios</model>
128
<sort_order>10</sort_order>
129
- <sallowspecific>1</sallowspecific>
130
<name>MercadoEnvios</name>
131
<specificerrmsg>This shipping method is currently unavailable.</specificerrmsg>
132
</mercadoenvios>
2
<config>
3
<modules>
4
<MercadoPago_MercadoEnvios>
5
+ <version>2.4.0</version>
6
</MercadoPago_MercadoEnvios>
7
</modules>
8
<frontend>
75
<observers>
76
<paymentfilter_payment_method_is_active>
77
<type>singleton</type>
78
+ <class>mercadopago_mercadoenvios/observer</class>
79
<method>filterActivePaymentMethods</method>
80
</paymentfilter_payment_method_is_active>
81
</observers>
83
<admin_system_config_changed_section_payment>
84
<observers>
85
<payment_section_observer>
86
+ <class>mercadopago_mercadoenvios/observer</class>
87
<method>checkAndValidateData</method>
88
</payment_section_observer>
89
<payment_section_observer_shipping_method>
90
+ <class>mercadopago_mercadoenvios/observer</class>
91
<method>validateShippingMethod</method>
92
</payment_section_observer_shipping_method>
93
</observers>
95
<admin_system_config_changed_section_carriers>
96
<observers>
97
<payment_section_observer_shipping_method>
98
+ <class>mercadopago_mercadoenvios/observer</class>
99
<method>validateShippingMethod</method>
100
</payment_section_observer_shipping_method>
101
</observers>
110
<observers>
111
<mercadopago_mercadoenvios>
112
<type>singleton</type>
113
+ <class>mercadopago_mercadoenvios/observer</class>
114
<method>addPrintButton</method>
115
</mercadopago_mercadoenvios>
116
</observers>
117
</adminhtml_widget_container_html_before>
118
</events>
119
</adminhtml>
120
125
<title>MercadoEnvĂ­os</title>
126
<model>MercadoPago_MercadoEnvios_Model_Shipping_Carrier_MercadoEnvios</model>
127
<sort_order>10</sort_order>
128
+ <sallowspecific>0</sallowspecific>
129
<name>MercadoEnvios</name>
130
<specificerrmsg>This shipping method is currently unavailable.</specificerrmsg>
131
</mercadoenvios>
app/code/community/MercadoPago/OneStepCheckout/etc/config.xml CHANGED
@@ -2,7 +2,7 @@
2
<config>
3
<modules>
4
<MercadoPago_OneStepCheckout>
5
- <version>2.2.0</version>
6
</MercadoPago_OneStepCheckout>
7
</modules>
8
<global>
2
<config>
3
<modules>
4
<MercadoPago_OneStepCheckout>
5
+ <version>2.4.0</version>
6
</MercadoPago_OneStepCheckout>
7
</modules>
8
<global>
app/design/frontend/base/default/template/mercadopago/custom/form.phtml CHANGED
@@ -167,7 +167,9 @@ $customer = $this->getCustomerAndCards();
167
</li>
168
169
<li>
170
-
171
<?php if ($this->getMethod()->getConfigData('banner_checkout') != ""): ?>
172
<img src="<?php echo $this->getMethod()->getConfigData('banner_checkout'); ?>" class="banner_checkout_mp"/>
173
<?php endif; ?>
167
</li>
168
169
<li>
170
+ <?php if ($this->getMethod()->getConfigData('communication') != ""): ?>
171
+ <p class="communication"><?php echo $this->getMethod()->getConfigData('communication') ?></p>
172
+ <?php endif; ?>
173
<?php if ($this->getMethod()->getConfigData('banner_checkout') != ""): ?>
174
<img src="<?php echo $this->getMethod()->getConfigData('banner_checkout'); ?>" class="banner_checkout_mp"/>
175
<?php endif; ?>
app/design/frontend/base/default/template/mercadopago/custom/success.phtml CHANGED
@@ -3,7 +3,6 @@
3
$total = $this->getTotal();
4
$payment = $this->getPayment();
5
6
- //monta link para o pedido
7
$link_to_order = $this->__('Your order %s has been successfully generated.', '<a href="'. Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK,true) . "sales/order/view/order_id/" . $this->getEntityId() . '">' . $order->getIncrementId() .'</a>');
8
9
$payment_method = $this->getPaymentMethod();
3
$total = $this->getTotal();
4
$payment = $this->getPayment();
5
6
$link_to_order = $this->__('Your order %s has been successfully generated.', '<a href="'. Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK,true) . "sales/order/view/order_id/" . $this->getEntityId() . '">' . $order->getIncrementId() .'</a>');
7
8
$payment_method = $this->getPaymentMethod();
app/design/frontend/base/default/template/mercadopago/custom_ticket/form.phtml CHANGED
@@ -55,6 +55,9 @@ $route = $this->getRequest()->getRequestedRouteName();
55
</ul>
56
</div>
57
<br/>
58
<?php if ($this->getMethod()->getConfigData('banner_checkout') != ""): ?>
59
<img src="<?php echo $this->getMethod()->getConfigData('banner_checkout'); ?>" class="banner_checkout_mp"/>
60
<?php endif; ?>
55
</ul>
56
</div>
57
<br/>
58
+ <?php if ($this->getMethod()->getConfigData('communication') != ""): ?>
59
+ <p class="communication"><?php echo $this->getMethod()->getConfigData('communication') ?></p>
60
+ <?php endif; ?>
61
<?php if ($this->getMethod()->getConfigData('banner_checkout') != ""): ?>
62
<img src="<?php echo $this->getMethod()->getConfigData('banner_checkout'); ?>" class="banner_checkout_mp"/>
63
<?php endif; ?>
app/design/frontend/base/default/template/mercadopago/custom_ticket/success.phtml CHANGED
@@ -3,7 +3,6 @@
3
$total = $this->getTotal();
4
$payment = $this->getPayment();
5
6
- //monta link para o pedido
7
$link_to_order = $this->__('Your order %s has been successfully generated.', '<a href="'. Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK,true) . "sales/order/view/order_id/" . $this->getEntityId() . '">' . $order->getIncrementId() .'</a>');
8
9
$payment_method = $this->getPaymentMethod();
3
$total = $this->getTotal();
4
$payment = $this->getPayment();
5
6
$link_to_order = $this->__('Your order %s has been successfully generated.', '<a href="'. Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK,true) . "sales/order/view/order_id/" . $this->getEntityId() . '">' . $order->getIncre