· 6 years ago · Oct 03, 2019, 11:06 PM
1<?php
2
3/**
4 * Modulo MercadoPago Tools Pro
5 *
6 * @author Kijam
7 * @copyright 2019 Kijam
8 * @license Commercial use allowed (Non-assignable & non-transferable),
9 * can modify source-code but cannot distribute modifications
10 * (derivative works).
11 */
12class MercadoPagoGatewayKijam
13{
14
15 // Configuracion general del modulo
16 public $config = array();
17
18 public $settings = null;
19
20 public $module_name = null;
21
22 public $os_pending = null;
23
24 public $os_wait_payment = null;
25
26 public $currency_convert = array();
27
28 public $api_me = null;
29
30 public $mercadoenvios_available = false;
31
32 public $carrier_list = array();
33
34 public $carrier_list_name = array();
35
36 protected $test_user = null;
37
38 protected $test_user_retry = null;
39
40 protected $list_shippings = array(
41 'mp_ps' => array(),
42 'ps_mp' => array()
43 );
44
45 protected $site_id = null;
46
47 protected $site_url = null;
48
49 protected $id_shop = null;
50
51 protected $id_shop_group = null;
52
53 protected $instance_module = null;
54
55 protected $context = null;
56
57 public static $dimension_unit = '';
58
59 public static $weight_unit = '';
60
61 protected $dimension_unit_list = array(
62 'CM' => 'CM',
63 'IN' => 'IN',
64 'CMS' => 'CM',
65 'INC' => 'IN'
66 );
67
68 protected $weight_unit_list = array(
69 'KG' => 'KGS',
70 'KGS' => 'KGS',
71 'LBS' => 'LBS',
72 'LB' => 'LBS'
73 );
74
75 public $warning = '';
76
77 // Propiedades estaticas
78 protected static $instance = null;
79
80 protected static $instance_status = 'uninstance';
81
82 protected static $ignore_update_status = false;
83
84 /**
85 * ****************************************************
86 */
87 /**
88 * ****************************************************
89 */
90 /**
91 * ****** DESDE AQUI VA TODO LO RELACIONADO ***********
92 */
93 /**
94 * ***************** A MERCADOPAGO ********************
95 */
96 /**
97 * ****************************************************
98 */
99 /**
100 * ****************************************************
101 */
102 public function verifyMercadoPago($force_reload = false)
103 {
104 if (! isset($this->config['client_secret']) || ! isset($this->config['client_secret'])) {
105 return false;
106 }
107 $data = include (dirname(__FILE__) . '/data-mp-countries.php');
108 if (! $force_reload && ! is_null($this->api_me)) {
109 if ($this->api_me['site_id']) {
110 $this->site_id = $this->api_me['site_id'];
111 $this->settings = $data[Tools::strtoupper($this->site_id)];
112 $this->mercadoenvios_available = isset($this->settings['MPENVIOS_REGISTER_URL']);
113 if ($this->mercadoenvios_available) {
114 foreach ($this->settings['CARRIER_LIST'] as $me_op) {
115 $this->carrier_list[] = $me_op['id'];
116 $this->carrier_list_name[$me_op['id']] = $me_op['name'];
117 }
118 $this->installMercadoEnvios();
119 }
120 }
121 return $this->api_me;
122 }
123 $cache_id = 'mp_me_' . md5($this->config['client_id'] . '-' . $this->config['client_secret']);
124 $me = false;
125 if (! $force_reload && ($me = UKijam::getCache($cache_id)) && isset($me['id'])) {
126 $this->api_me = $me;
127 if ($this->api_me['site_id']) {
128 $this->site_id = $this->api_me['site_id'];
129 $this->settings = $data[Tools::strtoupper($this->site_id)];
130 $this->mercadoenvios_available = isset($this->settings['MPENVIOS_REGISTER_URL']);
131 if ($this->mercadoenvios_available) {
132 foreach ($this->settings['CARRIER_LIST'] as $me_op) {
133 $this->carrier_list[] = $me_op['id'];
134 $this->carrier_list_name[$me_op['id']] = $me_op['name'];
135 }
136 $this->installMercadoEnvios();
137 }
138 }
139 return $this->api_me;
140 }
141 try {
142 MPClassTK::check_token(true);
143 $me = MPClassTK::get_me();
144 if ($me !== null) {
145 $this->api_me = $me;
146 if ($this->api_me['site_id']) {
147 $this->site_id = $this->api_me['site_id'];
148 $this->settings = $data[Tools::strtoupper($this->site_id)];
149 $this->mercadoenvios_available = isset($this->settings['MPENVIOS_REGISTER_URL']);
150 if ($this->mercadoenvios_available) {
151 foreach ($this->settings['CARRIER_LIST'] as $me_op) {
152 $this->carrier_list[] = $me_op['id'];
153 $this->carrier_list_name[$me_op['id']] = $me_op['name'];
154 }
155 $this->installMercadoEnvios();
156 }
157 }
158 UKijam::setCache($cache_id, $me);
159 return $this->api_me;
160 }
161 UKijam::setCache($cache_id, '');
162 throw new Exception('Invalid access token for get me(object).');
163 } catch (Exception $e) {
164 UKijam::log('ERROR-verifyMercadoPago: ' . $e->getFile() . "[" . $e->getLine() . "] -> " . $e->getMessage());
165 return false;
166 }
167 return false;
168 }
169
170 public function getBalance()
171 {
172 $me = $this->verifyMercadoPago();
173 if ($me) {
174 $balance = MPClassTK::get_balance($me['id']);
175 UKijam::log('getBalance: ' . UKijam::pL($balance, true));
176 return $balance !== null ? $balance : false;
177 }
178 return false;
179 }
180
181 public function getPaymentButton($cart = null, $order = null)
182 {
183 if (! $this->verifyMercadoPago()) {
184 return false;
185 }
186 if ($cart === null && $order === null) {
187 $cart = Context::getContext()->cart;
188 if (! Validate::isLoadedObject($cart) || (int) $cart->id < 1) {
189 return false;
190 }
191 $products = $cart->getProducts();
192 if (count($products) < 1) {
193 return false;
194 }
195 }
196 if ($cart === null) {
197 $cart = new Cart($order->id_cart);
198 }
199 if ($order === null) {
200 $id_order = (int) Order::getOrderByCartId($cart->id);
201 if ($id_order > 0) {
202 $order = new Order($id_order);
203 }
204 }
205 $link = Context::getContext()->link;
206 $currency = new Currency((int) $cart->id_currency);
207 if ($order === null) {
208 $full_total_price = $cart->getOrderTotal(true, Cart::BOTH);
209 } else {
210 $full_total_price = $order->total_paid;
211 }
212 $custom_image = false;
213 if (isset($this->config['custom_payment_button']) && ! empty($this->config['custom_payment_button'])) {
214 $custom_image = $this->site_url . 'modules/' . $this->module_name . $this->config['custom_payment_button'];
215 if ((bool) Configuration::get('PS_SSL_ENABLED')) {
216 $custom_image = str_replace('http:', 'https:', $custom_image);
217 }
218 }
219 $qr_image = false;
220 if (isset($this->config['logo_qr_checkout']) && ! empty($this->config['logo_qr_checkout'])) {
221 $qr_image = $this->site_url . 'modules/' . $this->module_name . $this->config['logo_qr_checkout'];
222 if ((bool) Configuration::get('PS_SSL_ENABLED')) {
223 $qr_image = str_replace('http:', 'https:', $qr_image);
224 }
225 }
226 $rate = UKijam::getRate($currency->iso_code, $this->settings['CURRENCY']);
227 $full_price = $full_total_price * $rate;
228 $fee = 100.0 / (100.0 - (float) $this->config['fee']);
229 $fee_total = $fee * $full_price + $this->config['fee_amount'] - $full_price;
230 $fee_qr = 100.0 / (100.0 - (float) $this->config['fee_qr']);
231 $fee_total_qr = $fee_qr * $full_price + $this->config['fee_amount_qr'] - $full_price;
232 $fee_custom = 100.0 / (100.0 - (float) $this->config['fee_custom']);
233 $fee_total_custom = $fee_custom * $full_price + $this->config['fee_amount_custom'] - $full_price;
234 $mp_params = array();
235 $decimals = $this->settings['UNIT_PRICE_TYPE'] == 'INTEGER' ? 0 : 2;
236 $mp_params['price'] = $full_price + $fee_total;
237 $mp_params['price'] = Tools::ps_round($mp_params['price'], $decimals);
238 $mp_params['price_qr'] = $full_price + $fee_total_qr;
239 $mp_params['price_qr'] = Tools::ps_round($mp_params['price_qr'], $decimals);
240 $mp_params['price_custom'] = $full_price + $fee_total_custom;
241 $mp_params['price_custom'] = Tools::ps_round($mp_params['price_custom'], $decimals);
242 $mp_params['id_cart'] = $cart->id;
243 $mp_params['id_order'] = $order !== null ? $order->id : '';
244 $mp_params['init_point'] = $link->getModuleLink('mptoolspro', 'redirect', array(
245 'gen_order' => 1,
246 'payment_type' => 'basic'
247 ));
248 $mp_params['init_point_custom'] = Context::getContext()->link->getModuleLink('mptoolspro', 'redirect', array(
249 'gen_order' => 1,
250 'payment_type' => 'custom'
251 ));
252 // BUG causado por MP...
253 $mp_params['init_point_custom'] = parse_url($mp_params['init_point_custom'], PHP_URL_PATH) . '?' . parse_url($mp_params['init_point_custom'], PHP_URL_QUERY);
254 // Fin bugfix
255 $mp_params['init_point_qr'] = Context::getContext()->link->getModuleLink('mptoolspro', 'redirect', array(
256 'gen_order' => 1,
257 'payment_type' => 'qr'
258 ));
259 $mp_params['back_url'] = Context::getContext()->link->getModuleLink('mptoolspro', 'redirect');
260
261 $mp_params['modal'] = (bool) $this->config['modal'];
262 $mp_params['mpstyle'] = $this->config['style'];
263 $mp_params['qr_image'] = $qr_image;
264 $mp_params['custom_image'] = $custom_image;
265 $mp_params['fee'] = $this->config['fee'];
266 $mp_params['fee_amount'] = $this->config['fee_amount'];
267 $mp_params['fee_custom'] = $this->config['fee_custom'];
268 $mp_params['fee_amount_custom'] = $this->config['fee_amount_custom'];
269 $mp_params['fee_qr'] = $this->config['fee_qr'];
270 $mp_params['fee_amount_qr'] = $this->config['fee_amount_qr'];
271 $mp_params['fee_total_qr'] = $fee_total_qr;
272 $mp_params['fee_total_custom'] = $fee_total_custom;
273 $mp_params['fee_total'] = $fee_total;
274 $mp_params['TOKEN_JS'] = $this->settings['TOKEN_JS'];
275 $mp_params['mp_country_btn'] = $this->settings['BTN_COUNTRY'];
276 $mp_params['installment_calculator'] = (bool) $this->config['installment_calculator'];
277 // echo var_export($mp_params, true);
278 return $mp_params;
279 }
280
281 public function createInitPoint($cart = null, $order = null)
282 {
283 if (! $this->verifyMercadoPago()) {
284 return false;
285 }
286 if ($cart === null && $order === null) {
287 $cart = Context::getContext()->cart;
288 if (! Validate::isLoadedObject($cart) || (int) $cart->id < 1) {
289 return false;
290 }
291 $products = $cart->getProducts();
292 if (count($products) < 1) {
293 return false;
294 }
295 }
296 if ($cart === null) {
297 $cart = new Cart($order->id_cart);
298 }
299 if ($order === null) {
300 $id_order = (int) Order::getOrderByCartId($cart->id);
301 if ($id_order > 0) {
302 $order = new Order($id_order);
303 }
304 }
305 if ($order !== null) {
306 $currency = new Currency((int) $order->id_currency);
307 $customer = new Customer((int) $order->id_customer);
308 } else {
309 $currency = new Currency((int) $cart->id_currency);
310 $customer = new Customer((int) $cart->id_customer);
311 }
312 $link = new Link();
313 $cart_prices = UKijam::getCartOrderTotal($cart);
314 $address = new Address((int) $cart->id_address_invoice);
315 $total_price = 0;
316 $shipping_price = 0;
317 $id_carrier = 0;
318 if ($order !== null) {
319 $full_total_price = $order->total_paid;
320 $id_carrier = $order->id_carrier;
321 } else {
322 $full_total_price = $cart_prices['both'];
323 $id_carrier = $cart->id_carrier;
324 }
325 $is_mp_envios = false;
326 if ($this->mercadoenvios_available && $this->config['shipping_active'] && isset($this->list_shippings['ps_mp'][$id_carrier])) {
327 if ($order) {
328 $shipping_price = $order->total_shipping_tax_incl;
329 } else {
330 $shipping_price = $cart_prices['shipping'];
331 }
332 $total_price = $full_total_price - $shipping_price;
333 $is_mp_envios = true;
334 } else {
335 $total_price = $full_total_price;
336 }
337 $logo = false;
338 if (isset($this->config['logo_mercadopago_checkout']) && $this->config['logo_mercadopago_checkout']) {
339 if (Tools::strtolower(Tools::substr($this->config['logo_mercadopago_checkout'], 0, 4)) != 'http') {
340 $logo = $this->site_url . 'modules/' . $this->module_name . $this->config['logo_mercadopago_checkout'];
341 } else {
342 $logo = $this->config['logo_mercadopago_checkout'];
343 }
344 } else {
345 $logo = $link->getMediaLink(_PS_IMG_ . Configuration::get('PS_LOGO'));
346 }
347 if ((bool) Configuration::get('PS_SSL_ENABLED')) {
348 $logo = str_replace('http:', 'https:', $logo);
349 }
350 $rate = UKijam::getRate($currency->iso_code, $this->settings['CURRENCY']);
351 $full_price = $full_total_price * $rate;
352 $price = $total_price * $rate;
353
354 $fee = 100.0 / (100.0 - (float) $this->config['fee']);
355 // Esto es para incluir el costo de MercadoEnvios en el calculo de comisión.
356 $fee_total = $fee * $full_price + $this->config['fee_amount'] - $full_price;
357
358 $unit_price = Tools::ps_round($price + $fee_total, 2);
359 $link = new Link();
360 $ipn_url = $link->getModuleLink('mptoolspro', 'redirect');
361 $max_installments = max(1, min(36, (int) $this->config['max_installments']));
362 $mp_unit_price = (float) $unit_price;
363 if ($this->settings['UNIT_PRICE_TYPE'] == 'INTEGER') {
364 $mp_unit_price = (int) Tools::ps_round($unit_price, 0);
365 }
366 $id = 'C-' . $cart->id;
367 $name = "Carrito No: {$cart->id}";
368 if ($order !== null) {
369 $id = 'O-' . $order->id;
370 $name = "Orden No: {$order->id}";
371 }
372 $preference_data = array(
373 'items' => array(
374 array(
375 'id' => $id,
376 'title' => $name . " - {$address->firstname} {$address->lastname}",
377 'quantity' => 1,
378 'currency_id' => $this->settings['CURRENCY'],
379 'unit_price' => $mp_unit_price,
380 'picture_url' => $logo
381 )
382 ),
383 'back_urls' => array(
384 'success' => $ipn_url,
385 'failure' => $ipn_url,
386 'pending' => $ipn_url
387 ),
388 'notification_url' => $ipn_url,
389 // 'notification_url'=> 'https://kijam.com/ipn_mercadopago/get_data/'.
390 // MPRestClientGeneric::encodeUrl($ipn_url),
391 'external_reference' => $id,
392 'payer' => array(
393 'email' => $customer->email,
394 'name' => $customer->firstname,
395 'surname' => $customer->lastname,
396 'phone' => array(
397 'number' => ! empty($address->phone) ? $address->phone : ! empty($address->phone_mobile) ? $address->phone_mobile : mull
398 ),
399 'identification' => array(
400 'type' => ! empty($address->vat_number) ? 'VAT' : $this->settings['DNI_NAME'],
401 'number' => ! empty($address->vat_number) ? $address->vat_number : $address->dni
402 ),
403 'address' => array(
404 'zip_code' => $address->postcode,
405 'street_name' => $address->address1
406 )
407 ),
408 'payment_methods' => array(
409 'installments' => $price < $this->config['min_amount_installments'] ? 1 : $max_installments,
410 'default_installments' => 1
411 )
412 );
413 if ($this->config['auto_return']) {
414 $preference_data['auto_return'] = 'approved';
415 }
416 $products = $cart->getProducts();
417 $picture_added = false;
418 $is_first_item = true;
419 $additional_info = $name . ' - ';
420 foreach ($products as &$p) {
421 if ($is_first_item) {
422 $is_first_item = false;
423 $additional_info .= $p['name'] . '(' . $p['quantity'] . ' U.)';
424 } else {
425 $additional_info .= ' - ' . $p['name'] . '(' . $p['quantity'] . ' U.)';
426 }
427 if (isset($p['attributes']) && ! empty($p['attributes'])) {
428 $additional_info .= ', ' . str_replace('-', ',', $p['attributes']);
429 }
430 if (! $picture_added && $this->config['image_for_order'] == 'product') {
431 $img = ((bool) Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . preg_replace('/https?:\/\//i', '', $link->getImageLink($p['link_rewrite'], $p['id_image'], ImageType::getFormatedName('large')));
432 if (! $img || ! UKijam::urlExists($img)) {
433 $images_type = ImageType::getImagesTypes('products');
434 $image_type = false;
435 foreach ($images_type as $r) {
436 if ($r['width'] > 100) {
437 $image_type = $r['name'];
438 break;
439 }
440 }
441 if ($image_type) {
442 $img = ((bool) Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . preg_replace('/https?:\/\//i', '', $link->getImageLink($p['link_rewrite'], $p['id_image'], ImageType::getFormatedName($image_type)));
443 }
444 }
445 if ($img && ! empty($img) && UKijam::urlExists($img)) {
446 $preference_data['items'][0]['picture_url'] = $img;
447 $picture_added = true;
448 }
449 }
450 }
451 $preference_data['additional_info'] = $additional_info;
452 $preference_data['items'][0]['title'] = Tools::substr($additional_info, 0, 255);
453 $preference_data['items'][0]['description'] =Tools::substr($additional_info, 0, 255);
454 if (Tools::strlen($preference_data['items'][0]['title']) < Tools::strlen($additional_info)) {
455 $preference_data['items'][0]['title'] .= ' |HAY MAS|';
456 }
457 if ($is_mp_envios) {
458 $preference_data['shipments'] = array();
459 $preference_data['shipments']['mode'] = 'me2';
460 $preference_data['shipments']['local_pickup'] = false;
461 $products = $cart->getProducts();
462 $dim = UKijam::getMPShippingDim($products);
463 $str_dimensions = "{$dim['width']}x{$dim['height']}x{$dim['depth']},{$dim['weight']}";
464 $str_zip = preg_replace('/[^0-9]/', '', $address->postcode);
465 $str_method = $this->list_shippings['ps_mp'][$id_carrier];
466 $preference_data['shipments']['dimensions'] = $str_dimensions;
467 $preference_data['shipments']['receiver_address']['zip_code'] = $str_zip;
468 $preference_data['shipments']['default_shipping_method'] = $str_method;
469 $preference_data['shipments']['free_methods'] = array();
470 $list_free_method = array();
471 foreach ($this->list_shippings['ps_mp'] as $id_mp_carrier => $cid) {
472 $carrier = new Carrier($id_mp_carrier);
473 if (! Validate::isLoadedObject($carrier) || $carrier->deleted) {
474 continue;
475 }
476 if ($carrier->is_free) {
477 $preference_data['shipments']['free_methods'][] = array(
478 'id' => (int) $cid
479 );
480 $list_free_method[] = (int) $id_mp_carrier;
481 }
482 }
483 if ($shipping_price < 0.1 && ! in_array((int) $id_carrier, $list_free_method)) {
484 $id_mp_carrier = (int) $this->list_shippings['ps_mp'][$id_carrier];
485 $preference_data['shipments']['free_methods'][] = array(
486 'id' => $id_mp_carrier
487 );
488 }
489 } else {
490 $str_zip = preg_replace('/[^0-9]/', '', $address->postcode);
491 $preference_data['shipments'] = array();
492 $preference_data['shipments']['mode'] = 'not_specified';
493 $preference_data['shipments']['receiver_address'] = array();
494 $preference_data['shipments']['receiver_address']['zip_code'] = $str_zip;
495 $preference_data['shipments']['receiver_address']['street_name'] = $address->address1;
496 $preference_data['shipments']['receiver_address']['apartment'] = $address->address2;
497 }
498 if (! empty($this->config['exclude_payments']) && is_array($this->config['exclude_payments'])) {
499 foreach ($this->config['exclude_payments'] as $k => $v) {
500 if ((int) $v) {
501 $preference_data['payment_methods']['excluded_payment_types'][] = array(
502 'id' => $k
503 );
504 }
505 }
506 }
507 $mp_params = array(
508 'error' => false,
509 'preference' => false
510 );
511 try {
512 UKijam::log('preference_data: ' . UKijam::pL($preference_data, true));
513 $preference = MPClassTK::create_preference($preference_data);
514 if ($preference) {
515 $mp_params['preference'] = $preference;
516 } else {
517 UKijam::log('ERROR-preference_result: false return.');
518 $mp_params['error'] = $this->l('Error conectando a MercadoPago.');
519 }
520 } catch (Exception $e) {
521 UKijam::log('ERROR-create_preference: ' . $e->getFile() . "[" . $e->getLine() . "] -> " . $e->getMessage());
522 $mp_params['error'] = $this->l('Error conectando a MercadoPago: ') . ' [' . $e->getCode() . ']
523 - ' . $e->getMessage();
524 }
525 $mp_params['currency_id'] = $this->settings['CURRENCY'];
526 $mp_params['total_products'] = $full_price - ($shipping_price * $rate);
527 $mp_params['shipping'] = $shipping_price * $rate;
528 $mp_params['subtotal'] = $full_price;
529 $mp_params['total_fee'] = $mp_unit_price - $full_price;
530 $mp_params['is_mp_envios'] = $is_mp_envios;
531 $mp_params['total_paid'] = $mp_unit_price;
532 $mp_params['item_id'] = $id;
533 return $mp_params;
534 }
535
536 public function validateMercadoPago($topic, $mp_op_id, $data_payment_obj = null)
537 {
538 if (! $mp_op_id || ! $this->verifyMercadoPago()) {
539 return false;
540 }
541 $is_sandbox = false;
542 $this->verifyOrderStatus();
543 $paid_amount = 0;
544 // $f_amount = 0;
545 $status_act = false;
546 $merchant_order_info = false;
547 $payment_info = false;
548 $last_payment_id = false;
549 $shipping_info = false;
550 $commision_amount = 0;
551 $ret = array();
552 $ret['shipment_ids'] = array();
553 if ($topic == null || ! $topic || Tools::strlen($topic) < 1 || $topic == 'payment') {
554 $payment_info = MPClassTK::get_payment_info($mp_op_id);
555 if ($payment_info === null) {
556 if ($data_payment_obj !== null) {
557 $payment_info = (array) Tools::jsonDecode($data_payment_obj, true);
558 UKijam::log('DATAOBJ-JSON1-validateMercadoPago[' . $mp_op_id . ']->get_payment_info:
559 ' . $data_payment_obj . UKijam::pL($payment_info, true));
560 }
561 if (! $payment_info || ! isset($payment_info['id']) || empty($payment_info['id'])) {
562 UKijam::log('NULL-validateMercadoPago[' . $mp_op_id . ']->get_payment_info 1');
563 return false;
564 }
565 } else {
566 $payment_info = $payment_info->toArray();
567 $data_payment_obj = (string) Tools::jsonEncode($payment_info);
568 $payment_info = (array) Tools::jsonDecode($data_payment_obj, true);
569 }
570 $payment_info = UKijam::fixPaymentInfo($payment_info);
571 UKijam::log('validateMercadoPago[' . $mp_op_id . ']->get_payment_info:
572 ' . UKijam::pL($payment_info, true));
573 if (isset($payment_info['merchant_order_id'])) {
574 $moid = $payment_info['merchant_order_id'];
575 $merchant_order_info = MPClassTK::get_merchant_order($moid);
576 if ($merchant_order_info === null) {
577 UKijam::log('NULL-validateMercadoPago[' . $mp_op_id . ',' . $moid . ']->get_merchant_order');
578 return false;
579 }
580 $merchant_order_info = $merchant_order_info->toArray();
581 $merchant_order_info = (string) Tools::jsonEncode($merchant_order_info);
582 $merchant_order_info = (array) Tools::jsonDecode($merchant_order_info, true);
583 }
584 UKijam::log('validateMercadoPago[' . $mp_op_id . ']->get_merchant_order:
585 ' . UKijam::pL($merchant_order_info, true));
586 } else {
587 $merchant_order_info = MPClassTK::get_merchant_order($mp_op_id);
588 if ($merchant_order_info === null) {
589 UKijam::log('NULL-validateMercadoPago[' . $mp_op_id . ']->get_merchant_order');
590 return false;
591 }
592 $merchant_order_info = $merchant_order_info->toArray();
593 $merchant_order_info = (string) Tools::jsonEncode($merchant_order_info);
594 $merchant_order_info = (array) Tools::jsonDecode($merchant_order_info, true);
595 }
596 if (isset($merchant_order_info['total_amount'])) {
597 if (isset($merchant_order_info['shipments'])) {
598 if (is_array($merchant_order_info['shipments']) && count($merchant_order_info['shipments']) > 0) {
599 foreach ($merchant_order_info['shipments'] as $shipping) {
600 $shipping_info = $shipping;
601 $ret['shipment_ids'][] = $shipping['id'];
602 }
603 }
604 }
605 $payment_pending = false;
606 $payment_refunded = false;
607 $with_ok = false;
608 foreach ($merchant_order_info['payments'] as &$payment) {
609 $pstatus = $payment['status'];
610 if (! $last_payment_id) {
611 $last_payment_id = $payment['id'];
612 }
613 if (in_array($pstatus, array(
614 'approved',
615 'refunded',
616 'authorized',
617 'pending',
618 'in_process'
619 ))) {
620 $payment_info = MPClassTK::get_payment_info($payment['id']);
621 if ($payment_info === null) {
622 UKijam::log('NULL-validateMercadoPago[' . $payment['id'] . ']->get_payment_info 2.0');
623 $payment_info = $payment;
624 } else {
625 $payment_info = $payment_info->toArray();
626 $payment_info = (string) Tools::jsonEncode($payment_info);
627 $payment_info = (array) Tools::jsonDecode($payment_info, true);
628 }
629 $payment_info = UKijam::fixPaymentInfo($payment_info);
630 $payment = $payment_info;
631 UKijam::log('validateMercadoPago[' . $payment['id'] . ']->get_payment_info 2.0:
632 ' . UKijam::pL($payment_info, true));
633 }
634 $pstatus = $payment['status'];
635 if (in_array($pstatus, array(
636 'approved',
637 'authorized'
638 ))) {
639 $with_ok = $payment_info;
640 }
641 if (in_array($pstatus, array(
642 'approved',
643 'refunded',
644 'authorized',
645 'in_process'
646 ))) {
647 if (isset($payment['shipping_cost'])) {
648 $paid_amount += $payment['transaction_amount'] + $payment['shipping_cost'];
649 } else {
650 $paid_amount += $payment['transaction_amount'];
651 }
652 $commision_amount += $payment['total_paid_amount'] - $payment['net_received_amount'];
653 }
654 if ($payment['status'] == 'pending' || $payment['status'] == 'in_process') {
655 $payment_pending = true;
656 }
657 if ($payment['status'] == 'refunded') {
658 $payment_refunded = true;
659 }
660 }
661 if ($with_ok) {
662 $payment_info = $with_ok;
663 }
664 if ($payment_pending && $with_ok) {
665 $payment_pending = false;
666 }
667 if ($shipping_info) {
668 if ($shipping_info['shipping_mode'] == 'me2') {
669 $merchant_order_info['shipping_cost'] = $shipping_info['shipping_option']['cost'];
670 }
671 }
672 $scost = isset($merchant_order_info['shipping_cost']) ? $merchant_order_info['shipping_cost'] : 0;
673 $diff = abs($paid_amount - ($merchant_order_info['total_amount'] + $scost));
674 UKijam::log("paid_amount: $diff ===>>> $paid_amount <> {$merchant_order_info['total_amount']} + $scost");
675 if (! $payment_refunded && ! $payment_pending && $diff < 1.5) {
676 $status_act = Configuration::get($this->config['os_authorization']);
677 UKijam::log('OK --> paid_amount');
678 } elseif (! $payment_refunded && ! $payment_pending && $paid_amount < 0.01) {
679 UKijam::log('ERROR --> paid_amount');
680 $status_act = $this->config['os_refused'];
681 } elseif (! $payment_refunded) {
682 UKijam::log('ERROR --> paid pending --> ' . $payment_pending . ' <-> ' . $paid_amount);
683 $status_act = $this->os_pending;
684 } else {
685 $status_act = Configuration::get('PS_OS_REFUND');
686 }
687 }
688 $data_payment_obj = (string) Tools::jsonEncode($payment_info);
689 UKijam::log('validateMercadoPago[' . $mp_op_id . ']->get_merchant_order:
690 ' . UKijam::pL($merchant_order_info, true));
691 if (! $status_act && ! $payment_info) {
692 return false;
693 } elseif (! $status_act) {
694 if (! isset($payment_info['status'])) {
695 return false;
696 } else {
697 switch ($payment_info['status']) {
698 case 'approved':
699 case 'authorized':
700 $status_act = $this->config['os_authorization'];
701 break;
702 case 'refunded':
703 $status_act = Configuration::get('PS_OS_REFUND');
704 break;
705 case 'cancelled':
706 case 'rejected':
707 $status_act = $this->config['os_refused'];
708 break;
709 default:
710 $status_act = $this->os_pending;
711 break;
712 }
713 }
714 }
715
716 $ref = false;
717 if (isset($merchant_order_info['external_reference'])) {
718 $ref = $merchant_order_info['external_reference'];
719 } else {
720 $ret['pref_id'] = false;
721 if (isset($payment_info['transaction_details'])) {
722 $payment_info = array_merge($payment_info, $payment_info['transaction_details']);
723 }
724 $ref = $payment_info['external_reference'];
725 }
726 $pre_check = explode('-', $ref);
727 $sufix_fee = '';
728 if (count($pre_check) == 3) {
729 $sufix_fee = '_custom';
730 } elseif (count($pre_check) < 2) {
731 $sufix_fee = '_qr';
732 }
733 $fee = ((float) $this->config['fee' . $sufix_fee]) / 100.0;
734 $famount = (float) $this->config['fee_amount' . $sufix_fee];
735 if (isset($merchant_order_info['external_reference'])) {
736 $ret['pref_id'] = $merchant_order_info['preference_id'];
737 $ret['shipping'] = isset($merchant_order_info['shipping_cost']) ? $merchant_order_info['shipping_cost'] : 0;
738 $ret['fee'] = (float) ($merchant_order_info['total_amount'] + $ret['shipping'] - $famount) * $fee + $famount;
739 $ret['price'] = (float) $merchant_order_info['total_amount'] + $ret['shipping'] - $ret['fee'];
740 $ret['price_with_fee'] = (float) $merchant_order_info['total_amount'] + $ret['shipping'];
741 $ret['price_without_shipping'] = (float) $merchant_order_info['total_amount'] - $ret['fee'];
742 $ret['mp_op_id'] = $payment_info['id'];
743 $ret['mp_order_id'] = $merchant_order_info['id'];
744 $ret['order_id'] = $merchant_order_info['external_reference'];
745 $scost = isset($merchant_order_info['shipping_cost']) ? $merchant_order_info['shipping_cost'] : 0;
746 $ret['paid_amount_expected'] = $merchant_order_info['total_amount'] + $scost;
747 } else {
748 $total_paid_amount = (float) $payment_info['transaction_amount'];
749 $ret['fee'] = (float) ($total_paid_amount - (float) $famount) * $fee + (float) $famount;
750 $ret['price_with_fee'] = (float) $total_paid_amount;
751 $ret['price'] = (float) $total_paid_amount - (float) $ret['fee'];
752 $ret['shipping'] = isset($payment_info['shipping_cost']) ? (float) $payment_info['shipping_cost'] : 0;
753 $ret['price_without_shipping'] = $ret['price'] - $ret['shipping'];
754 $ret['mp_op_id'] = $payment_info['id'];
755 $ret['order_id'] = $payment_info['external_reference'];
756 $ret['paid_amount_expected'] = 0;
757 }
758 if (isset($payment_info['payer']) && isset($payment_info['payer']['identification']) && isset($payment_info['payer']['identification']['number']) && ! empty($payment_info['payer']['identification']['number'])) {
759 $ret['identification'] = $payment_info['payer']['identification']['type'];
760 $ret['identification'] .= ' ' . $payment_info['payer']['identification']['number'];
761 } else {
762 if (isset($payment_info['cardholder']) && isset($payment_info['cardholder']['identification']) && isset($payment_info['cardholder']['identification']['number']) && ! empty($payment_info['cardholder']['identification']['number'])) {
763 $ret['identification'] = $payment_info['cardholder']['identification']['type'];
764 $ret['identification'] .= ' ' . $payment_info['cardholder']['identification']['number'];
765 } else {
766 if (isset($payment_info['card']) && isset($payment_info['card']['cardholder']) && isset($payment_info['card']['cardholder']['identification']) && isset($payment_info['card']['cardholder']['identification']['number']) && ! empty($payment_info['card']['cardholder']['identification']['number'])) {
767 $ret['identification'] = $payment_info['card']['cardholder']['identification']['type'];
768 $ret['identification'] .= ' ' . $payment_info['card']['cardholder']['identification']['number'];
769 } else {
770 $ret['identification'] = $this->l('Not available');
771 }
772 }
773 }
774 if (isset($payment_info['payer']) && isset($payment_info['payer']['first_name'])) {
775 $ret['client_name'] = trim($payment_info['payer']['first_name'] . ' ' . $payment_info['payer']['last_name']);
776 } else {
777 $ret['client_name'] = $this->l('Not available');
778 }
779 $ret['transaction_id'] = $payment_info['id'];
780 $ret['last_four_digits'] = false;
781 $ret['cardholder_name'] = false;
782 $ret['card_brand'] = false;
783 if (isset($payment_info['payment_method_id']) && ! empty($payment_info['payment_method_id'])) {
784 $ret['card_brand'] = Tools::ucfirst($payment_info['payment_method_id']);
785 } elseif (isset($payment_info['payment_type'])) {
786 $ret['card_brand'] = Tools::ucfirst(str_replace('_', ' ', $payment_info['payment_type']));
787 }
788 if (isset($payment_info['card'])) {
789 if (isset($payment_info['card']['first_six_digits']) && ! empty($payment_info['card']['first_six_digits'])) {
790 $ret['first_six_digits'] = '******';
791 }
792 if (isset($payment_info['card']['last_four_digits']) && ! empty($payment_info['card']['last_four_digits'])) {
793 $ret['last_four_digits'] = ' ****** ' . $payment_info['card']['last_four_digits'];
794 }
795 if (isset($payment_info['card']['cardholder']) && isset($payment_info['card']['cardholder']['name']) && ! empty($payment_info['card']['cardholder']['name'])) {
796 $ret['cardholder_name'] = Tools::strtoupper($payment_info['card']['cardholder']['name']);
797 }
798 if ($ret['cardholder_name'] && $ret['client_name'] == $this->l('Not available')) {
799 $ret['client_name'] = $ret['cardholder_name'];
800 }
801 }
802 if (isset($payment_info['last_four_digits']) && ! empty($payment_info['last_four_digits'])) {
803 $ret['last_four_digits'] = '******** **** ' . $payment_info['last_four_digits'];
804 }
805 if (isset($payment_info['cardholder']) && isset($payment_info['cardholder']['name']) && ! empty($payment_info['cardholder']['name'])) {
806 $ret['cardholder_name'] = Tools::strtoupper($payment_info['cardholder']['name']);
807 }
808 $ret['total'] = $ret['price_with_fee'];
809 if ($shipping_info) {
810 if ($shipping_info['shipping_mode'] == 'me2') {
811 switch ($shipping_info['status']) {
812 case 'pending':
813 case 'handling':
814 case 'ready_to_ship':
815 case 'not_delivered':
816 case 'cancelled':
817 UKijam::log('Shipping status: ' . $shipping_info['status']);
818 break;
819 case 'shipped':
820 UKijam::log('Shipping status: shipped');
821 if ($status_act == $this->config['os_authorization']) {
822 $status_act = Configuration::get('PS_OS_SHIPPING');
823 }
824 break;
825 case 'delivered':
826 UKijam::log('Shipping status: delivered');
827 if ($status_act == $this->config['os_authorization']) {
828 $status_act = Configuration::get('PS_OS_DELIVERED');
829 }
830 break;
831 }
832 }
833 }
834 $ret['status'] = (int) $status_act;
835 $ret['paid_amount'] = $paid_amount;
836 $ret['commision_amount'] = $commision_amount;
837 $ret['is_mp_envios'] = $shipping_info ? true : false;
838 $ret['sandbox'] = $is_sandbox;
839 $ret['currency_id'] = $payment_info['currency_id'];
840 $ret['message1'] = Tools::jsonEncode($merchant_order_info);
841 $ret['message2'] = Tools::jsonEncode($payment_info);
842 if (empty($ret['currency_id']) || ($ret['paid_amount'] > 0 && $ret['paid_amount_expected'] > 0 && abs($ret['paid_amount_expected'] - $ret['paid_amount']) > 0.1)) {
843 UKijam::log('validateMercadoPago[' . $mp_op_id . ']->return
844 ERROR - CURRENCY ID EMPTY OR PAYMENT EXPECTED INVALID --->> ' . UKijam::pL($ret, true));
845 $ret_f = array(
846 'mp_op_id' => $last_payment_id,
847 'transaction_id' => $last_payment_id,
848 'total' => $ret['total'],
849 'mp_order_id' => $ret['mp_order_id']
850 );
851 return $ret_f;
852 }
853 UKijam::log('validateMercadoPago[' . $mp_op_id . ']->return: ' . UKijam::pL($ret, true));
854 return $ret;
855 }
856
857 public function hookDisplayPDFInvoice($params)
858 {
859 $order_invoice = $params['object'];
860 $order = new Order((int) $order_invoice->id_order);
861 $valid = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
862 SELECT * FROM `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
863 WHERE `id_order` = ' . (int) $order->id);
864
865 UKijam::log('hookDisplayPDFInvoice-valid: ' . UKijam::pL($valid, true));
866 if (isset($valid[0])) {
867 $valid = $valid[0];
868 }
869 if (! $valid || ! isset($valid['mp_op_id'])) {
870 return '';
871 }
872 $result = $this->validateMercadoPago($valid['topic'], $valid['mp_op_id']);
873 if ($result && isset($result['status'])) {
874 $currency = new Currency((int) $order->id_currency);
875 $total_price = 0;
876 // if ($result['is_mp_envios']) {
877 // $total_price = $order->total_paid_tax_incl - $order->total_shipping_tax_incl;
878 // } else {
879 $total_price = $order->total_paid_tax_incl;
880 // }
881 $diff = abs($total_price - UKijam::getRate(Tools::strtoupper($result['currency_id']), Tools::strtoupper($currency->iso_code)) * $result['price_with_fee']);
882 $same_cur = Tools::strtoupper($result['currency_id']) == Tools::strtoupper($currency->iso_code);
883 if ($same_cur && $diff > $total_price * 0.01 || ! $same_cur && $diff > $total_price * 0.03) {
884 return $this->instance_module->lang('Commission charge a customer for using MercadoPago:') . '
885 ' . Tools::displayPrice($diff, $currency);
886 }
887 }
888 return '';
889 }
890
891 public function getLabelsUrl($order_id, $validation, $file_template, $force_download = false, $only_valid_labels = false)
892 {
893 $url_labels = array();
894 if (isset($validation['shipment_ids']) && count($validation['shipment_ids']) > 0) {
895 foreach ($validation['shipment_ids'] as $shipping_id) {
896 $result = false;
897 if (! isset($this->config['create_manual_label'])) {
898 $this->config['create_manual_label'] = false;
899 }
900 $url = $this->readPDFMercadoEnvios($shipping_id, $order_id, $result, ! $force_download && (bool) $this->config['create_manual_label']);
901 if ($result) {
902 $link_tpl = $this->instance_module->display($file_template, 'views/templates/admin/link.tpl');
903 $url_labels[] = sprintf($link_tpl, $url, $this->l('Download'));
904 } else {
905 if (! $only_valid_labels) {
906 $url_labels[] = $url;
907 }
908 }
909 }
910 }
911 return $url_labels;
912 }
913
914 public function hookDisplayAdminOrder($params, $file_template)
915 {
916 $order_id = (int) $params['id_order'];
917 $valid = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
918 SELECT * FROM `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
919 WHERE `id_order` = ' . (int) $order_id);
920
921 UKijam::log('hookDisplayAdminOrder-valid: ' . UKijam::pL($valid, true));
922
923 if (isset($valid[0])) {
924 $valid = $valid[0];
925 }
926 if (! $valid || ! isset($valid['mp_op_id']) || empty($valid['mp_op_id'])) {
927 return false;
928 }
929 $has_refund = Db::getInstance()->ExecuteS('SELECT *
930 FROM `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '_refunds`
931 WHERE `id_order` = ' . (int) $order_id);
932
933 UKijam::log('hookDisplayAdminOrder-has_refund: ' . UKijam::pL($has_refund, true));
934
935 if (isset($has_refund[0])) {
936 $has_refund = $has_refund[0];
937 }
938 $order = new Order($params['id_order']);
939 $validation = $this->validateMercadoPago($valid['topic'], $valid['mp_op_id'], $valid['payment_obj']);
940 if ($validation && isset($validation['status'])) {
941 UKijam::log('hookDisplayAdminOrder-validation: ' . UKijam::pL($validation, true));
942 $cancel_status = array(
943 (int) Configuration::get('PS_OS_REFUND'),
944 (int) Configuration::get('PS_OS_CANCELED'),
945 (int) Configuration::get('PS_OS_OUTOFSTOCK_PAID'),
946 (int) Configuration::get('PS_OS_ERROR'),
947 (int) Configuration::get('PS_OS_DELIVERED')
948 );
949 $status_act = $order->getCurrentState();
950 if (in_array($status_act, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && $status_act != $validation['status'] && ! in_array($status_act, $cancel_status)) {
951 self::$ignore_update_status = true;
952 $order->setCurrentState($validation['status']);
953 self::$ignore_update_status = false;
954 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
955 SET
956 `next_retry` = ' . (int) (time() + 6 * 60 * 60) . ',
957 `status` = ' . (int) $order->getCurrentState() . '
958 WHERE id = ' . (int) $valid['id']);
959 }
960 }
961 if ($validation && isset($validation['transaction_id']) && Validate::isLoadedObject($order)) {
962 $order_payments = $order->getOrderPayments();
963 foreach ($order_payments as $order_payment) {
964 $order_payment->transaction_id = $validation['transaction_id'];
965 if ($validation['last_four_digits'] && ! empty($validation['last_four_digits'])) {
966 $order_payment->card_number = $validation['last_four_digits'];
967 }
968 if ($validation['card_brand'] && ! empty($validation['card_brand'])) {
969 $order_payment->card_brand = $validation['card_brand'];
970 }
971 if ($validation['cardholder_name'] && ! empty($validation['cardholder_name'])) {
972 $order_payment->card_holder = $validation['cardholder_name'];
973 }
974 $order_payment->save();
975 }
976 $updated = array();
977 if (! empty($validation['transaction_id'])) {
978 $updated[] = '`mp_payment_id` = \'' . pSQL($validation['transaction_id']) . '\'';
979 }
980 if (! empty($validation['mp_order_id'])) {
981 $updated[] = '`mp_order_id` = \'' . pSQL($validation['mp_order_id']) . '\'';
982 }
983 if (! empty($validation['last_four_digits'])) {
984 $updated[] = '`mp_card_number` = \'' . pSQL($validation['last_four_digits']) . '\'';
985 }
986 if (! empty($validation['card_brand'])) {
987 $updated[] = '`mp_card_brand` = \'' . pSQL($validation['card_brand']) . '\'';
988 }
989 if (! empty($validation['cardholder_name'])) {
990 $updated[] = '`mp_card_holder` = \'' . pSQL($validation['cardholder_name']) . '\'';
991 }
992 if (! empty($validation['client_name'])) {
993 $updated[] = '`mp_payer_name` = \'' . pSQL($validation['client_name']) . '\'';
994 }
995 if (! empty($validation['identification'])) {
996 $updated[] = '`mp_payer_dni` = \'' . pSQL($validation['identification']) . '\'';
997 }
998 if (! empty($validation['total'])) {
999 $updated[] = '`mp_total_amount` = \'' . pSQL($validation['total']) . '\'';
1000 }
1001 if (! empty($validation['commision_amount'])) {
1002 $updated[] = '`mp_total_commision` = \'' . pSQL($validation['commision_amount']) . '\'';
1003 }
1004 if (count($updated) > 0 && (int) $order_id > 0) {
1005 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1006 SET
1007 ' . implode(', ', $updated) . '
1008 WHERE id_order = ' . (int) $order_id);
1009 }
1010 }
1011 $order_state = new OrderState($valid['status']);
1012 $url_labels = $this->getLabelsUrl($order_id, $validation, $file_template, Tools::isSubmit('generate_label'));
1013 if (Tools::isSubmit('mp_tracking_code') && Tools::getValue('mp_tracking_code') != '') {
1014 $this->setTrackingOrder(Tools::getValue('mp_tracking_code'), Tools::getValue('mp_courier_url'), $order);
1015 $manual_tracking = UKijam::setCache('manual_tracking_' . $order_id, 'ready');
1016 }
1017 $manual_tracking = UKijam::getCache('manual_tracking_' . $order_id);
1018 return array(
1019 'order_id' => $order_id,
1020 'mp_data' => $valid,
1021 'manual_tracking' => $manual_tracking,
1022 'mp_country' => $this->site_id,
1023 'mercadoenvios_available' => $this->mercadoenvios_available,
1024 'mp_validation' => $validation,
1025 'is_sandbox' => $valid && $valid['is_sandbox'] ? $this->l('Yes') : $this->l('No'),
1026 'mp_label_shipping' => is_array($url_labels) && count($url_labels) > 0 ? $url_labels : false,
1027 'has_refund' => $has_refund,
1028 'mp_last_sync' => date('Y-m-d H:i:s', $valid['next_retry'] - 6 * 60 * 60),
1029 'mp_status' => $order_state->name[$this->context->language->id]
1030 );
1031 }
1032
1033 public function hookOrderConfirmation($order)
1034 {
1035 $cart = new Cart((int) $order->id_cart);
1036 $btn = $this->getPaymentButton($cart, $order);
1037 $mptools_error = false;
1038 $show_modal = false;
1039 if (Tools::isSubmit('mpqr_voucher')) {
1040 $is_ok = $this->checkResponseMP($cart->id, $order->id, Tools::getValue('mpqr_voucher'), false, '_qr');
1041 if (! $is_ok || $is_ok['error']) {
1042 $mptools_error = $is_ok['error_str'];
1043 }
1044 }
1045 if (Tools::getValue('payment_type') == 'basic') {
1046 $mp_init_point = Db::getInstance()->getValue('
1047 SELECT `mp_init_point`
1048 FROM `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1049 WHERE `id_order` = ' . (int) $order->id);
1050 if ($mp_init_point && ! empty($mp_init_point)) {
1051 $show_modal = $mp_init_point;
1052 }
1053 }
1054 $order = new Order($order->id);
1055 $status_act = $order->getCurrentState();
1056 switch ($status_act) {
1057 case $this->config['os_authorization']:
1058 case Configuration::get('PS_OS_PREPARATION'):
1059 case Configuration::get('PS_OS_SHIPPING'):
1060 $result = array(
1061 'status' => 'ok',
1062 'show_modal' => false,
1063 'id_order' => $order->id
1064 );
1065 break;
1066 case $this->os_pending:
1067 case $this->os_wait_payment:
1068 case Configuration::get('PS_OS_OUTOFSTOCK'):
1069 $result = array(
1070 'status' => 'pending',
1071 'show_modal' => $show_modal,
1072 'id_order' => $order->id
1073 );
1074 break;
1075 default:
1076 $result = array(
1077 'show_modal' => false,
1078 'status' => 'failed'
1079 );
1080 break;
1081 }
1082 $result['mptools_error'] = $mptools_error;
1083 $mp_op_id = (int) Db::getInstance()->getValue('SELECT `mp_op_id` FROM
1084 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1085 WHERE `id_order` > 0 AND`id_order` = ' . (int) $order->id . ' OR ' . '`id_cart` > 0 AND`id_cart` = ' . (int) $cart->id);
1086 $result['show_qr'] = false;
1087 if (Tools::getValue('payment_type') == 'qr' && (! $mp_op_id || empty($mp_op_id))) {
1088 $result['show_qr'] = true;
1089 }
1090 $result['shop_name'] = '';
1091 $result = array_merge($btn, $result);
1092 return $result;
1093 }
1094
1095 public function cronjob($smarty, $file_template)
1096 {
1097 if (! $this->verifyMercadoPago()) {
1098 return;
1099 }
1100 $rand_mutex = rand();
1101 $mutex = new MpMutex(dirname(__FILE__) . '/mpk_validation');
1102 UKijam::log('cronjob-[' . $rand_mutex . ']: init lock');
1103 while (! $mutex->lock()) {
1104 sleep(.5);
1105 }
1106 $valid = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
1107 SELECT * FROM `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1108 WHERE `next_retry` < ' . (int) time() . ' AND
1109 (`status` = ' . (int) $this->os_pending . '
1110 OR
1111 `status` = ' . (int) $this->os_wait_payment . '
1112 OR
1113 `status` = ' . (int) Configuration::get('PS_OS_OUTOFSTOCK') . '
1114 OR
1115 `status` = ' . (int) Configuration::get('PS_OS_OUTOFSTOCK_UNPAID') . '
1116 OR
1117 (`is_mercadoenvios` > 0 AND `status` = ' . (int) $this->config['os_authorization'] . ')
1118 OR
1119 `status` = ' . (int) Configuration::get('PS_OS_PREPARATION') . '
1120 OR
1121 `status` = ' . (int) Configuration::get('PS_OS_SHIPPING') . ') ORDER BY id_order ASC LIMIT 3');
1122 $cancel_status = array(
1123 (int) Configuration::get('PS_OS_CANCELED'),
1124 // (int)Configuration::get('PS_OS_DELIVERED'),
1125 (int) Configuration::get('PS_OS_REFUND')
1126 // (int)Configuration::get('PS_OS_OUTOFSTOCK'),
1127 // (int)Configuration::get('PS_OS_OUTOFSTOCK_PAID'),
1128 // (int)Configuration::get('PS_OS_OUTOFSTOCK_UNPAID'),
1129 );
1130 foreach ($valid as &$pago) {
1131 UKijam::log('cronjob-[' . $rand_mutex . ']: checking: ' . UKijam::pL($pago, true));
1132 $order = new Order($pago['id_order']);
1133 if (Validate::isLoadedObject($order)) {
1134 if (empty($pago['mp_op_id']) || ! $pago['mp_op_id']) {
1135 UKijam::log('cronjob-[' . $rand_mutex . ']: expired');
1136 self::$ignore_update_status = true;
1137 $order->setCurrentState((int) Configuration::get('PS_OS_CANCELED'));
1138 self::$ignore_update_status = false;
1139 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1140 SET
1141 `next_retry` = ' . (int) (time() + 6 * 60 * 60) . ',
1142 `status` = ' . (int) Configuration::get('PS_OS_CANCELED') . '
1143 WHERE id = ' . (int) $pago['id']);
1144 // $order->delete();
1145 continue;
1146 }
1147 $status_act = $order->getCurrentState();
1148 if (! in_array($status_act, $cancel_status) && $status_act == $pago['status']) {
1149 $result = $this->validateMercadoPago($pago['topic'], $pago['mp_op_id']);
1150 if (in_array($status_act, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && isset($result['status'])) {
1151 if ($result['status'] != $order->getCurrentState()) {
1152 UKijam::log('cronjob-[' . $rand_mutex . ']: status updated:
1153 from ' . $order->getCurrentState() . ' to ' . $result['status']);
1154 self::$ignore_update_status = true;
1155 $order->setCurrentState($result['status']);
1156 self::$ignore_update_status = false;
1157 $status_act = $order->getCurrentState();
1158 } else {
1159 UKijam::log('cronjob-[' . $rand_mutex . ']: status without changes');
1160 }
1161 } else {
1162 UKijam::log('cronjob-[' . $rand_mutex . ']: API without status');
1163 }
1164 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1165 SET
1166 `next_retry` = ' . (int) (time() + 6 * 60 * 60) . ',
1167 `status` = ' . (int) $status_act . '
1168 WHERE id = ' . (int) $pago['id']);
1169 } else {
1170 UKijam::log('cronjob-[' . $rand_mutex . ']: order handled by user');
1171 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1172 SET
1173 `next_retry` = ' . (int) (time() + 6 * 60 * 60) . ',
1174 `status` = ' . (int) Configuration::get('PS_OS_DELIVERED') . '
1175 WHERE id = ' . (int) $pago['id']);
1176 }
1177 } else {
1178 UKijam::log('cronjob-[' . $rand_mutex . ']: order deleted by user');
1179 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1180 SET
1181 `next_retry` = ' . (int) (time() + 6 * 60 * 60) . ',
1182 `status` = ' . (int) Configuration::get('PS_OS_CANCELED') . '
1183 WHERE id = ' . (int) $pago['id']);
1184 }
1185 }
1186 UKijam::log('cronjob-[' . $rand_mutex . ']: releaseLock');
1187 $mutex->releaseLock();
1188 $ps_version = 1.6;
1189 if (version_compare(_PS_VERSION_, '1.6') < 0) {
1190 $ps_version = 1.5;
1191 }
1192 if (version_compare(_PS_VERSION_, '1.7.0.0') >= 0) {
1193 $ps_version = 1.7;
1194 }
1195 if (isset($this->config['publickey']) && $this->config['publickey'] != "") {
1196 $smarty->assign('publickey', $this->config['publickey']);
1197 } else {
1198 if (isset($this->config['publickey_installment']) && $this->config['publickey_installment'] != "") {
1199 $smarty->assign('publickey', $this->config['publickey_installment']);
1200 } else {
1201 $smarty->assign('publickey', false);
1202 }
1203 }
1204 $smarty->assign('ps_version', $ps_version);
1205 return $this->instance_module->display($file_template, 'views/templates/hook/cronjob.tpl');
1206 }
1207
1208 public function hookUpdateOrderStatus($params)
1209 {
1210 if (! $this->verifyMercadoPago() || self::$ignore_update_status) {
1211 return '';
1212 }
1213 UKijam::log('hookUpdateOrderStatus:
1214 ' . UKijam::pL($params, true) . UKijam::pL($this->config['status_refound'], true));
1215 if (in_array((int) $params['newOrderStatus']->id, $this->config['status_refound'])) {
1216 $id_order = $params['id_order'];
1217 $has_mp_order = Db::getInstance()->ExecuteS('SELECT *
1218 FROM `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1219 WHERE `id_order` = ' . (int) $id_order);
1220 UKijam::log('hookUpdateOrderStatus: checking: ' . UKijam::pL($has_mp_order, true));
1221 if ($has_mp_order && isset($has_mp_order[0])) {
1222 $has_mp_order = $has_mp_order[0];
1223 $has_refund = Db::getInstance()->ExecuteS('SELECT *
1224 FROM `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '_refunds`
1225 WHERE `id_order` = ' . (int) $id_order);
1226 UKijam::log('hookUpdateOrderStatus: has_refund: ' . UKijam::pL($has_refund, true));
1227 if (! $has_refund) {
1228 $payment = $this->validateMercadoPago($has_mp_order['topic'], $has_mp_order['mp_op_id']);
1229 UKijam::log('hookUpdateOrderStatus: status: ' . UKijam::pL($payment['status'], true));
1230 switch (isset($payment['status']) ? (int) $payment['status'] : - 1) {
1231 case (int) $this->config['os_authorization']:
1232 case (int) $this->os_pending:
1233 case (int) $this->config['os_refused']:
1234 case (int) Configuration::get('PS_OS_CANCELED'):
1235 case (int) Configuration::get('PS_OS_DELIVERED'):
1236 case (int) Configuration::get('PS_OS_PREPARATION'):
1237 case (int) Configuration::get('PS_OS_SHIPPING'):
1238 try {
1239 $result = MPClassTK::refund_payment($payment['mp_op_id']);
1240 if (! $result) {
1241 UKijam::log('ERROR-refund_payment: ' . UKijam::pL($result, true));
1242 return '';
1243 }
1244 UKijam::log('OK-refund_payment: ' . UKijam::pL($result, true));
1245 Db::getInstance()->Execute('INSERT IGNORE INTO
1246 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '_refunds`
1247 (id_order, mp_op_id, date_create, response) VALUES
1248 ( ' . (int) $id_order . ',
1249 \'' . pSQL($has_mp_order['mp_op_id']) . '\',
1250 NOW(),
1251 \'' . pSQL(Tools::jsonEncode($result)) . '\'
1252 )');
1253 UKijam::log('refund_payment: ' . UKijam::pL($has_mp_order, true) . ' ->
1254 ' . UKijam::pL($result, true));
1255 } catch (Exception $e) {
1256 UKijam::log('Refound error: ' . UKijam::pL($has_mp_order, true) . ' ->
1257 ' . $e->getFile() . "[" . $e->getLine() . "] -> " . $e->getMessage());
1258 }
1259 break;
1260 default:
1261 UKijam::log('hookUpdateOrderStatus: invalid status: ' . UKijam::pL($payment['status'], true));
1262 UKijam::log('hookUpdateOrderStatus: os_authorization: ' . $this->config['os_authorization']);
1263 UKijam::log('hookUpdateOrderStatus: os_pending: ' . $this->os_pending);
1264 UKijam::log('hookUpdateOrderStatus: os_refused: ' . $this->config['os_refused']);
1265 UKijam::log('hookUpdateOrderStatus: os_canceled: ' . Configuration::get('PS_OS_CANCELED'));
1266 UKijam::log('hookUpdateOrderStatus: os_delivered: ' . Configuration::get('PS_OS_DELIVERED'));
1267 UKijam::log('hookUpdateOrderStatus: os_preparat: ' . Configuration::get('PS_OS_PREPARATION'));
1268 UKijam::log('hookUpdateOrderStatus: os_shipping: ' . Configuration::get('PS_OS_SHIPPING'));
1269 return '';
1270 }
1271 }
1272 }
1273 }
1274 return '';
1275 }
1276
1277 public function checkResponseMP($id_cart, $id_order, $id_mp_order, $data_payment_obj = null, $sufix_fee = '')
1278 {
1279 // die(var_export($data_payment_obj, true));
1280 if (! $id_mp_order || empty($id_mp_order)) {
1281 return array(
1282 'error' => true,
1283 'error_str' => $this->l('The voucher number is required')
1284 );
1285 }
1286 $check_id_cart = (int) Db::getInstance()->getValue('SELECT `id_cart` FROM
1287 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1288 WHERE `mp_op_id` = \'' . pSQL($id_mp_order) . '\'');
1289 if ($check_id_cart && $id_cart && $check_id_cart != $id_cart) {
1290 return array(
1291 'error' => true,
1292 'error_str' => $this->l('The voucher number is used by other order')
1293 );
1294 }
1295 if ($data_payment_obj === null) {
1296 $check_data_obj = (string) Db::getInstance()->getValue('SELECT `payment_obj` FROM
1297 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1298 WHERE `mp_op_id` = \'' . pSQL($id_mp_order) . '\'');
1299 if ($check_data_obj && ! empty($check_data_obj)) {
1300 $data_payment_obj = $check_data_obj;
1301 }
1302 }
1303 $check_id_order = (int) Db::getInstance()->getValue('SELECT `id_order` FROM
1304 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1305 WHERE `mp_op_id` = \'' . pSQL($id_mp_order) . '\'');
1306 if ($check_id_order && $id_order && $check_id_order != $id_order) {
1307 return array(
1308 'error' => true,
1309 'error_str' => $this->l('The voucher number is used by other cart')
1310 );
1311 }
1312 $result = $this->validateMercadoPago('payment', $id_mp_order, $data_payment_obj);
1313 $rand_mutex = rand();
1314 if (! $result || ! isset($result['status']) || ! isset($result['mp_op_id'])) {
1315 UKijam::log('validation[' . $rand_mutex . ']: Respuesta IPN Invalida');
1316 return array(
1317 'error' => true,
1318 'error_str' => $this->l('Invalid voucher number')
1319 );
1320 }
1321
1322 $mutex = new MpMutex(dirname(__FILE__) . '/mpk_validation');
1323
1324 UKijam::log('validation-[' . $rand_mutex . ']: init lock:
1325 ' . UKijam::pL($id_cart, true) . '-' . UKijam::pL($id_order, true) . '-' . $id_mp_order);
1326 while (! $mutex->lock()) {
1327 sleep(.5);
1328 }
1329
1330 UKijam::log('validation-[' . $rand_mutex . ']: locked:
1331 ' . UKijam::pL($id_cart, true) . '-' . UKijam::pL($id_order, true) . '-' . $id_mp_order);
1332
1333 if (! $id_order && $id_cart) {
1334 $id_cart = (int) $id_cart;
1335 $cart = new Cart($id_cart);
1336 if (! Validate::isLoadedObject($cart)) {
1337 UKijam::log('validation-[' . $rand_mutex . ']: unlock Invalid Cart ID');
1338 $mutex->releaseLock();
1339 return array(
1340 'error' => true,
1341 'error_str' => $this->l('Invalid cart object')
1342 );
1343 }
1344 $id_order = Order::getOrderByCartId($id_cart);
1345 if ($id_order > 0) {
1346 $result['order_id'] = $id_order;
1347 } else {
1348 $status_act = $result['status'];
1349 $customer = new Customer((int) $cart->id_customer);
1350 $currency = new Currency((int) $cart->id_currency);
1351 $context = $this->context;
1352 $context->cart = $cart;
1353 $context->cookie->id_currency = (int) $cart->id_currency;
1354 $context->customer = $customer;
1355 $context->currency = $currency;
1356 $msg = '';
1357 $original_total_price = 0;
1358 $rate_dst = UKijam::getRate(Tools::strtoupper($currency->iso_code), Tools::strtoupper($result['currency_id']));
1359 $original_total_price = Tools::ps_round($cart->getOrderTotal(true, Cart::BOTH), 2);
1360 $total_price = $original_total_price * $rate_dst;
1361 $fee = 100.0 / (100.0 - (float) $this->config['fee' . $sufix_fee]);
1362 $total = Tools::ps_round($fee * $total_price + $this->config['fee_amount' . $sufix_fee], 2);
1363 $original_total = Tools::ps_round($fee * $original_total_price + $this->config['fee_amount' . $sufix_fee], 2);
1364 $diff = abs($total - $result['price_with_fee']);
1365 $same_cur = Tools::strtoupper($result['currency_id']) == Tools::strtoupper($currency->iso_code);
1366 UKijam::log('validation-[' . $rand_mutex . ']: total-' . $id_cart . ' ' . $total_price);
1367
1368 if ($same_cur && $diff > $total * 0.01 || ! $same_cur && $diff > $total * 0.03) {
1369 $status_act = (int) Configuration::get('PS_OS_ERROR');
1370 $diff = round($diff, 2);
1371 $msg = $this->l('The amount is invalid, there is a difference:');
1372 $msg .= " {$diff} {$result['currency_id']}";
1373 return array(
1374 'error' => true,
1375 'error_str' => $msg
1376 );
1377 }
1378 if (! $same_cur) {
1379 $msg .= $this->l('Prestashop order price (currency order): ');
1380 $msg .= " {$original_total_price} {$currency->iso_code})\n\n";
1381 $msg .= $this->l('Prestashop order price with fee (currency order): ');
1382 $msg .= " {$original_total} {$currency->iso_code})\n\n";
1383 }
1384 $payed = $result['price_with_fee']; // + $result['shipping'];
1385 $msg .= $this->l('Prestashop order price: ') . " {$total_price} {$result['currency_id']}\n\n";
1386 $msg .= $this->l('Prestashop order price with fee: ') . " {$total} {$result['currency_id']}\n\n";
1387 $msg .= $this->l('Products price: ') . " {$result['price']} {$result['currency_id']}\n";
1388 $msg .= $this->l('Commission price: ') . " {$result['fee']} {$result['currency_id']}\n";
1389 if ($this->mercadoenvios_available) {
1390 $msg .= $this->l('MercadoEnvios price: ') . " {$result['shipping']} {$result['currency_id']}\n";
1391 }
1392 $msg .= $this->l('Payed: ') . " {$payed} {$result['currency_id']}\n\n";
1393 if (! $same_cur) {
1394 $msg .= ' ' . $this->l('The customer payment through');
1395 $msg .= ' ' . Tools::strtoupper($result['currency_id']);
1396 $msg .= ' ' . $this->l(', currency of the order');
1397 $msg .= ' ' . Tools::strtoupper($currency->iso_code) . '. ';
1398 $msg .= $this->l('This maybe can generate additional commissions due to currency conversions.');
1399 }
1400 UKijam::log('validation-[' . $rand_mutex . ']: validateOrder-' . $id_cart . '-init
1401 ' . Tools::getValue('topic') . Tools::getValue('id'));
1402 $name = trim($this->instance_module->displayName);
1403 self::$ignore_update_status = true;
1404 $this->instance_module->validateOrder($id_cart, $status_act, (float) $result['price'] / (float) $rate_dst,
1405 // $cart->getOrderTotal(true, Cart::BOTH),
1406 ! empty($name) ? $name : 'MercadoPago', $msg, array(), (int) $cart->id_currency, false, $customer->secure_key);
1407 $order = new Order(Order::getOrderByCartId($id_cart));
1408 $status_ps = (int) $order->getCurrentState();
1409 if (in_array($status_ps, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && $status_ps != $status_act) {
1410 $order->setCurrentState($status_act);
1411 }
1412 self::$ignore_update_status = false;
1413 $result['order_id'] = $order->id;
1414 UKijam::log('validation-[' . $rand_mutex . ']: validateOrder-' . $id_cart . '-order created
1415 ' . UKijam::pL($id_cart, true) . '-' . UKijam::pL($id_order, true) . '-' . $id_mp_order);
1416 }
1417 } else {
1418 $result['order_id'] = $id_order;
1419 }
1420 $id_order = (int) $result['order_id'];
1421 $order = new Order($id_order);
1422 if (! Validate::isLoadedObject($order)) {
1423 UKijam::log('validation-[' . $rand_mutex . ']: unlock Invalid Order ID');
1424 $mutex->releaseLock();
1425 return array(
1426 'error' => true,
1427 'error_str' => $this->l('Invalid order')
1428 );
1429 }
1430 $id_cart = (int) $order->id_cart;
1431 $cart = new Cart($id_cart);
1432 if (! Validate::isLoadedObject($cart)) {
1433 UKijam::log('validation-[' . $rand_mutex . ']: unlock Invalid Cart ID');
1434 $mutex->releaseLock();
1435 return array(
1436 'error' => true,
1437 'error_str' => $this->l('Invalid cart of order')
1438 );
1439 }
1440
1441 UKijam::log('validation-[' . $rand_mutex . ']: cart-' . $id_cart . ' order-' . $id_order . '
1442 ' . UKijam::pL($id_cart, true) . '-' . UKijam::pL($id_order, true) . '-' . $id_mp_order);
1443
1444 $status_act = $result['status'];
1445 UKijam::log('validation-[' . $rand_mutex . ']: status_act: ' . $status_act);
1446 $customer = new Customer((int) $cart->id_customer);
1447 $currency = new Currency((int) $cart->id_currency);
1448
1449 $context = $this->context;
1450 $context->cart = $cart;
1451 $context->cookie->id_currency = (int) $cart->id_currency;
1452 $context->customer = $customer;
1453 $context->currency = $currency;
1454 $status_mp = (int) Db::getInstance()->getValue('SELECT `status` FROM
1455 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1456 WHERE `id_order` = ' . (int) $id_order);
1457 UKijam::log('validation-[' . $rand_mutex . ']: status_mp: ' . $status_mp);
1458 $first_check = false;
1459 if ($status_mp < 1) {
1460 UKijam::log('validation-[' . $rand_mutex . ']: INSERT');
1461 Db::getInstance()->Execute('INSERT INTO `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1462 (
1463 id_order,
1464 id_cart,
1465 id_shop,
1466 `topic`,
1467 mp_op_id,
1468 is_sandbox,
1469 status,
1470 next_retry,
1471 is_mercadoenvios,
1472 shipping_id,
1473 order_reference,
1474 next_retry_mercadoenvios,
1475 payment_obj
1476 )
1477 VALUES
1478 (' . (int) $order->id . ', ' . (int) $cart->id . ', ' . (int) $order->id_shop . ',
1479 \'payment\',
1480 \'' . pSQL($id_mp_order) . '\',
1481 \'' . (int) $result['sandbox'] . '\',
1482 ' . (int) $order->getCurrentState() . ',
1483 ' . (int) (time() + 6 * 60 * 60) . ',
1484 0,
1485 NULL,
1486 \'' . pSQL($order->reference) . '\',
1487 ' . (int) (time() + 2 * 60) . ',
1488 \'' . pSQL(trim($result['message2'])) . '\'
1489 )');
1490 $status_mp = (int) Db::getInstance()->getValue('SELECT `status` FROM
1491 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1492 WHERE `id_order` = ' . (int) $id_order);
1493 $first_check = true;
1494 } else {
1495 $mp_op_id = (int) Db::getInstance()->getValue('SELECT `mp_order_id` FROM
1496 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1497 WHERE `id_order` = ' . (int) $id_order);
1498 if (empty($mp_op_id)) {
1499 UKijam::log('validation-[' . $rand_mutex . ']: UPDATE');
1500 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1501 SET
1502 `topic` = \'payment\',
1503 `mp_op_id` = \'' . pSQL($id_mp_order) . '\',
1504 `shipping_id` = NULL,
1505 `next_retry_mercadoenvios` = ' . (int) (time() + 2 * 60) . ',
1506 `payment_obj` = \'' . pSQL(trim($result['message2'])) . '\'
1507 WHERE id_order = ' . (int) $id_order);
1508 $first_check = true;
1509 }
1510 }
1511 $status_ps = (int) $order->getCurrentState();
1512 $cancel_status = array(
1513 (int) Configuration::get('PS_OS_CANCELED'),
1514 (int) Configuration::get('PS_OS_ERROR'),
1515 (int) Configuration::get('PS_OS_PREPARATION'),
1516 (int) Configuration::get('PS_OS_DELIVERED'),
1517 // (int)Configuration::get('PS_OS_REFUND'),
1518 (int) Configuration::get('PS_OS_OUTOFSTOCK'),
1519 (int) Configuration::get('PS_OS_OUTOFSTOCK_PAID'),
1520 (int) Configuration::get('PS_OS_OUTOFSTOCK_UNPAID')
1521 );
1522 UKijam::log('validation-[' . $rand_mutex . ']: status_ps: ' . $status_ps . ' - status_act: ' . $status_act . '
1523 - List of cancel status: ' . UKijam::pL($cancel_status, true));
1524 if ($status_ps > 0 && in_array($status_ps, $cancel_status)) {
1525 $status_act = $status_ps;
1526 } else {
1527 UKijam::log('validation-[' . $rand_mutex . ']: changing status...');
1528 if (in_array($status_ps, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && $status_act != $status_ps) {
1529 self::$ignore_update_status = true;
1530 $order->setCurrentState($status_act);
1531 self::$ignore_update_status = false;
1532 UKijam::log('validation-[' . $rand_mutex . ']: status changed!');
1533 } else {
1534 UKijam::log('validation-[' . $rand_mutex . ']: is some status.');
1535 }
1536 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1537 SET
1538 `next_retry` = ' . (int) (time() + 6 * 60 * 60) . ',
1539 `status` = ' . (int) $status_act . '
1540 WHERE id_order = ' . (int) $id_order);
1541 }
1542 if ($first_check) {
1543 UKijam::log('validation-[' . $rand_mutex . ']: first_check-' . $id_cart . '-' . $id_order . '
1544 ' . UKijam::pL($id_cart, true) . '-' . UKijam::pL($id_order, true) . '-' . $id_mp_order);
1545 $msg = '';
1546 $original_total_price = 0;
1547 $rate_dst = UKijam::getRate(Tools::strtoupper($currency->iso_code), Tools::strtoupper($result['currency_id']));
1548 // if (isset($this->list_shippings['ps_mp'][$cart->id_carrier])) {
1549 // $original_total_cart = $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING);
1550 // $original_total_price = Tools::ps_round($original_total_cart, 2);
1551 // } else {
1552 $original_total_price = Tools::ps_round($order->total_paid, 2);
1553 // $shipping_price = $order->total_shipping_tax_incl;
1554 // }
1555 $total_price = $original_total_price * $rate_dst;
1556 $fee = 100.0 / (100.0 - (float) $this->config['fee' . $sufix_fee]);
1557 $total = Tools::ps_round($fee * $total_price + $this->config['fee_amount' . $sufix_fee], 2);
1558 $original_total = Tools::ps_round($fee * $original_total_price + $this->config['fee_amount' . $sufix_fee], 2);
1559 $diff = abs($total - $result['price_with_fee']);
1560 $same_cur = Tools::strtoupper($result['currency_id']) == Tools::strtoupper($currency->iso_code);
1561 UKijam::log('validation-[' . $rand_mutex . ']: total-' . $id_cart . ' ' . $total_price);
1562
1563 if ($same_cur && $diff > $total * 0.01 || ! $same_cur && $diff > $total * 0.03) {
1564 $status_act = (int) Configuration::get('PS_OS_ERROR');
1565 $msg .= $this->l('Maybe Hacking Price (Price Diff:') . " {$diff} {$result['currency_id']})\n\n";
1566 }
1567 if (! $same_cur) {
1568 $msg .= $this->l('Prestashop order price (currency order): ');
1569 $msg .= " {$original_total_price} {$currency->iso_code})\n\n";
1570 $msg .= $this->l('Prestashop order price with fee (currency order): ');
1571 $msg .= " {$original_total} {$currency->iso_code})\n\n";
1572 }
1573 $payed = $result['price_with_fee']; // + $result['shipping'];
1574 $msg .= $this->l('Prestashop order price: ') . " {$total_price} {$result['currency_id']}\n\n";
1575 $msg .= $this->l('Prestashop order price with fee: ') . " {$total} {$result['currency_id']}\n\n";
1576 $msg .= $this->l('Products price: ') . " {$result['price']} {$result['currency_id']}\n";
1577 $msg .= $this->l('Commission price: ') . " {$result['fee']} {$result['currency_id']}\n";
1578 if ($this->mercadoenvios_available) {
1579 $msg .= $this->l('MercadoEnvios price: ') . " {$result['shipping']} {$result['currency_id']}\n";
1580 }
1581 $msg .= $this->l('Payed: ') . " {$payed} {$result['currency_id']}\n\n";
1582 if (! $same_cur) {
1583 $msg .= ' ' . $this->l('The customer payment through');
1584 $msg .= ' ' . Tools::strtoupper($result['currency_id']);
1585 $msg .= ' ' . $this->l(', currency of the order');
1586 $msg .= ' ' . Tools::strtoupper($currency->iso_code) . '. ';
1587 $msg .= $this->l('This maybe can generate additional commissions due to currency conversions.');
1588 }
1589 $message = new Message();
1590 $message->id_customer = (int) $order->id_customer;
1591 $message->message = $msg;
1592 $message->id_order = (int) $order->id;
1593 $message->id_cart = (int) $order->id_cart;
1594 $message->protected = true;
1595 $id = $message->add();
1596 UKijam::log('validation-[' . $rand_mutex . '] message[' . $id . ']: ' . UKijam::pL($message, true));
1597 self::$ignore_update_status = true;
1598 $status_ps = (int) $order->getCurrentState();
1599 if (in_array($status_ps, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && $status_ps != $status_act) {
1600 $order->setCurrentState($status_act);
1601 }
1602 self::$ignore_update_status = false;
1603 UKijam::log('validation-[' . $rand_mutex . ']: first_check-' . $id_cart . '-end
1604 ' . UKijam::pL($id_cart, true) . '-' . UKijam::pL($id_order, true) . '-' . $id_mp_order);
1605 }
1606 $order_payments = $order->getOrderPayments();
1607 foreach ($order_payments as $order_payment) {
1608 $order_payment->transaction_id = $result['transaction_id'];
1609 if ($result['last_four_digits'] && ! empty($result['last_four_digits'])) {
1610 $order_payment->card_number = $result['last_four_digits'];
1611 }
1612 if ($result['card_brand'] && ! empty($result['card_brand'])) {
1613 $order_payment->card_brand = $result['card_brand'];
1614 }
1615 if ($result['cardholder_name'] && ! empty($result['cardholder_name'])) {
1616 $order_payment->card_holder = $result['cardholder_name'];
1617 }
1618 $order_payment->save();
1619 }
1620 $updated = array();
1621 if (! empty($result['transaction_id'])) {
1622 $updated[] = '`mp_payment_id` = \'' . pSQL($result['transaction_id']) . '\'';
1623 }
1624 if (! empty($result['mp_order_id'])) {
1625 $updated[] = '`mp_order_id` = \'' . pSQL($result['mp_order_id']) . '\'';
1626 }
1627 if (! empty($result['last_four_digits'])) {
1628 $updated[] = '`mp_card_number` = \'' . pSQL($result['last_four_digits']) . '\'';
1629 }
1630 if (! empty($result['card_brand'])) {
1631 $updated[] = '`mp_card_brand` = \'' . pSQL($result['card_brand']) . '\'';
1632 }
1633 if (! empty($result['cardholder_name'])) {
1634 $updated[] = '`mp_card_holder` = \'' . pSQL($result['cardholder_name']) . '\'';
1635 }
1636 if (! empty($result['client_name'])) {
1637 $updated[] = '`mp_payer_name` = \'' . pSQL($result['client_name']) . '\'';
1638 }
1639 if (! empty($result['identification'])) {
1640 $updated[] = '`mp_payer_dni` = \'' . pSQL($result['identification']) . '\'';
1641 }
1642 if (! empty($result['total'])) {
1643 $updated[] = '`mp_total_amount` = \'' . pSQL($result['total']) . '\'';
1644 }
1645 if (! empty($result['commision_amount'])) {
1646 $updated[] = '`mp_total_commision` = \'' . pSQL($result['commision_amount']) . '\'';
1647 }
1648 if (count($updated) > 0 && (int) $id_order > 0) {
1649 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1650 SET
1651 ' . implode(', ', $updated) . '
1652 WHERE id_order = ' . (int) $id_order);
1653 }
1654 UKijam::log('validation-[' . $rand_mutex . ']: releaseLock:
1655 ' . UKijam::pL($id_cart, true) . '-' . UKijam::pL($id_order, true) . '-' . $id_mp_order);
1656 $mutex->releaseLock();
1657 return array(
1658 'error' => false
1659 );
1660 }
1661
1662 public function paymentButton16($context)
1663 {
1664 $result = $this->getPaymentButton();
1665 $payment_options = array();
1666 try {
1667 $is_mp_envios = false;
1668 if ($this->mercadoenvios_available && $this->config['shipping_active'] && isset($this->list_shippings['ps_mp'][$context->cart->id_carrier])) {
1669 $is_mp_envios = true;
1670 }
1671 $result = $this->getPaymentButton();
1672 if (! $is_mp_envios && isset($this->config['mp_qr_enable']) && $this->config['mp_qr_enable'] && isset($this->config['logo_mercadopago_checkout']) && ! empty($this->config['logo_mercadopago_checkout'])) {
1673 $context->smarty->assign($result);
1674 $context->smarty->assign('mp_name', $this->config['mp_qr_name']);
1675 if ($this->config['preorder']) {
1676 $tpl = '/views/templates/hook/mpQr.tpl';
1677 } else {
1678 $tpl = '/views/templates/hook/mpQrCart.tpl';
1679 }
1680 $payment_options[] = $context->smarty->fetch(dirname(__FILE__) . $tpl);
1681 }
1682 if (! $is_mp_envios && isset($this->config['mp_custom_enable']) && $this->config['mp_custom_enable']) {
1683 $context->smarty->assign($result);
1684 $context->smarty->assign('mp_name', $this->config['mp_custom_name']);
1685 $context->smarty->assign('publickey', $this->config['publickey']);
1686 $tpl = '/views/templates/hook/mpCustom.tpl';
1687 $payment_options[] = $context->smarty->fetch(dirname(__FILE__) . $tpl);
1688 }
1689 if ($is_mp_envios || isset($this->config['mp_basic_enable']) && $this->config['mp_basic_enable']) {
1690 $context->smarty->assign('mp_name', $this->config['mp_basic_name']);
1691 $result['is_mp_envios'] = false;
1692 if ($this->config['preorder']) {
1693 $tpl = '/views/templates/hook/mpBasic.tpl';
1694 } else {
1695 $tpl = '/views/templates/hook/mpBasicCart.tpl';
1696 $btn = $this->createInitPoint();
1697 $context->smarty->assign($btn);
1698 $result['is_mp_envios'] = $btn['is_mp_envios'];
1699 $result['init_point'] = $btn['preference'] ? $btn['preference']->init_point : false;
1700 }
1701 $context->smarty->assign($result);
1702 $payment_options[] = $context->smarty->fetch(dirname(__FILE__) . $tpl);
1703 }
1704 } catch (\Exception $e) {
1705 return $e->getFile() . "[" . $e->getLine() . "] -> " . $e->getMessage();
1706 }
1707 return implode("\n\n", $payment_options);
1708 }
1709
1710 public function paymentButton17($context)
1711 {
1712 if (! class_exists('PaymentOptionKijam')) {
1713 include_once (dirname(__FILE__) . '/paymentoption.php');
1714 }
1715 $payment_options = array();
1716 try {
1717 $is_mp_envios = false;
1718 if ($this->mercadoenvios_available && $this->config['shipping_active'] && isset($this->list_shippings['ps_mp'][$context->cart->id_carrier])) {
1719 $is_mp_envios = true;
1720 }
1721 $icon = $this->site_url . 'modules/' . $this->module_name . '/views/img/icons/' . $this->site_id . '.jpg';
1722 $result = $this->getPaymentButton();
1723 if (! $is_mp_envios && isset($this->config['mp_qr_enable']) && $this->config['mp_qr_enable'] && isset($this->config['logo_mercadopago_checkout']) && ! empty($this->config['logo_mercadopago_checkout'])) {
1724 if (is_array($result) && isset($result['init_point_qr'])) {
1725 $context->smarty->assign($result);
1726 $newOption = PaymentOptionKijam::getInstance();
1727 $newOption->setCallToActionText($this->config['mp_qr_name']);
1728 if ($this->config['preorder']) {
1729 $tpl = '/views/templates/hook/mp17Qr.tpl';
1730 $newOption->setAction($result['init_point_qr'])
1731 ->setAdditionalInformation($context->smarty->fetch('module:' . $this->module_name . $tpl))
1732 ->setLogo($icon);
1733 } else {
1734 $tpl = '/views/templates/hook/mp17QrCart.tpl';
1735 $newOption->setForm($context->smarty->fetch('module:' . $this->module_name . $tpl))
1736 ->setAdditionalInformation('')
1737 ->setLogo($icon);
1738 }
1739 $payment_options[] = $newOption;
1740 }
1741 }
1742 if (! $is_mp_envios && isset($this->config['mp_custom_enable']) && $this->config['mp_custom_enable']) {
1743 if (is_array($result) && isset($result['init_point_custom'])) {
1744 $context->smarty->assign($result);
1745 $context->smarty->assign('publickey', $this->config['publickey']);
1746 $newOption = PaymentOptionKijam::getInstance();
1747 $newOption->setCallToActionText($this->config['mp_custom_name']);
1748 $tpl = '/views/templates/hook/mp17Custom.tpl';
1749 $newOption->setForm($context->smarty->fetch('module:' . $this->module_name . $tpl))
1750 ->setAdditionalInformation('')
1751 ->setLogo($icon);
1752 $payment_options[] = $newOption;
1753 }
1754 }
1755 if ($is_mp_envios || isset($this->config['mp_basic_enable']) && $this->config['mp_basic_enable']) {
1756 $newOption = PaymentOptionKijam::getInstance();
1757 if ($this->config['preorder']) {
1758 $tpl = '/views/templates/hook/mp17Basic.tpl';
1759 } else {
1760 $tpl = '/views/templates/hook/mp17BasicCart.tpl';
1761 $btn = $this->createInitPoint();
1762 $context->smarty->assign($btn);
1763 $result['init_point'] = $btn['preference'] ? $btn['preference']->init_point : false;
1764 }
1765 $context->smarty->assign($result);
1766 $newOption->setCallToActionText($this->config['mp_basic_name'])
1767 ->setAction($result['init_point'])
1768 ->setAdditionalInformation($context->smarty->fetch('module:' . $this->module_name . $tpl))
1769 ->setLogo($icon);
1770 $payment_options[] = $newOption;
1771 }
1772 } catch (\Exception $e) {
1773 echo $e->getFile() . "[" . $e->getLine() . "] -> " . $e->getMessage();
1774 }
1775 return $payment_options;
1776 }
1777
1778 public static function redirectUrl($url, $base_uri = __PS_BASE_URI__, Link $link = null)
1779 {
1780 if (! $link) {
1781 $link = Context::getContext()->link;
1782 }
1783 if (strpos($url, 'http://') === false && strpos($url, 'https://') === false && $link) {
1784 if (strpos($url, $base_uri) === 0) {
1785 $url = Tools::substr($url, Tools::strlen($base_uri));
1786 }
1787 if (strpos($url, 'index.php?controller=') !== false && strpos($url, 'index.php/') == 0) {
1788 $url = Tools::substr($url, Tools::strlen('index.php?controller='));
1789 if (Configuration::get('PS_REWRITING_SETTINGS')) {
1790 $url = Tools::strReplaceFirst('&', '?', $url);
1791 }
1792 }
1793 $explode = explode('?', $url);
1794 // don't use ssl if url is home page
1795 // used when logout for example
1796 $use_ssl = ! empty($url);
1797 $url = $link->getPageLink($explode[0], $use_ssl);
1798 if (isset($explode[1])) {
1799 $url .= '?' . $explode[1];
1800 }
1801 }
1802 return $url;
1803 }
1804
1805 public function returnMP()
1806 {
1807 $rand_mutex = rand();
1808 UKijam::log('return[' . $rand_mutex . ']: ' . UKijam::pL($_GET, true) . UKijam::pL($_POST, true));
1809
1810 $collection_id = Tools::getValue('collection_id');
1811 if (! empty($collection_id)) {
1812 list ($collection_id) = preg_split('/,/', $collection_id);
1813 }
1814 $collection_status = Tools::getValue('collection_status');
1815 $merchant_order_id = Tools::getValue('merchant_order_id');
1816 if (! empty($merchant_order_id) || empty($collection_id) || $collection_id == 'null') {
1817 $topic = 'marchent';
1818 $op_id = $merchant_order_id;
1819 } else {
1820 $topic = 'payment';
1821 $op_id = $collection_id;
1822 }
1823 $result = $this->validateMercadoPago($topic, $op_id);
1824 UKijam::log('return-[' . $rand_mutex . ']: init lock mp_validation -
1825 ' . Tools::getValue('external_reference') . ' result: ' . UKijam::pL($result, true));
1826
1827 if (! $result || ! $collection_status || empty($collection_status) || $collection_status == 'null') {
1828 UKijam::log('return-emptystatus: ' . Tools::getValue('external_reference'));
1829 Tools::redirect('index');
1830 return;
1831 }
1832 $mutex = new MpMutex('mpk_validation');
1833 while (! $mutex->lock()) {
1834 sleep(.5);
1835 }
1836 UKijam::log('return-[' . $rand_mutex . ']: lock ' . Tools::getValue('external_reference'));
1837
1838 $pre_check = explode('-', Tools::getValue('external_reference'));
1839 if (count($pre_check) == 3) {
1840 unset($pre_check[2]);
1841 }
1842 if (count($pre_check) == 2 && $pre_check[0] == 'C' || isset($result['is_by_cart']) && $result['is_by_cart']) {
1843 $idx = count($pre_check) == 1 ? 0 : 1;
1844 $id_cart = (int) $pre_check[$idx];
1845 $cart = new Cart($id_cart);
1846 if (! Validate::isLoadedObject($cart)) {
1847 UKijam::log('return-[' . $rand_mutex . ']: releaseLock2 ' . Tools::getValue('external_reference'));
1848 $mutex->releaseLock();
1849 Tools::redirect('cart.php');
1850 return;
1851 }
1852 $id_order = (int) Order::getOrderByCartId($id_cart);
1853 if ($id_order <= 0) {
1854 $context = $this->context;
1855 if ((int) $cart->id_customer != (int) $context->customer->id) {
1856 UKijam::log('return-[' . $rand_mutex . ']: releaseLock3 ' . Tools::getValue('external_reference'));
1857 $mutex->releaseLock();
1858 Tools::redirect('index.php?controller=cart');
1859 return;
1860 }
1861
1862 $cart = new Cart($id_cart);
1863 $customer = new Customer((int) $cart->id_customer);
1864
1865 $status_act = isset($result['status']) ? $result['status'] : (int) $this->config['os_refused'];
1866 $currency = new Currency((int) $cart->id_currency);
1867 $context->cart = $cart;
1868 $context->cookie->id_currency = (int) $cart->id_currency;
1869 $context->customer = $customer;
1870 $context->currency = $currency;
1871 $msg = '';
1872 $original_total_price = 0;
1873 $rate_dst = UKijam::getRate(Tools::strtoupper($currency->iso_code), Tools::strtoupper($result['currency_id']));
1874 $prices = UKijam::getCartOrderTotal($cart);
1875 if (isset($this->list_shippings['ps_mp'][$cart->id_carrier])) {
1876 $ps_total = $prices['products'];
1877 $original_total_price = Tools::ps_round($ps_total, 2);
1878 } else {
1879 $original_total_price = Tools::ps_round($prices['both'], 2);
1880 }
1881 $total_price = $original_total_price * $rate_dst;
1882 $diff = abs($total_price - $result['price_without_shipping']);
1883 $same_cur = Tools::strtoupper($result['currency_id']) == Tools::strtoupper($currency->iso_code);
1884 UKijam::log('validation-[' . $rand_mutex . ']: total-' . $id_cart . '
1885 - total_price: ' . $total_price . '
1886 - payment: ' . $result['price_without_shipping'] . '
1887 - diff: ' . $diff);
1888
1889 if ($same_cur && $diff > 0.02 || ! $same_cur && $diff > 0.05) {
1890 // $status_act = (int)Configuration::get('PS_OS_ERROR');
1891 $msg .= $this->l('Maybe Hacking Price (Price Diff:') . " {$diff} {$result['currency_id']}\n\n";
1892 }
1893 if (! $same_cur) {
1894 $msg .= $this->l('Prestashop order price (currency order): ');
1895 $msg .= " {$original_total_price} {$currency->iso_code})\n\n";
1896 $msg .= $this->l('Prestashop order price with fee (currency order): ');
1897 $msg .= " {$total_price} {$currency->iso_code})\n\n";
1898 }
1899 $payed = $result['price_with_fee'];
1900 $msg .= $this->l('Prestashop order price: ');
1901 $msg .= " {$result['price_without_shipping']} {$result['currency_id']}\n\n";
1902 $msg .= $this->l('Prestashop order price with fee: ');
1903 $msg .= " {$result['price_with_fee']} {$result['currency_id']}\n\n";
1904 $msg .= $this->l('Commission price: ');
1905 $msg .= " {$result['fee']} {$result['currency_id']}\n";
1906 if ($this->mercadoenvios_available) {
1907 $msg .= $this->l('MercadoEnvios price: ');
1908 $msg .= " {$result['shipping']} {$result['currency_id']}\n";
1909 }
1910 $msg .= $this->l('Payed: ') . " {$payed} {$result['currency_id']}\n\n";
1911 if (! $same_cur) {
1912 $msg .= ' ' . $this->l('The customer payment through');
1913 $msg .= ' ' . Tools::strtoupper($result['currency_id']);
1914 $msg .= ' ' . $this->l(', currency of the order');
1915 $msg .= ' ' . Tools::strtoupper($currency->iso_code) . '. ';
1916 $msg .= $this->l('This maybe can generate additional commissions due to currency conversions.');
1917 }
1918 UKijam::log('return-[' . $rand_mutex . ']: validateOrder-' . $id_cart . '
1919 ' . Tools::getValue('external_reference') . ' msg: ' . $msg);
1920 $name = trim($this->instance_module->displayName);
1921 self::$ignore_update_status = true;
1922 $this->instance_module->validateOrder($id_cart, $status_act,
1923 // (float)$result['price'] / (float)$rate_dst,
1924 $prices['both'], ! empty($name) ? $name : 'MercadoPago', $msg, array(), (int) $cart->id_currency, false, $customer->secure_key);
1925 UKijam::log('return-[' . $rand_mutex . ']: validateOrder-' . $id_cart . '-end
1926 ' . Tools::getValue('external_reference'));
1927 self::$ignore_update_status = false;
1928 $order = new Order(Order::getOrderByCartId($id_cart));
1929 $id_order = $order->id;
1930 if (Validate::isLoadedObject($order)) {
1931 $jids = Tools::jsonEncode($result['shipment_ids']);
1932 Db::getInstance()->Execute('INSERT INTO `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1933 (
1934 id_order,
1935 id_cart,
1936 id_shop,
1937 `topic`,
1938 mp_op_id,
1939 is_sandbox,
1940 status,
1941 next_retry,
1942 is_mercadoenvios,
1943 shipping_id,
1944 order_reference,
1945 next_retry_mercadoenvios,
1946 payment_obj
1947 )
1948 VALUES
1949 (' . (int) $order->id . ', ' . (int) $cart->id . ', ' . (int) $order->id_shop . ',
1950 \'' . pSQL($topic) . '\',
1951 \'' . pSQL($op_id) . '\',
1952 \'' . (int) $result['sandbox'] . '\',
1953 ' . (int) $order->getCurrentState() . ',
1954 ' . (int) (time() + 6 * 60 * 60) . ',
1955 ' . (int) $result['is_mp_envios'] . ',
1956 ' . (count($result['shipment_ids']) > 0 ? '\'' . pSQL($jids) . '\'' : 'NULL') . ',
1957 \'' . pSQL($order->reference) . '\',
1958 ' . (int) (time() + 2 * 60) . ',
1959 \'' . pSQL(trim($result['message2'])) . '\')');
1960 } else {
1961 UKijam::log('return-[' . $rand_mutex . ']: invalid DB order ' . Tools::getValue('external_reference'));
1962 $mutex->releaseLock();
1963 Tools::redirect('index');
1964 return;
1965 }
1966 }
1967 } else {
1968 if (count($pre_check) == 2) {
1969 $id_order = (int) $pre_check[1];
1970 } else {
1971 $id_order = (int) $pre_check[0];
1972 }
1973 }
1974 $order = new Order($id_order);
1975 if (! Validate::isLoadedObject($order)) {
1976 UKijam::log('return-[' . $rand_mutex . ']: invalid order ' . Tools::getValue('external_reference'));
1977 $mutex->releaseLock();
1978 Tools::redirect('index');
1979 return;
1980 }
1981 $id_cart = (int) $order->id_cart;
1982 $cart = new Cart($id_cart);
1983 if ($result['status'] && $result['order_id']) {
1984 $context = $this->context;
1985 if ((int) $cart->id_customer != (int) $context->customer->id) {
1986 UKijam::log('return-[' . $rand_mutex . ']: invalid owner ' . Tools::getValue('external_reference'));
1987 $mutex->releaseLock();
1988 Tools::redirect('index');
1989 return;
1990 }
1991 $status_act = $result['status'];
1992 $order = new Order($id_order);
1993 $status_mp = (int) Db::getInstance()->getValue('SELECT `status` FROM
1994 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
1995 WHERE `id_order` = ' . (int) $id_order);
1996 $status_ps = (int) $order->getCurrentState();
1997 $cancel_status = array(
1998 (int) Configuration::get('PS_OS_CANCELED'),
1999 (int) Configuration::get('PS_OS_ERROR'),
2000 (int) Configuration::get('PS_OS_REFUND'),
2001 (int) Configuration::get('PS_OS_OUTOFSTOCK_PAID')
2002 );
2003 $valid_status = array(
2004 (int) Configuration::get('PS_OS_OUTOFSTOCK'),
2005 (int) Configuration::get('PS_OS_OUTOFSTOCK_UNPAID'),
2006 (int) Configuration::get('PS_OS_SHIPPING'),
2007 (int) Configuration::get('PS_OS_DELIVERED'),
2008 (int) Configuration::get('PS_OS_PREPARATION'),
2009 (int) $this->os_wait_payment,
2010 (int) $this->os_pending,
2011 (int) $this->config['os_authorization']
2012 );
2013
2014 if ($status_ps > 0 && (in_array($status_ps, $cancel_status) || $status_mp != $status_ps && ! in_array($status_ps, $valid_status))) {
2015 // if ($status_ps > 0 && (in_array($status_ps, $cancel_status) || $status_mp != $status_ps)) {
2016 $status_act = $status_ps;
2017 } else {
2018 if (in_array($status_ps, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && $status_act != $status_ps) {
2019 self::$ignore_update_status = true;
2020 $order->setCurrentState($status_act);
2021 self::$ignore_update_status = false;
2022 }
2023 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
2024 SET
2025 `next_retry` = ' . (int) (time() + 6 * 60 * 60) . ',
2026 `status` = ' . (int) $status_act . '
2027 WHERE id_order = ' . (int) $id_order);
2028 }
2029 UKijam::log('returnMP-[' . $rand_mutex . ']: Old status ' . $status_ps . ' - Actual: ' . $status_act);
2030 UKijam::log('returnMP-[' . $rand_mutex . ']: returnMP-' . $id_cart . '-' . $id_order . '-end
2031 ' . Tools::getValue('topic') . Tools::getValue('id'));
2032 }
2033 UKijam::log('return-[' . $rand_mutex . ']: releaseLock4 ' . Tools::getValue('external_reference'));
2034 $mutex->releaseLock();
2035 $customer = new Customer((int) $cart->id_customer);
2036 $this->checkResponseBasicMP($result);
2037 die('<script>top.location.href = "' . self::redirectUrl('index.php?controller=order-confirmation&id_cart=' . $cart->id . '&id_module=' . $this->instance_module->id . '&id_order=' . $order->id . '&key=' . $customer->secure_key) . '";</script>');
2038 }
2039
2040 protected function checkResponseBasicMP($result)
2041 {
2042 $rand_mutex = rand();
2043 if (! $result || ! isset($result['status']) || ! isset($result['order_id'])) {
2044 UKijam::log('validation[' . $rand_mutex . ']: Respuesta IPN Invalida');
2045 die('IPN Invalido');
2046 }
2047
2048 $mutex = new MpMutex('mpk_validation');
2049
2050 UKijam::log('validation-[' . $rand_mutex . ']: init lock mp_validation -
2051 ' . Tools::getValue('topic') . Tools::getValue('id'));
2052
2053 if (! Tools::isSubmit('id')) {
2054 $_GET['id'] = $result['mp_op_id'];
2055 $_GET['topic'] = 'payment';
2056 }
2057
2058 while (! $mutex->lock()) {
2059 sleep(.5);
2060 }
2061
2062 UKijam::log('validation-[' . $rand_mutex . ']: lock ' . Tools::getValue('topic') . Tools::getValue('id'));
2063
2064 $pre_check = explode('-', $result['order_id']);
2065 if (count($pre_check) == 2 && $pre_check[0] == 'C' || isset($result['is_by_cart']) && $result['is_by_cart']) {
2066 $idx = count($pre_check) == 1 ? 0 : 1;
2067 $id_cart = (int) $pre_check[$idx];
2068 $cart = new Cart($id_cart);
2069 if (! Validate::isLoadedObject($cart)) {
2070 UKijam::log('validation-[' . $rand_mutex . ']: unlock Invalid Cart ID');
2071 $mutex->releaseLock();
2072 exit();
2073 }
2074 $id_order = Order::getOrderByCartId($id_cart);
2075 if ($id_order > 0) {
2076 $result['order_id'] = $id_order;
2077 } else {
2078 $id_cart = $pre_check[1];
2079 $cart = new Cart($id_cart);
2080 if (! Validate::isLoadedObject($cart)) {
2081 UKijam::log('validation-[' . $rand_mutex . ']: unlock Invalid Cart ID');
2082 $mutex->releaseLock();
2083 exit();
2084 }
2085 $status_act = $result['status'];
2086 $customer = new Customer((int) $cart->id_customer);
2087 $currency = new Currency((int) $cart->id_currency);
2088 $context = $this->context;
2089 $context->cart = $cart;
2090 $context->cookie->id_currency = (int) $cart->id_currency;
2091 $context->customer = $customer;
2092 $context->currency = $currency;
2093 $msg = '';
2094 $original_total_price = 0;
2095 $rate_dst = UKijam::getRate(Tools::strtoupper($currency->iso_code), Tools::strtoupper($result['currency_id']));
2096 $prices = UKijam::getCartOrderTotal($cart);
2097 if (isset($this->list_shippings['ps_mp'][$cart->id_carrier])) {
2098 $ps_total = $prices['products'] * $rate_dst;
2099 $original_total_price = Tools::ps_round($ps_total, 2);
2100 } else {
2101 $original_total_price = Tools::ps_round($prices['both'] * $rate_dst, 2);
2102 }
2103 $total_price = $original_total_price * $rate_dst;
2104 $diff = abs($total_price - $result['price_without_shipping']);
2105 $same_cur = Tools::strtoupper($result['currency_id']) == Tools::strtoupper($currency->iso_code);
2106 UKijam::log('validation-[' . $rand_mutex . ']: total-' . $id_cart . '
2107 - total_price: ' . $total_price . '
2108 - payment: ' . $result['price_without_shipping'] . '
2109 - diff: ' . $diff);
2110
2111 if ($same_cur && $diff > 0.02 || ! $same_cur && $diff > 0.05) {
2112 // $status_act = (int)Configuration::get('PS_OS_ERROR');
2113 $msg .= $this->l('Maybe Hacking Price (Price Diff:') . " {$diff} {$result['currency_id']}\n\n";
2114 }
2115 if (! $same_cur) {
2116 $msg .= $this->l('Prestashop order price (currency order): ');
2117 $msg .= " {$original_total_price} {$currency->iso_code})\n\n";
2118 $msg .= $this->l('Prestashop order price with fee (currency order): ');
2119 $msg .= " {$total_price} {$currency->iso_code})\n\n";
2120 }
2121 $payed = $result['price_with_fee'];
2122 $msg .= $this->l('Prestashop order price: ');
2123 $msg .= " {$result['price_without_shipping']} {$result['currency_id']}\n\n";
2124 $msg .= $this->l('Prestashop order price with fee: ');
2125 $msg .= " {$result['price_with_fee']} {$result['currency_id']}\n\n";
2126 $msg .= $this->l('Commission price: ') . " {$result['fee']} {$result['currency_id']}\n";
2127 if ($this->mercadoenvios_available) {
2128 $msg .= $this->l('MercadoEnvios price: ') . " {$result['shipping']} {$result['currency_id']}\n";
2129 }
2130 $msg .= $this->l('Payed: ') . " {$payed} {$result['currency_id']}\n\n";
2131 if (! $same_cur) {
2132 $msg .= ' ' . $this->l('The customer payment through');
2133 $msg .= ' ' . Tools::strtoupper($result['currency_id']);
2134 $msg .= ' ' . $this->l(', currency of the order');
2135 $msg .= ' ' . Tools::strtoupper($currency->iso_code) . '. ';
2136 $msg .= $this->l('This maybe can generate additional commissions due to currency conversions.');
2137 }
2138 UKijam::log('validation-[' . $rand_mutex . ']: validateOrder-' . $id_cart . '-init
2139 ' . Tools::getValue('topic') . Tools::getValue('id'));
2140 $name = trim($this->instance_module->displayName);
2141 self::$ignore_update_status = true;
2142 $this->instance_module->validateOrder($id_cart, $status_act, (float) $result['price'] / (float) $rate_dst,
2143 // $result['both'],
2144 ! empty($name) ? $name : 'MercadoPago', $msg, array(), (int) $cart->id_currency, false, $customer->secure_key);
2145 $order = new Order(Order::getOrderByCartId($id_cart));
2146 $status_ps = (int) $order->getCurrentState();
2147 if (in_array($status_ps, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && $status_ps != $status_act) {
2148 $order->setCurrentState($status_act);
2149 }
2150 self::$ignore_update_status = false;
2151 $result['order_id'] = $order->id;
2152 UKijam::log('validation-[' . $rand_mutex . ']: validateOrder-' . $id_cart . '-order created
2153 ' . Tools::getValue('topic') . Tools::getValue('id'));
2154 }
2155 } else {
2156 if (count($pre_check) == 2) {
2157 $result['order_id'] = $pre_check[1];
2158 } else {
2159 $result['order_id'] = $pre_check[0];
2160 }
2161 }
2162 $id_order = (int) $result['order_id'];
2163 $order = new Order($id_order);
2164 if (! Validate::isLoadedObject($order)) {
2165 UKijam::log('validation-[' . $rand_mutex . ']: unlock Invalid Order ID');
2166 $mutex->releaseLock();
2167 exit();
2168 }
2169 $id_cart = (int) $order->id_cart;
2170 $cart = new Cart($id_cart);
2171 if (! Validate::isLoadedObject($cart)) {
2172 UKijam::log('validation-[' . $rand_mutex . ']: unlock Invalid Cart ID');
2173 $mutex->releaseLock();
2174 exit();
2175 }
2176
2177 UKijam::log('validation-[' . $rand_mutex . ']: cart-' . $id_cart . ' order-' . $id_order . '
2178 ' . Tools::getValue('topic') . Tools::getValue('id'));
2179
2180 $status_act = $result['status'];
2181
2182 $customer = new Customer((int) $cart->id_customer);
2183 $currency = new Currency((int) $cart->id_currency);
2184
2185 $context = $this->context;
2186 $context->cart = $cart;
2187 $context->cookie->id_currency = (int) $cart->id_currency;
2188 $context->customer = $customer;
2189 $context->currency = $currency;
2190 $status_mp = (int) Db::getInstance()->getValue('SELECT `status` FROM
2191 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
2192 WHERE `id_order` = ' . (int) $id_order);
2193 $first_check = false;
2194 if ($status_mp < 1) {
2195 $jids = Tools::jsonEncode($result['shipment_ids']);
2196 Db::getInstance()->Execute('INSERT INTO `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
2197 (
2198 id_order,
2199 id_cart,
2200 id_shop,
2201 `topic`,
2202 mp_op_id,
2203 is_sandbox,
2204 status,
2205 next_retry,
2206 is_mercadoenvios,
2207 shipping_id,
2208 order_reference,
2209 next_retry_mercadoenvios,
2210 payment_obj
2211 )
2212 VALUES
2213 (' . (int) $order->id . ', ' . (int) $cart->id . ', ' . (int) $order->id_shop . ',
2214 \'' . pSQL(Tools::getValue('topic')) . '\',
2215 \'' . pSQL(Tools::getValue('id')) . '\',
2216 \'' . (int) $result['sandbox'] . '\',
2217 ' . (int) $order->getCurrentState() . ',
2218 ' . (int) (time() + 6 * 60 * 60) . ',
2219 ' . (int) $result['is_mp_envios'] . ',
2220 ' . (count($result['shipment_ids']) > 0 ? '\'' . pSQL($jids) . '\'' : 'NULL') . ',
2221 \'' . pSQL($order->reference) . '\',
2222 ' . (int) (time() + 2 * 60) . ',
2223 \'' . pSQL(trim($result['message2'])) . '\'
2224 )');
2225 $status_mp = (int) Db::getInstance()->getValue('SELECT `status` FROM
2226 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
2227 WHERE `id_order` = ' . (int) $id_order);
2228 $first_check = true;
2229 } else {
2230 $mp_op_id = (int) Db::getInstance()->getValue('SELECT `mp_order_id` FROM
2231 `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
2232 WHERE `id_order` = ' . (int) $id_order);
2233 if (empty($mp_op_id)) {
2234 $jids = Tools::jsonEncode($result['shipment_ids']);
2235 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
2236 SET
2237 `topic` = \'' . pSQL(Tools::getValue('topic')) . '\',
2238 `mp_op_id` = \'' . pSQL(Tools::getValue('id')) . '\',
2239 `is_mercadoenvios` = ' . (count($result['shipment_ids']) > 0 ? '1' : '0') . ',
2240 `shipping_id` = ' . (count($result['shipment_ids']) > 0 ? '\'' . pSQL($jids) . '\'' : 'NULL') . ',
2241 `next_retry_mercadoenvios` = ' . (int) (time() + 2 * 60) . '
2242 WHERE id_order = ' . (int) $id_order);
2243 $first_check = true;
2244 }
2245 }
2246 $status_ps = (int) $order->getCurrentState();
2247 $cancel_status = array(
2248 (int) Configuration::get('PS_OS_CANCELED'),
2249 (int) Configuration::get('PS_OS_ERROR'),
2250 (int) Configuration::get('PS_OS_OUTOFSTOCK_PAID'),
2251 (int) Configuration::get('PS_OS_REFUND')
2252 );
2253 $valid_status = array(
2254 (int) Configuration::get('PS_OS_OUTOFSTOCK'),
2255 (int) Configuration::get('PS_OS_OUTOFSTOCK_UNPAID'),
2256 (int) Configuration::get('PS_OS_SHIPPING'),
2257 (int) Configuration::get('PS_OS_DELIVERED'),
2258 (int) Configuration::get('PS_OS_PREPARATION'),
2259 (int) $this->os_wait_payment,
2260 (int) $this->os_pending,
2261 (int) $this->config['os_authorization']
2262 );
2263 if (in_array($status_ps, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && $status_ps > 0 && $status_mp == $status_ps && $status_act != $status_ps) {
2264 self::$ignore_update_status = true;
2265 $order->setCurrentState($status_act);
2266 self::$ignore_update_status = false;
2267 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
2268 SET
2269 `next_retry` = ' . (int) (time() + 6 * 60 * 60) . ',
2270 `status` = ' . (int) $status_act . '
2271 WHERE id_order = ' . (int) $id_order);
2272 } elseif ($status_ps > 0 && (in_array($status_ps, $cancel_status) || $status_mp != $status_ps && ! in_array($status_ps, $valid_status))) {
2273 $status_act = $status_ps;
2274 } else {
2275 if (in_array($status_ps, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && $status_act != $status_ps) {
2276 self::$ignore_update_status = true;
2277 $order->setCurrentState($status_act);
2278 self::$ignore_update_status = false;
2279 }
2280 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
2281 SET
2282 `next_retry` = ' . (int) (time() + 6 * 60 * 60) . ',
2283 `status` = ' . (int) $status_act . '
2284 WHERE id_order = ' . (int) $id_order);
2285 }
2286 if ($first_check) {
2287 UKijam::log('validation-[' . $rand_mutex . ']: first_check-' . $id_cart . '-' . $id_order . '
2288 ' . Tools::getValue('topic') . Tools::getValue('id'));
2289 $msg = '';
2290 $original_total_price = 0;
2291 $rate_dst = UKijam::getRate(Tools::strtoupper($currency->iso_code), Tools::strtoupper($result['currency_id']));
2292 $prices = UKijam::getCartOrderTotal($cart);
2293 if (isset($this->list_shippings['ps_mp'][$cart->id_carrier])) {
2294 $original_total_price = Tools::ps_round($prices['products'], 2);
2295 } else {
2296 $original_total_price = Tools::ps_round($prices['both'], 2);
2297 }
2298 $total_price = $original_total_price * $rate_dst;
2299 $diff = abs($total_price - $result['price_without_shipping']);
2300 $same_cur = Tools::strtoupper($result['currency_id']) == Tools::strtoupper($currency->iso_code);
2301 UKijam::log('validation-[' . $rand_mutex . ']: total-' . $id_cart . '
2302 - total_price: ' . $total_price . '
2303 - payment: ' . $result['price_without_shipping'] . '
2304 - diff: ' . $diff);
2305 if ($same_cur && $diff > 0.02 || ! $same_cur && $diff > 0.05) {
2306 // $status_act = (int)Configuration::get('PS_OS_ERROR');
2307 $msg .= $this->l('Maybe Hacking Price (Price Diff:') . " {$diff} {$result['currency_id']})\n\n";
2308 }
2309 if (! $same_cur) {
2310 $msg .= $this->l('Prestashop order price (currency order): ');
2311 $msg .= " {$original_total_price} {$currency->iso_code})\n\n";
2312 $msg .= $this->l('Prestashop order price with fee (currency order): ');
2313 $msg .= " {$total_price} {$currency->iso_code})\n\n";
2314 }
2315 $payed = $result['price_with_fee'];
2316 $msg .= $this->l('Prestashop order price: ');
2317 $msg .= " {$result['price_without_shipping']} {$result['currency_id']}\n\n";
2318 $msg .= $this->l('Prestashop order price with fee: ');
2319 $msg .= " {$result['price_with_fee']} {$result['currency_id']}\n\n";
2320 $msg .= $this->l('Commission price: ') . " {$result['fee']} {$result['currency_id']}\n";
2321 if ($this->mercadoenvios_available) {
2322 $msg .= $this->l('MercadoEnvios price: ') . " {$result['shipping']} {$result['currency_id']}\n";
2323 }
2324 $msg .= $this->l('Payed: ') . " {$payed} {$result['currency_id']}\n\n";
2325 if (! $same_cur) {
2326 $msg .= ' ' . $this->l('The customer payment through');
2327 $msg .= ' ' . Tools::strtoupper($result['currency_id']);
2328 $msg .= ' ' . $this->l(', currency of the order');
2329 $msg .= ' ' . Tools::strtoupper($currency->iso_code) . '. ';
2330 $msg .= $this->l('This maybe can generate additional commissions due to currency conversions.');
2331 }
2332 $message = new Message();
2333 $message->id_customer = (int) $order->id_customer;
2334 $message->message = $msg;
2335 $message->id_order = (int) $order->id;
2336 $message->id_cart = (int) $order->id_cart;
2337 $message->protected = true;
2338 $id = $message->add();
2339 UKijam::log('validation-[' . $rand_mutex . '] message[' . $id . ']: ' . UKijam::pL($message, true));
2340 self::$ignore_update_status = true;
2341 $status_ps = (int) $order->getCurrentState();
2342 if (in_array($status_ps, array(Configuration::get('mptoolsproc_os_wait_payment'),Configuration::get('mptoolsproc_os_pending'))) && $status_ps != $status_act) {
2343 $order->setCurrentState($status_act);
2344 }
2345 self::$ignore_update_status = false;
2346 UKijam::log('validation-[' . $rand_mutex . ']: first_check-' . $id_cart . '-end
2347 ' . Tools::getValue('topic') . Tools::getValue('id'));
2348 }
2349 $order_payments = $order->getOrderPayments();
2350 foreach ($order_payments as $order_payment) {
2351 $order_payment->transaction_id = $result['transaction_id'];
2352 if ($result['last_four_digits'] && ! empty($result['last_four_digits'])) {
2353 $order_payment->card_number = $result['last_four_digits'];
2354 }
2355 if ($result['card_brand'] && ! empty($result['card_brand'])) {
2356 $order_payment->card_brand = $result['card_brand'];
2357 }
2358 if ($result['cardholder_name'] && ! empty($result['cardholder_name'])) {
2359 $order_payment->card_holder = $result['cardholder_name'];
2360 }
2361 $order_payment->save();
2362 }
2363 $updated = array();
2364 if (! empty($result['transaction_id'])) {
2365 $updated[] = '`mp_payment_id` = \'' . pSQL($result['transaction_id']) . '\'';
2366 }
2367 if (! empty($result['mp_order_id'])) {
2368 $updated[] = '`mp_order_id` = \'' . pSQL($result['mp_order_id']) . '\'';
2369 }
2370 if (! empty($result['last_four_digits'])) {
2371 $updated[] = '`mp_card_number` = \'' . pSQL($result['last_four_digits']) . '\'';
2372 }
2373 if (! empty($result['card_brand'])) {
2374 $updated[] = '`mp_card_brand` = \'' . pSQL($result['card_brand']) . '\'';
2375 }
2376 if (! empty($result['cardholder_name'])) {
2377 $updated[] = '`mp_card_holder` = \'' . pSQL($result['cardholder_name']) . '\'';
2378 }
2379 if (! empty($result['client_name'])) {
2380 $updated[] = '`mp_payer_name` = \'' . pSQL($result['client_name']) . '\'';
2381 }
2382 if (! empty($result['identification'])) {
2383 $updated[] = '`mp_payer_dni` = \'' . pSQL($result['identification']) . '\'';
2384 }
2385 if (! empty($result['total'])) {
2386 $updated[] = '`mp_total_amount` = \'' . pSQL($result['total']) . '\'';
2387 }
2388 if (! empty($result['commision_amount'])) {
2389 $updated[] = '`mp_total_commision` = \'' . pSQL($result['commision_amount']) . '\'';
2390 }
2391 if (count($updated) > 0 && (int) $id_order > 0) {
2392 Db::getInstance()->Execute('UPDATE `' . bqSQL(_DB_PREFIX_ . UKijam::DB_PREFIX) . '`
2393 SET
2394 ' . implode(', ', $updated) . '
2395 WHERE id_order = ' . (int) $id_order);
2396 }
2397 UKijam::log('validation-[' . $rand_mutex . ']: releaseLock ' . Tools::getValue('topic') . Tools::getValue('id'));
2398 $mutex->releaseLock();
2399 }
2400
2401 public function ipn()
2402 {
2403 UKijam::log('ipn: ' . UKijam::pL($_GET, true) . UKijam::pL($_POST, true));
2404 if (! Tools::getValue('id')) {
2405 UKijam::log('ipn: ID Desconocido');
2406 die('ID Desconocido');
2407 }
2408 $result = $this->validateMercadoPago(Tools::getValue('topic'), Tools::getValue('id'));
2409 $this->checkResponseBasicMP($result);
2410 }
2411
2412 public function hookDisplayProductButtons($params)
2413 {
2414 if (! isset($params['product'])) {
2415 $params['product'] = new Product((int) Tools::getValue('id_product'));
2416 } elseif (is_array($params['product'])) {
2417 $params['product'] = new Product((int) $params['product']['id_product']);
2418 }
2419 $commision_fee = false;
2420 $commision_fee_qr = false;
2421 $commision_fee_custom = false;
2422 $commision_fee_d = false;
2423 $commision_fee_qr_d = false;
2424 $commision_fee_custom_d = false;
2425 $prod = $params['product'];
2426 $price_prod = 0.0;
2427 if (is_object($prod)) {
2428 if (method_exists($prod, 'getPrice')) {
2429 $price_prod = (float) $prod->getPrice(true, false);
2430 } elseif (method_exists($prod, 'offsetGet')) {
2431 $price_prod = (float) $prod->offsetGet('price_amount');
2432 }
2433 }
2434 $currency = null;
2435 $cart = $this->context->cart;
2436 if (Validate::isLoadedObject($cart) && $cart->id_currency > 0) {
2437 $currency = new Currency((int) $cart->id_currency);
2438 } else {
2439 $id_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT');
2440 $currency = new Currency($id_currency);
2441 }
2442 $rate = UKijam::getRate(Tools::strtoupper($currency->iso_code), Tools::strtoupper($this->settings['CURRENCY']));
2443 $price_prod = $price_prod * $rate;
2444 $id_currency_mp = (int) Currency::getIdByIsoCode($this->settings['CURRENCY']);
2445 $currency_mp = new Currency($id_currency_mp);
2446 $price_prod_d = Tools::displayPrice($price_prod, $currency_mp);
2447 if (isset($this->config['mp_basic_enable']) && $this->config['mp_basic_enable'] && isset($this->config['commision_fee']) && $this->config['commision_fee']) {
2448 $fee = 100.0 / (100.0 - (float) $this->config['fee']);
2449 $commision_fee = $price_prod * $fee + $this->config['fee_amount'];
2450 $commision_fee_d = Tools::displayPrice($commision_fee, $currency_mp);
2451 }
2452 if (isset($this->config['mp_qr_enable']) && $this->config['mp_qr_enable'] && isset($this->config['commision_fee_qr']) && $this->config['commision_fee_qr']) {
2453 $fee = 100.0 / (100.0 - (float) $this->config['fee_qr']);
2454 $commision_fee_qr = $price_prod * $fee + $this->config['fee_amount_qr'];
2455 $commision_fee_qr_d = Tools::displayPrice($commision_fee_qr, $currency_mp);
2456 }
2457 if (isset($this->config['mp_custom_enable']) && $this->config['mp_custom_enable'] && isset($this->config['commision_fee_custom']) && $this->config['commision_fee_custom']) {
2458 $fee = 100.0 / (100.0 - (float) $this->config['fee_custom']);
2459 $commision_fee_custom = $price_prod * $fee + $this->config['fee_amount_custom'];
2460 $commision_fee_custom_d = Tools::displayPrice($commision_fee_custom, $currency_mp);
2461 }
2462 if (! $this->api_me || ! $this->mercadoenvios_available || ! $this->config['shipping_active'] || ! $this->config['ship_check_price']) {
2463 if (isset($this->config['installment_calculator']) && $this->config['installment_calculator']) {
2464 return array(
2465 'installment_calculator' => $this->config['installment_pcalculator'],
2466 'id_product' => $params['product']->id,
2467 'price' => $price_prod,
2468 'price_d' => $price_prod_d,
2469 'config' => $this->config,
2470 'commision_fee' => $commision_fee,
2471 'commision_fee_qr' => $commision_fee_qr,
2472 'commision_fee_custom' => $commision_fee_custom,
2473 'commision_fee_d' => $commision_fee_d,
2474 'commision_fee_qr_d' => $commision_fee_qr_d,
2475 'commision_fee_custom_d' => $commision_fee_custom_d
2476 );
2477 } else {
2478 return array(
2479 'config' => $this->config,
2480 'price' => $price_prod,
2481 'price_d' => $price_prod_d,
2482 'commision_fee' => $commision_fee,
2483 'commision_fee_qr' => $commision_fee_qr,
2484 'commision_fee_custom' => $commision_fee_custom,
2485 'commision_fee_d' => $commision_fee_d,
2486 'commision_fee_qr_d' => $commision_fee_qr_d,
2487 'commision_fee_custom_d' => $commision_fee_custom_d
2488 );
2489 }
2490 } // INIT_NO_MERCADOENVIOS
2491 $cart = $this->context->cart;
2492 $address = false;
2493 if ((int) $cart->id_address_delivery > 0) {
2494 $address = new Address((int) $cart->id_address_delivery);
2495 }
2496 $link = new Link();
2497 return array(
2498 'url_ajax' => $link->getModuleLink('mptoolspro', 'redirect'),
2499 'installment_calculator' => $this->config['installment_pcalculator'],
2500 'id_product' => $params['product']->id,
2501 'postalcode' => $address ? $address->postcode : '',
2502 'config' => $this->config,
2503 'price' => $price_prod,
2504 'price_d' => $price_prod_d,
2505 'commision_fee' => $commision_fee,
2506 'commision_fee_qr' => $commision_fee_qr,
2507 'commision_fee_custom' => $commision_fee_custom,
2508 'commision_fee_d' => $commision_fee_d,
2509 'commision_fee_qr_d' => $commision_fee_qr_d,
2510 'commision_fee_custom_d' => $commision_fee_custom_d
2511 );
2512 // END_NO_MERCADOENVIOS
2513 }
2514
2515 private function l($key, $file = 'mercadopago_gateway')
2516 {
2517 if ($this->instance_module) {
2518 return $this->instance_module->lang($key, $file);
2519 }
2520 return $key;
2521 }
2522}