From a0ac0df2a4cb6ca88cbdc4212506442c7c8dd0b8 Mon Sep 17 00:00:00 2001 From: Fernando Lira Date: Wed, 6 Jan 2021 15:57:53 -0300 Subject: [PATCH 01/99] =?UTF-8?q?Applied=20Wordpress=20Coding=20Standards?= =?UTF-8?q?=20=F0=9F=98=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .editorconfig | 35 +- i18n/languages/woocommerce-mercadopago.pot | 535 ++-- .../notices/WC_WooMercadoPago_Notices.php | 222 +- .../WC_WooMercadoPago_ReviewNotice.php | 190 +- ...oMercadoPago_Helpers_CurrencyConverter.php | 864 +++--- includes/module/WC_WooMercadoPago_Configs.php | 529 ++-- .../module/WC_WooMercadoPago_Credentials.php | 663 ++-- .../module/WC_WooMercadoPago_Exception.php | 21 +- includes/module/WC_WooMercadoPago_Init.php | 287 +- includes/module/WC_WooMercadoPago_Module.php | 1366 +++++---- .../config/WC_WooMercadoPago_Constants.php | 16 +- includes/module/log/WC_WooMercadoPago_Log.php | 159 +- .../WC_WooMercadoPago_PreferenceAbstract.php | 863 +++--- .../WC_WooMercadoPago_PreferenceBasic.php | 234 +- .../WC_WooMercadoPago_PreferenceCustom.php | 151 +- .../WC_WooMercadoPago_PreferenceTicket.php | 216 +- .../WC_WooMercadoPago_PreferenceAnalytics.php | 44 +- includes/module/sdk/lib/MP.php | 1389 +++++---- .../sdk/lib/RestClient/AbstractRestClient.php | 316 +- .../sdk/lib/RestClient/MeliRestClient.php | 82 +- .../sdk/lib/RestClient/MpRestClient.php | 80 +- ...C_WooMercadoPago_Notification_Abstract.php | 781 +++-- .../WC_WooMercadoPago_Notification_IPN.php | 307 +- ...WC_WooMercadoPago_Notification_Webhook.php | 325 +- .../WC_WooMercadoPago_BasicGateway.php | 1258 ++++---- .../WC_WooMercadoPago_CustomGateway.php | 1076 ++++--- .../WC_WooMercadoPago_PaymentAbstract.php | 2657 ++++++++--------- .../WC_WooMercadoPago_TicketGateway.php | 1205 ++++---- .../hooks/WC_WooMercadoPago_Hook_Abstract.php | 670 ++--- .../hooks/WC_WooMercadoPago_Hook_Basic.php | 193 +- .../hooks/WC_WooMercadoPago_Hook_Custom.php | 196 +- .../hooks/WC_WooMercadoPago_Hook_Ticket.php | 222 +- .../stock/WC_WooMercadoPago_Stock_Manager.php | 96 +- templates/checkout/basic_checkout.php | 94 +- templates/checkout/custom_checkout.php | 114 +- templates/checkout/ticket_checkout.php | 572 ++-- woocommerce-mercadopago.php | 21 +- 37 files changed, 8976 insertions(+), 9073 deletions(-) diff --git a/.editorconfig b/.editorconfig index bb8863a7e..9fa6c0027 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,12 +1,35 @@ +# This file is for unifying the coding style for different editors and IDEs +# editorconfig.org + +# WordPress Coding Standards +# https://make.wordpress.org/core/handbook/coding-standards/ + +root = true + [*] -trim_trailing_whitespace = true -insert_final_newline = true -end_of_line = lf charset = utf-8 -indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = tab +block_comment_start = /* +block_comment = * +block_comment_end = */ -[*.js] +[{*.yml,*.neon}] +indent_style = space indent_size = 2 -[*.{html,php}] +[{composer.json,composer.lock,package.json}] +indent_style = space indent_size = 4 + +[*.md] +trim_trailing_whitespace = false + +[{wp-config-sample.php}] +end_of_line = crlf + +[{LICENSE.txt,README.txt}] +indent_style = space +end_of_line = lf diff --git a/i18n/languages/woocommerce-mercadopago.pot b/i18n/languages/woocommerce-mercadopago.pot index 9fe671d6a..d4282d81c 100644 --- a/i18n/languages/woocommerce-mercadopago.pot +++ b/i18n/languages/woocommerce-mercadopago.pot @@ -14,375 +14,375 @@ msgstr "" "X-Poedit-SourceCharset: UTF-8\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" -#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:52 +#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:51 msgid "Activate this option so that the value of the currency set in WooCommerce is compatible with the value of the currency you use in Mercado Pago." msgstr "" -#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:327 +#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:313 msgid "Convert Currency" msgstr "" -#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:332, includes/payments/WC_WooMercadoPago_BasicGateway.php:500, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:593, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:677, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:963, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1070, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1105, includes/payments/WC_WooMercadoPago_TicketGateway.php:281 +#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:318, includes/payments/WC_WooMercadoPago_BasicGateway.php:489, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:574, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:652, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:919, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1020, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1053, includes/payments/WC_WooMercadoPago_TicketGateway.php:273 msgid "No" msgstr "" -#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:333, includes/payments/WC_WooMercadoPago_BasicGateway.php:499, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:594, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:678, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:964, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1071, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1104, includes/payments/WC_WooMercadoPago_TicketGateway.php:282 +#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:319, includes/payments/WC_WooMercadoPago_BasicGateway.php:488, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:575, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:653, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:920, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1021, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1052, includes/payments/WC_WooMercadoPago_TicketGateway.php:274 msgid "Yes" msgstr "" -#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:395 -msgid "Now we convert your currency from %s to %s." +#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:378 +msgid "Now we convert your currency from %1$s to %2$s." msgstr "" -#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:410 -msgid "We no longer convert your currency from %s to %s." +#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:392 +msgid "We no longer convert your currency from %1$s to %2$s." msgstr "" -#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:427 +#: includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php:408 msgid "Attention: The currency settings you have in WooCommerce are not compatible with the currency you use in your Mercado Pago account. Please activate the currency conversion." msgstr "" -#: includes/module/WC_WooMercadoPago_Configs.php:103 +#: includes/module/WC_WooMercadoPago_Configs.php:98 msgid "Update your credentials with the Access Token and Public Key, you need them to continue receiving payments!" msgstr "" -#: includes/module/WC_WooMercadoPago_Configs.php:113 +#: includes/module/WC_WooMercadoPago_Configs.php:107 msgid "The store should have HTTPS in order to activate both Checkout Personalizado and Ticket Checkout." msgstr "" -#: includes/module/WC_WooMercadoPago_Init.php:37 +#: includes/module/WC_WooMercadoPago_Init.php:35 msgid "Mercado Pago payments for WooCommerce requires PHP version 5.6 or later. Please update your PHP version." msgstr "" -#: includes/module/WC_WooMercadoPago_Init.php:47 +#: includes/module/WC_WooMercadoPago_Init.php:44 msgid "Mercado Pago Error: PHP Extension CURL is not installed." msgstr "" -#: includes/module/WC_WooMercadoPago_Init.php:59 +#: includes/module/WC_WooMercadoPago_Init.php:55 msgid "The Mercado Pago module needs an active version of %s in order to work!" msgstr "" -#: includes/module/WC_WooMercadoPago_Init.php:67 +#: includes/module/WC_WooMercadoPago_Init.php:62 msgid "Cancel order" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:242, includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:348 +#: includes/module/WC_WooMercadoPago_Module.php:227, includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:336 msgid "Fill in your credentials to enable payment methods." msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:251 +#: includes/module/WC_WooMercadoPago_Module.php:235 msgid "Set up" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:252 +#: includes/module/WC_WooMercadoPago_Module.php:236 msgid "Your opinion helps us get better" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:253 +#: includes/module/WC_WooMercadoPago_Module.php:237 msgid "Guides and Documentation" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:254 +#: includes/module/WC_WooMercadoPago_Module.php:238 msgid "Report Problem" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:325 +#: includes/module/WC_WooMercadoPago_Module.php:309 msgid "By Mercado Pago" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:350, includes/module/WC_WooMercadoPago_Module.php:371 +#: includes/module/WC_WooMercadoPago_Module.php:333, includes/module/WC_WooMercadoPago_Module.php:354 msgid "The Sponsor ID must be valid!" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:367 +#: includes/module/WC_WooMercadoPago_Module.php:350 msgid "The Sponsor ID must be from the same country as the seller!" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:398 +#: includes/module/WC_WooMercadoPago_Module.php:380 msgid "The payment method is not valid or not available." msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:401 +#: includes/module/WC_WooMercadoPago_Module.php:383 msgid "The transaction amount cannot be processed by Mercado Pago." msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:402 +#: includes/module/WC_WooMercadoPago_Module.php:384 msgid "Possible causes: Currency not supported; Amounts below the minimum or above the maximum allowed." msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:405 +#: includes/module/WC_WooMercadoPago_Module.php:387 msgid "The users are not valid." msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:406 +#: includes/module/WC_WooMercadoPago_Module.php:388 msgid "Possible causes: Buyer and seller have the same account in Mercado Pago; The transaction involving production and test users." msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:409 +#: includes/module/WC_WooMercadoPago_Module.php:391 msgid "Unauthorized use of production credentials." msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:410 +#: includes/module/WC_WooMercadoPago_Module.php:392 msgid "Possible causes: Use permission in use for the credential of the seller." msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:528 +#: includes/module/WC_WooMercadoPago_Module.php:505 msgid "ERROR: It was not possible to convert the unsupported currency" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:530 +#: includes/module/WC_WooMercadoPago_Module.php:507 msgid "a" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:531, includes/module/WC_WooMercadoPago_Module.php:542 +#: includes/module/WC_WooMercadoPago_Module.php:508, includes/module/WC_WooMercadoPago_Module.php:518 msgid "Currency conversions should be done outside of this module." msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:538 +#: includes/module/WC_WooMercadoPago_Module.php:514 msgid "ATTENTION: The currency" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:540 +#: includes/module/WC_WooMercadoPago_Module.php:516 msgid "defined in WooCommerce is different from that used by the credentials of your country.
The currency for transactions made with this payment method will be" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:549 +#: includes/module/WC_WooMercadoPago_Module.php:524 msgid "CONVERTED CURRENCY: Your store is converting currency of" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:551, templates/checkout/custom_checkout.php:135 +#: includes/module/WC_WooMercadoPago_Module.php:526, templates/checkout/custom_checkout.php:135 msgid "for" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:558, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:536 +#: includes/module/WC_WooMercadoPago_Module.php:532, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:520 msgid "Colombia" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:560, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:533 +#: includes/module/WC_WooMercadoPago_Module.php:534, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:517 msgid "Argentina" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:562, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:534 +#: includes/module/WC_WooMercadoPago_Module.php:536, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:518 msgid "Brazil" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:564, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:535 +#: includes/module/WC_WooMercadoPago_Module.php:538, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:519 msgid "Chile" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:566, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:537 +#: includes/module/WC_WooMercadoPago_Module.php:540, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:521 msgid "Mexico" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:568, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:539 +#: includes/module/WC_WooMercadoPago_Module.php:542, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:523 msgid "Uruguay" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:570 +#: includes/module/WC_WooMercadoPago_Module.php:544 msgid "Venezuela" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:572, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:538 +#: includes/module/WC_WooMercadoPago_Module.php:546, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:522 msgid "Peru" msgstr "" -#: includes/module/WC_WooMercadoPago_Module.php:607 +#: includes/module/WC_WooMercadoPago_Module.php:583 msgid "Update the WooCommerce order to " msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:142 +#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:137 msgid "Payment approved." msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:195, includes/notification/WC_WooMercadoPago_Notification_Abstract.php:198 +#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:189, includes/notification/WC_WooMercadoPago_Notification_Abstract.php:192 msgid "Waiting for the ticket payment." msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:205 +#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:200 msgid "The customer has not made the payment yet." msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:224 +#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:218 msgid "Payment is pending review." msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:241 +#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:234 msgid "Payment was declined. The customer can try again." msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:257 +#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:249 msgid "Payment was returned to the customer." msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:270 +#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:261 msgid "Payment was canceled." msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:286, includes/notification/WC_WooMercadoPago_Notification_Abstract.php:298 +#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:276, includes/notification/WC_WooMercadoPago_Notification_Abstract.php:287 msgid "The payment is in mediation or the purchase was unknown by the customer." msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:388 -msgid "Mercado Pago: The payment %s was notified by Mercado Pago with status %s." +#: includes/notification/WC_WooMercadoPago_Notification_Abstract.php:376 +msgid "Mercado Pago: The payment %1$s was notified by Mercado Pago with status %2$s." msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:35 +#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:34 msgid "No ID or TOPIC param in Request IPN" msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:40 +#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:39 msgid "Type of topic IPN invalid, need to be merchant_order" msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:49 +#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:48 msgid "IPN merchant_order not found" msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:55 +#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:54 msgid "Not found Payments into Merchant_Order" msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:148, includes/notification/WC_WooMercadoPago_Notification_IPN.php:122, includes/notification/WC_WooMercadoPago_Notification_Webhook.php:156, includes/notification/WC_WooMercadoPago_Notification_Webhook.php:138 +#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:145, includes/notification/WC_WooMercadoPago_Notification_IPN.php:119, includes/notification/WC_WooMercadoPago_Notification_Webhook.php:161, includes/notification/WC_WooMercadoPago_Notification_Webhook.php:143 msgid "Buyer email" msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:151, includes/notification/WC_WooMercadoPago_Notification_IPN.php:125, includes/notification/WC_WooMercadoPago_Notification_Webhook.php:159, includes/notification/WC_WooMercadoPago_Notification_Webhook.php:141 +#: includes/notification/WC_WooMercadoPago_Notification_IPN.php:148, includes/notification/WC_WooMercadoPago_Notification_IPN.php:122, includes/notification/WC_WooMercadoPago_Notification_Webhook.php:164, includes/notification/WC_WooMercadoPago_Notification_Webhook.php:146 msgid "Payment method" msgstr "" -#: includes/notification/WC_WooMercadoPago_Notification_Webhook.php:39 +#: includes/notification/WC_WooMercadoPago_Notification_Webhook.php:38 msgid "Please enter your email address at the billing address to use this service" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:27 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:26 msgid "It offers all means of payment: credit and debit cards, cash and account money. Your customers choose whether they pay as guests or from their Mercado Pago account." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:30 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:29 msgid "Mercado Pago - Checkout Pro" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:32 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:31 msgid "Pay with the payment method you prefer" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:246 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:241 msgid "Checkout Pro %s" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:249 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:244 msgid "Accept all method of payment and take your charges to another level" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:253 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:248 msgid "Turn your online store into your customers preferred payment gateway. Choose if the final payment experience will be inside or outside your store." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:270, includes/payments/WC_WooMercadoPago_TicketGateway.php:224 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:264, includes/payments/WC_WooMercadoPago_TicketGateway.php:220 msgid "Configure Mercado Pago for WooCommerce" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:283 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:276 msgid "Enable the experience of the Checkout Pro in your online store, select the means of payment available to your customers and
define the maximum fees in which they can pay you." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:296 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:288 msgid "Set payment preferences in your store" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:309 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:300 msgid "Advanced settings" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:322 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:312 msgid "Payment experience" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:324 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:314 msgid "Define what payment experience your customers will have, whether inside or outside your store." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:327 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:317 msgid "Redirect" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:328 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:318 msgid "Modal" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:344 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:333 msgid "Choose the URL that we will show your customers when they finish their purchase." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:342, includes/payments/WC_WooMercadoPago_BasicGateway.php:362, includes/payments/WC_WooMercadoPago_BasicGateway.php:383 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:331, includes/payments/WC_WooMercadoPago_BasicGateway.php:350, includes/payments/WC_WooMercadoPago_BasicGateway.php:370 msgid "This seems to be an invalid URL." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:347 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:336 msgid "Success URL" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:364 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:352 msgid "Choose the URL that we will show to your customers when we refuse their purchase. Make sure it includes a message appropriate to the situation and give them useful information so they can solve it." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:367 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:355 msgid "Payment URL rejected" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:385 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:372 msgid "Choose the URL that we will show to your customers when they have a payment pending approval." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:388 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:375 msgid "Payment URL pending" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:462 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:453 msgid "Select offline payments" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:451 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:442 msgid "Select debit cards" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:440 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:431 msgid "Select credit cards" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:469, includes/payments/WC_WooMercadoPago_TicketGateway.php:331 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:459, includes/payments/WC_WooMercadoPago_TicketGateway.php:321 msgid "Payment methods" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:470, includes/payments/WC_WooMercadoPago_TicketGateway.php:332 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:460, includes/payments/WC_WooMercadoPago_TicketGateway.php:322 msgid "Choose the available payment methods in your store." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:476, includes/payments/WC_WooMercadoPago_TicketGateway.php:335 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:466, includes/payments/WC_WooMercadoPago_TicketGateway.php:325 msgid "Activate the available payment methods to your clients." msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:494 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:483 msgid "Return to the store" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:497 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:486 msgid "Do you want your customer to automatically return to the store after payment?" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:526 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:514 msgid "installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:530 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:518 msgid "installment" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:598, includes/payments/WC_WooMercadoPago_BasicGateway.php:598, includes/payments/WC_WooMercadoPago_BasicGateway.php:585, includes/payments/WC_WooMercadoPago_BasicGateway.php:585, includes/payments/WC_WooMercadoPago_CustomGateway.php:352, includes/payments/WC_WooMercadoPago_CustomGateway.php:352, includes/payments/WC_WooMercadoPago_CustomGateway.php:340, includes/payments/WC_WooMercadoPago_CustomGateway.php:340, includes/payments/WC_WooMercadoPago_TicketGateway.php:451, includes/payments/WC_WooMercadoPago_TicketGateway.php:451, includes/payments/WC_WooMercadoPago_TicketGateway.php:438, includes/payments/WC_WooMercadoPago_TicketGateway.php:438, includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:100, includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:98 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:585, includes/payments/WC_WooMercadoPago_BasicGateway.php:585, includes/payments/WC_WooMercadoPago_BasicGateway.php:572, includes/payments/WC_WooMercadoPago_BasicGateway.php:572, includes/payments/WC_WooMercadoPago_CustomGateway.php:344, includes/payments/WC_WooMercadoPago_CustomGateway.php:344, includes/payments/WC_WooMercadoPago_CustomGateway.php:332, includes/payments/WC_WooMercadoPago_CustomGateway.php:332, includes/payments/WC_WooMercadoPago_TicketGateway.php:439, includes/payments/WC_WooMercadoPago_TicketGateway.php:439, includes/payments/WC_WooMercadoPago_TicketGateway.php:426, includes/payments/WC_WooMercadoPago_TicketGateway.php:426, includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:100, includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:98 msgid "discount of" msgstr "" -#: includes/payments/WC_WooMercadoPago_BasicGateway.php:603, includes/payments/WC_WooMercadoPago_BasicGateway.php:603, includes/payments/WC_WooMercadoPago_BasicGateway.php:590, includes/payments/WC_WooMercadoPago_BasicGateway.php:590, includes/payments/WC_WooMercadoPago_CustomGateway.php:357, includes/payments/WC_WooMercadoPago_CustomGateway.php:357, includes/payments/WC_WooMercadoPago_CustomGateway.php:345, includes/payments/WC_WooMercadoPago_CustomGateway.php:345, includes/payments/WC_WooMercadoPago_TicketGateway.php:456, includes/payments/WC_WooMercadoPago_TicketGateway.php:456, includes/payments/WC_WooMercadoPago_TicketGateway.php:443, includes/payments/WC_WooMercadoPago_TicketGateway.php:443, includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:102 +#: includes/payments/WC_WooMercadoPago_BasicGateway.php:590, includes/payments/WC_WooMercadoPago_BasicGateway.php:590, includes/payments/WC_WooMercadoPago_BasicGateway.php:577, includes/payments/WC_WooMercadoPago_BasicGateway.php:577, includes/payments/WC_WooMercadoPago_CustomGateway.php:349, includes/payments/WC_WooMercadoPago_CustomGateway.php:349, includes/payments/WC_WooMercadoPago_CustomGateway.php:337, includes/payments/WC_WooMercadoPago_CustomGateway.php:337, includes/payments/WC_WooMercadoPago_TicketGateway.php:444, includes/payments/WC_WooMercadoPago_TicketGateway.php:444, includes/payments/WC_WooMercadoPago_TicketGateway.php:431, includes/payments/WC_WooMercadoPago_TicketGateway.php:431, includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:102 msgid "fee of" msgstr "" @@ -398,475 +398,475 @@ msgstr "" msgid "Pay with debit and credit cards" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:163 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:161 msgid "Checkout of payments with debit and credit cards %s" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:166 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:164 msgid "Accept payments instantly and maximize the conversion of your business" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:170 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:168 msgid "Turn your online store into a secure and easy-to-use payment gateway for your customers. With personalized checkout your customers pay without leaving your store!" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:187 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:184 msgid "Set up the payment experience in your store" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:200 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:196 msgid "Configure the personalized payment experience in your store" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:213 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:208 msgid "Advanced configuration of the personalized payment experience\"" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:228 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:222 msgid "That’s it, payment accepted!" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:230 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:224 msgid "We are processing your payment. In less than an hour we will send you the result by email." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:232 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:226 msgid "We are processing your payment. In less than 2 days we will send you by email if the payment has been approved or if additional information is needed." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:234 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:228 msgid "Check the card number." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:236 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:230 msgid "Check the expiration date." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:238 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:232 msgid "Check the information provided." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:240, templates/checkout/custom_checkout.php:107, templates/checkout/custom_checkout.php:108 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:234, templates/checkout/custom_checkout.php:107, templates/checkout/custom_checkout.php:108 msgid "Check the informed security code." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:242, includes/payments/WC_WooMercadoPago_CustomGateway.php:248 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:236, includes/payments/WC_WooMercadoPago_CustomGateway.php:242 msgid "Your payment cannot be processed." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:244 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:238 msgid "You must authorize payments for your orders." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:246 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:240 msgid "Contact your card issuer to activate it. The phone is on the back of your card." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:250 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:244 msgid "You have already made a payment of this amount. If you have to pay again, use another card or other method of payment." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:252 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:246 msgid "Your payment was declined. Please select another payment method. It is recommended in cash." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:254 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:248 msgid "Your payment does not have sufficient funds." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:256 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:250 msgid "Payment cannot process the selected fee." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:258 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:252 msgid "You have reached the limit of allowed attempts. Choose another card or other payment method." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:260, includes/payments/WC_WooMercadoPago_CustomGateway.php:262, includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php:64 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:254, includes/payments/WC_WooMercadoPago_CustomGateway.php:256, includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php:64 msgid "This payment method cannot process your payment." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:451 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:448 msgid "A problem was occurred when processing your payment. Please, try again." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:442 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:437 msgid "A problem was occurred when processing your payment. Are you sure you have correctly filled all information in the checkout form?" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:403 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:395 msgid "See your order form" msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:415 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:407 msgid "Your payment was declined. You can try again." msgstr "" -#: includes/payments/WC_WooMercadoPago_CustomGateway.php:420, includes/payments/hooks/WC_WooMercadoPago_Hook_Basic.php:83 +#: includes/payments/WC_WooMercadoPago_CustomGateway.php:414, includes/payments/hooks/WC_WooMercadoPago_Hook_Basic.php:82 msgid "Click to try again" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:298 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:290 msgid "%s, it only takes a few minutes" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:298 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:290 msgid "Approve your account" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:379 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:369 msgid "Title" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:394 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:383 msgid "Description" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:429 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:416 msgid "Follow these steps to activate Mercado Pago in your store:" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:434 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:421 msgid "Upload your credentials depending on the country in which you are registered." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:441 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:428 msgid "Approve your account to be able to charge." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:448 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:435 msgid "Add the basic information of your business in the plugin configuration." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:455 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:442 msgid "Configure the payment preferences for your customers." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:462 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:449 msgid "Go to advanced settings only when you want to change the presets." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:481 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:467 msgid "Credentials are the keys we provide you to integrate quickly
and securely. You must have a %s in Mercado Pago to obtain and collect them
on your website. You do not need to know how to design or program to do it" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:482 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:468 msgid "approved account" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:499 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:484 msgid "In which country does your Mercado Pago account operate?" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:528 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:512 msgid "Select your country" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:530 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:514 msgid "Select the country in which you operate with Mercado Pago" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:566, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:570 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:548, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:552 msgid "Save Changes" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:588 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:569 msgid "Activate checkout" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:591 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:572 msgid "Activate the Mercado Pago experience at the checkout of your store." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:606 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:586 msgid "Enter your credentials and choose how to operate" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:619 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:598 msgid "Test Mode" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:632 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:610 msgid "By default, we activate the Sandbox test environment for you to test before you start selling." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:645 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:622 msgid "Production Mode" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:658 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:634 msgid "When you see that everything is going well, deactivate Sandbox, turn on Production and make way for your online sales." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:672 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:647 msgid "Production" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:674 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:649 msgid "Choose “Yes” only when you’re ready to sell. Switch to “No” to activate Testing mode." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:696 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:670 msgid "Load credentials" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:700 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:674 msgid "Search my credentials" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:719 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:692 msgid "Test credentials" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:731 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:703 msgid "With these keys you can do the tests you want.." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:744, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:801 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:715, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:768 msgid "Public key" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:760, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:818 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:730, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:784 msgid "Access token" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:776 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:745 msgid "Production credentials" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:788 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:756 msgid "With these keys you can receive real payments from your customers." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:835 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:799 msgid "Approve your account, it will only take a few minutes" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:848 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:811 msgid "Complete this process to secure your customers data and comply with the regulations
and legal provisions of each country." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:862, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1190, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1268 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:824, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1132, includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1206 msgid "%s" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:863 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:825 msgid "Homologate account in Mercado Pago" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:877 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:838 msgid "Store name" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:879 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:840 msgid "This name will appear on your customers invoice." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:880 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:841 msgid "Mercado Pago" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:896 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:856 msgid "Store Category" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:898 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:858 msgid "What category do your products belong to? Choose the one that best characterizes them (choose \"other\" if your product is too specific)." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:899 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:859 msgid "Categories" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:911 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:870 msgid "Store ID" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:913 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:872 msgid "Use a number or prefix to identify orders and payments from this store." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:926 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:884 msgid "Integrator ID" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:929 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:887 msgid "Do not forget to enter your integrator_id as a certified Mercado Pago Partner. If you don`t have it, you can %s" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:930 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:888 msgid "request it now." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:944 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:901 msgid "Advanced adjustment" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:957 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:913 msgid "Debug and Log mode" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:960 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:916 msgid "Record your store actions in our changes file to have more support information." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:961 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:917 msgid "We debug the information in our change file." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:976 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:931 msgid "Basic Configuration" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:989 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:943 msgid "Max of installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:991 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:945 msgid "What is the maximum quota with which a customer can buy?" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:994 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:948 msgid "1x installment" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:995 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:949 msgid "2x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:996 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:950 msgid "3x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:997 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:951 msgid "4x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:998 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:952 msgid "5x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:999 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:953 msgid "6x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1000 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:954 msgid "10x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1001 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:955 msgid "12x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1002 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:956 msgid "15x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1003 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:957 msgid "18x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1004 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:958 msgid "24x installments" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1033 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:985 msgid "URL for IPN" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1036 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:988 msgid "Enter a URL to receive payment notifications. In %s you can check more information." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1037 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:989 msgid "our guides" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1052 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1003 msgid "Edit these advanced fields only when you want to modify the preset values." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1065 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1015 msgid "Discount coupons" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1068 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1018 msgid "Will you offer discount coupons to customers who buy with Mercado Pago?" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1083 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1032 msgid "It appears that your credentials are not properly configured.
Please, go to %s and configure it." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1084 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1033 msgid "Market Payment Configuration" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1098 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1046 msgid "Binary mode" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1101 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1049 msgid "Accept and reject payments automatically. Do you want us to activate it?" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1117 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1064 msgid "Discounts per purchase with Mercado Pago" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1119 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1066 msgid "Choose a percentage value that you want to discount your customers for paying with Mercado Pago." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1136 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1082 msgid "Commission for purchase with Mercado Pago" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1138 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1084 msgid "Choose an additional percentage value that you want to charge as commission to your customers for paying with Mercado Pago." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1159 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1103 msgid "Questions?" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1173 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1116 msgid "Check out the step-by-step of how to integrate the Mercado Pago Plugin for WooCommerce in our developer website." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1187 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1129 msgid "Review documentation" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1205 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1146 msgid "Still having problems? Contact our support team through their %s" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1206 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1147 msgid "contact form." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1225 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1165 msgid "Everything set up? Go to your store in Sandbox mode" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1223 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1163 msgid "Everything ready for the takeoff of your sales?" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1244 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1183 msgid "Visit your store and simulate a payment to check that everything is fine." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1242 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1181 msgid "Visit your store as if you were one of your customers and check that everything is fine. If you already went to Production,
bring your customers and increase your sales with the best online shopping experience." msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1263 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1201 msgid "I want to test my sales" msgstr "" -#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1261 +#: includes/payments/WC_WooMercadoPago_PaymentAbstract.php:1199 msgid "Visit my store" msgstr "" @@ -878,71 +878,71 @@ msgstr "" msgid "Pay with cash" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:200 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:197 msgid "Checkout of payments with cash %s" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:203 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:200 msgid "Accept face-to-face payments, do not leave anyone out!" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:207 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:204 msgid "Include this preferred purchase option by some customers." msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:237 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:232 msgid "Enable Mercado Pago for cash payments in your store and
select the options available to your customers." msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:250 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:244 msgid "Set payment preferences with cash" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:263 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:256 msgid "Advanced configuration of the cash payment experience" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:276 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:268 msgid "Reduce inventory" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:279 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:271 msgid "Activates inventory reduction during the creation of an order, whether or not the final payment is credited. Disable this option to reduce it only when payments are approved." msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:293 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:284 msgid "Payment Due" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:295 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:286 msgid "In how many days will cash payments expire." msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:324 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:314 msgid "All payment methods" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:473, includes/payments/WC_WooMercadoPago_TicketGateway.php:491 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:461, includes/payments/WC_WooMercadoPago_TicketGateway.php:479 msgid "There was a problem processing your payment. Are you sure you have correctly filled out all the information on the payment form?" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:560 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:550 msgid "A problem occurred when processing your payment. Please try again." msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:546 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:536 msgid "A problem occurred when processing your payment. Are you sure you have correctly filled in all the information on the checkout form?" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:523 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:511 msgid "The customer has not paid yet." msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:528 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:516 msgid "To print the ticket again click" msgstr "" -#: includes/payments/WC_WooMercadoPago_TicketGateway.php:531 +#: includes/payments/WC_WooMercadoPago_TicketGateway.php:519 msgid "here" msgstr "" @@ -982,7 +982,7 @@ msgstr "" msgid "Enter your coupon" msgstr "" -#: templates/checkout/custom_checkout.php:57, templates/checkout/ticket_checkout.php:23, includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:80, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:82 +#: templates/checkout/custom_checkout.php:57, templates/checkout/ticket_checkout.php:23, includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:76, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:78 msgid "Apply" msgstr "" @@ -1035,6 +1035,7 @@ msgid "Select the number of installment" msgstr "" #: templates/checkout/custom_checkout.php:131 +msgid "" msgstr "" #: templates/checkout/custom_checkout.php:134 @@ -1073,7 +1074,7 @@ msgstr "" msgid "You must provide your document number" msgstr "" -#: templates/checkout/ticket_checkout.php:56, templates/checkout/ticket_checkout.php:172 +#: templates/checkout/ticket_checkout.php:56, templates/checkout/ticket_checkout.php:312 msgid "Complete all fields, they are mandatory." msgstr "" @@ -1141,63 +1142,63 @@ msgstr "" msgid "State" msgstr "" -#: templates/checkout/ticket_checkout.php:129 +#: templates/checkout/ticket_checkout.php:134 msgid "Select state\"" msgstr "" -#: templates/checkout/ticket_checkout.php:159 +#: templates/checkout/ticket_checkout.php:299 msgid "You must inform your status" msgstr "" -#: templates/checkout/ticket_checkout.php:163 +#: templates/checkout/ticket_checkout.php:303 msgid "Postal Code" msgstr "" -#: templates/checkout/ticket_checkout.php:165 +#: templates/checkout/ticket_checkout.php:305 msgid "You must provide your zip code" msgstr "" -#: templates/checkout/ticket_checkout.php:181 +#: templates/checkout/ticket_checkout.php:321 msgid "Select the issuer with whom you want to process the payment" msgstr "" -#: includes/admin/notices/WC_WooMercadoPago_Notices.php:88, includes/admin/notices/WC_WooMercadoPago_Notices.php:143, includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php:120 +#: includes/admin/notices/WC_WooMercadoPago_Notices.php:83, includes/admin/notices/WC_WooMercadoPago_Notices.php:137, includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php:114 msgid "Discard" msgstr "" -#: includes/admin/notices/WC_WooMercadoPago_Notices.php:119 +#: includes/admin/notices/WC_WooMercadoPago_Notices.php:113 msgid "See WooCommerce" msgstr "" -#: includes/admin/notices/WC_WooMercadoPago_Notices.php:117 +#: includes/admin/notices/WC_WooMercadoPago_Notices.php:111 msgid "Install WooCommerce" msgstr "" -#: includes/admin/notices/WC_WooMercadoPago_Notices.php:114 +#: includes/admin/notices/WC_WooMercadoPago_Notices.php:108 msgid "Activate WooCommerce" msgstr "" -#: includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php:103 +#: includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php:97 msgid "do you have a minute to share your experience with our plugin?" msgstr "" -#: includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php:106 +#: includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php:100 msgid "Your opinion is very important so that we can offer you the best possible payment solution and continue to improve." msgstr "" -#: includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php:115 +#: includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php:109 msgid "Rate the plugin" msgstr "" -#: includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php:225 +#: includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php:222 msgid "Shipping service used by the store." msgstr "" -#: includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php:372, includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php:373 +#: includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php:370, includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php:371 msgid "Discount provided by store" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:64 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:65 msgid "Discount for coupon %s" msgstr "" @@ -1205,78 +1206,78 @@ msgstr "" msgid " and fee of" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:308 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:300 msgid "Public Key production credential is invalid. Review the field to receive real payments." msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:318 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:309 msgid "Public Key test credential is invalid. Review the field to perform tests in your store." msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:328 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:318 msgid "Access Token production credential is invalid. Remember that it must be complete to receive real payments." msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:338 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Abstract.php:327 msgid "Access Token test credential is invalid. Review the field to perform tests in your store." msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Basic.php:80 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Basic.php:79 msgid "There was an error processing your payment. Please try again or contact us for Assistance." msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Basic.php:72 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Basic.php:71 msgid "Pay with Mercado Pago" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Basic.php:74 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Basic.php:73 msgid "Cancel & Clear Cart" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:81, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:83 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:77, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:79 msgid "Remove" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:82, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:84 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:78, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:80 msgid "Please, inform your coupon code" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:83, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:85 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:79, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:81 msgid "To choose" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:84, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:86 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:80, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:82 msgid "Other bank" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:85, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:87 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:81, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:83 msgid "You will save" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:86, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:88 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:82, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:84 msgid "with discount of" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:87, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:89 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:83, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:85 msgid "Total of your purchase:" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:88, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:90 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:84, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:86 msgid "Total of your purchase with discount:" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:89, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:91 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:85, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:87 msgid "*After payment approval" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:90, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:92 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Custom.php:86, includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:88 msgid "Terms and conditions of use" msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:123 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:117 msgid "Great, we processed your purchase order. Complete the payment with ticket so that we finish approving it." msgstr "" -#: includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:128 +#: includes/payments/hooks/WC_WooMercadoPago_Hook_Ticket.php:122 msgid "Print ticket" msgstr "" diff --git a/includes/admin/notices/WC_WooMercadoPago_Notices.php b/includes/admin/notices/WC_WooMercadoPago_Notices.php index 821b7917c..60f72d366 100644 --- a/includes/admin/notices/WC_WooMercadoPago_Notices.php +++ b/includes/admin/notices/WC_WooMercadoPago_Notices.php @@ -8,131 +8,125 @@ * License - https://www.gnu.org/licenses/gpl.html GPL version 2 or higher */ -if (!defined('ABSPATH')) { - exit; +if ( ! defined( 'ABSPATH' ) ) { + exit; } /** * Class WC_WooMercadoPago_Notification */ -class WC_WooMercadoPago_Notices -{ - public static $instance = null; - - private function __construct() - { - add_action('admin_enqueue_scripts', [$this, 'loadAdminNoticeCss']); - } - - /** - * @return WC_WooMercadoPago_Notices|null - * Singleton - */ - public static function initMercadopagoNotice() - { - if (self::$instance === null) { - self::$instance = new self; - } - return self::$instance; - } - - /** - * Get sufix to static files - */ - public function getSufix() - { - return defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; - } - - /** - * Load admin notices CSS - */ - public function loadAdminNoticeCss() - { - if (is_admin()) { - $suffix = $this->getSufix(); - - wp_enqueue_style( - 'woocommerce-mercadopago-admin-notice', - plugins_url('../../assets/css/admin_notice_mercadopago' . $suffix . '.css', plugin_dir_path(__FILE__)) - ); - } - } - - /** - * @param $message - * @param $type - * @return string - */ - public static function getAlertFrame($message, $type) - { - $inline = null; - if ( - (class_exists('WC_WooMercadoPago_Module') && WC_WooMercadoPago_Module::isWcNewVersion()) - && - (isset($_GET['page']) && $_GET['page'] == "wc-settings") - ) { - $inline = "inline"; - } - - $notice = '
+class WC_WooMercadoPago_Notices { + + public static $instance = null; + + private function __construct() { + add_action( 'admin_enqueue_scripts', array( $this, 'loadAdminNoticeCss' ) ); + } + + /** + * @return WC_WooMercadoPago_Notices|null + * Singleton + */ + public static function initMercadopagoNotice() { + if ( self::$instance === null ) { + self::$instance = new self(); + } + return self::$instance; + } + + /** + * Get sufix to static files + */ + public function getSufix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Load admin notices CSS + */ + public function loadAdminNoticeCss() { + if ( is_admin() ) { + $suffix = $this->getSufix(); + + wp_enqueue_style( + 'woocommerce-mercadopago-admin-notice', + plugins_url( '../../assets/css/admin_notice_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ) + ); + } + } + + /** + * @param $message + * @param $type + * @return string + */ + public static function getAlertFrame( $message, $type ) { + $inline = null; + if ( + ( class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::isWcNewVersion() ) + && + ( isset( $_GET['page'] ) && $_GET['page'] == 'wc-settings' ) + ) { + $inline = 'inline'; + } + + $notice = '
- +

' . $message . '

'; - if (class_exists('WC_WooMercadoPago_Module')) { - WC_WooMercadoPago_Module::$notices[] = $notice; - } - - return $notice; - } - - /** - * @param $message - * @param $type - * @return string - */ - public static function getAlertWocommerceMiss($message, $type) - { - - $is_installed = false; - - if (function_exists('get_plugins')) { - $all_plugins = get_plugins(); - $is_installed = !empty($all_plugins['woocommerce/woocommerce.php']); - } - - if ($is_installed && current_user_can('install_plugins')) { - $buttonUrl = '' . __('Activate WooCommerce', 'woocommerce-mercadopago') . ''; - } else { - if (current_user_can('install_plugins')) { - $buttonUrl = '' . __('Install WooCommerce', 'woocommerce-mercadopago') . ''; - } else { - $buttonUrl = '' . __('See WooCommerce', 'woocommerce-mercadopago') . ''; - } - } - - $inline = null; - if ( - (class_exists('WC_WooMercadoPago_Module') && WC_WooMercadoPago_Module::isWcNewVersion()) - && - (isset($_GET['page']) && $_GET['page'] == "wc-settings") - ) { - $inline = "inline"; - } - - $notice = '
+ if ( class_exists( 'WC_WooMercadoPago_Module' ) ) { + WC_WooMercadoPago_Module::$notices[] = $notice; + } + + return $notice; + } + + /** + * @param $message + * @param $type + * @return string + */ + public static function getAlertWocommerceMiss( $message, $type ) { + + $is_installed = false; + + if ( function_exists( 'get_plugins' ) ) { + $all_plugins = get_plugins(); + $is_installed = ! empty( $all_plugins['woocommerce/woocommerce.php'] ); + } + + if ( $is_installed && current_user_can( 'install_plugins' ) ) { + $buttonUrl = '' . __( 'Activate WooCommerce', 'woocommerce-mercadopago' ) . ''; + } else { + if ( current_user_can( 'install_plugins' ) ) { + $buttonUrl = '' . __( 'Install WooCommerce', 'woocommerce-mercadopago' ) . ''; + } else { + $buttonUrl = '' . __( 'See WooCommerce', 'woocommerce-mercadopago' ) . ''; + } + } + + $inline = null; + if ( + ( class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::isWcNewVersion() ) + && + ( isset( $_GET['page'] ) && $_GET['page'] == 'wc-settings' ) + ) { + $inline = 'inline'; + } + + $notice = '
- +

' . $message . '

@@ -140,13 +134,13 @@ public static function getAlertWocommerceMiss($message, $type)
'; - if (class_exists('WC_WooMercadoPago_Module')) { - WC_WooMercadoPago_Module::$notices[] = $notice; - } - return $notice; - } + if ( class_exists( 'WC_WooMercadoPago_Module' ) ) { + WC_WooMercadoPago_Module::$notices[] = $notice; + } + return $notice; + } } diff --git a/includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php b/includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php index a1ddda506..961b3dfcb 100644 --- a/includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php +++ b/includes/admin/notices/WC_WooMercadoPago_ReviewNotice.php @@ -8,103 +8,97 @@ * License - https://www.gnu.org/licenses/gpl.html GPL version 2 or higher */ -if (!defined('ABSPATH')) { - exit; +if ( ! defined( 'ABSPATH' ) ) { + exit; } /** * Class WC_WooMercadoPago_ReviewNotice */ -class WC_WooMercadoPago_ReviewNotice -{ - public static $instance = null; - - private function __construct() - { - add_action('admin_enqueue_scripts', [$this, 'loadAdminNoticeCss']); - add_action('admin_enqueue_scripts', [$this, 'loadAdminNoticeJs']); - add_action('wp_ajax_mercadopago_review_dismiss', [$this, 'reviewDismiss']); - } - - /** - * @return WC_WooMercadoPago_ReviewNotice|null - * Singleton - */ - public static function initMercadopagoReviewNotice() - { - if (self::$instance === null) { - self::$instance = new self; - } - return self::$instance; - } - - /** - * Get sufix to static files - */ - public function getSufix() - { - return defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; - } - - /** - * Load admin notices CSS - */ - public function loadAdminNoticeCss() - { - if (is_admin()) { - $suffix = $this->getSufix(); - - wp_enqueue_style( - 'woocommerce-mercadopago-admin-notice', - plugins_url('../../assets/css/admin_notice_mercadopago' . $suffix . '.css', plugin_dir_path(__FILE__)) - ); - } - } - - /** - * Load admin notices JS - */ - public function loadAdminNoticeJs() - { - if (is_admin()) { - $suffix = $this->getSufix(); - - wp_enqueue_script( - 'woocommerce-mercadopago-admin-notice-review', - plugins_url('../../assets/js/review'.$suffix.'.js', plugin_dir_path(__FILE__)), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - } - } - - /** - * @return string - */ - public static function getPluginReviewBanner() - { - $inline = null; - if ( - (class_exists('WC_WooMercadoPago_Module') && WC_WooMercadoPago_Module::isWcNewVersion()) && - (isset($_GET['page']) && $_GET['page'] == "wc-settings") - ) { - $inline = "inline"; - } - - $notice = '
+class WC_WooMercadoPago_ReviewNotice { + + public static $instance = null; + + private function __construct() { + add_action( 'admin_enqueue_scripts', array( $this, 'loadAdminNoticeCss' ) ); + add_action( 'admin_enqueue_scripts', array( $this, 'loadAdminNoticeJs' ) ); + add_action( 'wp_ajax_mercadopago_review_dismiss', array( $this, 'reviewDismiss' ) ); + } + + /** + * @return WC_WooMercadoPago_ReviewNotice|null + * Singleton + */ + public static function initMercadopagoReviewNotice() { + if ( self::$instance === null ) { + self::$instance = new self(); + } + return self::$instance; + } + + /** + * Get sufix to static files + */ + public function getSufix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Load admin notices CSS + */ + public function loadAdminNoticeCss() { + if ( is_admin() ) { + $suffix = $this->getSufix(); + + wp_enqueue_style( + 'woocommerce-mercadopago-admin-notice', + plugins_url( '../../assets/css/admin_notice_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ) + ); + } + } + + /** + * Load admin notices JS + */ + public function loadAdminNoticeJs() { + if ( is_admin() ) { + $suffix = $this->getSufix(); + + wp_enqueue_script( + 'woocommerce-mercadopago-admin-notice-review', + plugins_url( '../../assets/js/review' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + } + } + + /** + * @return string + */ + public static function getPluginReviewBanner() { + $inline = null; + if ( + ( class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::isWcNewVersion() ) && + ( isset( $_GET['page'] ) && $_GET['page'] == 'wc-settings' ) + ) { + $inline = 'inline'; + } + + $notice = '
- +

' . - wp_get_current_user()->user_login . ', ' . - __('do you have a minute to share your experience with our plugin?', 'woocommerce-mercadopago') . - '

+ wp_get_current_user()->user_login . ', ' . + __( 'do you have a minute to share your experience with our plugin?', 'woocommerce-mercadopago' ) . + '

' . - __('Your opinion is very important so that we can offer you the best possible payment solution and continue to improve.', 'woocommerce-mercadopago') . - '

+ __( 'Your opinion is very important so that we can offer you the best possible payment solution and continue to improve.', 'woocommerce-mercadopago' ) . + '

@@ -112,32 +106,32 @@ public static function getPluginReviewBanner() class="mp-rating-link" href="https://wordpress.org/support/plugin/woocommerce-mercadopago/reviews/?filter=5#new-post" target="blank" >' - . __('Rate the plugin', 'woocommerce-mercadopago') . - ' + . __( 'Rate the plugin', 'woocommerce-mercadopago' ) . + '
'; - if (class_exists('WC_WooMercadoPago_Module')) { - WC_WooMercadoPago_Module::$notices[] = $notice; - } + if ( class_exists( 'WC_WooMercadoPago_Module' ) ) { + WC_WooMercadoPago_Module::$notices[] = $notice; + } - return $notice; - } + return $notice; + } - /** + /** * Dismiss the review admin notice */ public function reviewDismiss() { - $dismissedReview = (int) get_option('_mp_dismiss_review', 0); + $dismissedReview = (int) get_option( '_mp_dismiss_review', 0 ); - if ($dismissedReview == 0) { - update_option('_mp_dismiss_review', 1, true); - } + if ( $dismissedReview == 0 ) { + update_option( '_mp_dismiss_review', 1, true ); + } wp_send_json_success(); } diff --git a/includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php b/includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php index 5b1793006..fa55b34ac 100644 --- a/includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php +++ b/includes/helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php @@ -1,450 +1,430 @@ msg_description = __('Activate this option so that the value of the currency set in WooCommerce is compatible with the value of the currency you use in Mercado Pago.', 'woocommerce-mercadopago'); - $this->log = new WC_WooMercadoPago_Log(); - return $this; - } - - /** - * @return static - */ - public static function getInstance() - { - if (is_null(self::$instance)) { - self::$instance = new static(); - } - - return self::$instance; - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return $this - */ - private function init(WC_WooMercadoPago_PaymentAbstract $method) - { - if (!isset($this->ratios[$method->id])) { - - try { - if (!$this->isEnabled($method)) { - $this->setRatio($method->id); - return $this; - } - - $accountCurrency = $this->getAccountCurrency($method); - $localCurrency = get_woocommerce_currency(); - - if (!$accountCurrency || $accountCurrency == $localCurrency) { - $this->setRatio($method->id); - return $this; - } - - $this->setRatio($method->id, $this->loadRatio($localCurrency, $accountCurrency, $method)); - } catch (Exception $e) { - $this->setRatio($method->id); - throw $e; - } - } - - return $this; - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return mixed|null - */ - private function getAccountCurrency(WC_WooMercadoPago_PaymentAbstract $method) - { - $key = $method->id; - - if (isset($this->currencyCache[$key])) { - return $this->currencyCache[$key]; - } - - $siteId = $this->getSiteId($this->getAccessToken($method)); - - if (!$siteId) { - return null; - } - - $configs = $this->getCountryConfigs(); - - if (!isset($configs[$siteId]) || !isset($configs[$siteId]['currency'])) { - return null; - } - - return isset($configs[$siteId]) ? $configs[$siteId]['currency'] : null; - } - - /** - * @return array - */ - private function getCountryConfigs() - { - try { - $configInstance = new WC_WooMercadoPago_Configs(); - return $configInstance->getCountryConfigs(); - } catch (Exception $e) { - return []; - } - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return mixed - */ - private function getAccessToken(WC_WooMercadoPago_PaymentAbstract $method) - { - $type = $method->getOption('checkout_credential_prod') == 'no' - ? '_mp_access_token_test' - : '_mp_access_token_prod'; - - return $method->getOption($type); - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return mixed - */ - public function isEnabled(WC_WooMercadoPago_PaymentAbstract $method) - { - return $method->getoption(self::CONFIG_KEY, 'no') == 'yes' ? true : false; - } - - /** - * @param $methodId - * @param int $value - */ - private function setRatio($methodId, $value = self::DEFAULT_RATIO) - { - $this->ratios[$methodId] = $value; - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return int|mixed - */ - private function getRatio(WC_WooMercadoPago_PaymentAbstract $method) - { - $this->init($method); - return isset($this->ratios[$method->id]) - ? $this->ratios[$method->id] - : self::DEFAULT_RATIO; - } - - /** - * @param $fromCurrency - * @param $toCurrency - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return int - */ - public function loadRatio($fromCurrency, $toCurrency, WC_WooMercadoPago_PaymentAbstract $method = null) - { - $cacheKey = $fromCurrency . '--' . $toCurrency; - - if (isset($this->cache[$cacheKey])) { - return $this->cache[$cacheKey]; - } - - $ratio = self::DEFAULT_RATIO; - - if ($fromCurrency == $toCurrency) { - $this->cache[$cacheKey] = $ratio; - return $ratio; - } - - try { - $result = MeliRestClient::get( - array( - 'uri' => sprintf('/currency_conversions/search?from=%s&to=%s', $fromCurrency, $toCurrency), - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->getAccessToken($method) - ) - ) - ); - - if ($result['status'] != 200) { - $this->log->write_log(__FUNCTION__, 'Mercado pago gave error to get currency value, payment creation failed with error: ' . print_r($result, true)); - $ratio = self::DEFAULT_RATIO; - throw new Exception('Status: ' . $result['status'] . ' Message: ' . $result['response']['message']); - } - - if (isset($result['response'], $result['response']['ratio'])) { - $ratio = $result['response']['ratio'] > 0 ? $result['response']['ratio'] : self::DEFAULT_RATIO; - } - } catch (Exception $e) { - $this->log->write_log( - "WC_WooMercadoPago_Helpers_CurrencyConverter::loadRatio('$fromCurrency', '$toCurrency')", - $e->__toString() - ); - - throw $e; - } - - $this->cache[$cacheKey] = $ratio; - return $ratio; - } - - /** - * @param $accessToken - * @return string | null - */ - private function getSiteId($accessToken) - { - try { - $mp = new MP($accessToken); - $result = $mp->get('/users/me', array('Authorization' => 'Bearer ' . $accessToken)); - return isset($result['response'], $result['response']['site_id']) ? $result['response']['site_id'] : null; - } catch (Exception $e) { - return null; - } - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return float - */ - public function ratio(WC_WooMercadoPago_PaymentAbstract $method) - { - $this->init($method); - return $this->getRatio($method); - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return string|void - */ - public function getDescription(WC_WooMercadoPago_PaymentAbstract $method) - { - return $this->msg_description; - } - - /** - * Check if currency is supported in mercado pago API - * @param $currency - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return bool - */ - private function isCurrencySupported($currency, WC_WooMercadoPago_PaymentAbstract $method) - { - foreach ($this->getSupportedCurrencies($method) as $country) { - if ($country['id'] == $currency) { - return true; - } - } - - return false; - } - - /** - * Get supported currencies from mercado pago API - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return array|bool - */ - public function getSupportedCurrencies(WC_WooMercadoPago_PaymentAbstract $method) - { - if (is_null($this->supportedCurrencies)) { - try { - - $request = array( - 'uri' => '/currencies', - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->getAccessToken($method) - ) - ); - - $result = MeliRestClient::get($request); - - if (!isset($result['response'])) { - return false; - } - - $this->supportedCurrencies = $result['response']; - } catch (Exception $e) { - $this->supportedCurrencies = []; - } - } - - return $this->supportedCurrencies; - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return array - */ - public function getField(WC_WooMercadoPago_PaymentAbstract $method) - { - return array( - 'title' => __('Convert Currency', 'woocommerce-mercadopago'), - 'type' => 'select', - 'default' => 'no', - 'description' => $this->msg_description, - 'options' => array( - 'no' => __('No', 'woocommerce-mercadopago'), - 'yes' => __('Yes', 'woocommerce-mercadopago'), - ), - ); - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @param $oldData - * @param $newData - */ - public function scheduleNotice(WC_WooMercadoPago_PaymentAbstract $method, $oldData, $newData) - { - if (!isset($oldData[self::CONFIG_KEY]) || !isset($newData[self::CONFIG_KEY])) { - return; - } - - if ($oldData[self::CONFIG_KEY] != $newData[self::CONFIG_KEY]) { - $_SESSION[self::CONFIG_KEY]['notice'] = array( - 'type' => $newData[self::CONFIG_KEY] == 'yes' ? 'enabled' : 'disabled', - 'method' => $method, - ); - } - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - */ - public function notices(WC_WooMercadoPago_PaymentAbstract $method) - { - $show = isset($_SESSION[self::CONFIG_KEY]) ? $_SESSION[self::CONFIG_KEY] : array(); - $localCurrency = get_woocommerce_currency(); - - $accountCurrency = $this->getAccountCurrency($method); - - if ($localCurrency == $accountCurrency || empty($accountCurrency) ) { - return; - } - - if (isset($show['notice'])) { - unset($_SESSION[self::CONFIG_KEY]['notice']); - if ($show['notice']['type'] == 'enabled') { - echo $this->noticeEnabled($method); - } elseif ($show['notice']['type'] == 'disabled') { - echo $this->noticeDisabled($method); - } - } - - if (!$this->isEnabled($method) && !$this->isShowingAlert && $method->isCurrencyConvertable()) { - echo $this->noticeWarning($method); - } - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return string - */ - public function noticeEnabled(WC_WooMercadoPago_PaymentAbstract $method) - { - $localCurrency = get_woocommerce_currency(); - $currency = $this->getAccountCurrency($method); - - $type = 'notice-error'; - $message = sprintf(__('Now we convert your currency from %s to %s.', 'woocommerce-mercadopago'), $localCurrency, $currency); - - return WC_WooMercadoPago_Notices::getAlertFrame($message, $type); - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return string - */ - public function noticeDisabled(WC_WooMercadoPago_PaymentAbstract $method) - { - $localCurrency = get_woocommerce_currency(); - $currency = $this->getAccountCurrency($method); - - $type = 'notice-error'; - $message = sprintf(__('We no longer convert your currency from %s to %s.', 'woocommerce-mercadopago'), $localCurrency, $currency); - - return WC_WooMercadoPago_Notices::getAlertFrame($message, $type); - } - - /** - * @param WC_WooMercadoPago_PaymentAbstract $method - * @return string - */ - public function noticeWarning(WC_WooMercadoPago_PaymentAbstract $method) - { - global $current_section; - - if (in_array($current_section, array($method->id, sanitize_title(get_class($method))), true)) { - $this->isShowingAlert = true; - - $type = 'notice-error'; - $message = __('Attention: The currency settings you have in WooCommerce are not compatible with the currency you use in your Mercado Pago account. Please activate the currency conversion.', 'woocommerce-mercadopago'); - - return WC_WooMercadoPago_Notices::getAlertFrame($message, $type); - } - - return ''; - } - - /** - * @param $str - * @param mixed ...$values - * @return string|void - */ - private function __($str, ...$values) - { - $translated = $str; - - if (!empty($values)) { - $translated = vsprintf($translated, $values); - } - - return $translated; - } +class WC_WooMercadoPago_Helpers_CurrencyConverter { + + const CONFIG_KEY = 'currency_conversion'; + const DEFAULT_RATIO = 1; + + /** @var WC_WooMercadoPago_Helpers_CurrencyConverter */ + private static $instance; + private $msg_description; + + /** + * @var array + */ + private $ratios = array(); + + /** + * @var array + */ + private $cache = array(); + + /** + * @var array + */ + private $currencyCache = array(); + + /** + * @var + */ + private $supportedCurrencies; + + /** + * @var bool + */ + private $isShowingAlert = false; + + /** @var WC_WooMercadoPago_Log */ + private $log; + + /** + * Private constructor to make class singleton + */ + private function __construct() { + $this->msg_description = __( 'Activate this option so that the value of the currency set in WooCommerce is compatible with the value of the currency you use in Mercado Pago.', 'woocommerce-mercadopago' ); + $this->log = new WC_WooMercadoPago_Log(); + return $this; + } + + /** + * @return static + */ + public static function getInstance() { + if ( is_null( self::$instance ) ) { + self::$instance = new static(); + } + + return self::$instance; + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return $this + */ + private function init( WC_WooMercadoPago_PaymentAbstract $method ) { + if ( ! isset( $this->ratios[ $method->id ] ) ) { + + try { + if ( ! $this->isEnabled( $method ) ) { + $this->setRatio( $method->id ); + return $this; + } + + $accountCurrency = $this->getAccountCurrency( $method ); + $localCurrency = get_woocommerce_currency(); + + if ( ! $accountCurrency || $accountCurrency == $localCurrency ) { + $this->setRatio( $method->id ); + return $this; + } + + $this->setRatio( $method->id, $this->loadRatio( $localCurrency, $accountCurrency, $method ) ); + } catch ( Exception $e ) { + $this->setRatio( $method->id ); + throw $e; + } + } + + return $this; + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return mixed|null + */ + private function getAccountCurrency( WC_WooMercadoPago_PaymentAbstract $method ) { + $key = $method->id; + + if ( isset( $this->currencyCache[ $key ] ) ) { + return $this->currencyCache[ $key ]; + } + + $siteId = $this->getSiteId( $this->getAccessToken( $method ) ); + + if ( ! $siteId ) { + return null; + } + + $configs = $this->getCountryConfigs(); + + if ( ! isset( $configs[ $siteId ] ) || ! isset( $configs[ $siteId ]['currency'] ) ) { + return null; + } + + return isset( $configs[ $siteId ] ) ? $configs[ $siteId ]['currency'] : null; + } + + /** + * @return array + */ + private function getCountryConfigs() { + try { + $configInstance = new WC_WooMercadoPago_Configs(); + return $configInstance->getCountryConfigs(); + } catch ( Exception $e ) { + return array(); + } + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return mixed + */ + private function getAccessToken( WC_WooMercadoPago_PaymentAbstract $method ) { + $type = $method->getOption( 'checkout_credential_prod' ) == 'no' + ? '_mp_access_token_test' + : '_mp_access_token_prod'; + + return $method->getOption( $type ); + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return mixed + */ + public function isEnabled( WC_WooMercadoPago_PaymentAbstract $method ) { + return $method->getoption( self::CONFIG_KEY, 'no' ) == 'yes' ? true : false; + } + + /** + * @param $methodId + * @param int $value + */ + private function setRatio( $methodId, $value = self::DEFAULT_RATIO ) { + $this->ratios[ $methodId ] = $value; + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return int|mixed + */ + private function getRatio( WC_WooMercadoPago_PaymentAbstract $method ) { + $this->init( $method ); + return isset( $this->ratios[ $method->id ] ) + ? $this->ratios[ $method->id ] + : self::DEFAULT_RATIO; + } + + /** + * @param $fromCurrency + * @param $toCurrency + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return int + */ + public function loadRatio( $fromCurrency, $toCurrency, WC_WooMercadoPago_PaymentAbstract $method = null ) { + $cacheKey = $fromCurrency . '--' . $toCurrency; + + if ( isset( $this->cache[ $cacheKey ] ) ) { + return $this->cache[ $cacheKey ]; + } + + $ratio = self::DEFAULT_RATIO; + + if ( $fromCurrency == $toCurrency ) { + $this->cache[ $cacheKey ] = $ratio; + return $ratio; + } + + try { + $result = MeliRestClient::get( + array( + 'uri' => sprintf( '/currency_conversions/search?from=%s&to=%s', $fromCurrency, $toCurrency ), + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->getAccessToken( $method ), + ), + ) + ); + + if ( $result['status'] != 200 ) { + $this->log->write_log( __FUNCTION__, 'Mercado pago gave error to get currency value, payment creation failed with error: ' . print_r( $result, true ) ); + $ratio = self::DEFAULT_RATIO; + throw new Exception( 'Status: ' . $result['status'] . ' Message: ' . $result['response']['message'] ); + } + + if ( isset( $result['response'], $result['response']['ratio'] ) ) { + $ratio = $result['response']['ratio'] > 0 ? $result['response']['ratio'] : self::DEFAULT_RATIO; + } + } catch ( Exception $e ) { + $this->log->write_log( + "WC_WooMercadoPago_Helpers_CurrencyConverter::loadRatio('$fromCurrency', '$toCurrency')", + $e->__toString() + ); + + throw $e; + } + + $this->cache[ $cacheKey ] = $ratio; + return $ratio; + } + + /** + * @param $accessToken + * @return string | null + */ + private function getSiteId( $accessToken ) { + try { + $mp = new MP( $accessToken ); + $result = $mp->get( '/users/me', array( 'Authorization' => 'Bearer ' . $accessToken ) ); + return isset( $result['response'], $result['response']['site_id'] ) ? $result['response']['site_id'] : null; + } catch ( Exception $e ) { + return null; + } + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return float + */ + public function ratio( WC_WooMercadoPago_PaymentAbstract $method ) { + $this->init( $method ); + return $this->getRatio( $method ); + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return string|void + */ + public function getDescription( WC_WooMercadoPago_PaymentAbstract $method ) { + return $this->msg_description; + } + + /** + * Check if currency is supported in mercado pago API + * + * @param $currency + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return bool + */ + private function isCurrencySupported( $currency, WC_WooMercadoPago_PaymentAbstract $method ) { + foreach ( $this->getSupportedCurrencies( $method ) as $country ) { + if ( $country['id'] == $currency ) { + return true; + } + } + + return false; + } + + /** + * Get supported currencies from mercado pago API + * + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return array|bool + */ + public function getSupportedCurrencies( WC_WooMercadoPago_PaymentAbstract $method ) { + if ( is_null( $this->supportedCurrencies ) ) { + try { + + $request = array( + 'uri' => '/currencies', + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->getAccessToken( $method ), + ), + ); + + $result = MeliRestClient::get( $request ); + + if ( ! isset( $result['response'] ) ) { + return false; + } + + $this->supportedCurrencies = $result['response']; + } catch ( Exception $e ) { + $this->supportedCurrencies = array(); + } + } + + return $this->supportedCurrencies; + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return array + */ + public function getField( WC_WooMercadoPago_PaymentAbstract $method ) { + return array( + 'title' => __( 'Convert Currency', 'woocommerce-mercadopago' ), + 'type' => 'select', + 'default' => 'no', + 'description' => $this->msg_description, + 'options' => array( + 'no' => __( 'No', 'woocommerce-mercadopago' ), + 'yes' => __( 'Yes', 'woocommerce-mercadopago' ), + ), + ); + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @param $oldData + * @param $newData + */ + public function scheduleNotice( WC_WooMercadoPago_PaymentAbstract $method, $oldData, $newData ) { + if ( ! isset( $oldData[ self::CONFIG_KEY ] ) || ! isset( $newData[ self::CONFIG_KEY ] ) ) { + return; + } + + if ( $oldData[ self::CONFIG_KEY ] != $newData[ self::CONFIG_KEY ] ) { + $_SESSION[ self::CONFIG_KEY ]['notice'] = array( + 'type' => $newData[ self::CONFIG_KEY ] == 'yes' ? 'enabled' : 'disabled', + 'method' => $method, + ); + } + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + */ + public function notices( WC_WooMercadoPago_PaymentAbstract $method ) { + $show = isset( $_SESSION[ self::CONFIG_KEY ] ) ? $_SESSION[ self::CONFIG_KEY ] : array(); + $localCurrency = get_woocommerce_currency(); + + $accountCurrency = $this->getAccountCurrency( $method ); + + if ( $localCurrency == $accountCurrency || empty( $accountCurrency ) ) { + return; + } + + if ( isset( $show['notice'] ) ) { + unset( $_SESSION[ self::CONFIG_KEY ]['notice'] ); + if ( $show['notice']['type'] == 'enabled' ) { + echo $this->noticeEnabled( $method ); + } elseif ( $show['notice']['type'] == 'disabled' ) { + echo $this->noticeDisabled( $method ); + } + } + + if ( ! $this->isEnabled( $method ) && ! $this->isShowingAlert && $method->isCurrencyConvertable() ) { + echo $this->noticeWarning( $method ); + } + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return string + */ + public function noticeEnabled( WC_WooMercadoPago_PaymentAbstract $method ) { + $localCurrency = get_woocommerce_currency(); + $currency = $this->getAccountCurrency( $method ); + + $type = 'notice-error'; + $message = sprintf( __( 'Now we convert your currency from %1$s to %2$s.', 'woocommerce-mercadopago' ), $localCurrency, $currency ); + + return WC_WooMercadoPago_Notices::getAlertFrame( $message, $type ); + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return string + */ + public function noticeDisabled( WC_WooMercadoPago_PaymentAbstract $method ) { + $localCurrency = get_woocommerce_currency(); + $currency = $this->getAccountCurrency( $method ); + + $type = 'notice-error'; + $message = sprintf( __( 'We no longer convert your currency from %1$s to %2$s.', 'woocommerce-mercadopago' ), $localCurrency, $currency ); + + return WC_WooMercadoPago_Notices::getAlertFrame( $message, $type ); + } + + /** + * @param WC_WooMercadoPago_PaymentAbstract $method + * @return string + */ + public function noticeWarning( WC_WooMercadoPago_PaymentAbstract $method ) { + global $current_section; + + if ( in_array( $current_section, array( $method->id, sanitize_title( get_class( $method ) ) ), true ) ) { + $this->isShowingAlert = true; + + $type = 'notice-error'; + $message = __( 'Attention: The currency settings you have in WooCommerce are not compatible with the currency you use in your Mercado Pago account. Please activate the currency conversion.', 'woocommerce-mercadopago' ); + + return WC_WooMercadoPago_Notices::getAlertFrame( $message, $type ); + } + + return ''; + } + + /** + * @param $str + * @param mixed ...$values + * @return string|void + */ + private function __( $str, ...$values ) { + $translated = $str; + + if ( ! empty( $values ) ) { + $translated = vsprintf( $translated, $values ); + } + + return $translated; + } } diff --git a/includes/module/WC_WooMercadoPago_Configs.php b/includes/module/WC_WooMercadoPago_Configs.php index 13c29f794..256670d1a 100755 --- a/includes/module/WC_WooMercadoPago_Configs.php +++ b/includes/module/WC_WooMercadoPago_Configs.php @@ -1,283 +1,304 @@ updateTokenNewVersion(); - $this->showNotices(); - } +class WC_WooMercadoPago_Configs { - /** - * Show Notices in ADMIN - */ - private function showNotices() - { - add_action('admin_notices', array($this, 'plugin_review')); + /** + * WC_WooMercadoPago_Configs constructor. + * + * @throws WC_WooMercadoPago_Exception + */ + public function __construct() { + $this->updateTokenNewVersion(); + $this->showNotices(); + } - if (empty(get_option('_mp_public_key_prod')) && empty(get_option('_mp_access_token_prod'))) { - if (!empty(get_option('_mp_client_id')) && !empty(get_option('_mp_client_secret'))) { - add_action('admin_notices', array($this, 'noticeUpdateAccessToken')); - } - } + /** + * Show Notices in ADMIN + */ + private function showNotices() { + add_action( 'admin_notices', array( $this, 'plugin_review' ) ); - if ((empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off')) { - add_action('admin_notices', array($this, 'noticeHttps')); - } - } + if ( empty( get_option( '_mp_public_key_prod' ) ) && empty( get_option( '_mp_access_token_prod' ) ) ) { + if ( ! empty( get_option( '_mp_client_id' ) ) && ! empty( get_option( '_mp_client_secret' ) ) ) { + add_action( 'admin_notices', array( $this, 'noticeUpdateAccessToken' ) ); + } + } - /** - * @throws WC_WooMercadoPago_Exception - */ - private function updateTokenNewVersion() - { - if (empty(get_option('_mp_public_key_prod', '')) || empty(get_option('_mp_access_token_prod', ''))) { - if (!empty(get_option('_mp_public_key')) && !empty(get_option('_mp_access_token'))) { - $this->updateToken(); - } - } - if (empty(get_option('_site_id_v1')) || empty(get_option('_collector_id_v1'))) { - WC_WooMercadoPago_Credentials::validate_credentials_v1(); - } + if ( ( empty( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS'] == 'off' ) ) { + add_action( 'admin_notices', array( $this, 'noticeHttps' ) ); + } + } - $ticketMethods = get_option('_all_payment_methods_ticket', ''); - if (empty($ticketMethods) || !is_array($ticketMethods)) { - $this->updateTicketMethods(); - } + /** + * @throws WC_WooMercadoPago_Exception + */ + private function updateTokenNewVersion() { + if ( empty( get_option( '_mp_public_key_prod', '' ) ) || empty( get_option( '_mp_access_token_prod', '' ) ) ) { + if ( ! empty( get_option( '_mp_public_key' ) ) && ! empty( get_option( '_mp_access_token' ) ) ) { + $this->updateToken(); + } + } + if ( empty( get_option( '_site_id_v1' ) ) || empty( get_option( '_collector_id_v1' ) ) ) { + WC_WooMercadoPago_Credentials::validate_credentials_v1(); + } - $allPayments = get_option('_checkout_payments_methods', ''); - if (empty($allPayments)) { - $this->updatePayments(); - return; - } + $ticketMethods = get_option( '_all_payment_methods_ticket', '' ); + if ( empty( $ticketMethods ) || ! is_array( $ticketMethods ) ) { + $this->updateTicketMethods(); + } - if (!empty($allPayments)) { - foreach ($allPayments as $payment) { - if (!isset($payment['name'])) { - $this->updatePayments(); - break; - } - } - } - } + $allPayments = get_option( '_checkout_payments_methods', '' ); + if ( empty( $allPayments ) ) { + $this->updatePayments(); + return; + } - /** - * @throws WC_WooMercadoPago_Exception - */ - private function updatePayments() - { - $mpInstance = WC_WooMercadoPago_Module::getMpInstanceSingleton(); - if ($mpInstance) { - WC_WooMercadoPago_Credentials::updatePaymentMethods($mpInstance, $mpInstance->get_access_token()); - } - } + if ( ! empty( $allPayments ) ) { + foreach ( $allPayments as $payment ) { + if ( ! isset( $payment['name'] ) ) { + $this->updatePayments(); + break; + } + } + } + } - /** - * @throws WC_WooMercadoPago_Exception - */ - private function updateTicketMethods() - { - $mpInstance = WC_WooMercadoPago_Module::getMpInstanceSingleton(); - if ($mpInstance) { - WC_WooMercadoPago_Credentials::updateTicketMethod($mpInstance, $mpInstance->get_access_token()); - } - } + /** + * @throws WC_WooMercadoPago_Exception + */ + private function updatePayments() { + $mpInstance = WC_WooMercadoPago_Module::getMpInstanceSingleton(); + if ( $mpInstance ) { + WC_WooMercadoPago_Credentials::updatePaymentMethods( $mpInstance, $mpInstance->get_access_token() ); + } + } - /** - * Notice AccessToken - */ - public function noticeUpdateAccessToken() - { - $type = 'error'; - $message = __('Update your credentials with the Access Token and Public Key, you need them to continue receiving payments!', 'woocommerce-mercadopago'); - echo WC_WooMercadoPago_Notices::getAlertFrame($message, $type); - } + /** + * @throws WC_WooMercadoPago_Exception + */ + private function updateTicketMethods() { + $mpInstance = WC_WooMercadoPago_Module::getMpInstanceSingleton(); + if ( $mpInstance ) { + WC_WooMercadoPago_Credentials::updateTicketMethod( $mpInstance, $mpInstance->get_access_token() ); + } + } - /** - * Notice HTTPS - */ - public function noticeHttps() - { - $type = 'notice-warning'; - $message = __('The store should have HTTPS in order to activate both Checkout Personalizado and Ticket Checkout.', 'woocommerce-mercadopago'); - echo WC_WooMercadoPago_Notices::getAlertFrame($message, $type); - } + /** + * Notice AccessToken + */ + public function noticeUpdateAccessToken() { + $type = 'error'; + $message = __( 'Update your credentials with the Access Token and Public Key, you need them to continue receiving payments!', 'woocommerce-mercadopago' ); + echo WC_WooMercadoPago_Notices::getAlertFrame( $message, $type ); + } - public function plugin_review() - { - $pagesToShow = array('dashboard', 'plugins', 'woocommerce_page_wc-settings'); - $dismissedReview = (int) get_option('_mp_dismiss_review', 0); + /** + * Notice HTTPS + */ + public function noticeHttps() { + $type = 'notice-warning'; + $message = __( 'The store should have HTTPS in order to activate both Checkout Personalizado and Ticket Checkout.', 'woocommerce-mercadopago' ); + echo WC_WooMercadoPago_Notices::getAlertFrame( $message, $type ); + } - if (!in_array(get_current_screen()->id, $pagesToShow, true) || $dismissedReview != 0) { - return false; - } + public function plugin_review() { + $pagesToShow = array( 'dashboard', 'plugins', 'woocommerce_page_wc-settings' ); + $dismissedReview = (int) get_option( '_mp_dismiss_review', 0 ); - echo WC_WooMercadoPago_ReviewNotice::getPluginReviewBanner(); - } + if ( ! in_array( get_current_screen()->id, $pagesToShow, true ) || $dismissedReview != 0 ) { + return false; + } - /** - * UpdateToken - */ - private function updateToken() - { - $mpInstance = WC_WooMercadoPago_Module::getMpInstanceSingleton(); + echo WC_WooMercadoPago_ReviewNotice::getPluginReviewBanner(); + } - if ($mpInstance) { - if ( - WC_WooMercadoPago_Credentials::validateCredentialsTest($mpInstance, null, get_option('_mp_public_key')) == true - && WC_WooMercadoPago_Credentials::validateCredentialsTest($mpInstance, get_option('_mp_access_token')) == true - ) { - update_option('_mp_public_key_test', get_option('_mp_public_key'), true); - update_option('_mp_access_token_test', get_option('_mp_access_token'), true); - update_option('checkout_credential_prod', 'no', true); - } + /** + * UpdateToken + */ + private function updateToken() { + $mpInstance = WC_WooMercadoPago_Module::getMpInstanceSingleton(); - if ( - WC_WooMercadoPago_Credentials::validateCredentialsProd($mpInstance, null, get_option('_mp_public_key')) == true - && WC_WooMercadoPago_Credentials::validateCredentialsProd($mpInstance, get_option('_mp_access_token')) == true - ) { - update_option('_mp_public_key_prod', get_option('_mp_public_key'), true); - update_option('_mp_access_token_prod', get_option('_mp_access_token'), true); - if (!empty(get_option('_mp_public_key_prod', '')) && !empty(get_option('_mp_access_token_prod', ''))) { - update_option('_mp_public_key', ''); - update_option('_mp_access_token', ''); - } - update_option('checkout_credential_prod', 'yes', true); - } - } - } + if ( $mpInstance ) { + if ( + WC_WooMercadoPago_Credentials::validateCredentialsTest( $mpInstance, null, get_option( '_mp_public_key' ) ) == true + && WC_WooMercadoPago_Credentials::validateCredentialsTest( $mpInstance, get_option( '_mp_access_token' ) ) == true + ) { + update_option( '_mp_public_key_test', get_option( '_mp_public_key' ), true ); + update_option( '_mp_access_token_test', get_option( '_mp_access_token' ), true ); + update_option( 'checkout_credential_prod', 'no', true ); + } - /** - * Country Configs - */ - public static function getCountryConfigs() - { - return 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', - 'zip_code' => '110111', - ), - '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', - 'zip_code' => '3039', - ), - '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', - 'zip_code' => '01310924', - ), - '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', - 'zip_code' => '7591538', - ), - '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', - 'zip_code' => '11250', - ), - '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', - 'zip_code' => '11800', - ), - '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', - 'zip_code' => '1160', - ), - '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', - 'zip_code' => '15074', - ) - ); - } + if ( + WC_WooMercadoPago_Credentials::validateCredentialsProd( $mpInstance, null, get_option( '_mp_public_key' ) ) == true + && WC_WooMercadoPago_Credentials::validateCredentialsProd( $mpInstance, get_option( '_mp_access_token' ) ) == true + ) { + update_option( '_mp_public_key_prod', get_option( '_mp_public_key' ), true ); + update_option( '_mp_access_token_prod', get_option( '_mp_access_token' ), true ); + if ( ! empty( get_option( '_mp_public_key_prod', '' ) ) && ! empty( get_option( '_mp_access_token_prod', '' ) ) ) { + update_option( '_mp_public_key', '' ); + update_option( '_mp_access_token', '' ); + } + update_option( 'checkout_credential_prod', 'yes', true ); + } + } + } - /** - * @return array - */ - public function getCategories() - { - return array( - 'store_categories_id' => - [ - "art", "baby", "coupons", "donations", "computing", "cameras", "video games", "television", - "car electronics", "electronics", "automotive", "entertainment", "fashion", "games", "home", - "musical", "phones", "services", "learnings", "tickets", "travels", "virtual goods", "others" - ], - 'store_categories_description' => - [ - "Collectibles & Art", "Toys for Baby, Stroller, Stroller Accessories, Car Safety Seats", "Coupons", - "Donations", "Computers & Tablets", "Cameras & Photography", "Video Games & Consoles", - "LCD, LED, Smart TV, Plasmas, TVs", "Car Audio, Car Alarm Systems & Security, Car DVRs, Car Video Players, Car PC", - "Audio & Surveillance, Video & GPS, Others", "Parts & Accessories", "Music, Movies & Series, Books, Magazines & Comics, Board Games & Toys", - "Men's, Women's, Kids & baby, Handbags & Accessories, Health & Beauty, Shoes, Jewelry & Watches", - "Online Games & Credits", "Home appliances. Home & Garden", "Instruments & Gear", - "Cell Phones & Accessories", "General services", "Trainings, Conferences, Workshops", - "Tickets for Concerts, Sports, Arts, Theater, Family, Excursions tickets, Events & more", - "Plane tickets, Hotel vouchers, Travel vouchers", - "E-books, Music Files, Software, Digital Images, PDF Files and any item which can be electronically stored in a file, Mobile Recharge, DTH Recharge and any Online Recharge", - "Other categories" - ] - ); - } + /** + * Country Configs + */ + public static function getCountryConfigs() { + return 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', + 'zip_code' => '110111', + ), + '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', + 'zip_code' => '3039', + ), + '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', + 'zip_code' => '01310924', + ), + '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', + 'zip_code' => '7591538', + ), + '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', + 'zip_code' => '11250', + ), + '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', + 'zip_code' => '11800', + ), + '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', + 'zip_code' => '1160', + ), + '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', + 'zip_code' => '15074', + ), + ); + } - /** - * @param $methods - * @return array - */ - public function setPaymentGateway($methods = null) - { - global $wp; - if (!empty($wp) && isset($wp->query_vars['wc-api'])) { - $api_request = wc_clean($wp->query_vars['wc-api']); - if (!empty($api_request) && in_array($api_request, ['WC_WooMercadoPago_BasicGateway', 'WC_WooMercadoPago_CustomGateway', 'WC_WooMercadoPago_TicketGateway'])) { - $methods[] = $api_request; - } - return $methods; - } + /** + * @return array + */ + public function getCategories() { + return array( + 'store_categories_id' => + array( + 'art', + 'baby', + 'coupons', + 'donations', + 'computing', + 'cameras', + 'video games', + 'television', + 'car electronics', + 'electronics', + 'automotive', + 'entertainment', + 'fashion', + 'games', + 'home', + 'musical', + 'phones', + 'services', + 'learnings', + 'tickets', + 'travels', + 'virtual goods', + 'others', + ), + 'store_categories_description' => + array( + 'Collectibles & Art', + 'Toys for Baby, Stroller, Stroller Accessories, Car Safety Seats', + 'Coupons', + 'Donations', + 'Computers & Tablets', + 'Cameras & Photography', + 'Video Games & Consoles', + 'LCD, LED, Smart TV, Plasmas, TVs', + 'Car Audio, Car Alarm Systems & Security, Car DVRs, Car Video Players, Car PC', + 'Audio & Surveillance, Video & GPS, Others', + 'Parts & Accessories', + 'Music, Movies & Series, Books, Magazines & Comics, Board Games & Toys', + "Men's, Women's, Kids & baby, Handbags & Accessories, Health & Beauty, Shoes, Jewelry & Watches", + 'Online Games & Credits', + 'Home appliances. Home & Garden', + 'Instruments & Gear', + 'Cell Phones & Accessories', + 'General services', + 'Trainings, Conferences, Workshops', + 'Tickets for Concerts, Sports, Arts, Theater, Family, Excursions tickets, Events & more', + 'Plane tickets, Hotel vouchers, Travel vouchers', + 'E-books, Music Files, Software, Digital Images, PDF Files and any item which can be electronically stored in a file, Mobile Recharge, DTH Recharge and any Online Recharge', + 'Other categories', + ), + ); + } - $methods[] = 'WC_WooMercadoPago_BasicGateway'; - $methods[] = 'WC_WooMercadoPago_CustomGateway'; - $methods[] = 'WC_WooMercadoPago_TicketGateway'; - return $methods; - } + /** + * @param $methods + * @return array + */ + public function setPaymentGateway( $methods = null ) { + global $wp; + if ( ! empty( $wp ) && isset( $wp->query_vars['wc-api'] ) ) { + $api_request = wc_clean( $wp->query_vars['wc-api'] ); + if ( ! empty( $api_request ) && in_array( $api_request, array( 'WC_WooMercadoPago_BasicGateway', 'WC_WooMercadoPago_CustomGateway', 'WC_WooMercadoPago_TicketGateway' ) ) ) { + $methods[] = $api_request; + } + return $methods; + } + + $methods[] = 'WC_WooMercadoPago_BasicGateway'; + $methods[] = 'WC_WooMercadoPago_CustomGateway'; + $methods[] = 'WC_WooMercadoPago_TicketGateway'; + return $methods; + } } diff --git a/includes/module/WC_WooMercadoPago_Credentials.php b/includes/module/WC_WooMercadoPago_Credentials.php index f0d992002..cdcc8e8fd 100755 --- a/includes/module/WC_WooMercadoPago_Credentials.php +++ b/includes/module/WC_WooMercadoPago_Credentials.php @@ -1,346 +1,333 @@ payment = $payment; - $publicKey = get_option('_mp_public_key_prod', ''); - $accessToken = get_option('_mp_access_token_prod', ''); - - if (!is_null($this->payment)) { - $this->sandbox = $payment->isTestUser(); - if ($this->payment->getOption('checkout_credential_prod', '') == 'no' || empty($this->payment->getOption('checkout_credential_prod', ''))) { - $publicKey = get_option('_mp_public_key_test', ''); - $accessToken = get_option('_mp_access_token_test', ''); - } - } - - if (is_null($this->payment) && empty($publicKey) && empty($accessToken)) { - $publicKey = get_option('_mp_public_key_test', ''); - $accessToken = get_option('_mp_access_token_test', ''); - } - - $this->publicKey = $publicKey; - $this->accessToken = $accessToken; - $this->clientId = get_option('_mp_client_id'); - $this->clientSecret = get_option('_mp_client_secret'); - } - - public static function mercadopago_payment_update() - { - try { - $mp_v1 = WC_WooMercadoPago_Module::getMpInstanceSingleton(); - if ($mp_v1 instanceof MP == false) { - self::setNoCredentials(); - return; - } - - $access_token = $mp_v1->get_access_token(); - if (!empty($access_token)) { - $payments_response = self::getPaymentResponse($mp_v1, $access_token); - self::updatePaymentMethods($mp_v1, $access_token, $payments_response); - self::updateTicketMethod($mp_v1, $access_token, $payments_response); - } - } catch (WC_WooMercadoPago_Exception $e) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log('WC_WooMercadoPago_Credentials'); - $log->write_log('mercadopago_payment_update', 'Exception ERROR' . $e->getMessage()); - } - } - - /** - * @return bool|string - */ - public function validateCredentialsType() - { - $basicIsEnabled = self::basicIsEnabled(); - if (!$this->tokenIsValid() && ($this->payment instanceof WC_WooMercadoPago_BasicGateway || $basicIsEnabled == 'yes')) { - if (!$this->clientIsValid()) { - return self::TYPE_ACCESS_TOKEN; - } - return self::TYPE_ACCESS_CLIENT; - } - - return self::TYPE_ACCESS_TOKEN; - } - - /** - * @return bool - */ - public function clientIsValid() - { - if (empty($this->clientId) || empty($this->clientSecret)) { - return false; - } - return true; - } - - /** - * @return bool - */ - public function tokenIsValid() - { - if (empty($this->publicKey) || empty($this->accessToken)) { - return false; - } - - return true; - } - - /** - * Set no Credentials - */ - public static function setNoCredentials() - { - update_option('_test_user_v1', '', true); - update_option('_site_id_v1', '', true); - update_option('_collector_id_v1', '', true); - update_option('_all_payment_methods_v0', array(), true); - update_option('_all_payment_methods_ticket', '[]', true); - update_option('_can_do_currency_conversion_v1', false, true); - } - - /** - * @param $access_token - * @return bool - * @throws WC_WooMercadoPago_Exception - */ - public static function access_token_is_valid($access_token) - { - $mp_v1 = WC_WooMercadoPago_Module::getMpInstanceSingleton(); - if (empty($mp_v1)) { - return false; - } - $get_request = $mp_v1->get('/users/me', array('Authorization' => 'Bearer ' . $access_token), false); - if ($get_request['status'] > 202) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log('WC_WooMercadoPago_Credentials'); - $log->write_log('API valid_access_token error:', $get_request['response']['message']); - return false; - } - - if (isset($get_request['response']['site_id'])) { - update_option('_site_id_v1', $get_request['response']['site_id'], true); - update_option('_test_user_v1', in_array('test_user', $get_request['response']['tags']), true); - } - - if (isset($get_request['response']['id'])) { - update_option('_collector_id_v1', $get_request['response']['id'], true); - } - - return true; - } - - /** - * @return bool - */ - public static function validate_credentials_v1() - { - $credentials = new self(); - $basicIsEnabled = 'no'; - if (!$credentials->tokenIsValid()) { - $basicIsEnabled = self::basicIsEnabled(); - if ($basicIsEnabled != 'yes') { - self::setNoCredentials(); - return false; - } - } - - try { - $mp_v1 = WC_WooMercadoPago_Module::getMpInstanceSingleton(); - if ($mp_v1 instanceof MP == false) { - self::setNoCredentials(); - return false; - } - $access_token = $mp_v1->get_access_token(); - $get_request = $mp_v1->get('/users/me', array('Authorization' => 'Bearer ' . $access_token)); - - if (isset($get_request['response']['site_id']) && (!empty($credentials->publicKey) || $basicIsEnabled == 'yes')) { - - 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); - - self::mercadopago_payment_update(); - - $currency_ratio = WC_WooMercadoPago_Module::get_conversion_rate( - WC_WooMercadoPago_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 (WC_WooMercadoPago_Exception $e) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log('WC_WooMercadoPago_Credentials'); - $log->write_log('validate_credentials_v1', 'Exception ERROR' . $e->getMessage()); - } - - self::setNoCredentials(); - return false; - } - - /** - * @param $mpInstance - * @param $accessToken - * @return null - */ - public static function getPaymentResponse($mpInstance, $accessToken) - { - $seller = get_option('_collector_id_v1', ''); - $payments = $mpInstance->get_payment_methods($accessToken); - if (isset($payments['response'])) { - return $payments['response']; - } - - return null; - } - - /** - * @param $mpInstance - * @param null $accessToken - * @param null $paymentsResponse - */ - public static function updatePaymentMethods($mpInstance, $accessToken = null, $paymentsResponse = null) - { - if (empty($accessToken) || empty($mpInstance)) { - return; - } - - if (empty($paymentsResponse)) { - $paymentsResponse = self::getPaymentResponse($mpInstance, $accessToken); - } - - if (empty($paymentsResponse) || (isset($paymentsResponse['status']) && $paymentsResponse['status'] != 200 && - $paymentsResponse['status'] != 201)) { - return; - } - - $arr = array(); - $cho = array(); - $excluded = array('consumer_credits', 'paypal'); - - foreach ($paymentsResponse as $payment) { - if (in_array($payment['id'], $excluded)) { - continue; - } - - $arr[] = $payment['id']; - - $cho[] = array( - "id" => $payment['id'], - "name" => $payment['name'], - "type" => $payment['payment_type_id'], - "image" => $payment['secure_thumbnail'], - "config" => "ex_payments_" . $payment['id'], - ); - } - - update_option('_all_payment_methods_v0', implode(',', $arr), true); - update_option('_checkout_payments_methods', $cho, true); - } - - /** - * @param $mpInstance - * @param $accessToken - * @param null $paymentsResponse - */ - public static function updateTicketMethod($mpInstance, $accessToken, $paymentsResponse = null) - { - if (empty($accessToken) || empty($mpInstance)) { - return; - } - - if (empty($paymentsResponse)) { - $paymentsResponse = self::getPaymentResponse($mpInstance, $accessToken); - } - - if (empty($paymentsResponse) || (isset($paymentsResponse['status']) && $paymentsResponse['status'] != 200 && - $paymentsResponse['status'] != 201)) { - return; - } - - $payment_methods_ticket = array(); - $excluded = array('paypal'); - - foreach ($paymentsResponse as $payment) { - if ( - !in_array($payment['id'], $excluded) && - $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_methods_ticket[] = array( - "id" => $payment['id'], - "name" => $payment['name'], - "secure_thumbnail" => $payment['secure_thumbnail'], - ); - } - } - - update_option('_all_payment_methods_ticket', $payment_methods_ticket, true); - } - - /** - * @return string - */ - public static function basicIsEnabled() - { - $basicIsEnabled = 'no'; - $basicSettings = get_option('woocommerce_woo-mercado-pago-basic_settings', ''); - if (isset($basicSettings['enabled'])) { - $basicIsEnabled = $basicSettings['enabled']; - } - - return $basicIsEnabled; - } - - /** - * @throws WC_WooMercadoPago_Exception - */ - public static function validateCredentialsTest($mpInstance, $access_token = null, $public_key = null) - { - $isTeste = $mpInstance->getCredentialsWrapper($access_token, $public_key); - if (is_array($isTeste) && isset($isTeste['is_test']) && $isTeste['is_test'] == true) { - return true; - } - return false; - } - - /** - * @throws WC_WooMercadoPago_Exception - */ - public static function validateCredentialsProd($mpInstance, $access_token = null, $public_key = null) - { - $isTeste = $mpInstance->getCredentialsWrapper($access_token, $public_key); - if (is_array($isTeste) && isset($isTeste['is_test']) && $isTeste['is_test'] == false) { - return true; - } - return false; - } +class WC_WooMercadoPago_Credentials { + + const TYPE_ACCESS_CLIENT = 'client'; + const TYPE_ACCESS_TOKEN = 'token'; + + public $payment; + public $publicKey; + public $accessToken; + public $clientId; + public $clientSecret; + public $sandbox; + public $log; + + /** + * WC_WooMercadoPago_Credentials constructor. + * + * @param $payment + */ + public function __construct( $payment = null ) { + $this->payment = $payment; + $publicKey = get_option( '_mp_public_key_prod', '' ); + $accessToken = get_option( '_mp_access_token_prod', '' ); + + if ( ! is_null( $this->payment ) ) { + $this->sandbox = $payment->isTestUser(); + if ( $this->payment->getOption( 'checkout_credential_prod', '' ) == 'no' || empty( $this->payment->getOption( 'checkout_credential_prod', '' ) ) ) { + $publicKey = get_option( '_mp_public_key_test', '' ); + $accessToken = get_option( '_mp_access_token_test', '' ); + } + } + + if ( is_null( $this->payment ) && empty( $publicKey ) && empty( $accessToken ) ) { + $publicKey = get_option( '_mp_public_key_test', '' ); + $accessToken = get_option( '_mp_access_token_test', '' ); + } + + $this->publicKey = $publicKey; + $this->accessToken = $accessToken; + $this->clientId = get_option( '_mp_client_id' ); + $this->clientSecret = get_option( '_mp_client_secret' ); + } + + public static function mercadopago_payment_update() { + try { + $mp_v1 = WC_WooMercadoPago_Module::getMpInstanceSingleton(); + if ( $mp_v1 instanceof MP == false ) { + self::setNoCredentials(); + return; + } + + $access_token = $mp_v1->get_access_token(); + if ( ! empty( $access_token ) ) { + $payments_response = self::getPaymentResponse( $mp_v1, $access_token ); + self::updatePaymentMethods( $mp_v1, $access_token, $payments_response ); + self::updateTicketMethod( $mp_v1, $access_token, $payments_response ); + } + } catch ( WC_WooMercadoPago_Exception $e ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'WC_WooMercadoPago_Credentials' ); + $log->write_log( 'mercadopago_payment_update', 'Exception ERROR' . $e->getMessage() ); + } + } + + /** + * @return bool|string + */ + public function validateCredentialsType() { + $basicIsEnabled = self::basicIsEnabled(); + if ( ! $this->tokenIsValid() && ( $this->payment instanceof WC_WooMercadoPago_BasicGateway || $basicIsEnabled == 'yes' ) ) { + if ( ! $this->clientIsValid() ) { + return self::TYPE_ACCESS_TOKEN; + } + return self::TYPE_ACCESS_CLIENT; + } + + return self::TYPE_ACCESS_TOKEN; + } + + /** + * @return bool + */ + public function clientIsValid() { + if ( empty( $this->clientId ) || empty( $this->clientSecret ) ) { + return false; + } + return true; + } + + /** + * @return bool + */ + public function tokenIsValid() { + if ( empty( $this->publicKey ) || empty( $this->accessToken ) ) { + return false; + } + + return true; + } + + /** + * Set no Credentials + */ + public static function setNoCredentials() { + update_option( '_test_user_v1', '', true ); + update_option( '_site_id_v1', '', true ); + update_option( '_collector_id_v1', '', true ); + update_option( '_all_payment_methods_v0', array(), true ); + update_option( '_all_payment_methods_ticket', '[]', true ); + update_option( '_can_do_currency_conversion_v1', false, true ); + } + + /** + * @param $access_token + * @return bool + * @throws WC_WooMercadoPago_Exception + */ + public static function access_token_is_valid( $access_token ) { + $mp_v1 = WC_WooMercadoPago_Module::getMpInstanceSingleton(); + if ( empty( $mp_v1 ) ) { + return false; + } + $get_request = $mp_v1->get( '/users/me', array( 'Authorization' => 'Bearer ' . $access_token ), false ); + if ( $get_request['status'] > 202 ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'WC_WooMercadoPago_Credentials' ); + $log->write_log( 'API valid_access_token error:', $get_request['response']['message'] ); + return false; + } + + if ( isset( $get_request['response']['site_id'] ) ) { + update_option( '_site_id_v1', $get_request['response']['site_id'], true ); + update_option( '_test_user_v1', in_array( 'test_user', $get_request['response']['tags'] ), true ); + } + + if ( isset( $get_request['response']['id'] ) ) { + update_option( '_collector_id_v1', $get_request['response']['id'], true ); + } + + return true; + } + + /** + * @return bool + */ + public static function validate_credentials_v1() { + $credentials = new self(); + $basicIsEnabled = 'no'; + if ( ! $credentials->tokenIsValid() ) { + $basicIsEnabled = self::basicIsEnabled(); + if ( $basicIsEnabled != 'yes' ) { + self::setNoCredentials(); + return false; + } + } + + try { + $mp_v1 = WC_WooMercadoPago_Module::getMpInstanceSingleton(); + if ( $mp_v1 instanceof MP == false ) { + self::setNoCredentials(); + return false; + } + $access_token = $mp_v1->get_access_token(); + $get_request = $mp_v1->get( '/users/me', array( 'Authorization' => 'Bearer ' . $access_token ) ); + + if ( isset( $get_request['response']['site_id'] ) && ( ! empty( $credentials->publicKey ) || $basicIsEnabled == 'yes' ) ) { + + 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 ); + + self::mercadopago_payment_update(); + + $currency_ratio = WC_WooMercadoPago_Module::get_conversion_rate( + WC_WooMercadoPago_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 ( WC_WooMercadoPago_Exception $e ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'WC_WooMercadoPago_Credentials' ); + $log->write_log( 'validate_credentials_v1', 'Exception ERROR' . $e->getMessage() ); + } + + self::setNoCredentials(); + return false; + } + + /** + * @param $mpInstance + * @param $accessToken + * @return null + */ + public static function getPaymentResponse( $mpInstance, $accessToken ) { + $seller = get_option( '_collector_id_v1', '' ); + $payments = $mpInstance->get_payment_methods( $accessToken ); + if ( isset( $payments['response'] ) ) { + return $payments['response']; + } + + return null; + } + + /** + * @param $mpInstance + * @param null $accessToken + * @param null $paymentsResponse + */ + public static function updatePaymentMethods( $mpInstance, $accessToken = null, $paymentsResponse = null ) { + if ( empty( $accessToken ) || empty( $mpInstance ) ) { + return; + } + + if ( empty( $paymentsResponse ) ) { + $paymentsResponse = self::getPaymentResponse( $mpInstance, $accessToken ); + } + + if ( empty( $paymentsResponse ) || ( isset( $paymentsResponse['status'] ) && $paymentsResponse['status'] != 200 && + $paymentsResponse['status'] != 201 ) ) { + return; + } + + $arr = array(); + $cho = array(); + $excluded = array( 'consumer_credits', 'paypal' ); + + foreach ( $paymentsResponse as $payment ) { + if ( in_array( $payment['id'], $excluded ) ) { + continue; + } + + $arr[] = $payment['id']; + + $cho[] = array( + 'id' => $payment['id'], + 'name' => $payment['name'], + 'type' => $payment['payment_type_id'], + 'image' => $payment['secure_thumbnail'], + 'config' => 'ex_payments_' . $payment['id'], + ); + } + + update_option( '_all_payment_methods_v0', implode( ',', $arr ), true ); + update_option( '_checkout_payments_methods', $cho, true ); + } + + /** + * @param $mpInstance + * @param $accessToken + * @param null $paymentsResponse + */ + public static function updateTicketMethod( $mpInstance, $accessToken, $paymentsResponse = null ) { + if ( empty( $accessToken ) || empty( $mpInstance ) ) { + return; + } + + if ( empty( $paymentsResponse ) ) { + $paymentsResponse = self::getPaymentResponse( $mpInstance, $accessToken ); + } + + if ( empty( $paymentsResponse ) || ( isset( $paymentsResponse['status'] ) && $paymentsResponse['status'] != 200 && + $paymentsResponse['status'] != 201 ) ) { + return; + } + + $payment_methods_ticket = array(); + $excluded = array( 'paypal' ); + + foreach ( $paymentsResponse as $payment ) { + if ( + ! in_array( $payment['id'], $excluded ) && + $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_methods_ticket[] = array( + 'id' => $payment['id'], + 'name' => $payment['name'], + 'secure_thumbnail' => $payment['secure_thumbnail'], + ); + } + } + + update_option( '_all_payment_methods_ticket', $payment_methods_ticket, true ); + } + + /** + * @return string + */ + public static function basicIsEnabled() { + $basicIsEnabled = 'no'; + $basicSettings = get_option( 'woocommerce_woo-mercado-pago-basic_settings', '' ); + if ( isset( $basicSettings['enabled'] ) ) { + $basicIsEnabled = $basicSettings['enabled']; + } + + return $basicIsEnabled; + } + + /** + * @throws WC_WooMercadoPago_Exception + */ + public static function validateCredentialsTest( $mpInstance, $access_token = null, $public_key = null ) { + $isTeste = $mpInstance->getCredentialsWrapper( $access_token, $public_key ); + if ( is_array( $isTeste ) && isset( $isTeste['is_test'] ) && $isTeste['is_test'] == true ) { + return true; + } + return false; + } + + /** + * @throws WC_WooMercadoPago_Exception + */ + public static function validateCredentialsProd( $mpInstance, $access_token = null, $public_key = null ) { + $isTeste = $mpInstance->getCredentialsWrapper( $access_token, $public_key ); + if ( is_array( $isTeste ) && isset( $isTeste['is_test'] ) && $isTeste['is_test'] == false ) { + return true; + } + return false; + } } diff --git a/includes/module/WC_WooMercadoPago_Exception.php b/includes/module/WC_WooMercadoPago_Exception.php index 661d50439..3b678b111 100644 --- a/includes/module/WC_WooMercadoPago_Exception.php +++ b/includes/module/WC_WooMercadoPago_Exception.php @@ -9,13 +9,14 @@ */ class WC_WooMercadoPago_Exception extends Exception { - /** - * WC_WooMercadoPago_Exception constructor. - * @param $message - * @param int $code - * @param Exception|null $previous - */ - public function __construct( $message, $code = 500, Exception $previous = null ) { - parent::__construct( $message, $code, $previous ); - } -} \ No newline at end of file + /** + * WC_WooMercadoPago_Exception constructor. + * + * @param $message + * @param int $code + * @param Exception|null $previous + */ + public function __construct( $message, $code = 500, Exception $previous = null ) { + parent::__construct( $message, $code, $previous ); + } +} diff --git a/includes/module/WC_WooMercadoPago_Init.php b/includes/module/WC_WooMercadoPago_Init.php index 1b7781ea6..2427fd414 100644 --- a/includes/module/WC_WooMercadoPago_Init.php +++ b/includes/module/WC_WooMercadoPago_Init.php @@ -1,153 +1,144 @@ WooCommerce' - ); - echo WC_WooMercadoPago_Notices::getAlertWocommerceMiss($message, $type); - } - - public static function add_mp_order_meta_box_actions($actions) - { - $actions['cancel_order'] = __('Cancel order', 'woocommerce-mercadopago'); - return $actions; - } - - /** - * - */ - public static function mp_show_admin_notices() - { - if (!WC_WooMercadoPago_Module::isWcNewVersion() || (isset($_GET['page']) && $_GET['page'] == "wc-settings") && is_plugin_active('woocommerce-admin/woocommerce-admin.php')) { - return; - } - - $noticesArray = WC_WooMercadoPago_Module::$notices; - $notices = array_unique($noticesArray, SORT_STRING); - foreach ($notices as $notice) { - echo $notice; - } - } - - /** - * Activation plugin hook - */ - public static function mercadopago_plugin_activation() - { - $dismissedReview = (int) get_option('_mp_dismiss_review'); - if (!isset($dismissedReview) || $dismissedReview == 1) { - update_option('_mp_dismiss_review', 0, true); - } - } - - /** - * Update plugin version in db - */ - public static function update_plugin_version() - { - $oldVersion = get_option('_mp_version', '0'); - if (version_compare(WC_WooMercadoPago_Constants::VERSION, $oldVersion, '>')) { - do_action('mercadopago_plugin_updated'); - update_option('_mp_version', WC_WooMercadoPago_Constants::VERSION, true); - } - } - - /** - * Init the plugin - */ - public static function woocommerce_mercadopago_init() - { - self::woocommerce_mercadopago_load_plugin_textdomain(); - require_once dirname(__FILE__) . '../../admin/notices/WC_WooMercadoPago_Notices.php'; - WC_WooMercadoPago_Notices::initMercadopagoNotice(); - - // Check for PHP version and throw notice. - if (version_compare(PHP_VERSION, '5.6', '<=')) { - add_action('admin_notices', array(__CLASS__, 'wc_mercado_pago_unsupported_php_version_notice')); - return; - } - - if (!in_array('curl', get_loaded_extensions())) { - add_action('admin_notices', array(__CLASS__, 'wc_mercado_pago_notify_curl_error')); - return; - } - - // Load Mercado Pago SDK - require_once dirname(__FILE__) . '/sdk/lib/MP.php'; - - // Checks with WooCommerce is installed. - if (class_exists('WC_Payment_Gateway')) { - require_once dirname(__FILE__) . '/config/WC_WooMercadoPago_Constants.php'; - require_once dirname(__FILE__) . '/WC_WooMercadoPago_Exception.php'; - require_once dirname(__FILE__) . '/WC_WooMercadoPago_Configs.php'; - require_once dirname(__FILE__) . '/log/WC_WooMercadoPago_Log.php'; - require_once dirname(__FILE__) . '/WC_WooMercadoPago_Module.php'; - require_once dirname(__FILE__) . '/WC_WooMercadoPago_Credentials.php'; - require_once dirname(__FILE__) . '../../admin/notices/WC_WooMercadoPago_ReviewNotice.php'; - - WC_WooMercadoPago_Module::init_mercado_pago_class(); - WC_WooMercadoPago_ReviewNotice::initMercadopagoReviewNotice(); - self::update_plugin_version(); - - add_action('woocommerce_order_actions', array(__CLASS__, 'add_mp_order_meta_box_actions')); - } else { - add_action('admin_notices', array(__CLASS__, 'notify_woocommerce_miss')); - } - add_action('woocommerce_settings_checkout', array(__CLASS__, 'mp_show_admin_notices')); - } +class WC_WooMercadoPago_Init { + + /** + * Load plugin text domain. + * + * Need to require here before test for PHP version. + * + * @since 3.0.1 + */ + public static function woocommerce_mercadopago_load_plugin_textdomain() { + $text_domain = 'woocommerce-mercadopago'; + $locale = apply_filters( 'plugin_locale', get_locale(), $text_domain ); + + $original_language_file = dirname( __FILE__ ) . '/../../i18n/languages/woocommerce-mercadopago-' . $locale . '.mo'; + + // Unload the translation for the text domain of the plugin + unload_textdomain( $text_domain ); + // Load first the override file + load_textdomain( $text_domain, $original_language_file ); + } + + /** + * Notice about unsupported PHP version. + * + * @since 3.0.1 + */ + public static function wc_mercado_pago_unsupported_php_version_notice() { + $type = 'error'; + $message = esc_html__( 'Mercado Pago payments for WooCommerce requires PHP version 5.6 or later. Please update your PHP version.', 'woocommerce-mercadopago' ); + echo WC_WooMercadoPago_Notices::getAlertFrame( $message, $type ); + } + + /** + * Curl validation + */ + public static function wc_mercado_pago_notify_curl_error() { + $type = 'error'; + $message = __( 'Mercado Pago Error: PHP Extension CURL is not installed.', 'woocommerce-mercadopago' ); + echo WC_WooMercadoPago_Notices::getAlertFrame( $message, $type ); + } + + /** + * 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 static function notify_woocommerce_miss() { + $type = 'error'; + $message = sprintf( + __( 'The Mercado Pago module needs an active version of %s in order to work!', 'woocommerce-mercadopago' ), + ' WooCommerce' + ); + echo WC_WooMercadoPago_Notices::getAlertWocommerceMiss( $message, $type ); + } + + public static function add_mp_order_meta_box_actions( $actions ) { + $actions['cancel_order'] = __( 'Cancel order', 'woocommerce-mercadopago' ); + return $actions; + } + + /** + * + */ + public static function mp_show_admin_notices() { + if ( ! WC_WooMercadoPago_Module::isWcNewVersion() || ( isset( $_GET['page'] ) && $_GET['page'] == 'wc-settings' ) && is_plugin_active( 'woocommerce-admin/woocommerce-admin.php' ) ) { + return; + } + + $noticesArray = WC_WooMercadoPago_Module::$notices; + $notices = array_unique( $noticesArray, SORT_STRING ); + foreach ( $notices as $notice ) { + echo $notice; + } + } + + /** + * Activation plugin hook + */ + public static function mercadopago_plugin_activation() { + $dismissedReview = (int) get_option( '_mp_dismiss_review' ); + if ( ! isset( $dismissedReview ) || $dismissedReview == 1 ) { + update_option( '_mp_dismiss_review', 0, true ); + } + } + + /** + * Update plugin version in db + */ + public static function update_plugin_version() { + $oldVersion = get_option( '_mp_version', '0' ); + if ( version_compare( WC_WooMercadoPago_Constants::VERSION, $oldVersion, '>' ) ) { + do_action( 'mercadopago_plugin_updated' ); + update_option( '_mp_version', WC_WooMercadoPago_Constants::VERSION, true ); + } + } + + /** + * Init the plugin + */ + public static function woocommerce_mercadopago_init() { + self::woocommerce_mercadopago_load_plugin_textdomain(); + require_once dirname( __FILE__ ) . '../../admin/notices/WC_WooMercadoPago_Notices.php'; + WC_WooMercadoPago_Notices::initMercadopagoNotice(); + + // Check for PHP version and throw notice. + if ( version_compare( PHP_VERSION, '5.6', '<=' ) ) { + add_action( 'admin_notices', array( __CLASS__, 'wc_mercado_pago_unsupported_php_version_notice' ) ); + return; + } + + if ( ! in_array( 'curl', get_loaded_extensions() ) ) { + add_action( 'admin_notices', array( __CLASS__, 'wc_mercado_pago_notify_curl_error' ) ); + return; + } + + // Load Mercado Pago SDK + require_once dirname( __FILE__ ) . '/sdk/lib/MP.php'; + + // Checks with WooCommerce is installed. + if ( class_exists( 'WC_Payment_Gateway' ) ) { + require_once dirname( __FILE__ ) . '/config/WC_WooMercadoPago_Constants.php'; + require_once dirname( __FILE__ ) . '/WC_WooMercadoPago_Exception.php'; + require_once dirname( __FILE__ ) . '/WC_WooMercadoPago_Configs.php'; + require_once dirname( __FILE__ ) . '/log/WC_WooMercadoPago_Log.php'; + require_once dirname( __FILE__ ) . '/WC_WooMercadoPago_Module.php'; + require_once dirname( __FILE__ ) . '/WC_WooMercadoPago_Credentials.php'; + require_once dirname( __FILE__ ) . '../../admin/notices/WC_WooMercadoPago_ReviewNotice.php'; + + WC_WooMercadoPago_Module::init_mercado_pago_class(); + WC_WooMercadoPago_ReviewNotice::initMercadopagoReviewNotice(); + self::update_plugin_version(); + + add_action( 'woocommerce_order_actions', array( __CLASS__, 'add_mp_order_meta_box_actions' ) ); + } else { + add_action( 'admin_notices', array( __CLASS__, 'notify_woocommerce_miss' ) ); + } + add_action( 'woocommerce_settings_checkout', array( __CLASS__, 'mp_show_admin_notices' ) ); + } } diff --git a/includes/module/WC_WooMercadoPago_Module.php b/includes/module/WC_WooMercadoPago_Module.php index 06662ddc3..a4c3b37b8 100755 --- a/includes/module/WC_WooMercadoPago_Module.php +++ b/includes/module/WC_WooMercadoPago_Module.php @@ -1,621 +1,596 @@ loadHelpers(); - $this->loadConfigs(); - $this->loadLog(); - $this->loadHooks(); - $this->loadPreferences(); - $this->loadPayments(); - $this->loadNotifications(); - $this->loadStockManager(); - - add_action('admin_enqueue_scripts', [$this, 'loadAdminCss']); - - add_filter('woocommerce_available_payment_gateways', array($this, 'filterPaymentMethodByShipping')); - add_filter('plugin_action_links_' . WC_MERCADOPAGO_BASENAME, array($this, 'woomercadopago_settings_link')); - add_filter('plugin_row_meta', array($this, 'mp_plugin_row_meta'), 10, 2); - add_action('mercadopago_plugin_updated', array('WC_WooMercadoPago_Credentials', 'mercadopago_payment_update')); - - if (is_admin()) { - //validate credentials - if (isset($_REQUEST['section'])) { - $credentials = new WC_WooMercadoPago_Credentials(); - if (!$credentials->tokenIsValid()) { - add_action('admin_notices', [$this, 'enablePaymentNotice']); - } - } - } - } catch (Exception $e) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log('WC_WooMercadoPago_Module'); - $log->write_log('__construct: ', $e->getMessage()); - } - } - - /** - * @param $payment - * @return MP - * @throws WC_WooMercadoPago_Exception - */ - public static function getMpInstance($payment = null) - { - $credentials = new WC_WooMercadoPago_Credentials($payment); - $validateCredentialsType = $credentials->validateCredentialsType(); - if ($validateCredentialsType == WC_WooMercadoPago_Credentials::TYPE_ACCESS_TOKEN) { - $mp = new MP($credentials->accessToken); - $mp->setPaymentClass($payment); - } - if ($validateCredentialsType == WC_WooMercadoPago_Credentials::TYPE_ACCESS_CLIENT) { - $mp = new MP($credentials->clientId, $credentials->clientSecret); - $mp->setPaymentClass($payment); - if (!empty($payment)) { - $payment->sandbox = false; - } - } - - if (!isset($mp)) { - return false; - } - - $email = (wp_get_current_user()->ID != 0) ? wp_get_current_user()->user_email : null; - $mp->set_email($email); - - $locale = get_locale(); - $locale = (strpos($locale, '_') !== false && strlen($locale) == 5) ? explode('_', $locale) : array('', ''); - $mp->set_locale($locale[1]); - - return $mp; - } - - /** - * @param null $payment - * @return MP|null - * @throws WC_WooMercadoPago_Exception - */ - public static function getMpInstanceSingleton($payment = null) - { - $mp = null; - if (!empty($payment)) { - $class = get_class($payment); - if (!isset(self::$mpInstancePayment[$class])) { - self::$mpInstancePayment[$class] = self::getMpInstance($payment); - $mp = self::$mpInstancePayment[$class]; - if (!empty($mp)) { - return $mp; - } - } - } - - if (self::$mpInstance === null || empty($mp)) { - self::$mpInstance = self::getMpInstance(); - } - - return self::$mpInstance; - } - - /** - * @return WC_WooMercadoPago_Module|null - * Singleton - */ - public static function init_mercado_pago_class() - { - if (self::$instance === null) { - self::$instance = new self; - } - return self::$instance; - } - - /** - * Load Config / Categories - */ - public function loadConfigs() - { - self::$country_configs = self::getCountryConfigs(); - $configs = new parent(); - self::$categories = $configs->getCategories(); - self::$site_data = self::get_site_data(); - self::$payments_name = self::setPaymentGateway(); - } - - /** - * Load Hooks - */ - public function loadHooks() - { - include_once dirname(__FILE__) . '/../payments/hooks/WC_WooMercadoPago_Hook_Abstract.php'; - include_once dirname(__FILE__) . '/../payments/hooks/WC_WooMercadoPago_Hook_Basic.php'; - include_once dirname(__FILE__) . '/../payments/hooks/WC_WooMercadoPago_Hook_Custom.php'; - include_once dirname(__FILE__) . '/../payments/hooks/WC_WooMercadoPago_Hook_Ticket.php'; - } - - /** - * Load Helpers - */ - public function loadHelpers() - { - include_once dirname(__FILE__) . '/../helpers/WC_WooMercadoPago_Helpers_CurrencyConverter.php'; - } - - /** - * Load Preferences Classes - */ - public function loadPreferences() - { - include_once dirname(__FILE__) . '/preference/WC_WooMercadoPago_PreferenceAbstract.php'; - include_once dirname(__FILE__) . '/preference/WC_WooMercadoPago_PreferenceBasic.php'; - include_once dirname(__FILE__) . '/preference/WC_WooMercadoPago_PreferenceCustom.php'; - include_once dirname(__FILE__) . '/preference/WC_WooMercadoPago_PreferenceTicket.php'; - include_once dirname(__FILE__) . '/preference/analytics/WC_WooMercadoPago_PreferenceAnalytics.php'; - } - - /** - * Load Payment Classes - */ - public function loadPayments() - { - include_once dirname(__FILE__) . '/../payments/WC_WooMercadoPago_PaymentAbstract.php'; - include_once dirname(__FILE__) . '/../payments/WC_WooMercadoPago_BasicGateway.php'; - include_once dirname(__FILE__) . '/../payments/WC_WooMercadoPago_CustomGateway.php'; - include_once dirname(__FILE__) . '/../payments/WC_WooMercadoPago_TicketGateway.php'; - add_filter('woocommerce_payment_gateways', array($this, 'setPaymentGateway')); - } - - /** - * - */ - public function loadNotifications() - { - include_once dirname(__FILE__) . '/../notification/WC_WooMercadoPago_Notification_Abstract.php'; - include_once dirname(__FILE__) . '/../notification/WC_WooMercadoPago_Notification_IPN.php'; - include_once dirname(__FILE__) . '/../notification/WC_WooMercadoPago_Notification_Webhook.php'; - } - - /** - * - */ - public function loadLog() - { - include_once dirname(__FILE__) . '/log/WC_WooMercadoPago_Log.php'; - } - - /** - * - */ - public function loadAdminCss() - { - if (is_admin()) { - $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; - - wp_enqueue_style( - 'woocommerce-mercadopago-basic-config-styles', - plugins_url('../assets/css/config_mercadopago' . $suffix . '.css', plugin_dir_path(__FILE__)) - ); - } - } - - /** - * Stock Manager - */ - public function loadStockManager() - { - include_once dirname(__FILE__) . '/../stock/WC_WooMercadoPago_Stock_Manager.php'; - } - - /** - * @param $methods - * @return array - */ - public function filterPaymentMethodByShipping($methods) - { - return $methods; - } - - /** - * Enable Payment Notice - */ - public function enablePaymentNotice() - { - $type = 'notice-warning'; - $message = __('Fill in your credentials to enable payment methods.', 'woocommerce-mercadopago'); - echo WC_WooMercadoPago_Notices::getAlertFrame($message, $type); - } - - // Add settings link on plugin page. - public function woomercadopago_settings_link($links) - { - $links_mp = $this->define_link_country(); - $plugin_links = array(); - $plugin_links[] = '' . __('Set up', 'woocommerce-mercadopago') . ''; - $plugin_links[] = '' . __('Your opinion helps us get better', 'woocommerce-mercadopago') . ''; - $plugin_links[] = '
' . __('Guides and Documentation', 'woocommerce-mercadopago') . ''; - $plugin_links[] = '' . __('Report Problem', 'woocommerce-mercadopago') . ''; - return array_merge($plugin_links, $links); - } - - /** - * Construct link - * @return array - */ - public static function define_link_country() - { - $wc_country = get_option('woocommerce_default_country', ''); - $sufix_country = 'AR'; - $country = array( - 'AR' => array( // Argentinian - 'help' => 'ayuda', - 'sufix_url' => 'com.ar/', - 'translate' => 'es', - ), - 'BR' => array( // Brazil - 'help' => 'ajuda', - 'sufix_url' => 'com.br/', - 'translate' => 'pt', - ), - 'CL' => array( // Chile - 'help' => 'ayuda', - 'sufix_url' => 'cl/', - 'translate' => 'es', - ), - 'CO' => array( // Colombia - 'help' => 'ayuda', - 'sufix_url' => 'com.co/', - 'translate' => 'es', - ), - 'MX' => array( // Mexico - 'help' => 'ayuda', - 'sufix_url' => 'com.mx/', - 'translate' => 'es', - ), - 'PE' => array( // Peru - 'help' => 'ayuda', - 'sufix_url' => 'com.pe/', - 'translate' => 'es', - ), - 'UY' => array( // Uruguay - 'help' => 'ayuda', - 'sufix_url' => 'com.uy/', - 'translate' => 'es', - ), - ); - if ($wc_country != '') { - - $sufix_country = strlen($wc_country) > 2 ? substr($wc_country, 0, 2) : $wc_country; - } - - $sufix_country = strtoupper($sufix_country); - $links_country = array_key_exists($sufix_country, $country) ? $country[$sufix_country] : $country['AR']; - - return $links_country; - } - - /** - * Show row meta on the plugin screen. - * @param mixed $links Plugin Row Meta. - * @param mixed $file Plugin Base file. - * @return array - */ - public function mp_plugin_row_meta($links, $file) - { - if (WC_MERCADOPAGO_BASENAME === $file) { - $new_link = array(); - $new_link[] = $links[0]; - $new_link[] = esc_html__('By Mercado Pago', 'woocommerce-mercadopago'); - - return $new_link; - } - - return (array)$links; - } - - // ============================================================ - - // Save and valid Sponsor_id if the site_id returned that api is equal site_id costumers - public static function is_valid_sponsor_id($sponsor_id) - { - $access_token = get_option('_mp_access_token_prod', ''); - $site_id = get_option('_site_id_v1', ''); - - $varify_sponsor = true; - - if (empty($access_token)) { - $varify_sponsor = false; - } elseif ($sponsor_id == '') { - $varify_sponsor = false; - update_option('_mp_sponsor_id', $sponsor_id, true); - } elseif (!is_numeric($sponsor_id)) { - $varify_sponsor = false; - echo '

' . __('The Sponsor ID must be valid!', 'woocommerce-mercadopago') . '

'; - } elseif ($sponsor_id != get_option('_mp_sponsor_id', '')) { - $varify_sponsor = true; - } elseif ($site_id != get_option('_mp_sponsor_site_id', '')) { - $varify_sponsor = true; - } else { - $varify_sponsor = false; - } - - if ($varify_sponsor) { - $mp_sponsor_id = WC_WooMercadoPago_Module::getMpInstanceSingleton(); - $get_sponor_id = $mp_sponsor_id->get('/users/' . $sponsor_id, array('Authorization' => 'Bearer ' . $access_token), false); - if (!is_wp_error($get_sponor_id) && ($get_sponor_id['status'] == 200 || $get_sponor_id['status'] == 201)) { - if ($get_sponor_id['response']['site_id'] == $site_id) { - update_option('_mp_sponsor_id', $sponsor_id, true); - update_option('_mp_sponsor_site_id', $get_sponor_id['response']['site_id'], true); - } else { - echo '

' . __('The Sponsor ID must be from the same country as the seller!', 'woocommerce-mercadopago') . '

'; - update_option('_mp_sponsor_id', '', true); - } - } else { - echo '

' . __('The Sponsor ID must be valid!', 'woocommerce-mercadopago') . '

'; - update_option('_mp_sponsor_id', '', true); - } - } - } - - /** - * 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. - */ - - // 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 __('The payment method is not valid or not available.', 'woocommerce-mercadopago'); - } - if ($key === 'Invalid transaction_amount') { - return __('The transaction amount cannot be processed by Mercado Pago.', 'woocommerce-mercadopago') . ' ' . - __('Possible causes: Currency not supported; Amounts below the minimum or above the maximum allowed.', 'woocommerce-mercadopago'); - } - if ($key === 'Invalid users involved') { - return __('The users are not valid.', 'woocommerce-mercadopago') . ' ' . - __('Possible causes: Buyer and seller have the same account in Mercado Pago; The transaction involving production and test users.', 'woocommerce-mercadopago'); - } - if ($key === 'Unauthorized use of live credentials') { - return __('Unauthorized use of production credentials.', 'woocommerce-mercadopago') . ' ' . - __('Possible causes: Use permission in use for the credential of the seller.', '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 float float that is the rate of conversion. - */ - public static function get_conversion_rate($used_currency) - { - $fromCurrency = get_woocommerce_currency(); - $toCurrency = $used_currency; - - return WC_WooMercadoPago_Helpers_CurrencyConverter::getInstance()->loadRatio($fromCurrency, $toCurrency); - } - - /** - * @return array - */ - public static function get_common_settings() - { - $w = WC_WooMercadoPago_Module::woocommerce_instance(); - $infra_data = array( - 'module_version' => WC_WooMercadoPago_Constants::VERSION, - 'platform' => 'WooCommerce', - 'platform_version' => $w->version, - 'code_version' => phpversion(), - 'so_server' => PHP_OS - ); - return $infra_data; - } - - /** - * Summary: Get Sponsor ID to preferences. - * Description: This function verifies, if the sponsor ID was configured, - * if NO, return Sponsor ID determined of get_site_data(), - * if YES return Sponsor ID configured on plugin - * @return a string. - */ - public static function get_sponsor_id() - { - $site_data = WC_WooMercadoPago_Module::get_site_data(); - return $site_data['sponsor_id']; - } - - /** - * 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() - { - $site_id = get_option('_site_id_v1', ''); - if (isset($site_id) && !empty($site_id)) { - return self::$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 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_WooMercadoPago_Module::$country_configs[$site_id]['currency']; - } - - public static function build_currency_conversion_err_msg($currency) - { - return ' ' . - __('ERROR: It was not possible to convert the unsupported currency', 'woocommerce-mercadopago') . - ' ' . get_woocommerce_currency() . ' ' . - __('a', 'woocommerce-mercadopago') . ' ' . $currency . '. ' . - __('Currency conversions should be done outside of this module.', 'woocommerce-mercadopago'); - } - - public static function build_currency_not_converted_msg($currency, $country_name) - { - return ' ' . - __('ATTENTION: The currency', 'woocommerce-mercadopago') . - ' ' . get_woocommerce_currency() . ' ' . - __('defined in WooCommerce is different from that used by the credentials of your country.
The currency for transactions made with this payment method will be', 'woocommerce-mercadopago') . - ' ' . $currency . ' (' . $country_name . '). ' . - __('Currency conversions should be done outside of this module.', 'woocommerce-mercadopago'); - } - - public static function build_currency_converted_msg($currency) - { - return ' ' . - __('CONVERTED CURRENCY: Your store is converting currency of', 'woocommerce-mercadopago') . - ' ' . get_woocommerce_currency() . ' ' . - __('for', 'woocommerce-mercadopago') . ' ' . $currency; - } - - public static function get_country_name($site_id) - { - switch ($site_id) { - case 'MCO': - return __('Colombia', 'woocommerce-mercadopago'); - case 'MLA': - return __('Argentina', '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 '' . - $gateway_name . ''; - } - - public static function get_map($selector_id) - { - $html = ''; - $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( - '', - $slug, - selected($selection, $slug, false), - __('Update the 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) - { - error_log('generate_refund_cancel_subscription'); - $subscription_js = ''; - $subscription_meta_box = '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '
' . - '
'; - 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; - } - - /** - * @return bool - */ - public static function isWcNewVersion() - { - $wooCommerceVersion = WC()->version; - if ($wooCommerceVersion <= "4.0.0") { - return false; - } - return true; - } - - /** - * @return bool - */ - public static function is_mobile() - { - $mobile = false; - $user_agent = $_SERVER['HTTP_USER_AGENT']; - if (preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i', $user_agent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr($user_agent, 0, 4))) { - $mobile = true; - } - return $mobile; - } + $subscription_meta_box = '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '
' . + '
'; + 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; + } + + /** + * @return bool + */ + public static function isWcNewVersion() { + $wooCommerceVersion = WC()->version; + if ( $wooCommerceVersion <= '4.0.0' ) { + return false; + } + return true; + } + + /** + * @return bool + */ + public static function is_mobile() { + $mobile = false; + $user_agent = $_SERVER['HTTP_USER_AGENT']; + if ( preg_match( '/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i', $user_agent ) || preg_match( '/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr( $user_agent, 0, 4 ) ) ) { + $mobile = true; + } + return $mobile; + } } diff --git a/includes/module/config/WC_WooMercadoPago_Constants.php b/includes/module/config/WC_WooMercadoPago_Constants.php index 63df38c5f..869b84d3e 100644 --- a/includes/module/config/WC_WooMercadoPago_Constants.php +++ b/includes/module/config/WC_WooMercadoPago_Constants.php @@ -7,12 +7,12 @@ /** * Class WC_WooMercadoPago_Constants */ -class WC_WooMercadoPago_Constants -{ - const PRODUCT_ID_DESKTOP = 'BT7OF5FEOO6G01NJK3QG'; - const PRODUCT_ID_MOBILE = 'BT7OFH09QS3001K5A0H0'; - const PLATAFORM_ID = 'bo2hnr2ic4p001kbgpt0'; - const VERSION = '4.6.2'; - const MIN_PHP = 5.6; - const API_MP_BASE_URL = 'https://api.mercadopago.com'; +class WC_WooMercadoPago_Constants { + + const PRODUCT_ID_DESKTOP = 'BT7OF5FEOO6G01NJK3QG'; + const PRODUCT_ID_MOBILE = 'BT7OFH09QS3001K5A0H0'; + const PLATAFORM_ID = 'bo2hnr2ic4p001kbgpt0'; + const VERSION = '4.6.2'; + const MIN_PHP = 5.6; + const API_MP_BASE_URL = 'https://api.mercadopago.com'; } diff --git a/includes/module/log/WC_WooMercadoPago_Log.php b/includes/module/log/WC_WooMercadoPago_Log.php index 36a832762..77005b37d 100644 --- a/includes/module/log/WC_WooMercadoPago_Log.php +++ b/includes/module/log/WC_WooMercadoPago_Log.php @@ -7,93 +7,88 @@ /** * Class WC_WooMercadoPago_Log */ -class WC_WooMercadoPago_Log -{ - public $log; - public $id; - public $debugMode; +class WC_WooMercadoPago_Log { - /** - * WC_WooMercadoPago_Log constructor. - * @param null $payment - * @param bool $debugMode - */ - public function __construct($payment = null, $debugMode = false) - { - $this->getDebugMode($payment, $debugMode); - if(!empty($payment)){ - $this->id = get_class($payment); - } - return $this->initLog(); - } + public $log; + public $id; + public $debugMode; - /** - * @param $payment - * @param $debugMode - */ - public function getDebugMode($payment, $debugMode) - { - if (!empty($payment)) { - $debugMode = $payment->debug_mode; - if($debugMode == 'no'){ - $debugMode = false; - }else{ - $debugMode = true; - } - } + /** + * WC_WooMercadoPago_Log constructor. + * + * @param null $payment + * @param bool $debugMode + */ + public function __construct( $payment = null, $debugMode = false ) { + $this->getDebugMode( $payment, $debugMode ); + if ( ! empty( $payment ) ) { + $this->id = get_class( $payment ); + } + return $this->initLog(); + } - if (empty($payment) && empty($debugMode)) { - $debugMode = true; - } + /** + * @param $payment + * @param $debugMode + */ + public function getDebugMode( $payment, $debugMode ) { + if ( ! empty( $payment ) ) { + $debugMode = $payment->debug_mode; + if ( $debugMode == 'no' ) { + $debugMode = false; + } else { + $debugMode = true; + } + } - $this->debugMode = $debugMode; - } + if ( empty( $payment ) && empty( $debugMode ) ) { + $debugMode = true; + } - /** - * @return WC_Logger|null - */ - public function initLog() - { - if (!empty($this->debugMode)) { - if (class_exists('WC_Logger')) { - $this->log = new WC_Logger(); - } else { - $this->log = WC_WooMercadoPago_Module::woocommerce_instance()->logger(); - } - return $this->log; - } - return null; - } + $this->debugMode = $debugMode; + } - /** - * @param null $id - * @return WC_WooMercadoPago_Log|null - */ - public static function init_mercado_pago_log($id = null) - { - $log = new self(null, true); - if (!empty($log) && !empty($id)) { - $log->setId($id); - } - return $log; - } + /** + * @return WC_Logger|null + */ + public function initLog() { + if ( ! empty( $this->debugMode ) ) { + if ( class_exists( 'WC_Logger' ) ) { + $this->log = new WC_Logger(); + } else { + $this->log = WC_WooMercadoPago_Module::woocommerce_instance()->logger(); + } + return $this->log; + } + return null; + } - /** - * @param $function - * @param $message - */ - public function write_log($function, $message) - { - if (!empty ($this->debugMode)) { - $this->log->add($this->id, '[' . $function . ']: ' . $message); - } - } + /** + * @param null $id + * @return WC_WooMercadoPago_Log|null + */ + public static function init_mercado_pago_log( $id = null ) { + $log = new self( null, true ); + if ( ! empty( $log ) && ! empty( $id ) ) { + $log->setId( $id ); + } + return $log; + } - /** - * @param mixed $id - */ - public function setId($id) - { - $this->id = $id; - } -} \ No newline at end of file + /** + * @param $function + * @param $message + */ + public function write_log( $function, $message ) { + if ( ! empty( $this->debugMode ) ) { + $this->log->add( $this->id, '[' . $function . ']: ' . $message ); + } + } + + /** + * @param mixed $id + */ + public function setId( $id ) { + $this->id = $id; + } +} diff --git a/includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php b/includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php index 372c63da8..24967ed0f 100755 --- a/includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php +++ b/includes/module/preference/WC_WooMercadoPago_PreferenceAbstract.php @@ -8,439 +8,434 @@ * License - https://www.gnu.org/licenses/gpl.html GPL version 2 or higher */ -if (!defined('ABSPATH')) { - exit; +if ( ! defined( 'ABSPATH' ) ) { + exit; } -abstract class WC_WooMercadoPago_PreferenceAbstract extends WC_Payment_Gateway -{ - protected $order; - protected $payment; - protected $log; - protected $checkout; - protected $gateway_discount; - protected $commission; - protected $currency_ratio; - protected $items; - protected $order_total; - protected $list_of_items; - protected $preference; - protected $selected_shipping; - protected $ship_cost; - protected $site_id; - protected $site_data; - protected $test_user_v1; - protected $sandbox; - protected $notification_class; - protected $ex_payments; - protected $installments; - - /** - * WC_WooMercadoPago_PreferenceAbstract constructor. - * @param $payment - * @param $order - * @param null $requestCheckout - */ - public function __construct($payment, $order, $requestCheckout = null) - { - $this->payment = $payment; - $this->log = $payment->log; - $this->order = $order; - $this->gateway_discount = $this->payment->gateway_discount; - $this->commission = $this->payment->commission; - $this->ex_payments = $this->payment->ex_payments; - $this->installments = $this->payment->installments; - $this->notification_class = get_class($this->payment); - $this->sandbox = $this->payment->isTestUser(); - $this->test_user_v1 = get_option('_test_user_v1', ''); - $this->site_id = get_option('_site_id_v1', ''); - $this->site_data = WC_WooMercadoPago_Module::$country_configs; - $this->order = $order; - $this->checkout = $requestCheckout; - - try { - $this->currency_ratio = $this->get_currency_conversion(); - } catch (Exception $e) { - $this->log->write_log(__FUNCTION__, 'Currency conversion rate failed: payment creation failed with exception: ' . $e->getMessage()); - throw new Exception(__('This payment method cannot process your payment.', 'woocommerce-mercadopago')); - } - - $this->items = array(); - $this->order_total = 0; - $this->list_of_items = array(); - $this->selected_shipping = $order->get_shipping_method(); - $this->ship_cost = $this->order->get_total_shipping() + $this->order->get_shipping_tax(); - - if (sizeof($this->order->get_items()) > 0) { - $this->items = $this->get_items_build_array(); - } - - //shipping is added to items - $this->items = array_merge($this->items, $this->prepare_shipping()); - - //fees is added to items - if (0 < count($this->order->get_fees())) { - $this->items = array_merge($this->items, $this->fees_cost_item()); - } - } - - /** - * @return float - */ - protected function number_format_value($value) - { - return (float) number_format($value, 2, '.', ''); - } - - protected function prepare_shipping() - { - $result = []; - - if ($this->ship_cost > 0) { - $shipCost = $this->ship_cost_item(); - $result[] = $shipCost; - } - - return $result; - } - - /** - * @return array - */ - public function make_commum_preference() - { - $preference = array( - 'binary_mode' => $this->get_binary_mode($this->payment), - 'external_reference' => $this->get_external_reference($this->payment), - 'notification_url' => $this->get_notification_url(), - 'statement_descriptor' => $this->payment->getOption('mp_statement_descriptor', 'Mercado Pago'), - ); - - if (!$this->test_user_v1 && !$this->sandbox) { - $preference['sponsor_id'] = $this->get_sponsor_id(); - } - - return $preference; - } - - /** - * @return int - */ - public function get_currency_conversion() - { - return WC_WooMercadoPago_Helpers_CurrencyConverter::getInstance()->ratio($this->payment); - } - - /** - * @return mixed - */ - public function get_email() - { - if (method_exists($this->order, 'get_id')) { - return $this->order->get_billing_email(); - } else { - return $this->order->billing_email; - } - } - - /** - * @return array - */ - public function get_payer_custom() - { - $payer_additional_info = array( - 'first_name' => (method_exists($this->order, 'get_id') ? html_entity_decode($this->order->get_billing_first_name()) : html_entity_decode($this->order->billing_first_name)), - 'last_name' => (method_exists($this->order, 'get_id') ? html_entity_decode($this->order->get_billing_last_name()) : html_entity_decode($this->order->billing_last_name)), - //'registration_date' => - 'phone' => array( - //'area_code' => - 'number' => (method_exists($this->order, 'get_id') ? $this->order->get_billing_phone() : $this->order->billing_phone) - ), - 'address' => array( - 'zip_code' => (method_exists($this->order, 'get_id') ? $this->order->get_billing_postcode() : $this->order->billing_postcode), - //'street_number' => - 'street_name' => html_entity_decode( - method_exists($this->order, 'get_id') ? - $this->order->get_billing_address_1() . ' / ' . - $this->order->get_billing_city() . ' ' . - $this->order->get_billing_state() . ' ' . - $this->order->get_billing_country() : $this->order->billing_address_1 . ' / ' . - $this->order->billing_city . ' ' . - $this->order->billing_state . ' ' . - $this->order->billing_country - ) - ) - ); - return $payer_additional_info; - } - - /** - * @return array - */ - public function get_items_build_array() - { - $items = array(); - foreach ($this->order->get_items() as $item) { - if ($item['qty']) { - $product = wc_get_product($item['product_id']); - $product_title = method_exists($product, 'get_description') ? $product->get_name() : $product->post->post_title; - $product_content = method_exists($product, 'get_description') ? $product->get_description() : $product->post->post_content; - // Calculates line amount and discounts. - $line_amount = $item['line_total'] + $item['line_tax']; - $discount_by_gateway = (float) $line_amount * ($this->gateway_discount / 100); - $commission_by_gateway = (float) $line_amount * ($this->commission / 100); - $item_amount = $this->calculate_price($line_amount - $discount_by_gateway + $commission_by_gateway); - $this->order_total += $this->number_format_value($item_amount); - - // Add the item. - array_push($this->list_of_items, $product_title . ' x ' . $item['qty']); - array_push($items, array( - 'id' => $item['product_id'], - 'title' => html_entity_decode($product_title) . ' x ' . $item['qty'], - 'description' => sanitize_file_name(html_entity_decode( - strlen($product_content) > 230 ? - substr($product_content, 0, 230) . '...' : $product_content - )), - 'picture_url' => sizeof($this->order->get_items()) > 1 ? - plugins_url('../../assets/images/cart.png', plugin_dir_path(__FILE__)) : wp_get_attachment_url($product->get_image_id()), - 'category_id' => get_option('_mp_category_id', 'others'), - 'quantity' => 1, - 'unit_price' => $this->number_format_value($item_amount), - 'currency_id' => $this->site_data[$this->site_id]['currency'] - )); - } - } - return $items; - } - - /** - * @return array - */ - public function ship_cost_item() - { - $ship_cost = $this->calculate_price($this->ship_cost); - $this->order_total += $this->number_format_value($ship_cost); - - return array( - 'title' => method_exists($this->order, 'get_id') ? $this->order->get_shipping_method() : $this->order->shipping_method, - 'description' => __('Shipping service used by the store.', 'woocommerce-mercadopago'), - 'category_id' => get_option('_mp_category_id', 'others'), - 'quantity' => 1, - 'unit_price' => $this->number_format_value($ship_cost), - ); - } - - /** - * @return array - */ - public function fees_cost_item() - { - $items = array(); - foreach ($this->order->get_fees() as $fee) { - if ((float) $fee['total'] >= 0) { - continue; - } - - $final = ($fee['total'] + $fee['total_tax']) * $this->currency_ratio; - - $this->order_total += $this->number_format_value($final); - array_push($items, array( - 'title' => sanitize_file_name(html_entity_decode( - strlen($fee['name']) > 230 ? - substr($fee['name'], 0, 230) . '...' : $fee['name'] - )), - 'description' => sanitize_file_name(html_entity_decode( - strlen($fee['name']) > 230 ? - substr($fee['name'], 0, 230) . '...' : $fee['name'] - )), - 'category_id' => get_option('_mp_category_id', 'others'), - 'quantity' => 1, - 'unit_price' => $this->number_format_value($final) - )); - } - return $items; - } - - /** - * @return array - */ - public function shipments_receiver_address() - { - $shipments = array( - 'receiver_address' => array( - 'zip_code' => method_exists($this->order, 'get_id') ? - $this->order->get_shipping_postcode() : $this->order->shipping_postcode, - //'street_number' => - 'street_name' => html_entity_decode( - method_exists($this->order, 'get_id') ? - $this->order->get_shipping_address_1() . ' ' . - $this->order->get_shipping_address_2() . ' ' . - $this->order->get_shipping_city() . ' ' . - $this->order->get_shipping_state() . ' ' . - $this->order->get_shipping_country() : $this->order->shipping_address_1 . ' ' . - $this->order->shipping_address_2 . ' ' . - $this->order->shipping_city . ' ' . - $this->order->shipping_state . ' ' . - $this->order->shipping_country - ), - //'floor' => - 'apartment' => method_exists($this->order, 'get_id') ? - $this->order->get_shipping_address_2() : $this->order->shipping_address_2 - ) - ); - return $shipments; - } - - /** - * @return mixed - */ - public function get_notification_url() - { - if (!strrpos(get_site_url(), 'localhost')) { - $notification_url = $this->payment->custom_domain; - // Check if we have a custom URL. - if (empty($notification_url) || filter_var($notification_url, FILTER_VALIDATE_URL) === FALSE) { - return WC()->api_request_url($this->notification_class); - } else { - return WC_WooMercadoPago_Module::fix_url_ampersand(esc_url( - $notification_url . '/wc-api/' . $this->notification_class . '/' - )); - } - } - } - - /** - * get binary_mode - * @param class $payment - * @return bool - */ - public function get_binary_mode($payment = null) - { - $binary_mode = !is_null($payment) ? $payment->getOption('binary_mode', 'no') : 'no'; - - if ($binary_mode != 'no') { - return true; - } - - return false; - } - - /** - * Get Sponsor Id - */ - public function get_sponsor_id() - { - return WC_WooMercadoPago_Module::get_sponsor_id(); - } - - /** - * @return string - */ - public function get_external_reference($payment = null) - { - $store_identificator = get_option('_mp_store_identificator', 'WC-'); - - if (method_exists($this->order, 'get_id')) { - return $store_identificator . $this->order->get_id(); - } else { - return $store_identificator . $this->order->id; - } - } - - /** - * @return array - */ - public function get_preference() - { - $this->log->write_log('Created preference: ', 'Preference: ' . json_encode($this->preference, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - return $this->preference; - } - - /** - * @return float|int - */ - public function get_transaction_amount() - { - return $this->number_format_value($this->order_total); - } - - /** - * @return array - */ - public function add_discounts() - { - $item = array( - 'title' => __('Discount provided by store', 'woocommerce-mercadopago'), - 'description' => __('Discount provided by store', 'woocommerce-mercadopago'), - 'quantity' => 1, - 'category_id' => get_option('_mp_category_name', 'others'), - 'unit_price' => ($this->site_data[$this->site_id]['currency'] == 'COP' || $this->site_data[$this->site_id]['currency'] == 'CLP') ? - -floor($this->checkout['discount'] * $this->currency_ratio) : -floor($this->checkout['discount'] * $this->currency_ratio * 100) / 100 - ); - return $item; - } - - /** - * Discount Campaign - * - * @return array - */ - public function add_discounts_campaign() - { - return array( - 'campaign_id' => (int) $this->checkout['campaign_id'], - 'coupon_amount' => ($this->site_data[$this->site_id]['currency'] == 'COP' || $this->site_data[$this->site_id]['currency'] == 'CLP') ? - floor($this->checkout['discount'] * $this->currency_ratio) : floor($this->checkout['discount'] * $this->currency_ratio * 100) / 100, - 'coupon_code' => strtoupper($this->checkout['coupon_code']) - ); - } - - /** - * @return array - */ - public function get_internal_metadata() - { - $accessToken = get_option('_mp_access_token_prod', ''); - $test_mode = false; - - if ($this->payment->getOption('checkout_credential_prod', '') == 'no') { - $test_mode = true; - $accessToken = get_option('_mp_access_token_test', ''); - } - - if (empty($accessToken)) { - return []; - } - - $analytics = new WC_WooMercadoPago_PreferenceAnalytics(); - - $seller = get_option('_collector_id_v1', ''); - $w = WC_WooMercadoPago_Module::woocommerce_instance(); - $internal_metadata = array( - "platform" => WC_WooMercadoPago_Constants::PLATAFORM_ID, - "platform_version" => $w->version, - "module_version" => WC_WooMercadoPago_Constants::VERSION, - "site_id" => get_option('_site_id_v1'), - "sponsor_id" => $this->get_sponsor_id(), - "collector" => $seller, - "test_mode" => $test_mode, - "details" => "", - "basic_settings" => json_encode($analytics->getBasicSettings(), true), - "custom_settings" => json_encode($analytics->getCustomSettings(), true), - "ticket_settings" => json_encode($analytics->getTicketSettings(), true) - ); - - return $internal_metadata; - } - - /** - * @param $amount - * @return float - */ - private function calculate_price($amount) - { - if ($this->site_data[$this->site_id]['currency'] == 'COP' || $this->site_data[$this->site_id]['currency'] == 'CLP') { - return floor($amount * $this->currency_ratio); - } - return floor($amount * $this->currency_ratio * 100) / 100; - } +abstract class WC_WooMercadoPago_PreferenceAbstract extends WC_Payment_Gateway { + + protected $order; + protected $payment; + protected $log; + protected $checkout; + protected $gateway_discount; + protected $commission; + protected $currency_ratio; + protected $items; + protected $order_total; + protected $list_of_items; + protected $preference; + protected $selected_shipping; + protected $ship_cost; + protected $site_id; + protected $site_data; + protected $test_user_v1; + protected $sandbox; + protected $notification_class; + protected $ex_payments; + protected $installments; + + /** + * WC_WooMercadoPago_PreferenceAbstract constructor. + * + * @param $payment + * @param $order + * @param null $requestCheckout + */ + public function __construct( $payment, $order, $requestCheckout = null ) { + $this->payment = $payment; + $this->log = $payment->log; + $this->order = $order; + $this->gateway_discount = $this->payment->gateway_discount; + $this->commission = $this->payment->commission; + $this->ex_payments = $this->payment->ex_payments; + $this->installments = $this->payment->installments; + $this->notification_class = get_class( $this->payment ); + $this->sandbox = $this->payment->isTestUser(); + $this->test_user_v1 = get_option( '_test_user_v1', '' ); + $this->site_id = get_option( '_site_id_v1', '' ); + $this->site_data = WC_WooMercadoPago_Module::$country_configs; + $this->order = $order; + $this->checkout = $requestCheckout; + + try { + $this->currency_ratio = $this->get_currency_conversion(); + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, 'Currency conversion rate failed: payment creation failed with exception: ' . $e->getMessage() ); + throw new Exception( __( 'This payment method cannot process your payment.', 'woocommerce-mercadopago' ) ); + } + + $this->items = array(); + $this->order_total = 0; + $this->list_of_items = array(); + $this->selected_shipping = $order->get_shipping_method(); + $this->ship_cost = $this->order->get_total_shipping() + $this->order->get_shipping_tax(); + + if ( sizeof( $this->order->get_items() ) > 0 ) { + $this->items = $this->get_items_build_array(); + } + + // shipping is added to items + $this->items = array_merge( $this->items, $this->prepare_shipping() ); + + // fees is added to items + if ( 0 < count( $this->order->get_fees() ) ) { + $this->items = array_merge( $this->items, $this->fees_cost_item() ); + } + } + + /** + * @return float + */ + protected function number_format_value( $value ) { + return (float) number_format( $value, 2, '.', '' ); + } + + protected function prepare_shipping() { + $result = array(); + + if ( $this->ship_cost > 0 ) { + $shipCost = $this->ship_cost_item(); + $result[] = $shipCost; + } + + return $result; + } + + /** + * @return array + */ + public function make_commum_preference() { + $preference = array( + 'binary_mode' => $this->get_binary_mode( $this->payment ), + 'external_reference' => $this->get_external_reference( $this->payment ), + 'notification_url' => $this->get_notification_url(), + 'statement_descriptor' => $this->payment->getOption( 'mp_statement_descriptor', 'Mercado Pago' ), + ); + + if ( ! $this->test_user_v1 && ! $this->sandbox ) { + $preference['sponsor_id'] = $this->get_sponsor_id(); + } + + return $preference; + } + + /** + * @return int + */ + public function get_currency_conversion() { + return WC_WooMercadoPago_Helpers_CurrencyConverter::getInstance()->ratio( $this->payment ); + } + + /** + * @return mixed + */ + public function get_email() { + if ( method_exists( $this->order, 'get_id' ) ) { + return $this->order->get_billing_email(); + } else { + return $this->order->billing_email; + } + } + + /** + * @return array + */ + public function get_payer_custom() { + $payer_additional_info = array( + 'first_name' => ( method_exists( $this->order, 'get_id' ) ? html_entity_decode( $this->order->get_billing_first_name() ) : html_entity_decode( $this->order->billing_first_name ) ), + 'last_name' => ( method_exists( $this->order, 'get_id' ) ? html_entity_decode( $this->order->get_billing_last_name() ) : html_entity_decode( $this->order->billing_last_name ) ), + // 'registration_date' => + 'phone' => array( + // 'area_code' => + 'number' => ( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_phone() : $this->order->billing_phone ), + ), + 'address' => array( + 'zip_code' => ( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_postcode() : $this->order->billing_postcode ), + // 'street_number' => + 'street_name' => html_entity_decode( + method_exists( $this->order, 'get_id' ) ? + $this->order->get_billing_address_1() . ' / ' . + $this->order->get_billing_city() . ' ' . + $this->order->get_billing_state() . ' ' . + $this->order->get_billing_country() : $this->order->billing_address_1 . ' / ' . + $this->order->billing_city . ' ' . + $this->order->billing_state . ' ' . + $this->order->billing_country + ), + ), + ); + return $payer_additional_info; + } + + /** + * @return array + */ + public function get_items_build_array() { + $items = array(); + foreach ( $this->order->get_items() as $item ) { + if ( $item['qty'] ) { + $product = wc_get_product( $item['product_id'] ); + $product_title = method_exists( $product, 'get_description' ) ? $product->get_name() : $product->post->post_title; + $product_content = method_exists( $product, 'get_description' ) ? $product->get_description() : $product->post->post_content; + // Calculates line amount and discounts. + $line_amount = $item['line_total'] + $item['line_tax']; + $discount_by_gateway = (float) $line_amount * ( $this->gateway_discount / 100 ); + $commission_by_gateway = (float) $line_amount * ( $this->commission / 100 ); + $item_amount = $this->calculate_price( $line_amount - $discount_by_gateway + $commission_by_gateway ); + $this->order_total += $this->number_format_value( $item_amount ); + + // Add the item. + array_push( $this->list_of_items, $product_title . ' x ' . $item['qty'] ); + array_push( + $items, + array( + 'id' => $item['product_id'], + 'title' => html_entity_decode( $product_title ) . ' x ' . $item['qty'], + 'description' => sanitize_file_name( + html_entity_decode( + strlen( $product_content ) > 230 ? + substr( $product_content, 0, 230 ) . '...' : $product_content + ) + ), + 'picture_url' => sizeof( $this->order->get_items() ) > 1 ? + plugins_url( '../../assets/images/cart.png', plugin_dir_path( __FILE__ ) ) : wp_get_attachment_url( $product->get_image_id() ), + 'category_id' => get_option( '_mp_category_id', 'others' ), + 'quantity' => 1, + 'unit_price' => $this->number_format_value( $item_amount ), + 'currency_id' => $this->site_data[ $this->site_id ]['currency'], + ) + ); + } + } + return $items; + } + + /** + * @return array + */ + public function ship_cost_item() { + $ship_cost = $this->calculate_price( $this->ship_cost ); + $this->order_total += $this->number_format_value( $ship_cost ); + + return array( + 'title' => method_exists( $this->order, 'get_id' ) ? $this->order->get_shipping_method() : $this->order->shipping_method, + 'description' => __( 'Shipping service used by the store.', 'woocommerce-mercadopago' ), + 'category_id' => get_option( '_mp_category_id', 'others' ), + 'quantity' => 1, + 'unit_price' => $this->number_format_value( $ship_cost ), + ); + } + + /** + * @return array + */ + public function fees_cost_item() { + $items = array(); + foreach ( $this->order->get_fees() as $fee ) { + if ( (float) $fee['total'] >= 0 ) { + continue; + } + + $final = ( $fee['total'] + $fee['total_tax'] ) * $this->currency_ratio; + + $this->order_total += $this->number_format_value( $final ); + array_push( + $items, + array( + 'title' => sanitize_file_name( + html_entity_decode( + strlen( $fee['name'] ) > 230 ? + substr( $fee['name'], 0, 230 ) . '...' : $fee['name'] + ) + ), + 'description' => sanitize_file_name( + html_entity_decode( + strlen( $fee['name'] ) > 230 ? + substr( $fee['name'], 0, 230 ) . '...' : $fee['name'] + ) + ), + 'category_id' => get_option( '_mp_category_id', 'others' ), + 'quantity' => 1, + 'unit_price' => $this->number_format_value( $final ), + ) + ); + } + return $items; + } + + /** + * @return array + */ + public function shipments_receiver_address() { + $shipments = array( + 'receiver_address' => array( + 'zip_code' => method_exists( $this->order, 'get_id' ) ? + $this->order->get_shipping_postcode() : $this->order->shipping_postcode, + // 'street_number' => + 'street_name' => html_entity_decode( + method_exists( $this->order, 'get_id' ) ? + $this->order->get_shipping_address_1() . ' ' . + $this->order->get_shipping_address_2() . ' ' . + $this->order->get_shipping_city() . ' ' . + $this->order->get_shipping_state() . ' ' . + $this->order->get_shipping_country() : $this->order->shipping_address_1 . ' ' . + $this->order->shipping_address_2 . ' ' . + $this->order->shipping_city . ' ' . + $this->order->shipping_state . ' ' . + $this->order->shipping_country + ), + // 'floor' => + 'apartment' => method_exists( $this->order, 'get_id' ) ? + $this->order->get_shipping_address_2() : $this->order->shipping_address_2, + ), + ); + return $shipments; + } + + /** + * @return mixed + */ + public function get_notification_url() { + if ( ! strrpos( get_site_url(), 'localhost' ) ) { + $notification_url = $this->payment->custom_domain; + // Check if we have a custom URL. + if ( empty( $notification_url ) || filter_var( $notification_url, FILTER_VALIDATE_URL ) === false ) { + return WC()->api_request_url( $this->notification_class ); + } else { + return WC_WooMercadoPago_Module::fix_url_ampersand( + esc_url( + $notification_url . '/wc-api/' . $this->notification_class . '/' + ) + ); + } + } + } + + /** + * get binary_mode + * + * @param class $payment + * @return bool + */ + public function get_binary_mode( $payment = null ) { + $binary_mode = ! is_null( $payment ) ? $payment->getOption( 'binary_mode', 'no' ) : 'no'; + + if ( $binary_mode != 'no' ) { + return true; + } + + return false; + } + + /** + * Get Sponsor Id + */ + public function get_sponsor_id() { + return WC_WooMercadoPago_Module::get_sponsor_id(); + } + + /** + * @return string + */ + public function get_external_reference( $payment = null ) { + $store_identificator = get_option( '_mp_store_identificator', 'WC-' ); + + if ( method_exists( $this->order, 'get_id' ) ) { + return $store_identificator . $this->order->get_id(); + } else { + return $store_identificator . $this->order->id; + } + } + + /** + * @return array + */ + public function get_preference() { + $this->log->write_log( 'Created preference: ', 'Preference: ' . json_encode( $this->preference, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + return $this->preference; + } + + /** + * @return float|int + */ + public function get_transaction_amount() { + return $this->number_format_value( $this->order_total ); + } + + /** + * @return array + */ + public function add_discounts() { + $item = array( + 'title' => __( 'Discount provided by store', 'woocommerce-mercadopago' ), + 'description' => __( 'Discount provided by store', 'woocommerce-mercadopago' ), + 'quantity' => 1, + 'category_id' => get_option( '_mp_category_name', 'others' ), + 'unit_price' => ( $this->site_data[ $this->site_id ]['currency'] == 'COP' || $this->site_data[ $this->site_id ]['currency'] == 'CLP' ) ? + -floor( $this->checkout['discount'] * $this->currency_ratio ) : -floor( $this->checkout['discount'] * $this->currency_ratio * 100 ) / 100, + ); + return $item; + } + + /** + * Discount Campaign + * + * @return array + */ + public function add_discounts_campaign() { + return array( + 'campaign_id' => (int) $this->checkout['campaign_id'], + 'coupon_amount' => ( $this->site_data[ $this->site_id ]['currency'] == 'COP' || $this->site_data[ $this->site_id ]['currency'] == 'CLP' ) ? + floor( $this->checkout['discount'] * $this->currency_ratio ) : floor( $this->checkout['discount'] * $this->currency_ratio * 100 ) / 100, + 'coupon_code' => strtoupper( $this->checkout['coupon_code'] ), + ); + } + + /** + * @return array + */ + public function get_internal_metadata() { + $accessToken = get_option( '_mp_access_token_prod', '' ); + $test_mode = false; + + if ( $this->payment->getOption( 'checkout_credential_prod', '' ) == 'no' ) { + $test_mode = true; + $accessToken = get_option( '_mp_access_token_test', '' ); + } + + if ( empty( $accessToken ) ) { + return array(); + } + + $analytics = new WC_WooMercadoPago_PreferenceAnalytics(); + + $seller = get_option( '_collector_id_v1', '' ); + $w = WC_WooMercadoPago_Module::woocommerce_instance(); + $internal_metadata = array( + 'platform' => WC_WooMercadoPago_Constants::PLATAFORM_ID, + 'platform_version' => $w->version, + 'module_version' => WC_WooMercadoPago_Constants::VERSION, + 'site_id' => get_option( '_site_id_v1' ), + 'sponsor_id' => $this->get_sponsor_id(), + 'collector' => $seller, + 'test_mode' => $test_mode, + 'details' => '', + 'basic_settings' => json_encode( $analytics->getBasicSettings(), true ), + 'custom_settings' => json_encode( $analytics->getCustomSettings(), true ), + 'ticket_settings' => json_encode( $analytics->getTicketSettings(), true ), + ); + + return $internal_metadata; + } + + /** + * @param $amount + * @return float + */ + private function calculate_price( $amount ) { + if ( $this->site_data[ $this->site_id ]['currency'] == 'COP' || $this->site_data[ $this->site_id ]['currency'] == 'CLP' ) { + return floor( $amount * $this->currency_ratio ); + } + return floor( $amount * $this->currency_ratio * 100 ) / 100; + } } diff --git a/includes/module/preference/WC_WooMercadoPago_PreferenceBasic.php b/includes/module/preference/WC_WooMercadoPago_PreferenceBasic.php index c8afb6953..ad80f1bee 100644 --- a/includes/module/preference/WC_WooMercadoPago_PreferenceBasic.php +++ b/includes/module/preference/WC_WooMercadoPago_PreferenceBasic.php @@ -12,130 +12,128 @@ exit; } -class WC_WooMercadoPago_PreferenceBasic extends WC_WooMercadoPago_PreferenceAbstract -{ - /** - * WC_WooMercadoPago_PreferenceBasic constructor. - * @param $payment - * @param $order - */ - public function __construct($payment, $order) - { - parent::__construct($payment, $order); - $this->preference = $this->make_commum_preference(); - $this->preference['items'] = $this->items; - $this->preference['payer'] = $this->get_payer_basic(); - $this->preference['back_urls'] = $this->get_back_urls(); - $this->preference['shipments'] = $this->shipments_receiver_address(); +class WC_WooMercadoPago_PreferenceBasic extends WC_WooMercadoPago_PreferenceAbstract { - $this->preference['payment_methods'] = $this->get_payment_methods($this->ex_payments, $this->installments); - $this->preference['auto_return'] = $this->auto_return(); + /** + * WC_WooMercadoPago_PreferenceBasic constructor. + * + * @param $payment + * @param $order + */ + public function __construct( $payment, $order ) { + parent::__construct( $payment, $order ); + $this->preference = $this->make_commum_preference(); + $this->preference['items'] = $this->items; + $this->preference['payer'] = $this->get_payer_basic(); + $this->preference['back_urls'] = $this->get_back_urls(); + $this->preference['shipments'] = $this->shipments_receiver_address(); - $internal_metadata = parent::get_internal_metadata(); - $merge_array = array_merge($internal_metadata, $this->get_internal_metadata_basic()); - $this->preference['metadata'] = $merge_array; - } + $this->preference['payment_methods'] = $this->get_payment_methods( $this->ex_payments, $this->installments ); + $this->preference['auto_return'] = $this->auto_return(); - /** - * @return array - */ - public function get_payer_basic() - { - $payer_additional_info = array( - 'name' => (method_exists($this->order, 'get_id') ? html_entity_decode($this->order->get_billing_first_name()) : html_entity_decode($this->order->billing_first_name)), - 'surname' => (method_exists($this->order, 'get_id') ? html_entity_decode($this->order->get_billing_last_name()) : html_entity_decode($this->order->billing_last_name)), - 'email' => $this->order->get_billing_email(), - 'phone' => array( - //'area_code' => - 'number' => (method_exists($this->order, 'get_id') ? $this->order->get_billing_phone() : $this->order->billing_phone), - ), - 'address' => array( - 'zip_code' => (method_exists($this->order, 'get_id') ? $this->order->get_billing_postcode() : $this->order->billing_postcode), - //'street_number' => - 'street_name' => html_entity_decode( - method_exists($this->order, 'get_id') ? - $this->order->get_billing_address_1() . ' / ' . - $this->order->get_billing_city() . ' ' . - $this->order->get_billing_state() . ' ' . - $this->order->get_billing_country() : $this->order->billing_address_1 . ' / ' . - $this->order->billing_city . ' ' . - $this->order->billing_state . ' ' . - $this->order->billing_country - ) - ) - ); - return $payer_additional_info; - } + $internal_metadata = parent::get_internal_metadata(); + $merge_array = array_merge( $internal_metadata, $this->get_internal_metadata_basic() ); + $this->preference['metadata'] = $merge_array; + } - /** - * @return array - */ - public function get_back_urls() - { - $success_url = $this->payment->getOption('success_url', ''); - $failure_url = $this->payment->getOption('failure_url', ''); - $pending_url = $this->payment->getOption('pending_url', ''); - $back_urls = array( - 'success' => empty($success_url) ? - WC_WooMercadoPago_Module::fix_url_ampersand( - esc_url($this->get_return_url($this->order)) - ) : $success_url, - 'failure' => empty($failure_url) ? - WC_WooMercadoPago_Module::fix_url_ampersand( - esc_url($this->order->get_cancel_order_url()) - ) : $failure_url, - 'pending' => empty($pending_url) ? - WC_WooMercadoPago_Module::fix_url_ampersand( - esc_url($this->get_return_url($this->order)) - ) : $pending_url - ); - return $back_urls; - } + /** + * @return array + */ + public function get_payer_basic() { + $payer_additional_info = array( + 'name' => ( method_exists( $this->order, 'get_id' ) ? html_entity_decode( $this->order->get_billing_first_name() ) : html_entity_decode( $this->order->billing_first_name ) ), + 'surname' => ( method_exists( $this->order, 'get_id' ) ? html_entity_decode( $this->order->get_billing_last_name() ) : html_entity_decode( $this->order->billing_last_name ) ), + 'email' => $this->order->get_billing_email(), + 'phone' => array( + // 'area_code' => + 'number' => ( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_phone() : $this->order->billing_phone ), + ), + 'address' => array( + 'zip_code' => ( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_postcode() : $this->order->billing_postcode ), + // 'street_number' => + 'street_name' => html_entity_decode( + method_exists( $this->order, 'get_id' ) ? + $this->order->get_billing_address_1() . ' / ' . + $this->order->get_billing_city() . ' ' . + $this->order->get_billing_state() . ' ' . + $this->order->get_billing_country() : $this->order->billing_address_1 . ' / ' . + $this->order->billing_city . ' ' . + $this->order->billing_state . ' ' . + $this->order->billing_country + ), + ), + ); + return $payer_additional_info; + } - /** - * @param $ex_payments - * @param $installments - * @return array - */ - public function get_payment_methods($ex_payments, $installments) - { - $excluded_payment_methods = array(); - if (is_array($ex_payments) && count($ex_payments) != 0) { - foreach ($ex_payments as $excluded) { - array_push($excluded_payment_methods, array( - 'id' => $excluded - )); - } - } - $payment_methods = array( - 'installments' => (int)$installments, - 'excluded_payment_methods' => $excluded_payment_methods - ); - return $payment_methods; - } + /** + * @return array + */ + public function get_back_urls() { + $success_url = $this->payment->getOption( 'success_url', '' ); + $failure_url = $this->payment->getOption( 'failure_url', '' ); + $pending_url = $this->payment->getOption( 'pending_url', '' ); + $back_urls = array( + 'success' => empty( $success_url ) ? + WC_WooMercadoPago_Module::fix_url_ampersand( + esc_url( $this->get_return_url( $this->order ) ) + ) : $success_url, + 'failure' => empty( $failure_url ) ? + WC_WooMercadoPago_Module::fix_url_ampersand( + esc_url( $this->order->get_cancel_order_url() ) + ) : $failure_url, + 'pending' => empty( $pending_url ) ? + WC_WooMercadoPago_Module::fix_url_ampersand( + esc_url( $this->get_return_url( $this->order ) ) + ) : $pending_url, + ); + return $back_urls; + } - /** - * @return string|void - */ - public function auto_return() - { - $auto_return = get_option('auto_return', 'yes'); - if ('yes' == $auto_return) { - return 'approved'; - } - return; - } + /** + * @param $ex_payments + * @param $installments + * @return array + */ + public function get_payment_methods( $ex_payments, $installments ) { + $excluded_payment_methods = array(); + if ( is_array( $ex_payments ) && count( $ex_payments ) != 0 ) { + foreach ( $ex_payments as $excluded ) { + array_push( + $excluded_payment_methods, + array( + 'id' => $excluded, + ) + ); + } + } + $payment_methods = array( + 'installments' => (int) $installments, + 'excluded_payment_methods' => $excluded_payment_methods, + ); + return $payment_methods; + } - /** - * @return array - */ - public function get_internal_metadata_basic() - { - $internal_metadata = array( - "checkout" => "smart", - "checkout_type" => $this->payment->getOption('method', 'redirect'), - ); + /** + * @return string|void + */ + public function auto_return() { + $auto_return = get_option( 'auto_return', 'yes' ); + if ( 'yes' == $auto_return ) { + return 'approved'; + } + return; + } - return $internal_metadata; - } + /** + * @return array + */ + public function get_internal_metadata_basic() { + $internal_metadata = array( + 'checkout' => 'smart', + 'checkout_type' => $this->payment->getOption( 'method', 'redirect' ), + ); + + return $internal_metadata; + } } diff --git a/includes/module/preference/WC_WooMercadoPago_PreferenceCustom.php b/includes/module/preference/WC_WooMercadoPago_PreferenceCustom.php index e211d81b9..69fed9cad 100755 --- a/includes/module/preference/WC_WooMercadoPago_PreferenceCustom.php +++ b/includes/module/preference/WC_WooMercadoPago_PreferenceCustom.php @@ -11,90 +11,87 @@ if ( ! defined( 'ABSPATH' ) ) { exit; } -class WC_WooMercadoPago_PreferenceCustom extends WC_WooMercadoPago_PreferenceAbstract -{ - /** - * WC_WooMercadoPago_PreferenceCustom constructor. - * @param $payment - * @param $order - * @param $custom_checkout - */ - public function __construct($payment, $order, $custom_checkout) - { - parent::__construct($payment, $order, $custom_checkout); - $this->preference = $this->make_commum_preference(); - $this->preference['transaction_amount'] = $this->get_transaction_amount(); - $this->preference['token'] = $this->checkout['token']; - $this->preference['description'] = implode(', ', $this->list_of_items); - $this->preference['installments'] = (int)$this->checkout['installments']; - $this->preference['payment_method_id'] = $this->checkout['paymentMethodId']; - $this->preference['payer']['email'] = $this->get_email(); - if (array_key_exists('token', $this->checkout)) { - $this->preference['metadata']['token'] = $this->checkout['token']; - if (!empty($this->checkout['CustomerId'])) { - $this->preference['payer']['id'] = $this->checkout['CustomerId']; - } - if (!empty($this->checkout['issuer'])) { - $this->preference['issuer_id'] = (integer)$this->checkout['issuer']; - } - } +class WC_WooMercadoPago_PreferenceCustom extends WC_WooMercadoPago_PreferenceAbstract { - $this->preference['additional_info']['items'] = $this->items; - $this->preference['additional_info']['payer'] = $this->get_payer_custom(); - $this->preference['additional_info']['shipments'] = $this->shipments_receiver_address(); + /** + * WC_WooMercadoPago_PreferenceCustom constructor. + * + * @param $payment + * @param $order + * @param $custom_checkout + */ + public function __construct( $payment, $order, $custom_checkout ) { + parent::__construct( $payment, $order, $custom_checkout ); + $this->preference = $this->make_commum_preference(); + $this->preference['transaction_amount'] = $this->get_transaction_amount(); + $this->preference['token'] = $this->checkout['token']; + $this->preference['description'] = implode( ', ', $this->list_of_items ); + $this->preference['installments'] = (int) $this->checkout['installments']; + $this->preference['payment_method_id'] = $this->checkout['paymentMethodId']; + $this->preference['payer']['email'] = $this->get_email(); + if ( array_key_exists( 'token', $this->checkout ) ) { + $this->preference['metadata']['token'] = $this->checkout['token']; + if ( ! empty( $this->checkout['CustomerId'] ) ) { + $this->preference['payer']['id'] = $this->checkout['CustomerId']; + } + if ( ! empty( $this->checkout['issuer'] ) ) { + $this->preference['issuer_id'] = (int) $this->checkout['issuer']; + } + } - if ( - isset($this->checkout['discount']) && !empty($this->checkout['discount']) && - isset($this->checkout['coupon_code']) && !empty($this->checkout['coupon_code']) && - $this->checkout['discount'] > 0 && WC()->session->chosen_payment_method == 'woo-mercado-pago-custom' - ) { - $this->preference['additional_info']['items'][] = $this->add_discounts(); - $this->preference = array_merge($this->preference , $this->add_discounts_campaign()); - } + $this->preference['additional_info']['items'] = $this->items; + $this->preference['additional_info']['payer'] = $this->get_payer_custom(); + $this->preference['additional_info']['shipments'] = $this->shipments_receiver_address(); - $internal_metadata = parent::get_internal_metadata(); - $merge_array = array_merge($internal_metadata, $this->get_internal_metadata_custom()); - $this->preference['metadata'] = $merge_array; + if ( + isset( $this->checkout['discount'] ) && ! empty( $this->checkout['discount'] ) && + isset( $this->checkout['coupon_code'] ) && ! empty( $this->checkout['coupon_code'] ) && + $this->checkout['discount'] > 0 && WC()->session->chosen_payment_method == 'woo-mercado-pago-custom' + ) { + $this->preference['additional_info']['items'][] = $this->add_discounts(); + $this->preference = array_merge( $this->preference, $this->add_discounts_campaign() ); + } - } + $internal_metadata = parent::get_internal_metadata(); + $merge_array = array_merge( $internal_metadata, $this->get_internal_metadata_custom() ); + $this->preference['metadata'] = $merge_array; - /** - * @return array - */ - public function ship_cost_item() - { - $item = parent::ship_cost_item(); - if (isset($item['currency_id'])) { - unset($item['currency_id']); - } - return $item; - } + } - /** - * @return array - */ - public function get_items_build_array() - { - $items = parent::get_items_build_array(); - foreach ($items as $key => $item) { - if (isset($item['currency_id'])) { - unset($items[$key]['currency_id']); - } - } + /** + * @return array + */ + public function ship_cost_item() { + $item = parent::ship_cost_item(); + if ( isset( $item['currency_id'] ) ) { + unset( $item['currency_id'] ); + } + return $item; + } - return $items; - } + /** + * @return array + */ + public function get_items_build_array() { + $items = parent::get_items_build_array(); + foreach ( $items as $key => $item ) { + if ( isset( $item['currency_id'] ) ) { + unset( $items[ $key ]['currency_id'] ); + } + } - /** - * @return array - */ - public function get_internal_metadata_custom() - { - $internal_metadata = array( - "checkout" => "custom", - "checkout_type" => "credit_card", - ); + return $items; + } - return $internal_metadata; - } + /** + * @return array + */ + public function get_internal_metadata_custom() { + $internal_metadata = array( + 'checkout' => 'custom', + 'checkout_type' => 'credit_card', + ); + + return $internal_metadata; + } } diff --git a/includes/module/preference/WC_WooMercadoPago_PreferenceTicket.php b/includes/module/preference/WC_WooMercadoPago_PreferenceTicket.php index 207188f86..f1e4952e7 100644 --- a/includes/module/preference/WC_WooMercadoPago_PreferenceTicket.php +++ b/includes/module/preference/WC_WooMercadoPago_PreferenceTicket.php @@ -11,113 +11,111 @@ if ( ! defined( 'ABSPATH' ) ) { exit; } -class WC_WooMercadoPago_PreferenceTicket extends WC_WooMercadoPago_PreferenceAbstract -{ - - /** - * WC_WooMercadoPago_PreferenceTicket constructor. - * @param $payment - * @param $order - * @param $ticket_checkout - */ - public function __construct($payment, $order, $ticket_checkout) - { - parent::__construct($payment, $order, $ticket_checkout); - $this->preference = $this->make_commum_preference(); - $this->preference['date_of_expiration'] = $this->get_date_of_expiration($payment); - $this->preference['transaction_amount'] = $this->get_transaction_amount(); - $this->preference['description'] = implode(', ', $this->list_of_items); - $this->preference['payment_method_id'] = $this->checkout['paymentMethodId']; - $this->preference['payer']['email'] = $this->get_email(); - - if ($this->site_data[$this->site_id]['currency'] == 'BRL') { - $this->preference['payer']['first_name'] = $this->checkout['firstname']; - $this->preference['payer']['last_name'] = strlen($this->checkout['docNumber']) == 14 ? $this->checkout['lastname'] : $this->checkout['firstname']; - $this->preference['payer']['identification']['type'] = strlen($this->checkout['docNumber']) == 14 ? 'CPF' : 'CNPJ'; - $this->preference['payer']['identification']['number'] = $this->checkout['docNumber']; - $this->preference['payer']['address']['street_name'] = $this->checkout['address']; - $this->preference['payer']['address']['street_number'] = $this->checkout['number']; - $this->preference['payer']['address']['neighborhood'] = $this->checkout['city']; - $this->preference['payer']['address']['city'] = $this->checkout['city']; - $this->preference['payer']['address']['federal_unit'] = $this->checkout['state']; - $this->preference['payer']['address']['zip_code'] = $this->checkout['zipcode']; - } - - if ($this->site_data[$this->site_id]['currency'] == 'UYU') { - $this->preference['payer']['identification']['type'] = $ticket_checkout['docType']; - $this->preference['payer']['identification']['number'] = $ticket_checkout['docNumber']; - } - - if($ticket_checkout['paymentMethodId'] == 'webpay'){ - $this->preference['callback_url'] = get_site_url(); - $this->preference['transaction_details']['financial_institution'] = "1234"; - $this->preference['additional_info']['ip_address'] = "127.0.0.1"; - $this->preference['payer']['identification']['type'] = "RUT"; - $this->preference['payer']['identification']['number'] = "0"; - $this->preference['payer']['entity_type'] = "individual"; - } - - $this->preference['external_reference'] = $this->get_external_reference(); - $this->preference['additional_info']['items'] = $this->items; - $this->preference['additional_info']['payer'] = $this->get_payer_custom(); - $this->preference['additional_info']['shipments'] = $this->shipments_receiver_address(); - $this->preference['additional_info']['payer'] = $this->get_payer_custom(); - - if ( - isset($this->checkout['discount']) && !empty($this->checkout['discount']) && - isset($this->checkout['coupon_code']) && !empty($this->checkout['coupon_code']) && - $this->checkout['discount'] > 0 && WC()->session->chosen_payment_method == 'woo-mercado-pago-ticket' - ) { - $this->preference['additional_info']['items'][] = $this->add_discounts(); - $this->preference = array_merge($this->preference , $this->add_discounts_campaign()); - } - - $internal_metadata = parent::get_internal_metadata(); - $merge_array = array_merge($internal_metadata, $this->get_internal_metadata_ticket()); - $this->preference['metadata'] = $merge_array; - } - - /** - * get_date_of_expiration - * @param WC_WooMercadoPago_TicketGateway $payment - * @return string date - */ - public function get_date_of_expiration(WC_WooMercadoPago_TicketGateway $payment = null) - { - $date_expiration = !is_null($payment) - ? $payment->getOption('date_expiration') - : $this->get_option('date_expiration', ''); - - if($date_expiration != ""){ - return date('Y-m-d\TH:i:s.000O', strtotime('+' . $date_expiration . ' days')); - } - } - - /** - * @return array - */ - public function get_items_build_array() - { - $items = parent::get_items_build_array(); - foreach ($items as $key => $item) { - if (isset($item['currency_id'])) { - unset($items[$key]['currency_id']); - } - } - - return $items; - } - - /** - * @return array - */ - public function get_internal_metadata_ticket() - { - $internal_metadata = array( - "checkout" => "custom", - "checkout_type" => "ticket", - ); - - return $internal_metadata; - } +class WC_WooMercadoPago_PreferenceTicket extends WC_WooMercadoPago_PreferenceAbstract { + + + /** + * WC_WooMercadoPago_PreferenceTicket constructor. + * + * @param $payment + * @param $order + * @param $ticket_checkout + */ + public function __construct( $payment, $order, $ticket_checkout ) { + parent::__construct( $payment, $order, $ticket_checkout ); + $this->preference = $this->make_commum_preference(); + $this->preference['date_of_expiration'] = $this->get_date_of_expiration( $payment ); + $this->preference['transaction_amount'] = $this->get_transaction_amount(); + $this->preference['description'] = implode( ', ', $this->list_of_items ); + $this->preference['payment_method_id'] = $this->checkout['paymentMethodId']; + $this->preference['payer']['email'] = $this->get_email(); + + if ( $this->site_data[ $this->site_id ]['currency'] == 'BRL' ) { + $this->preference['payer']['first_name'] = $this->checkout['firstname']; + $this->preference['payer']['last_name'] = strlen( $this->checkout['docNumber'] ) == 14 ? $this->checkout['lastname'] : $this->checkout['firstname']; + $this->preference['payer']['identification']['type'] = strlen( $this->checkout['docNumber'] ) == 14 ? 'CPF' : 'CNPJ'; + $this->preference['payer']['identification']['number'] = $this->checkout['docNumber']; + $this->preference['payer']['address']['street_name'] = $this->checkout['address']; + $this->preference['payer']['address']['street_number'] = $this->checkout['number']; + $this->preference['payer']['address']['neighborhood'] = $this->checkout['city']; + $this->preference['payer']['address']['city'] = $this->checkout['city']; + $this->preference['payer']['address']['federal_unit'] = $this->checkout['state']; + $this->preference['payer']['address']['zip_code'] = $this->checkout['zipcode']; + } + + if ( $this->site_data[ $this->site_id ]['currency'] == 'UYU' ) { + $this->preference['payer']['identification']['type'] = $ticket_checkout['docType']; + $this->preference['payer']['identification']['number'] = $ticket_checkout['docNumber']; + } + + if ( $ticket_checkout['paymentMethodId'] == 'webpay' ) { + $this->preference['callback_url'] = get_site_url(); + $this->preference['transaction_details']['financial_institution'] = '1234'; + $this->preference['additional_info']['ip_address'] = '127.0.0.1'; + $this->preference['payer']['identification']['type'] = 'RUT'; + $this->preference['payer']['identification']['number'] = '0'; + $this->preference['payer']['entity_type'] = 'individual'; + } + + $this->preference['external_reference'] = $this->get_external_reference(); + $this->preference['additional_info']['items'] = $this->items; + $this->preference['additional_info']['payer'] = $this->get_payer_custom(); + $this->preference['additional_info']['shipments'] = $this->shipments_receiver_address(); + $this->preference['additional_info']['payer'] = $this->get_payer_custom(); + + if ( + isset( $this->checkout['discount'] ) && ! empty( $this->checkout['discount'] ) && + isset( $this->checkout['coupon_code'] ) && ! empty( $this->checkout['coupon_code'] ) && + $this->checkout['discount'] > 0 && WC()->session->chosen_payment_method == 'woo-mercado-pago-ticket' + ) { + $this->preference['additional_info']['items'][] = $this->add_discounts(); + $this->preference = array_merge( $this->preference, $this->add_discounts_campaign() ); + } + + $internal_metadata = parent::get_internal_metadata(); + $merge_array = array_merge( $internal_metadata, $this->get_internal_metadata_ticket() ); + $this->preference['metadata'] = $merge_array; + } + + /** + * get_date_of_expiration + * + * @param WC_WooMercadoPago_TicketGateway $payment + * @return string date + */ + public function get_date_of_expiration( WC_WooMercadoPago_TicketGateway $payment = null ) { + $date_expiration = ! is_null( $payment ) + ? $payment->getOption( 'date_expiration' ) + : $this->get_option( 'date_expiration', '' ); + + if ( $date_expiration != '' ) { + return date( 'Y-m-d\TH:i:s.000O', strtotime( '+' . $date_expiration . ' days' ) ); + } + } + + /** + * @return array + */ + public function get_items_build_array() { + $items = parent::get_items_build_array(); + foreach ( $items as $key => $item ) { + if ( isset( $item['currency_id'] ) ) { + unset( $items[ $key ]['currency_id'] ); + } + } + + return $items; + } + + /** + * @return array + */ + public function get_internal_metadata_ticket() { + $internal_metadata = array( + 'checkout' => 'custom', + 'checkout_type' => 'ticket', + ); + + return $internal_metadata; + } } diff --git a/includes/module/preference/analytics/WC_WooMercadoPago_PreferenceAnalytics.php b/includes/module/preference/analytics/WC_WooMercadoPago_PreferenceAnalytics.php index 9fd975cc5..6b8d947e2 100644 --- a/includes/module/preference/analytics/WC_WooMercadoPago_PreferenceAnalytics.php +++ b/includes/module/preference/analytics/WC_WooMercadoPago_PreferenceAnalytics.php @@ -1,32 +1,32 @@ getSettings('woocommerce_woo-mercado-pago-basic_settings'); - } - public function getCustomSettings(){ - return $this->getSettings('woocommerce_woo-mercado-pago-custom_settings'); - } - public function getTicketSettings(){ - return $this->getSettings('woocommerce_woo-mercado-pago-ticket_settings'); - } + public function getBasicSettings() { + return $this->getSettings( 'woocommerce_woo-mercado-pago-basic_settings' ); + } + public function getCustomSettings() { + return $this->getSettings( 'woocommerce_woo-mercado-pago-custom_settings' ); + } + public function getTicketSettings() { + return $this->getSettings( 'woocommerce_woo-mercado-pago-ticket_settings' ); + } - public function getSettings($option){ + public function getSettings( $option ) { - $db_options = get_option($option, []); + $db_options = get_option( $option, array() ); - $validValues = array(); - foreach ($db_options as $key => $value) { - if (!empty($value) && !in_array($key, WC_WooMercadoPago_PreferenceAnalytics::$ignoreFields)) { - $validValues[$key] = $value; - } - } - return $validValues; - } + $validValues = array(); + foreach ( $db_options as $key => $value ) { + if ( ! empty( $value ) && ! in_array( $key, self::$ignoreFields ) ) { + $validValues[ $key ] = $value; + } + } + return $validValues; + } } diff --git a/includes/module/sdk/lib/MP.php b/includes/module/sdk/lib/MP.php index 409973122..c176fa133 100755 --- a/includes/module/sdk/lib/MP.php +++ b/includes/module/sdk/lib/MP.php @@ -1,719 +1,690 @@ 2 || $i < 1) { - throw new WC_WooMercadoPago_Exception('Invalid arguments. Use CLIENT_ID and CLIENT SECRET, or ACCESS_TOKEN'); - } - - if ($i == 1) { - $this->ll_access_token = func_get_arg(0); - } - - if ($i == 2) { - $this->client_id = func_get_arg(0); - $this->client_secret = func_get_arg(1); - } - } - - /** - * @param $email - */ - public function set_email($email) - { - MPRestClient::set_email($email); - MeliRestClient::set_email($email); - } - - /** - * @param $country_code - */ - public function set_locale($country_code) - { - MPRestClient::set_locale($country_code); - MeliRestClient::set_locale($country_code); - } - - /** - * @param null $enable - * @return bool - */ - public function sandbox_mode($enable = NULL) - { - if (!is_null($enable)) { - $this->sandbox = $enable === TRUE; - } - return $this->sandbox; - } - - /** - * @return mixed|null - * @throws WC_WooMercadoPago_Exception - */ - public function get_access_token() - { - - if (isset($this->ll_access_token) && !is_null($this->ll_access_token)) { - return $this->ll_access_token; - } - - if (!empty($this->accessTokenByClient)) { - return $this->accessTokenByClient; - } - - $app_client_values = array( - 'client_id' => $this->client_id, - 'client_secret' => $this->client_secret, - 'grant_type' => 'client_credentials' - ); - - $access_data = MPRestClient::post( - array( - 'uri' => '/oauth/token', - 'data' => $app_client_values, - 'headers' => array( - 'content-type' => 'application/x-www-form-urlencoded' - ) - ), - WC_WooMercadoPago_Constants::VERSION - ); - - if ($access_data['status'] != 200) { - return null; - } - - $response = $access_data['response']; - $this->accessTokenByClient = $response['access_token']; - - return $this->accessTokenByClient; - } - - /** - * @param $id - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function search_paymentV1($id) - { - - $request = array( - 'uri' => '/v1/payments/' . $id, - 'params' => array('access_token' => $this->get_access_token()) - ); - - $payment = MPRestClient::get($request, WC_WooMercadoPago_Constants::VERSION); - return $payment; - } - - //=== CUSTOMER CARDS FUNCTIONS === - - /** - * @param $payer_email - * @return array|mixed|null - * @throws WC_WooMercadoPago_Exception - */ - public function get_or_create_customer($payer_email) - { - - $customer = $this->search_customer($payer_email); - - if ($customer['status'] == 200 && $customer['response']['paging']['total'] > 0) { - $customer = $customer['response']['results'][0]; - } else { - $resp = $this->create_customer($payer_email); - $customer = $resp['response']; - } - - return $customer; - } - - /** - * @param $email - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function create_customer($email) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/v1/customers', - 'data' => array( - 'email' => $email - ) - ); - - $customer = MPRestClient::post($request); - return $customer; - } - - /** - * @param $email - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function search_customer($email) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/v1/customers/search', - 'params' => array( - 'email' => $email - ) - ); - - $customer = MPRestClient::get($request); - return $customer; - } - - /** - * @param $customer_id - * @param $token - * @param null $payment_method_id - * @param null $issuer_id - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function create_card_in_customer( - $customer_id, - $token, - $payment_method_id = null, - $issuer_id = null - ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/v1/customers/' . $customer_id . '/cards', - 'data' => array( - 'token' => $token, - 'issuer_id' => $issuer_id, - 'payment_method_id' => $payment_method_id - ) - ); - - $card = MPRestClient::post($request); - return $card; - } - - /** - * @param $customer_id - * @param $token - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function get_all_customer_cards($customer_id, $token) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/v1/customers/' . $customer_id . '/cards', - ); - - $cards = MPRestClient::get($request); - return $cards; - } - - //=== COUPOM AND DISCOUNTS FUNCTIONS === - /** - * @param $transaction_amount - * @param $payer_email - * @param $coupon_code - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function check_discount_campaigns($transaction_amount, $payer_email, $coupon_code) - { - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/discount_campaigns', - 'params' => array( - 'transaction_amount' => $transaction_amount, - 'payer_email' => $payer_email, - 'coupon_code' => $coupon_code - ) - ); - $discount_info = MPRestClient::get($request); - return $discount_info; - } - - //=== CHECKOUT AUXILIARY FUNCTIONS === - - /** - * @param $id - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function get_authorized_payment($id) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/authorized_payments/{$id}', - ); - - $authorized_payment_info = MPRestClient::get($request); - return $authorized_payment_info; - } - - /** - * @param $preference - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function create_preference($preference) - { - - $request = array( - 'uri' => '/checkout/preferences', - 'headers' => array( - 'user-agent' => 'platform:desktop,type:woocommerce,so:' . WC_WooMercadoPago_Constants::VERSION, - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'data' => $preference - ); - - $preference_result = MPRestClient::post($request); - return $preference_result; - } - - /** - * @param $id - * @param $preference - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function update_preference($id, $preference) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/checkout/preferences/{$id}', - 'data' => $preference - ); - - $preference_result = MPRestClient::put($request); - return $preference_result; - } - - /** - * @param $id - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function get_preference($id) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/checkout/preferences/{$id}', - ); - - $preference_result = MPRestClient::get($request); - return $preference_result; - } - - /** - * @param $preference - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function create_payment($preference) - { - - $request = array( - 'uri' => '/v1/payments', - 'headers' => array( - 'X-Tracking-Id' => 'platform:v1-whitelabel,type:woocommerce,so:' . WC_WooMercadoPago_Constants::VERSION, - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'data' => $preference - ); - - $payment = MPRestClient::post($request, WC_WooMercadoPago_Constants::VERSION); - return $payment; - } - - /** - * @param $preapproval_payment - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function create_preapproval_payment($preapproval_payment) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/preapproval', - 'data' => $preapproval_payment - ); - - $preapproval_payment_result = MPRestClient::post($request); - return $preapproval_payment_result; - } - - /** - * @param $id - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function get_preapproval_payment($id) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/preapproval/' . $id - ); - - $preapproval_payment_result = MPRestClient::get($request); - return $preapproval_payment_result; - } - - /** - * @param $id - * @param $preapproval_payment - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function update_preapproval_payment($id, $preapproval_payment) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/preapproval/' . $id, - 'data' => $preapproval_payment - ); - - $preapproval_payment_result = MPRestClient::put($request); - return $preapproval_payment_result; - } - - /** - * @param $id - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function cancel_preapproval_payment($id) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/preapproval/' . $id, - 'data' => array( - 'status' => 'cancelled' - ) - ); - - $response = MPRestClient::put($request); - return $response; - } - - //=== REFUND AND CANCELING FLOW FUNCTIONS === - - /** - * @param $id - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function refund_payment($id) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/v1/payments/' . $id . '/refunds' - ); - - $response = MPRestClient::post($request); - return $response; - } - - /** - * @param $id - * @param $amount - * @param $reason - * @param $external_reference - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function partial_refund_payment($id, $amount, $reason, $external_reference) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/v1/payments/' . $id . '/refunds', - 'data' => array( - 'amount' => $amount, - 'metadata' => array( - 'metadata' => $reason, - 'external_reference' => $external_reference - ) - ) - ); - - $response = MPRestClient::post($request); - return $response; - } - - /** - * @param $id - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function cancel_payment($id) - { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token() - ), - 'uri' => '/v1/payments/' . $id, - 'data' => '{"status":"cancelled"}' - ); - - $response = MPRestClient::put($request); - return $response; - } - - /** - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function get_payment_methods($accessToken) - { - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $accessToken - ), - 'uri' => '/v1/payment_methods', - ); - - $response = MPRestClient::get($request); - - if ($response['status'] > 202) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log('get_payment_methods'); - $log->write_log('API get_payment_methods error: ', $response['response']['message']); - return null; - } - - asort($response); - - return $response; - } - - /** - * Validate if the seller is homologated - * @param $access_token - * @param $public_key - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function getCredentialsWrapper($access_token = null, $public_key = null) - { - $request = array( - 'uri' => '/plugins-credentials-wrapper/credentials', - ); - - if (!empty($access_token) && empty($public_key)) { - $request['headers'] = array('Authorization' => 'Bearer ' . $access_token); - } - - if (empty($access_token) && !empty($public_key)) { - $request['params'] = array('public_key' => $public_key); - } - - $response = MPRestClient::get($request); - - if ($response['status'] > 202) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log('getCredentialsWrapper'); - $log->write_log('API GET Credentials Wrapper error:', $response['response']['message']); - return false; - } - - return $response['response']; - } - - //=== GENERIC RESOURCE CALL METHODS === - - /** - * @param $request - * @param null $params - * @param bool $authenticate - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function get($request, $headers = [], $authenticate = true) - { - - if (is_string($request)) { - $request = array( - 'headers' => $headers, - 'uri' => $request, - 'authenticate' => $authenticate - ); - } - - if (!isset($request['authenticate']) || $request['authenticate'] !== false) { - $access_token = $this->get_access_token(); - if (!empty($access_token)) { - $request['headers'] = array('Authorization'=> 'Bearer ' . $access_token); - } - } - - $result = MPRestClient::get($request); - return $result; - } - - /** - * @param $request - * @param null $data - * @param null $params - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function post($request, $data = null, $params = null) - { - - if (is_string($request)) { - $request = array( - 'headers' => array('Authorization' => 'Bearer ' . $this->get_access_token()), - 'uri' => $request, - 'data' => $data, - 'params' => $params - ); - } - - $request['params'] = isset($request['params']) && is_array($request['params']) ? - $request["params"] : - array(); - - $result = MPRestClient::post($request); - return $result; - } - - /** - * @param $request - * @param null $data - * @param null $params - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function put($request, $data = null, $params = null) - { - - if (is_string($request)) { - $request = array( - 'headers' => array('Authorization' => 'Bearer ' . $this->get_access_token()), - 'uri' => $request, - 'data' => $data, - 'params' => $params - ); - } - - $request['params'] = isset($request['params']) && is_array($request['params']) ? - $request['params'] : - array(); - - $result = MPRestClient::put($request); - return $result; - } - - /** - * @param $request - * @param null $params - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function delete($request, $params = null) - { - - if (is_string($request)) { - $request = array( - 'headers' => array('Authorization' => 'Bearer ' . $this->get_access_token()), - 'uri' => $request, - 'params' => $params - ); - } - - $request['params'] = isset($request['params']) && is_array($request['params']) ? - $request['params'] : - array(); - - $result = MPRestClient::delete($request); - return $result; - } - - /** - * @param null $payment - */ - public function setPaymentClass($payment = null) - { - if (!empty($payment)) { - $this->paymentClass = get_class($payment); - } - } - - /** - * @return mixed - */ - public function getPaymentClass() - { - return $this->paymentClass; - } +class MP { + + private $client_id; + private $client_secret; + private $ll_access_token; + private $sandbox = false; + private $accessTokenByClient; + private $paymentClass; + + /** + * MP constructor. + * + * @throws WC_WooMercadoPago_Exception + */ + public function __construct() { + $includes_path = dirname( __FILE__ ); + require_once $includes_path . '/RestClient/AbstractRestClient.php'; + require_once $includes_path . '/RestClient/MeliRestClient.php'; + require_once $includes_path . '/RestClient/MpRestClient.php'; + + $i = func_num_args(); + if ( $i > 2 || $i < 1 ) { + throw new WC_WooMercadoPago_Exception( 'Invalid arguments. Use CLIENT_ID and CLIENT SECRET, or ACCESS_TOKEN' ); + } + + if ( $i == 1 ) { + $this->ll_access_token = func_get_arg( 0 ); + } + + if ( $i == 2 ) { + $this->client_id = func_get_arg( 0 ); + $this->client_secret = func_get_arg( 1 ); + } + } + + /** + * @param $email + */ + public function set_email( $email ) { + MPRestClient::set_email( $email ); + MeliRestClient::set_email( $email ); + } + + /** + * @param $country_code + */ + public function set_locale( $country_code ) { + MPRestClient::set_locale( $country_code ); + MeliRestClient::set_locale( $country_code ); + } + + /** + * @param null $enable + * @return bool + */ + public function sandbox_mode( $enable = null ) { + if ( ! is_null( $enable ) ) { + $this->sandbox = $enable === true; + } + return $this->sandbox; + } + + /** + * @return mixed|null + * @throws WC_WooMercadoPago_Exception + */ + public function get_access_token() { + + if ( isset( $this->ll_access_token ) && ! is_null( $this->ll_access_token ) ) { + return $this->ll_access_token; + } + + if ( ! empty( $this->accessTokenByClient ) ) { + return $this->accessTokenByClient; + } + + $app_client_values = array( + 'client_id' => $this->client_id, + 'client_secret' => $this->client_secret, + 'grant_type' => 'client_credentials', + ); + + $access_data = MPRestClient::post( + array( + 'uri' => '/oauth/token', + 'data' => $app_client_values, + 'headers' => array( + 'content-type' => 'application/x-www-form-urlencoded', + ), + ), + WC_WooMercadoPago_Constants::VERSION + ); + + if ( $access_data['status'] != 200 ) { + return null; + } + + $response = $access_data['response']; + $this->accessTokenByClient = $response['access_token']; + + return $this->accessTokenByClient; + } + + /** + * @param $id + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function search_paymentV1( $id ) { + + $request = array( + 'uri' => '/v1/payments/' . $id, + 'params' => array( 'access_token' => $this->get_access_token() ), + ); + + $payment = MPRestClient::get( $request, WC_WooMercadoPago_Constants::VERSION ); + return $payment; + } + + // === CUSTOMER CARDS FUNCTIONS === + + /** + * @param $payer_email + * @return array|mixed|null + * @throws WC_WooMercadoPago_Exception + */ + public function get_or_create_customer( $payer_email ) { + + $customer = $this->search_customer( $payer_email ); + + if ( $customer['status'] == 200 && $customer['response']['paging']['total'] > 0 ) { + $customer = $customer['response']['results'][0]; + } else { + $resp = $this->create_customer( $payer_email ); + $customer = $resp['response']; + } + + return $customer; + } + + /** + * @param $email + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function create_customer( $email ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/customers', + 'data' => array( + 'email' => $email, + ), + ); + + $customer = MPRestClient::post( $request ); + return $customer; + } + + /** + * @param $email + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function search_customer( $email ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/customers/search', + 'params' => array( + 'email' => $email, + ), + ); + + $customer = MPRestClient::get( $request ); + return $customer; + } + + /** + * @param $customer_id + * @param $token + * @param null $payment_method_id + * @param null $issuer_id + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function create_card_in_customer( + $customer_id, + $token, + $payment_method_id = null, + $issuer_id = null + ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/customers/' . $customer_id . '/cards', + 'data' => array( + 'token' => $token, + 'issuer_id' => $issuer_id, + 'payment_method_id' => $payment_method_id, + ), + ); + + $card = MPRestClient::post( $request ); + return $card; + } + + /** + * @param $customer_id + * @param $token + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function get_all_customer_cards( $customer_id, $token ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/customers/' . $customer_id . '/cards', + ); + + $cards = MPRestClient::get( $request ); + return $cards; + } + + // === COUPOM AND DISCOUNTS FUNCTIONS === + /** + * @param $transaction_amount + * @param $payer_email + * @param $coupon_code + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function check_discount_campaigns( $transaction_amount, $payer_email, $coupon_code ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/discount_campaigns', + 'params' => array( + 'transaction_amount' => $transaction_amount, + 'payer_email' => $payer_email, + 'coupon_code' => $coupon_code, + ), + ); + $discount_info = MPRestClient::get( $request ); + return $discount_info; + } + + // === CHECKOUT AUXILIARY FUNCTIONS === + + /** + * @param $id + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function get_authorized_payment( $id ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/authorized_payments/{$id}', + ); + + $authorized_payment_info = MPRestClient::get( $request ); + return $authorized_payment_info; + } + + /** + * @param $preference + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function create_preference( $preference ) { + + $request = array( + 'uri' => '/checkout/preferences', + 'headers' => array( + 'user-agent' => 'platform:desktop,type:woocommerce,so:' . WC_WooMercadoPago_Constants::VERSION, + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'data' => $preference, + ); + + $preference_result = MPRestClient::post( $request ); + return $preference_result; + } + + /** + * @param $id + * @param $preference + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function update_preference( $id, $preference ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/checkout/preferences/{$id}', + 'data' => $preference, + ); + + $preference_result = MPRestClient::put( $request ); + return $preference_result; + } + + /** + * @param $id + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function get_preference( $id ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/checkout/preferences/{$id}', + ); + + $preference_result = MPRestClient::get( $request ); + return $preference_result; + } + + /** + * @param $preference + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function create_payment( $preference ) { + + $request = array( + 'uri' => '/v1/payments', + 'headers' => array( + 'X-Tracking-Id' => 'platform:v1-whitelabel,type:woocommerce,so:' . WC_WooMercadoPago_Constants::VERSION, + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'data' => $preference, + ); + + $payment = MPRestClient::post( $request, WC_WooMercadoPago_Constants::VERSION ); + return $payment; + } + + /** + * @param $preapproval_payment + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function create_preapproval_payment( $preapproval_payment ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/preapproval', + 'data' => $preapproval_payment, + ); + + $preapproval_payment_result = MPRestClient::post( $request ); + return $preapproval_payment_result; + } + + /** + * @param $id + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function get_preapproval_payment( $id ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/preapproval/' . $id, + ); + + $preapproval_payment_result = MPRestClient::get( $request ); + return $preapproval_payment_result; + } + + /** + * @param $id + * @param $preapproval_payment + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function update_preapproval_payment( $id, $preapproval_payment ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/preapproval/' . $id, + 'data' => $preapproval_payment, + ); + + $preapproval_payment_result = MPRestClient::put( $request ); + return $preapproval_payment_result; + } + + /** + * @param $id + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function cancel_preapproval_payment( $id ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/preapproval/' . $id, + 'data' => array( + 'status' => 'cancelled', + ), + ); + + $response = MPRestClient::put( $request ); + return $response; + } + + // === REFUND AND CANCELING FLOW FUNCTIONS === + + /** + * @param $id + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function refund_payment( $id ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/payments/' . $id . '/refunds', + ); + + $response = MPRestClient::post( $request ); + return $response; + } + + /** + * @param $id + * @param $amount + * @param $reason + * @param $external_reference + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function partial_refund_payment( $id, $amount, $reason, $external_reference ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/payments/' . $id . '/refunds', + 'data' => array( + 'amount' => $amount, + 'metadata' => array( + 'metadata' => $reason, + 'external_reference' => $external_reference, + ), + ), + ); + + $response = MPRestClient::post( $request ); + return $response; + } + + /** + * @param $id + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function cancel_payment( $id ) { + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/payments/' . $id, + 'data' => '{"status":"cancelled"}', + ); + + $response = MPRestClient::put( $request ); + return $response; + } + + /** + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function get_payment_methods( $accessToken ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $accessToken, + ), + 'uri' => '/v1/payment_methods', + ); + + $response = MPRestClient::get( $request ); + + if ( $response['status'] > 202 ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'get_payment_methods' ); + $log->write_log( 'API get_payment_methods error: ', $response['response']['message'] ); + return null; + } + + asort( $response ); + + return $response; + } + + /** + * Validate if the seller is homologated + * + * @param $access_token + * @param $public_key + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function getCredentialsWrapper( $access_token = null, $public_key = null ) { + $request = array( + 'uri' => '/plugins-credentials-wrapper/credentials', + ); + + if ( ! empty( $access_token ) && empty( $public_key ) ) { + $request['headers'] = array( 'Authorization' => 'Bearer ' . $access_token ); + } + + if ( empty( $access_token ) && ! empty( $public_key ) ) { + $request['params'] = array( 'public_key' => $public_key ); + } + + $response = MPRestClient::get( $request ); + + if ( $response['status'] > 202 ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'getCredentialsWrapper' ); + $log->write_log( 'API GET Credentials Wrapper error:', $response['response']['message'] ); + return false; + } + + return $response['response']; + } + + // === GENERIC RESOURCE CALL METHODS === + + /** + * @param $request + * @param null $params + * @param bool $authenticate + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function get( $request, $headers = array(), $authenticate = true ) { + + if ( is_string( $request ) ) { + $request = array( + 'headers' => $headers, + 'uri' => $request, + 'authenticate' => $authenticate, + ); + } + + if ( ! isset( $request['authenticate'] ) || $request['authenticate'] !== false ) { + $access_token = $this->get_access_token(); + if ( ! empty( $access_token ) ) { + $request['headers'] = array( 'Authorization' => 'Bearer ' . $access_token ); + } + } + + $result = MPRestClient::get( $request ); + return $result; + } + + /** + * @param $request + * @param null $data + * @param null $params + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function post( $request, $data = null, $params = null ) { + + if ( is_string( $request ) ) { + $request = array( + 'headers' => array( 'Authorization' => 'Bearer ' . $this->get_access_token() ), + 'uri' => $request, + 'data' => $data, + 'params' => $params, + ); + } + + $request['params'] = isset( $request['params'] ) && is_array( $request['params'] ) ? + $request['params'] : + array(); + + $result = MPRestClient::post( $request ); + return $result; + } + + /** + * @param $request + * @param null $data + * @param null $params + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function put( $request, $data = null, $params = null ) { + + if ( is_string( $request ) ) { + $request = array( + 'headers' => array( 'Authorization' => 'Bearer ' . $this->get_access_token() ), + 'uri' => $request, + 'data' => $data, + 'params' => $params, + ); + } + + $request['params'] = isset( $request['params'] ) && is_array( $request['params'] ) ? + $request['params'] : + array(); + + $result = MPRestClient::put( $request ); + return $result; + } + + /** + * @param $request + * @param null $params + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function delete( $request, $params = null ) { + + if ( is_string( $request ) ) { + $request = array( + 'headers' => array( 'Authorization' => 'Bearer ' . $this->get_access_token() ), + 'uri' => $request, + 'params' => $params, + ); + } + + $request['params'] = isset( $request['params'] ) && is_array( $request['params'] ) ? + $request['params'] : + array(); + + $result = MPRestClient::delete( $request ); + return $result; + } + + /** + * @param null $payment + */ + public function setPaymentClass( $payment = null ) { + if ( ! empty( $payment ) ) { + $this->paymentClass = get_class( $payment ); + } + } + + /** + * @return mixed + */ + public function getPaymentClass() { + return $this->paymentClass; + } } diff --git a/includes/module/sdk/lib/RestClient/AbstractRestClient.php b/includes/module/sdk/lib/RestClient/AbstractRestClient.php index 27397175e..297d38a37 100644 --- a/includes/module/sdk/lib/RestClient/AbstractRestClient.php +++ b/includes/module/sdk/lib/RestClient/AbstractRestClient.php @@ -8,168 +8,164 @@ * License - https://www.gnu.org/licenses/gpl.html GPL version 2 or higher */ -if (!defined('ABSPATH')) { - exit; +if ( ! defined( 'ABSPATH' ) ) { + exit; } /** * Class AbstractRestClient */ -class AbstractRestClient -{ - public static $email_admin = ''; - public static $site_locale = ''; - public static $check_loop = 0; - - /** - * @param $request - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function execAbs($request, $url) - { - try { - $connect = self::build_request($request, $url); - return self::execute($request, $connect); - } catch (Exception $e) { - return null; - } - } - - /** - * @param $request - * @return false|resource - * @throws WC_WooMercadoPago_Exception - */ - public static function build_request($request, $url) - { - if (!extension_loaded('curl')) { - throw new WC_WooMercadoPago_Exception('cURL extension not found. You need to enable cURL in your php.ini or another configuration you have.'); - } - - if (!isset($request['method'])) { - throw new WC_WooMercadoPago_Exception('No HTTP METHOD specified'); - } - - if (!isset($request['uri'])) { - throw new WC_WooMercadoPago_Exception('No URI specified'); - } - - $headers = array('accept: application/json'); - if ($request['method'] == 'POST') { - $headers[] = 'x-product-id:' . (WC_WooMercadoPago_Module::is_mobile() ? WC_WooMercadoPago_Constants::PRODUCT_ID_MOBILE : WC_WooMercadoPago_Constants::PRODUCT_ID_DESKTOP); - $headers[] = 'x-platform-id:' . WC_WooMercadoPago_Constants::PLATAFORM_ID; - $headers[] = 'x-integrator-id:' . get_option('_mp_integrator_id', null); - } - - $json_content = true; - $form_content = false; - $default_content_type = true; - - if (isset($request['headers']) && is_array($request['headers'])) { - foreach ($request['headers'] as $h => $v) { - if ($h == 'content-type') { - $default_content_type = false; - $json_content = $v == 'application/json'; - $form_content = $v == 'application/x-www-form-urlencoded'; - } - array_push($headers, $h . ': ' . $v); - } - } - if ($default_content_type) { - array_push($headers, 'content-type: application/json'); - } - - $connect = curl_init(); - curl_setopt($connect, CURLOPT_USERAGENT, 'platform:v1-whitelabel,type:woocommerce,so:' . WC_WooMercadoPago_Constants::VERSION); - curl_setopt($connect, CURLOPT_RETURNTRANSFER, true); - curl_setopt($connect, CURLOPT_SSL_VERIFYPEER, true); - curl_setopt($connect, CURLOPT_CAINFO, $GLOBALS['LIB_LOCATION'] . '/cacert.pem'); - curl_setopt($connect, CURLOPT_CUSTOMREQUEST, $request['method']); - curl_setopt($connect, CURLOPT_HTTPHEADER, $headers); - - if (isset($request['params']) && is_array($request['params'])) { - if (count($request['params']) > 0) { - $request['uri'] .= (strpos($request['uri'], '?') === false) ? '?' : '&'; - $request['uri'] .= self::build_query($request['params']); - } - } - - curl_setopt($connect, CURLOPT_URL, $url . $request['uri']); - - - if (isset($request['data'])) { - if ($json_content) { - if (gettype($request['data']) == 'string') { - json_decode($request['data'], true); - } else { - $request['data'] = json_encode($request['data']); - } - if (function_exists('json_last_error')) { - $json_error = json_last_error(); - if ($json_error != JSON_ERROR_NONE) { - throw new WC_WooMercadoPago_Exception("JSON Error [{$json_error}] - Data: " . $request['data']); - } - } - } elseif ($form_content) { - $request['data'] = self::build_query($request['data']); - } - curl_setopt($connect, CURLOPT_POSTFIELDS, $request['data']); - } - - return $connect; - } - - /** - * @param $connect - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function execute($request, $connect) - { - $response = null; - $api_result = curl_exec($connect); - if (curl_errno($connect)) { - throw new WC_WooMercadoPago_Exception(curl_error($connect)); - } - $api_http_code = curl_getinfo($connect, CURLINFO_HTTP_CODE); - - if ($api_http_code != null && $api_result != null) { - $response = array('status' => $api_http_code, 'response' => json_decode($api_result, true)); - } - - curl_close($connect); - return $response; - } - - /** - * @param $params - * @return string - */ - public static function build_query($params) - { - if (function_exists('http_build_query')) { - return http_build_query($params, '', '&'); - } else { - foreach ($params as $name => $value) { - $elements[] = "{$name}=" . urlencode($value); - } - return implode('&', $elements); - } - } - - /** - * @param $email - */ - public static function set_email($email) - { - self::$email_admin = $email; - } - - /** - * @param $country_code - */ - public static function set_locale($country_code) - { - self::$site_locale = $country_code; - } +class AbstractRestClient { + + public static $email_admin = ''; + public static $site_locale = ''; + public static $check_loop = 0; + + /** + * @param $request + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function execAbs( $request, $url ) { + try { + $connect = self::build_request( $request, $url ); + return self::execute( $request, $connect ); + } catch ( Exception $e ) { + return null; + } + } + + /** + * @param $request + * @return false|resource + * @throws WC_WooMercadoPago_Exception + */ + public static function build_request( $request, $url ) { + if ( ! extension_loaded( 'curl' ) ) { + throw new WC_WooMercadoPago_Exception( 'cURL extension not found. You need to enable cURL in your php.ini or another configuration you have.' ); + } + + if ( ! isset( $request['method'] ) ) { + throw new WC_WooMercadoPago_Exception( 'No HTTP METHOD specified' ); + } + + if ( ! isset( $request['uri'] ) ) { + throw new WC_WooMercadoPago_Exception( 'No URI specified' ); + } + + $headers = array( 'accept: application/json' ); + if ( $request['method'] == 'POST' ) { + $headers[] = 'x-product-id:' . ( WC_WooMercadoPago_Module::is_mobile() ? WC_WooMercadoPago_Constants::PRODUCT_ID_MOBILE : WC_WooMercadoPago_Constants::PRODUCT_ID_DESKTOP ); + $headers[] = 'x-platform-id:' . WC_WooMercadoPago_Constants::PLATAFORM_ID; + $headers[] = 'x-integrator-id:' . get_option( '_mp_integrator_id', null ); + } + + $json_content = true; + $form_content = false; + $default_content_type = true; + + if ( isset( $request['headers'] ) && is_array( $request['headers'] ) ) { + foreach ( $request['headers'] as $h => $v ) { + if ( $h == 'content-type' ) { + $default_content_type = false; + $json_content = $v == 'application/json'; + $form_content = $v == 'application/x-www-form-urlencoded'; + } + array_push( $headers, $h . ': ' . $v ); + } + } + if ( $default_content_type ) { + array_push( $headers, 'content-type: application/json' ); + } + + $connect = curl_init(); + curl_setopt( $connect, CURLOPT_USERAGENT, 'platform:v1-whitelabel,type:woocommerce,so:' . WC_WooMercadoPago_Constants::VERSION ); + curl_setopt( $connect, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( $connect, CURLOPT_SSL_VERIFYPEER, true ); + curl_setopt( $connect, CURLOPT_CAINFO, $GLOBALS['LIB_LOCATION'] . '/cacert.pem' ); + curl_setopt( $connect, CURLOPT_CUSTOMREQUEST, $request['method'] ); + curl_setopt( $connect, CURLOPT_HTTPHEADER, $headers ); + + if ( isset( $request['params'] ) && is_array( $request['params'] ) ) { + if ( count( $request['params'] ) > 0 ) { + $request['uri'] .= ( strpos( $request['uri'], '?' ) === false ) ? '?' : '&'; + $request['uri'] .= self::build_query( $request['params'] ); + } + } + + curl_setopt( $connect, CURLOPT_URL, $url . $request['uri'] ); + + if ( isset( $request['data'] ) ) { + if ( $json_content ) { + if ( gettype( $request['data'] ) == 'string' ) { + json_decode( $request['data'], true ); + } else { + $request['data'] = json_encode( $request['data'] ); + } + if ( function_exists( 'json_last_error' ) ) { + $json_error = json_last_error(); + if ( $json_error != JSON_ERROR_NONE ) { + throw new WC_WooMercadoPago_Exception( "JSON Error [{$json_error}] - Data: " . $request['data'] ); + } + } + } elseif ( $form_content ) { + $request['data'] = self::build_query( $request['data'] ); + } + curl_setopt( $connect, CURLOPT_POSTFIELDS, $request['data'] ); + } + + return $connect; + } + + /** + * @param $connect + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function execute( $request, $connect ) { + $response = null; + $api_result = curl_exec( $connect ); + if ( curl_errno( $connect ) ) { + throw new WC_WooMercadoPago_Exception( curl_error( $connect ) ); + } + $api_http_code = curl_getinfo( $connect, CURLINFO_HTTP_CODE ); + + if ( $api_http_code != null && $api_result != null ) { + $response = array( + 'status' => $api_http_code, + 'response' => json_decode( $api_result, true ), + ); + } + + curl_close( $connect ); + return $response; + } + + /** + * @param $params + * @return string + */ + public static function build_query( $params ) { + if ( function_exists( 'http_build_query' ) ) { + return http_build_query( $params, '', '&' ); + } else { + foreach ( $params as $name => $value ) { + $elements[] = "{$name}=" . urlencode( $value ); + } + return implode( '&', $elements ); + } + } + + /** + * @param $email + */ + public static function set_email( $email ) { + self::$email_admin = $email; + } + + /** + * @param $country_code + */ + public static function set_locale( $country_code ) { + self::$site_locale = $country_code; + } } diff --git a/includes/module/sdk/lib/RestClient/MeliRestClient.php b/includes/module/sdk/lib/RestClient/MeliRestClient.php index 6b0f8f6cf..a816737e7 100755 --- a/includes/module/sdk/lib/RestClient/MeliRestClient.php +++ b/includes/module/sdk/lib/RestClient/MeliRestClient.php @@ -15,51 +15,47 @@ /** * Class MeliRestClient */ -class MeliRestClient extends AbstractRestClient -{ - const API_MELI_BASE_URL = 'https://api.mercadolibre.com'; +class MeliRestClient extends AbstractRestClient { - /** - * @param $request - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function get($request) - { - $request['method'] = 'GET'; - return self::execAbs($request, self::API_MELI_BASE_URL); - } + const API_MELI_BASE_URL = 'https://api.mercadolibre.com'; - /** - * @param $request - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function post($request) - { - $request['method'] = 'POST'; - return self::execAbs($request, self::API_MELI_BASE_URL); - } + /** + * @param $request + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function get( $request ) { + $request['method'] = 'GET'; + return self::execAbs( $request, self::API_MELI_BASE_URL ); + } - /** - * @param $request - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function put($request) - { - $request['method'] = 'PUT'; - return self::execAbs($request, self::API_MELI_BASE_URL); - } + /** + * @param $request + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function post( $request ) { + $request['method'] = 'POST'; + return self::execAbs( $request, self::API_MELI_BASE_URL ); + } - /** - * @param $request - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function delete($request) - { - $request['method'] = 'DELETE'; - return self::execAbs($request, self::API_MELI_BASE_URL); - } + /** + * @param $request + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function put( $request ) { + $request['method'] = 'PUT'; + return self::execAbs( $request, self::API_MELI_BASE_URL ); + } + + /** + * @param $request + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function delete( $request ) { + $request['method'] = 'DELETE'; + return self::execAbs( $request, self::API_MELI_BASE_URL ); + } } diff --git a/includes/module/sdk/lib/RestClient/MpRestClient.php b/includes/module/sdk/lib/RestClient/MpRestClient.php index 7a709547c..2b15c95cf 100644 --- a/includes/module/sdk/lib/RestClient/MpRestClient.php +++ b/includes/module/sdk/lib/RestClient/MpRestClient.php @@ -15,50 +15,46 @@ /** * Class MPRestClient */ -class MPRestClient extends AbstractRestClient -{ - /** - * @param $request - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function get($request) - { - $request['method'] = 'GET'; - return self::execAbs($request, WC_WooMercadoPago_Constants::API_MP_BASE_URL); - } +class MPRestClient extends AbstractRestClient { - /** - * @param $request - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function post($request) - { - $request['method'] = 'POST'; - return self::execAbs($request, WC_WooMercadoPago_Constants::API_MP_BASE_URL); - } + /** + * @param $request + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function get( $request ) { + $request['method'] = 'GET'; + return self::execAbs( $request, WC_WooMercadoPago_Constants::API_MP_BASE_URL ); + } - /** - * @param $request - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function put($request) - { - $request['method'] = 'PUT'; - return self::execAbs($request, WC_WooMercadoPago_Constants::API_MP_BASE_URL); - } + /** + * @param $request + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function post( $request ) { + $request['method'] = 'POST'; + return self::execAbs( $request, WC_WooMercadoPago_Constants::API_MP_BASE_URL ); + } - /** - * @param $request - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public static function delete($request) - { - $request['method'] = 'DELETE'; - return self::execAbs($request, WC_WooMercadoPago_Constants::API_MP_BASE_URL); - } + /** + * @param $request + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function put( $request ) { + $request['method'] = 'PUT'; + return self::execAbs( $request, WC_WooMercadoPago_Constants::API_MP_BASE_URL ); + } + + /** + * @param $request + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public static function delete( $request ) { + $request['method'] = 'DELETE'; + return self::execAbs( $request, WC_WooMercadoPago_Constants::API_MP_BASE_URL ); + } } diff --git a/includes/notification/WC_WooMercadoPago_Notification_Abstract.php b/includes/notification/WC_WooMercadoPago_Notification_Abstract.php index 1becce398..43b2c8eb1 100644 --- a/includes/notification/WC_WooMercadoPago_Notification_Abstract.php +++ b/includes/notification/WC_WooMercadoPago_Notification_Abstract.php @@ -1,405 +1,392 @@ payment = $payment; - $this->mp = $payment->mp; - $this->log = $payment->log; - $this->sandbox = $payment->sandbox; - $this->payment = $payment; - - add_action('woocommerce_api_' . strtolower(get_class($payment)), array($this, 'check_ipn_response')); - add_action('valid_mercadopago_ipn_request', array($this, 'successful_request')); - add_action('woocommerce_order_status_cancelled', array($this, 'process_cancel_order_meta_box_actions'), 10, 1); - } - - /** - * @param $mp_status - * @return mixed - */ - 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 = $defaults[$mp_status]; - return str_replace('_', '-', $status); - } - - /** - * - */ - public function check_ipn_response() - { - @ob_clean(); - $this->log->write_log(__FUNCTION__, 'received _get content: ' . json_encode($_GET, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - } - - /** - * @param $data - * @return bool|WC_Order|WC_Order_Refund - */ - public function successful_request($data) - { - $this->log->write_log(__FUNCTION__, 'starting to process update...'); - $order_key = $data['external_reference']; - - if (empty($order_key)) { - $this->log->write_log(__FUNCTION__, 'External Reference not found'); - $this->setResponse(422, null, "External Reference not found"); - } - $invoice_prefix = get_option('_mp_store_identificator', 'WC-'); - $id = (int)str_replace($invoice_prefix, '', $order_key); - $order = wc_get_order($id); - if (!$order) { - $this->log->write_log(__FUNCTION__, 'Order is invalid'); - $this->setResponse(422, null, "Order is invalid"); - } - - $order_id = (method_exists($order, 'get_id') ? $order->get_id() : $order->get_id()); - if ($order_id !== $id) { - $this->log->write_log(__FUNCTION__, 'Order error'); - $this->setResponse(422, null, "Order error"); - } - - $this->log->write_log(__FUNCTION__, 'updating metadata and status with data: ' . json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - - return $order; - } - - /** - * @param $processed_status - * @param $data - * @param $order - * @throws WC_WooMercadoPago_Exception - */ - public function proccessStatus($processed_status, $data, $order) - { - $used_gateway = get_class($this->payment); - - switch ($processed_status) { - case 'approved': - $this->mp_rule_approved($data, $order, $used_gateway); - break; - case 'pending': - $this->mp_rule_pending($data, $order, $used_gateway); - break; - case 'in_process': - $this->mp_rule_in_process($data, $order); - break; - case 'rejected': - $this->mp_rule_rejected($data, $order); - break; - case 'refunded': - $this->mp_rule_refunded($order); - break; - case 'cancelled': - $this->mp_rule_cancelled($data, $order); - break; - case 'in_mediation': - $this->mp_rule_in_mediation($order); - break; - case 'charged_back': - $this->mp_rule_charged_back($order); - break; - default: - throw new WC_WooMercadoPago_Exception('Process Status - Invalid Status: ' . $processed_status); - } - } - - /** - * @param $data - * @param $order - * @param $used_gateway - */ - public function mp_rule_approved($data, $order, $used_gateway) - { - $order->add_order_note('Mercado Pago: ' . __('Payment approved.', 'woocommerce-mercadopago')); - - $payment_completed_status = apply_filters( - 'woocommerce_payment_complete_order_status', - $order->needs_processing() ? 'processing' : 'completed', - $order->get_id(), - $order - ); - - if (method_exists($order, 'get_status') && $order->get_status() !== 'completed') { - switch ($used_gateway) { - case 'WC_WooMercadoPago_CustomGateway': - $order->payment_complete(); - if ($payment_completed_status !== 'completed') { - $order->update_status(self::get_wc_status_for_mp_status('approved')); - } - break; - case 'WC_WooMercadoPago_TicketGateway': - if (get_option('stock_reduce_mode', 'no') == 'no') { - $order->payment_complete(); - if ($payment_completed_status !== 'completed') { - $order->update_status(self::get_wc_status_for_mp_status('approved')); - } - } - break; - case 'WC_WooMercadoPago_BasicGateway': - $order->payment_complete(); - if ($payment_completed_status !== 'completed') { - $order->update_status(self::get_wc_status_for_mp_status('approved')); - } - break; - } - } - } - - /** - * @param $order - * @param $usedGateway - */ - public function mp_rule_pending($data, $order, $used_gateway) - { - if ($this->canUpdateOrderStatus($order)) { - $order->update_status(self::get_wc_status_for_mp_status('pending')); - switch ($used_gateway) { - case 'WC_WooMercadoPago_TicketGateway': - $notes = $order->get_customer_order_notes(); - $has_note = false; - if (sizeof($notes) > 1) { - $has_note = true; - break; - } - if (!$has_note) { - $order->add_order_note( - 'Mercado Pago: ' . __('Waiting for the ticket payment.', 'woocommerce-mercadopago') - ); - $order->add_order_note( - 'Mercado Pago: ' . __('Waiting for the ticket payment.', 'woocommerce-mercadopago'), - 1, false - ); - } - break; - default: - $order->add_order_note( - 'Mercado Pago: ' . __('The customer has not made the payment yet.', 'woocommerce-mercadopago') - ); - break; - } - } else { - $this->validateOrderNoteType($data, $order, 'pending'); - } - - return; - } - - /** - * @param $order - */ - public function mp_rule_in_process($data, $order) - { - if ($this->canUpdateOrderStatus($order)) { - $order->update_status( - self::get_wc_status_for_mp_status('inprocess'), - 'Mercado Pago: ' . __('Payment is pending review.', 'woocommerce-mercadopago') - ); - } else { - $this->validateOrderNoteType($data, $order, 'in_process'); - } - - return; - } - - /** - * @param $order - */ - public function mp_rule_rejected($data, $order) - { - if ($this->canUpdateOrderStatus($order)) { - $order->update_status( - self::get_wc_status_for_mp_status('rejected'), - 'Mercado Pago: ' . __('Payment was declined. The customer can try again.', 'woocommerce-mercadopago') - ); - } else { - $this->validateOrderNoteType($data, $order, 'rejected'); - } - - return; - } - - /** - * @param $order - */ - public function mp_rule_refunded($order) - { - $order->update_status( - self::get_wc_status_for_mp_status('refunded'), - 'Mercado Pago: ' . __('Payment was returned to the customer.', 'woocommerce-mercadopago') - ); - return; - } - - /** - * @param $order - */ - public function mp_rule_cancelled($data, $order) - { - if ($this->canUpdateOrderStatus($order)) { - $order->update_status( - self::get_wc_status_for_mp_status('cancelled'), - 'Mercado Pago: ' . __('Payment was canceled.', 'woocommerce-mercadopago') - ); - } else { - $this->validateOrderNoteType($data, $order, 'cancelled'); - } - - return; - } - - /** - * @param $order - */ - public function mp_rule_in_mediation($order) - { - $order->update_status(self::get_wc_status_for_mp_status('inmediation')); - $order->add_order_note( - 'Mercado Pago: ' . __('The payment is in mediation or the purchase was unknown by the customer.', 'woocommerce-mercadopago') - ); - return; - } - - /** - * @param $order - */ - public function mp_rule_charged_back($order) - { - $order->update_status(self::get_wc_status_for_mp_status('chargedback')); - $order->add_order_note( - 'Mercado Pago: ' . __('The payment is in mediation or the purchase was unknown by the customer.', - 'woocommerce-mercadopago') - ); - return; - } - - /** - * @param $order - */ - public function process_cancel_order_meta_box_actions($order) - { - $order_payment = wc_get_order($order); - $used_gateway = (method_exists($order_payment, 'get_meta')) ? $order_payment->get_meta('_used_gateway') : get_post_meta($order_payment->id, '_used_gateway', true); - $payments = (method_exists($order_payment, 'get_meta')) ? $order_payment->get_meta('_Mercado_Pago_Payment_IDs') : get_post_meta($order_payment->id, '_Mercado_Pago_Payment_IDs', true); - - if ($used_gateway == 'WC_WooMercadoPago_CustomGateway') { - return; - } - $this->log->write_log(__FUNCTION__, 'cancelling payments for ' . $payments); - // Canceling the order and all of its payments. - if ($this->mp != null && !empty($payments)) { - $payment_ids = explode(', ', $payments); - foreach ($payment_ids as $p_id) { - $response = $this->mp->cancel_payment($p_id); - $status = $response['status']; - $this->log->write_log(__FUNCTION__, 'cancel payment of id ' . $p_id . ' => ' . ($status >= 200 && $status < 300 ? 'SUCCESS' : 'FAIL - ' . $response['response']['message'])); - } - } else { - $this->log->write_log(__FUNCTION__, 'no payments or credentials invalid'); - } - } - - /** - * @param $checkout_info - */ - public function check_and_save_customer_card($checkout_info) - { - $this->log->write_log(__FUNCTION__, 'checking info to create card: ' . json_encode($checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - $custId = null; - $token = null; - $issuer_id = null; - $payment_method_id = null; - if (isset($checkout_info['payer']['id']) && !empty($checkout_info['payer']['id'])) { - $custId = $checkout_info['payer']['id']; - } else { - return; - } - if (isset($checkout_info['metadata']['token']) && !empty($checkout_info['metadata']['token'])) { - $token = $checkout_info['metadata']['token']; - } else { - return; - } - if (isset($checkout_info['issuer_id']) && !empty($checkout_info['issuer_id'])) { - $issuer_id = (integer)($checkout_info['issuer_id']); - } - if (isset($checkout_info['payment_method_id']) && !empty($checkout_info['payment_method_id'])) { - $payment_method_id = $checkout_info['payment_method_id']; - } - try { - $this->mp->create_card_in_customer($custId, $token, $payment_method_id, $issuer_id); - } catch (WC_WooMercadoPago_Exception $ex) { - $this->log->write_log(__FUNCTION__, 'card creation failed: ' . json_encode($ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - } - } - - protected function canUpdateOrderStatus($order) { - return method_exists($order, 'get_status') && $order->get_status() !== 'completed' && $order->get_status() !== 'processing'; - } - - /** - * @param $data - * @param $order - * @param $status - * @return void - */ - protected function validateOrderNoteType($data, $order, $status) - { - $paymentId = $data['id']; - - if(isset($data['ipn_type']) && $data['ipn_type'] === 'merchant_order') { - $payments = []; - foreach($data['payments'] as $payment) { - $payments[] = $payment['id']; - } - - $paymentId = implode(',', $payments); - } - - $order->add_order_note( - sprintf( - __('Mercado Pago: The payment %s was notified by Mercado Pago with status %s.', 'woocommerce-mercadopago'), - $paymentId, - $status - ) - ); - } - - /** - * @param $code - * @param $code_message - * @param $body - */ - public function setResponse($code, $code_message, $body) - { - status_header($code, $code_message); - die($body); - } +abstract class WC_WooMercadoPago_Notification_Abstract { + + public $mp; + public $sandbox; + public $log; + public $payment; + + /** + * WC_WooMercadoPago_Notification_Abstract constructor. + * + * @param $payment + */ + public function __construct( $payment ) { + $this->payment = $payment; + $this->mp = $payment->mp; + $this->log = $payment->log; + $this->sandbox = $payment->sandbox; + $this->payment = $payment; + + add_action( 'woocommerce_api_' . strtolower( get_class( $payment ) ), array( $this, 'check_ipn_response' ) ); + add_action( 'valid_mercadopago_ipn_request', array( $this, 'successful_request' ) ); + add_action( 'woocommerce_order_status_cancelled', array( $this, 'process_cancel_order_meta_box_actions' ), 10, 1 ); + } + + /** + * @param $mp_status + * @return mixed + */ + 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 = $defaults[ $mp_status ]; + return str_replace( '_', '-', $status ); + } + + /** + * + */ + public function check_ipn_response() { + @ob_clean(); + $this->log->write_log( __FUNCTION__, 'received _get content: ' . json_encode( $_GET, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + } + + /** + * @param $data + * @return bool|WC_Order|WC_Order_Refund + */ + public function successful_request( $data ) { + $this->log->write_log( __FUNCTION__, 'starting to process update...' ); + $order_key = $data['external_reference']; + + if ( empty( $order_key ) ) { + $this->log->write_log( __FUNCTION__, 'External Reference not found' ); + $this->setResponse( 422, null, 'External Reference not found' ); + } + $invoice_prefix = get_option( '_mp_store_identificator', 'WC-' ); + $id = (int) str_replace( $invoice_prefix, '', $order_key ); + $order = wc_get_order( $id ); + if ( ! $order ) { + $this->log->write_log( __FUNCTION__, 'Order is invalid' ); + $this->setResponse( 422, null, 'Order is invalid' ); + } + + $order_id = ( method_exists( $order, 'get_id' ) ? $order->get_id() : $order->get_id() ); + if ( $order_id !== $id ) { + $this->log->write_log( __FUNCTION__, 'Order error' ); + $this->setResponse( 422, null, 'Order error' ); + } + + $this->log->write_log( __FUNCTION__, 'updating metadata and status with data: ' . json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + + return $order; + } + + /** + * @param $processed_status + * @param $data + * @param $order + * @throws WC_WooMercadoPago_Exception + */ + public function proccessStatus( $processed_status, $data, $order ) { + $used_gateway = get_class( $this->payment ); + + switch ( $processed_status ) { + case 'approved': + $this->mp_rule_approved( $data, $order, $used_gateway ); + break; + case 'pending': + $this->mp_rule_pending( $data, $order, $used_gateway ); + break; + case 'in_process': + $this->mp_rule_in_process( $data, $order ); + break; + case 'rejected': + $this->mp_rule_rejected( $data, $order ); + break; + case 'refunded': + $this->mp_rule_refunded( $order ); + break; + case 'cancelled': + $this->mp_rule_cancelled( $data, $order ); + break; + case 'in_mediation': + $this->mp_rule_in_mediation( $order ); + break; + case 'charged_back': + $this->mp_rule_charged_back( $order ); + break; + default: + throw new WC_WooMercadoPago_Exception( 'Process Status - Invalid Status: ' . $processed_status ); + } + } + + /** + * @param $data + * @param $order + * @param $used_gateway + */ + public function mp_rule_approved( $data, $order, $used_gateway ) { + $order->add_order_note( 'Mercado Pago: ' . __( 'Payment approved.', 'woocommerce-mercadopago' ) ); + + $payment_completed_status = apply_filters( + 'woocommerce_payment_complete_order_status', + $order->needs_processing() ? 'processing' : 'completed', + $order->get_id(), + $order + ); + + if ( method_exists( $order, 'get_status' ) && $order->get_status() !== 'completed' ) { + switch ( $used_gateway ) { + case 'WC_WooMercadoPago_CustomGateway': + $order->payment_complete(); + if ( $payment_completed_status !== 'completed' ) { + $order->update_status( self::get_wc_status_for_mp_status( 'approved' ) ); + } + break; + case 'WC_WooMercadoPago_TicketGateway': + if ( get_option( 'stock_reduce_mode', 'no' ) == 'no' ) { + $order->payment_complete(); + if ( $payment_completed_status !== 'completed' ) { + $order->update_status( self::get_wc_status_for_mp_status( 'approved' ) ); + } + } + break; + case 'WC_WooMercadoPago_BasicGateway': + $order->payment_complete(); + if ( $payment_completed_status !== 'completed' ) { + $order->update_status( self::get_wc_status_for_mp_status( 'approved' ) ); + } + break; + } + } + } + + /** + * @param $order + * @param $usedGateway + */ + public function mp_rule_pending( $data, $order, $used_gateway ) { + if ( $this->canUpdateOrderStatus( $order ) ) { + $order->update_status( self::get_wc_status_for_mp_status( 'pending' ) ); + switch ( $used_gateway ) { + case 'WC_WooMercadoPago_TicketGateway': + $notes = $order->get_customer_order_notes(); + $has_note = false; + if ( sizeof( $notes ) > 1 ) { + $has_note = true; + break; + } + if ( ! $has_note ) { + $order->add_order_note( + 'Mercado Pago: ' . __( 'Waiting for the ticket payment.', 'woocommerce-mercadopago' ) + ); + $order->add_order_note( + 'Mercado Pago: ' . __( 'Waiting for the ticket payment.', 'woocommerce-mercadopago' ), + 1, + false + ); + } + break; + default: + $order->add_order_note( + 'Mercado Pago: ' . __( 'The customer has not made the payment yet.', 'woocommerce-mercadopago' ) + ); + break; + } + } else { + $this->validateOrderNoteType( $data, $order, 'pending' ); + } + + return; + } + + /** + * @param $order + */ + public function mp_rule_in_process( $data, $order ) { + if ( $this->canUpdateOrderStatus( $order ) ) { + $order->update_status( + self::get_wc_status_for_mp_status( 'inprocess' ), + 'Mercado Pago: ' . __( 'Payment is pending review.', 'woocommerce-mercadopago' ) + ); + } else { + $this->validateOrderNoteType( $data, $order, 'in_process' ); + } + + return; + } + + /** + * @param $order + */ + public function mp_rule_rejected( $data, $order ) { + if ( $this->canUpdateOrderStatus( $order ) ) { + $order->update_status( + self::get_wc_status_for_mp_status( 'rejected' ), + 'Mercado Pago: ' . __( 'Payment was declined. The customer can try again.', 'woocommerce-mercadopago' ) + ); + } else { + $this->validateOrderNoteType( $data, $order, 'rejected' ); + } + + return; + } + + /** + * @param $order + */ + public function mp_rule_refunded( $order ) { + $order->update_status( + self::get_wc_status_for_mp_status( 'refunded' ), + 'Mercado Pago: ' . __( 'Payment was returned to the customer.', 'woocommerce-mercadopago' ) + ); + return; + } + + /** + * @param $order + */ + public function mp_rule_cancelled( $data, $order ) { + if ( $this->canUpdateOrderStatus( $order ) ) { + $order->update_status( + self::get_wc_status_for_mp_status( 'cancelled' ), + 'Mercado Pago: ' . __( 'Payment was canceled.', 'woocommerce-mercadopago' ) + ); + } else { + $this->validateOrderNoteType( $data, $order, 'cancelled' ); + } + + return; + } + + /** + * @param $order + */ + public function mp_rule_in_mediation( $order ) { + $order->update_status( self::get_wc_status_for_mp_status( 'inmediation' ) ); + $order->add_order_note( + 'Mercado Pago: ' . __( 'The payment is in mediation or the purchase was unknown by the customer.', 'woocommerce-mercadopago' ) + ); + return; + } + + /** + * @param $order + */ + public function mp_rule_charged_back( $order ) { + $order->update_status( self::get_wc_status_for_mp_status( 'chargedback' ) ); + $order->add_order_note( + 'Mercado Pago: ' . __( + 'The payment is in mediation or the purchase was unknown by the customer.', + 'woocommerce-mercadopago' + ) + ); + return; + } + + /** + * @param $order + */ + public function process_cancel_order_meta_box_actions( $order ) { + $order_payment = wc_get_order( $order ); + $used_gateway = ( method_exists( $order_payment, 'get_meta' ) ) ? $order_payment->get_meta( '_used_gateway' ) : get_post_meta( $order_payment->id, '_used_gateway', true ); + $payments = ( method_exists( $order_payment, 'get_meta' ) ) ? $order_payment->get_meta( '_Mercado_Pago_Payment_IDs' ) : get_post_meta( $order_payment->id, '_Mercado_Pago_Payment_IDs', true ); + + if ( $used_gateway == 'WC_WooMercadoPago_CustomGateway' ) { + return; + } + $this->log->write_log( __FUNCTION__, 'cancelling payments for ' . $payments ); + // Canceling the order and all of its payments. + if ( $this->mp != null && ! empty( $payments ) ) { + $payment_ids = explode( ', ', $payments ); + foreach ( $payment_ids as $p_id ) { + $response = $this->mp->cancel_payment( $p_id ); + $status = $response['status']; + $this->log->write_log( __FUNCTION__, 'cancel payment of id ' . $p_id . ' => ' . ( $status >= 200 && $status < 300 ? 'SUCCESS' : 'FAIL - ' . $response['response']['message'] ) ); + } + } else { + $this->log->write_log( __FUNCTION__, 'no payments or credentials invalid' ); + } + } + + /** + * @param $checkout_info + */ + public function check_and_save_customer_card( $checkout_info ) { + $this->log->write_log( __FUNCTION__, 'checking info to create card: ' . json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + $custId = null; + $token = null; + $issuer_id = null; + $payment_method_id = null; + if ( isset( $checkout_info['payer']['id'] ) && ! empty( $checkout_info['payer']['id'] ) ) { + $custId = $checkout_info['payer']['id']; + } else { + return; + } + if ( isset( $checkout_info['metadata']['token'] ) && ! empty( $checkout_info['metadata']['token'] ) ) { + $token = $checkout_info['metadata']['token']; + } else { + return; + } + if ( isset( $checkout_info['issuer_id'] ) && ! empty( $checkout_info['issuer_id'] ) ) { + $issuer_id = (int) ( $checkout_info['issuer_id'] ); + } + if ( isset( $checkout_info['payment_method_id'] ) && ! empty( $checkout_info['payment_method_id'] ) ) { + $payment_method_id = $checkout_info['payment_method_id']; + } + try { + $this->mp->create_card_in_customer( $custId, $token, $payment_method_id, $issuer_id ); + } catch ( WC_WooMercadoPago_Exception $ex ) { + $this->log->write_log( __FUNCTION__, 'card creation failed: ' . json_encode( $ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + } + } + + protected function canUpdateOrderStatus( $order ) { + return method_exists( $order, 'get_status' ) && $order->get_status() !== 'completed' && $order->get_status() !== 'processing'; + } + + /** + * @param $data + * @param $order + * @param $status + * @return void + */ + protected function validateOrderNoteType( $data, $order, $status ) { + $paymentId = $data['id']; + + if ( isset( $data['ipn_type'] ) && $data['ipn_type'] === 'merchant_order' ) { + $payments = array(); + foreach ( $data['payments'] as $payment ) { + $payments[] = $payment['id']; + } + + $paymentId = implode( ',', $payments ); + } + + $order->add_order_note( + sprintf( + __( 'Mercado Pago: The payment %1$s was notified by Mercado Pago with status %2$s.', 'woocommerce-mercadopago' ), + $paymentId, + $status + ) + ); + } + + /** + * @param $code + * @param $code_message + * @param $body + */ + public function setResponse( $code, $code_message, $body ) { + status_header( $code, $code_message ); + die( $body ); + } } diff --git a/includes/notification/WC_WooMercadoPago_Notification_IPN.php b/includes/notification/WC_WooMercadoPago_Notification_IPN.php index cb3a395d9..86f113b82 100644 --- a/includes/notification/WC_WooMercadoPago_Notification_IPN.php +++ b/includes/notification/WC_WooMercadoPago_Notification_IPN.php @@ -1,173 +1,170 @@ log->write_log(__FUNCTION__, 'No ID or TOPIC param in Request IPN.'); - $this->setResponse(422, null, __('No ID or TOPIC param in Request IPN', 'woocommerce-mercadopago')); - } + if ( isset( $data['data_id'] ) && isset( $data['type'] ) ) { + status_header( 200, 'OK' ); + } - if ($data['topic'] == 'payment' || $data['topic'] != 'merchant_order') { - $this->log->write_log(__FUNCTION__, 'Type of topic IPN invalid, need to be merchant_order'); - $this->setResponse(422, null, __('Type of topic IPN invalid, need to be merchant_order', 'woocommerce-mercadopago')); - } + if ( ! isset( $data['id'] ) || ! isset( $data['topic'] ) ) { + $this->log->write_log( __FUNCTION__, 'No ID or TOPIC param in Request IPN.' ); + $this->setResponse( 422, null, __( 'No ID or TOPIC param in Request IPN', 'woocommerce-mercadopago' ) ); + } - $access_token = $this->mp->get_access_token(); - if ($data['topic'] == 'merchant_order') { - $ipn_info = $this->mp->get('/merchant_orders/' . $data['id'], array('Authorization' => 'Bearer ' . $access_token), false); + if ( $data['topic'] == 'payment' || $data['topic'] != 'merchant_order' ) { + $this->log->write_log( __FUNCTION__, 'Type of topic IPN invalid, need to be merchant_order' ); + $this->setResponse( 422, null, __( 'Type of topic IPN invalid, need to be merchant_order', 'woocommerce-mercadopago' ) ); + } - if (is_wp_error($ipn_info) || ($ipn_info['status'] != 200 && $ipn_info['status'] != 201)) { - $this->log->write_log(__FUNCTION__, ' IPN merchant_order not found ' . json_encode($ipn_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - $this->setResponse(422, null, __('IPN merchant_order not found', 'woocommerce-mercadopago')); - } + $access_token = $this->mp->get_access_token(); + if ( $data['topic'] == 'merchant_order' ) { + $ipn_info = $this->mp->get( '/merchant_orders/' . $data['id'], array( 'Authorization' => 'Bearer ' . $access_token ), false ); - $payments = $ipn_info['response']['payments']; - if (sizeof($payments) < 1) { - $this->log->write_log(__FUNCTION__, 'Not found Payments into Merchant_Order'); - $this->setResponse(422, null, __('Not found Payments into Merchant_Order', 'woocommerce-mercadopago')); - } + if ( is_wp_error( $ipn_info ) || ( $ipn_info['status'] != 200 && $ipn_info['status'] != 201 ) ) { + $this->log->write_log( __FUNCTION__, ' IPN merchant_order not found ' . json_encode( $ipn_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + $this->setResponse( 422, null, __( 'IPN merchant_order not found', 'woocommerce-mercadopago' ) ); + } - $ipn_info['response']['ipn_type'] = 'merchant_order'; - do_action('valid_mercadopago_ipn_request', $ipn_info['response']); - $this->setResponse(200, "OK", "Notification IPN Successfull"); - } - } + $payments = $ipn_info['response']['payments']; + if ( sizeof( $payments ) < 1 ) { + $this->log->write_log( __FUNCTION__, 'Not found Payments into Merchant_Order' ); + $this->setResponse( 422, null, __( 'Not found Payments into Merchant_Order', 'woocommerce-mercadopago' ) ); + } - /** - * @param $data - * @return bool|void|WC_Order|WC_Order_Refund - * @throws WC_Data_Exception - */ - public function successful_request($data) - { - try { - $order = parent::successful_request($data); - $processed_status = $this->process_status_mp_business($data, $order); - $this->log->write_log(__FUNCTION__, 'Changing order status to: ' . parent::get_wc_status_for_mp_status(str_replace('_', '', $processed_status))); - $this->proccessStatus($processed_status, $data, $order); - } catch (Exception $e) { - $this->setResponse(422, null, $e->getMessage()); - $this->log->write_log(__FUNCTION__, $e->getMessage()); - } - } + $ipn_info['response']['ipn_type'] = 'merchant_order'; + do_action( 'valid_mercadopago_ipn_request', $ipn_info['response'] ); + $this->setResponse( 200, 'OK', 'Notification IPN Successfull' ); + } + } - /** - * @param $data - * @param $order - * @return string - */ - public function process_status_mp_business($data, $order) - { - $status = 'pending'; - $payments = $data['payments']; - if (sizeof($payments) == 1) { - // If we have only one payment, just set status as its status - $status = $payments[0]['status']; - } elseif (sizeof($payments) > 1) { - // However, if we have multiple payments, the overall payment have some rules... - $total_paid = 0.00; - $total_refund = 0.00; - $total = $data['shipping_cost'] + $data['total_amount']; - // Grab some information... - foreach ($data['payments'] as $payment) { - if ($payment['status'] === 'approved') { - // Get the total paid amount, considering only approved incomings. - $total_paid += (float)$payment['total_paid_amount']; - } elseif ($payment['status'] === 'refunded') { - // Get the total refounded amount. - $total_refund += (float)$payment['amount_refunded']; - } - } - if ($total_paid >= $total) { - $status = 'approved'; - } elseif ($total_refund >= $total) { - $status = 'refunded'; - } else { - $status = 'pending'; - } - } - // WooCommerce 3.0 or later. - if (method_exists($order, 'update_meta_data')) { - // Updates the type of gateway. - $order->update_meta_data('_used_gateway', 'WC_WooMercadoPago_BasicGateway'); - if (!empty($data['payer']['email'])) { - $order->update_meta_data(__('Buyer email', 'woocommerce-mercadopago'), $data['payer']['email']); - } - if (!empty($data['payment_type_id'])) { - $order->update_meta_data(__('Payment method', 'woocommerce-mercadopago'), $data['payment_type_id']); - } - if (!empty($data['payments'])) { - $payment_ids = array(); - foreach ($data['payments'] as $payment) { - $payment_ids[] = $payment['id']; - $order->update_meta_data( - 'Mercado Pago - Payment ' . $payment['id'], - '[Date ' . date('Y-m-d H:i:s', strtotime($payment['date_created'])) . - ']/[Amount ' . $payment['transaction_amount'] . - ']/[Paid ' . $payment['total_paid_amount'] . - ']/[Refund ' . $payment['amount_refunded'] . ']' - ); - } - if (sizeof($payment_ids) > 0) { - $order->update_meta_data('_Mercado_Pago_Payment_IDs', implode(', ', $payment_ids)); - } - } - $order->save(); - } else { - // Updates the type of gateway. - update_post_meta($order->id, '_used_gateway', 'WC_WooMercadoPago_BasicGateway'); - if (!empty($data['payer']['email'])) { - update_post_meta($order->id, __('Buyer email', 'woocommerce-mercadopago'), $data['payer']['email']); - } - if (!empty($data['payment_type_id'])) { - update_post_meta($order->id, __('Payment method', 'woocommerce-mercadopago'), $data['payment_type_id']); - } - if (!empty($data['payments'])) { - $payment_ids = array(); - foreach ($data['payments'] as $payment) { - $payment_ids[] = $payment['id']; - update_post_meta( - $order->id, - 'Mercado Pago - Payment ' . $payment['id'], - '[Date ' . date('Y-m-d H:i:s', strtotime($payment['date_created'])) . - ']/[Amount ' . $payment['transaction_amount'] . - ']/[Paid ' . $payment['total_paid_amount'] . - ']/[Refund ' . $payment['amount_refunded'] . ']' - ); - } - if (sizeof($payment_ids) > 0) { - update_post_meta($order->id, '_Mercado_Pago_Payment_IDs', implode(', ', $payment_ids)); - } - } - } - return $status; - } + /** + * @param $data + * @return bool|void|WC_Order|WC_Order_Refund + * @throws WC_Data_Exception + */ + public function successful_request( $data ) { + try { + $order = parent::successful_request( $data ); + $processed_status = $this->process_status_mp_business( $data, $order ); + $this->log->write_log( __FUNCTION__, 'Changing order status to: ' . parent::get_wc_status_for_mp_status( str_replace( '_', '', $processed_status ) ) ); + $this->proccessStatus( $processed_status, $data, $order ); + } catch ( Exception $e ) { + $this->setResponse( 422, null, $e->getMessage() ); + $this->log->write_log( __FUNCTION__, $e->getMessage() ); + } + } + + /** + * @param $data + * @param $order + * @return string + */ + public function process_status_mp_business( $data, $order ) { + $status = 'pending'; + $payments = $data['payments']; + if ( sizeof( $payments ) == 1 ) { + // If we have only one payment, just set status as its status + $status = $payments[0]['status']; + } elseif ( sizeof( $payments ) > 1 ) { + // However, if we have multiple payments, the overall payment have some rules... + $total_paid = 0.00; + $total_refund = 0.00; + $total = $data['shipping_cost'] + $data['total_amount']; + // Grab some information... + foreach ( $data['payments'] as $payment ) { + if ( $payment['status'] === 'approved' ) { + // Get the total paid amount, considering only approved incomings. + $total_paid += (float) $payment['total_paid_amount']; + } elseif ( $payment['status'] === 'refunded' ) { + // Get the total refounded amount. + $total_refund += (float) $payment['amount_refunded']; + } + } + if ( $total_paid >= $total ) { + $status = 'approved'; + } elseif ( $total_refund >= $total ) { + $status = 'refunded'; + } else { + $status = 'pending'; + } + } + // WooCommerce 3.0 or later. + if ( method_exists( $order, 'update_meta_data' ) ) { + // Updates the type of gateway. + $order->update_meta_data( '_used_gateway', 'WC_WooMercadoPago_BasicGateway' ); + if ( ! empty( $data['payer']['email'] ) ) { + $order->update_meta_data( __( 'Buyer email', 'woocommerce-mercadopago' ), $data['payer']['email'] ); + } + if ( ! empty( $data['payment_type_id'] ) ) { + $order->update_meta_data( __( 'Payment method', 'woocommerce-mercadopago' ), $data['payment_type_id'] ); + } + if ( ! empty( $data['payments'] ) ) { + $payment_ids = array(); + foreach ( $data['payments'] as $payment ) { + $payment_ids[] = $payment['id']; + $order->update_meta_data( + 'Mercado Pago - Payment ' . $payment['id'], + '[Date ' . date( 'Y-m-d H:i:s', strtotime( $payment['date_created'] ) ) . + ']/[Amount ' . $payment['transaction_amount'] . + ']/[Paid ' . $payment['total_paid_amount'] . + ']/[Refund ' . $payment['amount_refunded'] . ']' + ); + } + if ( sizeof( $payment_ids ) > 0 ) { + $order->update_meta_data( '_Mercado_Pago_Payment_IDs', implode( ', ', $payment_ids ) ); + } + } + $order->save(); + } else { + // Updates the type of gateway. + update_post_meta( $order->id, '_used_gateway', 'WC_WooMercadoPago_BasicGateway' ); + if ( ! empty( $data['payer']['email'] ) ) { + update_post_meta( $order->id, __( 'Buyer email', 'woocommerce-mercadopago' ), $data['payer']['email'] ); + } + if ( ! empty( $data['payment_type_id'] ) ) { + update_post_meta( $order->id, __( 'Payment method', 'woocommerce-mercadopago' ), $data['payment_type_id'] ); + } + if ( ! empty( $data['payments'] ) ) { + $payment_ids = array(); + foreach ( $data['payments'] as $payment ) { + $payment_ids[] = $payment['id']; + update_post_meta( + $order->id, + 'Mercado Pago - Payment ' . $payment['id'], + '[Date ' . date( 'Y-m-d H:i:s', strtotime( $payment['date_created'] ) ) . + ']/[Amount ' . $payment['transaction_amount'] . + ']/[Paid ' . $payment['total_paid_amount'] . + ']/[Refund ' . $payment['amount_refunded'] . ']' + ); + } + if ( sizeof( $payment_ids ) > 0 ) { + update_post_meta( $order->id, '_Mercado_Pago_Payment_IDs', implode( ', ', $payment_ids ) ); + } + } + } + return $status; + } } diff --git a/includes/notification/WC_WooMercadoPago_Notification_Webhook.php b/includes/notification/WC_WooMercadoPago_Notification_Webhook.php index 5c55f7152..88bfa2f43 100644 --- a/includes/notification/WC_WooMercadoPago_Notification_Webhook.php +++ b/includes/notification/WC_WooMercadoPago_Notification_Webhook.php @@ -1,173 +1,178 @@ mp->check_discount_campaigns($data['amount'], $data['payer'], $data['coupon_id']); - header('Content-Type: application/json'); - echo json_encode($response); - } else { - $obj = new stdClass(); - $obj->status = 404; - $obj->response = array( - 'message' => __('Please enter your email address at the billing address to use this service', 'woocommerce-mercadopago'), - 'error' => 'payer_not_found', - 'status' => 404, - 'cause' => array() - ); - header('HTTP/1.1 200 OK'); - header('Content-Type: application/json'); - echo json_encode($obj); - } - exit(0); - } else if (!isset($data['data_id']) || !isset($data['type'])) { - $this->log->write_log(__FUNCTION__, 'data_id or type not set: ' . - json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - if (!isset($data['id']) || !isset($data['topic'])) { - $this->log->write_log(__FUNCTION__, 'Mercado Pago Request failure: ' . - json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - $this->setResponse(422, null, "Mercado Pago Request failure"); - } - } else { - if ($data['type'] == 'payment') { - $access_token = $this->mp->get_access_token(); - $payment_info = $this->mp->get('/v1/payments/' . $data['data_id'], array('Authorization' => 'Bearer ' . $access_token), false); - if (!is_wp_error($payment_info) && ($payment_info['status'] == 200 || $payment_info['status'] == 201)) { - if ($payment_info['response']) { - do_action('valid_mercadopago_ipn_request', $payment_info['response']); - $this->setResponse(200, "OK", "Webhook Notification Successfull"); - } - } else { - $this->log->write_log(__FUNCTION__, 'error when processing received data: ' . json_encode($payment_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - } - } - } - $this->setResponse(422, null, "Mercado Pago Invalid Requisition"); - } + /** + * Notification Custom + */ + public function check_ipn_response() { + parent::check_ipn_response(); + $data = $_GET; + header( 'HTTP/1.1 200 OK' ); - /** - * @param $data - */ - public function successful_request($data) - { - try { - $order = parent::successful_request($data); - $status = $this->process_status_mp_business($data, $order); - $this->log->write_log(__FUNCTION__, 'Changing order status to: ' . - parent::get_wc_status_for_mp_status(str_replace('_', '', $status))); - $this->proccessStatus($status, $data, $order); - } catch (Exception $e) { - $this->log->write_log(__FUNCTION__, $e->getMessage()); - } - } + if ( isset( $data['coupon_id'] ) && ! empty( $data['coupon_id'] ) ) { + if ( isset( $data['payer'] ) && ! empty( $data['payer'] ) ) { + $response = $this->mp->check_discount_campaigns( $data['amount'], $data['payer'], $data['coupon_id'] ); + header( 'Content-Type: application/json' ); + echo json_encode( $response ); + } else { + $obj = new stdClass(); + $obj->status = 404; + $obj->response = array( + 'message' => __( 'Please enter your email address at the billing address to use this service', 'woocommerce-mercadopago' ), + 'error' => 'payer_not_found', + 'status' => 404, + 'cause' => array(), + ); + header( 'HTTP/1.1 200 OK' ); + header( 'Content-Type: application/json' ); + echo json_encode( $obj ); + } + exit( 0 ); + } elseif ( ! isset( $data['data_id'] ) || ! isset( $data['type'] ) ) { + $this->log->write_log( + __FUNCTION__, + 'data_id or type not set: ' . + json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) + ); + if ( ! isset( $data['id'] ) || ! isset( $data['topic'] ) ) { + $this->log->write_log( + __FUNCTION__, + 'Mercado Pago Request failure: ' . + json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) + ); + $this->setResponse( 422, null, 'Mercado Pago Request failure' ); + } + } else { + if ( $data['type'] == 'payment' ) { + $access_token = $this->mp->get_access_token(); + $payment_info = $this->mp->get( '/v1/payments/' . $data['data_id'], array( 'Authorization' => 'Bearer ' . $access_token ), false ); + if ( ! is_wp_error( $payment_info ) && ( $payment_info['status'] == 200 || $payment_info['status'] == 201 ) ) { + if ( $payment_info['response'] ) { + do_action( 'valid_mercadopago_ipn_request', $payment_info['response'] ); + $this->setResponse( 200, 'OK', 'Webhook Notification Successfull' ); + } + } else { + $this->log->write_log( __FUNCTION__, 'error when processing received data: ' . json_encode( $payment_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + } + } + } + $this->setResponse( 422, null, 'Mercado Pago Invalid Requisition' ); + } - /** - * @param $checkout_info - */ - public function check_and_save_customer_card($checkout_info) - { - $this->log->write_log(__FUNCTION__, 'checking info to create card: ' . json_encode($checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - $custId = null; - $token = null; - $issuer_id = null; - $payment_method_id = null; - if (isset($checkout_info['payer']['id']) && !empty($checkout_info['payer']['id'])) { - $custId = $checkout_info['payer']['id']; - } else { - return; - } - if (isset($checkout_info['metadata']['token']) && !empty($checkout_info['metadata']['token'])) { - $token = $checkout_info['metadata']['token']; - } else { - return; - } - if (isset($checkout_info['issuer_id']) && !empty($checkout_info['issuer_id'])) { - $issuer_id = (int)($checkout_info['issuer_id']); - } - if (isset($checkout_info['payment_method_id']) && !empty($checkout_info['payment_method_id'])) { - $payment_method_id = $checkout_info['payment_method_id']; - } - try { - $this->mp->create_card_in_customer($custId, $token, $payment_method_id, $issuer_id); - } catch (WC_WooMercadoPago_Exception $ex) { - $this->log->write_log(__FUNCTION__, 'card creation failed: ' . json_encode($ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - } - } + /** + * @param $data + */ + public function successful_request( $data ) { + try { + $order = parent::successful_request( $data ); + $status = $this->process_status_mp_business( $data, $order ); + $this->log->write_log( + __FUNCTION__, + 'Changing order status to: ' . + parent::get_wc_status_for_mp_status( str_replace( '_', '', $status ) ) + ); + $this->proccessStatus( $status, $data, $order ); + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, $e->getMessage() ); + } + } - /** - * @param $data - * @param $order - * @return string - */ - public function process_status_mp_business($data, $order) - { - $status = isset($data['status']) ? $data['status'] : 'pending'; - $total_paid = isset($data['transaction_details']['total_paid_amount']) ? $data['transaction_details']['total_paid_amount'] : 0.00; - $total_refund = isset($data['transaction_amount_refunded']) ? $data['transaction_amount_refunded'] : 0.00; - // WooCommerce 3.0 or later. - if (method_exists($order, 'update_meta_data')) { - // Updates the type of gateway. - $order->update_meta_data('_used_gateway', get_class($this)); - if (!empty($data['payer']['email'])) { - $order->update_meta_data(__('Buyer email', 'woocommerce-mercadopago'), $data['payer']['email']); - } - if (!empty($data['payment_type_id'])) { - $order->update_meta_data(__('Payment method', 'woocommerce-mercadopago'), $data['payment_type_id']); - } - $order->update_meta_data( - 'Mercado Pago - Payment ' . $data['id'], - '[Date ' . date('Y-m-d H:i:s', strtotime($data['date_created'])) . - ']/[Amount ' . $data['transaction_amount'] . - ']/[Paid ' . $total_paid . - ']/[Refund ' . $total_refund . ']' - ); - $order->update_meta_data('_Mercado_Pago_Payment_IDs', $data['id']); - $order->save(); - } else { - // Updates the type of gateway. - update_post_meta($order->id, '_used_gateway', get_class($this)); - if (!empty($data['payer']['email'])) { - update_post_meta($order->id, __('Buyer email', 'woocommerce-mercadopago'), $data['payer']['email']); - } - if (!empty($data['payment_type_id'])) { - update_post_meta($order->id, __('Payment method', 'woocommerce-mercadopago'), $data['payment_type_id']); - } - update_post_meta( - $order->id, - 'Mercado Pago - Payment ' . $data['id'], - '[Date ' . date('Y-m-d H:i:s', strtotime($data['date_created'])) . - ']/[Amount ' . $data['transaction_amount'] . - ']/[Paid ' . $total_paid . - ']/[Refund ' . $total_refund . ']' - ); - update_post_meta($order->id, '_Mercado_Pago_Payment_IDs', $data['id']); - } - return $status; - } + /** + * @param $checkout_info + */ + public function check_and_save_customer_card( $checkout_info ) { + $this->log->write_log( __FUNCTION__, 'checking info to create card: ' . json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + $custId = null; + $token = null; + $issuer_id = null; + $payment_method_id = null; + if ( isset( $checkout_info['payer']['id'] ) && ! empty( $checkout_info['payer']['id'] ) ) { + $custId = $checkout_info['payer']['id']; + } else { + return; + } + if ( isset( $checkout_info['metadata']['token'] ) && ! empty( $checkout_info['metadata']['token'] ) ) { + $token = $checkout_info['metadata']['token']; + } else { + return; + } + if ( isset( $checkout_info['issuer_id'] ) && ! empty( $checkout_info['issuer_id'] ) ) { + $issuer_id = (int) ( $checkout_info['issuer_id'] ); + } + if ( isset( $checkout_info['payment_method_id'] ) && ! empty( $checkout_info['payment_method_id'] ) ) { + $payment_method_id = $checkout_info['payment_method_id']; + } + try { + $this->mp->create_card_in_customer( $custId, $token, $payment_method_id, $issuer_id ); + } catch ( WC_WooMercadoPago_Exception $ex ) { + $this->log->write_log( __FUNCTION__, 'card creation failed: ' . json_encode( $ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + } + } + + /** + * @param $data + * @param $order + * @return string + */ + public function process_status_mp_business( $data, $order ) { + $status = isset( $data['status'] ) ? $data['status'] : 'pending'; + $total_paid = isset( $data['transaction_details']['total_paid_amount'] ) ? $data['transaction_details']['total_paid_amount'] : 0.00; + $total_refund = isset( $data['transaction_amount_refunded'] ) ? $data['transaction_amount_refunded'] : 0.00; + // WooCommerce 3.0 or later. + if ( method_exists( $order, 'update_meta_data' ) ) { + // Updates the type of gateway. + $order->update_meta_data( '_used_gateway', get_class( $this ) ); + if ( ! empty( $data['payer']['email'] ) ) { + $order->update_meta_data( __( 'Buyer email', 'woocommerce-mercadopago' ), $data['payer']['email'] ); + } + if ( ! empty( $data['payment_type_id'] ) ) { + $order->update_meta_data( __( 'Payment method', 'woocommerce-mercadopago' ), $data['payment_type_id'] ); + } + $order->update_meta_data( + 'Mercado Pago - Payment ' . $data['id'], + '[Date ' . date( 'Y-m-d H:i:s', strtotime( $data['date_created'] ) ) . + ']/[Amount ' . $data['transaction_amount'] . + ']/[Paid ' . $total_paid . + ']/[Refund ' . $total_refund . ']' + ); + $order->update_meta_data( '_Mercado_Pago_Payment_IDs', $data['id'] ); + $order->save(); + } else { + // Updates the type of gateway. + update_post_meta( $order->id, '_used_gateway', get_class( $this ) ); + if ( ! empty( $data['payer']['email'] ) ) { + update_post_meta( $order->id, __( 'Buyer email', 'woocommerce-mercadopago' ), $data['payer']['email'] ); + } + if ( ! empty( $data['payment_type_id'] ) ) { + update_post_meta( $order->id, __( 'Payment method', 'woocommerce-mercadopago' ), $data['payment_type_id'] ); + } + update_post_meta( + $order->id, + 'Mercado Pago - Payment ' . $data['id'], + '[Date ' . date( 'Y-m-d H:i:s', strtotime( $data['date_created'] ) ) . + ']/[Amount ' . $data['transaction_amount'] . + ']/[Paid ' . $total_paid . + ']/[Refund ' . $total_refund . ']' + ); + update_post_meta( $order->id, '_Mercado_Pago_Payment_IDs', $data['id'] ); + } + return $status; + } } diff --git a/includes/payments/WC_WooMercadoPago_BasicGateway.php b/includes/payments/WC_WooMercadoPago_BasicGateway.php index d87f3a901..bcf1906e5 100755 --- a/includes/payments/WC_WooMercadoPago_BasicGateway.php +++ b/includes/payments/WC_WooMercadoPago_BasicGateway.php @@ -7,652 +7,638 @@ /** * * WC_WooMercadoPago_BasicGateway - * */ -class WC_WooMercadoPago_BasicGateway extends WC_WooMercadoPago_PaymentAbstract -{ - const ID = 'woo-mercado-pago-basic'; - /** - * WC_WooMercadoPago_BasicGateway constructor. - * @throws WC_WooMercadoPago_Exception - */ - public function __construct() - { - $this->id = self::ID; - - if (!$this->validateSection()) { - return; - } - - $this->description = __('It offers all means of payment: credit and debit cards, cash and account money. Your customers choose whether they pay as guests or from their Mercado Pago account.', 'woocommerce-mercadopago'); - - $this->form_fields = array(); - $this->method_title = __('Mercado Pago - Checkout Pro', 'woocommerce-mercadopago'); - $this->method = $this->getOption('method', 'redirect'); - $this->title = __('Pay with the payment method you prefer', 'woocommerce-mercadopago'); - $this->method_description = $this->getMethodDescription($this->description); - $this->auto_return = $this->getOption('auto_return', 'yes'); - $this->success_url = $this->getOption('success_url', ''); - $this->failure_url = $this->getOption('failure_url', ''); - $this->pending_url = $this->getOption('pending_url', ''); - $this->installments = $this->getOption('installments', '24'); - $this->gateway_discount = $this->getOption('gateway_discount', 0); - $this->clientid_old_version = $this->getClientId(); - $this->field_forms_order = $this->get_fields_sequence(); - $this->ex_payments = $this->getExPayments(); - parent::__construct(); - $this->form_fields = $this->getFormFields('Basic'); - $this->hook = new WC_WooMercadoPago_Hook_Basic($this); - $this->notification = new WC_WooMercadoPago_Notification_IPN($this); - $this->currency_convertion = true; - } - - /** - * @param $label - * @return array - */ - public function getFormFields($label) - { - if (is_admin() && $this->isManageSection()) { - $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; - wp_enqueue_script( - 'woocommerce-mercadopago-basic-config-script', - plugins_url('../assets/js/basic_config_mercadopago'.$suffix.'.js', plugin_dir_path(__FILE__)), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - } - - if (empty($this->checkout_country)) { - $this->field_forms_order = array_slice($this->field_forms_order, 0, 7); - } - - if (!empty($this->checkout_country) && empty($this->getAccessToken()) && empty($this->getPublicKey())) { - $this->field_forms_order = array_slice($this->field_forms_order, 0, 22); - } - - $form_fields = array(); - - $form_fields['checkout_header'] = $this->field_checkout_header(); - - if (!empty($this->checkout_country) && !empty($this->getAccessToken()) && !empty($this->getPublicKey())) { - $form_fields['checkout_options_title'] = $this->field_checkout_options_title(); - $form_fields['checkout_payments_title'] = $this->field_checkout_payments_title(); - $form_fields['checkout_payments_subtitle'] = $this->field_checkout_payments_subtitle(); - $form_fields['checkout_payments_description'] = $this->field_checkout_options_description(); - $form_fields['binary_mode'] = $this->field_binary_mode(); - $form_fields['installments'] = $this->field_installments(); - $form_fields['checkout_payments_advanced_title'] = $this->field_checkout_payments_advanced_title(); - $form_fields['method'] = $this->field_method(); - $form_fields['success_url'] = $this->field_success_url(); - $form_fields['failure_url'] = $this->field_failure_url(); - $form_fields['pending_url'] = $this->field_pending_url(); - $form_fields['auto_return'] = $this->field_auto_return(); - foreach ($this->field_ex_payments() as $key => $value) { - $form_fields[$key] = $value; - } - } - - $form_fields_abs = parent::getFormFields($label); - if (count($form_fields_abs) == 1) { - return $form_fields_abs; - } - $form_fields_merge = array_merge($form_fields_abs, $form_fields); - $fields = $this->sortFormFields($form_fields_merge, $this->field_forms_order); - - return $fields; - } - - /** - * get_fields_sequence - * - * @return array - */ - public function get_fields_sequence() - { - return [ - // Necessary to run - 'title', - 'description', - // Checkout Básico. Acepta todos los medios de pago y lleva tus cobros a otro nivel - 'checkout_header', - 'checkout_steps', - // ¿En qué país vas a activar tu tienda? - 'checkout_country_title', - 'checkout_country', - 'checkout_btn_save', - // Carga tus credenciales - 'checkout_credential_title', - 'checkout_credential_mod_test_title', - 'checkout_credential_mod_test_description', - 'checkout_credential_mod_prod_title', - 'checkout_credential_mod_prod_description', - 'checkout_credential_prod', - 'checkout_credential_link', - 'checkout_credential_title_test', - 'checkout_credential_description_test', - '_mp_public_key_test', - '_mp_access_token_test', - 'checkout_credential_title_prod', - 'checkout_credential_description_prod', - '_mp_public_key_prod', - '_mp_access_token_prod', - // No olvides de homologar tu cuenta - 'checkout_homolog_title', - 'checkout_homolog_subtitle', - 'checkout_homolog_link', - // Configure Mercado Pago for WooCommerce - 'checkout_options_title', - 'mp_statement_descriptor', - '_mp_category_id', - '_mp_store_identificator', - '_mp_integrator_id', - // Advanced settings - 'checkout_advanced_settings', - '_mp_debug_mode', - '_mp_custom_domain', - // Set up the payment experience in your store - 'checkout_payments_title', - 'checkout_payments_subtitle', - 'checkout_payments_description', - 'enabled', - WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, - 'installments', - // advanced settings - 'checkout_payments_advanced_title', - 'checkout_payments_advanced_description', - 'method', - 'auto_return', - 'success_url', - 'failure_url', - 'pending_url', - 'binary_mode', - 'gateway_discount', - 'commission', - // Support session - 'checkout_support_title', - 'checkout_support_description', - 'checkout_support_description_link', - 'checkout_support_problem', - // Everything ready for the takeoff of your sales? - 'checkout_ready_title', - 'checkout_ready_description', - 'checkout_ready_description_link' - ]; - } - - /** - * @return bool - */ - public function is_available() - { - if (parent::is_available()) { - return true; - } - - if (isset($this->settings['enabled']) && $this->settings['enabled'] == 'yes') { - if ($this->mp instanceof MP) { - $accessToken = $this->mp->get_access_token(); - if (WC_WooMercadoPago_Credentials::validateCredentialsTest($this->mp ,$accessToken) == false && $this->sandbox == true) { - return false; - } - - if (WC_WooMercadoPago_Credentials::validateCredentialsProd($this->mp ,$accessToken) == false && $this->sandbox == false) { - return false; - } - return true; - } - } - return false; - } - - /** - * Get clientID when update version 3.0.17 to 4 latest - * @return string - */ - public function getClientId() { - $clientId = get_option( '_mp_client_id', ''); - if(!empty($clientId)){ - return true; - } - return false; - } - - - /** - * @return array - */ - private function getExPayments() - { - $ex_payments = array(); - $get_ex_payment_options = $this->getOption('_all_payment_methods_v0', ''); - if (!empty($get_ex_payment_options)) { - foreach ($get_ex_payment_options = explode(',', $get_ex_payment_options) as $get_ex_payment_option) { - if ($this->getOption('ex_payments_' . $get_ex_payment_option, 'yes') == 'no') { - $ex_payments[] = $get_ex_payment_option; - } - } - } - return $ex_payments; - } - - /** - * @return array - */ - public function field_checkout_header() - { - $checkout_header = array( - 'title' => sprintf( - __('Checkout Pro %s', 'woocommerce-mercadopago'), - '
+class WC_WooMercadoPago_BasicGateway extends WC_WooMercadoPago_PaymentAbstract { + + const ID = 'woo-mercado-pago-basic'; + /** + * WC_WooMercadoPago_BasicGateway constructor. + * + * @throws WC_WooMercadoPago_Exception + */ + public function __construct() { + $this->id = self::ID; + + if ( ! $this->validateSection() ) { + return; + } + + $this->description = __( 'It offers all means of payment: credit and debit cards, cash and account money. Your customers choose whether they pay as guests or from their Mercado Pago account.', 'woocommerce-mercadopago' ); + + $this->form_fields = array(); + $this->method_title = __( 'Mercado Pago - Checkout Pro', 'woocommerce-mercadopago' ); + $this->method = $this->getOption( 'method', 'redirect' ); + $this->title = __( 'Pay with the payment method you prefer', 'woocommerce-mercadopago' ); + $this->method_description = $this->getMethodDescription( $this->description ); + $this->auto_return = $this->getOption( 'auto_return', 'yes' ); + $this->success_url = $this->getOption( 'success_url', '' ); + $this->failure_url = $this->getOption( 'failure_url', '' ); + $this->pending_url = $this->getOption( 'pending_url', '' ); + $this->installments = $this->getOption( 'installments', '24' ); + $this->gateway_discount = $this->getOption( 'gateway_discount', 0 ); + $this->clientid_old_version = $this->getClientId(); + $this->field_forms_order = $this->get_fields_sequence(); + $this->ex_payments = $this->getExPayments(); + parent::__construct(); + $this->form_fields = $this->getFormFields( 'Basic' ); + $this->hook = new WC_WooMercadoPago_Hook_Basic( $this ); + $this->notification = new WC_WooMercadoPago_Notification_IPN( $this ); + $this->currency_convertion = true; + } + + /** + * @param $label + * @return array + */ + public function getFormFields( $label ) { + if ( is_admin() && $this->isManageSection() ) { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + wp_enqueue_script( + 'woocommerce-mercadopago-basic-config-script', + plugins_url( '../assets/js/basic_config_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + } + + if ( empty( $this->checkout_country ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); + } + + if ( ! empty( $this->checkout_country ) && empty( $this->getAccessToken() ) && empty( $this->getPublicKey() ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); + } + + $form_fields = array(); + + $form_fields['checkout_header'] = $this->field_checkout_header(); + + if ( ! empty( $this->checkout_country ) && ! empty( $this->getAccessToken() ) && ! empty( $this->getPublicKey() ) ) { + $form_fields['checkout_options_title'] = $this->field_checkout_options_title(); + $form_fields['checkout_payments_title'] = $this->field_checkout_payments_title(); + $form_fields['checkout_payments_subtitle'] = $this->field_checkout_payments_subtitle(); + $form_fields['checkout_payments_description'] = $this->field_checkout_options_description(); + $form_fields['binary_mode'] = $this->field_binary_mode(); + $form_fields['installments'] = $this->field_installments(); + $form_fields['checkout_payments_advanced_title'] = $this->field_checkout_payments_advanced_title(); + $form_fields['method'] = $this->field_method(); + $form_fields['success_url'] = $this->field_success_url(); + $form_fields['failure_url'] = $this->field_failure_url(); + $form_fields['pending_url'] = $this->field_pending_url(); + $form_fields['auto_return'] = $this->field_auto_return(); + foreach ( $this->field_ex_payments() as $key => $value ) { + $form_fields[ $key ] = $value; + } + } + + $form_fields_abs = parent::getFormFields( $label ); + if ( count( $form_fields_abs ) == 1 ) { + return $form_fields_abs; + } + $form_fields_merge = array_merge( $form_fields_abs, $form_fields ); + $fields = $this->sortFormFields( $form_fields_merge, $this->field_forms_order ); + + return $fields; + } + + /** + * get_fields_sequence + * + * @return array + */ + public function get_fields_sequence() { + return array( + // Necessary to run + 'title', + 'description', + // Checkout Básico. Acepta todos los medios de pago y lleva tus cobros a otro nivel + 'checkout_header', + 'checkout_steps', + // ¿En qué país vas a activar tu tienda? + 'checkout_country_title', + 'checkout_country', + 'checkout_btn_save', + // Carga tus credenciales + 'checkout_credential_title', + 'checkout_credential_mod_test_title', + 'checkout_credential_mod_test_description', + 'checkout_credential_mod_prod_title', + 'checkout_credential_mod_prod_description', + 'checkout_credential_prod', + 'checkout_credential_link', + 'checkout_credential_title_test', + 'checkout_credential_description_test', + '_mp_public_key_test', + '_mp_access_token_test', + 'checkout_credential_title_prod', + 'checkout_credential_description_prod', + '_mp_public_key_prod', + '_mp_access_token_prod', + // No olvides de homologar tu cuenta + 'checkout_homolog_title', + 'checkout_homolog_subtitle', + 'checkout_homolog_link', + // Configure Mercado Pago for WooCommerce + 'checkout_options_title', + 'mp_statement_descriptor', + '_mp_category_id', + '_mp_store_identificator', + '_mp_integrator_id', + // Advanced settings + 'checkout_advanced_settings', + '_mp_debug_mode', + '_mp_custom_domain', + // Set up the payment experience in your store + 'checkout_payments_title', + 'checkout_payments_subtitle', + 'checkout_payments_description', + 'enabled', + WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, + 'installments', + // advanced settings + 'checkout_payments_advanced_title', + 'checkout_payments_advanced_description', + 'method', + 'auto_return', + 'success_url', + 'failure_url', + 'pending_url', + 'binary_mode', + 'gateway_discount', + 'commission', + // Support session + 'checkout_support_title', + 'checkout_support_description', + 'checkout_support_description_link', + 'checkout_support_problem', + // Everything ready for the takeoff of your sales? + 'checkout_ready_title', + 'checkout_ready_description', + 'checkout_ready_description_link', + ); + } + + /** + * @return bool + */ + public function is_available() { + if ( parent::is_available() ) { + return true; + } + + if ( isset( $this->settings['enabled'] ) && $this->settings['enabled'] == 'yes' ) { + if ( $this->mp instanceof MP ) { + $accessToken = $this->mp->get_access_token(); + if ( WC_WooMercadoPago_Credentials::validateCredentialsTest( $this->mp, $accessToken ) == false && $this->sandbox == true ) { + return false; + } + + if ( WC_WooMercadoPago_Credentials::validateCredentialsProd( $this->mp, $accessToken ) == false && $this->sandbox == false ) { + return false; + } + return true; + } + } + return false; + } + + /** + * Get clientID when update version 3.0.17 to 4 latest + * + * @return string + */ + public function getClientId() { + $clientId = get_option( '_mp_client_id', '' ); + if ( ! empty( $clientId ) ) { + return true; + } + return false; + } + + + /** + * @return array + */ + private function getExPayments() { + $ex_payments = array(); + $get_ex_payment_options = $this->getOption( '_all_payment_methods_v0', '' ); + if ( ! empty( $get_ex_payment_options ) ) { + foreach ( $get_ex_payment_options = explode( ',', $get_ex_payment_options ) as $get_ex_payment_option ) { + if ( $this->getOption( 'ex_payments_' . $get_ex_payment_option, 'yes' ) == 'no' ) { + $ex_payments[] = $get_ex_payment_option; + } + } + } + return $ex_payments; + } + + /** + * @return array + */ + public function field_checkout_header() { + $checkout_header = array( + 'title' => sprintf( + __( 'Checkout Pro %s', 'woocommerce-mercadopago' ), + '
- ' . __('Accept all method of payment and take your charges to another level', 'woocommerce-mercadopago') . ' + ' . __( 'Accept all method of payment and take your charges to another level', 'woocommerce-mercadopago' ) . '

- ' . __('Turn your online store into your customers preferred payment gateway. Choose if the final payment experience will be inside or outside your store.', 'woocommerce-mercadopago') . ' + ' . __( 'Turn your online store into your customers preferred payment gateway. Choose if the final payment experience will be inside or outside your store.', 'woocommerce-mercadopago' ) . '

' - ), - 'type' => 'title', - 'class' => 'mp_title_header' - ); - return $checkout_header; - } - - /** - * @return array - */ - public function field_checkout_options_title() - { - $checkout_options_title = array( - 'title' => __('Configure Mercado Pago for WooCommerce', 'woocommerce-mercadopago'), - 'type' => 'title', - 'class' => 'mp_title_bd' - ); - return $checkout_options_title; - } - - /** - * @return array - */ - public function field_checkout_options_description() - { - $checkout_options_description = array( - 'title' => __('Enable the experience of the Checkout Pro in your online store, select the means of payment available to your customers and
define the maximum fees in which they can pay you.', 'woocommerce-mercadopago'), - 'type' => 'title', - 'class' => 'mp_small_text' - ); - return $checkout_options_description; - } - - /** - * @return array - */ - public function field_checkout_payments_title() - { - $checkout_payments_title = array( - 'title' => __('Set payment preferences in your store', 'woocommerce-mercadopago'), - 'type' => 'title', - 'class' => 'mp_title_bd' - ); - return $checkout_payments_title; - } - - /** - * @return array - */ - public function field_checkout_payments_advanced_title() - { - $checkout_payments_advanced_title = array( - 'title' => __('Advanced settings', 'woocommerce-mercadopago'), - 'type' => 'title', - 'class' => 'mp_subtitle_bd' - ); - return $checkout_payments_advanced_title; - } - - /** - * @return array - */ - public function field_method() - { - $method = array( - 'title' => __('Payment experience', 'woocommerce-mercadopago'), - 'type' => 'select', - 'description' => __('Define what payment experience your customers will have, whether inside or outside your store.', 'woocommerce-mercadopago'), - 'default' => ($this->method == 'iframe') ? 'redirect' : $this->method, - 'options' => array( - 'redirect' => __('Redirect', 'woocommerce-mercadopago'), - 'modal' => __('Modal', 'woocommerce-mercadopago') - ) - ); - return $method; - } - - /** - * @return array - */ - public function field_success_url() - { - // Validate back URL. - if (!empty($this->success_url) && filter_var($this->success_url, FILTER_VALIDATE_URL) === FALSE) { - $success_back_url_message = ' ' . - __('This seems to be an invalid URL.', 'woocommerce-mercadopago') . ' '; - } else { - $success_back_url_message = __('Choose the URL that we will show your customers when they finish their purchase.', 'woocommerce-mercadopago'); - } - $success_url = array( - 'title' => __('Success URL', 'woocommerce-mercadopago'), - 'type' => 'text', - 'description' => $success_back_url_message, - 'default' => '' - ); - return $success_url; - } - - /** - * @return array - */ - public function field_failure_url() - { - if (!empty($this->failure_url) && filter_var($this->failure_url, FILTER_VALIDATE_URL) === FALSE) { - $fail_back_url_message = ' ' . - __('This seems to be an invalid URL.', 'woocommerce-mercadopago') . ' '; - } else { - $fail_back_url_message = __('Choose the URL that we will show to your customers when we refuse their purchase. Make sure it includes a message appropriate to the situation and give them useful information so they can solve it.', 'woocommerce-mercadopago'); - } - $failure_url = array( - 'title' => __('Payment URL rejected', 'woocommerce-mercadopago'), - 'type' => 'text', - 'description' => $fail_back_url_message, - 'default' => '' - ); - return $failure_url; - } - - /** - * @return array - */ - public function field_pending_url() - { - // Validate back URL. - if (!empty($this->pending_url) && filter_var($this->pending_url, FILTER_VALIDATE_URL) === FALSE) { - $pending_back_url_message = ' ' . - __('This seems to be an invalid URL.', 'woocommerce-mercadopago') . ' '; - } else { - $pending_back_url_message = __('Choose the URL that we will show to your customers when they have a payment pending approval.', 'woocommerce-mercadopago'); - } - $pending_url = array( - 'title' => __('Payment URL pending', 'woocommerce-mercadopago'), - 'type' => 'text', - 'description' => $pending_back_url_message, - 'default' => '' - ); - return $pending_url; - } - - /** - * @return array - */ - public function field_ex_payments() - { - $ex_payments = array(); - $ex_payments_sort = array(); - - $all_payments = get_option('_checkout_payments_methods', ''); - - if (empty($all_payments)) { - return $ex_payments; - } - - $get_payment_methods = get_option('_all_payment_methods_v0', ''); - - if (!empty($get_payment_methods)) { - $get_payment_methods = explode(',', $get_payment_methods); - } - - //change type atm to ticket - foreach ($all_payments as $key => $value) { - if ($value['type'] == 'atm' || $value['type'] == 'bank_transfer') { - $all_payments[$key]['type'] = 'ticket'; - } - } - - //sort array by type asc - usort($all_payments, function($a, $b) { - if($a['type'] == $b['type']) return 0; - return $b['type'] < $a['type'] ? 1 : -1; - }); - - $count_payment = 0; - - foreach ($all_payments as $payment_method) { - if ($payment_method['type'] == 'credit_card') { - $element = array( - 'label' => $payment_method['name'], - 'id' => 'woocommerce_mercadopago_' . $payment_method['id'], - 'default' => 'yes', - 'type' => 'checkbox', - 'class' => 'online_payment_method', - 'custom_attributes' => array( - 'data-translate' => __('Select credit cards', 'woocommerce-mercadopago') - ), - ); - } elseif ($payment_method['type'] == 'debit_card' || $payment_method['type'] == 'prepaid_card') { - $element = array( - 'label' => $payment_method['name'], - 'id' => 'woocommerce_mercadopago_' . $payment_method['id'], - 'default' => 'yes', - 'type' => 'checkbox', - 'class' => 'debit_payment_method', - 'custom_attributes' => array( - 'data-translate' => __('Select debit cards', 'woocommerce-mercadopago') - ), - ); - } else { - $element = array( - 'label' => $payment_method['name'], - 'id' => 'woocommerce_mercadopago_' . $payment_method['id'], - 'default' => 'yes', - 'type' => 'checkbox', - 'class' => 'offline_payment_method', - 'custom_attributes' => array( - 'data-translate' => __('Select offline payments', 'woocommerce-mercadopago') - ), - ); - } - - - if ($count_payment == 0) { - $element['title'] = __('Payment methods', 'woocommerce-mercadopago'); - $element['desc_tip'] = __('Choose the available payment methods in your store.', 'woocommerce-mercadopago'); - } - - $count_payment++; - - if ($count_payment == count($get_payment_methods)) { - $element['description'] = __('Activate the available payment methods to your clients.', 'woocommerce-mercadopago'); - } - - $ex_payments["ex_payments_" . $payment_method['id']] = $element; - $ex_payments_sort[] = "ex_payments_" . $payment_method['id']; - } - - array_splice($this->field_forms_order, 37, 0, $ex_payments_sort); - - return $ex_payments; - } - - /** - * @return array - */ - public function field_auto_return() - { - $auto_return = array( - 'title' => __('Return to the store', 'woocommerce-mercadopago'), - 'type' => 'select', - 'default' => 'yes', - 'description' => __('Do you want your customer to automatically return to the store after payment?', 'woocommerce-mercadopago'), - 'options' => array( - 'yes' => __('Yes', 'woocommerce-mercadopago'), - 'no' => __('No', 'woocommerce-mercadopago'), - ) - ); - return $auto_return; - } - - /** - * Payment Fields - */ - public function payment_fields() - { - $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; - - //add css - wp_enqueue_style( - 'woocommerce-mercadopago-basic-checkout-styles', - plugins_url('../assets/css/basic_checkout_mercadopago' . $suffix . '.css', plugin_dir_path(__FILE__)) - ); - - //validate active payments methods - $debito = 0; - $credito = 0; - $efectivo = 0; - $method = $this->getOption('method', 'redirect'); - $tarjetas = get_option('_checkout_payments_methods', ''); - $installments = $this->getOption('installments'); - $str_cuotas = __('installments', 'woocommerce-mercadopago'); - $cho_tarjetas = array(); - - if ($installments == 1) { - $str_cuotas = __('installment', 'woocommerce-mercadopago'); - } - - //change type account_money to ticket - foreach ($tarjetas as $key => $value) { - if ($value['type'] == 'account_money') { - $all_payments[$key]['type'] = 'ticket'; - } else { - continue; - } - } - - foreach ($tarjetas as $tarjeta) { - if ($this->get_option($tarjeta['config'], '') == 'yes') { - $cho_tarjetas[] = $tarjeta; - if ($tarjeta['type'] == 'credit_card') { - $credito += 1; - } elseif ($tarjeta['type'] == 'debit_card' || $tarjeta['type'] == 'prepaid_card') { - $debito += 1; - } else { - $efectivo += 1; - } - } - } - - $parameters = array( - "debito" => $debito, - "credito" => $credito, - "efectivo" => $efectivo, - "tarjetas" => $cho_tarjetas, - "method" => $method, - "str_cuotas" => $str_cuotas, - "installments" => $installments, - "plugin_version" => WC_WooMercadoPago_Constants::VERSION, - "cho_image" => plugins_url('../assets/images/redirect_checkout.png', plugin_dir_path(__FILE__)), - "path_to_javascript" => plugins_url('../assets/js/basic-cho'.$suffix.'.js', plugin_dir_path(__FILE__)) - ); - - wc_get_template('checkout/basic_checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path()); - } - - /** - * @param $order_id - * @return array - */ - public function process_payment($order_id) - { - $order = wc_get_order($order_id); - $amount = $this->get_order_total(); - - if (method_exists($order, 'update_meta_data')) { - $order->update_meta_data('_used_gateway', get_class($this)); - - if (!empty($this->gateway_discount)) { - $discount = $amount * ($this->gateway_discount / 100); - $order->update_meta_data('Mercado Pago: discount', __('discount of', 'woocommerce-mercadopago') . ' ' . $this->gateway_discount . '% / ' . __('discount of', 'woocommerce-mercadopago') . ' = ' . $discount); - } - - if (!empty($this->commission)) { - $comission = $amount * ($this->commission / 100); - $order->update_meta_data('Mercado Pago: comission', __('fee of', 'woocommerce-mercadopago') . ' ' . $this->commission . '% / ' . __('fee of', 'woocommerce-mercadopago') . ' = ' . $comission); - } - $order->save(); - } else { - update_post_meta($order_id, '_used_gateway', get_class($this)); - - if (!empty($this->gateway_discount)) { - $discount = $amount * ($this->gateway_discount / 100); - update_post_meta($order_id,'Mercado Pago: discount', __('discount of', 'woocommerce-mercadopago') . ' ' . $this->gateway_discount . '% / ' . __('discount of', 'woocommerce-mercadopago') . ' = ' . $discount); - } - - if (!empty($this->commission)) { - $comission = $amount * ($this->commission / 100); - update_post_meta($order_id,'Mercado Pago: comission', __('fee of', 'woocommerce-mercadopago') . ' ' . $this->commission . '% / ' . __('fee of', 'woocommerce-mercadopago') . ' = ' . $comission); - } - } - - if ('redirect' == $this->method || 'iframe' == $this->method) { - $this->log->write_log(__FUNCTION__, 'customer being redirected to Mercado Pago.'); - return array( - 'result' => 'success', - 'redirect' => $this->create_preference($order) - ); - } elseif ('modal' == $this->method) { - $this->log->write_log(__FUNCTION__, 'preparing to render Checkout Pro view.'); - return array( - 'result' => 'success', - 'redirect' => $order->get_checkout_payment_url(true) - ); - } - } - - /** - * @param $order - * @return bool - */ - public function create_preference($order) - { - $preferencesBasic = new WC_WooMercadoPago_PreferenceBasic($this, $order); - $preferences = $preferencesBasic->get_preference(); - try { - $checkout_info = $this->mp->create_preference(json_encode($preferences)); - $this->log->write_log(__FUNCTION__, 'Created Preference: ' . json_encode($checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - if ($checkout_info['status'] < 200 || $checkout_info['status'] >= 300) { - $this->log->write_log(__FUNCTION__, 'mercado pago gave error, payment creation failed with error: ' . $checkout_info['response']['message']); - return false; - } elseif (is_wp_error($checkout_info)) { - $this->log->write_log(__FUNCTION__, 'wordpress gave error, payment creation failed with error: ' . $checkout_info['response']['message']); - return false; - } else { - $this->log->write_log(__FUNCTION__, 'payment link generated with success from mercado pago, with structure as follow: ' . json_encode($checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - if ($this->sandbox) { - return $checkout_info['response']['sandbox_init_point']; - } - return $checkout_info['response']['init_point']; - } - } catch (WC_WooMercadoPago_Exception $ex) { - $this->log->write_log(__FUNCTION__, 'payment creation failed with exception: ' . json_encode($ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - return false; - } - } + ), + 'type' => 'title', + 'class' => 'mp_title_header', + ); + return $checkout_header; + } + + /** + * @return array + */ + public function field_checkout_options_title() { + $checkout_options_title = array( + 'title' => __( 'Configure Mercado Pago for WooCommerce', 'woocommerce-mercadopago' ), + 'type' => 'title', + 'class' => 'mp_title_bd', + ); + return $checkout_options_title; + } + + /** + * @return array + */ + public function field_checkout_options_description() { + $checkout_options_description = array( + 'title' => __( 'Enable the experience of the Checkout Pro in your online store, select the means of payment available to your customers and
define the maximum fees in which they can pay you.', 'woocommerce-mercadopago' ), + 'type' => 'title', + 'class' => 'mp_small_text', + ); + return $checkout_options_description; + } + + /** + * @return array + */ + public function field_checkout_payments_title() { + $checkout_payments_title = array( + 'title' => __( 'Set payment preferences in your store', 'woocommerce-mercadopago' ), + 'type' => 'title', + 'class' => 'mp_title_bd', + ); + return $checkout_payments_title; + } + + /** + * @return array + */ + public function field_checkout_payments_advanced_title() { + $checkout_payments_advanced_title = array( + 'title' => __( 'Advanced settings', 'woocommerce-mercadopago' ), + 'type' => 'title', + 'class' => 'mp_subtitle_bd', + ); + return $checkout_payments_advanced_title; + } + + /** + * @return array + */ + public function field_method() { + $method = array( + 'title' => __( 'Payment experience', 'woocommerce-mercadopago' ), + 'type' => 'select', + 'description' => __( 'Define what payment experience your customers will have, whether inside or outside your store.', 'woocommerce-mercadopago' ), + 'default' => ( $this->method == 'iframe' ) ? 'redirect' : $this->method, + 'options' => array( + 'redirect' => __( 'Redirect', 'woocommerce-mercadopago' ), + 'modal' => __( 'Modal', 'woocommerce-mercadopago' ), + ), + ); + return $method; + } + + /** + * @return array + */ + public function field_success_url() { + // Validate back URL. + if ( ! empty( $this->success_url ) && filter_var( $this->success_url, FILTER_VALIDATE_URL ) === false ) { + $success_back_url_message = ' ' . + __( 'This seems to be an invalid URL.', 'woocommerce-mercadopago' ) . ' '; + } else { + $success_back_url_message = __( 'Choose the URL that we will show your customers when they finish their purchase.', 'woocommerce-mercadopago' ); + } + $success_url = array( + 'title' => __( 'Success URL', 'woocommerce-mercadopago' ), + 'type' => 'text', + 'description' => $success_back_url_message, + 'default' => '', + ); + return $success_url; + } + + /** + * @return array + */ + public function field_failure_url() { + if ( ! empty( $this->failure_url ) && filter_var( $this->failure_url, FILTER_VALIDATE_URL ) === false ) { + $fail_back_url_message = ' ' . + __( 'This seems to be an invalid URL.', 'woocommerce-mercadopago' ) . ' '; + } else { + $fail_back_url_message = __( 'Choose the URL that we will show to your customers when we refuse their purchase. Make sure it includes a message appropriate to the situation and give them useful information so they can solve it.', 'woocommerce-mercadopago' ); + } + $failure_url = array( + 'title' => __( 'Payment URL rejected', 'woocommerce-mercadopago' ), + 'type' => 'text', + 'description' => $fail_back_url_message, + 'default' => '', + ); + return $failure_url; + } + + /** + * @return array + */ + public function field_pending_url() { + // Validate back URL. + if ( ! empty( $this->pending_url ) && filter_var( $this->pending_url, FILTER_VALIDATE_URL ) === false ) { + $pending_back_url_message = ' ' . + __( 'This seems to be an invalid URL.', 'woocommerce-mercadopago' ) . ' '; + } else { + $pending_back_url_message = __( 'Choose the URL that we will show to your customers when they have a payment pending approval.', 'woocommerce-mercadopago' ); + } + $pending_url = array( + 'title' => __( 'Payment URL pending', 'woocommerce-mercadopago' ), + 'type' => 'text', + 'description' => $pending_back_url_message, + 'default' => '', + ); + return $pending_url; + } + + /** + * @return array + */ + public function field_ex_payments() { + $ex_payments = array(); + $ex_payments_sort = array(); + + $all_payments = get_option( '_checkout_payments_methods', '' ); + + if ( empty( $all_payments ) ) { + return $ex_payments; + } + + $get_payment_methods = get_option( '_all_payment_methods_v0', '' ); + + if ( ! empty( $get_payment_methods ) ) { + $get_payment_methods = explode( ',', $get_payment_methods ); + } + + // change type atm to ticket + foreach ( $all_payments as $key => $value ) { + if ( $value['type'] == 'atm' || $value['type'] == 'bank_transfer' ) { + $all_payments[ $key ]['type'] = 'ticket'; + } + } + + // sort array by type asc + usort( + $all_payments, + function( $a, $b ) { + if ( $a['type'] == $b['type'] ) { + return 0; + } + return $b['type'] < $a['type'] ? 1 : -1; + } + ); + + $count_payment = 0; + + foreach ( $all_payments as $payment_method ) { + if ( $payment_method['type'] == 'credit_card' ) { + $element = array( + 'label' => $payment_method['name'], + 'id' => 'woocommerce_mercadopago_' . $payment_method['id'], + 'default' => 'yes', + 'type' => 'checkbox', + 'class' => 'online_payment_method', + 'custom_attributes' => array( + 'data-translate' => __( 'Select credit cards', 'woocommerce-mercadopago' ), + ), + ); + } elseif ( $payment_method['type'] == 'debit_card' || $payment_method['type'] == 'prepaid_card' ) { + $element = array( + 'label' => $payment_method['name'], + 'id' => 'woocommerce_mercadopago_' . $payment_method['id'], + 'default' => 'yes', + 'type' => 'checkbox', + 'class' => 'debit_payment_method', + 'custom_attributes' => array( + 'data-translate' => __( 'Select debit cards', 'woocommerce-mercadopago' ), + ), + ); + } else { + $element = array( + 'label' => $payment_method['name'], + 'id' => 'woocommerce_mercadopago_' . $payment_method['id'], + 'default' => 'yes', + 'type' => 'checkbox', + 'class' => 'offline_payment_method', + 'custom_attributes' => array( + 'data-translate' => __( 'Select offline payments', 'woocommerce-mercadopago' ), + ), + ); + } + + if ( $count_payment == 0 ) { + $element['title'] = __( 'Payment methods', 'woocommerce-mercadopago' ); + $element['desc_tip'] = __( 'Choose the available payment methods in your store.', 'woocommerce-mercadopago' ); + } + + $count_payment++; + + if ( $count_payment == count( $get_payment_methods ) ) { + $element['description'] = __( 'Activate the available payment methods to your clients.', 'woocommerce-mercadopago' ); + } + + $ex_payments[ 'ex_payments_' . $payment_method['id'] ] = $element; + $ex_payments_sort[] = 'ex_payments_' . $payment_method['id']; + } + + array_splice( $this->field_forms_order, 37, 0, $ex_payments_sort ); + + return $ex_payments; + } + + /** + * @return array + */ + public function field_auto_return() { + $auto_return = array( + 'title' => __( 'Return to the store', 'woocommerce-mercadopago' ), + 'type' => 'select', + 'default' => 'yes', + 'description' => __( 'Do you want your customer to automatically return to the store after payment?', 'woocommerce-mercadopago' ), + 'options' => array( + 'yes' => __( 'Yes', 'woocommerce-mercadopago' ), + 'no' => __( 'No', 'woocommerce-mercadopago' ), + ), + ); + return $auto_return; + } + + /** + * Payment Fields + */ + public function payment_fields() { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + // add css + wp_enqueue_style( + 'woocommerce-mercadopago-basic-checkout-styles', + plugins_url( '../assets/css/basic_checkout_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ) + ); + + // validate active payments methods + $debito = 0; + $credito = 0; + $efectivo = 0; + $method = $this->getOption( 'method', 'redirect' ); + $tarjetas = get_option( '_checkout_payments_methods', '' ); + $installments = $this->getOption( 'installments' ); + $str_cuotas = __( 'installments', 'woocommerce-mercadopago' ); + $cho_tarjetas = array(); + + if ( $installments == 1 ) { + $str_cuotas = __( 'installment', 'woocommerce-mercadopago' ); + } + + // change type account_money to ticket + foreach ( $tarjetas as $key => $value ) { + if ( $value['type'] == 'account_money' ) { + $all_payments[ $key ]['type'] = 'ticket'; + } else { + continue; + } + } + + foreach ( $tarjetas as $tarjeta ) { + if ( $this->get_option( $tarjeta['config'], '' ) == 'yes' ) { + $cho_tarjetas[] = $tarjeta; + if ( $tarjeta['type'] == 'credit_card' ) { + $credito += 1; + } elseif ( $tarjeta['type'] == 'debit_card' || $tarjeta['type'] == 'prepaid_card' ) { + $debito += 1; + } else { + $efectivo += 1; + } + } + } + + $parameters = array( + 'debito' => $debito, + 'credito' => $credito, + 'efectivo' => $efectivo, + 'tarjetas' => $cho_tarjetas, + 'method' => $method, + 'str_cuotas' => $str_cuotas, + 'installments' => $installments, + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'cho_image' => plugins_url( '../assets/images/redirect_checkout.png', plugin_dir_path( __FILE__ ) ), + 'path_to_javascript' => plugins_url( '../assets/js/basic-cho' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + ); + + wc_get_template( 'checkout/basic_checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); + } + + /** + * @param $order_id + * @return array + */ + public function process_payment( $order_id ) { + $order = wc_get_order( $order_id ); + $amount = $this->get_order_total(); + + if ( method_exists( $order, 'update_meta_data' ) ) { + $order->update_meta_data( '_used_gateway', get_class( $this ) ); + + if ( ! empty( $this->gateway_discount ) ) { + $discount = $amount * ( $this->gateway_discount / 100 ); + $order->update_meta_data( 'Mercado Pago: discount', __( 'discount of', 'woocommerce-mercadopago' ) . ' ' . $this->gateway_discount . '% / ' . __( 'discount of', 'woocommerce-mercadopago' ) . ' = ' . $discount ); + } + + if ( ! empty( $this->commission ) ) { + $comission = $amount * ( $this->commission / 100 ); + $order->update_meta_data( 'Mercado Pago: comission', __( 'fee of', 'woocommerce-mercadopago' ) . ' ' . $this->commission . '% / ' . __( 'fee of', 'woocommerce-mercadopago' ) . ' = ' . $comission ); + } + $order->save(); + } else { + update_post_meta( $order_id, '_used_gateway', get_class( $this ) ); + + if ( ! empty( $this->gateway_discount ) ) { + $discount = $amount * ( $this->gateway_discount / 100 ); + update_post_meta( $order_id, 'Mercado Pago: discount', __( 'discount of', 'woocommerce-mercadopago' ) . ' ' . $this->gateway_discount . '% / ' . __( 'discount of', 'woocommerce-mercadopago' ) . ' = ' . $discount ); + } + + if ( ! empty( $this->commission ) ) { + $comission = $amount * ( $this->commission / 100 ); + update_post_meta( $order_id, 'Mercado Pago: comission', __( 'fee of', 'woocommerce-mercadopago' ) . ' ' . $this->commission . '% / ' . __( 'fee of', 'woocommerce-mercadopago' ) . ' = ' . $comission ); + } + } + + if ( 'redirect' == $this->method || 'iframe' == $this->method ) { + $this->log->write_log( __FUNCTION__, 'customer being redirected to Mercado Pago.' ); + return array( + 'result' => 'success', + 'redirect' => $this->create_preference( $order ), + ); + } elseif ( 'modal' == $this->method ) { + $this->log->write_log( __FUNCTION__, 'preparing to render Checkout Pro view.' ); + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_payment_url( true ), + ); + } + } + + /** + * @param $order + * @return bool + */ + public function create_preference( $order ) { + $preferencesBasic = new WC_WooMercadoPago_PreferenceBasic( $this, $order ); + $preferences = $preferencesBasic->get_preference(); + try { + $checkout_info = $this->mp->create_preference( json_encode( $preferences ) ); + $this->log->write_log( __FUNCTION__, 'Created Preference: ' . json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + if ( $checkout_info['status'] < 200 || $checkout_info['status'] >= 300 ) { + $this->log->write_log( __FUNCTION__, 'mercado pago gave error, payment creation failed with error: ' . $checkout_info['response']['message'] ); + return false; + } elseif ( is_wp_error( $checkout_info ) ) { + $this->log->write_log( __FUNCTION__, 'WordPress gave error, payment creation failed with error: ' . $checkout_info['response']['message'] ); + return false; + } else { + $this->log->write_log( __FUNCTION__, 'payment link generated with success from mercado pago, with structure as follow: ' . json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + if ( $this->sandbox ) { + return $checkout_info['response']['sandbox_init_point']; + } + return $checkout_info['response']['init_point']; + } + } catch ( WC_WooMercadoPago_Exception $ex ) { + $this->log->write_log( __FUNCTION__, 'payment creation failed with exception: ' . json_encode( $ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + return false; + } + } /** * @return string */ - public static function getId(){ - return WC_WooMercadoPago_BasicGateway::ID; - } + public static function getId() { + return self::ID; + } } diff --git a/includes/payments/WC_WooMercadoPago_CustomGateway.php b/includes/payments/WC_WooMercadoPago_CustomGateway.php index e47225355..39d508889 100755 --- a/includes/payments/WC_WooMercadoPago_CustomGateway.php +++ b/includes/payments/WC_WooMercadoPago_CustomGateway.php @@ -7,553 +7,545 @@ /** * WC_WooMercadoPago_CustomGateway */ -class WC_WooMercadoPago_CustomGateway extends WC_WooMercadoPago_PaymentAbstract -{ - const ID = 'woo-mercado-pago-custom'; - - /** - * WC_WooMercadoPago_CustomGateway constructor. - * @throws WC_WooMercadoPago_Exception - */ - public function __construct() - { - $this->id = self::ID; - - if (!$this->validateSection()) { - return; - } - - $this->description = __('Accept card payments on your website with the best possible financing and maximize the conversion of your business. With personalized checkout your customers pay without leaving your store!', 'woocommerce-mercadopago'); - $this->form_fields = array(); - $this->method_title = __('Mercado Pago - Custom Checkout', 'woocommerce-mercadopago'); - $this->title = __('Pay with debit and credit cards', 'woocommerce-mercadopago'); - $this->method_description = $this->getMethodDescription($this->description); - $this->coupon_mode = $this->getOption('coupon_mode', 'no'); - $this->field_forms_order = $this->get_fields_sequence(); - parent::__construct(); - $this->form_fields = $this->getFormFields('Custom'); - $this->customer = $this->getOrCreateCustomer(); - $this->hook = new WC_WooMercadoPago_Hook_Custom($this); - $this->notification = new WC_WooMercadoPago_Notification_Webhook($this); - $this->currency_convertion = true; - } - - /** - * @param $label - * @return array - */ - public function getFormFields($label) - { - if (is_admin() && $this->isManageSection()) { - $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; - wp_enqueue_script( - 'woocommerce-mercadopago-custom-config-script', - plugins_url('../assets/js/custom_config_mercadopago'.$suffix.'.js', plugin_dir_path(__FILE__)), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - } - - if (empty($this->checkout_country)) { - $this->field_forms_order = array_slice($this->field_forms_order, 0, 7); - } - - if (!empty($this->checkout_country) && empty($this->getAccessToken()) && empty($this->getPublicKey())) { - $this->field_forms_order = array_slice($this->field_forms_order, 0, 22); - } - - $form_fields = array(); - $form_fields['checkout_custom_header'] = $this->field_checkout_custom_header(); - if (!empty($this->checkout_country) && !empty($this->getAccessToken()) && !empty($this->getPublicKey())) { - $form_fields['checkout_custom_options_title'] = $this->field_checkout_custom_options_title(); - $form_fields['checkout_custom_payments_title'] = $this->field_checkout_custom_payments_title(); - $form_fields['checkout_payments_subtitle'] = $this->field_checkout_payments_subtitle(); - $form_fields['binary_mode'] = $this->field_binary_mode(); - $form_fields['checkout_custom_payments_advanced_title'] = $this->field_checkout_custom_payments_advanced_title(); - $form_fields['coupon_mode'] = $this->field_coupon_mode(); - } - $form_fields_abs = parent::getFormFields($label); - if (count($form_fields_abs) == 1) { - return $form_fields_abs; - } - $form_fields_merge = array_merge($form_fields_abs, $form_fields); - $fields = $this->sortFormFields($form_fields_merge, $this->field_forms_order); - - return $fields; - } - - /** - * get_fields_sequence - * @return array - */ - public function get_fields_sequence() - { - return [ - // Necessary to run - 'title', - 'description', - // Checkout de pagos con tarjetas de débito y crédito
Aceptá pagos al instante y maximizá la conversión de tu negocio - 'checkout_custom_header', - 'checkout_steps', - // ¿En qué país vas a activar tu tienda? - 'checkout_country_title', - 'checkout_country', - 'checkout_btn_save', - // Carga tus credenciales - 'checkout_credential_title', - 'checkout_credential_mod_test_title', - 'checkout_credential_mod_test_description', - 'checkout_credential_mod_prod_title', - 'checkout_credential_mod_prod_description', - 'checkout_credential_prod', - 'checkout_credential_link', - 'checkout_credential_title_test', - 'checkout_credential_description_test', - '_mp_public_key_test', - '_mp_access_token_test', - 'checkout_credential_title_prod', - 'checkout_credential_description_prod', - '_mp_public_key_prod', - '_mp_access_token_prod', - // No olvides de homologar tu cuenta - 'checkout_homolog_title', - 'checkout_homolog_subtitle', - 'checkout_homolog_link', - // Set up the payment experience in your store - 'checkout_custom_options_title', - 'mp_statement_descriptor', - '_mp_category_id', - '_mp_store_identificator', - '_mp_integrator_id', - // Advanced settings - 'checkout_advanced_settings', - '_mp_debug_mode', - '_mp_custom_domain', - // Configure the personalized payment experience in your store - 'checkout_custom_payments_title', - 'checkout_payments_subtitle', - 'enabled', - WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, - // Advanced configuration of the personalized payment experience" - 'checkout_custom_payments_advanced_title', - 'checkout_payments_advanced_description', - 'coupon_mode', - 'binary_mode', - 'gateway_discount', - 'commission', - // Support session - 'checkout_support_title', - 'checkout_support_description', - 'checkout_support_description_link', - 'checkout_support_problem', - // Everything ready for the takeoff of your sales? - 'checkout_ready_title', - 'checkout_ready_description', - 'checkout_ready_description_link' - ]; - } - - /** - * @return array - */ - public function field_checkout_custom_header() - { - $checkout_custom_header = array( - 'title' => sprintf( - __('Checkout of payments with debit and credit cards %s', 'woocommerce-mercadopago'), - '
+class WC_WooMercadoPago_CustomGateway extends WC_WooMercadoPago_PaymentAbstract { + + const ID = 'woo-mercado-pago-custom'; + + /** + * WC_WooMercadoPago_CustomGateway constructor. + * + * @throws WC_WooMercadoPago_Exception + */ + public function __construct() { + $this->id = self::ID; + + if ( ! $this->validateSection() ) { + return; + } + + $this->description = __( 'Accept card payments on your website with the best possible financing and maximize the conversion of your business. With personalized checkout your customers pay without leaving your store!', 'woocommerce-mercadopago' ); + $this->form_fields = array(); + $this->method_title = __( 'Mercado Pago - Custom Checkout', 'woocommerce-mercadopago' ); + $this->title = __( 'Pay with debit and credit cards', 'woocommerce-mercadopago' ); + $this->method_description = $this->getMethodDescription( $this->description ); + $this->coupon_mode = $this->getOption( 'coupon_mode', 'no' ); + $this->field_forms_order = $this->get_fields_sequence(); + parent::__construct(); + $this->form_fields = $this->getFormFields( 'Custom' ); + $this->customer = $this->getOrCreateCustomer(); + $this->hook = new WC_WooMercadoPago_Hook_Custom( $this ); + $this->notification = new WC_WooMercadoPago_Notification_Webhook( $this ); + $this->currency_convertion = true; + } + + /** + * @param $label + * @return array + */ + public function getFormFields( $label ) { + if ( is_admin() && $this->isManageSection() ) { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + wp_enqueue_script( + 'woocommerce-mercadopago-custom-config-script', + plugins_url( '../assets/js/custom_config_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + } + + if ( empty( $this->checkout_country ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); + } + + if ( ! empty( $this->checkout_country ) && empty( $this->getAccessToken() ) && empty( $this->getPublicKey() ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); + } + + $form_fields = array(); + $form_fields['checkout_custom_header'] = $this->field_checkout_custom_header(); + if ( ! empty( $this->checkout_country ) && ! empty( $this->getAccessToken() ) && ! empty( $this->getPublicKey() ) ) { + $form_fields['checkout_custom_options_title'] = $this->field_checkout_custom_options_title(); + $form_fields['checkout_custom_payments_title'] = $this->field_checkout_custom_payments_title(); + $form_fields['checkout_payments_subtitle'] = $this->field_checkout_payments_subtitle(); + $form_fields['binary_mode'] = $this->field_binary_mode(); + $form_fields['checkout_custom_payments_advanced_title'] = $this->field_checkout_custom_payments_advanced_title(); + $form_fields['coupon_mode'] = $this->field_coupon_mode(); + } + $form_fields_abs = parent::getFormFields( $label ); + if ( count( $form_fields_abs ) == 1 ) { + return $form_fields_abs; + } + $form_fields_merge = array_merge( $form_fields_abs, $form_fields ); + $fields = $this->sortFormFields( $form_fields_merge, $this->field_forms_order ); + + return $fields; + } + + /** + * get_fields_sequence + * + * @return array + */ + public function get_fields_sequence() { + return array( + // Necessary to run + 'title', + 'description', + // Checkout de pagos con tarjetas de débito y crédito
Aceptá pagos al instante y maximizá la conversión de tu negocio + 'checkout_custom_header', + 'checkout_steps', + // ¿En qué país vas a activar tu tienda? + 'checkout_country_title', + 'checkout_country', + 'checkout_btn_save', + // Carga tus credenciales + 'checkout_credential_title', + 'checkout_credential_mod_test_title', + 'checkout_credential_mod_test_description', + 'checkout_credential_mod_prod_title', + 'checkout_credential_mod_prod_description', + 'checkout_credential_prod', + 'checkout_credential_link', + 'checkout_credential_title_test', + 'checkout_credential_description_test', + '_mp_public_key_test', + '_mp_access_token_test', + 'checkout_credential_title_prod', + 'checkout_credential_description_prod', + '_mp_public_key_prod', + '_mp_access_token_prod', + // No olvides de homologar tu cuenta + 'checkout_homolog_title', + 'checkout_homolog_subtitle', + 'checkout_homolog_link', + // Set up the payment experience in your store + 'checkout_custom_options_title', + 'mp_statement_descriptor', + '_mp_category_id', + '_mp_store_identificator', + '_mp_integrator_id', + // Advanced settings + 'checkout_advanced_settings', + '_mp_debug_mode', + '_mp_custom_domain', + // Configure the personalized payment experience in your store + 'checkout_custom_payments_title', + 'checkout_payments_subtitle', + 'enabled', + WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, + // Advanced configuration of the personalized payment experience" + 'checkout_custom_payments_advanced_title', + 'checkout_payments_advanced_description', + 'coupon_mode', + 'binary_mode', + 'gateway_discount', + 'commission', + // Support session + 'checkout_support_title', + 'checkout_support_description', + 'checkout_support_description_link', + 'checkout_support_problem', + // Everything ready for the takeoff of your sales? + 'checkout_ready_title', + 'checkout_ready_description', + 'checkout_ready_description_link', + ); + } + + /** + * @return array + */ + public function field_checkout_custom_header() { + $checkout_custom_header = array( + 'title' => sprintf( + __( 'Checkout of payments with debit and credit cards %s', 'woocommerce-mercadopago' ), + '
- ' . __('Accept payments instantly and maximize the conversion of your business', 'woocommerce-mercadopago') . ' + ' . __( 'Accept payments instantly and maximize the conversion of your business', 'woocommerce-mercadopago' ) . '

- ' . __('Turn your online store into a secure and easy-to-use payment gateway for your customers. With personalized checkout your customers pay without leaving your store!', 'woocommerce-mercadopago') . ' + ' . __( 'Turn your online store into a secure and easy-to-use payment gateway for your customers. With personalized checkout your customers pay without leaving your store!', 'woocommerce-mercadopago' ) . '

' - ), - 'type' => 'title', - 'class' => 'mp_title_header' - ); - return $checkout_custom_header; - } - - /** - * @return array - */ - public function field_checkout_custom_options_title() - { - $checkout_custom_options_title = array( - 'title' => __('Set up the payment experience in your store', 'woocommerce-mercadopago'), - 'type' => 'title', - 'class' => 'mp_title_bd' - ); - return $checkout_custom_options_title; - } - - /** - * @return array - */ - public function field_checkout_custom_payments_title() - { - $checkout_custom_payments_title = array( - 'title' => __('Configure the personalized payment experience in your store', 'woocommerce-mercadopago'), - 'type' => 'title', - 'class' => 'mp_title_bd', - ); - return $checkout_custom_payments_title; - } - - /** - * @return array - */ - public function field_checkout_custom_payments_advanced_title() - { - $checkout_custom_payments_advanced_title = array( - 'title' => __('Advanced configuration of the personalized payment experience"', 'woocommerce-mercadopago'), - 'type' => 'title', - 'class' => 'mp_subtitle_bd' - ); - return $checkout_custom_payments_advanced_title; - } - - /** - * @param $status_detail - * @return mixed - */ - public function get_order_status($status_detail) - { - switch ($status_detail) { - case 'accredited': - return __('That’s it, payment accepted!', 'woocommerce-mercadopago'); - case 'pending_contingency': - return __('We are processing your payment. In less than an hour we will send you the result by email.', 'woocommerce-mercadopago'); - case 'pending_review_manual': - return __('We are processing your payment. In less than 2 days we will send you by email if the payment has been approved or if additional information is needed.', 'woocommerce-mercadopago'); - case 'cc_rejected_bad_filled_card_number': - return __('Check the card number.', 'woocommerce-mercadopago'); - case 'cc_rejected_bad_filled_date': - return __('Check the expiration date.', 'woocommerce-mercadopago'); - case 'cc_rejected_bad_filled_other': - return __('Check the information provided.', 'woocommerce-mercadopago'); - case 'cc_rejected_bad_filled_security_code': - return __('Check the informed security code.', 'woocommerce-mercadopago'); - case 'cc_rejected_blacklist': - return __('Your payment cannot be processed.', 'woocommerce-mercadopago'); - case 'cc_rejected_call_for_authorize': - return __('You must authorize payments for your orders.', 'woocommerce-mercadopago'); - case 'cc_rejected_card_disabled': - return __('Contact your card issuer to activate it. The phone is on the back of your card.', 'woocommerce-mercadopago'); - case 'cc_rejected_card_error': - return __('Your payment cannot be processed.', 'woocommerce-mercadopago'); - case 'cc_rejected_duplicated_payment': - return __('You have already made a payment of this amount. If you have to pay again, use another card or other method of payment.', 'woocommerce-mercadopago'); - case 'cc_rejected_high_risk': - return __('Your payment was declined. Please select another payment method. It is recommended in cash.', 'woocommerce-mercadopago'); - case 'cc_rejected_insufficient_amount': - return __('Your payment does not have sufficient funds.', 'woocommerce-mercadopago'); - case 'cc_rejected_invalid_installments': - return __('Payment cannot process the selected fee.', 'woocommerce-mercadopago'); - case 'cc_rejected_max_attempts': - return __('You have reached the limit of allowed attempts. Choose another card or other payment method.', 'woocommerce-mercadopago'); - case 'cc_rejected_other_reason': - return __('This payment method cannot process your payment.', 'woocommerce-mercadopago'); - default: - return __('This payment method cannot process your payment.', 'woocommerce-mercadopago'); - } - } - - /** - * Payment Fields - */ - public function payment_fields() - { - //add css - $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; - - wp_enqueue_style( - 'woocommerce-mercadopago-basic-checkout-styles', - plugins_url('../assets/css/basic_checkout_mercadopago' . $suffix . '.css', plugin_dir_path(__FILE__)) - ); - - $amount = $this->get_order_total(); - $discount = $amount * ($this->gateway_discount / 100); - $comission = $amount * ($this->commission / 100); - $amount = $amount - $discount + $comission; - $banner_url = $this->getOption('_mp_custom_banner'); - if (!isset($banner_url) || empty($banner_url)) { - $banner_url = $this->site_data['checkout_banner_custom']; - } - - //credit or debit card - $debit_card = array(); - $credit_card = array(); - $tarjetas = get_option('_checkout_payments_methods', ''); - - foreach ($tarjetas as $tarjeta) { - if ($tarjeta['type'] == 'credit_card') { - $credit_card[] = $tarjeta['image']; - } elseif ($tarjeta['type'] == 'debit_card' || $tarjeta['type'] == 'prepaid_card') { - $debit_card[] = $tarjeta['image']; - } - } - - try { - $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::getInstance()->ratio($this); - } catch (Exception $e) { - $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::DEFAULT_RATIO; - } - - $parameters = array( - 'amount' => $amount, - 'site_id' => $this->getOption('_site_id_v1'), - 'public_key' => $this->getPublicKey(), - 'coupon_mode' => isset($this->logged_user_email) ? $this->coupon_mode : 'no', - 'discount_action_url' => $this->discount_action_url, - 'payer_email' => esc_js($this->logged_user_email), - 'images_path' => plugins_url('../assets/images/', plugin_dir_path(__FILE__)), - 'currency_ratio' => $currency_ratio, - 'woocommerce_currency' => get_woocommerce_currency(), - 'account_currency' => $this->site_data['currency'], - 'debit_card' => $debit_card, - 'credit_card' => $credit_card, - ); - - wc_get_template('checkout/custom_checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path()); - } - - /** - * @param int $order_id - * @return array|void - */ - public function process_payment($order_id) - { - $custom_checkout = $_POST['mercadopago_custom']; - $this->log->write_log(__FUNCTION__, 'POST Custom: ' . json_encode($custom_checkout, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - $order = wc_get_order($order_id); - $amount = $this->get_order_total(); - if (method_exists($order, 'update_meta_data')) { - $order->update_meta_data('_used_gateway', get_class($this)); - - if (!empty($this->gateway_discount)) { - $discount = $amount * ($this->gateway_discount / 100); - $order->update_meta_data('Mercado Pago: discount', __('discount of', 'woocommerce-mercadopago') . ' ' . $this->gateway_discount . '% / ' . __('discount of', 'woocommerce-mercadopago') . ' = ' . $discount); - } - - if (!empty($this->commission)) { - $comission = $amount * ($this->commission / 100); - $order->update_meta_data('Mercado Pago: comission', __('fee of', 'woocommerce-mercadopago') . ' ' . $this->commission . '% / ' . __('fee of', 'woocommerce-mercadopago') . ' = ' . $comission); - } - $order->save(); - } else { - update_post_meta($order_id, '_used_gateway', get_class($this)); - if (!empty($this->gateway_discount)) { - $discount = $amount * ($this->gateway_discount / 100); - update_post_meta($order_id, 'Mercado Pago: discount', __('discount of', 'woocommerce-mercadopago') . ' ' . $this->gateway_discount . '% / ' . __('discount of', 'woocommerce-mercadopago') . ' = ' . $discount); - } - - if (!empty($this->commission)) { - $comission = $amount * ($this->commission / 100); - update_post_meta($order_id, 'Mercado Pago: comission', __('fee of', 'woocommerce-mercadopago') . ' ' . $this->commission . '% / ' . __('fee of', 'woocommerce-mercadopago') . ' = ' . $comission); - } - } - // Mexico country case. - if (!isset($custom_checkout['paymentMethodId']) || empty($custom_checkout['paymentMethodId'])) { - $custom_checkout['paymentMethodId'] = $custom_checkout['paymentMethodSelector']; - } - if ( - isset($custom_checkout['amount']) && !empty($custom_checkout['amount']) && - isset($custom_checkout['token']) && !empty($custom_checkout['token']) && - isset($custom_checkout['paymentMethodId']) && !empty($custom_checkout['paymentMethodId']) && - isset($custom_checkout['installments']) && !empty($custom_checkout['installments']) && - $custom_checkout['installments'] != -1 - ) { - $response = $this->create_preference($order, $custom_checkout); - - if (!is_array($response)) { - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - // Switch on response. - if (array_key_exists('status', $response)) { - switch ($response['status']) { - case 'approved': - WC()->cart->empty_cart(); - wc_add_notice('

' . $this->get_order_status('accredited') . '

', 'notice'); - return array( - 'result' => 'success', - 'redirect' => $order->get_checkout_order_received_url() - ); - break; - case 'pending': - // Order approved/pending, we just redirect to the thankyou page. - return array( - 'result' => 'success', - 'redirect' => $order->get_checkout_order_received_url() - ); - break; - case 'in_process': - // For pending, we don't know if the purchase will be made, so we must inform this status. - WC()->cart->empty_cart(); - wc_add_notice( - '

' . $this->get_order_status($response['status_detail']) . '

' . - '

' . - __('See your order form', 'woocommerce-mercadopago') . - '

', - 'notice' - ); - return array( - 'result' => 'success', - 'redirect' => $order->get_checkout_payment_url(true) - ); - break; - case 'rejected': - // If rejected is received, the order will not proceed until another payment try, so we must inform this status. - wc_add_notice( - '

' . __('Your payment was declined. You can try again.', - 'woocommerce-mercadopago') . '
' . - $this->get_order_status($response['status_detail']) . - '

' . - '

' . - __('Click to try again', 'woocommerce-mercadopago') . - '

', - 'error' - ); - return array( - 'result' => 'success', - 'redirect' => $order->get_checkout_payment_url(true) - ); - break; - case 'cancelled': - case 'in_mediation': - case 'charged_back': - // If we enter here (an order generating a direct [cancelled, in_mediation, or charged_back] status), - // them there must be something very wrong! - break; - default: - break; - } - } else { - // Process when fields are imcomplete. - $this->log->write_log(__FUNCTION__, 'A problem was occurred when processing your payment. Are you sure you have correctly filled all information in the checkout form? '); - - wc_add_notice('

' . __('A problem was occurred when processing your payment. Are you sure you have correctly filled all information in the checkout form?', 'woocommerce-mercadopago') . ' MERCADO PAGO: ' . - WC_WooMercadoPago_Module::get_common_error_messages($response) . '

', 'error'); - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - } else { - $this->log->write_log(__FUNCTION__, 'A problem was occurred when processing your payment. Please, try again.'); - wc_add_notice('

' . __('A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago') . '

', 'error'); - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - } - - /** - * @param $order - * @param $custom_checkout - * @return string|array - */ - protected function create_preference($order, $custom_checkout) - { - $preferencesCustom = new WC_WooMercadoPago_PreferenceCustom($this, $order, $custom_checkout); - $preferences = $preferencesCustom->get_preference(); - try { - $checkout_info = $this->mp->post('/v1/payments', json_encode($preferences)); - $this->log->write_log(__FUNCTION__, 'Preference created: ' . json_encode($checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - if ($checkout_info['status'] < 200 || $checkout_info['status'] >= 300) { - $this->log->write_log(__FUNCTION__, 'mercado pago gave error, payment creation failed with error: ' . $checkout_info['response']['message']); - return $checkout_info['response']['message']; - } elseif (is_wp_error($checkout_info)) { - $this->log->write_log(__FUNCTION__, 'wordpress gave error, payment creation failed with error: ' . $checkout_info['response']['message']); - return $checkout_info['response']['message']; - } else { - $this->log->write_log(__FUNCTION__, 'payment link generated with success from mercado pago, with structure as follow: ' . json_encode($checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - return $checkout_info['response']; - } - } catch (WC_WooMercadoPago_Exception $ex) { - $this->log->write_log(__FUNCTION__, 'payment creation failed with exception: ' . json_encode($ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - return $ex->getMessage(); - } - } - - /** - * @param $checkout_info - */ - public function check_and_save_customer_card($checkout_info) - { - $this->log->write_log(__FUNCTION__, 'checking info to create card: ' . json_encode($checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - $custId = null; - $token = null; - $issuer_id = null; - $payment_method_id = null; - if (isset($checkout_info['payer']['id']) && !empty($checkout_info['payer']['id'])) { - $custId = $checkout_info['payer']['id']; - } else { - return; - } - if (isset($checkout_info['metadata']['token']) && !empty($checkout_info['metadata']['token'])) { - $token = $checkout_info['metadata']['token']; - } else { - return; - } - if (isset($checkout_info['issuer_id']) && !empty($checkout_info['issuer_id'])) { - $issuer_id = (int) ($checkout_info['issuer_id']); - } - if (isset($checkout_info['payment_method_id']) && !empty($checkout_info['payment_method_id'])) { - $payment_method_id = $checkout_info['payment_method_id']; - } - try { - $this->mp->create_card_in_customer($custId, $token, $payment_method_id, $issuer_id); - } catch (WC_WooMercadoPago_Exception $ex) { - $this->log->write_log(__FUNCTION__, 'card creation failed: ' . json_encode($ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); - } - } - - /** - * @return bool - */ - public function is_available() - { - if (!parent::is_available()) { - return false; - } - - $_mp_access_token = get_option('_mp_access_token_prod'); - $is_prod_credentials = WC_WooMercadoPago_Credentials::validateCredentialsTest($this->mp, $_mp_access_token, null) == false; - - if ((empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off') && $is_prod_credentials) { - $this->log->write_log(__FUNCTION__, 'NO HTTPS, Custom unavailable.'); - return false; - } - - return true; - } - - /** - * @return array|mixed|null - * @throws WC_WooMercadoPago_Exception - */ - public function getOrCreateCustomer() - { - if(empty($this->mp)) - { - return null; - } - return isset($this->logged_user_email) ? $this->mp->get_or_create_customer($this->logged_user_email) : null; - } - - /** - * @return string - */ - public static function getId(){ - return WC_WooMercadoPago_CustomGateway::ID; - } + ), + 'type' => 'title', + 'class' => 'mp_title_header', + ); + return $checkout_custom_header; + } + + /** + * @return array + */ + public function field_checkout_custom_options_title() { + $checkout_custom_options_title = array( + 'title' => __( 'Set up the payment experience in your store', 'woocommerce-mercadopago' ), + 'type' => 'title', + 'class' => 'mp_title_bd', + ); + return $checkout_custom_options_title; + } + + /** + * @return array + */ + public function field_checkout_custom_payments_title() { + $checkout_custom_payments_title = array( + 'title' => __( 'Configure the personalized payment experience in your store', 'woocommerce-mercadopago' ), + 'type' => 'title', + 'class' => 'mp_title_bd', + ); + return $checkout_custom_payments_title; + } + + /** + * @return array + */ + public function field_checkout_custom_payments_advanced_title() { + $checkout_custom_payments_advanced_title = array( + 'title' => __( 'Advanced configuration of the personalized payment experience"', 'woocommerce-mercadopago' ), + 'type' => 'title', + 'class' => 'mp_subtitle_bd', + ); + return $checkout_custom_payments_advanced_title; + } + + /** + * @param $status_detail + * @return mixed + */ + public function get_order_status( $status_detail ) { + switch ( $status_detail ) { + case 'accredited': + return __( 'That’s it, payment accepted!', 'woocommerce-mercadopago' ); + case 'pending_contingency': + return __( 'We are processing your payment. In less than an hour we will send you the result by email.', 'woocommerce-mercadopago' ); + case 'pending_review_manual': + return __( 'We are processing your payment. In less than 2 days we will send you by email if the payment has been approved or if additional information is needed.', 'woocommerce-mercadopago' ); + case 'cc_rejected_bad_filled_card_number': + return __( 'Check the card number.', 'woocommerce-mercadopago' ); + case 'cc_rejected_bad_filled_date': + return __( 'Check the expiration date.', 'woocommerce-mercadopago' ); + case 'cc_rejected_bad_filled_other': + return __( 'Check the information provided.', 'woocommerce-mercadopago' ); + case 'cc_rejected_bad_filled_security_code': + return __( 'Check the informed security code.', 'woocommerce-mercadopago' ); + case 'cc_rejected_blacklist': + return __( 'Your payment cannot be processed.', 'woocommerce-mercadopago' ); + case 'cc_rejected_call_for_authorize': + return __( 'You must authorize payments for your orders.', 'woocommerce-mercadopago' ); + case 'cc_rejected_card_disabled': + return __( 'Contact your card issuer to activate it. The phone is on the back of your card.', 'woocommerce-mercadopago' ); + case 'cc_rejected_card_error': + return __( 'Your payment cannot be processed.', 'woocommerce-mercadopago' ); + case 'cc_rejected_duplicated_payment': + return __( 'You have already made a payment of this amount. If you have to pay again, use another card or other method of payment.', 'woocommerce-mercadopago' ); + case 'cc_rejected_high_risk': + return __( 'Your payment was declined. Please select another payment method. It is recommended in cash.', 'woocommerce-mercadopago' ); + case 'cc_rejected_insufficient_amount': + return __( 'Your payment does not have sufficient funds.', 'woocommerce-mercadopago' ); + case 'cc_rejected_invalid_installments': + return __( 'Payment cannot process the selected fee.', 'woocommerce-mercadopago' ); + case 'cc_rejected_max_attempts': + return __( 'You have reached the limit of allowed attempts. Choose another card or other payment method.', 'woocommerce-mercadopago' ); + case 'cc_rejected_other_reason': + return __( 'This payment method cannot process your payment.', 'woocommerce-mercadopago' ); + default: + return __( 'This payment method cannot process your payment.', 'woocommerce-mercadopago' ); + } + } + + /** + * Payment Fields + */ + public function payment_fields() { + // add css + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + wp_enqueue_style( + 'woocommerce-mercadopago-basic-checkout-styles', + plugins_url( '../assets/css/basic_checkout_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ) + ); + + $amount = $this->get_order_total(); + $discount = $amount * ( $this->gateway_discount / 100 ); + $comission = $amount * ( $this->commission / 100 ); + $amount = $amount - $discount + $comission; + $banner_url = $this->getOption( '_mp_custom_banner' ); + if ( ! isset( $banner_url ) || empty( $banner_url ) ) { + $banner_url = $this->site_data['checkout_banner_custom']; + } + + // credit or debit card + $debit_card = array(); + $credit_card = array(); + $tarjetas = get_option( '_checkout_payments_methods', '' ); + + foreach ( $tarjetas as $tarjeta ) { + if ( $tarjeta['type'] == 'credit_card' ) { + $credit_card[] = $tarjeta['image']; + } elseif ( $tarjeta['type'] == 'debit_card' || $tarjeta['type'] == 'prepaid_card' ) { + $debit_card[] = $tarjeta['image']; + } + } + + try { + $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::getInstance()->ratio( $this ); + } catch ( Exception $e ) { + $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::DEFAULT_RATIO; + } + + $parameters = array( + 'amount' => $amount, + 'site_id' => $this->getOption( '_site_id_v1' ), + 'public_key' => $this->getPublicKey(), + 'coupon_mode' => isset( $this->logged_user_email ) ? $this->coupon_mode : 'no', + 'discount_action_url' => $this->discount_action_url, + 'payer_email' => esc_js( $this->logged_user_email ), + 'images_path' => plugins_url( '../assets/images/', plugin_dir_path( __FILE__ ) ), + 'currency_ratio' => $currency_ratio, + 'woocommerce_currency' => get_woocommerce_currency(), + 'account_currency' => $this->site_data['currency'], + 'debit_card' => $debit_card, + 'credit_card' => $credit_card, + ); + + wc_get_template( 'checkout/custom_checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); + } + + /** + * @param int $order_id + * @return array|void + */ + public function process_payment( $order_id ) { + $custom_checkout = $_POST['mercadopago_custom']; + $this->log->write_log( __FUNCTION__, 'POST Custom: ' . json_encode( $custom_checkout, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + $order = wc_get_order( $order_id ); + $amount = $this->get_order_total(); + if ( method_exists( $order, 'update_meta_data' ) ) { + $order->update_meta_data( '_used_gateway', get_class( $this ) ); + + if ( ! empty( $this->gateway_discount ) ) { + $discount = $amount * ( $this->gateway_discount / 100 ); + $order->update_meta_data( 'Mercado Pago: discount', __( 'discount of', 'woocommerce-mercadopago' ) . ' ' . $this->gateway_discount . '% / ' . __( 'discount of', 'woocommerce-mercadopago' ) . ' = ' . $discount ); + } + + if ( ! empty( $this->commission ) ) { + $comission = $amount * ( $this->commission / 100 ); + $order->update_meta_data( 'Mercado Pago: comission', __( 'fee of', 'woocommerce-mercadopago' ) . ' ' . $this->commission . '% / ' . __( 'fee of', 'woocommerce-mercadopago' ) . ' = ' . $comission ); + } + $order->save(); + } else { + update_post_meta( $order_id, '_used_gateway', get_class( $this ) ); + if ( ! empty( $this->gateway_discount ) ) { + $discount = $amount * ( $this->gateway_discount / 100 ); + update_post_meta( $order_id, 'Mercado Pago: discount', __( 'discount of', 'woocommerce-mercadopago' ) . ' ' . $this->gateway_discount . '% / ' . __( 'discount of', 'woocommerce-mercadopago' ) . ' = ' . $discount ); + } + + if ( ! empty( $this->commission ) ) { + $comission = $amount * ( $this->commission / 100 ); + update_post_meta( $order_id, 'Mercado Pago: comission', __( 'fee of', 'woocommerce-mercadopago' ) . ' ' . $this->commission . '% / ' . __( 'fee of', 'woocommerce-mercadopago' ) . ' = ' . $comission ); + } + } + // Mexico country case. + if ( ! isset( $custom_checkout['paymentMethodId'] ) || empty( $custom_checkout['paymentMethodId'] ) ) { + $custom_checkout['paymentMethodId'] = $custom_checkout['paymentMethodSelector']; + } + if ( + isset( $custom_checkout['amount'] ) && ! empty( $custom_checkout['amount'] ) && + isset( $custom_checkout['token'] ) && ! empty( $custom_checkout['token'] ) && + isset( $custom_checkout['paymentMethodId'] ) && ! empty( $custom_checkout['paymentMethodId'] ) && + isset( $custom_checkout['installments'] ) && ! empty( $custom_checkout['installments'] ) && + $custom_checkout['installments'] != -1 + ) { + $response = $this->create_preference( $order, $custom_checkout ); + + if ( ! is_array( $response ) ) { + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + // Switch on response. + if ( array_key_exists( 'status', $response ) ) { + switch ( $response['status'] ) { + case 'approved': + WC()->cart->empty_cart(); + wc_add_notice( '

' . $this->get_order_status( 'accredited' ) . '

', 'notice' ); + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_order_received_url(), + ); + break; + case 'pending': + // Order approved/pending, we just redirect to the thankyou page. + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_order_received_url(), + ); + break; + case 'in_process': + // For pending, we don't know if the purchase will be made, so we must inform this status. + WC()->cart->empty_cart(); + wc_add_notice( + '

' . $this->get_order_status( $response['status_detail'] ) . '

' . + '

' . + __( 'See your order form', 'woocommerce-mercadopago' ) . + '

', + 'notice' + ); + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_payment_url( true ), + ); + break; + case 'rejected': + // If rejected is received, the order will not proceed until another payment try, so we must inform this status. + wc_add_notice( + '

' . __( + 'Your payment was declined. You can try again.', + 'woocommerce-mercadopago' + ) . '
' . + $this->get_order_status( $response['status_detail'] ) . + '

' . + '

' . + __( 'Click to try again', 'woocommerce-mercadopago' ) . + '

', + 'error' + ); + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_payment_url( true ), + ); + break; + case 'cancelled': + case 'in_mediation': + case 'charged_back': + // If we enter here (an order generating a direct [cancelled, in_mediation, or charged_back] status), + // them there must be something very wrong! + break; + default: + break; + } + } else { + // Process when fields are imcomplete. + $this->log->write_log( __FUNCTION__, 'A problem was occurred when processing your payment. Are you sure you have correctly filled all information in the checkout form? ' ); + + wc_add_notice( + '

' . __( 'A problem was occurred when processing your payment. Are you sure you have correctly filled all information in the checkout form?', 'woocommerce-mercadopago' ) . ' MERCADO PAGO: ' . + WC_WooMercadoPago_Module::get_common_error_messages( $response ) . '

', + 'error' + ); + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + } else { + $this->log->write_log( __FUNCTION__, 'A problem was occurred when processing your payment. Please, try again.' ); + wc_add_notice( '

' . __( 'A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago' ) . '

', 'error' ); + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + } + + /** + * @param $order + * @param $custom_checkout + * @return string|array + */ + protected function create_preference( $order, $custom_checkout ) { + $preferencesCustom = new WC_WooMercadoPago_PreferenceCustom( $this, $order, $custom_checkout ); + $preferences = $preferencesCustom->get_preference(); + try { + $checkout_info = $this->mp->post( '/v1/payments', json_encode( $preferences ) ); + $this->log->write_log( __FUNCTION__, 'Preference created: ' . json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + if ( $checkout_info['status'] < 200 || $checkout_info['status'] >= 300 ) { + $this->log->write_log( __FUNCTION__, 'mercado pago gave error, payment creation failed with error: ' . $checkout_info['response']['message'] ); + return $checkout_info['response']['message']; + } elseif ( is_wp_error( $checkout_info ) ) { + $this->log->write_log( __FUNCTION__, 'WordPress gave error, payment creation failed with error: ' . $checkout_info['response']['message'] ); + return $checkout_info['response']['message']; + } else { + $this->log->write_log( __FUNCTION__, 'payment link generated with success from mercado pago, with structure as follow: ' . json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + return $checkout_info['response']; + } + } catch ( WC_WooMercadoPago_Exception $ex ) { + $this->log->write_log( __FUNCTION__, 'payment creation failed with exception: ' . json_encode( $ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + return $ex->getMessage(); + } + } + + /** + * @param $checkout_info + */ + public function check_and_save_customer_card( $checkout_info ) { + $this->log->write_log( __FUNCTION__, 'checking info to create card: ' . json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + $custId = null; + $token = null; + $issuer_id = null; + $payment_method_id = null; + if ( isset( $checkout_info['payer']['id'] ) && ! empty( $checkout_info['payer']['id'] ) ) { + $custId = $checkout_info['payer']['id']; + } else { + return; + } + if ( isset( $checkout_info['metadata']['token'] ) && ! empty( $checkout_info['metadata']['token'] ) ) { + $token = $checkout_info['metadata']['token']; + } else { + return; + } + if ( isset( $checkout_info['issuer_id'] ) && ! empty( $checkout_info['issuer_id'] ) ) { + $issuer_id = (int) ( $checkout_info['issuer_id'] ); + } + if ( isset( $checkout_info['payment_method_id'] ) && ! empty( $checkout_info['payment_method_id'] ) ) { + $payment_method_id = $checkout_info['payment_method_id']; + } + try { + $this->mp->create_card_in_customer( $custId, $token, $payment_method_id, $issuer_id ); + } catch ( WC_WooMercadoPago_Exception $ex ) { + $this->log->write_log( __FUNCTION__, 'card creation failed: ' . json_encode( $ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); + } + } + + /** + * @return bool + */ + public function is_available() { + if ( ! parent::is_available() ) { + return false; + } + + $_mp_access_token = get_option( '_mp_access_token_prod' ); + $is_prod_credentials = WC_WooMercadoPago_Credentials::validateCredentialsTest( $this->mp, $_mp_access_token, null ) == false; + + if ( ( empty( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS'] == 'off' ) && $is_prod_credentials ) { + $this->log->write_log( __FUNCTION__, 'NO HTTPS, Custom unavailable.' ); + return false; + } + + return true; + } + + /** + * @return array|mixed|null + * @throws WC_WooMercadoPago_Exception + */ + public function getOrCreateCustomer() { + if ( empty( $this->mp ) ) { + return null; + } + return isset( $this->logged_user_email ) ? $this->mp->get_or_create_customer( $this->logged_user_email ) : null; + } + + /** + * @return string + */ + public static function getId() { + return self::ID; + } } diff --git a/includes/payments/WC_WooMercadoPago_PaymentAbstract.php b/includes/payments/WC_WooMercadoPago_PaymentAbstract.php index c82bf31a0..b943ff3b1 100755 --- a/includes/payments/WC_WooMercadoPago_PaymentAbstract.php +++ b/includes/payments/WC_WooMercadoPago_PaymentAbstract.php @@ -1,1419 +1,1348 @@ mp_public_key_test = $this->getOption('_mp_public_key_test'); - $this->mp_access_token_test = $this->getOption('_mp_access_token_test'); - $this->mp_public_key_prod = $this->getOption('_mp_public_key_prod'); - $this->mp_access_token_prod = $this->getOption('_mp_access_token_prod'); - $this->checkout_country = get_option('checkout_country', ''); - $this->wc_country = get_option('woocommerce_default_country', ''); - $this->mp_category_id = $this->getOption('_mp_category_id', 0); - $this->store_identificator = $this->getOption('_mp_store_identificator', 'WC-'); - $this->integrator_id = $this->getOption('_mp_integrator_id', ''); - $this->debug_mode = $this->getOption('_mp_debug_mode', 'no'); - $this->custom_domain = $this->getOption('_mp_custom_domain', ''); - $this->binary_mode = $this->getOption('binary_mode', 'no'); - $this->gateway_discount = $this->getOption('gateway_discount', 0); - $this->commission = $this->getOption('commission', 0); - $this->sandbox = $this->isTestUser(); - $this->supports = array('products', 'refunds'); - $this->icon = $this->getMpIcon(); - $this->site_data = WC_WooMercadoPago_Module::get_site_data(); - $this->log = new WC_WooMercadoPago_Log($this); - $this->mp = $this->getMpInstance(); - $this->homolog_validate = $this->getHomologValidate(); - $this->application_id = $this->getApplicationId($this->mp_access_token_prod); - $this->logged_user_email = (wp_get_current_user()->ID != 0) ? wp_get_current_user()->user_email : null; - $this->discount_action_url = get_site_url() . '/index.php/woocommerce-mercadopago/?wc-api=' . get_class($this); - } - - /** - * @return mixed - * @throws WC_WooMercadoPago_Exception - */ - public function getHomologValidate() - { - $homolog_validate = (int)get_option('homolog_validate', 0); - if (($this->isProductionMode() && !empty($this->mp_access_token_prod)) && $homolog_validate == 0) { - if ($this->mp instanceof MP) { - $homolog_validate = $this->mp->getCredentialsWrapper($this->mp_access_token_prod); - $homolog_validate = isset($homolog_validate['homologated']) && $homolog_validate['homologated'] == true ? 1 : 0; - update_option('homolog_validate', $homolog_validate, true); - return $homolog_validate; - } - return 0; - } - return 1; - } - - /** - * @return mixed|string - */ - public function getAccessToken() - { - if (!$this->isProductionMode()) { - return $this->mp_access_token_test; - } - return $this->mp_access_token_prod; - } - - /** - * @return mixed|string - */ - public function getPublicKey() - { - if (!$this->isProductionMode()) { - return $this->mp_public_key_test; - } - return $this->mp_public_key_prod; - } - - /** - * @param $key - * @param string $default - * @return mixed|string - */ - public function getOption($key, $default = '') - { - $wordpressConfigs = self::COMMON_CONFIGS; - if (in_array($key, $wordpressConfigs)) { - return get_option($key, $default); - } - - $option = $this->get_option($key, $default); - if (!empty($option)) { - return $option; - } - - return get_option($key, $default); - } - - /** - * Normalize fields in admin - */ - public function normalizeCommonAdminFields() - { - if (empty($this->mp_access_token_test) && empty($this->mp_access_token_prod)) { - if (isset($this->settings['enabled']) && $this->settings['enabled'] == 'yes') { - $this->settings['enabled'] = 'no'; - $this->disableAllPaymentsMethodsMP(); - } - } - - $changed = false; - foreach (self::COMMON_CONFIGS as $config) { - $commonOption = get_option($config); - if (isset($this->settings[$config]) && $this->settings[$config] != $commonOption) { - $changed = true; - $this->settings[$config] = $commonOption; - } - } - - if ($changed) { - update_option($this->get_option_key(), apply_filters('woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings)); - } - } - - /** - * @return bool - */ - public function validateSection() - { - if ( - isset($_GET['section']) - && !empty($_GET['section']) - && ( - $this->id !== $_GET['section']) - && !in_array($_GET['section'], self::ALLOWED_CLASSES) - ) - { - return false; - } - - return true; - } - - /** - * @return bool - */ - public function isManageSection() - { - if (!isset($_GET['section']) || ( - $this->id !== $_GET['section']) - && !in_array($_GET['section'], self::ALLOWED_CLASSES) - ) { - return false; - } - - return true; - } - - /** - * @return string - */ - public function getMpLogo() - { - return '

'; - } - - /** - * @return mixed - */ - public function getMpIcon() - { - return apply_filters('woocommerce_mercadopago_icon', plugins_url('../assets/images/mercadopago.png', plugin_dir_path(__FILE__))); - } - - /** - * @param $description - * @return string - */ - public function getMethodDescription($description) - { - return '