forked from mercadopago/cart-woocommerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwoocommerce-mercadopago.php
1226 lines (1150 loc) · 54.1 KB
/
woocommerce-mercadopago.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: WooCommerce MercadoPago - Extensible
* Plugin URI: https://github.com/nmercado1986/cart-woocommerce
* Description: Fork del cart de woocommerce para mercadopago que permite extender ciertos métodos originalmente definidos como privados en el plugin de mercadopago
* Version: 3.0.17
* Author: Nicolás Mercado
* Author URI: https://github.com/nmercado1986
* Text Domain: woocommerce-mercadopago
* Domain Path: /i18n/languages/
* WC requires at least: 3.0.0
* WC tested up to: 3.4.3
*
* @package MercadoPago
* @category Core
* @author Nicolás Mercado
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Load plugin text domain.
*
* Need to require here before test for PHP version.
*
* @since 3.0.1
*/
function wc_mercado_pago_load_plugin_textdomain() {
load_plugin_textdomain( 'woocommerce-mercadopago', false, dirname( plugin_basename( __FILE__ ) ) . '/i18n/languages/' );
}
add_action( 'init', 'wc_mercado_pago_load_plugin_textdomain' );
/**
* Notice about unsupported PHP version.
*
* @since 3.0.1
*/
function wc_mercado_pago_unsupported_php_version_notice() {
echo '<div class="error"><p>' . esc_html__( 'WooCommerce Mercado Pago requires PHP version 5.6 or later. Please update your PHP version.', 'woocommerce-mercadopago' ) . '</p></div>';
}
// Check for PHP version and throw notice.
if ( version_compare( PHP_VERSION, '5.6', '<=' ) ) {
add_action( 'admin_notices', 'wc_mercado_pago_unsupported_php_version_notice' );
return;
}
/**
* Summary: Places a warning error to notify user that other older versions are active.
* Description: Places a warning error to notify user that other older versions are active.
* @since 3.0.7
*/
function wc_mercado_pago_notify_deprecated_presence() {
echo '<div class="error"><p>' .
__( 'It seems you have <strong>Woo Mercado Pago Module</strong> installed. Please, uninstall it before using this version.', 'woocommerce-mercadopago' ) .
'</p></div>';
}
// Check if previously versions are installed, as we can't let both operate.
if ( class_exists( 'WC_WooMercadoPago_Module' ) ) {
add_action( 'admin_notices', 'wc_mercado_pago_notify_deprecated_presence' );
return;
}
// Load Mercado Pago SDK
require_once dirname( __FILE__ ) . '/includes/sdk/lib/mercadopago.php';
// Load module class if it wasn't loaded yet.
if ( ! class_exists( 'WC_Woo_Mercado_Pago_Module' ) ) :
/**
* Summary: WooCommerce MercadoPago Module main class.
* Description: Used as a kind of manager to enable/disable each Mercado Pago gateway.
* Available Public Static Functions:
* - validate_credentials_v0()
* - validate_credentials_v1()
* - woocommerce_instance()
* - get_common_error_messages( $key )
* - get_conversion_rate( $used_currency )
* - get_common_settings()
* - get_categories()
* - get_site_data( $is_v1 = false )
* - fix_url_ampersand( $link )
* - get_templates_path()
* - get_module_version()
* - get_client_id( $at )
* - is_subscription( $items )
* - is_supported_currency( $site_id )
* - build_currency_conversion_err_msg( $currency )
* - build_currency_not_converted_msg( $currency, $country_name )
* - build_currency_converted_msg( $currency )
* - get_country_name( $site_id )
* - build_log_path_string( $gateway_id, $gateway_name )
* - get_wc_status_for_mp_status( $mp_status )
* - get_map( $selector_id )
* - generate_refund_cancel_subscription( $domain, $success_msg, $fail_msg, $options, $str1, $str2, $str3, $str4 )
* - is_product_dimensions_valid( $all_product_data )
* @since 3.0.0
*/
class WC_Woo_Mercado_Pago_Module {
// ============================================================
// General constants.
const VERSION = '3.0.17';
const MIN_PHP = 5.6;
// Arrays to hold configurations for LatAm environment.
// As this array contains runtime data, we can't set it as a class constant.
public static $categories = array();
public static $country_configs = array();
// ============================================================
// A singleton design pattern to access this class in global scope.
protected static $instance = null;
public static function init_mercado_pago_class() {
if ( self::$instance === null ) {
self::$instance = new self;
}
return self::$instance;
}
// Class constructor.
private function __construct() {
WC_Woo_Mercado_Pago_Module::$categories = WC_Woo_Mercado_Pago_Module::get_categories();
WC_Woo_Mercado_Pago_Module::$country_configs = array(
'MCO' => array(
'site_id' => 'MCO',
'sponsor_id' => 208687643,
'checkout_banner' => plugins_url( 'assets/images/MCO/standard_mco.jpg', __FILE__ ),
'checkout_banner_custom' => plugins_url( 'assets/images/MCO/credit_card.png', __FILE__ ),
'currency' => 'COP'
),
'MLA' => array(
'site_id' => 'MLA',
'sponsor_id' => 208682286,
'checkout_banner' => plugins_url( 'assets/images/MLA/standard_mla.jpg', __FILE__ ),
'checkout_banner_custom' => plugins_url( 'assets/images/MLA/credit_card.png', __FILE__ ),
'currency' => 'ARS'
),
'MLB' => array(
'site_id' => 'MLB',
'sponsor_id' => 208686191,
'checkout_banner' => plugins_url( 'assets/images/MLB/standard_mlb.jpg', __FILE__ ),
'checkout_banner_custom' => plugins_url( 'assets/images/MLB/credit_card.png', __FILE__ ),
'currency' => 'BRL'
),
'MLC' => array(
'site_id' => 'MLC',
'sponsor_id' => 208690789,
'checkout_banner' => plugins_url( 'assets/images/MLC/standard_mlc.gif', __FILE__ ),
'checkout_banner_custom' => plugins_url( 'assets/images/MLC/credit_card.png', __FILE__ ),
'currency' => 'CLP'
),
'MLM' => array(
'site_id' => 'MLM',
'sponsor_id' => 208692380,
'checkout_banner' => plugins_url( 'assets/images/MLM/standard_mlm.jpg', __FILE__ ),
'checkout_banner_custom' => plugins_url( 'assets/images/MLM/credit_card.png', __FILE__ ),
'currency' => 'MXN'
),
'MLU' => array(
'site_id' => 'MLU',
'sponsor_id' => 243692679,
'checkout_banner' => plugins_url( 'assets/images/MLU/standard_mlu.png', __FILE__ ),
'checkout_banner_custom' => plugins_url( 'assets/images/MLU/credit_card.png', __FILE__ ),
'currency' => 'UYU'
),
'MLV' => array(
'site_id' => 'MLV',
'sponsor_id' => 208692735,
'checkout_banner' => plugins_url( 'assets/images/MLV/standard_mlv.jpg', __FILE__ ),
'checkout_banner_custom' => plugins_url( 'assets/images/MLV/credit_card.png', __FILE__ ),
'currency' => 'VEF'
),
'MPE' => array(
'site_id' => 'MPE',
'sponsor_id' => 216998692,
'checkout_banner' => plugins_url( 'assets/images/MPE/standard_mpe.png', __FILE__ ),
'checkout_banner_custom' => plugins_url( 'assets/images/MPE/credit_card.png', __FILE__ ),
'currency' => 'PEN'
)
);
// First of all, verify if WooCommerce is already installed.
if ( class_exists( 'WC_Payment_Gateway' ) ) {
// Adds each Mercado Pago gateway as available payment method.
include_once dirname( __FILE__ ) . '/includes/WC_WooMercadoPago_BasicGateway.php';
include_once dirname( __FILE__ ) . '/includes/WC_WooMercadoPago_CustomGateway.php';
include_once dirname( __FILE__ ) . '/includes/WC_WooMercadoPago_TicketGateway.php';
//Get site_id and enable PSE only when credentials are set up and are from Colombia
$_site_id_v1 = get_option( '_site_id_v1', '' );
if ( !empty( $_site_id_v1 ) && $_site_id_v1=='MCO' ) {
include_once dirname( __FILE__ ) . '/includes/WC_WooMercadoPago_PSEGateway.php';
}
include_once dirname( __FILE__ ) . '/includes/WC_WooMercadoPago_SubscriptionGateway.php';
include_once dirname( __FILE__ ) . '/includes/class-wc-product-mp_recurrent.php';
add_filter( 'woocommerce_payment_gateways', array( $this, 'add_gateway' ) );
// Shipping.
include_once dirname( __FILE__ ) . '/includes/shipment/abstract-wc-mercadoenvios-shipping.php';
include_once dirname( __FILE__ ) . '/includes/shipment/class-wc-mercadoenvios-shipping-normal.php';
include_once dirname( __FILE__ ) . '/includes/shipment/class-wc-mercadoenvios-shipping-express.php';
include_once dirname( __FILE__ ) . '/includes/shipment/class-wc-mercadoenvios-package.php';
add_filter( 'woocommerce_shipping_methods', array( $this, 'add_shipping' ) );
add_filter( 'woocommerce_available_payment_gateways', array( $this, 'filter_payment_method_by_shipping' ) );
// This adds custom links in the plugin page.
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'woomercadopago_settings_link' ) );
} else {
add_action( 'admin_notices', array( $this, 'notify_woocommerce_miss' ) );
}
if ( is_admin() ) {
$this->admin_includes();
}
}
/**
* Admin includes.
*/
private function admin_includes() {
include_once dirname( __FILE__ ) . '/includes/admin/class-wc-mercadoenvios-admin-orders.php';
}
/**
* Summary: As well as defining your class, you need to also tell WooCommerce (WC) that
* it exists. Do this by filtering woocommerce_payment_gateways.
* Description: As well as defining your class, you need to also tell WooCommerce (WC) that
* it exists. Do this by filtering woocommerce_payment_gateways.
* @return an array containing the payment methods.
*/
public function add_gateway( $methods ) {
$methods[] = 'WC_WooMercadoPago_BasicGateway';
$methods[] = 'WC_WooMercadoPago_CustomGateway';
$methods[] = 'WC_WooMercadoPago_TicketGateway';
//Get site_id and enable PSE only when credentials are set up and are from Colombia
$_site_id_v1 = get_option( '_site_id_v1', '' );
if ( !empty( $_site_id_v1 ) && $_site_id_v1=='MCO' ) {
$methods[] = 'WC_WooMercadoPago_PSEGateway';
}
$methods[] = 'WC_WooMercadoPago_SubscriptionGateway';
return $methods;
}
// Woocommerce_shipping_methods.
public function add_shipping( $methods ) {
$methods['woo-mercado-pago-me-normal'] = 'WC_MercadoEnvios_Shipping_Normal';
$methods['woo-mercado-pago-me-express'] = 'WC_MercadoEnvios_Shipping_Express';
return $methods;
}
// When selecting Mercado Envios as shipping method, customer can only do the payment with Mercado Pago Basic Checkout
public function filter_payment_method_by_shipping( $methods ) {
$session = WC()->session;
if ( ! isset( $session ) ) {
return $methods;
}
$chosen_methods = $session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
// Check shipping methods is a Mercado Envios.
if ( strpos( $chosen_shipping, 'woo-mercado-pago-me-normal' ) !== false || strpos( $chosen_shipping, 'woo-mercado-pago-me-express' ) !== false ) {
$new_array = array();
foreach ( $methods as $payment_method => $payment_method_object ) {
if ( $payment_method == 'woo-mercado-pago-basic' ) {
$new_array['woo-mercado-pago-basic'] = $payment_method_object;
}
}
// Return new array shipping methods (only with Mercado Pago Basic Checkout).
return $new_array;
}
// Return all shipping methods.
return $methods;
}
/**
* Summary: Places a warning error to notify user that WooCommerce is missing.
* Description: Places a warning error to notify user that WooCommerce is missing.
*/
public function notify_woocommerce_miss() {
echo '<div class="error"><p>' .
sprintf(
__( 'Woo Mercado Pago Module depends on the last version of %s to execute!', 'woocommerce-mercadopago' ),
'<a href="https://wordpress.org/extend/plugins/woocommerce/">WooCommerce</a>'
) .
'</p></div>';
}
// Add settings link on plugin page.
public function woomercadopago_settings_link( $links ) {
$plugin_links = array();
$plugin_links[] = '<a href="' . esc_url( admin_url(
'admin.php?page=mercado-pago-settings' ) ) .
'">' . __( 'Mercado Pago Settings', 'woocommerce-mercadopago' ) . '</a>';
$plugin_links[] = '<a target="_blank" href="' .
'https://wordpress.org/support/plugin/woo-mercado-pago-module/reviews/?rate=5#new-post' .
'">' . sprintf(
__( 'Rate Us', 'woocommerce-mercadopago' ) . ' %s',
'★★★★★'
) . '</a>';
$plugin_links[] = '<br><a target="_blank" href="' .
'https://github.com/mercadopago/cart-woocommerce#installation' .
'">' . __( 'Tutorial', 'woocommerce-mercadopago' ) . '</a>';
$plugin_links[] = '<a target="_blank" href="' .
'https://wordpress.org/support/plugin/woo-mercado-pago-module#postform' .
'">' . __( 'Report Issue', 'woocommerce-mercadopago' ) . '</a>';
return array_merge( $plugin_links, $links );
}
// ============================================================
/**
* Summary: Check if we have valid credentials for v0.
* Description: Check if we have valid credentials.
* @return boolean true/false depending on the validation result.
*/
public static function validate_credentials_v0() {
$client_id = get_option( '_mp_client_id', '' );
$client_secret = get_option( '_mp_client_secret', '' );
// Pre-validate.
$is_valid_credentials = true;
if ( empty( $client_id ) || empty( $client_secret ) ) {
$is_valid_credentials = false;
}
if ( ! is_numeric( $client_id ) ) {
$is_valid_credentials = false;
}
if ( $is_valid_credentials ) {
try {
$mp_v0 = new MP( WC_Woo_Mercado_Pago_Module::VERSION, $client_id, $client_secret );
$email = ( wp_get_current_user()->ID != 0 ) ? wp_get_current_user()->user_email : null;
$mp_v0->set_email( $email );
$locale = get_locale();
$locale = ( strpos( $locale, '_' ) !== false && strlen( $locale ) == 5 ) ? explode( '_', $locale ) : array('','');
$mp_v0->set_locale( $locale[1] );
$access_token = $mp_v0->get_access_token();
$get_request = $mp_v0->get( '/users/me?access_token=' . $access_token );
if ( isset( $get_request['response']['site_id'] ) && ! empty( $access_token ) ) {
update_option( '_test_user_v0', in_array( 'test_user', $get_request['response']['tags'], true ) );
update_option( '_site_id_v0', $get_request['response']['site_id'], true );
update_option( '_collector_id_v0', $get_request['response']['id'], true );
// Get available payment methods.
$payment_methods = $mp_v0->get( '/v1/payment_methods/?access_token=' . $access_token );
$arr = array();
$arr[] = 'n/d';
foreach ( $payment_methods['response'] as $payment ) {
$arr[] = $payment['id'];
}
update_option( '_all_payment_methods_v0', implode( ',', $arr ), true );
// Check for auto converstion of currency.
$currency_ratio = WC_Woo_Mercado_Pago_Module::get_conversion_rate(
WC_Woo_Mercado_Pago_Module::$country_configs[$get_request['response']['site_id']]['currency']
);
if ( $currency_ratio > 0 ) {
update_option( '_can_do_currency_conversion_v0', true, true );
} else {
update_option( '_can_do_currency_conversion_v0', false, true );
}
return true;
}
} catch ( MercadoPagoException $e ) {
// TODO: should we handle an exception here?
}
}
update_option( '_test_user_v0', '', true );
update_option( '_site_id_v0', '', true );
update_option( '_collector_id_v0', '', true );
update_option( '_all_payment_methods_v0', array(), true );
update_option( '_can_do_currency_conversion_v0', false, true );
return false;
}
/**
* Summary: Check if we have valid credentials for v1.
* Description: Check if we have valid credentials.
* @return boolean true/false depending on the validation result.
*/
public static function validate_credentials_v1() {
$public_key = get_option( '_mp_public_key', '' );
$access_token = get_option( '_mp_access_token', '' );
// Pre-validate.
$is_valid_credentials = true;
if ( empty( $public_key ) || empty( $access_token ) ) {
$is_valid_credentials = false;
}
if ( strpos( $public_key, 'APP_USR' ) === false && strpos( $public_key, 'TEST' ) === false ) {
$is_valid_credentials = false;
}
if ( strpos( $access_token, 'APP_USR' ) === false && strpos( $access_token, 'TEST' ) === false ) {
$is_valid_credentials = false;
}
if ( $is_valid_credentials ) {
try {
$mp_v1 = new MP( WC_Woo_Mercado_Pago_Module::VERSION, $access_token );
$email = ( wp_get_current_user()->ID != 0 ) ? wp_get_current_user()->user_email : null;
$mp_v1->set_email( $email );
$locale = get_locale();
$locale = ( strpos( $locale, '_' ) !== false && strlen( $locale ) == 5 ) ? explode( '_', $locale ) : array('','');
$mp_v1->set_locale( $locale[1] );
$access_token = $mp_v1->get_access_token();
$get_request = $mp_v1->get( '/users/me?access_token=' . $access_token );
if ( isset( $get_request['response']['site_id'] ) && ! empty( $public_key ) ) {
update_option( '_test_user_v1', in_array( 'test_user', $get_request['response']['tags'] ), true );
update_option( '_site_id_v1', $get_request['response']['site_id'], true );
update_option( '_collector_id_v1', $get_request['response']['id'], true );
// Get available payment methods.
$payments = $mp_v1->get( '/v1/payment_methods/?access_token=' . $access_token );
$payment_methods_ticket = array();
foreach ( $payments['response'] as $payment ) {
if ( isset( $payment['payment_type_id'] ) ) {
if ( $payment['payment_type_id'] != 'account_money' &&
$payment['payment_type_id'] != 'credit_card' &&
$payment['payment_type_id'] != 'debit_card' &&
$payment['payment_type_id'] != 'prepaid_card' &&
$payment['id'] != 'pse') {
$obj = new stdClass();
$obj->id = $payment['id'];
$obj->name = $payment['name'];
$obj->secure_thumbnail = $payment['secure_thumbnail'];
array_push( $payment_methods_ticket, $obj );
}
}
}
update_option( '_all_payment_methods_ticket', json_encode( $payment_methods_ticket ), true );
// Check for auto converstion of currency.
$currency_ratio = WC_Woo_Mercado_Pago_Module::get_conversion_rate(
WC_Woo_Mercado_Pago_Module::$country_configs[$get_request['response']['site_id']]['currency']
);
if ( $currency_ratio > 0 ) {
update_option( '_can_do_currency_conversion_v1', true, true );
} else {
update_option( '_can_do_currency_conversion_v1', false, true );
}
return true;
}
} catch ( MercadoPagoException $e ) {
// TODO: should we handle an exception here?
}
}
update_option( '_test_user_v1', '', true );
update_option( '_site_id_v1', '', true );
update_option( '_collector_id_v1', '', true );
update_option( '_all_payment_methods_ticket', '[]', true );
update_option( '_can_do_currency_conversion_v1', false, true );
return false;
}
// Get WooCommerce instance
public static function woocommerce_instance() {
if ( function_exists( 'WC' ) ) {
return WC();
} else {
global $woocommerce;
return $woocommerce;
}
}
// Get common error messages
public static function get_common_error_messages( $key ) {
if ( $key === 'Invalid payment_method_id' ) {
return __( 'Invalid payment_method_id', 'woocommerce-mercadopago' );
}
if ( $key === 'Invalid transaction_amount' ) {
return __( 'Invalid transaction_amount', 'woocommerce-mercadopago' ) . ' ' .
__( 'Posible causes: Currency not supported; Values under the minimal or above the maximun allowed.', 'woocommerce-mercadopago' );
}
if ( $key === 'Invalid users involved' ) {
return __( 'Invalid users involved', 'woocommerce-mercadopago' ) . ' ' .
__( 'Posible causes: Seller and buyer have the same email in Mercado Pago; Transaction involves production and test users.', 'woocommerce-mercadopago' );
}
if ( $key === 'Unauthorized use of live credentials' ) {
return __( 'Unauthorized use of live credentials', 'woocommerce-mercadopago' ) . ' ' .
__( 'Posible causes: Pending permission of use in production of the seller credentials.', 'woocommerce-mercadopago' );
}
return $key;
}
/**
* Summary: Get the rate of conversion between two currencies.
* Description: The currencies are the one used in WooCommerce and the one used in $site_id.
* @return a float that is the rate of conversion.
*/
public static function get_conversion_rate( $used_currency ) {
$wc_currency = get_woocommerce_currency();
$email = ( wp_get_current_user()->ID != 0 ) ? wp_get_current_user()->user_email : null;
MPRestClient::set_email( $email );
if ( strlen( $wc_currency ) == 3 && strlen( $used_currency ) == 3 ) {
$currency_obj = MPRestClient::get(
array( 'uri' => '/currency_conversions/search?' .
'from=' . get_woocommerce_currency() .
'&to=' . $used_currency
),
WC_Woo_Mercado_Pago_Module::get_module_version()
);
if ( isset( $currency_obj['response'] ) ) {
$currency_obj = $currency_obj['response'];
if ( isset( $currency_obj['ratio'] ) ) {
return ( (float) $currency_obj['ratio'] );
}
}
}
return -1;
}
/**
* Summary: Builds up the array for the mp_install table, with info related with checkout.
* Description: Builds up the array for the mp_install table, with info related with checkout.
* @return an array with the module informations.
*/
public static function get_common_settings() {
$w = WC_Woo_Mercado_Pago_Module::woocommerce_instance();
$infra_data = array(
'module_version' => WC_Woo_Mercado_Pago_Module::VERSION,
'platform' => 'WooCommerce',
'platform_version' => $w->version,
'code_version' => phpversion(),
'so_server' => PHP_OS
);
return $infra_data;
}
/**
* Summary: Get store categories from Mercado Pago.
* Description: Trigger API to get available categories and proper description.
* @return an array with found categories and a description for its selector title.
*/
public static function get_categories() {
$store_categories_id = array();
$store_categories_description = array();
// Get Mercado Pago store categories.
$email = ( wp_get_current_user()->ID != 0 ) ? wp_get_current_user()->user_email : null;
MPRestClient::set_email( $email );
$categories = MPRestClient::get(
array( 'uri' => '/item_categories' ),
WC_Woo_Mercado_Pago_Module::get_module_version()
);
foreach ( $categories['response'] as $category ) {
array_push(
$store_categories_id, str_replace( '_', ' ', $category['id'] )
);
array_push(
$store_categories_description, str_replace( '_', ' ', $category['description'] )
);
}
return array(
'store_categories_id' => $store_categories_id,
'store_categories_description' => $store_categories_description
);
}
/**
* Summary: Get information about the used Mercado Pago account based in its site.
* Description: Get information about the used Mercado Pago account based in its site.
* @return an array with the information.
*/
public static function get_site_data( $is_v1 = false ) {
if ( ! $is_v1 ) {
$site_id = get_option( '_site_id_v0', '' );
} else {
$site_id = get_option( '_site_id_v1', '' );
}
if ( isset( $site_id ) && ! empty( $site_id ) ) {
return WC_Woo_Mercado_Pago_Module::$country_configs[$site_id];
} else {
return null;
}
}
// Fix to URL Problem : #038; replaces & and breaks the navigation.
public static function fix_url_ampersand( $link ) {
return str_replace( '\/', '/', str_replace( '&', '&', $link) );
}
/**
* Summary: Find template's folder.
* Description: Find template's folder.
* @return a string that identifies the path.
*/
public static function get_templates_path() {
return plugin_dir_path( __FILE__ ) . 'templates/';
}
/**
* Summary: Get module's version.
* Description: Get module's version.
* @return a string with the given version.
*/
public static function get_module_version() {
return WC_Woo_Mercado_Pago_Module::VERSION;
}
/**
* Summary: Get client id from access token.
* Description: Get client id from access token.
* @return the client id.
*/
public static function get_client_id( $at ) {
$t = explode ( '-', $at );
if ( count( $t ) > 0 ) {
return $t[1];
}
return '';
}
// Check if an order is recurrent.
public static function is_subscription( $items ) {
$is_subscription = false;
if ( sizeof( $items ) == 1 ) {
foreach ( $items as $cart_item_key => $cart_item ) {
$is_recurrent = ( method_exists( $cart_item, 'get_meta' ) ) ?
$cart_item->get_meta( '_used_gateway' ) :
get_post_meta( $cart_item['product_id'], '_mp_recurring_is_recurrent', true );
if ( $is_recurrent == 'yes' ) {
$is_subscription = true;
}
}
}
return $is_subscription;
}
// Return boolean indicating if currency is supported.
public static function is_supported_currency( $site_id ) {
return get_woocommerce_currency() == WC_Woo_Mercado_Pago_Module::$country_configs[$site_id]['currency'];
}
public static function build_currency_conversion_err_msg( $currency ) {
return '<img width="14" height="14" src="' .
plugins_url( 'assets/images/error.png', __FILE__ ) . '"> ' .
__( 'ERROR: It was not possible to convert the unsupported currency', 'woocommerce-mercadopago' ) .
' ' . get_woocommerce_currency() . ' ' .
__( 'to', 'woocommerce-mercadopago' ) . ' ' . $currency . '. ' .
__( 'Currency conversions should be made outside this module.', 'woocommerce-mercadopago' );
}
public static function build_currency_not_converted_msg( $currency, $country_name ) {
return '<img width="14" height="14" src="' .
plugins_url( 'assets/images/warning.png', __FILE__ ) . '"> ' .
__( 'ATTENTION: The currency', 'woocommerce-mercadopago' ) .
' ' . get_woocommerce_currency() . ' ' .
__( 'defined in WooCommerce is different from the one used in your credentials country.<br>The currency for transactions in this payment method will be', 'woocommerce-mercadopago' ) .
' ' . $currency . ' (' . $country_name . '). ' .
__( 'Currency conversions should be made outside this module.', 'woocommerce-mercadopago' );
}
public static function build_currency_converted_msg( $currency ) {
return '<img width="14" height="14" src="' .
plugins_url( 'assets/images/check.png', __FILE__ ) . '"> ' .
__( 'CURRENCY CONVERTED: Your store is converting currency from', 'woocommerce-mercadopago' ) .
' ' . get_woocommerce_currency() . ' ' .
__( 'to', 'woocommerce-mercadopago' ) . ' ' . $currency;
}
public static function get_country_name( $site_id ) {
switch ( $site_id ) {
case 'MCO':
return __( 'Colombia', 'woocommerce-mercadopago' );
case 'MLA':
return __( 'Argentine', 'woocommerce-mercadopago' );
case 'MLB':
return __( 'Brazil', 'woocommerce-mercadopago' );
case 'MLC':
return __( 'Chile', 'woocommerce-mercadopago' );
case 'MLM':
return __( 'Mexico', 'woocommerce-mercadopago' );
case 'MLU':
return __( 'Uruguay', 'woocommerce-mercadopago' );
case 'MLV':
return __( 'Venezuela', 'woocommerce-mercadopago' );
case 'MPE':
return __( 'Peru', 'woocommerce-mercadopago' );
}
return '';
}
// Build the string representing the path to the log file.
public static function build_log_path_string( $gateway_id, $gateway_name ) {
return '<a href="' . esc_url( admin_url( 'admin.php?page=wc-status&tab=logs&log_file=' .
esc_attr( $gateway_id ) . '-' . sanitize_file_name( wp_hash( $gateway_id ) ) . '.log' ) ) . '">' .
$gateway_name . '</a>';
}
public static function get_wc_status_for_mp_status( $mp_status ) {
$defaults = array(
'pending' => 'pending',
'approved' => 'processing',
'inprocess' => 'on_hold',
'inmediation' => 'on_hold',
'rejected' => 'failed',
'cancelled' => 'cancelled',
'refunded' => 'refunded',
'chargedback' => 'refunded'
);
$status = get_option( '_mp_order_status_' . $mp_status . '_map', $defaults[$mp_status] );
return str_replace( '_', '-', $status );
}
public static function get_map( $selector_id ) {
$arr = explode( '_', $selector_id );
$defaults = array(
'pending' => 'pending',
'approved' => 'processing',
'inprocess' => 'on_hold',
'inmediation' => 'on_hold',
'rejected' => 'failed',
'cancelled' => 'cancelled',
'refunded' => 'refunded',
'chargedback' => 'refunded'
);
$selection = get_option( '_mp_' . $selector_id, $defaults[$arr[2]] );
foreach ( wc_get_order_statuses() as $slug => $status ) {
$slug = str_replace( array( 'wc-', '-' ), array( '', '_' ), $slug );
$html .= sprintf(
'<option value="%s"%s>%s %s</option>',
$slug,
selected( $selection, $slug, false ),
__( 'Update WooCommerce order to ', 'woocommerce-mercadopago' ),
$status
);
}
return $html;
}
public static function generate_refund_cancel_subscription( $domain, $success_msg, $fail_msg, $options, $str1, $str2, $str3, $str4 ) {
$subscription_js = '<script type="text/javascript">
( function() {
var MPSubscription = {}
MPSubscription.callSubscriptionCancel = function () {
var url = "' . $domain . '";
url += "&action_mp_payment_id=" + document.getElementById("payment_id").value;
url += "&action_mp_payment_amount=" + document.getElementById("payment_amount").value;
url += "&action_mp_payment_action=cancel";
document.getElementById("sub_pay_cancel_btn").disabled = true;
MPSubscription.AJAX({
url: url,
method : "GET",
timeout : 5000,
error: function() {
document.getElementById("sub_pay_cancel_btn").disabled = false;
alert("' . $fail_msg . '");
},
success : function ( status, data ) {
document.getElementById("sub_pay_cancel_btn").disabled = false;
var mp_status = data.status;
var mp_message = data.message;
if (data.status == 200) {
alert("' . $success_msg . '");
} else {
alert(mp_message);
}
}
});
}
MPSubscription.callSubscriptionRefund = function () {
var url = "' . $domain . '";
url += "&action_mp_payment_id=" + document.getElementById("payment_id").value;
url += "&action_mp_payment_amount=" + document.getElementById("payment_amount").value;
url += "&action_mp_payment_action=refund";
document.getElementById("sub_pay_refund_btn").disabled = true;
MPSubscription.AJAX({
url: url,
method : "GET",
timeout : 5000,
error: function() {
document.getElementById("sub_pay_refund_btn").disabled = false;
alert("' . $fail_msg . '");
},
success : function ( status, data ) {
document.getElementById("sub_pay_refund_btn").disabled = false;
var mp_status = data.status;
var mp_message = data.message;
if (data.status == 200) {
alert("' . $success_msg . '");
} else {
alert(mp_message);
}
}
});
}
MPSubscription.AJAX = function( options ) {
var useXDomain = !!window.XDomainRequest;
var req = useXDomain ? new XDomainRequest() : new XMLHttpRequest()
var data;
options.url += ( options.url.indexOf( "?" ) >= 0 ? "&" : "?" );
options.requestedMethod = options.method;
if ( useXDomain && options.method == "PUT" ) {
options.method = "POST";
options.url += "&_method=PUT";
}
req.open( options.method, options.url, true );
req.timeout = options.timeout || 1000;
if ( window.XDomainRequest ) {
req.onload = function() {
data = JSON.parse( req.responseText );
if ( typeof options.success === "function" ) {
options.success( options.requestedMethod === "POST" ? 201 : 200, data );
}
};
req.onerror = req.ontimeout = function() {
if ( typeof options.error === "function" ) {
options.error( 400, {
user_agent:window.navigator.userAgent, error : "bad_request", cause:[]
});
}
};
req.onprogress = function() {};
} else {
req.setRequestHeader( "Accept", "application/json" );
if ( options.contentType ) {
req.setRequestHeader( "Content-Type", options.contentType );
} else {
req.setRequestHeader( "Content-Type", "application/json" );
}
req.onreadystatechange = function() {
if ( this.readyState === 4 ) {
if ( this.status >= 200 && this.status < 400 ) {
// Success!
data = JSON.parse( this.responseText );
if ( typeof options.success === "function" ) {
options.success( this.status, data );
}
} else if ( this.status >= 400 ) {
data = JSON.parse( this.responseText );
if ( typeof options.error === "function" ) {
options.error( this.status, data );
}
} else if ( typeof options.error === "function" ) {
options.error( 503, {} );
}
}
};
}
if ( options.method === "GET" || options.data == null || options.data == undefined ) {
req.send();
} else {
req.send( JSON.stringify( options.data ) );
}
}
this.MPSubscription = MPSubscription;
} ).call();
</script>';
$subscription_meta_box = '<table>' .
'<tr class="total">' .
'<td><label for="payment_id" style="margin-right:1px;">' .
$str1 .
'</label></td>' .
'<td><select id="payment_id" name="refund_payment_id" style="margin-left:1px;">' .
$options .
'</select></td>' .
'</tr>' .
'<tr class="total">' .
'<td><label for="payment_amount" style="margin-right:1px;">' .
$str2 .
'</label></td>' .
'<td><input type="number" class="text amount_input" id="payment_amount" value="0" name="payment_amount"' .
' placeholder="Decimal" min="0" step="0.01" value="0.00" style="width:112px; margin-left:1px;"' .
' ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/"/>' .
'</td>' .
'</tr>' .
'<tr class="total">' .
'<td><input onclick="MPSubscription.callSubscriptionRefund();" type="button"' .
' id="sub_pay_refund_btn" class="button button" style="margin-left:1px; margin-top:2px;"' .
' name="refund" value="' . $str3 .
'" style="margin-right:1px;"></td>' .
'<td><input onclick="MPSubscription.callSubscriptionCancel();" type="button"' .
' id="sub_pay_cancel_btn" class="button button" style="margin-right:1px; margin-top:2px;"' .
' name="cancel" value="' . $str4 .
'" style="margin-left:1px;"></td>' .
'</tr>' .
'</table>';
return $subscription_js . $subscription_meta_box;
}
/**
* Check if product dimensions are well defined
*/
public static function is_product_dimensions_valid( $all_product_data ) {
if ( empty( $all_product_data ) ) {
return true;
}
foreach ( $all_product_data as $p ) {
$product = wc_get_product( $p->ID );
if ( ! $product->is_virtual() ) {
$w = $product->get_weight();
$dimensions = $product->get_dimensions( false );
if ( empty( $w ) || ! is_numeric( $w ) ) {
return false;
}
if ( ! is_numeric( $dimensions['height'] ) ) {
return false;
}
if ( ! is_numeric( $dimensions['width'] ) ) {
return false;
}
if ( ! is_numeric( $dimensions['length'] ) ) {
return false;
}
}
}
return true;
}
}
//=====
// Create Mercado Pago option menu.
add_action( 'admin_menu', function() {
add_options_page(
'Mercado Pago Options', 'Mercado Pago', 'manage_options', 'mercado-pago-settings',
function() {
// Verify permissions.
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
// Check for submits.
if ( isset( $_POST['submit'] ) ) {
update_option( '_mp_client_id', isset( $_POST['client_id'] ) ? $_POST['client_id'] : '', true );
update_option( '_mp_client_secret', isset( $_POST['client_secret'] ) ? $_POST['client_secret'] : '', true );
update_option( '_mp_public_key', isset( $_POST['public_key'] ) ? $_POST['public_key'] : '', true );
update_option( '_mp_access_token', isset( $_POST['access_token'] ) ? $_POST['access_token'] : '', true );
update_option( '_mp_success_url', isset( $_POST['success_url'] ) ? $_POST['success_url'] : '', true );
update_option( '_mp_fail_url', isset( $_POST['fail_url'] ) ? $_POST['fail_url'] : '', true );
update_option( '_mp_pending_url', isset( $_POST['pending_url'] ) ? $_POST['pending_url'] : '', true );
update_option( '_mp_order_status_pending_map', isset( $_POST['order_status_pending_map'] ) ? $_POST['order_status_pending_map'] : '', true );
update_option( '_mp_order_status_approved_map', isset( $_POST['order_status_approved_map'] ) ? $_POST['order_status_approved_map'] : '', true );
update_option( '_mp_order_status_inprocess_map', isset( $_POST['order_status_inprocess_map'] ) ? $_POST['order_status_inprocess_map'] : '', true );
update_option( '_mp_order_status_inmediation_map', isset( $_POST['order_status_inmediation_map'] ) ? $_POST['order_status_inmediation_map'] : '', true );
update_option( '_mp_order_status_rejected_map', isset( $_POST['order_status_rejected_map'] ) ? $_POST['order_status_rejected_map'] : '', true );
update_option( '_mp_order_status_cancelled_map', isset( $_POST['order_status_cancelled_map'] ) ? $_POST['order_status_cancelled_map'] : '', true );
update_option( '_mp_order_status_refunded_map', isset( $_POST['order_status_refunded_map'] ) ? $_POST['order_status_refunded_map'] : '', true );
update_option( '_mp_order_status_chargedback_map', isset( $_POST['order_status_chargedback_map'] ) ? $_POST['order_status_chargedback_map'] : '', true );
update_option( '_mp_statement_descriptor', isset( $_POST['statement_descriptor'] ) ? $_POST['statement_descriptor'] : '', true );
if ( isset( $_POST['category_id'] ) ) {
update_option( '_mp_category_id', $_POST['category_id'], true );
$categories_data = WC_Woo_Mercado_Pago_Module::$categories;
update_option( '_mp_category_name', $categories_data['store_categories_id'][$_POST['category_id']], true );
} else {
update_option( '_mp_category_id', '', true );
update_option( '_mp_category_name', 'others', true );
}
update_option( '_mp_store_identificator', isset( $_POST['store_identificator'] ) ? $_POST['store_identificator'] : '', true );
update_option( '_mp_custom_banner', isset( $_POST['custom_banner'] ) ? $_POST['custom_banner'] : '', true );
update_option( '_mp_custom_domain', isset( $_POST['custom_domain'] ) ? $_POST['custom_domain'] : '', true );
update_option( '_mp_currency_conversion_v0', isset( $_POST['currency_conversion_v0'] ) ? $_POST['currency_conversion_v0'] : '', true );
update_option( '_mp_currency_conversion_v1', isset( $_POST['currency_conversion_v1'] ) ? $_POST['currency_conversion_v1'] : '', true );
update_option( '_mp_debug_mode', isset( $_POST['debug_mode'] ) ? $_POST['debug_mode'] : '', true );
update_option( '_mp_sandbox_mode', isset( $_POST['sandbox_mode'] ) ? $_POST['sandbox_mode'] : '', true );
}
// Mercado Pago logo.
$mp_logo = '<img width="185" height="48" src="' . plugins_url( 'assets/images/mplogo.png', __FILE__ ) . '">';
// Check WooCommerce.
$has_woocommerce_message = class_exists( 'WC_Payment_Gateway' ) ?
'<img width="14" height="14" src="' . plugins_url( 'assets/images/check.png', __FILE__ ) . '"> ' .
__( 'WooCommerce is installed and enabled.', 'woocommerce-mercadopago' ) :
'<img width="14" height="14" src="' . plugins_url( 'assets/images/error.png', __FILE__ ) . '"> ' .
__( 'You don\'t have WooCommerce installed and enabled.', 'woocommerce-mercadopago' );
// Creating PHP version message.
// Check for PHP version and throw notice.
$min_php_message = '<img width="14" height="14" src="' . plugins_url( 'assets/images/check.png', __FILE__ ) . '"> ' .
__( 'Your PHP version is OK.', 'woocommerce-mercadopago' );
if ( version_compare( PHP_VERSION, WC_Woo_Mercado_Pago_Module::MIN_PHP, '<=' ) ) {
$min_php_message = '<img width="14" height="14" src="' . plugins_url( 'assets/images/warning.png', __FILE__ ) . '"> ' .
sprintf(
__( 'Your PHP version do not support this module. You have %s, minimal required is %s.', 'woocommerce-mercadopago' ),
phpversion(), WC_Woo_Mercado_Pago_Module::MIN_PHP
);
}
// Check cURL.
$curl_message = in_array( 'curl', get_loaded_extensions() ) ?
'<img width="14" height="14" src="' . plugins_url( 'assets/images/check.png', __FILE__ ) . '"> ' .
__( 'cURL is installed.', 'woocommerce-mercadopago' ) :
'<img width="14" height="14" src="' . plugins_url( 'assets/images/error.png', __FILE__ ) . '"> ' .
__( 'cURL is not installed.', 'woocommerce-mercadopago' );
// Check SSL.
$is_ssl_message = empty( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS'] == 'off' ?
'<img width="14" height="14" src="' . plugins_url( 'assets/images/warning.png', __FILE__ ) . '"> ' .
__( 'SSL is missing in your site.', 'woocommerce-mercadopago' ) :
'<img width="14" height="14" src="' . plugins_url( 'assets/images/check.png', __FILE__ ) . '"> ' .
__( 'Your site has SSL enabled.', 'woocommerce-mercadopago' );