diff --git a/.devcontainer/devcontainer.example.json b/.devcontainer/devcontainer.example.json new file mode 100755 index 000000000..6b2c176de --- /dev/null +++ b/.devcontainer/devcontainer.example.json @@ -0,0 +1,102 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +{ + "name": "PHP", + "image": "mcr.microsoft.com/vscode/devcontainers/php:7.4", + "features": { + // https://github.com/devcontainers/features/tree/main/src/node + "ghcr.io/devcontainers/features/node:1": { + "version": "18.14.0", + "nvmVersion": "0.39.3" + } + }, + "postCreateCommand": "npm install;composer install", + "mounts": [ + { + // path in your local machine where WordPress is. + "source": "/home/{yourusername}/projects/_wordpress", + "target": "/home/vscode/_wordpress", + "type": "bind" + } + ], + "customizations": { + "vscode": { + "extensions": [ + "junstyle.php-cs-fixer", + "neilbrayfield.php-docblocker", + "bmewburn.vscode-intelephense-client" + ], + "settings": { + "php-cs-fixer.config": ".php-cs-fixer.php", + "files.eol": "\n", + "files.encoding": "utf8", + "php.suggest.basic": false, + "[smarty]": { + "editor.tabSize": 2 + }, + "[php]": { + "editor.indentSize": "tabSize", + "editor.detectIndentation": false, + "editor.defaultFormatter": "junstyle.php-cs-fixer", + "editor.insertSpaces": true, + "editor.tabSize": 4, + "editor.rulers": [ + 120 + ] + }, + "php-cs-fixer.formatHtml": true, + "php-cs-fixer.onsave": true, + "php-cs-fixer.executablePath": "${extensionPath}/php-cs-fixer.phar", + "php.validate.enable": false, + "php-docblocker.useShortNames": true, + "php-docblocker.qualifyClassNames": true, + "php-docblocker.paramDescription": true, + "php-docblocker.returnGap": true, + "php-docblocker.alignParams": true, + "php-docblocker.alignReturn": true, + "php-docblocker.gap": true, + "php-docblocker.defaultType": "string", + "php-docblocker.classTemplate": { + "message": {}, + "since": { + "content": "@since 1.0.0", + "gapAfter": true, + "gapBefore": true + }, + "link": { + "content": "@link " + } + }, + "php-docblocker.functionTemplate": { + "message": { + "gapAfter": true + }, + "since": { + "content": "@since 1.0.0" + }, + "param": { + "gapBefore": true, + "gapAfter": true + }, + "return": {} + }, + "php-docblocker.propertyTemplate": { + "message": { + "gapAfter": true + }, + "since": { + "content": "@since 1.0.0" + }, + "var": { + "content": "@var ${1:mixed}" + }, + "access": { + "access": "@access " + }, + "link": { + "content": "@link " + } + } + } + } + } +} \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..f5b3cd476 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,28 @@ +## Descreva o bug +Uma descrição clara e concisa do que é o bug. + +## Informação do sistema +- PHP: [ex. 8.1] +- WooCommerce: [ex. 7.8.0] +- WordPress: [ex. 6.1] + +## Passos para reproduzir +Etapas para reproduzir o comportamento: +1. Vá para '...' +2. Clique em '....' +3. Role para baixo até '....' +4. Ver erro + +## Comportamento esperado +Uma descrição clara e concisa do que você esperava que acontecesse. + +## Capturas de tela +Se aplicável, adicione capturas de tela para ajudar a explicar seu problema. + +## Critérios de Aceitação + + + +- [ ] Algo acontece quando uma ação é executada. +- [ ] Algo não acontece quando uma ação é executada. +- [ ] O comportamento de correção no Componente A não afeta o comportamento existente no Componente B. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..52edd67b6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,16 @@ +## Sua solicitação de recurso está relacionada a um problema? Por favor descreva +Uma descrição clara e concisa de qual é o problema. Ex. Eu sempre fico frustrado quando [...] + +## Descreva a solução que você gostaria +Uma descrição clara e concisa do que você quer que aconteça. + +## Descreva as alternativas que você considerou +Uma descrição clara e concisa de quaisquer soluções ou recursos alternativos que você considerou. + +## Critérios de Aceitação + + + +- [ ] Algo acontece quando uma ação é executada. +- [ ] Algo não acontece quando uma ação é executada. +- [ ] O comportamento de correção no Componente A não afeta o comportamento existente no Componente B. \ No newline at end of file diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 000000000..5debb644f --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,50 @@ +name: Generate new release for plugin + +on: + pull_request: + types: [ closed ] + branches: [ main ] + +env: + PLUGIN_NAME: lkn-mercadopago-woocommerce + +jobs: + release-build: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v3 + + # Add plugin files to a root directory + - name: Make plugin root directory + run: "mkdir $PLUGIN_NAME && mv -t ./$PLUGIN_NAME ./assets ./i18n ./includes ./packages ./templates *.php && ls -lah" + + # Compact plugin as .zip + - name: Archive Release + uses: thedoctor0/zip-release@master + with: + type: 'zip' + path: '${{ env.PLUGIN_NAME }}' + directory: '.' + filename: '${{ env.PLUGIN_NAME }}.zip' + exclusions: '*.git* /*node_modules/* .editorconfig' + + # Update version tag + - name: Bump version and push tag + id: tag_version + uses: mathieudutour/github-tag-action@v6.0 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + custom_tag: "6.9.3" + + # Generate new release + - name: Generate new Release + uses: ncipollo/release-action@v1 + with: + artifacts: "${{ env.PLUGIN_NAME }}.zip" + token: ${{ secrets.GITHUB_TOKEN }} + commit: "main" + draft: true + tag: ${{ steps.tag_version.outputs.new_tag }} + name: Release ${{ steps.tag_version.outputs.new_tag }} diff --git a/.github/workflows/phpcs.yml b/.github/workflows/phpcs.yml deleted file mode 100644 index a04931174..000000000 --- a/.github/workflows/phpcs.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: PHPCS - -on: [push] - -jobs: - phpcs: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: '7.4' - coverage: none - tools: composer, cs2pr - - - name: Get Composer cache directory - id: composer-cache - run: echo "::set-output name=dir::$(composer config cache-files-dir)" - - - name: Setup cache - uses: pat-s/always-upload-cache@v1.1.4 - with: - path: ${{ steps.composer-cache.outputs.dir }} - # Use the hash of composer.json as the key for your cache if you do not commit composer.lock. - # key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} - key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} - restore-keys: ${{ runner.os }}-composer- - - - name: Install dependencies - run: composer install --prefer-dist --no-suggest --no-progress - - - name: Detect coding standard violations - run: vendor/bin/phpcs -q --report=checkstyle --standard=phpcs.xml includes templates woocommerce-mercadopago.php | cs2pr --graceful-warnings diff --git a/.gitignore b/.gitignore index 10d2f2f15..66df44fed 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ node_modules .DS_Store -.vscode +.vscode/settings.json .idea .idea/ /vendor/ woocommerce-mercadopago.zip +.devcontainer/devcontainer.json \ No newline at end of file diff --git a/.vscode/.php-cs-fixer.php b/.vscode/.php-cs-fixer.php new file mode 100755 index 000000000..05c65b3aa --- /dev/null +++ b/.vscode/.php-cs-fixer.php @@ -0,0 +1,89 @@ +setRules(array( + 'short_scalar_cast' => true, + 'visibility_required' => true, + 'elseif' => true, + 'no_superfluous_elseif' => true, + 'align_multiline_comment' => array('comment_type' => 'phpdocs_like'), + 'array_syntax' => array('syntax' => 'long'), + 'binary_operator_spaces' => true, + 'blank_line_after_opening_tag' => false, + 'braces' => array( + 'position_after_functions_and_oop_constructs' => 'same', + ), + 'cast_spaces' => true, + 'class_attributes_separation' => array( + 'elements' => array( + 'const' => 'one', + 'method' => 'one', + 'property' => 'only_if_meta', + ), + ), + 'class_definition' => array('single_line' => true), + 'class_keyword_remove' => true, + 'concat_space' => array('spacing' => 'one'), + 'control_structure_continuation_position' => true, + 'dir_constant' => true, + 'fully_qualified_strict_types' => true, + 'global_namespace_import' => true, + 'include' => true, + 'list_syntax' => array('syntax' => 'long'), + 'lowercase_cast' => true, + 'lowercase_static_reference' => true, + 'magic_constant_casing' => true, + 'magic_method_casing' => true, + 'method_chaining_indentation' => true, + 'native_constant_invocation' => true, + 'native_function_casing' => true, + 'native_function_type_declaration_casing' => true, + 'new_with_braces' => true, + 'no_alternative_syntax' => array('fix_non_monolithic_code' => false), + 'no_blank_lines_after_class_opening' => false, + 'no_blank_lines_after_phpdoc' => true, + 'no_empty_comment' => true, + 'no_extra_blank_lines' => array( + 'tokens' => array( + 'continue', + 'extra', + 'parenthesis_brace_block', + 'square_brace_block', + 'throw', + 'use', + ), + ), + 'no_spaces_around_offset' => array('positions' => array('outside')), + 'no_spaces_inside_parenthesis' => false, + 'not_operator_with_space' => true, + // 'not_operator_with_successor_space' => true, + 'phpdoc_tag_casing' => true, + 'phpdoc_types_order' => array( + 'null_adjustment' => 'always_last', + 'sort_algorithm' => 'none', + ), + 'single_line_throw' => true, + 'strict_param' => true, + 'trim_array_spaces' => true, + // WPCS 3.0 proposal, yoda style is optional + 'yoda_style' => array( + 'always_move_variable' => true, + 'equal' => true, + 'identical' => true, + 'always_move_variable' => true, + ), + 'modernize_types_casting' => true, + 'void_return' => true, + 'logical_operators' => true, + 'array_indentation' => true, + 'whitespace_after_comma_in_array' => array( + 'ensure_single_space' => true, + ), + 'method_argument_space' => array( + 'keep_multiple_spaces_after_comma' => false, + 'on_multiline' => 'ensure_fully_multiline', + ), + )) + ->setIndent(' ') + ->setLineEnding("\n") + ->setRiskyAllowed(true); diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100755 index 000000000..08cdf1237 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,10 @@ +{ + "recommendations": [ + "mehedidracula.php-namespace-resolver", + "eamodio.gitlens", + "vivaxy.vscode-conventional-commits", + "ms-vscode-remote.remote-containers", + "yzhang.markdown-all-in-one", + "standard.vscode-standard" + ] +} \ No newline at end of file diff --git a/.vscode/settings.example.json b/.vscode/settings.example.json new file mode 100755 index 000000000..2ee23289d --- /dev/null +++ b/.vscode/settings.example.json @@ -0,0 +1,7 @@ +{ + "intelephense.environment.phpVersion": "8.1", + // For autocomplete + "intelephense.environment.includePaths": [ + "/home/vscode/_wordpress" // This path is a bind mount that comes from devcontainer.json. + ] +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 53be91c1d..b427436f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [6.9.3] - 2023-08-10 +### Fixed +- Updated the link to obtain credentials on the developer site +- Resolved warning related to the missing return type of the function AbstractCollection::getIterator() +### Changed +- Improved default activation of Credits Gateway +- Removed sending of product details to Payment Gateway + ## [6.9.2] - 2023-06-23 ### Fixed - Fixed bug that was causing the admin panel to become unresponsive or inaccessible diff --git a/README.md b/README.md index d122f0916..0b60c03c1 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,9 @@ -

MercadoPago +

Link Nacional

-

-version -download -license -

+# This is a unnoficial plugin mantained by Link Nacional -The Mercado Pago payments for WooCommerce plugin allows you to expand the functionalities of your online store and offer a unique payment experience for your customers. +The Link Nacional Mercado Pago payments for WooCommerce plugin allows you to expand the functionalities of your online store and offer a unique payment experience for your customers.
diff --git a/assets/css/index.php b/assets/css/index.php index a33130a51..891711d6d 100644 --- a/assets/css/index.php +++ b/assets/css/index.php @@ -1,14 +1,5 @@ enabled." msgstr "O checkout está ativo." #: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:262, -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:921 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:934 msgid "The checkout is disabled." msgstr "O checkout está inativo." @@ -353,7 +347,7 @@ msgstr "" "Pago." #: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:298, -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:269 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:348 msgid "Advanced settings" msgstr "Configuração Avançada" @@ -462,120 +456,119 @@ msgstr "O comprador não será redirecionado automaticamente à loja." msgid "Available payment methods" msgstr "Meios de pagamento disponíveis" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:535, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:521, -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:426, -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:411, -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:698, -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:418, -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:404, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:434, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:419, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:520, +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:441, +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:403, +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:418, #: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:174, #: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:172 msgid "discount of" msgstr "desconto de" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:541, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:527, -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:432, -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:417, -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:704, -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:691, -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:424, -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:410, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:440, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:425, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:526, +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:447, +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:683, +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:409, +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:424, #: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:176 msgid "fee of" msgstr "taxa de" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:641, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:667, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:719 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:626, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:652, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:704 msgid "Easy login" msgstr "Entre fácil" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:642, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:668, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:720 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:627, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:653, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:705 msgid "Log in with the same email and password you use in Mercado Libre." msgstr "Inicie sessão com seu mesmo e-mail e senha do Mercado Livre." -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:649, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:675, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:693, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:727 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:634, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:660, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:678, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:712 msgid "Quick payments" msgstr "Pague rápido" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:650 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:635 msgid "Use your saved cards, Pix or available balance." msgstr "Use seus cartões salvos, Pix ou saldo disponível." -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:657, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:683 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:642, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:668 msgid "Protected purchases" msgstr "Proteja sua compra" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:658, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:684 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:643, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:669 msgid "Get your money back in case you don't receive your product." msgstr "Receba o dinheiro de volta se você não receber o produto." -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:676 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:661 msgid "Use your available Mercado Pago Wallet balance or saved cards." msgstr "Use seu saldo disponível no Mercado Pago Wallet ou cartões salvos." -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:694, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:728 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:679, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:713 msgid "Use your available money or saved cards." msgstr "Use seu dinheiro disponível e cartões salvos." -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:701, -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:735 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:686, +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:720 msgid "Installments option" msgstr "Use parcelas" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:702 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:687 msgid "Pay with or without a credit card." msgstr "Pague com ou sem cartão de crédito." -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:709 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:694 msgid "Reliable purchases" msgstr "Compre com confiança" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:710 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:695 msgid "Get help if you have a problem with your purchase." msgstr "Receba ajuda se tiver algum problema com sua compra." -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:736 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:721 msgid "Interest-free installments with selected banks." msgstr "Parcelas sem juros em bancos selecionados." -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:30, -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:31, -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:245 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:42, +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:43, +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:324 msgid "Installments without card" msgstr "Parcelado sem cartão" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:32 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:44 msgid "Customers who buy on spot and pay later in up to 12 installments" msgstr "Clientes compram na hora e pagam depois em até 12x" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:40 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:54 msgid "Mercado Pago - Installments without card" msgstr "Mercado Pago - Parcelamento sem cartão" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:42 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:56 msgid "Checkout without card" msgstr "Parcelado sem cartão com Mercado Pago" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:182 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:112, +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:288 +msgid "Banner on the product page | Computer version" +msgstr "Informativo na página do produto | Versão para computador" + +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:113 +msgid "Banner on the product page | Cellphone version" +msgstr "Informativo na página do produto | Versão para celular" + +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:249 msgid "Activate installments without card in your store checkout " msgstr "Ativar parcelamento sem cartão no checkout da loja " -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:183 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:250 msgid "" "Offer the option to pay in installments without card directly from your " "store's checkout." @@ -583,34 +576,46 @@ msgstr "" "Ofereça a opção de pagamento parcelado sem cartão através do checkout da sua " "loja." -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:187 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:254 msgid "" "Payment in installments without card in the store checkout is active" msgstr "Parcelamento sem cartão no checkout da loja está ativo" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:188 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:255 msgid "" "Payment in installments without card in the store checkout is inactive" msgstr "Parcelamento sem cartão no checkout da loja está desativado" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:205 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:273 msgid "Checkout visualization" msgstr "Visualização no checkout" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:206, -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:367 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:274, +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:290 msgid "Check below how this feature will be displayed to your customers:" msgstr "Confira como aparecerá este recurso para seus clientes:" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:207 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:275 msgid "Checkout Preview" msgstr "Visualização no checkout" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:208 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:276 msgid "PREVIEW" msgstr "PRÉ-VISUALIZAÇÃO" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:249 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:286 +msgid "Computer" +msgstr "Computador" + +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:287 +msgid "Mobile" +msgstr "Celular" + +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:289 +msgid "Component visualization" +msgstr "Visualização do componente" + +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:328 msgid "" "Reach millions of buyers by offering Mercado Credito as a payment method. " "Our flexible payment options give your customers the possibility to buy " @@ -623,17 +628,17 @@ msgstr "" "clientes a possibilidade de comprar o que querem hoje em até 12x sem ter que " "usar cartão." -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:252 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:331 msgid "" "For your business, the approval of the purchase is immediate and guaranteed." msgstr "Para o seu negócio, a aprovação da compra é imediata e está garantida." -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:311 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:394 msgid "" "Inform your customers about the option of paying in installments without card" msgstr "Informe aos seus clientes sobre a opção de parcelamento sem cartão" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:314 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:397 msgid "" "By activating the installments without card component, you increase " "your chances of selling." @@ -641,35 +646,14 @@ msgstr "" "Ativando o componente de parcelamento sem cartão, você aumentará suas " "possibilidades de venda. " -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:316 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:399 msgid "The installments without card component is active." msgstr "O componente de parcelamento sem cartão está ativo." -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:317 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:400 msgid "The installments without card component is inactive." msgstr "O componente de parcelamento sem cartão está desativado." -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:355, -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:365 -msgid "Banner on the product page | Computer version" -msgstr "Informativo na página do produto | Versão para computador" - -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:356 -msgid "Banner on the product page | Cellphone version" -msgstr "Informativo na página do produto | Versão para celular" - -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:363 -msgid "Computer" -msgstr "Computador" - -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:364 -msgid "Mobile" -msgstr "Celular" - -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:366 -msgid "Component visualization" -msgstr "Visualização do componente" - #: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:41, #: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:42, #: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:52 @@ -705,11 +689,11 @@ msgid "Transparent checkout for credit cards is disabled." msgstr "" "O checkout transparente para cartões de crédito está desativado." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:191 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:184 msgid "Installments Fees" msgstr "Taxas de parcelamento" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:192 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:185 msgid "" "Set installment fees and whether they will be charged from the store or from " "the buyer." @@ -717,15 +701,15 @@ msgstr "" "Configure as taxas de parcelamento e se elas serão cobradas da loja ou do " "comprador." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:193 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:186 msgid "Set fees" msgstr "Configurar taxas" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:218 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:211 msgid "Transparent Checkout | Credit card " msgstr "Checkout Transparente | Cartão de Crédito " -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:222 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:215 msgid "" "With the Transparent Checkout, you can sell inside your store environment, " "without redirection and with the security from Mercado Pago." @@ -733,15 +717,15 @@ msgstr "" "Com o Checkout Transparente, você consegue vender dentro do ambiente da sua " "loja, sem redirecionamento, com toda a segurança do Mercado Pago." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:240 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:233 msgid "Advanced configuration of the personalized payment experience" msgstr "Configuração Avançada" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:254 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:247 msgid "Payments via Mercado Pago account" msgstr "Pagamentos via conta Mercado Pago" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:255 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:248 msgid "" "Your customers pay faster with saved cards, money balance or other available " "methods in their Mercado Pago accounts." @@ -749,23 +733,23 @@ msgstr "" "Seus clientes pagam mais rapidamente com cartões salvos, saldo ou outros " "meios disponíveis nas contas MP deles." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:259 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:252 msgid "Payments via Mercado Pago accounts are active." msgstr "Pagamentos via conta Mercado Pago estão ativos." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:260 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:253 msgid "Payments via Mercado Pago accounts are inactive." msgstr "Pagamentos via conta Mercado Pago estão desativados." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:279 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:272 msgid "Check an example of how it will appear in your store:" msgstr "Confira um exemplo de como vai aparecer na loja:" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:310 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:303 msgid "That’s it, payment accepted!" msgstr "Pronto, aceitamos seu pagamento!" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:312 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:305 msgid "" "We are processing your payment. In less than an hour we will send you the " "result by email." @@ -773,7 +757,7 @@ msgstr "" "Estamos processando seu pagamento. Em menos de uma hora você será notificado " "por email." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:314 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:307 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 " @@ -783,31 +767,31 @@ msgstr "" "notificado por email se o pagamento foi aprovado ou se são necessárias " "informações adicionais." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:316 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:309 msgid "Check the card number." msgstr "Verifique o número do cartão." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:318 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:311 msgid "Check the expiration date." msgstr "Verifique a data de expiração." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:320 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:313 msgid "Check the information provided." msgstr "Verifique as informações preenchidas." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:322 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:315 msgid "Check the informed security code." msgstr "Verifique o código de segurança informado." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:325 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:318 msgid "Your payment cannot be processed." msgstr "Não foi possível processar seu pagamento." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:327 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:320 msgid "You must authorize payments for your orders." msgstr "Você deve autorizar o pagamento dos seus pedidos." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:329 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:322 msgid "" "Contact your card issuer to activate it. The phone is on the back of your " "card." @@ -815,7 +799,7 @@ msgstr "" "Contacte o emissor de seu cartão para ativá-lo. O telefone está no verso do " "seu cartão." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:331 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:324 msgid "" "You have already made a payment of this amount. If you have to pay again, " "use another card or other method of payment." @@ -823,7 +807,7 @@ msgstr "" "Você já realizou o pagamento para esse valor. Se precisa pagar novamente, " "use outro cartão ou outro método de pagamento." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:333 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:326 msgid "" "Your payment was declined. Please select another payment method. It is " "recommended in cash." @@ -831,15 +815,15 @@ msgstr "" "Seu pagamento foi rejeitado. Escolha outro método de pagamento. Recomenda-se " "dinheiro." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:335 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:328 msgid "Your payment does not have sufficient funds." msgstr "Seu pagamento não possui saldo suficiente." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:337 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:330 msgid "Payment cannot process the selected fee." msgstr "Seu pagamento não pode processar o parcelamento selecionado." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:339 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:332 msgid "" "You have reached the limit of allowed attempts. Choose another card or other " "payment method." @@ -847,55 +831,55 @@ msgstr "" "Você atingiu o limite de tentativas permitidas. Escolha outro cartão ou " "outro método de pagamento." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:341, +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:334, #: ../../includes/module/preference/class-wc-woomercadopago-preference-abstract.php:204 msgid "This payment method cannot process your payment." msgstr "Este método de pagamento não pôde processar o seu pagamento." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:396 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:389 msgid "Credit cards" msgstr "Cartões de crédito" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:397 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:390 msgid "Up to " msgstr "ATÉ " -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:397 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:390 msgid " installments" msgstr " x" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:404 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:397 msgid "Debit cards" msgstr "Cartões de débito" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:447, -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:448, -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:480, -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:481, +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:440, +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:441, +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:473, +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:474, #: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:401, #: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:402, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:562, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:563 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:543, +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:544 msgid "A problem was occurred when processing your payment. Please, try again." msgstr "" "Ocorreu um problema ao processar seu pagamento. Por favor, tente novamente." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:577 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:570 msgid "See your order form" msgstr "Ver o resumo do pedido" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:588 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:581 msgid "Your payment was declined. You can try again." msgstr "Seu pagamento foi rejeitado. Você pode tentar novamente." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:595, +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:588, #: ../../includes/payments/hooks/class-wc-woomercadopago-hook-basic.php:95, #: ../../includes/payments/hooks/class-wc-woomercadopago-hook-credits.php:93 msgid "Click to try again" msgstr "Clique para tentar novamente" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:617, -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:618 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:610, +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:611 msgid "" "A problem was occurred when processing your payment. Are you sure you have " "correctly filled all information in the checkout form?" @@ -903,15 +887,15 @@ msgstr "" "Ocorreu um problema ao processar seu pagamento. Tem certeza de que preencheu " "corretamente todas as informações no formulário de checkout?" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:642 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:635 msgid "Represents the installment fee charged by Mercado Pago." msgstr "Representa a taxa de parcelamento cobrada pelo Mercado Pago." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:643 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:636 msgid "Mercado Pago Installment Fee:" msgstr "Taxa de Parcelamento do Mercado Pago:" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:648 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:641 msgid "" "Represents the total purchase plus the installment fee charged by Mercado " "Pago." @@ -919,7 +903,7 @@ msgstr "" "Representa a soma do total do pedido e da taxa de parcelamento cobrada pelo " "Mercado Pago." -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:649 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:642 msgid "Mercado Pago Total:" msgstr "Total no Mercado Pago:" @@ -928,55 +912,55 @@ msgid "Configure your credentials to enable Mercado Pago payment methods." msgstr "" "Complete suas credenciais para habilitar os meios de pagamento Mercado Pago." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:773 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:786 msgid "Title in the store Checkout" msgstr "Título no checkout da loja" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:775 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:788 msgid "Change the display text in Checkout, maximum characters: 85" msgstr "" "É possível modificar o título dentro da sua loja. Caracteres máximos: 85" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:777 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:790 msgid "The text inserted here will not be translated to other languages" msgstr "O texto inserido aqui não será traduzido para outras línguas" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:791 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:804 msgid "Description" msgstr "Descrição" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:828, -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:840, +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:841, +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:853, #: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:347 msgid "Important! To sell you must enter your credentials." msgstr "Importante! Para vender você deve inserir suas credenciais." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:829 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:842 msgid "You must enter production credentials." msgstr "É necessário inserir as credenciais de produção." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:830 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:843 msgid "Enter credentials" msgstr "Inserir credenciais" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:840 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:853 msgid "Mercado Pago Plugin general settings" msgstr "Configurações gerais do plugin do Mercado Pago" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:841 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:854 msgid "" "Set the deadlines and fees, test your store or access the Plugin manual." msgstr "Ajuste taxas e prazos, teste sua loja ou acesso o manual do plugin." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:842 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:855 msgid "Go to Settings" msgstr "Ir para Configurações" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:866 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:879 msgid "Activate your credentials to be able to sell" msgstr "Ative suas credenciais para conseguir vender" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:867 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:880 msgid "" "Credentials are codes that you must enter to enable sales. Go below on " "Activate Credentials. On the next screen, use again the Activate Credentials " @@ -986,42 +970,42 @@ msgstr "" "abaixo em Ativar credencias. Na tela seguinte, vá novamente no botão Ativar " "credenciais e preencha os campos com os dados pedidos." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:868 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:881 msgid "Activate credentials" msgstr "Ativar credenciais" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:916 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:929 msgid "By disabling it, you will disable all payment methods of this checkout." msgstr "" "Ao desativar, você desabilita todos os meios de pagamento deste checkout." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1029 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:989 msgid "Basic Configuration" msgstr "Configuração Básica" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1042 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1002 msgid "Discount coupons" msgstr "Cupons de desconto" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1045 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1005 msgid "Will you offer discount coupons to customers who buy with Mercado Pago?" msgstr "" "Você vai oferecer cupons de desconto para os clientes que comprarem com " "Mercado Pago?" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1047 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1007 msgid "Discount coupons is active." msgstr "Cupons de desconto estão habilitados." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1048 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1008 msgid "Discount coupons is disabled." msgstr "Cupons de desconto estão desabilitados." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1060 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1020 msgid "Automatic decline of payments without instant approval" msgstr "Recusa automática de pagamentos sem aprovação instantânea" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1061 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1021 msgid "" "Enable it if you want to automatically decline payments that are not " "instantly approved by banks or other institutions. " @@ -1029,19 +1013,19 @@ msgstr "" "Ative se quiser recusar automaticamente pagamentos que não são aprovados " "instantaneamente por bancos ou outros adquirentes. " -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1065 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1025 msgid "Pending payments will be automatically declined." msgstr "Pagamentos pendentes serão recusados automaticamente." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1066 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1026 msgid "Pending payments will not be automatically declined." msgstr "Pagamentos pendentes não serão recusados automaticamente." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1078 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1038 msgid "Discount in Mercado Pago Checkouts" msgstr "Desconto nos checkouts Mercado Pago" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1081 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1041 msgid "" "Choose a percentage value that you want to discount your customers for " "paying with Mercado Pago." @@ -1049,16 +1033,16 @@ msgstr "" "Selecione um valor percentual que quiser descontar para seus clientes por " "pagar com Mercado Pago." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1082, -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1103 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1042, +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1063 msgid "Activate and show this information on Mercado Pago Checkout" msgstr "Ativar e mostrar essa informação no checkout Mercado Pago" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1099 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1059 msgid "Commission in Mercado Pago Checkouts" msgstr "Comissão nos checkouts Mercado Pago" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1102 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1062 msgid "" "Choose an additional percentage value that you want to charge as commission " "to your customers for paying with Mercado Pago." @@ -1066,19 +1050,19 @@ msgstr "" "Selecione um valor percentual adicional que quiser cobrar como tarifa dos " "seus clientes por pagar com Mercado Pago." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1139 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1083 msgid "Convert Currency" msgstr "Converter moeda" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1144 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1088 msgid "Currency convertion is enabled." msgstr "Conversão de moeda está ativa." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1145 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1089 msgid "Currency convertion is disabled." msgstr "Conversão de moeda está inativa." -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1262 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1206 msgid "" "Edit these advanced fields only when you want to modify the preset values." msgstr "" @@ -1266,13 +1250,13 @@ msgstr "Criamos uma página que explica seu funcionamento e vantagens." msgid "Find out more about Pix" msgstr "Saber mais sobre o Pix" -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:493 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:470 msgid "A problem occurred when processing your payment. Please try again." msgstr "" "Um problema ocorreu ao processar seu pagamento. Por favor, tente novamente." -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:478, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:547 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:455, +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:528 msgid "" "A problem occurred when processing your payment. Are you sure you have " "correctly filled in all the information on the checkout form?" @@ -1280,16 +1264,16 @@ msgstr "" "Um problema ocorreu ao processar seu pagamento. Você tem certeza que " "preencheu corretamente todos os campos do formulário do checkout?" -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:456, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:522 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:433, +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:503 msgid "The customer has not paid yet." msgstr "Cliente ainda não pagou." -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:461 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:438 msgid "Now you just need to pay with Pix to finalize your purchase." msgstr "Agora é só pagar com o Pix para finalizar sua compra." -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:462 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:439 msgid "" "Scan the QR code below or copy and paste the code into your bank's " "application." @@ -1297,7 +1281,7 @@ msgstr "" "Escaneie o código QR abaixo ou copie e cole o código no aplicativo do seu " "banco." -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:563 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:540 msgid "" "Please note that to receive payments via Pix at our checkout, you must have " "a Pix key registered in your Mercado Pago account." @@ -1305,11 +1289,11 @@ msgstr "" "Lembre-se de que para receber pagamentos via PIX em nosso checkout, você " "precisa ter uma chave PIX cadastrada na sua conta Mercado Pago." -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:564 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:541 msgid "Register your Pix key at Mercado Pago." msgstr "Cadastre sua chave PIX no Mercado Pago." -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:614, +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:601, #: ../../includes/payments/hooks/class-wc-woomercadopago-hook-pix.php:148 msgid "Code valid for " msgstr "Código válido por " @@ -1395,8 +1379,8 @@ msgstr "Habilite os meios de pagamento disponíveis para seus clientes." msgid "All payment methods" msgstr "Todos os meios de pagamento" -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:458, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:486 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:443, +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:471 msgid "" "There was a problem processing your payment. Are you sure you have correctly " "filled out all the information on the payment form?" @@ -1404,45 +1388,45 @@ msgstr "" "Ocorreu um problema ao processar seu pagamento. Tem certeza de que preencheu " "corretamente todas as informações no formulário de pagamento?" -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:451, -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:479 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:436, +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:464 msgid "Your document data is invalid" msgstr "Número de documento inválido" -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:527 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:508 msgid "To print the ticket again click" msgstr "Para reimprimir o boleto clique" -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:530 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:511 msgid "here" msgstr "aqui" -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:659 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:640 msgid " and " msgstr " e " -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:113 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:117 msgid "Payment made" msgstr "Pagamento realizado" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:114 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:118 msgid "Payment made by the buyer and already credited in the account." msgstr "Pagamento realizado pelo comprador e já creditado na conta." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:117 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:121 msgid "Call resolved" msgstr "Chamado resolvido" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:118, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:218 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:122, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:222 msgid "Please contact Mercado Pago for further details." msgstr "Entre em contato com o Mercado Pago para consultar mais detalhes." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:121 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:125 msgid "Payment refunded" msgstr "Pagamento devolvido" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:122 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:126 msgid "" "Your refund request has been made. Please contact Mercado Pago for further " "details." @@ -1450,59 +1434,59 @@ msgstr "" "Seu pedido de reembolso já foi realizado. Entre em contato com o Mercado " "Pago para consultar mais detalhes." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:125, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:129 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:129, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:133 msgid "Payment returned" msgstr "Pagamento devolvido" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:126 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:130 msgid "The payment has been returned to the client." msgstr "O pagamento já foi devolvido ao cliente." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:130 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:134 msgid "The payment has been partially returned to the client." msgstr "O pagamento já foi devolvido parcialmente ao cliente." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:133 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:137 msgid "Payment canceled" msgstr "Pagamento cancelado" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:134 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:138 msgid "The payment has been successfully canceled." msgstr "O pagamento foi cancelado com sucesso." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:137 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:141 msgid "Purchase canceled" msgstr "Compra cancelada" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:138 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:142 msgid "The payment has been canceled by the customer." msgstr "O pagamento foi cancelado pelo cliente." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:141, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:145, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:149, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:153, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:157, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:173, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:161, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:177, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:181, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:185, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:189, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:193, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:197, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:307 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:201, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:311 msgid "Pending payment" msgstr "Pagamento pendente" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:142, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:146, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:150, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:154 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:154, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:158 msgid "Awaiting payment from the buyer." msgstr "Aguardando pagamento do comprador." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:158 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:162 msgid "" "We are veryfing the payment. We will notify you by email in up to 6 hours if " "everything is fine so that you can deliver the product or provide the " @@ -1512,19 +1496,18 @@ msgstr "" "se está tudo certo para que você possa entregar o produto ou oferecer o " "serviço." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:161, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:201, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:165, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:205, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:209, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:213, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:225, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:217, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:229, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:233, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:237, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:241, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:245, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:249, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:255, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:253, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:259, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:263, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:267, @@ -1537,19 +1520,20 @@ msgstr "" #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:295, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:299, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:303, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:315, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:321, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:325 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:307, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:319, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:325, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:329 msgid "Declined payment" msgstr "Pagamento recusado" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:162, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:206, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:166, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:210, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:214, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:226, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:246, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:256 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:218, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:230, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:250, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:260 msgid "" "The card-issuing bank declined the payment. Please ask your client to use " "another card or to get in touch with the bank." @@ -1557,11 +1541,11 @@ msgstr "" "O banco emissor do cartão recusou o pagamento. Peça para seu cliente usar " "outro cartão ou entrar em contato com o banco." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:165 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:169 msgid "Payment authorized. Awaiting capture." msgstr "Pagamento autorizado. Aguardando captura." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:166 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:170 msgid "" "The payment has been authorized on the client's card. Please capture the " "payment." @@ -1569,17 +1553,17 @@ msgstr "" "O pagamento já foi autorizado no cartão do cliente. Faça a captura do " "pagamento." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:169 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:173 msgid "Payment in process" msgstr "Pagamento em processamento" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:170, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:190 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:174, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:194 msgid "Please wait or contact Mercado Pago for further details" msgstr "" "Aguarde ou entre em contato com o Mercado Pago para consultar mais detalhes" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:174 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:178 msgid "" "The bank is reviewing the payment. As soon as we have their confirmation, we " "will notify you via email so that you can deliver the product or provide the " @@ -1589,21 +1573,21 @@ msgstr "" "recebermos a confirmação para que você possa entregar o produto ou oferecer " "o serviço." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:178, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:182, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:186 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:186, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:190 msgid "Awaiting payment information validation." msgstr "Aguardando validação das informações de pagamento." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:194 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:198 msgid "Waiting for the buyer." msgstr "Aguardando o comprador." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:198 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:202 msgid "Waiting for the card issuer." msgstr "Aguardando o emissor do cartão." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:202 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:206 msgid "" "The payment could not be processed. Please ask your client to use another " "card or to get in touch with the bank." @@ -1611,21 +1595,21 @@ msgstr "" "O pagamento não foi processado pelo banco. Peça para seu cliente usar outro " "meio de pagamento ou entrar em contato com o banco." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:217 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:221 msgid "Mercado Pago did not process the payment" msgstr "O Mercado Pago não processou o pagamento" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:221, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:311 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:225, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:315 msgid "Expired payment deadline" msgstr "Prazo expirado para pagamento" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:222, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:312 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:226, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:316 msgid "The client did not pay within the time limit." msgstr "O cliente não pagou dentro do limite de tempo." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:230 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:234 msgid "" "The CVV is invalid. Please ask your client to review the details or use " "another card." @@ -1633,7 +1617,7 @@ msgstr "" "O código de segurança é inválido. Por favor, peça para seu cliente revisar " "os dados ou usar outro cartão." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:234 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:238 msgid "" "The card is expired. Please ask your client to use another card or to " "contact the bank." @@ -1641,9 +1625,9 @@ msgstr "" "O cartão está vencido. Por favor, peça para seu cliente usar outro cartão ou " "entrar em contato com o banco." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:238, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:284, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:288 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:242, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:288, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:292 msgid "" "This payment was declined because it did not pass Mercado Pago security " "controls. Please ask your client to use another card." @@ -1651,8 +1635,8 @@ msgstr "" "Este pagamento foi recusado porque não passou pelos controles de segurança " "do Mercado Pago. Peça para seu cliente usar outro cartão." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:242, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:280 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:246, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:284 msgid "" "The buyer is suspended in our platform. Your client must contact us to check " "what happened." @@ -1660,7 +1644,7 @@ msgstr "" "O comprador está suspenso no Mercado Pago. Seu cliente precisa entrar em " "contato conosco para saber o que aconteceu." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:251 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:255 msgid "" "The card does not have enough limit. Please ask your client to use another " "card or to get in touch with the bank." @@ -1668,7 +1652,7 @@ msgstr "" "O cartão não tem saldo suficiente. Peça para seu cliente usar outro cartão " "ou entrar em contato com o banco." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:252 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:256 msgid "" "The card does not have sufficient balance. Please ask your client to use " "another card or to get in touch with the bank." @@ -1676,7 +1660,7 @@ msgstr "" "O cartão não tem saldo suficiente. Peça para seu cliente usar outro cartão " "ou entrar em contato com o banco." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:260 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:264 msgid "" "The CVV was entered incorrectly several times. Please ask your client to use " "another card or to get in touch with the bank." @@ -1684,7 +1668,7 @@ msgstr "" "O código de segurança do cartão foi inserido incorretamente várias vezes. " "Peça para seu cliente trocar o cartão ou entrar em contato com o banco." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:264 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:268 msgid "" "The card does not allow the number of installments entered. Please ask your " "client to choose another installment plan or to use another card." @@ -1692,7 +1676,7 @@ msgstr "" "O cartão não aceita o número de parcelas escolhido. Peça para seu cliente " "escolher um número diferente de parcelas ou usar outro cartão." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:268 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:272 msgid "" "The card-issuing bank declined the payment. Please instruct your client to " "ask the bank to authotize it or to use another card." @@ -1701,7 +1685,7 @@ msgstr "" "entrar em contato com o banco para pedir que o pagamento seja autorizado ou " "peça que use outro cartão." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:272 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:276 msgid "" "From Mercado Pago we have detected that this payment has already been made " "before. If that is not the case, your client may try to pay again." @@ -1710,7 +1694,7 @@ msgstr "" "anteriormente. Se esse não for o caso, seu cliente pode tentar pagar " "novamente." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:276 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:280 msgid "" "The card is not active yet. Please ask your client to use another card or to " "get in touch with the bank to activate it." @@ -1718,7 +1702,7 @@ msgstr "" "O cartão ainda não está desbloqueado. Peça para seu cliente usar outro " "cartão ou entrar em contato com o banco para desbloqueá-lo." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:292 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:296 msgid "" "The amount exceeded the card limit. Please ask your client to use another " "card or to get in touch with the bank." @@ -1726,9 +1710,9 @@ msgstr "" "O valor excedeu o limite do cartão. Peça para seu cliente usar outro cartão " "ou entrar em contato com o banco." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:296, #: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:300, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:304 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:304, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:308 msgid "" "Please ask your client to use another card or to get in touch with the card " "issuer." @@ -1736,7 +1720,7 @@ msgstr "" "Peça para seu cliente usar outro cartão ou entrar em contato com o emissor " "do cartão." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:308 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:312 msgid "" "The amount exceeded the card's limit. Please ask your client to use another " "card or to get in touch with the bank." @@ -1744,7 +1728,7 @@ msgstr "" "O valor excedeu o limite do cartão. Peça para seu cliente usar outro cartão " "ou entrar em contato com o banco." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:317 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:321 msgid "" "The credit function is not enabled for the card. Please tell your client " "that it is possible to pay with debit or to use another one." @@ -1752,7 +1736,7 @@ msgstr "" "A função crédito não está habilitada no cartão. Informe ao seu cliente que é " "possível pagar no débito ou peça para usar outro cartão." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:318 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:322 msgid "" "The debit function is not enabled for the card. Please tell your client that " "it is possible to pay with credit or to use another one." @@ -1760,7 +1744,7 @@ msgstr "" "A função débito não está habilitada no cartão. Informe ao seu cliente que é " "possível pagar no crédito ou peça para usar outro cartão." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:322 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:326 msgid "" "The card-issuing bank declined the payment. Please instruct your client to " "ask the bank to authorize it." @@ -1768,7 +1752,7 @@ msgstr "" "O banco emissor do cartão recusou o pagamento. Peça para seu cliente entrar " "em contato com o banco para autorizar o pagamento." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:326 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:330 msgid "" "The buyer does not have enough balance to make the purchase. Please ask your " "client to deposit money to the Mercado Pago Account or to use a different " @@ -1778,38 +1762,38 @@ msgstr "" "para seu cliente adicionar saldo no Mercado Pago ou usar outro meio de " "pagamento." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:329 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:333 msgid "There was an error" msgstr "Houve um erro" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:330 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:334 msgid "The transaction could not be completed." msgstr "Não foi possível completar a transação." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:413 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:417 msgid "Payment status on Mercado Pago" msgstr "Status de pagamento no Mercado Pago" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:473, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:485 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:477, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:489 msgid "View purchase details at Mercado Pago" msgstr "Ver detalhes da compra no Mercado Pago" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:474, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:486, -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:498 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:478, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:490, +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:502 msgid "Sync order status" msgstr "Sincronizar status do pedido" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:497 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:501 msgid "Check the reasons why the purchase was declined." msgstr "Consulte os motivos de recusa da sua compra." -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:606 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:608 msgid "Order update successfully. This page will be reloaded..." msgstr "Pedido atualizado com sucesso. Esta página será recarregada…" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:610 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:612 msgid "Unable to update order: " msgstr "Não foi possível atualizar o pedido: " @@ -2443,7 +2427,7 @@ msgstr "Desconto para o cupom %s" msgid " and fee of" msgstr " e taxa de" -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:547 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:545 msgid "" "Public Key production credential is invalid. Review the field to " "receive real payments." @@ -2451,7 +2435,7 @@ msgstr "" "A credencial de produção Public Key é inválida. Revise o campo para " "poder receber pagamentos reais." -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:556 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:554 msgid "" "Public Key test credential is invalid. Review the field to perform " "tests in your store." @@ -2459,7 +2443,7 @@ msgstr "" "A credencial de teste Public Key é inválida. Revise o campo para " "poder realizar testes em sua loja." -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:565 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:563 msgid "" "Access Token production credential is invalid. Remember that it must " "be complete to receive real payments." @@ -2467,7 +2451,7 @@ msgstr "" "A credencial de produção Access Token é inválida. Revise o campo para " "poder receber pagamentos reais." -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:574 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:572 msgid "" "Access Token test credential is invalid. Review the field to perform " "tests in your store." @@ -2475,7 +2459,7 @@ msgstr "" "A credencial de teste Access Token é inválida. Revise o campo para " "poder realizar testes em sua loja." -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:592 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:590 msgid "" "Public Key test credential is blank. Review the field to perform " "tests in your store." @@ -2483,7 +2467,7 @@ msgstr "" "A credencial de teste Public Key está em branco. Revise o campo para " "poder realizar testes em sua loja." -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:601 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:599 msgid "" "Public Key production credential is blank. Review the field to " "receive real payments." @@ -2491,7 +2475,7 @@ msgstr "" "A credencial de produção Public Key está em branco. Revise o campo " "para poder receber pagamentos reais." -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:610 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:608 msgid "" "Access Token test credential is blank. Review the field to perform " "tests in your store." @@ -2499,7 +2483,7 @@ msgstr "" "A credencial de teste Access Token está em branco. Revise o campo " "para poder realizar testes em sua loja." -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:619 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:617 msgid "" "Access Token production credential is blank. Remember that it must be " "complete to receive real payments." @@ -2757,7 +2741,7 @@ msgstr "Peça a linha de forma " #: ../../includes/products/hooks/class-wc-woomercadopago-products-hook-credits.php:120 msgid ". Login to your account or create one in a few steps." -msgstr "De forma 100% online e segura." +msgstr "100% online e segura." #: ../../includes/products/hooks/class-wc-woomercadopago-products-hook-credits.php:121 msgid "Search for" diff --git a/i18n/languages/woocommerce-mercadopago.pot b/i18n/languages/woocommerce-mercadopago.pot index 74631d3f8..c8658f12e 100644 --- a/i18n/languages/woocommerce-mercadopago.pot +++ b/i18n/languages/woocommerce-mercadopago.pot @@ -7,7 +7,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Last-Translator: MPB Desenvolvimento \n" -"POT-Creation-Date: 2023-05-16 21:36+0000\n" +"POT-Creation-Date: 2023-07-10 14:22+0000\n" "Project-Id-Version: undefined\n" "X-Poedit-Basepath: ..\n" "X-Poedit-KeywordsList: __;_e;_ex:1,2c;_n:1,2;_n_noop:1,2;_nx:1,2,4c;_nx_noop:1,2,3c;_x:1,2c;esc_attr__;esc_attr_e;esc_attr_x:1,2c;esc_html__;esc_html_e;esc_html_x:1,2c\n" @@ -16,11 +16,11 @@ msgstr "" "X-Poedit-SourceCharset: UTF-8\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" -#: ../../includes/helpers/class-wc-woomercadopago-helper-links.php:141, ../../includes/module/class-wc-woomercadopago-module.php:352 +#: ../../includes/helpers/class-wc-woomercadopago-helper-links.php:140, ../../includes/module/class-wc-woomercadopago-module.php:352 msgid "By continuing, you agree to our " msgstr "" -#: ../../includes/helpers/class-wc-woomercadopago-helper-links.php:143, ../../includes/module/class-wc-woomercadopago-module.php:354 +#: ../../includes/helpers/class-wc-woomercadopago-helper-links.php:142, ../../includes/module/class-wc-woomercadopago-module.php:354 msgid "Terms and Conditions" msgstr "" @@ -139,7 +139,7 @@ msgstr "" msgid "Update the WooCommerce order to " msgstr "" -#: ../../includes/module/class-wc-woomercadopago-module.php:821, ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:583 +#: ../../includes/module/class-wc-woomercadopago-module.php:821, ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:581 msgid "Fill in your credentials to enable payment methods." msgstr "" @@ -159,7 +159,7 @@ msgstr "" msgid "By Mercado Pago" msgstr "" -#: ../../includes/notification/class-wc-woomercadopago-notification-core.php:109, ../../includes/notification/class-wc-woomercadopago-notification-ipn.php:171, ../../includes/notification/class-wc-woomercadopago-notification-ipn.php:140, ../../includes/notification/class-wc-woomercadopago-notification-webhook.php:189, ../../includes/notification/class-wc-woomercadopago-notification-webhook.php:167 +#: ../../includes/notification/class-wc-woomercadopago-notification-core.php:109, ../../includes/notification/class-wc-woomercadopago-notification-ipn.php:139, ../../includes/notification/class-wc-woomercadopago-notification-webhook.php:166 msgid "Buyer email" msgstr "" @@ -179,11 +179,11 @@ msgstr "" msgid "Not found Payments into Merchant_Order" msgstr "" -#: ../../includes/notification/class-wc-woomercadopago-notification-ipn.php:174, ../../includes/notification/class-wc-woomercadopago-notification-ipn.php:143, ../../includes/notification/class-wc-woomercadopago-notification-webhook.php:192, ../../includes/notification/class-wc-woomercadopago-notification-webhook.php:170 +#: ../../includes/notification/class-wc-woomercadopago-notification-ipn.php:142, ../../includes/notification/class-wc-woomercadopago-notification-webhook.php:169 msgid "Payment type" msgstr "" -#: ../../includes/notification/class-wc-woomercadopago-notification-ipn.php:177, ../../includes/notification/class-wc-woomercadopago-notification-ipn.php:146, ../../includes/notification/class-wc-woomercadopago-notification-webhook.php:195, ../../includes/notification/class-wc-woomercadopago-notification-webhook.php:173 +#: ../../includes/notification/class-wc-woomercadopago-notification-ipn.php:145, ../../includes/notification/class-wc-woomercadopago-notification-webhook.php:172 msgid "Payment method" msgstr "" @@ -259,7 +259,7 @@ msgstr "" msgid "24 installments" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:256, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:153, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:915, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:203, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:197 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:256, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:153, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:928, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:203, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:197 msgid "Enable the checkout" msgstr "" @@ -267,11 +267,11 @@ msgstr "" msgid "By disabling it, you will disable all payments from Mercado Pago Checkout at Mercado Pago website by redirect." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:261, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:920 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:261, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:933 msgid "The checkout is enabled." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:262, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:921 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:262, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:934 msgid "The checkout is disabled." msgstr "" @@ -279,7 +279,7 @@ msgstr "" msgid "With Checkout Pro you sell with all the safety inside Mercado Pago environment." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:298, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:269 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:298, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:348 msgid "Advanced settings" msgstr "" @@ -367,156 +367,156 @@ msgstr "" msgid "Available payment methods" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:535, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:535, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:521, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:521, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:426, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:426, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:411, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:411, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:698, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:698, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:418, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:418, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:404, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:404, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:434, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:434, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:419, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:419, ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:174, ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:172 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:520, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:520, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:441, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:441, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:403, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:403, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:418, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:418, ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:174, ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:172 msgid "discount of" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:541, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:541, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:527, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:527, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:432, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:432, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:417, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:417, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:704, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:704, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:691, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:691, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:424, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:424, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:410, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:410, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:440, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:440, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:425, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:425, ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:176 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:526, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:526, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:447, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:447, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:683, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:683, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:409, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:409, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:424, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:424, ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:176 msgid "fee of" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:641, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:667, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:719 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:626, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:652, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:704 msgid "Easy login" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:642, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:668, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:720 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:627, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:653, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:705 msgid "Log in with the same email and password you use in Mercado Libre." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:649, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:675, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:693, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:727 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:634, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:660, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:678, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:712 msgid "Quick payments" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:650 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:635 msgid "Use your saved cards, Pix or available balance." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:657, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:683 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:642, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:668 msgid "Protected purchases" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:658, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:684 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:643, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:669 msgid "Get your money back in case you don't receive your product." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:676 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:661 msgid "Use your available Mercado Pago Wallet balance or saved cards." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:694, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:728 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:679, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:713 msgid "Use your available money or saved cards." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:701, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:735 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:686, ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:720 msgid "Installments option" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:702 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:687 msgid "Pay with or without a credit card." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:709 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:694 msgid "Reliable purchases" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:710 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:695 msgid "Get help if you have a problem with your purchase." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:736 +#: ../../includes/payments/class-wc-woomercadopago-basic-gateway.php:721 msgid "Interest-free installments with selected banks." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:30, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:31, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:245 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:42, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:43, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:324 msgid "Installments without card" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:32 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:44 msgid "Customers who buy on spot and pay later in up to 12 installments" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:40 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:54 msgid "Mercado Pago - Installments without card" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:42 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:56 msgid "Checkout without card" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:182 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:112, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:288 +msgid "Banner on the product page | Computer version" +msgstr "" + +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:113 +msgid "Banner on the product page | Cellphone version" +msgstr "" + +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:249 msgid "Activate installments without card in your store checkout " msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:183 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:250 msgid "Offer the option to pay in installments without card directly from your store's checkout." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:187 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:254 msgid "Payment in installments without card in the store checkout is active" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:188 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:255 msgid "Payment in installments without card in the store checkout is inactive" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:205 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:273 msgid "Checkout visualization" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:206, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:367 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:274, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:290 msgid "Check below how this feature will be displayed to your customers:" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:207 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:275 msgid "Checkout Preview" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:208 +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:276 msgid "PREVIEW" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:249 -msgid "Reach millions of buyers by offering Mercado Credito as a payment method. Our flexible payment options give your customers the possibility to buy today whatever they want in up to 12 installments without the need to use a credit card." -msgstr "" - -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:252 -msgid "For your business, the approval of the purchase is immediate and guaranteed." -msgstr "" - -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:311 -msgid "Inform your customers about the option of paying in installments without card" +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:286 +msgid "Computer" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:314 -msgid "By activating the installments without card component, you increase your chances of selling." +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:287 +msgid "Mobile" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:316 -msgid "The installments without card component is active." +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:289 +msgid "Component visualization" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:317 -msgid "The installments without card component is inactive." +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:328 +msgid "Reach millions of buyers by offering Mercado Credito as a payment method. Our flexible payment options give your customers the possibility to buy today whatever they want in up to 12 installments without the need to use a credit card." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:355, ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:365 -msgid "Banner on the product page | Computer version" +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:331 +msgid "For your business, the approval of the purchase is immediate and guaranteed." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:356 -msgid "Banner on the product page | Cellphone version" +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:394 +msgid "Inform your customers about the option of paying in installments without card" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:363 -msgid "Computer" +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:397 +msgid "By activating the installments without card component, you increase your chances of selling." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:364 -msgid "Mobile" +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:399 +msgid "The installments without card component is active." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:366 -msgid "Component visualization" +#: ../../includes/payments/class-wc-woomercadopago-credits-gateway.php:400 +msgid "The installments without card component is inactive." msgstr "" #: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:41, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:42, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:52 @@ -543,163 +543,163 @@ msgstr "" msgid "Transparent checkout for credit cards is disabled." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:191 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:184 msgid "Installments Fees" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:192 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:185 msgid "Set installment fees and whether they will be charged from the store or from the buyer." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:193 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:186 msgid "Set fees" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:218 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:211 msgid "Transparent Checkout | Credit card " msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:222 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:215 msgid "With the Transparent Checkout, you can sell inside your store environment, without redirection and with the security from Mercado Pago." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:240 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:233 msgid "Advanced configuration of the personalized payment experience" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:254 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:247 msgid "Payments via Mercado Pago account" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:255 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:248 msgid "Your customers pay faster with saved cards, money balance or other available methods in their Mercado Pago accounts." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:259 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:252 msgid "Payments via Mercado Pago accounts are active." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:260 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:253 msgid "Payments via Mercado Pago accounts are inactive." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:279 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:272 msgid "Check an example of how it will appear in your store:" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:310 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:303 msgid "That’s it, payment accepted!" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:312 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:305 msgid "We are processing your payment. In less than an hour we will send you the result by email." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:314 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:307 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/class-wc-woomercadopago-custom-gateway.php:316 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:309 msgid "Check the card number." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:318 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:311 msgid "Check the expiration date." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:320 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:313 msgid "Check the information provided." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:322 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:315 msgid "Check the informed security code." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:325 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:318 msgid "Your payment cannot be processed." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:327 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:320 msgid "You must authorize payments for your orders." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:329 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:322 msgid "Contact your card issuer to activate it. The phone is on the back of your card." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:331 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:324 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/class-wc-woomercadopago-custom-gateway.php:333 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:326 msgid "Your payment was declined. Please select another payment method. It is recommended in cash." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:335 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:328 msgid "Your payment does not have sufficient funds." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:337 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:330 msgid "Payment cannot process the selected fee." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:339 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:332 msgid "You have reached the limit of allowed attempts. Choose another card or other payment method." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:341, ../../includes/module/preference/class-wc-woomercadopago-preference-abstract.php:204 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:334, ../../includes/module/preference/class-wc-woomercadopago-preference-abstract.php:204 msgid "This payment method cannot process your payment." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:396 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:389 msgid "Credit cards" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:397 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:390 msgid "Up to " msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:397 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:390 msgid " installments" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:404 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:397 msgid "Debit cards" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:447, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:448, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:480, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:481, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:401, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:402, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:562, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:563 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:440, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:441, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:473, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:474, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:401, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:402, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:543, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:544 msgid "A problem was occurred when processing your payment. Please, try again." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:577 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:570 msgid "See your order form" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:588 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:581 msgid "Your payment was declined. You can try again." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:595, ../../includes/payments/hooks/class-wc-woomercadopago-hook-basic.php:95, ../../includes/payments/hooks/class-wc-woomercadopago-hook-credits.php:93 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:588, ../../includes/payments/hooks/class-wc-woomercadopago-hook-basic.php:95, ../../includes/payments/hooks/class-wc-woomercadopago-hook-credits.php:93 msgid "Click to try again" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:617, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:618 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:610, ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:611 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/class-wc-woomercadopago-custom-gateway.php:642 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:635 msgid "Represents the installment fee charged by Mercado Pago." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:643 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:636 msgid "Mercado Pago Installment Fee:" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:648 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:641 msgid "Represents the total purchase plus the installment fee charged by Mercado Pago." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:649 +#: ../../includes/payments/class-wc-woomercadopago-custom-gateway.php:642 msgid "Mercado Pago Total:" msgstr "" @@ -707,131 +707,131 @@ msgstr "" msgid "Configure your credentials to enable Mercado Pago payment methods." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:773 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:786 msgid "Title in the store Checkout" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:775 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:788 msgid "Change the display text in Checkout, maximum characters: 85" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:777 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:790 msgid "The text inserted here will not be translated to other languages" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:791 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:804 msgid "Description" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:828, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:840, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:347 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:841, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:853, ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:347 msgid "Important! To sell you must enter your credentials." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:829 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:842 msgid "You must enter production credentials." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:830 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:843 msgid "Enter credentials" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:840 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:853 msgid "Mercado Pago Plugin general settings" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:841 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:854 msgid "Set the deadlines and fees, test your store or access the Plugin manual." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:842 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:855 msgid "Go to Settings" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:866 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:879 msgid "Activate your credentials to be able to sell" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:867 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:880 msgid "Credentials are codes that you must enter to enable sales. Go below on Activate Credentials. On the next screen, use again the Activate Credentials button and fill in the fields with the requested information." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:868 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:881 msgid "Activate credentials" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:916 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:929 msgid "By disabling it, you will disable all payment methods of this checkout." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1029 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:989 msgid "Basic Configuration" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1042 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1002 msgid "Discount coupons" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1045 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1005 msgid "Will you offer discount coupons to customers who buy with Mercado Pago?" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1047 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1007 msgid "Discount coupons is active." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1048 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1008 msgid "Discount coupons is disabled." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1060 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1020 msgid "Automatic decline of payments without instant approval" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1061 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1021 msgid "Enable it if you want to automatically decline payments that are not instantly approved by banks or other institutions. " msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1065 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1025 msgid "Pending payments will be automatically declined." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1066 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1026 msgid "Pending payments will not be automatically declined." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1078 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1038 msgid "Discount in Mercado Pago Checkouts" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1081 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1041 msgid "Choose a percentage value that you want to discount your customers for paying with Mercado Pago." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1082, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1103 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1042, ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1063 msgid "Activate and show this information on Mercado Pago Checkout" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1099 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1059 msgid "Commission in Mercado Pago Checkouts" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1102 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1062 msgid "Choose an additional percentage value that you want to charge as commission to your customers for paying with Mercado Pago." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1139 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1083 msgid "Convert Currency" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1144 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1088 msgid "Currency convertion is enabled." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1145 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1089 msgid "Currency convertion is disabled." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1262 +#: ../../includes/payments/class-wc-woomercadopago-payment-abstract.php:1206 msgid "Edit these advanced fields only when you want to modify the preset values." msgstr "" @@ -983,35 +983,35 @@ msgstr "" msgid "Find out more about Pix" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:493 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:470 msgid "A problem occurred when processing your payment. Please try again." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:478, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:547 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:455, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:528 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/class-wc-woomercadopago-pix-gateway.php:456, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:522 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:433, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:503 msgid "The customer has not paid yet." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:461 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:438 msgid "Now you just need to pay with Pix to finalize your purchase." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:462 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:439 msgid "Scan the QR code below or copy and paste the code into your bank's application." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:563 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:540 msgid "Please note that to receive payments via Pix at our checkout, you must have a Pix key registered in your Mercado Pago account." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:564 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:541 msgid "Register your Pix key at Mercado Pago." msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:614, ../../includes/payments/hooks/class-wc-woomercadopago-hook-pix.php:148 +#: ../../includes/payments/class-wc-woomercadopago-pix-gateway.php:601, ../../includes/payments/hooks/class-wc-woomercadopago-hook-pix.php:148 msgid "Code valid for " msgstr "" @@ -1079,247 +1079,247 @@ msgstr "" msgid "All payment methods" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:458, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:486 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:443, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:471 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/class-wc-woomercadopago-ticket-gateway.php:451, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:479 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:436, ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:464 msgid "Your document data is invalid" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:527 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:508 msgid "To print the ticket again click" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:530 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:511 msgid "here" msgstr "" -#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:659 +#: ../../includes/payments/class-wc-woomercadopago-ticket-gateway.php:640 msgid " and " msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:113 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:117 msgid "Payment made" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:114 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:118 msgid "Payment made by the buyer and already credited in the account." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:117 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:121 msgid "Call resolved" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:118, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:218 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:122, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:222 msgid "Please contact Mercado Pago for further details." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:121 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:125 msgid "Payment refunded" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:122 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:126 msgid "Your refund request has been made. Please contact Mercado Pago for further details." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:125, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:129 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:129, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:133 msgid "Payment returned" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:126 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:130 msgid "The payment has been returned to the client." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:130 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:134 msgid "The payment has been partially returned to the client." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:133 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:137 msgid "Payment canceled" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:134 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:138 msgid "The payment has been successfully canceled." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:137 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:141 msgid "Purchase canceled" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:138 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:142 msgid "The payment has been canceled by the customer." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:141, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:145, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:149, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:153, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:157, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:173, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:177, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:181, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:185, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:189, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:193, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:197, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:307 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:145, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:149, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:153, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:157, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:161, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:177, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:181, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:185, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:189, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:193, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:197, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:201, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:311 msgid "Pending payment" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:142, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:146, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:150, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:154 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:146, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:150, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:154, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:158 msgid "Awaiting payment from the buyer." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:158 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:162 msgid "We are veryfing the payment. We will notify you by email in up to 6 hours if everything is fine so that you can deliver the product or provide the service." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:161, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:201, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:205, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:209, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:213, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:225, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:229, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:233, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:237, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:241, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:245, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:249, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:255, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:259, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:263, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:267, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:271, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:275, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:279, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:283, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:287, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:291, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:295, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:299, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:303, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:315, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:321, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:325 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:165, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:205, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:209, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:213, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:217, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:229, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:233, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:237, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:241, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:245, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:249, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:253, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:259, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:263, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:267, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:271, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:275, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:279, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:283, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:287, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:291, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:295, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:299, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:303, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:307, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:319, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:325, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:329 msgid "Declined payment" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:162, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:206, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:210, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:214, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:226, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:246, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:256 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:166, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:210, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:214, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:218, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:230, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:250, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:260 msgid "The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:165 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:169 msgid "Payment authorized. Awaiting capture." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:166 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:170 msgid "The payment has been authorized on the client's card. Please capture the payment." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:169 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:173 msgid "Payment in process" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:170, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:190 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:174, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:194 msgid "Please wait or contact Mercado Pago for further details" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:174 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:178 msgid "The bank is reviewing the payment. As soon as we have their confirmation, we will notify you via email so that you can deliver the product or provide the service." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:178, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:182, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:186 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:182, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:186, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:190 msgid "Awaiting payment information validation." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:194 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:198 msgid "Waiting for the buyer." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:198 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:202 msgid "Waiting for the card issuer." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:202 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:206 msgid "The payment could not be processed. Please ask your client to use another card or to get in touch with the bank." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:217 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:221 msgid "Mercado Pago did not process the payment" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:221, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:311 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:225, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:315 msgid "Expired payment deadline" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:222, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:312 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:226, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:316 msgid "The client did not pay within the time limit." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:230 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:234 msgid "The CVV is invalid. Please ask your client to review the details or use another card." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:234 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:238 msgid "The card is expired. Please ask your client to use another card or to contact the bank." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:238, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:284, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:288 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:242, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:288, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:292 msgid "This payment was declined because it did not pass Mercado Pago security controls. Please ask your client to use another card." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:242, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:280 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:246, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:284 msgid "The buyer is suspended in our platform. Your client must contact us to check what happened." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:251 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:255 msgid "The card does not have enough limit. Please ask your client to use another card or to get in touch with the bank." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:252 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:256 msgid "The card does not have sufficient balance. Please ask your client to use another card or to get in touch with the bank." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:260 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:264 msgid "The CVV was entered incorrectly several times. Please ask your client to use another card or to get in touch with the bank." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:264 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:268 msgid "The card does not allow the number of installments entered. Please ask your client to choose another installment plan or to use another card." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:268 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:272 msgid "The card-issuing bank declined the payment. Please instruct your client to ask the bank to authotize it or to use another card." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:272 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:276 msgid "From Mercado Pago we have detected that this payment has already been made before. If that is not the case, your client may try to pay again." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:276 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:280 msgid "The card is not active yet. Please ask your client to use another card or to get in touch with the bank to activate it." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:292 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:296 msgid "The amount exceeded the card limit. Please ask your client to use another card or to get in touch with the bank." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:296, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:300, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:304 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:300, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:304, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:308 msgid "Please ask your client to use another card or to get in touch with the card issuer." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:308 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:312 msgid "The amount exceeded the card's limit. Please ask your client to use another card or to get in touch with the bank." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:317 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:321 msgid "The credit function is not enabled for the card. Please tell your client that it is possible to pay with debit or to use another one." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:318 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:322 msgid "The debit function is not enabled for the card. Please tell your client that it is possible to pay with credit or to use another one." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:322 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:326 msgid "The card-issuing bank declined the payment. Please instruct your client to ask the bank to authorize it." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:326 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:330 msgid "The buyer does not have enough balance to make the purchase. Please ask your client to deposit money to the Mercado Pago Account or to use a different payment method." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:329 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:333 msgid "There was an error" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:330 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:334 msgid "The transaction could not be completed." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:413 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:417 msgid "Payment status on Mercado Pago" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:473, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:485 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:477, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:489 msgid "View purchase details at Mercado Pago" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:474, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:486, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:498 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:478, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:490, ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:502 msgid "Sync order status" msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:497 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:501 msgid "Check the reasons why the purchase was declined." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:606 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:608 msgid "Order update successfully. This page will be reloaded..." msgstr "" -#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:610 +#: ../../includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php:612 msgid "Unable to update order: " msgstr "" @@ -1885,35 +1885,35 @@ msgstr "" msgid " and fee of" msgstr "" -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:547 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:545 msgid "Public Key production credential is invalid. Review the field to receive real payments." msgstr "" -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:556 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:554 msgid "Public Key test credential is invalid. Review the field to perform tests in your store." msgstr "" -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:565 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:563 msgid "Access Token production credential is invalid. Remember that it must be complete to receive real payments." msgstr "" -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:574 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:572 msgid "Access Token test credential is invalid. Review the field to perform tests in your store." msgstr "" -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:592 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:590 msgid "Public Key test credential is blank. Review the field to perform tests in your store." msgstr "" -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:601 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:599 msgid "Public Key production credential is blank. Review the field to receive real payments." msgstr "" -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:610 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:608 msgid "Access Token test credential is blank. Review the field to perform tests in your store." msgstr "" -#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:619 +#: ../../includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php:617 msgid "Access Token production credential is blank. Remember that it must be complete to receive real payments." msgstr "" diff --git a/includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php b/includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php index eca45ab45..0835ee0c8 100644 --- a/includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php +++ b/includes/admin/hooks/class-wc-woomercadopago-hook-order-details.php @@ -1,636 +1,625 @@ nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); - $this->current_user = WC_WooMercadoPago_Helper_Current_User::get_instance(); - - $this->load_hooks(); - } - - /** - * Load Hooks - * - * @return void - */ - public function load_hooks() { - //hook for post - add_action( 'add_meta_boxes_shop_order', array( $this, 'payment_status_metabox' ) ); - - //hook for order - add_action( 'add_meta_boxes_woocommerce_page_wc-orders', array( $this, 'payment_status_metabox' ) ); - add_action( 'wp_ajax_mp_sync_payment_status', array( $this, 'mercadopago_sync_payment_status' ) ); - } - - /** - * Load Scripts - * - * @return void - */ - public function load_scripts( $order ) { - - $suffix = $this->get_suffix(); - $script_name = 'mp_payment_status_metabox'; - - if ( is_admin() ) { - - wp_enqueue_script( - $script_name, - plugins_url( '../../assets/js/payment_status_metabox' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - false - ); - - wp_localize_script($script_name, $script_name . '_vars', [ - 'order_id' => $order->get_id(), - 'nonce' => $this->nonce->generate_nonce(self::NONCE_ID), - ]); - } - } - - /** - * Get suffix to static files - */ - public function get_suffix() { - return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - } - - /** - * Get Alert Description - * - * @param $payment_status_detail - * @param $is_credit_card - * - * @return array - */ - public function get_alert_description( $payment_status_detail, $is_credit_card ) { - $all_status_detail = [ - 'accredited' => array( - 'alert_title' => __( 'Payment made', 'woocommerce-mercadopago' ), - 'description' => __( 'Payment made by the buyer and already credited in the account.', 'woocommerce-mercadopago' ), - ), - 'settled' => array( - 'alert_title' => __( 'Call resolved', 'woocommerce-mercadopago' ), - 'description' => __( 'Please contact Mercado Pago for further details.', 'woocommerce-mercadopago' ), - ), - 'reimbursed' => array( - 'alert_title' => __( 'Payment refunded', 'woocommerce-mercadopago' ), - 'description' => __( 'Your refund request has been made. Please contact Mercado Pago for further details.', 'woocommerce-mercadopago' ), - ), - 'refunded' => array( - 'alert_title' => __( 'Payment returned', 'woocommerce-mercadopago' ), - 'description' => __( 'The payment has been returned to the client.', 'woocommerce-mercadopago' ), - ), - 'partially_refunded' => array( - 'alert_title' => __( 'Payment returned', 'woocommerce-mercadopago' ), - 'description' => __( 'The payment has been partially returned to the client.', 'woocommerce-mercadopago' ), - ), - 'by_collector' => array( - 'alert_title' => __( 'Payment canceled', 'woocommerce-mercadopago' ), - 'description' => __( 'The payment has been successfully canceled.', 'woocommerce-mercadopago' ), - ), - 'by_payer' => array( - 'alert_title' => __( 'Purchase canceled', 'woocommerce-mercadopago' ), - 'description' => __( 'The payment has been canceled by the customer.', 'woocommerce-mercadopago' ), - ), - 'pending' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Awaiting payment from the buyer.', 'woocommerce-mercadopago' ), - ), - 'pending_waiting_payment' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Awaiting payment from the buyer.', 'woocommerce-mercadopago' ), - ), - 'pending_waiting_for_remedy' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Awaiting payment from the buyer.', 'woocommerce-mercadopago' ), - ), - 'pending_waiting_transfer' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Awaiting payment from the buyer.', 'woocommerce-mercadopago' ), - ), - 'pending_review_manual' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'We are veryfing the payment. We will notify you by email in up to 6 hours if everything is fine so that you can deliver the product or provide the service.', 'woocommerce-mercadopago' ), - ), - 'waiting_bank_confirmation' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'pending_capture' => array( - 'alert_title' => __( 'Payment authorized. Awaiting capture.', 'woocommerce-mercadopago' ), - 'description' => __( "The payment has been authorized on the client's card. Please capture the payment.", 'woocommerce-mercadopago' ), - ), - 'in_process' => array( - 'alert_title' => __( 'Payment in process', 'woocommerce-mercadopago' ), - 'description' => __( 'Please wait or contact Mercado Pago for further details', 'woocommerce-mercadopago' ), - ), - 'pending_contingency' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The bank is reviewing the payment. As soon as we have their confirmation, we will notify you via email so that you can deliver the product or provide the service.', 'woocommerce-mercadopago' ), - ), - 'pending_card_validation' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Awaiting payment information validation.', 'woocommerce-mercadopago' ), - ), - 'pending_online_validation' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Awaiting payment information validation.', 'woocommerce-mercadopago' ), - ), - 'pending_additional_info' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Awaiting payment information validation.', 'woocommerce-mercadopago' ), - ), - 'offline_process' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Please wait or contact Mercado Pago for further details', 'woocommerce-mercadopago' ), - ), - 'pending_challenge' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Waiting for the buyer.', 'woocommerce-mercadopago' ), - ), - 'pending_provider_response' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Waiting for the card issuer.', 'woocommerce-mercadopago' ), - ), - 'bank_rejected' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The payment could not be processed. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'rejected_by_bank' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'rejected_insufficient_data' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'bank_error' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'by_admin' => array( - 'alert_title' => __( 'Mercado Pago did not process the payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Please contact Mercado Pago for further details.', 'woocommerce-mercadopago' ), - ), - 'expired' => array( - 'alert_title' => __( 'Expired payment deadline', 'woocommerce-mercadopago' ), - 'description' => __( 'The client did not pay within the time limit.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_bad_filled_card_number' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_bad_filled_security_code' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The CVV is invalid. Please ask your client to review the details or use another card.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_bad_filled_date' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card is expired. Please ask your client to use another card or to contact the bank.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_high_risk' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'This payment was declined because it did not pass Mercado Pago security controls. Please ask your client to use another card.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_fraud' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The buyer is suspended in our platform. Your client must contact us to check what happened.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_blacklist' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_insufficient_amount' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => $is_credit_card - ? __( 'The card does not have enough limit. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ) - : __( 'The card does not have sufficient balance. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_other_reason' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_max_attempts' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The CVV was entered incorrectly several times. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_invalid_installments' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card does not allow the number of installments entered. Please ask your client to choose another installment plan or to use another card.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_call_for_authorize' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card-issuing bank declined the payment. Please instruct your client to ask the bank to authotize it or to use another card.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_duplicated_payment' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'From Mercado Pago we have detected that this payment has already been made before. If that is not the case, your client may try to pay again.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_card_disabled' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card is not active yet. Please ask your client to use another card or to get in touch with the bank to activate it.', 'woocommerce-mercadopago' ), - ), - 'payer_unavailable' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The buyer is suspended in our platform. Your client must contact us to check what happened.', 'woocommerce-mercadopago' ), - ), - 'rejected_high_risk' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'This payment was declined because it did not pass Mercado Pago security controls. Please ask your client to use another card.', 'woocommerce-mercadopago' ), - ), - 'rejected_by_regulations' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'This payment was declined because it did not pass Mercado Pago security controls. Please ask your client to use another card.', 'woocommerce-mercadopago' ), - ), - 'rejected_cap_exceeded' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The amount exceeded the card limit. Please ask your client to use another card or to get in touch with the bank.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_3ds_challenge' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Please ask your client to use another card or to get in touch with the card issuer.', 'woocommerce-mercadopago' ), - ), - 'rejected_other_reason' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Please ask your client to use another card or to get in touch with the card issuer.', 'woocommerce-mercadopago' ), - ), - 'authorization_revoked' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'Please ask your client to use another card or to get in touch with the card issuer.', 'woocommerce-mercadopago' ), - ), - 'cc_amount_rate_limit_exceeded' => array( - 'alert_title' => __( 'Pending payment', 'woocommerce-mercadopago' ), - 'description' => __( "The amount exceeded the card's limit. Please ask your client to use another card or to get in touch with the bank.", 'woocommerce-mercadopago' ), - ), - 'cc_rejected_expired_operation' => array( - 'alert_title' => __( 'Expired payment deadline', 'woocommerce-mercadopago' ), - 'description' => __( 'The client did not pay within the time limit.', 'woocommerce-mercadopago' ), - ), - 'cc_rejected_bad_filled_other' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => $is_credit_card - ? __( 'The credit function is not enabled for the card. Please tell your client that it is possible to pay with debit or to use another one.', 'woocommerce-mercadopago' ) - : __( 'The debit function is not enabled for the card. Please tell your client that it is possible to pay with credit or to use another one.', 'woocommerce-mercadopago' ), - ), - 'rejected_call_for_authorize' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The card-issuing bank declined the payment. Please instruct your client to ask the bank to authorize it.', 'woocommerce-mercadopago' ), - ), - 'am_insufficient_amount' => array( - 'alert_title' => __( 'Declined payment', 'woocommerce-mercadopago' ), - 'description' => __( 'The buyer does not have enough balance to make the purchase. Please ask your client to deposit money to the Mercado Pago Account or to use a different payment method.', 'woocommerce-mercadopago' ), - ), - 'generic' => array( - 'alert_title' => __( 'There was an error', 'woocommerce-mercadopago' ), - 'description' => __( 'The transaction could not be completed.', 'woocommerce-mercadopago' ), - ), - ]; - - return array_key_exists($payment_status_detail, $all_status_detail) - ? $all_status_detail[$payment_status_detail] - : $all_status_detail['generic']; - } - - /** - * Get Alert Status - * - * @param $payment_status - * - * @return string 'success' | 'pending' | 'rejected' | 'refunded' | 'charged_back' - */ - public function get_alert_status( $payment_status ) { - $all_payment_status = [ - 'approved' => 'success', - 'authorized' => 'success', - 'pending' => 'pending', - 'in_process' => 'pending', - 'in_mediation' => 'pending', - 'rejected' => 'rejected', - 'canceled' => 'rejected', - 'refunded' => 'refunded', - 'charged_back' => 'charged_back', - 'generic' => 'rejected' - ]; - - return array_key_exists($payment_status, $all_payment_status) ? $all_payment_status[$payment_status] : $all_payment_status['generic']; - } - - /** - * Get Order from Post - * - * @param $post - * - * @return bool|WC_Order|WC_Order_Refund - */ - private function get_order( $post ) { - if ( $this->order instanceof WC_Order ) { - return $this->order; - } - - if ( is_null($post->ID) ) { - return false; - } - - $this->order = wc_get_order($post->ID); - - if ( ! $this->order ) { - return false; - } - - return $this->order; - } - - /** - * Create payment status metabox - * - * @param WP_Post $post - * - * @return void - */ - public function payment_status_metabox( $post_or_order_object ) { - $order = ( $post_or_order_object instanceof WP_Post ) ? wc_get_order( $post_or_order_object->ID ) : $post_or_order_object; - - $this->load_scripts($order); - - if ( ! $order ) { - return; - } - - $payment_method = $order->get_payment_method(); - $is_mercadopago_payment_method = in_array($payment_method, WC_WooMercadoPago_Constants::GATEWAYS_IDS, true); - - if ( ! $is_mercadopago_payment_method ) { - return; - } - - add_meta_box( - 'mp-payment-status-metabox', - __( 'Payment status on Mercado Pago', 'woocommerce-mercadopago' ), - [$this, 'payment_status_metabox_content'] - ); - } - - /** - * Payment Status Metabox Content - * - * @param wc_get_order $order - * - * @return void - * @throws WC_WooMercadoPago_Exception - */ - public function payment_status_metabox_content( $order ) { - $payment = $this->get_payment($order); - - if ( ! $payment ) { - return; - } - - $payment_status = $payment['response']['status']; - $payment_status_details = $payment['response']['status_detail']; - - if ( ! $payment['response']['payment_type_id'] && ( - 'cc_rejected_bad_filled_other' === $payment_status_details || - 'cc_rejected_insufficient_amount' === $payment_status_details - ) ) { - return; - } - - $is_credit_card = 'credit_card' === $payment['response']['payment_type_id']; - $alert_status = $this->get_alert_status($payment_status); - $alert_description = $this->get_alert_description($payment_status_details, $is_credit_card); - $metabox_data = $this->get_metabox_data($alert_status, $alert_description); - - wc_get_template( - 'order/payment-status-metabox-content.php', - $metabox_data, - 'woo/mercado/pago/module/', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Metabolic Data - * - * @param $alert_status - * @param $alert - * @return Array - */ - public function get_metabox_data( $alert_status, $alert ) { - $country = strtolower(get_option( 'checkout_country', '' )); - - if ( 'success' === $alert_status ) { - return [ - 'img_src' => esc_url( plugins_url( '../../assets/images/generics/circle-green-check.png', plugin_dir_path( __FILE__ ) ) ), - 'alert_title' => $alert['alert_title'], - 'alert_description' => $alert['description'], - 'link' => $this->get_mp_home_link($country), - 'border_left_color' => '#00A650', - 'link_description' => __( 'View purchase details at Mercado Pago', 'woocommerce-mercadopago' ), - 'sync_button_text' => __( 'Sync order status', 'woocommerce-mercadopago' ), - ]; - } - - if ( 'pending' === $alert_status ) { - return [ - 'img_src' => esc_url( plugins_url( '../../assets/images/generics/circle-alert.png', plugin_dir_path( __FILE__ ) ) ), - 'alert_title' => $alert['alert_title'], - 'alert_description' => $alert['description'], - 'link' => $this->get_mp_home_link($country), - 'border_left_color' => '#f73', - 'link_description' => __( 'View purchase details at Mercado Pago', 'woocommerce-mercadopago' ), - 'sync_button_text' => __( 'Sync order status', 'woocommerce-mercadopago' ), - ]; - } - - if ( 'rejected' === $alert_status || 'refunded' === $alert_status || 'charged_back' === $alert_status ) { - return [ - 'img_src' => esc_url( plugins_url( '../../assets/images/generics/circle-red-alert.png', plugin_dir_path( __FILE__ ) ) ), - 'alert_title' => $alert['alert_title'], - 'alert_description' => $alert['description'], - 'link' => $this->get_mp_devsite_link($country), - 'border_left_color' => '#F23D4F', - 'link_description' => __( 'Check the reasons why the purchase was declined.', 'woocommerce-mercadopago' ), - 'sync_button_text' => __( 'Sync order status', 'woocommerce-mercadopago' ), - ]; - } - } - - /** - * Get Mercado Pago Home Link - * - * @param String $country Country Acronym - * - * @return String - */ - public function get_mp_home_link( $country ) { - $country_links = [ - 'mla' => 'https://www.mercadopago.com.ar/home', - 'mlb' => 'https://www.mercadopago.com.br/home', - 'mlc' => 'https://www.mercadopago.cl/home', - 'mco' => 'https://www.mercadopago.com.co/home', - 'mlm' => 'https://www.mercadopago.com.mx/home', - 'mpe' => 'https://www.mercadopago.com.pe/home', - 'mlu' => 'https://www.mercadopago.com.uy/home', - ]; - - return array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; - } - - /** - * Get Mercado Pago Devsite Page Link - * - * @param String $country Country Acronym - * - * @return String - */ - public function get_mp_devsite_link( $country ) { - $country_links = [ - 'mla' => 'https://www.mercadopago.com.ar/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', - 'mlb' => 'https://www.mercadopago.com.br/developers/pt/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_recusas', - 'mlc' => 'https://www.mercadopago.cl/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', - 'mco' => 'https://www.mercadopago.com.co/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', - 'mlm' => 'https://www.mercadopago.com.mx/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', - 'mpe' => 'https://www.mercadopago.com.pe/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', - 'mlu' => 'https://www.mercadopago.com.uy/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', - ]; - - return array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; - } - - /** - * Get payment - * - * @return array|null - * @throws WC_WooMercadoPago_Exception - */ - public function get_payment( $post_or_order_object ) { - - $order = ( $post_or_order_object instanceof WP_Post ) ? wc_get_order( $post_or_order_object->ID ) : $post_or_order_object; - - if ( ! $order ) { - return null; - } - - $payment_ids = explode(',', $order->get_meta( '_Mercado_Pago_Payment_IDs' )); - - if ( empty( $payment_ids ) ) { - return null; - } - - $last_payment_id = end($payment_ids); - $is_production_mode = $order->get_meta( 'is_production_mode' ); - $access_token = 'no' === $is_production_mode || ! $is_production_mode - ? get_option( '_mp_access_token_test' ) - : get_option( '_mp_access_token_prod' ); - - $mp = new MP($access_token); - $payment = $mp->search_payment_v1(trim($last_payment_id), $access_token); - - if ( ! $payment || 200 !== $payment['status'] ) { - return null; - } - - return $payment; - } - - /** - * Sync order status - * - * @return void - */ - public function mercadopago_sync_payment_status() { - try { - $this->current_user->validate_user_needed_permissions(); - $this->nonce->validate_nonce( - self::NONCE_ID, - WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'nonce' ) - ); - - $order = wc_get_order( (int) WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'order_id' ) ); - $payment = $this->get_payment( $order ); - $status = $payment['response']['status']; - - $gateway = $order->get_payment_method(); - $used_gateway = $this->get_wc_gateway_name_for_class_name($gateway); - - ( new WC_WooMercadoPago_Order() )->process_status($status, $payment, $order, $used_gateway); - - wp_send_json_success( - __( 'Order update successfully. This page will be reloaded...', 'woocommerce-mercadopago' ) - ); - } catch ( Exception $e ) { - wp_send_json_error( - __( 'Unable to update order: ', 'woocommerce-mercadopago' ) . $e->getMessage(), - 500 - ); - } - } - - /** - * Convert mercadopago gateway name for class name - * - * @param $gateway - * - * @return string|null - */ - public function get_wc_gateway_name_for_class_name( $gateway ) { - $classes_name = [ - 'woo-mercado-pago-pix' => 'WC_WooMercadoPago_Pix_Gateway', - 'woo-mercado-pago-basic' => 'WC_WooMercadoPago_Basic_Gateway', - 'woo-mercado-pago-ticket' => 'WC_WooMercadoPago_Ticket_Gateway', - 'woo-mercado-pago-custom' => 'WC_WooMercadoPago_Custom_Gateway', - 'woo-mercado-pago-credits' => 'WC_WooMercadoPago_Credits_Gateway', - ]; - - return array_key_exists ( $gateway, $classes_name ) ? $classes_name[ $gateway ] : null; - } + public const NONCE_ID = 'mp_hook_order_details_nonce'; + + /** + * WC_Order + * + * @var WC_Order + */ + protected $order; + + /** + * Nonce + * + * @var WC_WooMercadoPago_Helper_Nonce + */ + protected $nonce; + + /** + * Current User + * + * @var WC_WooMercadoPago_Helper_Current_User + */ + protected $current_user; + + /** + * Gateway + * + * @var string + */ + protected $gateway; + + public function __construct() { + $this->nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); + $this->current_user = WC_WooMercadoPago_Helper_Current_User::get_instance(); + + $this->load_hooks(); + } + + /** + * Load Hooks + * + * @return void + */ + public function load_hooks(): void { + //hook for post + add_action( 'add_meta_boxes_shop_order', array($this, 'payment_status_metabox') ); + + //hook for order + add_action( 'add_meta_boxes_woocommerce_page_wc-orders', array($this, 'payment_status_metabox') ); + add_action( 'wp_ajax_mp_sync_payment_status', array($this, 'mercadopago_sync_payment_status') ); + } + + /** + * Load Scripts + * + * @return void + */ + public function load_scripts( $order ): void { + $suffix = $this->get_suffix(); + $script_name = 'mp_payment_status_metabox'; + + if ( is_admin() ) { + wp_enqueue_script( + $script_name, + plugins_url( '../../assets/js/payment_status_metabox' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + false + ); + + wp_localize_script($script_name, $script_name . '_vars', array( + 'order_id' => $order->get_id(), + 'nonce' => $this->nonce->generate_nonce(self::NONCE_ID), + )); + } + } + + /** + * Get suffix to static files + */ + public function get_suffix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Get Alert Description + * + * @param $payment_status_detail + * @param $is_credit_card + * + * @return array + */ + public function get_alert_description( $payment_status_detail, $is_credit_card ) { + $all_status_detail = array( + 'accredited' => array( + 'alert_title' => __( 'Payment made', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Payment made by the buyer and already credited in the account.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'settled' => array( + 'alert_title' => __( 'Call resolved', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Please contact Mercado Pago for further details.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'reimbursed' => array( + 'alert_title' => __( 'Payment refunded', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Your refund request has been made. Please contact Mercado Pago for further details.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'refunded' => array( + 'alert_title' => __( 'Payment returned', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The payment has been returned to the client.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'partially_refunded' => array( + 'alert_title' => __( 'Payment returned', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The payment has been partially returned to the client.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'by_collector' => array( + 'alert_title' => __( 'Payment canceled', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The payment has been successfully canceled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'by_payer' => array( + 'alert_title' => __( 'Purchase canceled', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The payment has been canceled by the customer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Awaiting payment from the buyer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_waiting_payment' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Awaiting payment from the buyer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_waiting_for_remedy' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Awaiting payment from the buyer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_waiting_transfer' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Awaiting payment from the buyer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_review_manual' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'We are veryfing the payment. We will notify you by email in up to 6 hours if everything is fine so that you can deliver the product or provide the service.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'waiting_bank_confirmation' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_capture' => array( + 'alert_title' => __( 'Payment authorized. Awaiting capture.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( "The payment has been authorized on the client's card. Please capture the payment.", LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'in_process' => array( + 'alert_title' => __( 'Payment in process', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Please wait or contact Mercado Pago for further details', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_contingency' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The bank is reviewing the payment. As soon as we have their confirmation, we will notify you via email so that you can deliver the product or provide the service.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_card_validation' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Awaiting payment information validation.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_online_validation' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Awaiting payment information validation.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_additional_info' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Awaiting payment information validation.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'offline_process' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Please wait or contact Mercado Pago for further details', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_challenge' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Waiting for the buyer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'pending_provider_response' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Waiting for the card issuer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'bank_rejected' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The payment could not be processed. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'rejected_by_bank' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'rejected_insufficient_data' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'bank_error' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'by_admin' => array( + 'alert_title' => __( 'Mercado Pago did not process the payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Please contact Mercado Pago for further details.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'expired' => array( + 'alert_title' => __( 'Expired payment deadline', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The client did not pay within the time limit.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_bad_filled_card_number' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_bad_filled_security_code' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The CVV is invalid. Please ask your client to review the details or use another card.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_bad_filled_date' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card is expired. Please ask your client to use another card or to contact the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_high_risk' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'This payment was declined because it did not pass Mercado Pago security controls. Please ask your client to use another card.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_fraud' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The buyer is suspended in our platform. Your client must contact us to check what happened.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_blacklist' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_insufficient_amount' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => $is_credit_card + ? __( 'The card does not have enough limit. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + : __( 'The card does not have sufficient balance. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_other_reason' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card-issuing bank declined the payment. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_max_attempts' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The CVV was entered incorrectly several times. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_invalid_installments' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card does not allow the number of installments entered. Please ask your client to choose another installment plan or to use another card.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_call_for_authorize' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card-issuing bank declined the payment. Please instruct your client to ask the bank to authotize it or to use another card.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_duplicated_payment' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'From Mercado Pago we have detected that this payment has already been made before. If that is not the case, your client may try to pay again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_card_disabled' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card is not active yet. Please ask your client to use another card or to get in touch with the bank to activate it.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'payer_unavailable' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The buyer is suspended in our platform. Your client must contact us to check what happened.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'rejected_high_risk' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'This payment was declined because it did not pass Mercado Pago security controls. Please ask your client to use another card.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'rejected_by_regulations' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'This payment was declined because it did not pass Mercado Pago security controls. Please ask your client to use another card.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'rejected_cap_exceeded' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The amount exceeded the card limit. Please ask your client to use another card or to get in touch with the bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_3ds_challenge' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Please ask your client to use another card or to get in touch with the card issuer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'rejected_other_reason' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Please ask your client to use another card or to get in touch with the card issuer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'authorization_revoked' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Please ask your client to use another card or to get in touch with the card issuer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_amount_rate_limit_exceeded' => array( + 'alert_title' => __( 'Pending payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( "The amount exceeded the card's limit. Please ask your client to use another card or to get in touch with the bank.", LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_expired_operation' => array( + 'alert_title' => __( 'Expired payment deadline', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The client did not pay within the time limit.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cc_rejected_bad_filled_other' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => $is_credit_card + ? __( 'The credit function is not enabled for the card. Please tell your client that it is possible to pay with debit or to use another one.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + : __( 'The debit function is not enabled for the card. Please tell your client that it is possible to pay with credit or to use another one.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'rejected_call_for_authorize' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The card-issuing bank declined the payment. Please instruct your client to ask the bank to authorize it.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'am_insufficient_amount' => array( + 'alert_title' => __( 'Declined payment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The buyer does not have enough balance to make the purchase. Please ask your client to deposit money to the Mercado Pago Account or to use a different payment method.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'generic' => array( + 'alert_title' => __( 'There was an error', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'The transaction could not be completed.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + ); + + return array_key_exists($payment_status_detail, $all_status_detail) + ? $all_status_detail[$payment_status_detail] + : $all_status_detail['generic']; + } + + /** + * Get Alert Status + * + * @param $payment_status + * + * @return string 'success' | 'pending' | 'rejected' | 'refunded' | 'charged_back' + */ + public function get_alert_status( $payment_status ) { + $all_payment_status = array( + 'approved' => 'success', + 'authorized' => 'success', + 'pending' => 'pending', + 'in_process' => 'pending', + 'in_mediation' => 'pending', + 'rejected' => 'rejected', + 'canceled' => 'rejected', + 'refunded' => 'refunded', + 'charged_back' => 'charged_back', + 'generic' => 'rejected' + ); + + return array_key_exists($payment_status, $all_payment_status) ? $all_payment_status[$payment_status] : $all_payment_status['generic']; + } + + /** + * Get Order from Post + * + * @param $post + * + * @return bool|WC_Order|WC_Order_Refund + */ + private function get_order( $post ) { + if ( $this->order instanceof WC_Order ) { + return $this->order; + } + + if ( is_null($post->ID) ) { + return false; + } + + $this->order = wc_get_order($post->ID); + + if ( ! $this->order ) { + return false; + } + + return $this->order; + } + + /** + * Create payment status metabox + * + * @param WP_Post $post + * + * @return void + */ + public function payment_status_metabox( $post_or_order_object ): void { + $order = ( $post_or_order_object instanceof WP_Post ) ? wc_get_order( $post_or_order_object->ID ) : $post_or_order_object; + + $this->load_scripts($order); + + if ( ! $order ) { + return; + } + + $payment_method = $order->get_payment_method(); + $is_mercadopago_payment_method = in_array($payment_method, WC_WooMercadoPago_Constants::GATEWAYS_IDS, true); + + if ( ! $is_mercadopago_payment_method ) { + return; + } + + add_meta_box( + 'mp-payment-status-metabox', + __( 'Payment status on Mercado Pago', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + array($this, 'payment_status_metabox_content') + ); + } + + /** + * Payment Status Metabox Content + * + * @param wc_get_order $order + * + * @return void + * @throws WC_WooMercadoPago_Exception + */ + public function payment_status_metabox_content( $order ): void { + $payment = $this->get_payment($order); + + if ( ! $payment ) { + return; + } + + $payment_status = $payment['response']['status']; + $payment_status_details = $payment['response']['status_detail']; + + if ( ! $payment['response']['payment_type_id'] && ( + 'cc_rejected_bad_filled_other' === $payment_status_details || + 'cc_rejected_insufficient_amount' === $payment_status_details + ) ) { + return; + } + + $is_credit_card = 'credit_card' === $payment['response']['payment_type_id']; + $alert_status = $this->get_alert_status($payment_status); + $alert_description = $this->get_alert_description($payment_status_details, $is_credit_card); + $metabox_data = $this->get_metabox_data($alert_status, $alert_description); + + wc_get_template( + 'order/payment-status-metabox-content.php', + $metabox_data, + 'woo/mercado/pago/module/', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Metabolic Data + * + * @param $alert_status + * @param $alert + * @return Array + */ + public function get_metabox_data( $alert_status, $alert ) { + $country = strtolower(get_option( 'checkout_country', '' )); + + if ( 'success' === $alert_status ) { + return array( + 'img_src' => esc_url( plugins_url( '../../assets/images/generics/circle-green-check.png', plugin_dir_path( __FILE__ ) ) ), + 'alert_title' => $alert['alert_title'], + 'alert_description' => $alert['description'], + 'link' => $this->get_mp_home_link($country), + 'border_left_color' => '#00A650', + 'link_description' => __( 'View purchase details at Mercado Pago', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'sync_button_text' => __( 'Sync order status', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + } + + if ( 'pending' === $alert_status ) { + return array( + 'img_src' => esc_url( plugins_url( '../../assets/images/generics/circle-alert.png', plugin_dir_path( __FILE__ ) ) ), + 'alert_title' => $alert['alert_title'], + 'alert_description' => $alert['description'], + 'link' => $this->get_mp_home_link($country), + 'border_left_color' => '#f73', + 'link_description' => __( 'View purchase details at Mercado Pago', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'sync_button_text' => __( 'Sync order status', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + } + + if ( 'rejected' === $alert_status || 'refunded' === $alert_status || 'charged_back' === $alert_status ) { + return array( + 'img_src' => esc_url( plugins_url( '../../assets/images/generics/circle-red-alert.png', plugin_dir_path( __FILE__ ) ) ), + 'alert_title' => $alert['alert_title'], + 'alert_description' => $alert['description'], + 'link' => $this->get_mp_devsite_link($country), + 'border_left_color' => '#F23D4F', + 'link_description' => __( 'Check the reasons why the purchase was declined.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'sync_button_text' => __( 'Sync order status', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + } + } + + /** + * Get Mercado Pago Home Link + * + * @param String $country Country Acronym + * + * @return String + */ + public function get_mp_home_link( $country ) { + $country_links = array( + 'mla' => 'https://www.mercadopago.com.ar/home', + 'mlb' => 'https://www.mercadopago.com.br/home', + 'mlc' => 'https://www.mercadopago.cl/home', + 'mco' => 'https://www.mercadopago.com.co/home', + 'mlm' => 'https://www.mercadopago.com.mx/home', + 'mpe' => 'https://www.mercadopago.com.pe/home', + 'mlu' => 'https://www.mercadopago.com.uy/home', + ); + + return array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; + } + + /** + * Get Mercado Pago Devsite Page Link + * + * @param String $country Country Acronym + * + * @return String + */ + public function get_mp_devsite_link( $country ) { + $country_links = array( + 'mla' => 'https://www.mercadopago.com.ar/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', + 'mlb' => 'https://www.mercadopago.com.br/developers/pt/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_recusas', + 'mlc' => 'https://www.mercadopago.cl/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', + 'mco' => 'https://www.mercadopago.com.co/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', + 'mlm' => 'https://www.mercadopago.com.mx/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', + 'mpe' => 'https://www.mercadopago.com.pe/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', + 'mlu' => 'https://www.mercadopago.com.uy/developers/es/guides/plugins/woocommerce/sales-processing#bookmark_motivos_de_las_recusas', + ); + + return array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; + } + + /** + * Get payment + * + * @return array|null + * @throws WC_WooMercadoPago_Exception + */ + public function get_payment( $post_or_order_object ) { + $order = ( $post_or_order_object instanceof WP_Post ) ? wc_get_order( $post_or_order_object->ID ) : $post_or_order_object; + + if ( ! $order ) { + return null; + } + + $payment_ids = explode(',', $order->get_meta( '_Mercado_Pago_Payment_IDs' )); + + if ( empty( $payment_ids ) ) { + return null; + } + + $last_payment_id = end($payment_ids); + $is_production_mode = $order->get_meta( 'is_production_mode' ); + $access_token = 'no' === $is_production_mode || ! $is_production_mode + ? get_option( '_mp_access_token_test' ) + : get_option( '_mp_access_token_prod' ); + + $mp = new MP($access_token); + $payment = $mp->search_payment_v1(trim($last_payment_id), $access_token); + + if ( ! $payment || 200 !== $payment['status'] ) { + return null; + } + + return $payment; + } + + /** + * Sync order status + * + * @return void + */ + public function mercadopago_sync_payment_status(): void { + try { + $this->current_user->validate_user_needed_permissions(); + $this->nonce->validate_nonce( + self::NONCE_ID, + WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'nonce' ) + ); + + $order = wc_get_order( (int) WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'order_id' ) ); + $payment = $this->get_payment( $order ); + $status = $payment['response']['status']; + + $gateway = $order->get_payment_method(); + $used_gateway = $this->get_wc_gateway_name_for_class_name($gateway); + + ( new WC_WooMercadoPago_Order() )->process_status($status, $payment, $order, $used_gateway); + + wp_send_json_success( + __( 'Order update successfully. This page will be reloaded...', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } catch ( Exception $e ) { + wp_send_json_error( + __( 'Unable to update order: ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . $e->getMessage(), + 500 + ); + } + } + + /** + * Convert mercadopago gateway name for class name + * + * @param $gateway + * + * @return string|null + */ + public function get_wc_gateway_name_for_class_name( $gateway ) { + $classes_name = array( + 'woo-mercado-pago-pix' => 'WC_WooMercadoPago_Pix_Gateway', + 'woo-mercado-pago-basic' => 'WC_WooMercadoPago_Basic_Gateway', + 'woo-mercado-pago-ticket' => 'WC_WooMercadoPago_Ticket_Gateway', + 'woo-mercado-pago-custom' => 'WC_WooMercadoPago_Custom_Gateway', + 'woo-mercado-pago-credits' => 'WC_WooMercadoPago_Credits_Gateway', + ); + + return array_key_exists ( $gateway, $classes_name ) ? $classes_name[ $gateway ] : null; + } } diff --git a/includes/admin/index.php b/includes/admin/index.php index 258f3fae9..891711d6d 100644 --- a/includes/admin/index.php +++ b/includes/admin/index.php @@ -1,12 +1,5 @@ get_suffix(); - - wp_enqueue_style( - 'woocommerce-mercadopago-admin-notice', - plugins_url( '../../assets/css/admin_notice_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - } - } - - /** - * Alert frame - * - * @param string $message message. - * @param string $type type. - */ - public static function get_alert_frame( $message, $type ) { - - $inline = ''; - if ( - ( class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::is_wc_new_version() ) - && 'wc-settings' === sanitize_key( isset($_GET['page']) ) // phpcs:disable WordPress.Security.NonceVerification - ) { - $inline = 'inline'; - } - - $notice = '
+ /** + * Static Instance + * + * @var WC_WooMercadoPago_Notices + */ + public static $instance = null; + + /** + * Constructor + */ + private function __construct() { + add_action( 'admin_enqueue_scripts', array($this, 'load_admin_notice_css') ); + } + + /** + * Initialize + * + * @return WC_WooMercadoPago_Notices|null + * Singleton + */ + public static function init_mercadopago_notice() { + if ( null === self::$instance ) { + self::$instance = new self(); + } + return self::$instance; + } + + /** + * Get sufix to static files + */ + public function get_suffix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Load admin notices CSS + */ + public function load_admin_notice_css(): void { + if ( is_admin() ) { + $suffix = $this->get_suffix(); + + wp_enqueue_style( + 'woocommerce-mercadopago-admin-notice', + plugins_url( '../../assets/css/admin_notice_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + } + } + + /** + * Alert frame + * + * @param string $message message. + * @param string $type type. + */ + public static function get_alert_frame( $message, $type ) { + $inline = ''; + if ( + ( class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::is_wc_new_version() ) + && 'wc-settings' === sanitize_key( isset($_GET['page']) ) // phpcs:disable WordPress.Security.NonceVerification + ) { + $inline = 'inline'; + } + + $notice = '
@@ -96,46 +86,46 @@ public static function get_alert_frame( $message, $type ) {
'; - if ( class_exists( 'WC_WooMercadoPago_Module' ) ) { - WC_WooMercadoPago_Module::$notices[] = $notice; - } - - return $notice; - } - - /** - * Get Alert Woocommer Miss - * - * @param string $message message. - * @param string $type type. - */ - public static function get_alert_woocommerce_miss( $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' ) ) { - $button_url = '' . __( 'Activate WooCommerce', 'woocommerce-mercadopago' ) . ''; - } else { - if ( current_user_can( 'install_plugins' ) ) { - $button_url = '' . __( 'Install WooCommerce', 'woocommerce-mercadopago' ) . ''; - } else { - $button_url = '' . __( 'See WooCommerce', 'woocommerce-mercadopago' ) . ''; - } - } - - $inline = ''; - if ( - ( class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::is_wc_new_version() ) - // phpcs:disable WordPress.Security.NonceVerification - && 'wc-settings' === sanitize_key( isset($_GET['page']) ) - ) { - $inline = 'inline'; - } - - include dirname( __FILE__ ) . '/../views/html-admin-alert-woocommerce-miss.php'; - } + if ( class_exists( 'WC_WooMercadoPago_Module' ) ) { + WC_WooMercadoPago_Module::$notices[] = $notice; + } + + return $notice; + } + + /** + * Get Alert Woocommer Miss + * + * @param string $message message. + * @param string $type type. + */ + public static function get_alert_woocommerce_miss( $message, $type ): void { + $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' ) ) { + $button_url = '' . __( 'Activate WooCommerce', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ''; + } else { + if ( current_user_can( 'install_plugins' ) ) { + $button_url = '' . __( 'Install WooCommerce', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ''; + } else { + $button_url = '' . __( 'See WooCommerce', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ''; + } + } + + $inline = ''; + if ( + ( class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::is_wc_new_version() ) + // phpcs:disable WordPress.Security.NonceVerification + && 'wc-settings' === sanitize_key( isset($_GET['page']) ) + ) { + $inline = 'inline'; + } + + include __DIR__ . '/../views/html-admin-alert-woocommerce-miss.php'; + } } diff --git a/includes/admin/notices/class-wc-woomercadopago-review-notice.php b/includes/admin/notices/class-wc-woomercadopago-review-notice.php index a6339f213..ce79e8fc4 100644 --- a/includes/admin/notices/class-wc-woomercadopago-review-notice.php +++ b/includes/admin/notices/class-wc-woomercadopago-review-notice.php @@ -1,131 +1,123 @@ nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); - $this->current_user = WC_WooMercadoPago_Helper_Current_User::get_instance(); - - add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_notice_css' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_notice_js' ) ); - add_action( 'wp_ajax_mercadopago_review_dismiss', array( $this, 'review_dismiss' ) ); - } - - /** - * Singleton - * - * @return WC_WooMercadoPago_Review_Notice|null - */ - public static function init_mercadopago_review_notice() { - if ( null === self::$instance ) { - self::$instance = new self(); - } - return self::$instance; - } - - /** - * Get sufix to static files - */ - public function get_suffix() { - return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - } - - /** - * Load admin notices CSS - */ - public function load_admin_notice_css() { - if ( is_admin() ) { - $suffix = $this->get_suffix(); - - wp_enqueue_style( - 'woocommerce-mercadopago-admin-notice', - plugins_url( '../../assets/css/admin_notice_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - } - } - - /** - * Load admin notices JS - */ - public function load_admin_notice_js() { - if ( is_admin() ) { - $suffix = $this->get_suffix(); - $script_name = 'woocommerce_mercadopago_admin_notice_review'; - - wp_enqueue_script( - $script_name, - plugins_url( '../../assets/js/review' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - false - ); - - wp_localize_script($script_name, $script_name . '_vars', [ - 'nonce' => $this->nonce->generate_nonce(self::REVIEW_NOTICE_NONCE_ID), - ]); - } - } - - /** - * Get Plugin Review Banner - * - * @return string - */ - public static function get_plugin_review_banner() { - $inline = null; - - if ( - class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::is_wc_new_version() && - isset( $_GET['page']) && 'wc-settings' === sanitize_key( $_GET['page'] ) // phpcs:ignore WordPress.Security.NonceVerification - ) { - $inline = 'inline'; - } - - $notice = '
+ public const REVIEW_NOTICE_NONCE_ID = 'mp_review_notice_nonce'; + + /** + * WP_Nonce + * + * @var WC_WooMercadoPago_Helper_Nonce + */ + protected $nonce; + + /** + * WP_Current_user + * + * @var WC_WooMercadoPago_Helper_Current_User + */ + protected $current_user; + + /** + * Static instance + * + * @var WC_WooMercadoPago_Review_Notice + */ + public static $instance = null; + + /** + * WC_WooMercadoPago_ReviewNotice constructor. + */ + private function __construct() { + $this->nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); + $this->current_user = WC_WooMercadoPago_Helper_Current_User::get_instance(); + + add_action( 'admin_enqueue_scripts', array($this, 'load_admin_notice_css') ); + add_action( 'admin_enqueue_scripts', array($this, 'load_admin_notice_js') ); + add_action( 'wp_ajax_mercadopago_review_dismiss', array($this, 'review_dismiss') ); + } + + /** + * Singleton + * + * @return WC_WooMercadoPago_Review_Notice|null + */ + public static function init_mercadopago_review_notice() { + if ( null === self::$instance ) { + self::$instance = new self(); + } + return self::$instance; + } + + /** + * Get sufix to static files + */ + public function get_suffix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Load admin notices CSS + */ + public function load_admin_notice_css(): void { + if ( is_admin() ) { + $suffix = $this->get_suffix(); + + wp_enqueue_style( + 'woocommerce-mercadopago-admin-notice', + plugins_url( '../../assets/css/admin_notice_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + } + } + + /** + * Load admin notices JS + */ + public function load_admin_notice_js(): void { + if ( is_admin() ) { + $suffix = $this->get_suffix(); + $script_name = 'woocommerce_mercadopago_admin_notice_review'; + + wp_enqueue_script( + $script_name, + plugins_url( '../../assets/js/review' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + false + ); + + wp_localize_script($script_name, $script_name . '_vars', array( + 'nonce' => $this->nonce->generate_nonce(self::REVIEW_NOTICE_NONCE_ID), + )); + } + } + + /** + * Get Plugin Review Banner + * + * @return string + */ + public static function get_plugin_review_banner() { + $inline = null; + + if ( + class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::is_wc_new_version() && + isset( $_GET['page']) && 'wc-settings' === sanitize_key( $_GET['page'] ) // phpcs:ignore WordPress.Security.NonceVerification + ) { + $inline = 'inline'; + } + + $notice = '
@@ -133,12 +125,12 @@ class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::is_wc_ne

' . - 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?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

' . - __( '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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

@@ -146,36 +138,35 @@ class_exists( 'WC_WooMercadoPago_Module' ) && WC_WooMercadoPago_Module::is_wc_ne 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', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '
'; - if ( class_exists( 'WC_WooMercadoPago_Module' ) ) { - WC_WooMercadoPago_Module::$notices[] = $notice; - } - - return $notice; - } + if ( class_exists( 'WC_WooMercadoPago_Module' ) ) { + WC_WooMercadoPago_Module::$notices[] = $notice; + } - /** - * Dismiss the review admin notice - */ - public function review_dismiss() { - $this->current_user->validate_user_needed_permissions(); - $this->nonce->validate_nonce( - self::REVIEW_NOTICE_NONCE_ID, - WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'nonce' ) - ); + return $notice; + } - $dismissed_review = (int) get_option( '_mp_dismiss_review', 0 ); + /** + * Dismiss the review admin notice + */ + public function review_dismiss(): void { + $this->current_user->validate_user_needed_permissions(); + $this->nonce->validate_nonce( + self::REVIEW_NOTICE_NONCE_ID, + WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'nonce' ) + ); - if ( 0 === $dismissed_review ) { - update_option( '_mp_dismiss_review', 1, true ); - } + $dismissed_review = (int) get_option( '_mp_dismiss_review', 0 ); - wp_send_json_success(); - } + if ( 0 === $dismissed_review ) { + update_option( '_mp_dismiss_review', 1, true ); + } + wp_send_json_success(); + } } diff --git a/includes/admin/notices/class-wc-woomercadopago-saved-cards.php b/includes/admin/notices/class-wc-woomercadopago-saved-cards.php index e52527655..1f22d90b1 100644 --- a/includes/admin/notices/class-wc-woomercadopago-saved-cards.php +++ b/includes/admin/notices/class-wc-woomercadopago-saved-cards.php @@ -1,158 +1,150 @@ file_suffix = $this->get_suffix(); - $this->nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); - $this->current_user = WC_WooMercadoPago_Helper_Current_User::get_instance(); - - add_action( 'admin_enqueue_scripts', array( $this, 'load_saved_cards_notice_css' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'load_saved_cards_notice_js' ) ); - add_action( 'wp_ajax_mercadopago_saved_cards_notice_dismiss', array( $this, 'saved_cards_notice_dismiss' ) ); - } - - /** - * Init Singleton - * - * @return WC_WooMercadoPago_Saved_Cards|null - */ - public static function init_singleton() { - if ( null === self::$instance ) { - self::$instance = new self(); - } - - return self::$instance; - } - - /** - * Get sufix to static files - */ - private function get_suffix() { - return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - } - - /** - * Load admin notices CSS - * - * @return void - */ - public function load_saved_cards_notice_css() { - if ( is_admin() ) { - wp_enqueue_style( - 'woocommerce-mercadopago-admin-saved-cards', - plugins_url( '../../assets/css/saved_cards_notice_mercadopago' . $this->file_suffix . '.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - } - } - - /** - * Load admin notices JS - * - * @return void - */ - public function load_saved_cards_notice_js() { - if ( is_admin() ) { - $script_name = 'woocommerce_mercadopago_admin_saved_cards'; - - wp_enqueue_script( - $script_name, - plugins_url( '../../assets/js/saved_cards_notice_mercadopago' . $this->file_suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - false - ); - - wp_localize_script($script_name, $script_name . '_vars', [ - 'nonce' => $this->nonce->generate_nonce(self::SAVED_CARDS_NONCE_ID), - ]); - } - } - - /** - * Should Be Inline Style - * - * @return bool - */ - public static function should_be_inline_style() { - return class_exists( 'WC_WooMercadoPago_Module' ) - && WC_WooMercadoPago_Module::is_wc_new_version() - && isset( $_GET['page']) // phpcs:ignore WordPress.Security.NonceVerification - && 'wc-settings' === sanitize_key( $_GET['page'] ); // phpcs:ignore WordPress.Security.NonceVerification - } - - /** - * Get Plugin Review Banner - * - * @return string - */ - public static function get_plugin_review_banner() { - $inline = self::should_be_inline_style() ? 'inline' : null; - $checkout_custom_url = admin_url('admin.php?page=wc-settings&tab=checkout§ion=woo-mercado-pago-custom'); - - $notice = '
+ public const SAVED_CARDS_NONCE_ID = 'mp_saved_cards_nonce'; + + /** + * WP_Nonce + * + * @var WC_WooMercadoPago_Helper_Nonce + */ + protected $nonce; + + /** + * WP_Current_user + * + * @var WC_WooMercadoPago_Helper_Current_User + */ + protected $current_user; + + /** + * File Suffix + * + * @var string + */ + private $file_suffix; + + /** + * Static instance + * + * @var WC_WooMercadoPago_Saved_Cards + */ + private static $instance = null; + + /** + * WC_WooMercadoPago_Saved_Cards constructor. + */ + public function __construct() { + $this->file_suffix = $this->get_suffix(); + $this->nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); + $this->current_user = WC_WooMercadoPago_Helper_Current_User::get_instance(); + + add_action( 'admin_enqueue_scripts', array($this, 'load_saved_cards_notice_css') ); + add_action( 'admin_enqueue_scripts', array($this, 'load_saved_cards_notice_js') ); + add_action( 'wp_ajax_mercadopago_saved_cards_notice_dismiss', array($this, 'saved_cards_notice_dismiss') ); + } + + /** + * Init Singleton + * + * @return WC_WooMercadoPago_Saved_Cards|null + */ + public static function init_singleton() { + if ( null === self::$instance ) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * Get sufix to static files + */ + private function get_suffix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Load admin notices CSS + * + * @return void + */ + public function load_saved_cards_notice_css(): void { + if ( is_admin() ) { + wp_enqueue_style( + 'woocommerce-mercadopago-admin-saved-cards', + plugins_url( '../../assets/css/saved_cards_notice_mercadopago' . $this->file_suffix . '.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + } + } + + /** + * Load admin notices JS + * + * @return void + */ + public function load_saved_cards_notice_js(): void { + if ( is_admin() ) { + $script_name = 'woocommerce_mercadopago_admin_saved_cards'; + + wp_enqueue_script( + $script_name, + plugins_url( '../../assets/js/saved_cards_notice_mercadopago' . $this->file_suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + false + ); + + wp_localize_script($script_name, $script_name . '_vars', array( + 'nonce' => $this->nonce->generate_nonce(self::SAVED_CARDS_NONCE_ID), + )); + } + } + + /** + * Should Be Inline Style + * + * @return bool + */ + public static function should_be_inline_style() { + return class_exists( 'WC_WooMercadoPago_Module' ) + && WC_WooMercadoPago_Module::is_wc_new_version() + && isset( $_GET['page']) // phpcs:ignore WordPress.Security.NonceVerification + && 'wc-settings' === sanitize_key( $_GET['page'] ); // phpcs:ignore WordPress.Security.NonceVerification + } + + /** + * Get Plugin Review Banner + * + * @return string + */ + public static function get_plugin_review_banner() { + $inline = self::should_be_inline_style() ? 'inline' : null; + $checkout_custom_url = admin_url('admin.php?page=wc-settings&tab=checkout§ion=woo-mercado-pago-custom'); + + $notice = '

' . - __( 'Enable payments via Mercado Pago account', 'woocommerce-mercadopago' ) . - '

+ __( 'Enable payments via Mercado Pago account', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

' . - __( 'When you enable this function, your customers pay faster using their Mercado Pago accounts.
The approval rate of these payments in your store can be 25% higher compared to other payment methods.', 'woocommerce-mercadopago' ) . - '

+ __( 'When you enable this function, your customers pay faster using their Mercado Pago accounts.
The approval rate of these payments in your store can be 25% higher compared to other payment methods.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

@@ -160,35 +152,35 @@ public static function get_plugin_review_banner() { class="mp-saved-cards-link" href="' . $checkout_custom_url . '" >' - . __( 'Activate', 'woocommerce-mercadopago' ) . - ' + . __( 'Activate', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '
'; - 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 saved_cards_notice_dismiss() { - $this->current_user->validate_user_needed_permissions(); - $this->nonce->validate_nonce( - self::SAVED_CARDS_NONCE_ID, - WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'nonce' ) - ); + /** + * Dismiss the review admin notice + */ + public function saved_cards_notice_dismiss(): void { + $this->current_user->validate_user_needed_permissions(); + $this->nonce->validate_nonce( + self::SAVED_CARDS_NONCE_ID, + WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'nonce' ) + ); - $hide = 1; - $must_show_notice = (int) get_option( '_mp_dismiss_saved_cards_notice', 0 ); + $hide = 1; + $must_show_notice = (int) get_option( '_mp_dismiss_saved_cards_notice', 0 ); - if ( ! $must_show_notice ) { - update_option( '_mp_dismiss_saved_cards_notice', $hide, true ); - } + if ( ! $must_show_notice ) { + update_option( '_mp_dismiss_saved_cards_notice', $hide, true ); + } - wp_send_json_success(); - } + wp_send_json_success(); + } } diff --git a/includes/admin/notices/index.php b/includes/admin/notices/index.php index 258f3fae9..891711d6d 100644 --- a/includes/admin/notices/index.php +++ b/includes/admin/notices/index.php @@ -1,12 +1,5 @@ -
-
-
- +
+
+ -
-
-

- -

-
-
- -
+
+
+

+ +

+
+
+ +
\ No newline at end of file diff --git a/includes/admin/views/html-admin-alert-woocommerce-miss.php b/includes/admin/views/html-admin-alert-woocommerce-miss.php index 712981363..0fd7c97e6 100644 --- a/includes/admin/views/html-admin-alert-woocommerce-miss.php +++ b/includes/admin/views/html-admin-alert-woocommerce-miss.php @@ -4,31 +4,32 @@ * * @package Mercadopago/admin/notices */ - if ( ! defined( 'ABSPATH' ) ) { - exit; + exit; } ?> -
-
-
- -
-
- is-dismissible "> +
+
+ +
+
+ -

-

-
-
- -
+?> +

+

+
+
+ +
\ No newline at end of file diff --git a/includes/admin/views/index.php b/includes/admin/views/index.php index 258f3fae9..891711d6d 100644 --- a/includes/admin/views/index.php +++ b/includes/admin/views/index.php @@ -1,12 +1,5 @@ $exploded[0], - 'payment_place_id' => isset($exploded[1]) ? $exploded[1] : null, - ]; - } + return array( + 'payment_method_id' => $exploded[0], + 'payment_place_id' => isset($exploded[1]) ? $exploded[1] : null, + ); + } - public function getPaymentMethodId( $compositeId ) { - return $this->parse($compositeId)['payment_method_id']; - } + public function getPaymentMethodId( $compositeId ) { + return $this->parse($compositeId)['payment_method_id']; + } - public function getPaymentPlaceId( $compositeId ) { - return $this->parse($compositeId)['payment_place_id']; - } + public function getPaymentPlaceId( $compositeId ) { + return $this->parse($compositeId)['payment_place_id']; + } } diff --git a/includes/helpers/class-wc-woomercadopago-helper-credits-enable.php b/includes/helpers/class-wc-woomercadopago-helper-credits-enable.php new file mode 100644 index 000000000..fab295d2e --- /dev/null +++ b/includes/helpers/class-wc-woomercadopago-helper-credits-enable.php @@ -0,0 +1,61 @@ +settings['already_enabled_by_default']) && $creditsGateway->get_option('already_enabled_by_default') ) { + return; + } + + if ( isset($basicGateway->settings['enabled']) && $basicGateway->get_option('enabled') === 'yes' ) { + $creditsGateway->active_by_default(); + update_option(self::ALREADY_ENABLE_BY_DEFAULT, 'yes'); + } + } + } + } catch ( Exception $ex ) { + wc_get_logger()->error($ex->getMessage(), array('source' => __CLASS__)); + } + } +} diff --git a/includes/helpers/class-wc-woomercadopago-helper-credits.php b/includes/helpers/class-wc-woomercadopago-helper-credits.php index 957b7b6a6..86e930935 100644 --- a/includes/helpers/class-wc-woomercadopago-helper-credits.php +++ b/includes/helpers/class-wc-woomercadopago-helper-credits.php @@ -1,61 +1,53 @@ mp = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + public function __construct() { + $this->mp = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - if ( null === $this->mp_options ) { - $this->mp_options = WC_WooMercadoPago_Options::get_instance(); - } - return $this->mp_options; - } + if ( null === $this->mp_options ) { + $this->mp_options = WC_WooMercadoPago_Options::get_instance(); + } + return $this->mp_options; + } - /** - * Get Payment Response function - * - * @return bool - */ - public function is_credits() { - $site = strtoupper($this->mp_options->get_site_id()); - $payments_response = $this->mp->get_payment_response_by_sites($site); - if ( is_array($payments_response) ) { - foreach ( $payments_response as $payment ) { - if ( isset( $payment['id'] ) && 'consumer_credits' === $payment['id'] ) { - return true; - } - } - } - return false; - } + /** + * Get Payment Response function + * + * @return bool + */ + public function is_credits() { + $site = strtoupper($this->mp_options->get_site_id()); + $payments_response = $this->mp->get_payment_response_by_sites($site); + if ( is_array($payments_response) ) { + foreach ( $payments_response as $payment ) { + if ( isset( $payment['id'] ) && 'consumer_credits' === $payment['id'] ) { + return true; + } + } + } + return false; + } } diff --git a/includes/helpers/class-wc-woomercadopago-helper-current-url.php b/includes/helpers/class-wc-woomercadopago-helper-current-url.php index 0836bf1b5..1dff049e9 100644 --- a/includes/helpers/class-wc-woomercadopago-helper-current-url.php +++ b/includes/helpers/class-wc-woomercadopago-helper-current-url.php @@ -1,68 +1,59 @@ log = new WC_WooMercadoPago_Log($this); - $this->options = WC_WooMercadoPago_Options::get_instance(); - $this->debug_mode = false === $this->options->get_debug_mode() ? 'no' : $this->options->get_instance()->get_debug_mode(); - } + /** + * Current User constructor + */ + private function __construct() { + $this->log = new WC_WooMercadoPago_Log($this); + $this->options = WC_WooMercadoPago_Options::get_instance(); + $this->debug_mode = false === $this->options->get_debug_mode() ? 'no' : $this->options->get_instance()->get_debug_mode(); + } - /** - * Get WC_WooMercadoPago_Helper_Current_User instance - * - * @return WC_WooMercadoPago_Helper_Current_User - */ - public static function get_instance() { - if ( null === self::$instance ) { - self::$instance = new self(); - } - return self::$instance; - } + /** + * Get WC_WooMercadoPago_Helper_Current_User instance + * + * @return WC_WooMercadoPago_Helper_Current_User + */ + public static function get_instance() { + if ( null === self::$instance ) { + self::$instance = new self(); + } + return self::$instance; + } - /** - * Get current user roles - * - * @return WP_User - */ - public function get_current_user() { - return wp_get_current_user(); - } + /** + * Get current user roles + * + * @return WP_User + */ + public function get_current_user() { + return wp_get_current_user(); + } - /** - * Verify if current_user has specifics roles - * - * @param array $roles 'administrator | editor | author | contributor | subscriber' - * - * @return bool - */ - public function user_has_roles( $roles ) { - $current_user = $this->get_current_user(); - return is_super_admin( $current_user ) || ! empty ( array_intersect( $roles, $current_user->roles ) ); - } + /** + * Verify if current_user has specifics roles + * + * @param array $roles 'administrator | editor | author | contributor | subscriber' + * + * @return bool + */ + public function user_has_roles( $roles ) { + $current_user = $this->get_current_user(); + return is_super_admin( $current_user ) || ! empty ( array_intersect( $roles, $current_user->roles ) ); + } - /** - * Validate if user has administrator or editor permissions - * - * @return void - */ - public function validate_user_needed_permissions() { - $needed_roles = ['administrator', 'editor', 'author', 'contributor', 'subscriber']; + /** + * Validate if user has administrator or editor permissions + * + * @return void + */ + public function validate_user_needed_permissions(): void { + $needed_roles = array('administrator', 'editor', 'author', 'contributor', 'subscriber'); - if ( ! $this->user_has_roles( $needed_roles ) ) { - $this->log->write_log(__FUNCTION__, 'User does not have permission (need admin or editor).'); - wp_send_json_error('Forbidden', 403); - } - } + if ( ! $this->user_has_roles( $needed_roles ) ) { + $this->log->write_log(__FUNCTION__, 'User does not have permission (need admin or editor).'); + wp_send_json_error('Forbidden', 403); + } + } } diff --git a/includes/helpers/class-wc-woomercadopago-helper-filter.php b/includes/helpers/class-wc-woomercadopago-helper-filter.php index 60a1be487..e07c9b807 100644 --- a/includes/helpers/class-wc-woomercadopago-helper-filter.php +++ b/includes/helpers/class-wc-woomercadopago-helper-filter.php @@ -1,31 +1,23 @@ $link_prefix_mp . $link_settings ['sufix_url'] . $link_costs_mp, - 'link_guides_plugin' => $link_prefix_mp . $link_settings ['sufix_url'] . $link_developers . $link_settings ['translate'] . $link_guides, - 'link_credentials' => $link_prefix_mp_link . $link_developers . $link_credentials, - ); - } + /** + * Links by country configured in woocommerce. + */ + public static function woomercadopago_settings_links() { + $link_settings = WC_WooMercadoPago_Module::define_link_country(); + $link_prefix_mp = 'https://www.mercadopago.'; + $link_costs_mp = 'costs-section'; + $link_developers = 'developers/'; + $link_guides = '/docs/woocommerce/integration-configuration'; + $link_credentials = 'settings/account/credentials'; - public static function get_mp_devsite_links() { - $link = WC_WooMercadoPago_Module::define_link_country(); - $base_link = 'https://www.mercadopago.com/developers/' . $link['translate']; + return array ( + 'link_costs' => $link_prefix_mp . $link_settings['sufix_url'] . $link_costs_mp, + 'link_guides_plugin' => $link_prefix_mp . $link_settings['sufix_url'] . $link_developers . $link_settings['translate'] . $link_guides, + 'link_credentials' => $link_prefix_mp . $link_settings['sufix_url'] . $link_credentials + ); + } - return array( - 'dev_program' => $base_link . '/developer-program', - 'notifications_ipn' => $base_link . '/guides/notifications/ipn', - 'shopping_testing' => $base_link . '/docs/woocommerce/integration-test', - 'test_cards' => $base_link . '/docs/checkout-api/integration-test/test-cards' - ); - } + public static function get_mp_devsite_links() { + $link = WC_WooMercadoPago_Module::define_link_country(); + $base_link = 'https://www.mercadopago.com/developers/' . $link['translate']; - /** - * Get Mercado Pago Devsite Page Link - * - * @param String $country Country Acronym - * - * @return String - */ - public static function get_mp_devsite_link( $country ) { - $country_links = [ - 'mla' => 'https://www.mercadopago.com.ar/developers/es/guides/plugins/woocommerce/testing', - 'mlb' => 'https://www.mercadopago.com.br/developers/pt/guides/plugins/woocommerce/testing', - 'mlc' => 'https://www.mercadopago.cl/developers/es/guides/plugins/woocommerce/testing', - 'mco' => 'https://www.mercadopago.com.co/developers/es/guides/plugins/woocommerce/testing', - 'mlm' => 'https://www.mercadopago.com.mx/developers/es/guides/plugins/woocommerce/testing', - 'mpe' => 'https://www.mercadopago.com.pe/developers/es/guides/plugins/woocommerce/testing', - 'mlu' => 'https://www.mercadopago.com.uy/developers/es/guides/plugins/woocommerce/testing', - ]; + return array( + 'dev_program' => $base_link . '/developer-program', + 'notifications_ipn' => $base_link . '/guides/notifications/ipn', + 'shopping_testing' => $base_link . '/docs/woocommerce/integration-test', + 'test_cards' => $base_link . '/docs/checkout-api/integration-test/test-cards' + ); + } - return array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; - } + /** + * Get Mercado Pago Devsite Page Link + * + * @param String $country Country Acronym + * + * @return String + */ + public static function get_mp_devsite_link( $country ) { + $country_links = array( + 'mla' => 'https://www.mercadopago.com.ar/developers/es/guides/plugins/woocommerce/testing', + 'mlb' => 'https://www.mercadopago.com.br/developers/pt/guides/plugins/woocommerce/testing', + 'mlc' => 'https://www.mercadopago.cl/developers/es/guides/plugins/woocommerce/testing', + 'mco' => 'https://www.mercadopago.com.co/developers/es/guides/plugins/woocommerce/testing', + 'mlm' => 'https://www.mercadopago.com.mx/developers/es/guides/plugins/woocommerce/testing', + 'mpe' => 'https://www.mercadopago.com.pe/developers/es/guides/plugins/woocommerce/testing', + 'mlu' => 'https://www.mercadopago.com.uy/developers/es/guides/plugins/woocommerce/testing', + ); - /** - * Get Country Link to Mercado Pago - * - * @param string $checkout Checkout by country. - * @return string - */ - public static function get_country_link_mp_terms() { - $country_link = [ - 'mla' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.ar/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Argentinian. - ], - 'mlb' => [ - 'help' => 'ajuda', - 'sufix_url' => 'com.br/', - 'translate' => 'pt', - 'term_conditition' => '/termos-e-politicas_194', //Brasil - ], - 'mlc' => [ - 'help' => 'ayuda', - 'sufix_url' => 'cl/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Chile. - ], - 'mco' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.co/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Colombia. - ], - 'mlm' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.mx/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Mexico. - ], - 'mpe' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.pe/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Peru. - ], - 'mlu' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.uy/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Uruguay. - ], - ]; + return array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; + } - $option_country = WC_WooMercadoPago_Options::get_instance(); - $checkout_country = strtolower($option_country->get_checkout_country()); + /** + * Get Country Link to Mercado Pago + * + * @param string $checkout Checkout by country. + * @return string + */ + public static function get_country_link_mp_terms() { + $country_link = array( + 'mla' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.ar/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Argentinian. + ), + 'mlb' => array( + 'help' => 'ajuda', + 'sufix_url' => 'com.br/', + 'translate' => 'pt', + 'term_conditition' => '/termos-e-politicas_194', //Brasil + ), + 'mlc' => array( + 'help' => 'ayuda', + 'sufix_url' => 'cl/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Chile. + ), + 'mco' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.co/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Colombia. + ), + 'mlm' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.mx/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Mexico. + ), + 'mpe' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.pe/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Peru. + ), + 'mlu' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.uy/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Uruguay. + ), + ); - return $country_link[ $checkout_country ]; - } + $option_country = WC_WooMercadoPago_Options::get_instance(); + $checkout_country = strtolower($option_country->get_checkout_country()); - /** - * - * Define terms and conditions link - * - * @return array - */ - public static function mp_define_terms_and_conditions() { + return $country_link[ $checkout_country ]; + } - $links_mp = self::get_country_link_mp_terms(); - $link_prefix_mp = 'https://www.mercadopago.'; - return array ( - 'text_prefix' => __( 'By continuing, you agree to our ', 'woocommerce-mercadopago' ), - 'link_terms_and_conditions' => $link_prefix_mp . $links_mp['sufix_url'] . $links_mp['help'] . $links_mp['term_conditition'], - 'text_suffix' => __( 'Terms and Conditions', 'woocommerce-mercadopago' ), - ); - } + /** + * + * Define terms and conditions link + * + * @return array + */ + public static function mp_define_terms_and_conditions() { + $links_mp = self::get_country_link_mp_terms(); + $link_prefix_mp = 'https://www.mercadopago.'; + return array ( + 'text_prefix' => __( 'By continuing, you agree to our ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'link_terms_and_conditions' => $link_prefix_mp . $links_mp['sufix_url'] . $links_mp['help'] . $links_mp['term_conditition'], + 'text_suffix' => __( 'Terms and Conditions', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + } - /** - * Get Mercado Pago Devsite Page Link - * - * @param String $country Country Acronym - * - * @return String - */ - public static function get_mc_blog_link( $country ) { - $country_links = [ - 'mla' => array( - 'blog_link' => 'https://vendedores.mercadolibre.com.ar/nota/impulsa-tus-ventas-y-alcanza-mas-publico-con-mercado-credito', - 'FAQ_link' => 'https://www.mercadopago.com.ar/help/19040' - ), - 'mlm' => array( - 'blog_link' => 'https://vendedores.mercadolibre.com.mx/nota/impulsa-tus-ventas-y-alcanza-a-mas-clientes-con-mercado-credito', - 'FAQ_link' => 'https://www.mercadopago.com.mx/help/19040' - ), - 'mlb' => array( - 'blog_link' => 'https://conteudo.mercadopago.com.br/parcelamento-via-boleto-bancario-no-mercado-pago-seus-clientes-ja-podem-solicitar', - 'FAQ_link' => 'https://www.mercadopago.com.br/help/19040' - ), - ]; + /** + * Get Mercado Pago Devsite Page Link + * + * @param String $country Country Acronym + * + * @return String + */ + public static function get_mc_blog_link( $country ) { + $country_links = array( + 'mla' => array( + 'blog_link' => 'https://vendedores.mercadolibre.com.ar/nota/impulsa-tus-ventas-y-alcanza-mas-publico-con-mercado-credito', + 'FAQ_link' => 'https://www.mercadopago.com.ar/help/19040' + ), + 'mlm' => array( + 'blog_link' => 'https://vendedores.mercadolibre.com.mx/nota/impulsa-tus-ventas-y-alcanza-a-mas-clientes-con-mercado-credito', + 'FAQ_link' => 'https://www.mercadopago.com.mx/help/19040' + ), + 'mlb' => array( + 'blog_link' => 'https://conteudo.mercadopago.com.br/parcelamento-via-boleto-bancario-no-mercado-pago-seus-clientes-ja-podem-solicitar', + 'FAQ_link' => 'https://www.mercadopago.com.br/help/19040' + ), + ); - $link = array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; + $link = array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; - return $link; - } + return $link; + } } diff --git a/includes/helpers/class-wc-woomercadopago-helper-nonce.php b/includes/helpers/class-wc-woomercadopago-helper-nonce.php index 71254ca56..a44b4b067 100644 --- a/includes/helpers/class-wc-woomercadopago-helper-nonce.php +++ b/includes/helpers/class-wc-woomercadopago-helper-nonce.php @@ -1,111 +1,104 @@ log = new WC_WooMercadoPago_Log($this); - $this->options = WC_WooMercadoPago_Options::get_instance(); - $this->debug_mode = false === $this->options->get_debug_mode() ? 'no' : $this->options->get_instance()->get_debug_mode(); - } + /** + * Nonce constructor + */ + private function __construct() { + $this->log = new WC_WooMercadoPago_Log($this); + $this->options = WC_WooMercadoPago_Options::get_instance(); + $this->debug_mode = false === $this->options->get_debug_mode() ? 'no' : $this->options->get_instance()->get_debug_mode(); + } - /** - * Get WC_WooMercadoPago_Helper_Nonce instance - * - * @return WC_WooMercadoPago_Helper_Nonce - */ - public static function get_instance() { - if ( null === self::$instance ) { - self::$instance = new self(); - } - return self::$instance; - } + /** + * Get WC_WooMercadoPago_Helper_Nonce instance + * + * @return WC_WooMercadoPago_Helper_Nonce + */ + public static function get_instance() { + if ( null === self::$instance ) { + self::$instance = new self(); + } + return self::$instance; + } - /** - * Generate wp_nonce - * - * @return string - */ - public function generate_nonce( $id ) { - $nonce = wp_create_nonce( $id ); + /** + * Generate wp_nonce + * + * @return string + */ + public function generate_nonce( $id ) { + $nonce = wp_create_nonce( $id ); - if ( ! $nonce ) { - $this->log->write_log( __FUNCTION__, 'Security nonce ' . $id . ' creation failed.' ); - return ''; - } + if ( ! $nonce ) { + $this->log->write_log( __FUNCTION__, 'Security nonce ' . $id . ' creation failed.' ); + return ''; + } - return $nonce; - } + return $nonce; + } - /** - * Retrieves or display nonce hidden field for forms - * - * @param int|string $id - * @param string $fieldName - * - * @return string - */ - public function generate_nonce_field( $id, $fieldName ) { - return wp_nonce_field( $id, $fieldName ); - } + /** + * Retrieves or display nonce hidden field for forms + * + * @param int|string $id + * @param string $fieldName + * + * @return string + */ + public function generate_nonce_field( $id, $fieldName ) { + return wp_nonce_field( $id, $fieldName ); + } - /** - * Validate wp_nonce - * - * @param string $id - * @param string $nonce - * - * @return void - */ - public function validate_nonce( $id, $nonce ) { - if ( ! wp_verify_nonce( $nonce, $id ) ) { - $this->log->write_log(__FUNCTION__, 'Security nonce ' . $id . ' check failed. Nonce: ' . $nonce); - wp_send_json_error( 'Forbidden', 403 ); - } - } + /** + * Validate wp_nonce + * + * @param string $id + * @param string $nonce + * + * @return void + */ + public function validate_nonce( $id, $nonce ): void { + if ( ! wp_verify_nonce( $nonce, $id ) ) { + $this->log->write_log(__FUNCTION__, 'Security nonce ' . $id . ' check failed. Nonce: ' . $nonce); + wp_send_json_error( 'Forbidden', 403 ); + } + } } diff --git a/includes/helpers/class-wc-woomercadopago-helpers-currencyconverter.php b/includes/helpers/class-wc-woomercadopago-helpers-currencyconverter.php index bd077a102..be7c3ccb8 100644 --- a/includes/helpers/class-wc-woomercadopago-helpers-currencyconverter.php +++ b/includes/helpers/class-wc-woomercadopago-helpers-currencyconverter.php @@ -1,543 +1,534 @@ 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; - } - - /** - * - * Load class - * - * @return static - */ - public static function get_instance() { - if ( is_null( self::$instance ) ) { - self::$instance = new static(); - } - - return self::$instance; - } - - /** - * - * Init function - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return $this - * @throws Exception Return e. - */ - private function init( WC_WooMercadoPago_Payment_Abstract $method ) { - if ( ! isset( $this->ratios[ $method->id ] ) ) { - - try { - if ( ! $this->is_enabled( $method ) ) { - $this->set_ratio( $method->id ); - - return $this; - } - - $account_currency = $this->get_account_currency( $method ); - $local_currency = get_woocommerce_currency(); - - if ( ! $account_currency || $account_currency === $local_currency ) { - $this->set_ratio( $method->id ); - - return $this; - } - - $this->set_ratio( $method->id, $this->load_ratio( $local_currency, $account_currency, $method ) ); - } catch ( Exception $e ) { - $this->set_ratio( $method->id ); - throw $e; - } - } - - return $this; - } - - /** - * - * Get Account Currency - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return mixed|null - */ - private function get_account_currency( WC_WooMercadoPago_Payment_Abstract $method ) { - $key = $method->id; - - if ( isset( $this->currency_ache[ $key ] ) ) { - return $this->currency_ache[ $key ]; - } - - $site_id = $this->get_site_id( $this->get_access_token( $method ) ); - - if ( ! $site_id ) { - return null; - } - - $configs = $this->get_country_configs(); - - if ( ! isset( $configs[ $site_id ] ) || ! isset( $configs[ $site_id ]['currency'] ) ) { - return null; - } - - return isset( $configs[ $site_id ] ) ? $configs[ $site_id ]['currency'] : null; - } - - /** - * - * Get Country Configs - * - * @return array - */ - private function get_country_configs() { - try { - $config_instance = new WC_WooMercadoPago_Configs(); - - return $config_instance->get_country_configs(); - } catch ( Exception $e ) { - return array(); - } - } - - /** - * - * Get Access Token - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return mixed - */ - private function get_access_token( WC_WooMercadoPago_Payment_Abstract $method ) { - $type = $method->get_option( 'checkbox_checkout_test_mode' ) === 'yes' - ? '_mp_access_token_test' - : '_mp_access_token_prod'; - - return $method->get_option( $type ); - } - - /** - * - * Is Enabled - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return mixed - */ - public function is_enabled( WC_WooMercadoPago_Payment_Abstract $method ) { - return 'yes' === $method->get_option_mp( self::CONFIG_KEY, 'no' ); - } - - /** - * - * Set Ratio - * - * @param mixed $method_id method id. - * @param int $value value. - */ - private function set_ratio( $method_id, $value = self::DEFAULT_RATIO ) { - $this->ratios[ $method_id ] = $value; - } - - /** - * - * Get Ratio - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return int|mixed - */ - private function get_ratio( WC_WooMercadoPago_Payment_Abstract $method ) { - $this->init( $method ); - - return isset( $this->ratios[ $method->id ] ) - ? $this->ratios[ $method->id ] - : self::DEFAULT_RATIO; - } - - /** - * - * Load Ratio - * - * @param string $from_currency from Currency. - * @param string $to_currency to Currency. - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return int - * @throws Exception Return e. - */ - public function load_ratio( $from_currency, $to_currency, WC_WooMercadoPago_Payment_Abstract $method = null ) { - $cache_key = $from_currency . '--' . $to_currency; - - if ( isset( $this->cache[ $cache_key ] ) ) { - return $this->cache[ $cache_key ]; - } - - $ratio = self::DEFAULT_RATIO; - - if ( $from_currency === $to_currency ) { - $this->cache[ $cache_key ] = $ratio; - - return $ratio; - } - - try { - $result = Meli_Rest_Client::get( - array( - 'uri' => sprintf( '/currency_conversions/search?from=%s&to=%s', $from_currency, $to_currency ), - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token( $method ), - ), - ) - ); - - if ( 200 !== $result['status'] ) { - $this->log->write_log( __FUNCTION__, 'Mercado pago gave error to get currency value, payment creation failed with error: ' . wp_json_encode( $result ) ); - $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::load_ratio('$from_currency', '$to_currency')", - $e->__toString() - ); - - throw $e; - } - - $this->cache[ $cache_key ] = $ratio; - - return $ratio; - } - - /** - * - * Get SiteId - * - * @param string $access_token Access token. - * - * @return string | null - */ - private function get_site_id( $access_token ) { - try { - $site_id = strtolower(get_option( '_site_id_v1', false )); - - if ( $site_id ) { - return $site_id; - } - - $mp = new MP( $access_token ); - $result = $mp->get( '/users/me', array( 'Authorization' => 'Bearer ' . $access_token ) ); - $site_id = isset( $result['response'], $result['response']['site_id'] ) ? $result['response']['site_id'] : null; - - update_option( '_site_id_v1', $site_id ); - - return $site_id; - } catch ( Exception $e ) { - return null; - } - } - - /** - * - * Ratio - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return float - */ - public function ratio( WC_WooMercadoPago_Payment_Abstract $method ) { - $this->init( $method ); - - return $this->get_ratio( $method ); - } - - /** - * - * Get Description - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return string|void - */ - public function get_description( WC_WooMercadoPago_Payment_Abstract $method ) { - return $this->msg_description; - } - - /** - * Check if currency is supported in mercado pago API - * - * @param string $currency currency. - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return bool - */ - private function is_currency_supported( $currency, WC_WooMercadoPago_Payment_Abstract $method ) { - foreach ( $this->get_supported_currencies( $method ) as $country ) { - if ( $country['id'] === $currency ) { - return true; - } - } - - return false; - } - - /** - * Get supported currencies from mercado pago API - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - * - * @return array|bool - */ - public function get_supported_currencies( WC_WooMercadoPago_Payment_Abstract $method ) { - if ( is_null( $this->supported_currencies ) ) { - try { - - $request = array( - 'uri' => '/currencies', - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token( $method ), - ), - ); - - $result = Meli_Rest_Client::get( $request ); - - if ( ! isset( $result['response'] ) ) { - return false; - } - - $this->supported_currencies = $result['response']; - } catch ( Exception $e ) { - $this->supported_currencies = array(); - } - } - - return $this->supported_currencies; - } - - /** - * - * Schedule Notice - * - * @param WC_WooMercadoPago_Payment_Abstract $method methos. - * @param array $old_data old data. - * @param array $new_data new data. - */ - public function schedule_notice( WC_WooMercadoPago_Payment_Abstract $method, $old_data, $new_data ) { - if ( ! isset( $old_data[ self::CONFIG_KEY ] ) || ! isset( $new_data[ self::CONFIG_KEY ] ) ) { - return; - } - - if ( $old_data[ self::CONFIG_KEY ] !== $new_data[ self::CONFIG_KEY ] ) { - $_SESSION[ self::CONFIG_KEY ]['notice'] = array( - 'type' => 'yes' === $new_data[ self::CONFIG_KEY ] ? 'enabled' : 'disabled', - 'method' => $method, - ); - } - } - - /** - * - * Notices - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - */ - public function notices( WC_WooMercadoPago_Payment_Abstract $method ) { - $show = isset( $_SESSION[ self::CONFIG_KEY ] ) ? $_SESSION[ self::CONFIG_KEY ] : array(); - $local_currency = get_woocommerce_currency(); - - $account_currency = $this->get_account_currency( $method ); - - if ( $local_currency === $account_currency || empty( $account_currency ) ) { - return; - } - - if ( isset( $show['notice'] ) ) { - unset( $_SESSION[ self::CONFIG_KEY ]['notice'] ); - if ( 'enabled' === $show['notice']['type'] ) { - $this->notice_enabled( $method ); - } elseif ( 'disabled' === $show['notice']['type'] ) { - $this->notice_disabled( $method ); - } - } - - if ( ! $this->is_enabled( $method ) && ! $this->is_showing_alert && $method->is_currency_convertable() ) { - $this->notice_warning( $method ); - } - } - - /** - * - * Notice Enabled - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - */ - public function notice_enabled( WC_WooMercadoPago_Payment_Abstract $method ) { - $local_currency = get_woocommerce_currency(); - $currency = $this->get_account_currency( $method ); - $type = 'notice-error'; - $message = sprintf( - /* translators: 1: local currency 2: currency */ - __( 'Now we convert your currency from %1$s to %2$s.', 'woocommerce-mercadopago' ), - $local_currency, - $currency - ); - - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * - * Notice Disabled - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - */ - public function notice_disabled( WC_WooMercadoPago_Payment_Abstract $method ) { - $local_currency = get_woocommerce_currency(); - $currency = $this->get_account_currency( $method ); - $type = 'notice-error'; - $message = sprintf( - /* translators: 1: local currency 2: currency */ - __( 'We no longer convert your currency from %1$s to %2$s.', 'woocommerce-mercadopago' ), - $local_currency, - $currency - ); - - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * - * Notice Warning - * - * @param WC_WooMercadoPago_Payment_Abstract $method method. - */ - public function notice_warning( WC_WooMercadoPago_Payment_Abstract $method ) { - global $current_section; - - if ( in_array( $current_section, array( $method->id, sanitize_title( get_class( $method ) ) ), true ) ) { - $this->is_showing_alert = 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' ); - - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - } - - /** - * - * Translate - * - * @param string $str str. - * @param mixed ...$values value. - * - * @return string|void - */ - private function __( $str, ...$values ) { - $translated = $str; - - if ( ! empty( $values ) ) { - $translated = vsprintf( $translated, $values ); - } - - return $translated; - } + public const CONFIG_KEY = 'currency_conversion'; + + public const DEFAULT_RATIO = 1; + + /** + * + * Instance variable + * + * @var WC_WooMercadoPago_Helpers_CurrencyConverter + */ + private static $instance; + + /** + * + * Message description + * + * @var string $msg_description + */ + private $msg_description; + + /** + * + * Ratios array + * + * @var array + */ + private $ratios = array(); + + /** + * + * Cache array + * + * @var array + */ + private $cache = array(); + + /** + * + * Currency cache + * + * @var array + */ + private $currency_ache = array(); + + /** + * + * Supported Currencies + * + * @var undefined + */ + private $supported_currencies; + + /** + * + * Is Showing Alert + * + * @var bool + */ + private $is_showing_alert = false; + + /** + * + * Log + * + * @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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->log = new WC_WooMercadoPago_Log(); + + return $this; + } + + /** + * + * Load class + * + * @return static + */ + public static function get_instance() { + if ( is_null( self::$instance ) ) { + self::$instance = new static(); + } + + return self::$instance; + } + + /** + * + * Init function + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return $this + * @throws Exception Return e. + */ + private function init( WC_WooMercadoPago_Payment_Abstract $method ) { + if ( ! isset( $this->ratios[ $method->id ] ) ) { + try { + if ( ! $this->is_enabled( $method ) ) { + $this->set_ratio( $method->id ); + + return $this; + } + + $account_currency = $this->get_account_currency( $method ); + $local_currency = get_woocommerce_currency(); + + if ( ! $account_currency || $account_currency === $local_currency ) { + $this->set_ratio( $method->id ); + + return $this; + } + + $this->set_ratio( $method->id, $this->load_ratio( $local_currency, $account_currency, $method ) ); + } catch ( Exception $e ) { + $this->set_ratio( $method->id ); + throw $e; + } + } + + return $this; + } + + /** + * + * Get Account Currency + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return mixed|null + */ + private function get_account_currency( WC_WooMercadoPago_Payment_Abstract $method ) { + $key = $method->id; + + if ( isset( $this->currency_ache[ $key ] ) ) { + return $this->currency_ache[ $key ]; + } + + $site_id = $this->get_site_id( $this->get_access_token( $method ) ); + + if ( ! $site_id ) { + return null; + } + + $configs = $this->get_country_configs(); + + if ( ! isset( $configs[ $site_id ] ) || ! isset( $configs[ $site_id ]['currency'] ) ) { + return null; + } + + return isset( $configs[ $site_id ] ) ? $configs[ $site_id ]['currency'] : null; + } + + /** + * + * Get Country Configs + * + * @return array + */ + private function get_country_configs() { + try { + $config_instance = new WC_WooMercadoPago_Configs(); + + return $config_instance->get_country_configs(); + } catch ( Exception $e ) { + return array(); + } + } + + /** + * + * Get Access Token + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return mixed + */ + private function get_access_token( WC_WooMercadoPago_Payment_Abstract $method ) { + $type = $method->get_option( 'checkbox_checkout_test_mode' ) === 'yes' + ? '_mp_access_token_test' + : '_mp_access_token_prod'; + + return $method->get_option( $type ); + } + + /** + * + * Is Enabled + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return mixed + */ + public function is_enabled( WC_WooMercadoPago_Payment_Abstract $method ) { + return 'yes' === $method->get_option_mp( self::CONFIG_KEY, 'no' ); + } + + /** + * + * Set Ratio + * + * @param mixed $method_id method id. + * @param int $value value. + */ + private function set_ratio( $method_id, $value = self::DEFAULT_RATIO ): void { + $this->ratios[ $method_id ] = $value; + } + + /** + * + * Get Ratio + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return int|mixed + */ + private function get_ratio( WC_WooMercadoPago_Payment_Abstract $method ) { + $this->init( $method ); + + return isset( $this->ratios[ $method->id ] ) + ? $this->ratios[ $method->id ] + : self::DEFAULT_RATIO; + } + + /** + * + * Load Ratio + * + * @param string $from_currency from Currency. + * @param string $to_currency to Currency. + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return int + * @throws Exception Return e. + */ + public function load_ratio( $from_currency, $to_currency, WC_WooMercadoPago_Payment_Abstract $method = null ) { + $cache_key = $from_currency . '--' . $to_currency; + + if ( isset( $this->cache[ $cache_key ] ) ) { + return $this->cache[ $cache_key ]; + } + + $ratio = self::DEFAULT_RATIO; + + if ( $from_currency === $to_currency ) { + $this->cache[ $cache_key ] = $ratio; + + return $ratio; + } + + try { + $result = Meli_Rest_Client::get( + array( + 'uri' => sprintf( '/currency_conversions/search?from=%s&to=%s', $from_currency, $to_currency ), + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token( $method ), + ), + ) + ); + + if ( 200 !== $result['status'] ) { + $this->log->write_log( __FUNCTION__, 'Mercado pago gave error to get currency value, payment creation failed with error: ' . wp_json_encode( $result ) ); + $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::load_ratio('$from_currency', '$to_currency')", + $e->__toString() + ); + + throw $e; + } + + $this->cache[ $cache_key ] = $ratio; + + return $ratio; + } + + /** + * + * Get SiteId + * + * @param string $access_token Access token. + * + * @return string|null + */ + private function get_site_id( $access_token ) { + try { + $site_id = strtolower(get_option( '_site_id_v1', false )); + + if ( $site_id ) { + return $site_id; + } + + $mp = new MP( $access_token ); + $result = $mp->get( '/users/me', array('Authorization' => 'Bearer ' . $access_token) ); + $site_id = isset( $result['response'], $result['response']['site_id'] ) ? $result['response']['site_id'] : null; + + update_option( '_site_id_v1', $site_id ); + + return $site_id; + } catch ( Exception $e ) { + return null; + } + } + + /** + * + * Ratio + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return float + */ + public function ratio( WC_WooMercadoPago_Payment_Abstract $method ) { + $this->init( $method ); + + return $this->get_ratio( $method ); + } + + /** + * + * Get Description + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return string|void + */ + public function get_description( WC_WooMercadoPago_Payment_Abstract $method ) { + return $this->msg_description; + } + + /** + * Check if currency is supported in mercado pago API + * + * @param string $currency currency. + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return bool + */ + private function is_currency_supported( $currency, WC_WooMercadoPago_Payment_Abstract $method ) { + foreach ( $this->get_supported_currencies( $method ) as $country ) { + if ( $country['id'] === $currency ) { + return true; + } + } + + return false; + } + + /** + * Get supported currencies from mercado pago API + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + * + * @return array|bool + */ + public function get_supported_currencies( WC_WooMercadoPago_Payment_Abstract $method ) { + if ( is_null( $this->supported_currencies ) ) { + try { + $request = array( + 'uri' => '/currencies', + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token( $method ), + ), + ); + + $result = Meli_Rest_Client::get( $request ); + + if ( ! isset( $result['response'] ) ) { + return false; + } + + $this->supported_currencies = $result['response']; + } catch ( Exception $e ) { + $this->supported_currencies = array(); + } + } + + return $this->supported_currencies; + } + + /** + * + * Schedule Notice + * + * @param WC_WooMercadoPago_Payment_Abstract $method methos. + * @param array $old_data old data. + * @param array $new_data new data. + */ + public function schedule_notice( WC_WooMercadoPago_Payment_Abstract $method, $old_data, $new_data ): void { + if ( ! isset( $old_data[ self::CONFIG_KEY ] ) || ! isset( $new_data[ self::CONFIG_KEY ] ) ) { + return; + } + + if ( $old_data[ self::CONFIG_KEY ] !== $new_data[ self::CONFIG_KEY ] ) { + $_SESSION[ self::CONFIG_KEY ]['notice'] = array( + 'type' => 'yes' === $new_data[ self::CONFIG_KEY ] ? 'enabled' : 'disabled', + 'method' => $method, + ); + } + } + + /** + * + * Notices + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + */ + public function notices( WC_WooMercadoPago_Payment_Abstract $method ): void { + $show = isset( $_SESSION[ self::CONFIG_KEY ] ) ? $_SESSION[ self::CONFIG_KEY ] : array(); + $local_currency = get_woocommerce_currency(); + + $account_currency = $this->get_account_currency( $method ); + + if ( $local_currency === $account_currency || empty( $account_currency ) ) { + return; + } + + if ( isset( $show['notice'] ) ) { + unset( $_SESSION[ self::CONFIG_KEY ]['notice'] ); + if ( 'enabled' === $show['notice']['type'] ) { + $this->notice_enabled( $method ); + } elseif ( 'disabled' === $show['notice']['type'] ) { + $this->notice_disabled( $method ); + } + } + + if ( ! $this->is_enabled( $method ) && ! $this->is_showing_alert && $method->is_currency_convertable() ) { + $this->notice_warning( $method ); + } + } + + /** + * + * Notice Enabled + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + */ + public function notice_enabled( WC_WooMercadoPago_Payment_Abstract $method ): void { + $local_currency = get_woocommerce_currency(); + $currency = $this->get_account_currency( $method ); + $type = 'notice-error'; + $message = sprintf( + /* translators: 1: local currency 2: currency */ + __( 'Now we convert your currency from %1$s to %2$s.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + $local_currency, + $currency + ); + + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * + * Notice Disabled + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + */ + public function notice_disabled( WC_WooMercadoPago_Payment_Abstract $method ): void { + $local_currency = get_woocommerce_currency(); + $currency = $this->get_account_currency( $method ); + $type = 'notice-error'; + $message = sprintf( + /* translators: 1: local currency 2: currency */ + __( 'We no longer convert your currency from %1$s to %2$s.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + $local_currency, + $currency + ); + + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * + * Notice Warning + * + * @param WC_WooMercadoPago_Payment_Abstract $method method. + */ + public function notice_warning( WC_WooMercadoPago_Payment_Abstract $method ): void { + global $current_section; + + if ( in_array( $current_section, array($method->id, sanitize_title( get_class( $method ) )), true ) ) { + $this->is_showing_alert = 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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + } + + /** + * + * Translate + * + * @param string $str str. + * @param mixed ...$values value. + * + * @return string|void + */ + private function __( $str, ...$values ) { + $translated = $str; + + if ( ! empty( $values ) ) { + $translated = vsprintf( $translated, $values ); + } + + return $translated; + } } diff --git a/includes/helpers/index.php b/includes/helpers/index.php index 258f3fae9..891711d6d 100644 --- a/includes/helpers/index.php +++ b/includes/helpers/index.php @@ -1,12 +1,5 @@ update_token_new_version(); - $this->show_notices(); - } - - /** - * Show Notices in ADMIN - */ - private function show_notices() { - add_action( 'admin_notices', array( $this, 'plugin_review' ) ); - add_action( 'admin_notices', array( $this, 'saved_cards_notice' ) ); - - 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, 'notice_update_access_token' ) ); - } - } - - if ( ( empty( $_SERVER['HTTPS'] ) || 'off' === $_SERVER['HTTPS'] ) ) { - add_action( 'admin_notices', array( $this, 'notice_https' ) ); - } - } - - /** - * Update token new version - * - * @throws WC_WooMercadoPago_Exception Update token new version exception. - */ - private function update_token_new_version() { - 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->update_token(); - } - } - if ( empty( strtolower( get_option( '_site_id_v1' ) ) ) || empty( get_option( '_collector_id_v1' ) ) ) { - WC_WooMercadoPago_Credentials::validate_credentials_v1(); - } - - $ticket_methods = get_option( '_all_payment_methods_ticket', '' ); - if ( empty( $ticket_methods ) || ! is_array( $ticket_methods ) ) { - $this->update_ticket_methods(); - } - - $all_payments = get_option( '_checkout_payments_methods', '' ); - if ( empty( $all_payments ) ) { - $this->update_payments(); - } - - if ( ! empty( $all_payments ) ) { - foreach ( $all_payments as $payment ) { - if ( ! isset( $payment['name'] ) ) { - $this->update_payments(); - break; - } - } - } - } - - /** - * Update payments - * - * @throws WC_WooMercadoPago_Exception Update payment exception. - */ - private function update_payments() { - $mp_instance = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - if ( $mp_instance ) { - WC_WooMercadoPago_Credentials::update_payment_methods( $mp_instance, $mp_instance->get_access_token() ); - } - } - - /** - * Update ticket methods - * - * @throws WC_WooMercadoPago_Exception Update ticket exception. - */ - private function update_ticket_methods() { - $mp_instance = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - if ( $mp_instance ) { - WC_WooMercadoPago_Credentials::update_ticket_method( $mp_instance, $mp_instance->get_access_token() ); - } - } - - /** - * Update pix methods - * - * @throws WC_WooMercadoPago_Exception Update ticket exception. - */ - private function update_pix_methods() { - $mp_instance = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - if ( $mp_instance ) { - WC_WooMercadoPago_Credentials::update_pix_method( $mp_instance, $mp_instance->get_access_token() ); - } - } - - /** - * Notice Access Token - */ - public function notice_update_access_token() { - $type = 'error'; - $message = __( 'Update your credentials with the Access Token and Public Key, you need them to continue receiving payments!', 'woocommerce-mercadopago'); - echo wp_kses_post( WC_WooMercadoPago_Notices::get_alert_frame($message, $type )); - } - - /** - * Notice HTTPS - */ - public function notice_https() { - $type = 'notice-warning'; - $message = __( 'The store should have HTTPS in order to activate both Checkout Personalizado and Ticket Checkout.', 'woocommerce-mercadopago'); - echo wp_kses_post(WC_WooMercadoPago_Notices::get_alert_frame($message, $type )); - } - - private function must_not_show_notice() { - $pages_to_show = array( 'dashboard', 'plugins', 'woocommerce_page_wc-settings' ); - $dismissed_review = (int) get_option( '_mp_dismiss_review', 0 ); - - return ! in_array( get_current_screen()->id, $pages_to_show, true ) || 0 !== $dismissed_review; - } - - private function must_not_show_saved_cards_notice() { - $pages_to_show = array( 'dashboard', 'plugins', 'woocommerce_page_wc-settings' ); - $dismissed_review = (int) get_option( '_mp_dismiss_saved_cards_notice', 0 ); - - return ! in_array( get_current_screen()->id, $pages_to_show, true ) || 0 !== $dismissed_review; - } - - /** - * Plugin review - * - * @return false - */ - public function plugin_review() { - if ( $this->must_not_show_notice() ) { - return false; - } - echo wp_kses_post( WC_WooMercadoPago_Review_Notice::get_plugin_review_banner()); - } - - /** - * Saved Cards Notice - * - * @return false - */ - public function saved_cards_notice() { - if ( $this->must_not_show_saved_cards_notice() ) { - return false; - } - echo wp_kses_post( WC_WooMercadoPago_Saved_Cards::get_plugin_review_banner()); - } - - /** - * UpdateToken - */ - private function update_token() { - $mp_instance = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - - if ( $mp_instance ) { - if ( - true === WC_WooMercadoPago_Credentials::validate_credentials_test( $mp_instance, null, get_option( '_mp_public_key' ) ) - && true === WC_WooMercadoPago_Credentials::validate_credentials_test( $mp_instance, get_option( '_mp_access_token' ) ) - ) { - 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( 'checkbox_checkout_test_mode', 'yes', true ); - } - - if ( - true === WC_WooMercadoPago_Credentials::validate_credentials_prod( $mp_instance, null, get_option( '_mp_public_key' ) ) - && true === WC_WooMercadoPago_Credentials::validate_credentials_prod( $mp_instance, get_option( '_mp_access_token' ) ) - ) { - 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( 'checkbox_checkout_test_mode', 'no', true ); - } - } - } - - /** - * Country Configs - */ - public static function get_country_configs() { - 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', - 'currency_symbol' => '$', - 'intl' => 'es-CO', - ), - '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', - 'currency_symbol' => '$', - 'intl' => 'es-AR', - ), - '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', - 'currency_symbol' => 'R$', - 'intl' => 'pt-BR', - ), - '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', - 'currency_symbol' => '$', - 'intl' => 'es-CL', - ), - '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', - 'currency_symbol' => '$', - 'intl' => 'es-MX', - ), - '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', - 'currency_symbol' => '$', - 'intl' => 'es-UY', - ), - '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', - 'currency_symbol' => '$', - 'intl' => 'es-VE', - ), - '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', - 'currency_symbol' => '$', - 'intl' => 'es-PE', - ), - ); - } - - /** - * Get categories - * - * @return array - */ - public function get_categories() { - 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', - ), - ); - } - - /** - * Set payment - * - * @param array|null $methods Methods. - * - * @return array - */ - public function set_payment_gateway( $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( - strtolower( $api_request ), - array( - 'wc_woomercadopago_basic_gateway', - 'wc_woomercadopago_custom_gateway', - 'wc_woomercadopago_ticket_gateway', - 'wc_woomercadopago_pix_gateway', - 'wc_woomercadopago_credits_gateway', - 'wc_woomercadopago_basicgateway', - 'wc_woomercadopago_customgateway', - 'wc_woomercadopago_ticketgateway', - ), - true - ) ) { - if ( ! preg_match( '/(_gateway)/i', $api_request ) ) { - $api_request = preg_replace( '/gateway/i', '_Gateway', $api_request ); - } - $methods[] = $api_request; - } - - return $methods; - } - - return $this->get_available_payment_methods( $methods ); - } - - /** - * Get available payment methods - * - * @param array|null $methods - * - * @return array - */ - public function get_available_payment_methods( $methods = [] ) { - $wc_country = WC_WooMercadoPago_Module::get_woocommerce_default_country(); - $site_id = strtolower( get_option( '_site_id_v1', '' ) ); - - $methods[] = 'WC_WooMercadoPago_Basic_Gateway'; - - $credits_helper = $this->get_credits_helper_instance(); - if ( $credits_helper->is_credits() ) { - $methods[] = 'WC_WooMercadoPago_Credits_Gateway'; - } - - $methods[] = 'WC_WooMercadoPago_Custom_Gateway'; - $methods[] = 'WC_WooMercadoPago_Ticket_Gateway'; - - if ( ( 'BR' === $wc_country && '' === $site_id ) || ( 'mlb' === $site_id ) ) { - $methods[] = 'WC_WooMercadoPago_Pix_Gateway'; - } - - return $methods; - } - - public function get_credits_helper_instance() { - return new WC_WooMercadoPago_Helper_Credits(); - } - + /** + * WC_WooMercadoPago_Configs constructor. + * + * @throws WC_WooMercadoPago_Exception Load configs exception. + */ + public function __construct() { + $this->update_token_new_version(); + $this->show_notices(); + } + + /** + * Show Notices in ADMIN + */ + private function show_notices(): void { + add_action( 'admin_notices', array($this, 'plugin_review') ); + add_action( 'admin_notices', array($this, 'saved_cards_notice') ); + + 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, 'notice_update_access_token') ); + } + } + + if ( ( empty( $_SERVER['HTTPS'] ) || 'off' === $_SERVER['HTTPS'] ) ) { + add_action( 'admin_notices', array($this, 'notice_https') ); + } + } + + /** + * Update token new version + * + * @throws WC_WooMercadoPago_Exception Update token new version exception. + */ + private function update_token_new_version(): void { + 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->update_token(); + } + } + if ( empty( strtolower( get_option( '_site_id_v1' ) ) ) || empty( get_option( '_collector_id_v1' ) ) ) { + WC_WooMercadoPago_Credentials::validate_credentials_v1(); + } + + $ticket_methods = get_option( '_all_payment_methods_ticket', '' ); + if ( empty( $ticket_methods ) || ! is_array( $ticket_methods ) ) { + $this->update_ticket_methods(); + } + + $all_payments = get_option( '_checkout_payments_methods', '' ); + if ( empty( $all_payments ) ) { + $this->update_payments(); + } + + if ( ! empty( $all_payments ) ) { + foreach ( $all_payments as $payment ) { + if ( ! isset( $payment['name'] ) ) { + $this->update_payments(); + break; + } + } + } + } + + /** + * Update payments + * + * @throws WC_WooMercadoPago_Exception Update payment exception. + */ + private function update_payments(): void { + $mp_instance = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + if ( $mp_instance ) { + WC_WooMercadoPago_Credentials::update_payment_methods( $mp_instance, $mp_instance->get_access_token() ); + } + } + + /** + * Update ticket methods + * + * @throws WC_WooMercadoPago_Exception Update ticket exception. + */ + private function update_ticket_methods(): void { + $mp_instance = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + if ( $mp_instance ) { + WC_WooMercadoPago_Credentials::update_ticket_method( $mp_instance, $mp_instance->get_access_token() ); + } + } + + /** + * Update pix methods + * + * @throws WC_WooMercadoPago_Exception Update ticket exception. + */ + private function update_pix_methods(): void { + $mp_instance = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + if ( $mp_instance ) { + WC_WooMercadoPago_Credentials::update_pix_method( $mp_instance, $mp_instance->get_access_token() ); + } + } + + /** + * Notice Access Token + */ + public function notice_update_access_token(): void { + $type = 'error'; + $message = __( 'Update your credentials with the Access Token and Public Key, you need them to continue receiving payments!', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + echo wp_kses_post( WC_WooMercadoPago_Notices::get_alert_frame($message, $type )); + } + + /** + * Notice HTTPS + */ + public function notice_https(): void { + $type = 'notice-warning'; + $message = __( 'The store should have HTTPS in order to activate both Checkout Personalizado and Ticket Checkout.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + echo wp_kses_post(WC_WooMercadoPago_Notices::get_alert_frame($message, $type )); + } + + private function must_not_show_notice() { + $pages_to_show = array('dashboard', 'plugins', 'woocommerce_page_wc-settings'); + $dismissed_review = (int) get_option( '_mp_dismiss_review', 0 ); + + return ! in_array( get_current_screen()->id, $pages_to_show, true ) || 0 !== $dismissed_review; + } + + private function must_not_show_saved_cards_notice() { + $pages_to_show = array('dashboard', 'plugins', 'woocommerce_page_wc-settings'); + $dismissed_review = (int) get_option( '_mp_dismiss_saved_cards_notice', 0 ); + + return ! in_array( get_current_screen()->id, $pages_to_show, true ) || 0 !== $dismissed_review; + } + + /** + * Plugin review + * + * @return false + */ + public function plugin_review() { + if ( $this->must_not_show_notice() ) { + return false; + } + echo wp_kses_post( WC_WooMercadoPago_Review_Notice::get_plugin_review_banner()); + } + + /** + * Saved Cards Notice + * + * @return false + */ + public function saved_cards_notice() { + if ( $this->must_not_show_saved_cards_notice() ) { + return false; + } + echo wp_kses_post( WC_WooMercadoPago_Saved_Cards::get_plugin_review_banner()); + } + + /** + * UpdateToken + */ + private function update_token(): void { + $mp_instance = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + + if ( $mp_instance ) { + if ( + true === WC_WooMercadoPago_Credentials::validate_credentials_test( $mp_instance, null, get_option( '_mp_public_key' ) ) + && true === WC_WooMercadoPago_Credentials::validate_credentials_test( $mp_instance, get_option( '_mp_access_token' ) ) + ) { + 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( 'checkbox_checkout_test_mode', 'yes', true ); + } + + if ( + true === WC_WooMercadoPago_Credentials::validate_credentials_prod( $mp_instance, null, get_option( '_mp_public_key' ) ) + && true === WC_WooMercadoPago_Credentials::validate_credentials_prod( $mp_instance, get_option( '_mp_access_token' ) ) + ) { + 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( 'checkbox_checkout_test_mode', 'no', true ); + } + } + } + + /** + * Country Configs + */ + public static function get_country_configs() { + 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', + 'currency_symbol' => '$', + 'intl' => 'es-CO', + ), + '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', + 'currency_symbol' => '$', + 'intl' => 'es-AR', + ), + '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', + 'currency_symbol' => 'R$', + 'intl' => 'pt-BR', + ), + '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', + 'currency_symbol' => '$', + 'intl' => 'es-CL', + ), + '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', + 'currency_symbol' => '$', + 'intl' => 'es-MX', + ), + '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', + 'currency_symbol' => '$', + 'intl' => 'es-UY', + ), + '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', + 'currency_symbol' => '$', + 'intl' => 'es-VE', + ), + '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', + 'currency_symbol' => '$', + 'intl' => 'es-PE', + ), + ); + } + + /** + * Get categories + * + * @return array + */ + public function get_categories() { + 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', + ), + ); + } + + /** + * Set payment + * + * @param array|null $methods Methods. + * + * @return array + */ + public function set_payment_gateway( $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( + strtolower( $api_request ), + array( + 'wc_woomercadopago_basic_gateway', + 'wc_woomercadopago_custom_gateway', + 'wc_woomercadopago_ticket_gateway', + 'wc_woomercadopago_pix_gateway', + 'wc_woomercadopago_credits_gateway', + 'wc_woomercadopago_basicgateway', + 'wc_woomercadopago_customgateway', + 'wc_woomercadopago_ticketgateway', + ), + true + ) ) { + if ( ! preg_match( '/(_gateway)/i', $api_request ) ) { + $api_request = preg_replace( '/gateway/i', '_Gateway', $api_request ); + } + $methods[] = $api_request; + } + + return $methods; + } + + return $this->get_available_payment_methods( $methods ); + } + + /** + * Get available payment methods + * + * @param array|null $methods + * + * @return array + */ + public function get_available_payment_methods( $methods = array() ) { + $wc_country = WC_WooMercadoPago_Module::get_woocommerce_default_country(); + $site_id = strtolower( get_option( '_site_id_v1', '' ) ); + + $methods[] = 'WC_WooMercadoPago_Basic_Gateway'; + + $credits_helper = $this->get_credits_helper_instance(); + if ( $credits_helper->is_credits() ) { + $methods[] = 'WC_WooMercadoPago_Credits_Gateway'; + } + + $methods[] = 'WC_WooMercadoPago_Custom_Gateway'; + $methods[] = 'WC_WooMercadoPago_Ticket_Gateway'; + + if ( ( 'BR' === $wc_country && '' === $site_id ) || ( 'mlb' === $site_id ) ) { + $methods[] = 'WC_WooMercadoPago_Pix_Gateway'; + } + + return $methods; + } + + public function get_credits_helper_instance() { + return new WC_WooMercadoPago_Helper_Credits(); + } } diff --git a/includes/module/class-wc-woomercadopago-credentials.php b/includes/module/class-wc-woomercadopago-credentials.php index 5b2602714..c5df3838f 100755 --- a/includes/module/class-wc-woomercadopago-credentials.php +++ b/includes/module/class-wc-woomercadopago-credentials.php @@ -1,495 +1,487 @@ payment = $payment; - $public_key = get_option( '_mp_public_key_prod', '' ); - $access_token = get_option( '_mp_access_token_prod', '' ); - - if ( ! is_null( $this->payment ) ) { - $this->sandbox = $payment->is_test_user(); - if ( 'yes' === get_option( 'checkbox_checkout_test_mode', '' ) || empty( get_option( 'checkbox_checkout_test_mode', '' ) ) ) { - $public_key = get_option( '_mp_public_key_test', '' ); - $access_token = get_option( '_mp_access_token_test', '' ); - } - } - - if ( is_null( $this->payment ) && empty( $public_key ) && empty( $access_token ) ) { - $public_key = get_option( '_mp_public_key_test', '' ); - $access_token = get_option( '_mp_access_token_test', '' ); - } - - $this->public_key = $public_key; - $this->access_token = $access_token; - $this->client_id = get_option( '_mp_client_id' ); - $this->client_secret = get_option( '_mp_client_secret' ); - } - - /** - * Mercadopago payment update function - * - * @return void - * @throws WC_WooMercadoPago_Exception Error. - */ - public static function mercadopago_payment_update() { - try { - $mp_v1 = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - if ( false === $mp_v1 instanceof MP ) { - self::set_no_credentials(); - return; - } - - $access_token = $mp_v1->get_access_token(); - if ( ! empty( $access_token ) ) { - $payments_response = self::get_payment_response( $mp_v1, $access_token ); - self::update_payment_methods( $mp_v1, $access_token, $payments_response ); - self::update_ticket_method( $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() ); - } - } - - /** - * Validate Credentials Type function - * - * @return string - */ - public function validate_credentials_type() { - $basic_is_enabled = self::basic_is_enabled(); - if ( ! $this->token_is_valid() && ( $this->payment instanceof WC_WooMercadoPago_Basic_Gateway || 'yes' === $basic_is_enabled ) ) { - if ( ! $this->client_is_valid() ) { - return self::TYPE_ACCESS_TOKEN; - } - return self::TYPE_ACCESS_CLIENT; - } - - return self::TYPE_ACCESS_TOKEN; - } - - /** - * - * Client Is Valid function - * - * @return bool - */ - public function client_is_valid() { - if ( empty( $this->client_id ) || empty( $this->client_secret ) ) { - return false; - } - return true; - } - - /** - * - * Token Is Valid function - * - * @return bool - */ - public function token_is_valid() { - if ( empty( $this->public_key ) || empty( $this->access_token ) ) { - return false; - } - - return true; - } - - /** - * Set No Credentials function - * - * @return void - */ - public static function set_no_credentials() { - 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( '_mp_payment_methods_pix', '', true ); - update_option( '_can_do_currency_conversion_v1', false, true ); - } - - /** - * - * Access Token Is Valid function - * - * @param string $access_token access token. - * @return bool - * @throws WC_WooMercadoPago_Exception Error. - */ - public static function access_token_is_valid( $access_token ) { - $mp_v1 = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - 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', strtolower($get_request['response']['site_id']), true ); - update_option( '_test_user_v1', in_array( 'test_user', $get_request['response']['tags'], true ), true ); - } - - if ( isset( $get_request['response']['id'] ) ) { - update_option( '_collector_id_v1', $get_request['response']['id'], true ); - } - - return true; - } - - /** - * - * Validate Credentials v1 function - * - * @return bool - */ - public static function validate_credentials_v1() { - $credentials = new self(); - $basic_is_enabled = 'no'; - if ( ! $credentials->token_is_valid() ) { - $basic_is_enabled = self::basic_is_enabled(); - if ( 'yes' !== $basic_is_enabled ) { - self::set_no_credentials(); - return false; - } - } - - try { - $mp_v1 = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - if ( false === $mp_v1 instanceof MP ) { - self::set_no_credentials(); - 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->public_key ) || 'yes' === $basic_is_enabled ) ) { - - update_option( '_test_user_v1', in_array( 'test_user', $get_request['response']['tags'], true ), true ); - update_option( '_site_id_v1', strtolower($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[ strtolower($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::set_no_credentials(); - return false; - } - - /** - * Get Homolog Validate - * - * @return mixed - * @throws WC_WooMercadoPago_Exception Homolog validate exception. - */ - public static function get_homolog_validate( $production_mode, $mp_access_token_prod ) { - $homolog_validate = (int) get_option( WC_WooMercadoPago_Options::HOMOLOG_VALIDATE, 0 ); - $mp = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - if ( ( $production_mode && ! empty( $mp_access_token_prod ) ) && 0 === $homolog_validate ) { - if ( $mp instanceof MP ) { - $homolog_validate = $mp->get_credentials_wrapper( $mp_access_token_prod ); - $homolog_validate = isset( $homolog_validate['homologated'] ) && true === $homolog_validate['homologated'] ? 1 : 0; - update_option( 'homolog_validate', $homolog_validate, true ); - return $homolog_validate; - } - return 0; - } - return 1; - } - - /** - * - * Get Payment Response function - * - * @param MP $mp_instance MP Instance. - * @param string $access_token Access token. - * @return null - */ - public static function get_payment_response( $mp_instance, $access_token ) { - $payments = $mp_instance->get_payment_methods( $access_token ); - if ( isset( $payments['response'] ) ) { - return $payments['response']; - } - - return null; - } - - /** - * - * Update Payment Methods function - * - * @param MP $mp_instance MP instance. - * @param string|null $access_token Access token. - * @param array|null $payments_response Payments response. - */ - public static function update_payment_methods( $mp_instance, $access_token = null, $payments_response = null ) { - if ( empty( $access_token ) || empty( $mp_instance ) ) { - return; - } - - if ( empty( $payments_response ) ) { - $payments_response = self::get_payment_response( $mp_instance, $access_token ); - } - - if ( empty( $payments_response ) || ( isset( $payments_response['status'] ) && 200 !== $payments_response['status'] && - 201 !== $payments_response['status'] ) ) { - return; - } - - $arr = array(); - $cho = array(); - $excluded = array( 'consumer_credits', 'paypal', 'account_money' ); - - foreach ( $payments_response as $payment ) { - if ( in_array( $payment['id'], $excluded, true ) ) { - 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 ); - } - - /** - * - * Update Pix Method function - * - * @param MP $mp_instance Mp instance. - * @param string $access_token Access token. - * @param array|null $payments_response Payment response. - * @return void - */ - public static function update_pix_method( $mp_instance, $access_token, $payments_response = null ) { - if ( empty( $access_token ) || empty( $mp_instance ) ) { - return; - } - - if ( empty( $payments_response ) ) { - $payments_response = self::get_payment_response( $mp_instance, $access_token ); - } - - if ( empty( $payments_response ) ) { - return; - } - - $payment_methods_pix = array(); - $accepted = array( 'pix' ); - - foreach ( $payments_response as $payment ) { - if ( in_array( $payment['id'], $accepted, true ) ) { - $payment_methods_pix[ $payment['id'] ] = array( - 'id' => $payment['id'], - 'name' => $payment['name'], - 'secure_thumbnail' => $payment['secure_thumbnail'], - ); - } - } - - update_option( '_mp_payment_methods_pix', $payment_methods_pix, true ); - } - - /** - * - * Update Ticket Method function - * - * @param MP $mp_instance Mp instance. - * @param string $access_token Access token. - * @param array|null $payments_response Payment response. - * @return void - */ - public static function update_ticket_method( $mp_instance, $access_token, $payments_response = null ) { - if ( empty( $access_token ) || empty( $mp_instance ) ) { - return; - } - - if ( empty( $payments_response ) ) { - $payments_response = self::get_payment_response( $mp_instance, $access_token ); - } - - if ( empty( $payments_response ) || ( isset( $payments_response['status'] ) && 200 !== $payments_response['status'] && - 201 !== $payments_response['status'] ) ) { - return; - } - - $payment_methods_ticket = array(); - $excluded = array( 'paypal', 'pse', 'pix' ); - - foreach ( $payments_response as $payment ) { - if ( - ! in_array( $payment['id'], $excluded, true ) && - 'account_money' !== $payment['payment_type_id'] && - 'credit_card' !== $payment['payment_type_id'] && - 'debit_card' !== $payment['payment_type_id'] && - 'prepaid_card' !== $payment['payment_type_id'] - ) { - $payment_methods_ticket[] = $payment; - } - } - - update_option( '_all_payment_methods_ticket', $payment_methods_ticket, true ); - } - - /** - * - * Basic is enabled function - * - * @return string - */ - public static function basic_is_enabled() { - $basic_is_enabled = 'no'; - $basic_settings = get_option( 'woocommerce_woo-mercado-pago-basic_settings', '' ); - - if ( isset( $basic_settings['enabled'] ) ) { - $basic_is_enabled = $basic_settings['enabled']; - } - - return $basic_is_enabled; - } - - /** - * - * Validate Credentials Test function - * - * @param MP $mp_instance Mp instance. - * @param string|null $access_token Access token. - * @param string|null $public_key Payment response. - * - * @return bool - * @throws WC_WooMercadoPago_Exception - */ - public static function validate_credentials_test( $mp_instance, $access_token = null, $public_key = null ) { - $is_test = $mp_instance->get_credentials_wrapper( $access_token, $public_key ); - if ( is_array( $is_test ) && isset( $is_test['is_test'] ) && true === $is_test['is_test'] ) { - return true; - } - return false; - } - - /** - * - * Validate Credentials Prod function - * - * @param MP $mp_instance Mp instance. - * @param string|null $access_token Access token. - * @param string|null $public_key Payment response. - * - * @return bool - * @throws WC_WooMercadoPago_Exception - */ - public static function validate_credentials_prod( $mp_instance, $access_token = null, $public_key = null ) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'mercadopago_requests' ); - $log->write_log( 'Func:', __FUNCTION__ ); - $is_test = $mp_instance->get_credentials_wrapper( $access_token, $public_key ); - if ( is_array( $is_test ) && isset( $is_test['is_test'] ) && false === $is_test['is_test'] ) { - if ( ! empty($is_test['client_id']) ) { - update_option('mp_application_id', $is_test['client_id']); - } - return true; - } - return false; - } + public const TYPE_ACCESS_CLIENT = 'client'; + + public const TYPE_ACCESS_TOKEN = 'token'; + + /** + * Payment variable + * + * @var [mixed|null] + */ + public $payment; + + /** + * Public key variable + * + * @var [string] + */ + public $public_key; + + /** + * Access token variable + * + * @var [string] + */ + public $access_token; + + /** + * Client id variable + * + * @var [string] + */ + public $client_id; + + /** + * Client Secret variable + * + * @var [string] + */ + public $client_secret; + + /** + * Sandbox variable + * + * @var [bool] + */ + public $sandbox; + + /** + * Log variable + * + * @var WC_WooMercadoPago_Log + */ + public $log; + + /** + * WC_WooMercadoPago_Credentials constructor. + * + * @param mixed|null $payment payment. + */ + public function __construct( $payment = null ) { + $this->payment = $payment; + $public_key = get_option( '_mp_public_key_prod', '' ); + $access_token = get_option( '_mp_access_token_prod', '' ); + + if ( ! is_null( $this->payment ) ) { + $this->sandbox = $payment->is_test_user(); + if ( 'yes' === get_option( 'checkbox_checkout_test_mode', '' ) || empty( get_option( 'checkbox_checkout_test_mode', '' ) ) ) { + $public_key = get_option( '_mp_public_key_test', '' ); + $access_token = get_option( '_mp_access_token_test', '' ); + } + } + + if ( is_null( $this->payment ) && empty( $public_key ) && empty( $access_token ) ) { + $public_key = get_option( '_mp_public_key_test', '' ); + $access_token = get_option( '_mp_access_token_test', '' ); + } + + $this->public_key = $public_key; + $this->access_token = $access_token; + $this->client_id = get_option( '_mp_client_id' ); + $this->client_secret = get_option( '_mp_client_secret' ); + } + + /** + * Mercadopago payment update function + * + * @return void + * @throws WC_WooMercadoPago_Exception Error. + */ + public static function mercadopago_payment_update(): void { + try { + $mp_v1 = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + if ( false === $mp_v1 instanceof MP ) { + self::set_no_credentials(); + return; + } + + $access_token = $mp_v1->get_access_token(); + if ( ! empty( $access_token ) ) { + $payments_response = self::get_payment_response( $mp_v1, $access_token ); + self::update_payment_methods( $mp_v1, $access_token, $payments_response ); + self::update_ticket_method( $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() ); + } + } + + /** + * Validate Credentials Type function + * + * @return string + */ + public function validate_credentials_type() { + $basic_is_enabled = self::basic_is_enabled(); + if ( ! $this->token_is_valid() && ( $this->payment instanceof WC_WooMercadoPago_Basic_Gateway || 'yes' === $basic_is_enabled ) ) { + if ( ! $this->client_is_valid() ) { + return self::TYPE_ACCESS_TOKEN; + } + return self::TYPE_ACCESS_CLIENT; + } + + return self::TYPE_ACCESS_TOKEN; + } + + /** + * + * Client Is Valid function + * + * @return bool + */ + public function client_is_valid() { + if ( empty( $this->client_id ) || empty( $this->client_secret ) ) { + return false; + } + return true; + } + + /** + * + * Token Is Valid function + * + * @return bool + */ + public function token_is_valid() { + if ( empty( $this->public_key ) || empty( $this->access_token ) ) { + return false; + } + + return true; + } + + /** + * Set No Credentials function + * + * @return void + */ + public static function set_no_credentials(): void { + 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( '_mp_payment_methods_pix', '', true ); + update_option( '_can_do_currency_conversion_v1', false, true ); + } + + /** + * + * Access Token Is Valid function + * + * @param string $access_token access token. + * @return bool + * @throws WC_WooMercadoPago_Exception Error. + */ + public static function access_token_is_valid( $access_token ) { + $mp_v1 = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + 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', strtolower($get_request['response']['site_id']), true ); + update_option( '_test_user_v1', in_array( 'test_user', $get_request['response']['tags'], true ), true ); + } + + if ( isset( $get_request['response']['id'] ) ) { + update_option( '_collector_id_v1', $get_request['response']['id'], true ); + } + + return true; + } + + /** + * + * Validate Credentials v1 function + * + * @return bool + */ + public static function validate_credentials_v1() { + $credentials = new self(); + $basic_is_enabled = 'no'; + if ( ! $credentials->token_is_valid() ) { + $basic_is_enabled = self::basic_is_enabled(); + if ( 'yes' !== $basic_is_enabled ) { + self::set_no_credentials(); + return false; + } + } + + try { + $mp_v1 = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + if ( false === $mp_v1 instanceof MP ) { + self::set_no_credentials(); + 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->public_key ) || 'yes' === $basic_is_enabled ) ) { + update_option( '_test_user_v1', in_array( 'test_user', $get_request['response']['tags'], true ), true ); + update_option( '_site_id_v1', strtolower($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[ strtolower($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::set_no_credentials(); + return false; + } + + /** + * Get Homolog Validate + * + * @return mixed + * @throws WC_WooMercadoPago_Exception Homolog validate exception. + */ + public static function get_homolog_validate( $production_mode, $mp_access_token_prod ) { + $homolog_validate = (int) get_option( WC_WooMercadoPago_Options::HOMOLOG_VALIDATE, 0 ); + $mp = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + if ( ( $production_mode && ! empty( $mp_access_token_prod ) ) && 0 === $homolog_validate ) { + if ( $mp instanceof MP ) { + $homolog_validate = $mp->get_credentials_wrapper( $mp_access_token_prod ); + $homolog_validate = isset( $homolog_validate['homologated'] ) && true === $homolog_validate['homologated'] ? 1 : 0; + update_option( 'homolog_validate', $homolog_validate, true ); + return $homolog_validate; + } + return 0; + } + return 1; + } + + /** + * + * Get Payment Response function + * + * @param MP $mp_instance MP Instance. + * @param string $access_token Access token. + * @return null + */ + public static function get_payment_response( $mp_instance, $access_token ) { + $payments = $mp_instance->get_payment_methods( $access_token ); + if ( isset( $payments['response'] ) ) { + return $payments['response']; + } + + return null; + } + + /** + * + * Update Payment Methods function + * + * @param MP $mp_instance MP instance. + * @param string|null $access_token Access token. + * @param array|null $payments_response Payments response. + */ + public static function update_payment_methods( $mp_instance, $access_token = null, $payments_response = null ): void { + if ( empty( $access_token ) || empty( $mp_instance ) ) { + return; + } + + if ( empty( $payments_response ) ) { + $payments_response = self::get_payment_response( $mp_instance, $access_token ); + } + + if ( empty( $payments_response ) || ( isset( $payments_response['status'] ) && 200 !== $payments_response['status'] && + 201 !== $payments_response['status'] ) ) { + return; + } + + $arr = array(); + $cho = array(); + $excluded = array('consumer_credits', 'paypal', 'account_money'); + + foreach ( $payments_response as $payment ) { + if ( in_array( $payment['id'], $excluded, true ) ) { + 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 ); + } + + /** + * + * Update Pix Method function + * + * @param MP $mp_instance Mp instance. + * @param string $access_token Access token. + * @param array|null $payments_response Payment response. + * @return void + */ + public static function update_pix_method( $mp_instance, $access_token, $payments_response = null ): void { + if ( empty( $access_token ) || empty( $mp_instance ) ) { + return; + } + + if ( empty( $payments_response ) ) { + $payments_response = self::get_payment_response( $mp_instance, $access_token ); + } + + if ( empty( $payments_response ) ) { + return; + } + + $payment_methods_pix = array(); + $accepted = array('pix'); + + foreach ( $payments_response as $payment ) { + if ( in_array( $payment['id'], $accepted, true ) ) { + $payment_methods_pix[ $payment['id'] ] = array( + 'id' => $payment['id'], + 'name' => $payment['name'], + 'secure_thumbnail' => $payment['secure_thumbnail'], + ); + } + } + + update_option( '_mp_payment_methods_pix', $payment_methods_pix, true ); + } + + /** + * + * Update Ticket Method function + * + * @param MP $mp_instance Mp instance. + * @param string $access_token Access token. + * @param array|null $payments_response Payment response. + * @return void + */ + public static function update_ticket_method( $mp_instance, $access_token, $payments_response = null ): void { + if ( empty( $access_token ) || empty( $mp_instance ) ) { + return; + } + + if ( empty( $payments_response ) ) { + $payments_response = self::get_payment_response( $mp_instance, $access_token ); + } + + if ( empty( $payments_response ) || ( isset( $payments_response['status'] ) && 200 !== $payments_response['status'] && + 201 !== $payments_response['status'] ) ) { + return; + } + + $payment_methods_ticket = array(); + $excluded = array('paypal', 'pse', 'pix'); + + foreach ( $payments_response as $payment ) { + if ( + ! in_array( $payment['id'], $excluded, true ) && + 'account_money' !== $payment['payment_type_id'] && + 'credit_card' !== $payment['payment_type_id'] && + 'debit_card' !== $payment['payment_type_id'] && + 'prepaid_card' !== $payment['payment_type_id'] + ) { + $payment_methods_ticket[] = $payment; + } + } + + update_option( '_all_payment_methods_ticket', $payment_methods_ticket, true ); + } + + /** + * + * Basic is enabled function + * + * @return string + */ + public static function basic_is_enabled() { + $basic_is_enabled = 'no'; + $basic_settings = get_option( 'woocommerce_woo-mercado-pago-basic_settings', '' ); + + if ( isset( $basic_settings['enabled'] ) ) { + $basic_is_enabled = $basic_settings['enabled']; + } + + return $basic_is_enabled; + } + + /** + * + * Validate Credentials Test function + * + * @param MP $mp_instance Mp instance. + * @param string|null $access_token Access token. + * @param string|null $public_key Payment response. + * + * @return bool + * @throws WC_WooMercadoPago_Exception + */ + public static function validate_credentials_test( $mp_instance, $access_token = null, $public_key = null ) { + $is_test = $mp_instance->get_credentials_wrapper( $access_token, $public_key ); + if ( is_array( $is_test ) && isset( $is_test['is_test'] ) && true === $is_test['is_test'] ) { + return true; + } + return false; + } + + /** + * + * Validate Credentials Prod function + * + * @param MP $mp_instance Mp instance. + * @param string|null $access_token Access token. + * @param string|null $public_key Payment response. + * + * @return bool + * @throws WC_WooMercadoPago_Exception + */ + public static function validate_credentials_prod( $mp_instance, $access_token = null, $public_key = null ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'mercadopago_requests' ); + $log->write_log( 'Func:', __FUNCTION__ ); + $is_test = $mp_instance->get_credentials_wrapper( $access_token, $public_key ); + if ( is_array( $is_test ) && isset( $is_test['is_test'] ) && false === $is_test['is_test'] ) { + if ( ! empty($is_test['client_id']) ) { + update_option('mp_application_id', $is_test['client_id']); + } + return true; + } + return false; + } } diff --git a/includes/module/class-wc-woomercadopago-exception.php b/includes/module/class-wc-woomercadopago-exception.php index baf682ba7..b065c1015 100644 --- a/includes/module/class-wc-woomercadopago-exception.php +++ b/includes/module/class-wc-woomercadopago-exception.php @@ -1,16 +1,9 @@ WooCommerce' - ); - WC_WooMercadoPago_Notices::get_alert_woocommerce_miss( $message, $type ); - } - - /** - * Add mp order meta box actions function - * - * @param array $actions actions. - * @return array - */ - public static function add_mp_order_meta_box_actions( $actions ) { - $actions['cancel_order'] = __( 'Cancel order', 'woocommerce-mercadopago' ); - return $actions; - } - - /** - * Mp show admin notices function - * - * @return void - */ - public static function mp_show_admin_notices() { - // phpcs:ignore WordPress.Security.NonceVerification - if ( ! isset( $_GET['page']) ) { - return; - } - // phpcs:ignore WordPress.Security.NonceVerification - $page = sanitize_text_field( wp_unslash( $_GET['page'] ) ); - - if ( ! WC_WooMercadoPago_Module::is_wc_new_version() || 'wc-settings' === $page && is_plugin_active( 'woocommerce-admin/woocommerce-admin.php' ) ) { - return; - } - - $notices_array = WC_WooMercadoPago_Module::$notices; - $notices = array_unique( $notices_array, SORT_STRING ); - foreach ( $notices as $notice ) { - echo wp_kses_post($notice); - } - } - - /** - * Activation plugin hook - */ - public static function mercadopago_plugin_activation() { - $dismissed_review = (int) get_option( '_mp_dismiss_review' ); - if ( ! isset( $dismissed_review ) || 1 === $dismissed_review ) { - update_option( '_mp_dismiss_review', 0, true ); - } - } - - /** - * Handle saved cards notice - */ - public static function mercadopago_handle_saved_cards_notice() { - $must_not_show_review = (int) get_option( '_mp_dismiss_saved_cards_notice' ); - if ( ! isset( $must_not_show_review ) || $must_not_show_review ) { - /** - * Update if option was changed. - * - * @since 3.0.1 - */ - update_option( '_mp_dismiss_saved_cards_notice', 0, true ); - } - } - - /** - * Update plugin version in db - */ - public static function update_plugin_version() { - $old_version = get_option( '_mp_version', '0' ); - if ( version_compare( WC_WooMercadoPago_Constants::VERSION, $old_version, '>' ) ) { - /** - * Do action mercadopago_plugin_updated. - * - * @since 3.0.1 - */ - do_action( 'mercadopago_plugin_updated' ); - - /** - * Do action mercadopago_test_mode_update. - * - * @since 3.0.1 - */ - do_action( 'mercadopago_test_mode_update' ); - - update_option( '_mp_version', WC_WooMercadoPago_Constants::VERSION, true ); - } - } - - /** - * Sdk validation - */ - public static function wc_mercado_pago_notify_sdk_package_error() { - $type = 'error'; - $message = __( 'The Mercado Pago module needs the SDK package to work!', 'woocommerce-mercadopago' ); - echo wp_kses_post( WC_WooMercadoPago_Notices::get_alert_frame( $message, $type )); - } - - /** - * Load sdk package - */ - public static function woocommerce_mercadopago_load_sdk() { - $sdk_autoload_file = dirname( __FILE__ ) . '/../../packages/sdk/vendor/autoload.php'; - if ( file_exists( $sdk_autoload_file ) ) { - require_once $sdk_autoload_file; - } else { - add_action('admin_notices', array( __CLASS__, 'wc_mercado_pago_notify_sdk_package_error' )); - } - } - - /** - * Init the plugin - */ - public static function woocommerce_mercadopago_init() { - $isAdmin = is_admin(); - - self::woocommerce_mercadopago_load_plugin_textdomain(); - self::woocommerce_mercadopago_load_sdk(); - - require_once dirname( __FILE__ ) . '/sdk/lib/rest-client/class-mp-rest-client-abstract.php'; - require_once dirname( __FILE__ ) . '/sdk/lib/rest-client/class-mp-rest-client.php'; - require_once dirname( __FILE__ ) . '/config/class-wc-woomercadopago-constants.php'; - - if ( $isAdmin ) { - require_once dirname( __FILE__ ) . '../../admin/notices/class-wc-woomercadopago-notices.php'; - require_once dirname( __FILE__ ) . '../../admin/notices/class-wc-woomercadopago-saved-cards.php'; - require_once dirname( __FILE__ ) . '../../admin/hooks/class-wc-woomercadopago-hook-order-details.php'; - WC_WooMercadoPago_Notices::init_mercadopago_notice(); - } - - // 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(), true ) ) { - add_action( 'admin_notices', array( __CLASS__, 'wc_mercado_pago_notify_curl_error' ) ); - return; - } - - if ( ! in_array( 'gd', get_loaded_extensions(), true ) ) { - add_action( 'admin_notices', array( __CLASS__, 'wc_mercado_pago_notify_gd_error' ) ); - } - - // Load Mercado Pago SDK. - require_once dirname( __FILE__ ) . '/sdk/lib/class-mp.php'; - - // Checks with WooCommerce is installed. - if ( class_exists( 'WC_Payment_Gateway' ) ) { - require_once dirname( __FILE__ ) . '/class-wc-woomercadopago-exception.php'; - require_once dirname( __FILE__ ) . '/class-wc-woomercadopago-configs.php'; - require_once dirname( __FILE__ ) . '/log/class-wc-woomercadopago-log.php'; - require_once dirname( __FILE__ ) . '/class-wc-woomercadopago-module.php'; - require_once dirname( __FILE__ ) . '/class-wc-woomercadopago-credentials.php'; - require_once dirname( __FILE__ ) . '/class-wc-woomercadopago-options.php'; - include_once dirname( __FILE__ ) . '/../helpers/class-wc-woomercadopago-helper-nonce.php'; - include_once dirname( __FILE__ ) . '/../helpers/class-wc-woomercadopago-helper-filter.php'; - include_once dirname( __FILE__ ) . '/../helpers/class-wc-woomercadopago-helper-current-user.php'; - - if ( $isAdmin ) { - require_once dirname( __FILE__ ) . '../../admin/notices/class-wc-woomercadopago-review-notice.php'; - require_once dirname( __FILE__ ) . '/mercadopago-settings/class-wc-woomercadopago-mercadopago-settings.php'; - - // Init Get Option - $option = WC_WooMercadoPago_Options::get_instance(); - - // Init Nonce Helper - $nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); - - // Init Current User Helper - $current_user = WC_WooMercadoPago_Helper_Current_User::get_instance(); - - WC_WooMercadoPago_Review_Notice::init_mercadopago_review_notice(); - WC_WooMercadoPago_Saved_Cards::init_singleton(); - new WC_WooMercadoPago_Hook_Order_Details(); - - // Load Mercado Pago Settings Screen - ( new WC_WooMercadoPago_MercadoPago_Settings( $option, $nonce, $current_user ) )->init(); - } - - require_once dirname( __FILE__ ) . '../../pix/class-wc-woomercadopago-image-generator.php'; - - WC_WooMercadoPago_Module::init_mercado_pago_class(); - new WC_WooMercadoPago_Products_Hook_Credits(); - WC_WooMercadoPago_Image_Generator::init_image_generator_class(); - - 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' ) ); - add_filter( 'query_vars', function ( $vars ) { - $vars[] = 'wallet_button'; - return $vars; - } ); - } + /** + * 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(): void { + $text_domain = LKN_WC_MERCADOPAGO_TEXT_DOMAIN; + + /** + * Apply filters plugin_locale. + * + * @since 3.0.1 + */ + $locale = apply_filters( 'plugin_locale', get_locale(), $text_domain ); + + $original_language_file = __DIR__ . '/../../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(): void { + $type = 'error'; + $message = __( 'Mercado Pago payments for WooCommerce requires PHP version 5.6 or later. Please update your PHP version.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + echo wp_kses_post( WC_WooMercadoPago_Notices::get_alert_frame( $message, $type )); + } + + /** + * Curl validation + */ + public static function wc_mercado_pago_notify_curl_error(): void { + $type = 'error'; + $message = __( 'Mercado Pago Error: PHP Extension CURL is not installed.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + echo wp_kses_post( WC_WooMercadoPago_Notices::get_alert_frame( $message, $type )); + } + + /** + * GD validation + */ + public static function wc_mercado_pago_notify_gd_error(): void { + $type = 'error'; + $message = __( 'Mercado Pago Error: PHP Extension GD is not installed. Installation of GD extension is required to send QR Code Pix by email.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + echo wp_kses_post( WC_WooMercadoPago_Notices::get_alert_frame( $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(): void { + $type = 'error'; + $message = sprintf( + /* translators: %s link to WooCommerce */ + __( 'The Mercado Pago module needs an active version of %s in order to work!', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ' WooCommerce' + ); + WC_WooMercadoPago_Notices::get_alert_woocommerce_miss( $message, $type ); + } + + /** + * Add mp order meta box actions function + * + * @param array $actions actions. + * @return array + */ + public static function add_mp_order_meta_box_actions( $actions ) { + $actions['cancel_order'] = __( 'Cancel order', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + return $actions; + } + + /** + * Mp show admin notices function + * + * @return void + */ + public static function mp_show_admin_notices(): void { + // phpcs:ignore WordPress.Security.NonceVerification + if ( ! isset( $_GET['page']) ) { + return; + } + // phpcs:ignore WordPress.Security.NonceVerification + $page = sanitize_text_field( wp_unslash( $_GET['page'] ) ); + + if ( ! WC_WooMercadoPago_Module::is_wc_new_version() || 'wc-settings' === $page && is_plugin_active( 'woocommerce-admin/woocommerce-admin.php' ) ) { + return; + } + + $notices_array = WC_WooMercadoPago_Module::$notices; + $notices = array_unique( $notices_array, \SORT_STRING ); + foreach ( $notices as $notice ) { + echo wp_kses_post($notice); + } + } + + /** + * Activation plugin hook + */ + public static function mercadopago_plugin_activation(): void { + $dismissed_review = (int) get_option( '_mp_dismiss_review' ); + if ( ! isset( $dismissed_review ) || 1 === $dismissed_review ) { + update_option( '_mp_dismiss_review', 0, true ); + } + } + + /** + * Handle saved cards notice + */ + public static function mercadopago_handle_saved_cards_notice(): void { + $must_not_show_review = (int) get_option( '_mp_dismiss_saved_cards_notice' ); + if ( ! isset( $must_not_show_review ) || $must_not_show_review ) { + /** + * Update if option was changed. + * + * @since 3.0.1 + */ + update_option( '_mp_dismiss_saved_cards_notice', 0, true ); + } + } + + /** + * Update plugin version in db + */ + public static function update_plugin_version(): void { + $old_version = get_option( '_mp_version', '0' ); + if ( version_compare( WC_WooMercadoPago_Constants::VERSION, $old_version, '>' ) ) { + /** + * Do action mercadopago_plugin_updated. + * + * @since 3.0.1 + */ + do_action( 'mercadopago_plugin_updated' ); + + /** + * Do action mercadopago_test_mode_update. + * + * @since 3.0.1 + */ + do_action( 'mercadopago_test_mode_update' ); + + update_option( '_mp_version', WC_WooMercadoPago_Constants::VERSION, true ); + } + } + + /** + * Sdk validation + */ + public static function wc_mercado_pago_notify_sdk_package_error(): void { + $type = 'error'; + $message = __( 'The Mercado Pago module needs the SDK package to work!', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + echo wp_kses_post( WC_WooMercadoPago_Notices::get_alert_frame( $message, $type )); + } + + /** + * Load sdk package + */ + public static function woocommerce_mercadopago_load_sdk(): void { + $sdk_autoload_file = __DIR__ . '/../../packages/sdk/vendor/autoload.php'; + if ( file_exists( $sdk_autoload_file ) ) { + require_once $sdk_autoload_file; + } else { + add_action('admin_notices', array(__CLASS__, 'wc_mercado_pago_notify_sdk_package_error')); + } + } + + /** + * Initializes the external plugin updater + * + * @since 6.9.3 + * + * @return void + */ + public static function updater_init() { + return new Lkn_Puc_Plugin_UpdateChecker( + 'https://api.linknacional.com.br/v2/u/?slug=lkn-mercadopago-woocommerce', + LKN_WC_MERCADOPAGO_FILE, + 'lkn-mercadopago-woocommerce' + ); + } + + /** + * Init the plugin + */ + public static function woocommerce_mercadopago_init(): void { + $isAdmin = is_admin(); + + self::woocommerce_mercadopago_load_plugin_textdomain(); + self::woocommerce_mercadopago_load_sdk(); + + require_once __DIR__ . '/sdk/lib/rest-client/class-mp-rest-client-abstract.php'; + require_once __DIR__ . '/sdk/lib/rest-client/class-mp-rest-client.php'; + require_once __DIR__ . '/config/class-wc-woomercadopago-constants.php'; + + if ( $isAdmin ) { + require_once __DIR__ . '../../admin/notices/class-wc-woomercadopago-notices.php'; + require_once __DIR__ . '../../admin/notices/class-wc-woomercadopago-saved-cards.php'; + require_once __DIR__ . '../../admin/hooks/class-wc-woomercadopago-hook-order-details.php'; + WC_WooMercadoPago_Notices::init_mercadopago_notice(); + } + + // 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(), true ) ) { + add_action( 'admin_notices', array(__CLASS__, 'wc_mercado_pago_notify_curl_error') ); + return; + } + + if ( ! in_array( 'gd', get_loaded_extensions(), true ) ) { + add_action( 'admin_notices', array(__CLASS__, 'wc_mercado_pago_notify_gd_error') ); + } + + // Load Mercado Pago SDK. + require_once __DIR__ . '/sdk/lib/class-mp.php'; + + // Checks with WooCommerce is installed. + if ( class_exists( 'WC_Payment_Gateway' ) ) { + require_once __DIR__ . '/class-wc-woomercadopago-exception.php'; + require_once __DIR__ . '/class-wc-woomercadopago-configs.php'; + require_once __DIR__ . '/log/class-wc-woomercadopago-log.php'; + require_once __DIR__ . '/class-wc-woomercadopago-module.php'; + require_once __DIR__ . '/class-wc-woomercadopago-credentials.php'; + require_once __DIR__ . '/class-wc-woomercadopago-options.php'; + include_once __DIR__ . '/../helpers/class-wc-woomercadopago-helper-nonce.php'; + include_once __DIR__ . '/../helpers/class-wc-woomercadopago-helper-filter.php'; + include_once __DIR__ . '/../helpers/class-wc-woomercadopago-helper-current-user.php'; + include_once __DIR__ . '/../helpers/class-wc-woomercadopago-helper-credits-enable.php'; + + if ( $isAdmin ) { + require_once __DIR__ . '/../admin/notices/class-wc-woomercadopago-review-notice.php'; + require_once __DIR__ . '/mercadopago-settings/class-wc-woomercadopago-mercadopago-settings.php'; + require_once __DIR__ . '/../../packages/plugin-updater/plugin-update-checker.php'; + + add_action('woocommerce_init', array('WC_WooMercadoPago_Init', 'updater_init')); + + // Init Get Option + $option = WC_WooMercadoPago_Options::get_instance(); + + // Init Nonce Helper + $nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); + + // Init Current User Helper + $current_user = WC_WooMercadoPago_Helper_Current_User::get_instance(); + + WC_WooMercadoPago_Review_Notice::init_mercadopago_review_notice(); + WC_WooMercadoPago_Saved_Cards::init_singleton(); + new WC_WooMercadoPago_Hook_Order_Details(); + + // Load Mercado Pago Settings Screen + ( new WC_WooMercadoPago_MercadoPago_Settings( $option, $nonce, $current_user ) )->init(); + } + + require_once __DIR__ . '../../pix/class-wc-woomercadopago-image-generator.php'; + + WC_WooMercadoPago_Module::init_mercado_pago_class(); + new WC_WooMercadoPago_Products_Hook_Credits(); + WC_WooMercadoPago_Image_Generator::init_image_generator_class(); + WC_WooMercadoPago_Helper_Credits_Enable::register_enable_credits_action(); + + self::update_plugin_version(); + + add_action( 'woocommerce_order_actions', array(__CLASS__, 'add_mp_order_meta_box_actions') ); + /** + * Activate credits by default, if the seller has cho pro enabled + * and it was not previously enabled by default. + * + * @since 6.9.3 + */ + do_action(WC_WooMercadoPago_Helper_Credits_Enable::ENABLE_CREDITS_ACTION); + } else { + add_action( 'admin_notices', array(__CLASS__, 'notify_woocommerce_miss') ); + } + add_action( 'woocommerce_settings_checkout', array(__CLASS__, 'mp_show_admin_notices') ); + add_filter( 'query_vars', function ( $vars ) { + $vars[] = 'wallet_button'; + return $vars; + } ); + } } diff --git a/includes/module/class-wc-woomercadopago-module.php b/includes/module/class-wc-woomercadopago-module.php index f479a92bc..7f66c2a67 100644 --- a/includes/module/class-wc-woomercadopago-module.php +++ b/includes/module/class-wc-woomercadopago-module.php @@ -1,985 +1,953 @@ load_helpers(); - $this->load_configs(); - $this->load_log(); - $this->load_order(); - $this->load_hooks(); - $this->load_preferences(); - $this->load_payments(); - $this->load_notifications(); - $this->load_stock_manager(); - - // melidata admin scripts - add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_scripts' ) ); - - // melidata buyer scripts - add_action( 'before_woocommerce_pay', array( $this, 'load_before_woocommerce_pay_scripts' ) ); - add_action( 'woocommerce_before_checkout_form', array( $this, 'load_before_checkout_scripts' ) ); - add_action( 'woocommerce_pay_order_before_submit', array( $this, 'load_pay_order_scripts' ) ); - add_action( 'woocommerce_before_thankyou', array( $this, 'load_before_thankyou_scripts' ) ); - - add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_css' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'load_global_css' ) ); - add_action( 'wp_enqueue_scripts', array( $this, 'load_global_css' ) ); - - add_filter( 'woocommerce_available_payment_gateways', array( $this, 'filter_payment_method_by_shipping' ) ); - 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' ) ); - add_action( 'mercadopago_test_mode_update', array( $this, 'update_credential_production' ) ); - - if ( is_admin() ) { + /** + * Categories variable + * + * @var array + */ + public static $categories = array(); + + /** + * Country Configs variable + * + * @var array + */ + public static $country_configs = array(); + + /** + * Site data variable + * + * @var string + */ + public static $site_data; + + /** + * Undocumented variable + * + * @var MP + */ + public static $instance = null; + + /** + * MP instance ayment variable + * + * @var array + */ + public static $mp_instance_ayment = array(); + + /** + * MP instance variable + * + * @var MP + */ + public static $mp_instance = null; + + /** + * Payments name variable + * + * @var string + */ + public static $payments_name = null; + + /** + * Notices variable + * + * @var array + */ + public static $notices = array(); + + /** + * WC_WooMercadoPago_Module constructor. + * + * @throws WC_WooMercadoPago_Exception Error. + */ + public function __construct() { + try { + $this->load_helpers(); + $this->load_configs(); + $this->load_log(); + $this->load_order(); + $this->load_hooks(); + $this->load_preferences(); + $this->load_payments(); + $this->load_notifications(); + $this->load_stock_manager(); + + // melidata admin scripts + add_action( 'admin_enqueue_scripts', array($this, 'load_admin_scripts') ); + + // melidata buyer scripts + add_action( 'before_woocommerce_pay', array($this, 'load_before_woocommerce_pay_scripts') ); + add_action( 'woocommerce_before_checkout_form', array($this, 'load_before_checkout_scripts') ); + add_action( 'woocommerce_pay_order_before_submit', array($this, 'load_pay_order_scripts') ); + add_action( 'woocommerce_before_thankyou', array($this, 'load_before_thankyou_scripts') ); + + add_action( 'admin_enqueue_scripts', array($this, 'load_admin_css') ); + add_action( 'admin_enqueue_scripts', array($this, 'load_global_css') ); + add_action( 'wp_enqueue_scripts', array($this, 'load_global_css') ); + + add_filter( 'woocommerce_available_payment_gateways', array($this, 'filter_payment_method_by_shipping') ); + add_filter( 'plugin_action_links_' . LKN_WC_MERCADOPAGO_BASENAME, array($this, 'woomercadopago_settings_link') ); + add_action( 'mercadopago_plugin_updated', array('WC_WooMercadoPago_Credentials', 'mercadopago_payment_update') ); + add_action( 'mercadopago_test_mode_update', array($this, 'update_credential_production') ); + + if ( is_admin() ) { // validate credentials. - if ( isset( $_REQUEST['section'] ) ) { // phpcs:disable WordPress.Security.NonceVerification - $credentials = new WC_WooMercadoPago_Credentials(); - if ( ! $credentials->token_is_valid() ) { - add_action( 'admin_notices', array( $this, 'enable_payment_notice' ) ); - } - } - } - } catch ( Exception $e ) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'WC_WooMercadoPago_Module' ); - $log->write_log( '__construct: ', $e->getMessage() ); - } - } - - /** - * Load Helpers - * - * @return void - */ - public function load_helpers() { - include_once dirname( __FILE__ ) . '/../helpers/class-wc-woomercadopago-helper-current-url.php'; - include_once dirname( __FILE__ ) . '/../helpers/class-wc-woomercadopago-helpers-currencyconverter.php'; - include_once dirname( __FILE__ ) . '/../helpers/class-wc-woomercadopago-composite-id-helper.php'; - include_once dirname( __FILE__ ) . '/../helpers/class-wc-woomercadopago-helper-links.php'; - include_once dirname( __FILE__ ) . '/../helpers/class-wc-woomercadopago-helper-credits.php'; - } - - /** - * - * Load Config / Categories - * - * @return void - */ - public function load_configs() { - self::$country_configs = self::get_country_configs(); - $configs = new parent(); // phpcs:ignore - self::$categories = $configs->get_categories(); - self::$site_data = self::get_site_data(); - self::$payments_name = self::set_payment_gateway(); - } - - /** - * 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 array with the information. - */ - public static function get_site_data() { - $site_id = strtolower( get_option( '_site_id_v1', '' ) ); - if ( isset( $site_id ) && ! empty( $site_id ) ) { - return self::$country_configs[ $site_id ]; - } else { - return null; - } - } - - /** - * - * Load log - * - * @return void - */ - public function load_log() { - include_once dirname( __FILE__ ) . '/log/class-wc-woomercadopago-log.php'; - } - - public function load_order() { - include_once dirname( __FILE__ ) . '/order/class-wc-woomercadopago-order.php'; - } - - /** - * - * Load Hooks - * - * @return void - */ - public function load_hooks() { - include_once dirname( __FILE__ ) . '/../payments/hooks/class-wc-woomercadopago-hook-abstract.php'; - include_once dirname( __FILE__ ) . '/../payments/hooks/class-wc-woomercadopago-hook-basic.php'; - include_once dirname( __FILE__ ) . '/../payments/hooks/class-wc-woomercadopago-hook-custom.php'; - include_once dirname( __FILE__ ) . '/../payments/hooks/class-wc-woomercadopago-hook-ticket.php'; - include_once dirname( __FILE__ ) . '/../payments/hooks/class-wc-woomercadopago-hook-pix.php'; - include_once dirname( __FILE__ ) . '/../payments/hooks/class-wc-woomercadopago-hook-credits.php'; - include_once dirname( __FILE__ ) . '/../products/hooks/class-wc-woomercadopago-products-hook-credits.php'; - } - - /** - * Load Preferences Classes - * - * @return void - */ - public function load_preferences() { - include_once dirname( __FILE__ ) . '/preference/class-wc-woomercadopago-preference-abstract.php'; - include_once dirname( __FILE__ ) . '/preference/class-wc-woomercadopago-preference-basic.php'; - include_once dirname( __FILE__ ) . '/preference/class-wc-woomercadopago-preference-custom.php'; - include_once dirname( __FILE__ ) . '/preference/class-wc-woomercadopago-preference-ticket.php'; - include_once dirname( __FILE__ ) . '/preference/class-wc-woomercadopago-preference-pix.php'; - include_once dirname( __FILE__ ) . '/preference/class-wc-woomercadopago-preference-credits.php'; - include_once dirname( __FILE__ ) . '/preference/analytics/class-wc-woomercadopago-preferenceanalytics.php'; - include_once dirname( __FILE__ ) . '/preference/class-wc-woomercadopago-preference-custom-wallet-button.php'; - } - - /** - * Load Payment Classes - * - * @return void - */ - public function load_payments() { - include_once dirname( __FILE__ ) . '/../payments/class-wc-woomercadopago-payment-abstract.php'; - include_once dirname( __FILE__ ) . '/../payments/class-wc-woomercadopago-basic-gateway.php'; - include_once dirname( __FILE__ ) . '/../payments/class-wc-woomercadopago-custom-gateway.php'; - include_once dirname( __FILE__ ) . '/../payments/class-wc-woomercadopago-ticket-gateway.php'; - include_once dirname( __FILE__ ) . '/../payments/class-wc-woomercadopago-pix-gateway.php'; - include_once dirname( __FILE__ ) . '/../payments/class-wc-woomercadopago-credits-gateway.php'; - add_filter( 'woocommerce_payment_gateways', array( $this, 'set_payment_gateway' ) ); - } - - /** - * - * Load Notifications - * - * @return void - */ - public function load_notifications() { - include_once dirname( __FILE__ ) . '/../notification/class-wc-woomercadopago-notification-abstract.php'; - include_once dirname( __FILE__ ) . '/../notification/class-wc-woomercadopago-notification-ipn.php'; - include_once dirname( __FILE__ ) . '/../notification/class-wc-woomercadopago-notification-core.php'; - include_once dirname( __FILE__ ) . '/../notification/class-wc-woomercadopago-notification-webhook.php'; - } - - /** - * - * Load Stock Manager - * - * @return void - */ - public function load_stock_manager() { - include_once dirname( __FILE__ ) . '/../stock/class-wc-woomercadopago-stock-manager.php'; - } - - /** - * - * Get Mp InstanceSingleton - * - * @param null|object $payment payment. - * - * @return MP|null - * @throws WC_WooMercadoPago_Exception Error. - */ - public static function get_mp_instance_singleton( $payment = null ) { - $mp = null; - if ( ! empty( $payment ) ) { - $class = get_class( $payment ); - if ( ! isset( self::$mp_instance_ayment[ $class ] ) ) { - self::$mp_instance_ayment[ $class ] = self::get_mp_instance( $payment ); - $mp = self::$mp_instance_ayment[ $class ]; - if ( ! empty( $mp ) ) { - return $mp; - } - } - } - - if ( null === self::$mp_instance || empty( $mp ) ) { - self::$mp_instance = self::get_mp_instance(); - } - - return self::$mp_instance; - } - - /** - * - * Get Mp Instance - * - * @param object $payment payment. - * - * @return MP MP. - * @throws WC_WooMercadoPago_Exception Error. - */ - public static function get_mp_instance( $payment = null ) { - $credentials = new WC_WooMercadoPago_Credentials( $payment ); - $validate_credentials_type = $credentials->validate_credentials_type(); - if ( WC_WooMercadoPago_Credentials::TYPE_ACCESS_TOKEN === $validate_credentials_type ) { - $mp = new MP( $credentials->access_token ); - $mp->set_payment_class( $payment ); - } - - if ( WC_WooMercadoPago_Credentials::TYPE_ACCESS_CLIENT === $validate_credentials_type ) { - $mp = new MP( $credentials->client_id, $credentials->client_secret ); - $mp->set_payment_class( $payment ); - - if ( ! empty( $payment ) ) { - $payment->sandbox = false; - } - } - - if ( ! isset( $mp ) ) { - return false; - } - - $email = ( 0 !== wp_get_current_user()->ID ) ? wp_get_current_user()->user_email : null; - $mp->set_email( $email ); - - $locale = get_locale(); - $locale = false !== ( strpos( $locale, '_' ) && 5 === strlen( $locale ) ) ? explode( '_', $locale ) : array( - '', - '' - ); - $mp->set_locale( $locale[1] ); - - return $mp; - } - - /** - * - * Init Mercado Pago Class - * - * @return WC_WooMercadoPago_Module|null - * Singleton - */ - public static function init_mercado_pago_class() { - if ( null === self::$instance ) { - self::$instance = new self(); - } - - return self::$instance; - } - - /** - * - * Define terms and conditions link - * - * @return string - */ - public static function mp_define_terms_and_conditions() { - $links_mp = self::define_link_country(); - $link_prefix_mp = 'https://www.mercadopago.'; - - return array( - 'text_prefix' => __( 'By continuing, you agree to our ', 'woocommerce-mercadopago' ), - 'link_terms_and_conditions' => $link_prefix_mp . $links_mp['sufix_url'] . $links_mp['help'] . $links_mp['term_conditition'], - 'text_suffix' => __( 'Terms and Conditions', 'woocommerce-mercadopago' ), - ); - - } - - /** - * Get Common Error Messages function - * - * @param string $key Key. - * - * @return string - */ - public static function get_common_error_messages( $key ) { - if ( 'Invalid payment_method_id' === $key ) { - return __( 'The payment method is not valid or not available.', 'woocommerce-mercadopago' ); - } - if ( 'Invalid transaction_amount' === $key ) { - 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 ( 'Invalid users involved' === $key ) { - 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 ( 'Unauthorized use of live credentials' === $key ) { - 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. - * - * @param string $used_currency Used currency. - * - * @return float float that is the rate of conversion. - */ - public static function get_conversion_rate( $used_currency ) { - $from_currency = get_woocommerce_currency(); - $to_currency = $used_currency; - - return WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->load_ratio( $from_currency, $to_currency ); - } - - /** - * - * Get Common Settings function - * - * @return array - */ - public static function get_common_settings() { - $w = self::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; - } - - /** - * - * Get WooCommerce instance - * Summary: Check if we have valid credentials for v1. - * Description: Check if we have valid credentials. - * - * @return boolean true/false depending on the validation result. - */ - public static function woocommerce_instance() { - if ( function_exists( 'WC' ) ) { - return WC(); - } else { - global $woocommerce; - return $woocommerce; - } - } - - /** - * 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 string. - */ - public static function get_sponsor_id() { - $site_data = self::get_site_data(); - return $site_data['sponsor_id']; - } - - /** - * - * Fix url ampersand - * Fix to URL Problem : #038; replaces & and breaks the navigation. - * - * @param string $link Link. - * - * @return string - */ - public static function fix_url_ampersand( $link ) { - return str_replace( '\/', '/', str_replace( '&', '&', $link ) ); - } - - /** - * Summary: Find template's folder. - * Description: Find template's folder. - * - * @return string string that identifies the path. - */ - public static function get_templates_path() { - return plugin_dir_path( __FILE__ ) . '../../templates/'; - } - - /** - * Is Subscription function - * Check if an order is recurrent. - * - * @param object $items items. - * - * @return boolean - */ - public static function is_subscription( $items ) { - $is_subscription = false; - if ( 1 === count( $items ) ) { - foreach ( $items as $cart_item_key => $cart_item ) { - $is_recurrent = ( is_object( $cart_item ) && 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 ( 'yes' === $is_recurrent ) { - $is_subscription = true; - } - } - } - - return $is_subscription; - } - - /** - * Get Country Name function - * - * @param string $site_id Site id. - * - * @return string - */ - 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 ''; - } - - /** - * Get Map function - * - * @param array $selector_id Selector id. - * - * @return array - */ - 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; - } - - /** - * - * Is_wc_new_version function - * - * @return bool - */ - public static function is_wc_new_version() { - $woo_commerce_version = WC()->version; - if ( $woo_commerce_version <= '4.0.0' ) { - return false; - } - - return true; - } - - /** - * - * Is Mobile function - * - * @return bool - */ - public static function is_mobile() { - return wp_is_mobile(); - } - - /** - * - * Get notification type by the payment class - * - * @return string - */ - public static function get_notification_type( $notification_type ) { - $types['WC_WooMercadoPago_Basic_Gateway'] = 'ipn'; - $types['WC_WooMercadoPago_Credits_Gateway'] = 'ipn'; - $types['WC_WooMercadoPago_Custom_Gateway'] = 'webhooks'; - $types['WC_WooMercadoPago_Pix_Gateway'] = 'webhooks'; - $types['WC_WooMercadoPago_Ticket_Gateway'] = 'webhooks'; - - return $types[ $notification_type ]; - } - - /** - * Load Admin Css - * - * @return void - */ - public function load_admin_css() { - if ( is_admin() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) ) ) { - $suffix = $this->get_suffix(); - - wp_enqueue_style( - 'woocommerce-mercadopago-basic-config-styles', - plugins_url( '../assets/css/config_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - - wp_enqueue_style( - 'woocommerce-mercadopago-components', - plugins_url( '../assets/css/components_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - } - } - - /** - * Get Suffix to get minify files - * - * @return string - */ - private function get_suffix() { - return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - } - - /** - * Load global CSS - * - * @return void - */ - public function load_global_css() { - $suffix = $this->get_suffix(); - - wp_enqueue_style( - 'woocommerce-mercadopago-global-css', - plugins_url( '../assets/css/global' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - } - - /** - * Load admin scripts - * - * @return void - */ - public function load_admin_scripts() { - global $woocommerce; - - $site_id = get_option( '_site_id_v1' ); - - $this->load_notices_scripts($woocommerce, $site_id); - $this->load_melidata_scripts($woocommerce, $site_id); - } - - /** - * Load melidata scripts - * - * @param $woocommerce - * @param $site_id - * - * @return void - */ - public function load_melidata_scripts( $woocommerce, $site_id ) { - if ( - is_admin() && ( - WC_WooMercadoPago_Helper_Current_Url::validate_url( 'plugins' ) || - WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || - WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) - ) - ) { - wp_enqueue_script( - 'mercadopago_melidata', - plugins_url( '../assets/js/melidata/melidata-client' . $this->get_suffix() . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - - wp_localize_script( - 'mercadopago_melidata', - 'wc_melidata_params', - array( - 'type' => 'seller', - 'site_id' => $site_id ? strtoupper( $site_id ) : 'MLA', - 'location' => '/settings', - 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, - 'platform_version' => $woocommerce->version, - ) - ); - } - } - - /** - * Load jaiminho notices scripts - * - * @param $woocommerce - * @param $site_id - * - * @return void - */ - public function load_notices_scripts( $woocommerce, $site_id ) { - if ( - is_admin() && ( - WC_WooMercadoPago_Helper_Current_Url::validate_url( 'index' ) || - WC_WooMercadoPago_Helper_Current_Url::validate_url( 'plugins' ) || - WC_WooMercadoPago_Helper_Current_Url::validate_page( 'wc-admin' ) || - WC_WooMercadoPago_Helper_Current_Url::validate_page( 'wc-settings' ) || - WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) - ) - ) { - $credentials = ( WC_WooMercadoPago_Options::get_instance() )->get_access_token_and_public_key(); - $public_key = $credentials['credentials_public_key_prod']; - - wp_enqueue_script( - 'mercadopago_notices', - plugins_url( '../assets/js/notices/notices-client' . $this->get_suffix() . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - - wp_localize_script( - 'mercadopago_notices', - 'wc_mercadopago_notices_params', - array( - 'site_id' => $site_id ? strtoupper( $site_id ) : 'MLA', - 'container' => '#wpbody-content', - 'public_key' => $public_key, - 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, - 'platform_id' => WC_WooMercadoPago_Constants::PLATAFORM_ID, - 'platform_version' => $woocommerce->version, - ) - ); - } - } - - public function load_before_woocommerce_pay_scripts() { - $this->load_buyer_scripts('/woocommerce_pay', null); - } - - public function load_before_checkout_scripts() { - $this->load_buyer_scripts('/checkout', null); - } - - public function load_pay_order_scripts() { - $this->load_buyer_scripts('/pay_order', null); - } - - public function load_before_thankyou_scripts( $order_id ) { - $order = wc_get_order( $order_id ); - - $payment_method = $order->get_payment_method(); - $is_mercadopago_payment_method = in_array($payment_method, WC_WooMercadoPago_Constants::GATEWAYS_IDS, true); - - if ( $is_mercadopago_payment_method ) { - $this->load_buyer_scripts('/thankyou', $payment_method); - } - } - - /** - * Load buyer scripts - * - * @return void - */ - public function load_buyer_scripts( $location, $payment_method ) { - global $woocommerce; - - $site_id = get_option( '_site_id_v1' ); - - wp_enqueue_script( - 'mercadopago_melidata', - plugins_url( '../assets/js/melidata/melidata-client' . $this->get_suffix() . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - - wp_localize_script( - 'mercadopago_melidata', - 'wc_melidata_params', - array( - 'type' => 'buyer', - 'site_id' => $site_id ? strtoupper( $site_id ) : 'MLA', - 'location' => $location, - 'payment_method' => $payment_method, - 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, - 'platform_version' => $woocommerce->version, - ) - ); - } - - /** - * - * Filter Payment Method by Shipping - * - * @param array $methods methods. - * - * @return array - */ - public function filter_payment_method_by_shipping( $methods ) { - return $methods; - } - - /** - * - * Enable Payment Notice - * - * @return void - */ - public function enable_payment_notice() { - $type = 'notice-warning'; - $message = __( 'Fill in your credentials to enable payment methods.', 'woocommerce-mercadopago' ); - echo wp_kses_post( WC_WooMercadoPago_Notices::get_alert_frame( $message, $type )); - } - - /** - * - * Woomercadopago Settings Link add settings link on plugin page. - * Enable Payment Notice - * - * @param array $links links. - * - * @return array - */ - public function woomercadopago_settings_link( $links ) { - $links_mp = self::define_link_country(); - $plugin_links = array(); - $plugin_links[] = '' . __( 'Set plugin', 'woocommerce-mercadopago' ) . ''; - $plugin_links[] = '' . __( 'Payment methods', 'woocommerce-mercadopago' ) . ''; - $plugin_links[] = '
' . __( 'Plugin manual', 'woocommerce-mercadopago' ) . ''; - - return array_merge( $plugin_links, $links ); - } - - /** - * - * Define link country - * - * @return array - */ - public static function define_link_country() { - $sufix_country = 'AR'; - $country = array( - 'AR' => array( // Argentinian. - 'help' => 'ayuda', - 'sufix_url' => 'com.ar/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', - 'site_id_mp' => 'mla', - - ), - 'BR' => array( // Brazil. - 'help' => 'ajuda', - 'sufix_url' => 'com.br/', - 'translate' => 'pt', - 'term_conditition' => '/termos-e-politicas_194', - 'site_id_mp' => 'mlb', - ), - 'CL' => array( // Chile. - 'help' => 'ayuda', - 'sufix_url' => 'cl/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', - 'site_id_mp' => 'mlc', - ), - 'CO' => array( // Colombia. - 'help' => 'ayuda', - 'sufix_url' => 'com.co/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', - 'site_id_mp' => 'mco', - ), - 'MX' => array( // Mexico. - 'help' => 'ayuda', - 'sufix_url' => 'com.mx/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', - 'site_id_mp' => 'mlm', - ), - 'PE' => array( // Peru. - 'help' => 'ayuda', - 'sufix_url' => 'com.pe/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', - 'site_id_mp' => 'mpe', - ), - 'UY' => array( // Uruguay. - 'help' => 'ayuda', - 'sufix_url' => 'com.uy/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', - 'site_id_mp' => 'mlu', - ), - ); - - $sufix_country = strtoupper( self::get_woocommerce_default_country() ); - $links_country = array_key_exists( $sufix_country, $country ) ? $country[ $sufix_country ] : $country['AR']; - - return $links_country; - } - - /** - * - * Get Woocommerce default country configured - * - * @return string - */ - public static function get_woocommerce_default_country() { - $wc_country = get_option( 'woocommerce_default_country', '' ); - if ( '' !== $wc_country ) { - $wc_country = strlen( $wc_country ) > 2 ? substr( $wc_country, 0, 2 ) : $wc_country; - } - - return $wc_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; - } - - /** - * Update Credentials for production - */ - public function update_credential_production() { - if ( get_option( 'checkbox_checkout_test_mode' ) ) { - return; - } - - $has_a_gateway_in_production = false; - - foreach ( WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS as $gateway ) { - $key = 'woocommerce_' . $gateway::get_id() . '_settings'; - $options = get_option( $key ); - if ( ! empty( $options ) ) { - $old_credential_is_prod = array_key_exists( 'checkout_credential_prod', $options ) && isset( $options['checkout_credential_prod'] ) ? $options['checkout_credential_prod'] : 'no'; - $has_new_key = array_key_exists( 'checkbox_checkout_test_mode', $options ) && isset( $options['checkbox_checkout_test_mode'] ); - $options['checkbox_checkout_test_mode'] = $has_new_key && 'deprecated' === $old_credential_is_prod - ? $options['checkbox_checkout_test_mode'] - : ( 'yes' === $old_credential_is_prod ? 'no' : 'yes' ); - $options['checkout_credential_prod'] = 'deprecated'; - - if ( 'no' === $options['checkbox_checkout_test_mode'] ) { - $has_a_gateway_in_production = true; - } - - /** - * Update if options were changed. - * - * @since 3.0.1 - */ - update_option( $key, apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $gateway::get_id(), $options ) ); - } - } - - $test_mode_value = $has_a_gateway_in_production ? 'no' : 'yes'; - - update_option( 'checkbox_checkout_test_mode', $test_mode_value, true ); - } - + if ( isset( $_REQUEST['section'] ) ) { // phpcs:disable WordPress.Security.NonceVerification + $credentials = new WC_WooMercadoPago_Credentials(); + if ( ! $credentials->token_is_valid() ) { + add_action( 'admin_notices', array($this, 'enable_payment_notice') ); + } + } + } + } catch ( Exception $e ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'WC_WooMercadoPago_Module' ); + $log->write_log( '__construct: ', $e->getMessage() ); + } + } + + /** + * Load Helpers + * + * @return void + */ + public function load_helpers(): void { + include_once __DIR__ . '/../helpers/class-wc-woomercadopago-helper-current-url.php'; + include_once __DIR__ . '/../helpers/class-wc-woomercadopago-helpers-currencyconverter.php'; + include_once __DIR__ . '/../helpers/class-wc-woomercadopago-composite-id-helper.php'; + include_once __DIR__ . '/../helpers/class-wc-woomercadopago-helper-links.php'; + include_once __DIR__ . '/../helpers/class-wc-woomercadopago-helper-credits.php'; + } + + /** + * + * Load Config / Categories + * + * @return void + */ + public function load_configs(): void { + self::$country_configs = self::get_country_configs(); + $configs = new parent(); // phpcs:ignore + self::$categories = $configs->get_categories(); + self::$site_data = self::get_site_data(); + self::$payments_name = self::set_payment_gateway(); + } + + /** + * 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 array with the information. + */ + public static function get_site_data() { + $site_id = strtolower( get_option( '_site_id_v1', '' ) ); + if ( isset( $site_id ) && ! empty( $site_id ) ) { + return self::$country_configs[ $site_id ]; + } else { + return null; + } + } + + /** + * + * Load log + * + * @return void + */ + public function load_log(): void { + include_once __DIR__ . '/log/class-wc-woomercadopago-log.php'; + } + + public function load_order(): void { + include_once __DIR__ . '/order/class-wc-woomercadopago-order.php'; + } + + /** + * + * Load Hooks + * + * @return void + */ + public function load_hooks(): void { + include_once __DIR__ . '/../payments/hooks/class-wc-woomercadopago-hook-abstract.php'; + include_once __DIR__ . '/../payments/hooks/class-wc-woomercadopago-hook-basic.php'; + include_once __DIR__ . '/../payments/hooks/class-wc-woomercadopago-hook-custom.php'; + include_once __DIR__ . '/../payments/hooks/class-wc-woomercadopago-hook-ticket.php'; + include_once __DIR__ . '/../payments/hooks/class-wc-woomercadopago-hook-pix.php'; + include_once __DIR__ . '/../payments/hooks/class-wc-woomercadopago-hook-credits.php'; + include_once __DIR__ . '/../products/hooks/class-wc-woomercadopago-products-hook-credits.php'; + } + + /** + * Load Preferences Classes + * + * @return void + */ + public function load_preferences(): void { + include_once __DIR__ . '/preference/class-wc-woomercadopago-preference-abstract.php'; + include_once __DIR__ . '/preference/class-wc-woomercadopago-preference-basic.php'; + include_once __DIR__ . '/preference/class-wc-woomercadopago-preference-custom.php'; + include_once __DIR__ . '/preference/class-wc-woomercadopago-preference-ticket.php'; + include_once __DIR__ . '/preference/class-wc-woomercadopago-preference-pix.php'; + include_once __DIR__ . '/preference/class-wc-woomercadopago-preference-credits.php'; + include_once __DIR__ . '/preference/analytics/class-wc-woomercadopago-preferenceanalytics.php'; + include_once __DIR__ . '/preference/class-wc-woomercadopago-preference-custom-wallet-button.php'; + } + + /** + * Load Payment Classes + * + * @return void + */ + public function load_payments(): void { + include_once __DIR__ . '/../payments/class-wc-woomercadopago-payment-abstract.php'; + include_once __DIR__ . '/../payments/class-wc-woomercadopago-basic-gateway.php'; + include_once __DIR__ . '/../payments/class-wc-woomercadopago-custom-gateway.php'; + include_once __DIR__ . '/../payments/class-wc-woomercadopago-ticket-gateway.php'; + include_once __DIR__ . '/../payments/class-wc-woomercadopago-pix-gateway.php'; + include_once __DIR__ . '/../payments/class-wc-woomercadopago-credits-gateway.php'; + add_filter( 'woocommerce_payment_gateways', array($this, 'set_payment_gateway') ); + } + + /** + * + * Load Notifications + * + * @return void + */ + public function load_notifications(): void { + include_once __DIR__ . '/../notification/class-wc-woomercadopago-notification-abstract.php'; + include_once __DIR__ . '/../notification/class-wc-woomercadopago-notification-ipn.php'; + include_once __DIR__ . '/../notification/class-wc-woomercadopago-notification-core.php'; + include_once __DIR__ . '/../notification/class-wc-woomercadopago-notification-webhook.php'; + } + + /** + * + * Load Stock Manager + * + * @return void + */ + public function load_stock_manager(): void { + include_once __DIR__ . '/../stock/class-wc-woomercadopago-stock-manager.php'; + } + + /** + * + * Get Mp InstanceSingleton + * + * @param object|null $payment payment. + * + * @return MP|null + * @throws WC_WooMercadoPago_Exception Error. + */ + public static function get_mp_instance_singleton( $payment = null ) { + $mp = null; + if ( ! empty( $payment ) ) { + $class = get_class( $payment ); + if ( ! isset( self::$mp_instance_ayment[ $class ] ) ) { + self::$mp_instance_ayment[ $class ] = self::get_mp_instance( $payment ); + $mp = self::$mp_instance_ayment[ $class ]; + if ( ! empty( $mp ) ) { + return $mp; + } + } + } + + if ( null === self::$mp_instance || empty( $mp ) ) { + self::$mp_instance = self::get_mp_instance(); + } + + return self::$mp_instance; + } + + /** + * + * Get Mp Instance + * + * @param object $payment payment. + * + * @return MP MP. + * @throws WC_WooMercadoPago_Exception Error. + */ + public static function get_mp_instance( $payment = null ) { + $credentials = new WC_WooMercadoPago_Credentials( $payment ); + $validate_credentials_type = $credentials->validate_credentials_type(); + if ( WC_WooMercadoPago_Credentials::TYPE_ACCESS_TOKEN === $validate_credentials_type ) { + $mp = new MP( $credentials->access_token ); + $mp->set_payment_class( $payment ); + } + + if ( WC_WooMercadoPago_Credentials::TYPE_ACCESS_CLIENT === $validate_credentials_type ) { + $mp = new MP( $credentials->client_id, $credentials->client_secret ); + $mp->set_payment_class( $payment ); + + if ( ! empty( $payment ) ) { + $payment->sandbox = false; + } + } + + if ( ! isset( $mp ) ) { + return false; + } + + $email = ( 0 !== wp_get_current_user()->ID ) ? wp_get_current_user()->user_email : null; + $mp->set_email( $email ); + + $locale = get_locale(); + $locale = false !== ( strpos( $locale, '_' ) && 5 === strlen( $locale ) ) ? explode( '_', $locale ) : array( + '', + '' + ); + $mp->set_locale( $locale[1] ); + + return $mp; + } + + /** + * + * Init Mercado Pago Class + * + * @return WC_WooMercadoPago_Module|null + * Singleton + */ + public static function init_mercado_pago_class() { + if ( null === self::$instance ) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * + * Define terms and conditions link + * + * @return string + */ + public static function mp_define_terms_and_conditions() { + $links_mp = self::define_link_country(); + $link_prefix_mp = 'https://www.mercadopago.'; + + return array( + 'text_prefix' => __( 'By continuing, you agree to our ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'link_terms_and_conditions' => $link_prefix_mp . $links_mp['sufix_url'] . $links_mp['help'] . $links_mp['term_conditition'], + 'text_suffix' => __( 'Terms and Conditions', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + } + + /** + * Get Common Error Messages function + * + * @param string $key Key. + * + * @return string + */ + public static function get_common_error_messages( $key ) { + if ( 'Invalid payment_method_id' === $key ) { + return __( 'The payment method is not valid or not available.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + } + if ( 'Invalid transaction_amount' === $key ) { + return __( 'The transaction amount cannot be processed by Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . __( 'Possible causes: Currency not supported; Amounts below the minimum or above the maximum allowed.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + } + if ( 'Invalid users involved' === $key ) { + return __( 'The users are not valid.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . __( 'Possible causes: Buyer and seller have the same account in Mercado Pago; The transaction involving production and test users.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + } + if ( 'Unauthorized use of live credentials' === $key ) { + return __( 'Unauthorized use of production credentials.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . __( 'Possible causes: Use permission in use for the credential of the seller.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + } + + 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. + * + * @param string $used_currency Used currency. + * + * @return float float that is the rate of conversion. + */ + public static function get_conversion_rate( $used_currency ) { + $from_currency = get_woocommerce_currency(); + $to_currency = $used_currency; + + return WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->load_ratio( $from_currency, $to_currency ); + } + + /** + * + * Get Common Settings function + * + * @return array + */ + public static function get_common_settings() { + $w = self::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; + } + + /** + * + * Get WooCommerce instance + * Summary: Check if we have valid credentials for v1. + * Description: Check if we have valid credentials. + * + * @return WooCommerce true/false depending on the validation result. + */ + public static function woocommerce_instance() { + if ( function_exists( 'WC' ) ) { + return WC(); + } else { + global $woocommerce; + return $woocommerce; + } + } + + /** + * 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 string. + */ + public static function get_sponsor_id() { + $site_data = self::get_site_data(); + return $site_data['sponsor_id']; + } + + /** + * + * Fix url ampersand + * Fix to URL Problem : #038; replaces & and breaks the navigation. + * + * @param string $link Link. + * + * @return string + */ + public static function fix_url_ampersand( $link ) { + return str_replace( '\/', '/', str_replace( '&', '&', $link ) ); + } + + /** + * Summary: Find template's folder. + * Description: Find template's folder. + * + * @return string string that identifies the path. + */ + public static function get_templates_path() { + return plugin_dir_path( __FILE__ ) . '../../templates/'; + } + + /** + * Is Subscription function + * Check if an order is recurrent. + * + * @param object $items items. + * + * @return boolean + */ + public static function is_subscription( $items ) { + $is_subscription = false; + if ( 1 === count( $items ) ) { + foreach ( $items as $cart_item_key => $cart_item ) { + $is_recurrent = ( is_object( $cart_item ) && 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 ( 'yes' === $is_recurrent ) { + $is_subscription = true; + } + } + } + + return $is_subscription; + } + + /** + * Get Country Name function + * + * @param string $site_id Site id. + * + * @return string + */ + public static function get_country_name( $site_id ) { + switch ( $site_id ) { + case 'mco': + return __( 'Colombia', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'mla': + return __( 'Argentina', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'mlb': + return __( 'Brazil', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'mlc': + return __( 'Chile', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'mlm': + return __( 'Mexico', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'mlu': + return __( 'Uruguay', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'mlv': + return __( 'Venezuela', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'mpe': + return __( 'Peru', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + } + + return ''; + } + + /** + * Get Map function + * + * @param array $selector_id Selector id. + * + * @return array + */ + 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 ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + $status + ); + } + + return $html; + } + + /** + * + * Is_wc_new_version function + * + * @return bool + */ + public static function is_wc_new_version() { + $woo_commerce_version = WC()->version; + if ( $woo_commerce_version <= '4.0.0' ) { + return false; + } + + return true; + } + + /** + * + * Is Mobile function + * + * @return bool + */ + public static function is_mobile() { + return wp_is_mobile(); + } + + /** + * + * Get notification type by the payment class + * + * @return string + */ + public static function get_notification_type( $notification_type ) { + $types['WC_WooMercadoPago_Basic_Gateway'] = 'ipn'; + $types['WC_WooMercadoPago_Credits_Gateway'] = 'ipn'; + $types['WC_WooMercadoPago_Custom_Gateway'] = 'webhooks'; + $types['WC_WooMercadoPago_Pix_Gateway'] = 'webhooks'; + $types['WC_WooMercadoPago_Ticket_Gateway'] = 'webhooks'; + + return $types[ $notification_type ]; + } + + /** + * Load Admin Css + * + * @return void + */ + public function load_admin_css(): void { + if ( is_admin() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) ) ) { + $suffix = $this->get_suffix(); + + wp_enqueue_style( + 'woocommerce-mercadopago-basic-config-styles', + plugins_url( '../assets/css/config_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + + wp_enqueue_style( + 'woocommerce-mercadopago-components', + plugins_url( '../assets/css/components_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + } + } + + /** + * Get Suffix to get minify files + * + * @return string + */ + private function get_suffix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Load global CSS + * + * @return void + */ + public function load_global_css(): void { + $suffix = $this->get_suffix(); + + wp_enqueue_style( + 'woocommerce-mercadopago-global-css', + plugins_url( '../assets/css/global' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + } + + /** + * Load admin scripts + * + * @return void + */ + public function load_admin_scripts(): void { + global $woocommerce; + + $site_id = get_option( '_site_id_v1' ); + + $this->load_notices_scripts($woocommerce, $site_id); + $this->load_melidata_scripts($woocommerce, $site_id); + } + + /** + * Load melidata scripts + * + * @param $woocommerce + * @param $site_id + * + * @return void + */ + public function load_melidata_scripts( $woocommerce, $site_id ): void { + if ( + is_admin() && ( + WC_WooMercadoPago_Helper_Current_Url::validate_url( 'plugins' ) || + WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || + WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) + ) + ) { + wp_enqueue_script( + 'mercadopago_melidata', + plugins_url( '../assets/js/melidata/melidata-client' . $this->get_suffix() . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + + wp_localize_script( + 'mercadopago_melidata', + 'wc_melidata_params', + array( + 'type' => 'seller', + 'site_id' => $site_id ? strtoupper( $site_id ) : 'MLA', + 'location' => '/settings', + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'platform_version' => $woocommerce->version, + ) + ); + } + } + + /** + * Load jaiminho notices scripts + * + * @param $woocommerce + * @param $site_id + * + * @return void + */ + public function load_notices_scripts( $woocommerce, $site_id ): void { + if ( + is_admin() && ( + WC_WooMercadoPago_Helper_Current_Url::validate_url( 'index' ) || + WC_WooMercadoPago_Helper_Current_Url::validate_url( 'plugins' ) || + WC_WooMercadoPago_Helper_Current_Url::validate_page( 'wc-admin' ) || + WC_WooMercadoPago_Helper_Current_Url::validate_page( 'wc-settings' ) || + WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) + ) + ) { + $credentials = ( WC_WooMercadoPago_Options::get_instance() )->get_access_token_and_public_key(); + $public_key = $credentials['credentials_public_key_prod']; + + wp_enqueue_script( + 'mercadopago_notices', + plugins_url( '../assets/js/notices/notices-client' . $this->get_suffix() . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + + wp_localize_script( + 'mercadopago_notices', + 'wc_mercadopago_notices_params', + array( + 'site_id' => $site_id ? strtoupper( $site_id ) : 'MLA', + 'container' => '#wpbody-content', + 'public_key' => $public_key, + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'platform_id' => WC_WooMercadoPago_Constants::PLATAFORM_ID, + 'platform_version' => $woocommerce->version, + ) + ); + } + } + + public function load_before_woocommerce_pay_scripts(): void { + $this->load_buyer_scripts('/woocommerce_pay', null); + } + + public function load_before_checkout_scripts(): void { + $this->load_buyer_scripts('/checkout', null); + } + + public function load_pay_order_scripts(): void { + $this->load_buyer_scripts('/pay_order', null); + } + + public function load_before_thankyou_scripts( $order_id ): void { + $order = wc_get_order( $order_id ); + + $payment_method = $order->get_payment_method(); + $is_mercadopago_payment_method = in_array($payment_method, WC_WooMercadoPago_Constants::GATEWAYS_IDS, true); + + if ( $is_mercadopago_payment_method ) { + $this->load_buyer_scripts('/thankyou', $payment_method); + } + } + + /** + * Load buyer scripts + * + * @return void + */ + public function load_buyer_scripts( $location, $payment_method ): void { + global $woocommerce; + + $site_id = get_option( '_site_id_v1' ); + + wp_enqueue_script( + 'mercadopago_melidata', + plugins_url( '../assets/js/melidata/melidata-client' . $this->get_suffix() . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + + wp_localize_script( + 'mercadopago_melidata', + 'wc_melidata_params', + array( + 'type' => 'buyer', + 'site_id' => $site_id ? strtoupper( $site_id ) : 'MLA', + 'location' => $location, + 'payment_method' => $payment_method, + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'platform_version' => $woocommerce->version, + ) + ); + } + + /** + * + * Filter Payment Method by Shipping + * + * @param array $methods methods. + * + * @return array + */ + public function filter_payment_method_by_shipping( $methods ) { + return $methods; + } + + /** + * + * Enable Payment Notice + * + * @return void + */ + public function enable_payment_notice(): void { + $type = 'notice-warning'; + $message = __( 'Fill in your credentials to enable payment methods.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + echo wp_kses_post( WC_WooMercadoPago_Notices::get_alert_frame( $message, $type )); + } + + /** + * + * Woomercadopago Settings Link add settings link on plugin page. + * Enable Payment Notice + * + * @param array $links links. + * + * @return array + */ + public function woomercadopago_settings_link( $links ) { + $links_mp = self::define_link_country(); + $plugin_links = array(); + $plugin_links[] = '' . __( 'Set plugin', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ''; + $plugin_links[] = '' . __( 'Payment methods', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ''; + $plugin_links[] = '
' . __( 'Plugin manual', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ''; + + return array_merge( $plugin_links, $links ); + } + + /** + * + * Define link country + * + * @return array + */ + public static function define_link_country() { + $sufix_country = 'AR'; + $country = array( + 'AR' => array( // Argentinian. + 'help' => 'ayuda', + 'sufix_url' => 'com.ar/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', + 'site_id_mp' => 'mla', + ), + 'BR' => array( // Brazil. + 'help' => 'ajuda', + 'sufix_url' => 'com.br/', + 'translate' => 'pt', + 'term_conditition' => '/termos-e-politicas_194', + 'site_id_mp' => 'mlb', + ), + 'CL' => array( // Chile. + 'help' => 'ayuda', + 'sufix_url' => 'cl/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', + 'site_id_mp' => 'mlc', + ), + 'CO' => array( // Colombia. + 'help' => 'ayuda', + 'sufix_url' => 'com.co/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', + 'site_id_mp' => 'mco', + ), + 'MX' => array( // Mexico. + 'help' => 'ayuda', + 'sufix_url' => 'com.mx/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', + 'site_id_mp' => 'mlm', + ), + 'PE' => array( // Peru. + 'help' => 'ayuda', + 'sufix_url' => 'com.pe/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', + 'site_id_mp' => 'mpe', + ), + 'UY' => array( // Uruguay. + 'help' => 'ayuda', + 'sufix_url' => 'com.uy/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', + 'site_id_mp' => 'mlu', + ), + ); + + $sufix_country = strtoupper( self::get_woocommerce_default_country() ); + $links_country = array_key_exists( $sufix_country, $country ) ? $country[ $sufix_country ] : $country['AR']; + + return $links_country; + } + + /** + * + * Get Woocommerce default country configured + * + * @return string + */ + public static function get_woocommerce_default_country() { + $wc_country = get_option( 'woocommerce_default_country', '' ); + if ( '' !== $wc_country ) { + $wc_country = strlen( $wc_country ) > 2 ? substr( $wc_country, 0, 2 ) : $wc_country; + } + + return $wc_country; + } + + /** + * Update Credentials for production + */ + public function update_credential_production(): void { + if ( get_option( 'checkbox_checkout_test_mode' ) ) { + return; + } + + $has_a_gateway_in_production = false; + + foreach ( WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS as $gateway ) { + $key = 'woocommerce_' . $gateway::get_id() . '_settings'; + $options = get_option( $key ); + if ( ! empty( $options ) ) { + $old_credential_is_prod = array_key_exists( 'checkout_credential_prod', $options ) && isset( $options['checkout_credential_prod'] ) ? $options['checkout_credential_prod'] : 'no'; + $has_new_key = array_key_exists( 'checkbox_checkout_test_mode', $options ) && isset( $options['checkbox_checkout_test_mode'] ); + $options['checkbox_checkout_test_mode'] = $has_new_key && 'deprecated' === $old_credential_is_prod + ? $options['checkbox_checkout_test_mode'] + : ( 'yes' === $old_credential_is_prod ? 'no' : 'yes' ); + $options['checkout_credential_prod'] = 'deprecated'; + + if ( 'no' === $options['checkbox_checkout_test_mode'] ) { + $has_a_gateway_in_production = true; + } + + /** + * Update if options were changed. + * + * @since 3.0.1 + */ + update_option( $key, apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $gateway::get_id(), $options ) ); + } + } + + $test_mode_value = $has_a_gateway_in_production ? 'no' : 'yes'; + + update_option( 'checkbox_checkout_test_mode', $test_mode_value, true ); + } } diff --git a/includes/module/class-wc-woomercadopago-options.php b/includes/module/class-wc-woomercadopago-options.php index 79b38ea0c..e67e3e045 100644 --- a/includes/module/class-wc-woomercadopago-options.php +++ b/includes/module/class-wc-woomercadopago-options.php @@ -1,226 +1,242 @@ credentials_public_key_prod = get_option( self::CREDENTIALS_PUBLIC_KEY_PROD ); - $this->credentials_public_key_test = get_option( self::CREDENTIALS_PUBLIC_KEY_TEST ); - $this->credentials_access_token_prod = get_option( self::CREDENTIALS_ACCESS_TOKEN_PROD ); - $this->credentials_access_token_test = get_option( self::CREDENTIALS_ACCESS_TOKEN_TEST ); - $this->checkout_country = get_option( self::CHECKOUT_COUNTRY); - $this->store_id = get_option( self::STORE_ID ); - $this->store_name = get_option( self::STORE_NAME); - $this->store_category = get_option( self::STORE_CATEGORY); - $this->integrator_id = get_option( self::INTEGRATOR_ID ); - $this->debug_mode = get_option( self::DEBUG_MODE ); - $this->custom_domain = get_option( self::CUSTOM_DOMAIN ); - $this->custom_domain_options = get_option( self::CUSTOM_DOMAIN_OPTIONS, 'yes' ); - $this->checkbox_checkout_test_mode = get_option( self::CHECKBOX_CHECKOUT_TEST_MODE ); - $this->checkbox_checkout_production_mode = get_option( self::CHECKBOX_CHECKOUT_PRODUCTION_MODE ); - $this->woocommerce_country = get_option( self::WOOCOMMERCE_COUNTRY ); - $this->homolog_validate = get_option( self::HOMOLOG_VALIDATE ); - $this->application_id = get_option( self::APPLICATION_ID ); - $this->site_id = get_option( self::SITE_ID ); - $this->client_id = get_option( self::CLIENT_ID ); - } - - /** - * - * Init Options - */ - public static function get_instance() { - if ( null === self::$instance ) { - self::$instance = new self(); - } - - return self::$instance; - } - - /** - * Get Access token and Public Key - * - * @return array - */ - public function get_access_token_and_public_key() { - return array( - 'credentials_public_key_prod' => $this->credentials_public_key_prod, - 'credentials_public_key_test' => $this->credentials_public_key_test, - 'credentials_access_token_prod' => $this->credentials_access_token_prod, - 'credentials_access_token_test' => $this->credentials_access_token_test, - ); - } - - /** - * Get access token prod - */ - public function get_access_token_prod() { - return $this->credentials_access_token_prod; - } - - /** - * Get access token test - */ - public function get_access_token_test() { - return $this->credentials_access_token_test; - } - - /** - * Get public key prod - */ - public function get_public_key_prod() { - return $this->credentials_public_key_prod; - } - - /** - * Get public key test - */ - public function get_public_key_test() { - return $this->credentials_public_key_test; - } - - /** - * Get option checkout country - */ - public function get_checkout_country() { - return strtolower($this->checkout_country); - } - - /** - * Get option Store Identificator - */ - public function get_store_id() { - return $this->store_id; - } - - /** - * Get option Store Name - */ - public function get_store_name_on_invoice() { - return $this->store_name; - } - - /** - * Get option Store Category - */ - public function get_store_category() { - return $this->store_category; - } - - /** - * Get option Integrator id - */ - public function get_integrator_id() { - return $this->integrator_id; - } - - /** - * Get option Debug Mode - */ - public function get_debug_mode() { - return $this->debug_mode; - } - - /** - * Get option Custom Domain - */ - public function get_custom_domain() { - return $this->custom_domain; - } - - /** - * Get option Custom Domain Options - */ - public function get_custom_domain_options() { - return 'yes' === $this->custom_domain_options; - } - - /** - * Get option Checkbox Test Mode - */ - public function get_checkbox_checkout_test_mode() { - return $this->checkbox_checkout_test_mode; - } - - /** - * Get option Checkbox Production Mode - */ - public function get_checkbox_checkout_production_mode() { - return $this->checkbox_checkout_production_mode; - } - - /** - * Get option woocommerce country - */ - public function get_woocommerce_country() { - return $this->woocommerce_country; - } - - /** - * Get option homolog validate - */ - public function get_homolog_validate() { - return $this->homolog_validate; - } - - /** - * Get option application id - */ - public function get_application_id() { - return $this->application_id; - } - - /** - * Get option site id - */ - public function get_site_id() { - return strtolower($this->site_id); - } - - /** - * Get option client id - */ - public function get_client_id() { - return $this->client_id; - } + public const CREDENTIALS_PUBLIC_KEY_PROD = '_mp_public_key_prod'; + + public const CREDENTIALS_PUBLIC_KEY_TEST = '_mp_public_key_test'; + + public const CREDENTIALS_ACCESS_TOKEN_PROD = '_mp_access_token_prod'; + + public const CREDENTIALS_ACCESS_TOKEN_TEST = '_mp_access_token_test'; + + public const CHECKOUT_COUNTRY = 'checkout_country'; + + public const STORE_ID = '_mp_store_identificator'; + + public const STORE_NAME = 'mp_statement_descriptor'; + + public const STORE_CATEGORY = '_mp_category_id'; + + public const INTEGRATOR_ID = '_mp_integrator_id'; + + public const DEBUG_MODE = '_mp_debug_mode'; + + public const CUSTOM_DOMAIN = '_mp_custom_domain'; + + public const CUSTOM_DOMAIN_OPTIONS = '_mp_custom_domain_options'; + + public const CHECKBOX_CHECKOUT_TEST_MODE = 'checkbox_checkout_test_mode'; + + public const CHECKBOX_CHECKOUT_PRODUCTION_MODE = 'checkbox_checkout_production_mode'; + + public const WOOCOMMERCE_COUNTRY = 'woocommerce_default_country'; + + public const HOMOLOG_VALIDATE = 'homolog_validate'; + + public const APPLICATION_ID = 'mp_application_id'; + + public const SITE_ID = '_site_id_v1'; + + public const CLIENT_ID = '_mp_client_id'; + private $credentials_public_key_prod; + private $credentials_public_key_test; + private $credentials_access_token_prod; + private $credentials_access_token_test; + private $checkout_country; + private $store_id; + private $store_name; + private $store_category; + private $integrator_id; + private $debug_mode; + private $custom_domain; + private $custom_domain_options; + private $checkbox_checkout_test_mode; + private $checkbox_checkout_production_mode; + private $woocommerce_country; + private $homolog_validate; + private $application_id; + private $site_id; + private $client_id; + public static $instance; + + public function __construct() { + $this->credentials_public_key_prod = get_option( self::CREDENTIALS_PUBLIC_KEY_PROD ); + $this->credentials_public_key_test = get_option( self::CREDENTIALS_PUBLIC_KEY_TEST ); + $this->credentials_access_token_prod = get_option( self::CREDENTIALS_ACCESS_TOKEN_PROD ); + $this->credentials_access_token_test = get_option( self::CREDENTIALS_ACCESS_TOKEN_TEST ); + $this->checkout_country = get_option( self::CHECKOUT_COUNTRY); + $this->store_id = get_option( self::STORE_ID ); + $this->store_name = get_option( self::STORE_NAME); + $this->store_category = get_option( self::STORE_CATEGORY); + $this->integrator_id = get_option( self::INTEGRATOR_ID ); + $this->debug_mode = get_option( self::DEBUG_MODE ); + $this->custom_domain = get_option( self::CUSTOM_DOMAIN ); + $this->custom_domain_options = get_option( self::CUSTOM_DOMAIN_OPTIONS, 'yes' ); + $this->checkbox_checkout_test_mode = get_option( self::CHECKBOX_CHECKOUT_TEST_MODE ); + $this->checkbox_checkout_production_mode = get_option( self::CHECKBOX_CHECKOUT_PRODUCTION_MODE ); + $this->woocommerce_country = get_option( self::WOOCOMMERCE_COUNTRY ); + $this->homolog_validate = get_option( self::HOMOLOG_VALIDATE ); + $this->application_id = get_option( self::APPLICATION_ID ); + $this->site_id = get_option( self::SITE_ID ); + $this->client_id = get_option( self::CLIENT_ID ); + } + + /** + * + * Init Options + */ + public static function get_instance() { + if ( null === self::$instance ) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * Get Access token and Public Key + * + * @return array + */ + public function get_access_token_and_public_key() { + return array( + 'credentials_public_key_prod' => $this->credentials_public_key_prod, + 'credentials_public_key_test' => $this->credentials_public_key_test, + 'credentials_access_token_prod' => $this->credentials_access_token_prod, + 'credentials_access_token_test' => $this->credentials_access_token_test, + ); + } + + /** + * Get access token prod + */ + public function get_access_token_prod() { + return $this->credentials_access_token_prod; + } + + /** + * Get access token test + */ + public function get_access_token_test() { + return $this->credentials_access_token_test; + } + + /** + * Get public key prod + */ + public function get_public_key_prod() { + return $this->credentials_public_key_prod; + } + + /** + * Get public key test + */ + public function get_public_key_test() { + return $this->credentials_public_key_test; + } + + /** + * Get option checkout country + */ + public function get_checkout_country() { + return strtolower($this->checkout_country); + } + + /** + * Get option Store Identificator + */ + public function get_store_id() { + return $this->store_id; + } + + /** + * Get option Store Name + */ + public function get_store_name_on_invoice() { + return $this->store_name; + } + + /** + * Get option Store Category + */ + public function get_store_category() { + return $this->store_category; + } + + /** + * Get option Integrator id + */ + public function get_integrator_id() { + return $this->integrator_id; + } + + /** + * Get option Debug Mode + */ + public function get_debug_mode() { + return $this->debug_mode; + } + + /** + * Get option Custom Domain + */ + public function get_custom_domain() { + return $this->custom_domain; + } + + /** + * Get option Custom Domain Options + */ + public function get_custom_domain_options() { + return 'yes' === $this->custom_domain_options; + } + + /** + * Get option Checkbox Test Mode + */ + public function get_checkbox_checkout_test_mode() { + return $this->checkbox_checkout_test_mode; + } + + /** + * Get option Checkbox Production Mode + */ + public function get_checkbox_checkout_production_mode() { + return $this->checkbox_checkout_production_mode; + } + + /** + * Get option woocommerce country + */ + public function get_woocommerce_country() { + return $this->woocommerce_country; + } + + /** + * Get option homolog validate + */ + public function get_homolog_validate() { + return $this->homolog_validate; + } + + /** + * Get option application id + */ + public function get_application_id() { + return $this->application_id; + } + + /** + * Get option site id + */ + public function get_site_id() { + return strtolower($this->site_id); + } + + /** + * Get option client id + */ + public function get_client_id() { + return $this->client_id; + } } diff --git a/includes/module/config/class-wc-woomercadopago-constants.php b/includes/module/config/class-wc-woomercadopago-constants.php index 6bc502695..d053e2f3d 100644 --- a/includes/module/config/class-wc-woomercadopago-constants.php +++ b/includes/module/config/class-wc-woomercadopago-constants.php @@ -1,42 +1,42 @@ get_debug_mode( $payment, $debug_mode ); - if ( ! empty( $payment ) ) { - $this->id = get_class( $payment ); - } - return $this->init_log(); - } + /** + * WC_WooMercadoPago_Log constructor. + * + * @param null $payment . + * @param bool $debug_mode . + */ + public function __construct( $payment = null, $debug_mode = false ) { + $this->get_debug_mode( $payment, $debug_mode ); + if ( ! empty( $payment ) ) { + $this->id = get_class( $payment ); + } + return $this->init_log(); + } - /** - * Get_debug_mode function - * - * @param [type] $payment . - * @param [type] $debug_mode . - * @return void - */ - public function get_debug_mode( $payment, $debug_mode ) { - if ( ! empty( $payment ) ) { - $debug_mode = $payment->debug_mode; - if ( 'no' === $debug_mode ) { - $debug_mode = false; - } else { - $debug_mode = true; - } - } + /** + * Get_debug_mode function + * + * @param [type] $payment . + * @param [type] $debug_mode . + * @return void + */ + public function get_debug_mode( $payment, $debug_mode ): void { + if ( ! empty( $payment ) ) { + $debug_mode = $payment->debug_mode; + if ( 'no' === $debug_mode ) { + $debug_mode = false; + } else { + $debug_mode = true; + } + } - if ( empty( $payment ) && empty( $debug_mode ) ) { - $debug_mode = true; - } + if ( empty( $payment ) && empty( $debug_mode ) ) { + $debug_mode = true; + } - $this->debug_mode = $debug_mode; - } + $this->debug_mode = $debug_mode; + } - /** - * Init_log function - * - * @return WC_Logger|null - */ - public function init_log() { - if ( ! empty( $this->debug_mode ) ) { - if ( class_exists( 'WC_Logger' ) ) { - $this->log = new WC_Logger(); - } else { - $this->log = WC_WooMercadoPago_Module::woocommerce_instance()->logger(); - } - return $this->log; - } - return null; - } + /** + * Init_log function + * + * @return WC_Logger|null + */ + public function init_log() { + if ( ! empty( $this->debug_mode ) ) { + if ( class_exists( 'WC_Logger' ) ) { + $this->log = new WC_Logger(); + } else { + $this->log = WC_WooMercadoPago_Module::woocommerce_instance()->logger(); + } + return $this->log; + } + return null; + } - /** - * Init_mercado_pago_log function - * - * @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->set_id( $id ); - } - return $log; - } + /** + * Init_mercado_pago_log function + * + * @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->set_id( $id ); + } + return $log; + } - /** - * Write_log function - * - * @param [type] $function . - * @param [type] $message . - * @return void - */ - public function write_log( $function, $message ) { - if ( ! empty( $this->debug_mode ) ) { - $this->log->add( $this->id, '[' . $function . ']: ' . $message ); - } - } + /** + * Write_log function + * + * @param [type] $function . + * @param [type] $message . + * @return void + */ + public function write_log( $function, $message ): void { + if ( ! empty( $this->debug_mode ) ) { + $this->log->add( $this->id, '[' . $function . ']: ' . $message ); + } + } - /** - * Set_id function - * - * @param [type] $id . - * @return void - */ - public function set_id( $id ) { - $this->id = $id; - } + /** + * Set_id function + * + * @param [type] $id . + * @return void + */ + public function set_id( $id ): void { + $this->id = $id; + } } diff --git a/includes/module/log/index.php b/includes/module/log/index.php index 258f3fae9..891711d6d 100644 --- a/includes/module/log/index.php +++ b/includes/module/log/index.php @@ -1,12 +1,5 @@ options = $options; - $this->nonce = $nonce; - $this->current_user = $current_user; - } - - /** - * Action to insert Mercado Pago in WooCommerce Menu and Load JavaScript and CSS - */ - public function init() { - $this->load_menu(); - $this->register_endpoints(); - $this->load_scripts_and_styles(); - } - - /** - * Load menu - */ - public function load_menu() { - add_action( 'admin_menu', array( $this, 'register_mercadopago_in_woocommerce_menu' ), self::PRIORITY_ON_MENU ); - } - - /** - * Load Scripts - * - * @return void - */ - public function load_scripts_and_styles() { - add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_scripts' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_style' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'load_research_script' ) ); - } - - /** - * Load CSS - */ - public function load_admin_style() { - if ( is_admin() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) ) ) { - wp_register_style( - 'mercadopago_settings_admin_css', - $this->get_url( '../../../assets/css/mercadopago-settings/mercadopago_settings', '.css' ), - false, - WC_WooMercadoPago_Constants::VERSION - ); - wp_enqueue_style( 'mercadopago_settings_admin_css' ); - } - } - - /** - * Load JavaScripts - */ - public function load_admin_scripts() { - if ( - is_admin() && ( - WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || - WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) - ) - ) { - $script_name = 'mercadopago_settings_javascript'; - - wp_enqueue_script( - $script_name, - $this->get_url( '../../../assets/js/mercadopago-settings/mercadopago_settings', '.js' ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - - wp_localize_script($script_name, $script_name . '_vars', [ - 'nonce' => $this->nonce->generate_nonce(self::SETTINGS_NONCE_ID), - ]); - } - } - - /** - * Load Caronte Research Scripts - */ - public function load_research_script() { - if ( - is_admin() && ( - WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || - WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) - ) - ) { - global $woocommerce; - - wp_enqueue_script( - 'mercadopago_research_javascript', - plugins_url( '../../assets/js/caronte/caronte-client' . $this->get_suffix() . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - - wp_localize_script( - 'mercadopago_research_javascript', - 'wc_mercadopago_params', - array( - 'locale' => get_locale(), - 'site_id' => $this->options->get_site_id() ? strtoupper( $this->options->get_site_id() ) : 'MLA', - 'platform_id' => WC_WooMercadoPago_Constants::PLATAFORM_ID, - 'platform_version' => $woocommerce->version, - 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, - 'public_key_element_id' => 'mp-public-key-prod', - 'reference_element_id' => 'reference' - ) - ); - } - } - - /** - * Register Mercado Pago Option in WooCommerce Menu - */ - public function register_mercadopago_in_woocommerce_menu() { - add_submenu_page( - 'woocommerce', - __( 'Mercado Pago Settings', 'woocommerce-mercadopago' ), - 'Mercado Pago', - 'manage_options', - 'mercadopago-settings', - array( $this, 'mercadopago_submenu_page_callback' ) - ); - } - - /** - * Mercado Pago Template Call - */ - public function mercadopago_submenu_page_callback() { - $categories_store = WC_WooMercadoPago_Module::$categories; - $category_selected = false === $this->options->get_store_category() ? 'others' : $this->options->get_store_category(); - $category_id = false === $this->options->get_store_id() ? 'WC-' : $this->options->get_store_id(); - $store_identificator = false === $this->options->get_store_name_on_invoice() ? 'Mercado Pago' : $this->options->get_store_name_on_invoice(); - $integrator_id = $this->options->get_integrator_id(); - $devsite_links = WC_WooMercadoPago_Helper_Links::get_mp_devsite_links(); - $debug_mode = false === $this->options->get_debug_mode() ? 'no' : $this->options->get_debug_mode(); - $url_ipn = $this->options->get_custom_domain(); - $url_ipn_options_checked = $this->options->get_custom_domain_options() ? 'checked="checked"' : ''; - $links = WC_WooMercadoPago_Helper_Links::woomercadopago_settings_links(); - $checkbox_checkout_test_mode = false === $this->options->get_checkbox_checkout_test_mode() ? 'yes' : $this->options->get_checkbox_checkout_test_mode(); - $options_credentials = $this->options->get_access_token_and_public_key(); - $translation_header = self::mp_translation_admin_header(); - $translation_credential = self::mp_translation_admin_credential(); - $translation_store = self::mp_translation_admin_store(); - $translation_payment = self::mp_translation_admin_payment(); - $translation_test_mode = self::mp_translation_admin_test_mode(); - - include __DIR__ . '/../../../templates/mercadopago-settings/mercadopago-settings.php'; - } - - /** - * Register Mercado Pago Endpoints - */ - public function register_endpoints() { - add_action( 'wp_ajax_mp_get_requirements', array( $this, 'mercadopago_get_requirements' ) ); - add_action( 'wp_ajax_mp_validate_credentials', array( $this, 'mp_validate_credentials' ) ); - add_action( 'wp_ajax_mp_update_store_information', array( $this, 'mp_update_store_info' ) ); - add_action( 'wp_ajax_mp_store_mode', array( $this, 'mp_set_mode' ) ); - add_action( 'wp_ajax_mp_get_payment_properties', array( $this, 'mp_get_payment_class_properties' ) ); - add_action( 'wp_ajax_mp_validate_store_tips', array( $this, 'mp_validate_store_tips' ) ); - add_action( 'wp_ajax_mp_validate_credentials_tips', array( $this, 'mp_validate_credentials_tips' ) ); - add_action( 'wp_ajax_mp_validate_payment_tips', array( $this, 'mp_validate_payment_tips' ) ); - add_action( 'wp_ajax_mp_update_option_credentials', array( $this, 'mp_update_option_credentials' ) ); - } - - /** - * Admin translation header - * - * @return array - */ - public function mp_translation_admin_header() { - return array( - 'title_head_part_one' => __( 'Accept ', 'woocommerce-mercadopago' ), - 'title_head_part_two' => __( 'payments on the spot ', 'woocommerce-mercadopago' ), - 'title_head_part_three' => __( 'with', 'woocommerce-mercadopago' ), - 'title_head_part_four' => __( 'the ', 'woocommerce-mercadopago' ), - 'title_head_part_six' => __( 'security ', 'woocommerce-mercadopago' ), - 'title_head_part_seven' => __( 'from Mercado Pago', 'woocommerce-mercadopago' ), - 'title_requirements' => __( 'Technical requirements', 'woocommerce-mercadopago' ), - 'ssl' => __( 'SSL', 'woocommerce-mercadopago' ), - 'gd_extensions' => __( 'GD Extensions', 'woocommerce-mercadopago' ), - 'curl' => __( 'Curl', 'woocommerce-mercadopago' ), - 'description_ssl' => __( 'Implementation responsible for transmitting data to Mercado Pago in a secure and encrypted way.', 'woocommerce-mercadopago' ), - 'description_gd_extensions' => __( 'These extensions are responsible for the implementation and operation of Pix in your store.', 'woocommerce-mercadopago' ), - 'description_curl' => __( 'It is an extension responsible for making payments via requests from the plugin to Mercado Pago.', 'woocommerce-mercadopago' ), - 'title_installments' => __( 'Collections and installments', 'woocommerce-mercadopago' ), - 'descripition_installments' => __( 'Choose ', 'woocommerce-mercadopago' ), - 'descripition_installments_one' => __( 'when you want to receive the money ', 'woocommerce-mercadopago' ), - 'descripition_installments_two' => __( 'from your sales and if you want to offer ', 'woocommerce-mercadopago' ), - 'descripition_installments_three' => __( 'interest-free installments ', 'woocommerce-mercadopago' ), - 'descripition_installments_four' => __( 'to your clients.', 'woocommerce-mercadopago' ), - 'button_installments' => __( 'Set deadlines and fees', 'woocommerce-mercadopago' ), - 'title_questions' => __( 'Questions? ', 'woocommerce-mercadopago' ), - 'descripition_questions_one' => __( 'Review the step-by-step of ', 'woocommerce-mercadopago' ), - 'descripition_questions_two' => __( 'how to integrate the Mercado Pago Plugin ', 'woocommerce-mercadopago' ), - 'descripition_questions_three' => __( 'on our webiste for developers.', 'woocommerce-mercadopago' ), - 'button_questions' => __( 'Plugin manual', 'woocommerce-mercadopago' ), - ); - } - - /** - * Admin translation credential - * - * @return array - */ - public function mp_translation_admin_credential() { - return array( - 'title_credentials' => __( '1. Integrate your store with Mercado Pago ', 'woocommerce-mercadopago' ), - 'subtitle_credentials_one' => __( 'To enable orders, you must create and activate production credentials in your Mercado Pago Account. ', 'woocommerce-mercadopago' ), - 'subtitle_credentials_two' => __( 'Copy and paste the credentials below.', 'woocommerce-mercadopago' ), - 'button_link_credentials' => __( 'Check credentials', 'woocommerce-mercadopago' ), - 'title_credential_test' => __( 'Test credentials ', 'woocommerce-mercadopago' ), - 'subtitle_credential_test' => __( 'Enable Mercado Pago checkouts for test purchases in the store.', 'woocommerce-mercadopago' ), - 'public_key' => __( 'Public key', 'woocommerce-mercadopago' ), - 'access_token' => __( 'Access Token', 'woocommerce-mercadopago' ), - 'title_credential_prod' => __( 'Production credentials', 'woocommerce-mercadopago' ), - 'subtitle_credential_prod' => __( 'Enable Mercado Pago checkouts to receive real payments in the store.', 'woocommerce-mercadopago' ), - 'placeholder_public_key' => __( 'Paste your Public Key here', 'woocommerce-mercadopago' ), - 'placeholder_access_token' => __( 'Paste your Access Token here', 'woocommerce-mercadopago' ), - 'button_credentials' => __( 'Save and continue', 'woocommerce-mercadopago' ), - ); - } - - /** - * Admin translation store - * - * @return array - */ - public function mp_translation_admin_store() { - return array( - 'title_store' => __( '2. Customize your business', 'woocommerce-mercadopago' ), - 'subtitle_store' => __( 'Fill out the following information to have a better experience and offer more information to your clients', 'woocommerce-mercadopago' ), - 'title_info_store' => __( 'Your store information', 'woocommerce-mercadopago' ), - 'subtitle_name_store' => __( "Name of your store in your client's invoice", 'woocommerce-mercadopago' ), - 'placeholder_name_store' => __( "Eg: Mary's store", 'woocommerce-mercadopago' ), - 'helper_name_store' => __( 'If this field is empty, the purchase will be identified as Mercado Pago.', 'woocommerce-mercadopago' ), - 'subtitle_activities_store' => __( 'Identification in Activities of Mercad Pago', 'woocommerce-mercadopago' ), - 'placeholder_activities_store' => __( 'Eg: Marystore', 'woocommerce-mercadopago' ), - 'helper_activities_store' => __( 'In Activities, you will view this term before the order number', 'woocommerce-mercadopago' ), - 'subtitle_category_store' => __( 'Store category', 'woocommerce-mercadopago' ), - 'placeholder_category_store' => __( 'Select', 'woocommerce-mercadopago' ), - 'helper_category_store' => __( 'Select ”Other” if you do not find the appropriate category.', 'woocommerce-mercadopago' ), - 'title_advanced_store' => __( 'Advanced integration options (optional)', 'woocommerce-mercadopago' ), - 'subtitle_advanced_store' => __( 'For further integration of your store with Mercado Pago (IPN, Certified Partners, Debug Mode)', 'woocommerce-mercadopago' ), - 'accordion_advanced_store' => __( 'View advanced options', 'woocommerce-mercadopago' ), - 'subtitle_url' => __( 'URL for IPN ', 'woocommerce-mercadopago' ), - 'placeholder_url' => __( 'Eg: https://examples.com/my-custom-ipn-url', 'woocommerce-mercadopago' ), - 'helper_url' => __( 'Add the URL to receive payments notifications. Find out more information in the ', 'woocommerce-mercadopago' ), - 'helper_url_link' => __( 'guides.', 'woocommerce-mercadopago' ), - 'options_url' => __( 'Add plugin default params', 'woocommerce-mercadopago' ), - 'subtitle_integrator' => __( 'integrator_id', 'woocommerce-mercadopago' ), - 'placeholder_integrator' => __( 'Eg: 14987126498', 'woocommerce-mercadopago' ), - 'helper_integrator' => __( 'If you are a Mercado Pago Certified Partner, make sure to add your integrator_id. If you do not have the code, please ', 'woocommerce-mercadopago' ), - 'helper_integrator_link' => __( 'request it now. ', 'woocommerce-mercadopago' ), - 'title_debug' => __( 'Debug and Log Mode', 'woocommerce-mercadopago' ), - 'subtitle_debug' => __( "We record your store's actions in order to provide a better assistance.", 'woocommerce-mercadopago' ), - 'button_store' => __( 'Save and continue', 'woocommerce-mercadopago' ), - ); - } - - /** - * Admin translation payment - * - * @return array - */ - public function mp_translation_admin_payment() { - return array( - 'title_payments' => __( '3. Set payment methods', 'woocommerce-mercadopago' ), - 'subtitle_payments' => __( 'To view more options, please select a payment method below', 'woocommerce-mercadopago' ), - 'settings_payment' => __( 'Settings', 'woocommerce-mercadopago' ), - 'button_payment' => __( 'Continue', 'woocommerce-mercadopago' ), - ); - } - - /** - * Admin translation test mode - * - * @return array - */ - public function mp_translation_admin_test_mode() { - return array( - 'title_test_mode' => __( '4. Test your store before you sell', 'woocommerce-mercadopago' ), - 'subtitle_test_mode' => __( 'Test the experience in Test Mode and then enable the Sale Mode (Production) to sell.', 'woocommerce-mercadopago' ), - 'title_mode' => __( 'Choose how you want to operate your store:', 'woocommerce-mercadopago' ), - 'title_test' => __( 'Test Mode', 'woocommerce-mercadopago' ), - 'subtitle_test' => __( 'Mercado Pago Checkouts disabled for real collections. ', 'woocommerce-mercadopago' ), - 'subtitle_test_link' => __( 'Test Mode rules.', 'woocommerce-mercadopago' ), - 'title_prod' => __( 'Sale Mode (Production)', 'woocommerce-mercadopago' ), - 'subtitle_prod' => __( 'Mercado Pago Checkouts enabled for real collections.', 'woocommerce-mercadopago' ), - 'title_message_prod' => __( 'Mercado Pago payment methods in Production Mode', 'woocommerce-mercadopago' ), - 'subtitle_message_prod' => __( 'The clients can make real purchases in your store.', 'woocommerce-mercadopago' ), - 'title_message_test' => __( 'Mercado Pago payment methods in Test Mode', 'woocommerce-mercadopago' ), - 'subtitle_test1' => __( 'Create your ', 'woocommerce-mercadopago' ), - 'subtitle_link_test1' => __( 'test user ', 'woocommerce-mercadopago' ), - 'subtitle_message_test1' => __( '(Optional. Can be used in Production Mode and Test Mode, to test payments).', 'woocommerce-mercadopago' ), - 'subtitle_link_test2' => __( 'Use our test cards, ', 'woocommerce-mercadopago' ), - 'subtitle_test2' => __( 'never use real cards. ', 'woocommerce-mercadopago' ), - 'subtitle_link_test3' => __( 'Visit your store ', 'woocommerce-mercadopago' ), - 'subtitle_test3' => __( 'to test purchases', 'woocommerce-mercadopago' ), - 'button_mode' => __( 'Save changes', 'woocommerce-mercadopago' ), - 'badge_test' => __( 'Store under test', 'woocommerce-mercadopago' ), - 'badge_mode' => __( 'Store in sale mode (Production)', 'woocommerce-mercadopago' ), - 'title_alert_test' => __( 'Enter test credentials', 'woocommerce-mercadopago' ), - 'subtitle_alert_test' => __( 'To enable test mode, ', 'woocommerce-mercadopago' ), - 'title_alert_test_link' => __( 'copy your test credentials ', 'woocommerce-mercadopago' ), - 'title_alert_tes_one' => __( 'and paste them above in section 1 of this page.', 'woocommerce-mercadopago' ) - ); - } - - /** - * Requirements - */ - public function mercadopago_get_requirements() { - $this->validate_ajax_nonce(); - - $hasCurl = in_array( 'curl', get_loaded_extensions(), true ); - $hasGD = in_array( 'gd', get_loaded_extensions(), true ); - $hasSSL = is_ssl(); - - wp_send_json_success([ - 'ssl' => $hasSSL, - 'gd_ext' => $hasGD, - 'curl_ext' => $hasCurl - ]); - } - - /** - * Validate credentials Ajax - */ - public function mp_validate_credentials() { - try { - $this->validate_ajax_nonce(); - - $access_token = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'access_token' ); - $public_key = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'public_key' ); - $is_test = ( WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'is_test' ) === 'true' ); - - $mp = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - - if ( $access_token ) { - $validate_access_token = $mp->get_credentials_wrapper( $access_token, null ); - if ( ! $validate_access_token || $validate_access_token['is_test'] !== $is_test ) { - wp_send_json_error( __( 'Invalid Access Token', 'woocommerce-mercadopago' ) ); - } - wp_send_json_success( __( 'Valid Access Token', 'woocommerce-mercadopago' ) ); - } - - if ( $public_key ) { - $validate_public_key = $mp->get_credentials_wrapper( null, $public_key ); - if ( ! $validate_public_key || $validate_public_key['is_test'] !== $is_test ) { - wp_send_json_error( __( 'Invalid Public Key', 'woocommerce-mercadopago' ) ); - } - wp_send_json_success( __( 'Valid Public Key', 'woocommerce-mercadopago' ) ); - } - - throw new Exception( __( 'Credentials must be valid', 'woocommerce-mercadopago' ) ); - } catch ( Exception $e ) { - $response = [ - 'message' => $e->getMessage() - ]; - - wp_send_json_error( $response ); - } - } - - /** - * Update option Credentials - */ - public function mp_update_option_credentials() { - try { - $this->validate_ajax_nonce(); - - $public_key_test = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'public_key_test' ); - $access_token_test = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'access_token_test' ); - $public_key_prod = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'public_key_prod' ); - $access_token_prod = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'access_token_prod' ); - - $mp = WC_WooMercadoPago_Module::get_mp_instance_singleton(); - - $validate_public_key_test = $mp->get_credentials_wrapper( null, $public_key_test ); - $validate_access_token_test = $mp->get_credentials_wrapper( $access_token_test , null ); - $validate_public_key_prod = $mp->get_credentials_wrapper( null, $public_key_prod ); - $validate_access_token_prod = $mp->get_credentials_wrapper( $access_token_prod , null ); - $me = $mp->get_me( $access_token_prod ); - - if ( $validate_public_key_prod && $validate_access_token_prod && false === $validate_public_key_prod['is_test'] && false === $validate_access_token_prod['is_test'] ) { - update_option( WC_WooMercadoPago_Options::CREDENTIALS_ACCESS_TOKEN_PROD, $access_token_prod, true ); - update_option( WC_WooMercadoPago_Options::CREDENTIALS_PUBLIC_KEY_PROD, $public_key_prod, true ); - update_option( WC_WooMercadoPago_Options::CHECKOUT_COUNTRY, $me['site_id'], true ); - update_option( WC_WooMercadoPago_Options::SITE_ID, $me['site_id'], true ); - if ( ( empty( $public_key_test ) && empty( $access_token_test ) ) - || ( true === $validate_public_key_test['is_test'] && true === $validate_access_token_test['is_test'] ) ) { - update_option( WC_WooMercadoPago_Options::CREDENTIALS_PUBLIC_KEY_TEST, $public_key_test, true ); - update_option( WC_WooMercadoPago_Options::CREDENTIALS_ACCESS_TOKEN_TEST, $access_token_test, true ); - WC_WooMercadoPago_Credentials::mercadopago_payment_update(); - if ( empty( $public_key_test ) && empty( $access_token_test ) && ( 'yes' === get_option( 'checkbox_checkout_test_mode', '' ) ) ) { - $response = [ - 'message' => __( 'Your store has exited Test Mode and is making real sales in Production Mode.', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'To test the store, re-enter both test credentials.', 'woocommerce-mercadopago' ), - 'type' => 'alert', - 'test_mode' => 'no' - ]; - update_option( 'checkbox_checkout_test_mode', 'no' ); - throw new Exception(); - } else { - wp_send_json_success( __( 'Credentials were updated', 'woocommerce-mercadopago' ) ); - } - } - } - $links = WC_WooMercadoPago_Helper_Links::woomercadopago_settings_links(); - $response = [ - 'message' => __( 'Invalid credentials', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'See our manual to learn ', 'woocommerce-mercadopago' ), - 'subtitle_one' => __( 'how to enter the credentials the right way.', 'woocommerce-mercadopago' ), - 'subtitle_one_link' => $links['link_credentials'], - 'type' => 'error', - 'test_mode' => get_option( 'checkbox_checkout_test_mode' ) - ]; - - throw new Exception(); - } catch ( Exception $e ) { - wp_send_json_error( $response ); - } - } - - /** - * Get URL with path - * - * @param $path - * @param $extension - * - * @return string - */ - public function get_url( $path, $extension ) { - return sprintf( - '%s%s%s%s', - plugin_dir_url( __FILE__ ), - $path, - $this->get_suffix(), - $extension - ); - } - - /** - * Get suffix to static files - * - * @return string - */ - public function get_suffix() { - return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - } - - /** - * Validate store info Ajax - */ - public function mp_update_store_info() { - try { - $this->validate_ajax_nonce(); - - $store_info = array( - 'mp_statement_descriptor' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_identificator' ), - '_mp_category_id' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_categories' ), - '_mp_store_identificator' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_category_id' ), - '_mp_custom_domain' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_url_ipn' ), - '_mp_custom_domain_options' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_url_ipn_options' ), - '_mp_integrator_id' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_integrator_id' ), - '_mp_debug_mode' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_debug_mode' ), - ); - - foreach ( $store_info as $key => $value ) { - update_option( $key, $value, true ); - } - - wp_send_json_success( __( 'Store information is valid', 'woocommerce-mercadopago' ) ); - - } catch ( Exception $e ) { - $response = [ - 'message' => $e->getMessage() - ]; - - wp_send_json_error( $response ); - } - } - - /** - * Switch store mode - */ - public function mp_set_mode() { - try { - $this->validate_ajax_nonce(); - - $checkout_test_mode = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'input_mode_value' ); - - $verify_alert_test_mode = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'input_verify_alert_test_mode' ); - $without_test_credentials = ( ( '' === get_option( WC_WooMercadoPago_Options::CREDENTIALS_PUBLIC_KEY_TEST, '' ) || '' === get_option( WC_WooMercadoPago_Options::CREDENTIALS_ACCESS_TOKEN_TEST, '' ) ) ); - - if ( 'yes' === $verify_alert_test_mode || ( 'yes' === $checkout_test_mode && $without_test_credentials ) ) { - throw new Exception( __( 'Invalid credentials for test mode', 'woocommerce-mercadopago' ) ); - } else { - $this->update_credential_production(); - update_option( 'checkbox_checkout_test_mode', $checkout_test_mode, true ); - - $response = 'yes' === $checkout_test_mode ? - __( 'Mercado Pago\'s Payment Methods in Test Mode', 'woocommerce-mercadopago' ) : - __( 'Mercado Pago\'s Payment Methods in Production Mode', 'woocommerce-mercadopago' ); - - wp_send_json_success( $response ); - } - } catch ( Exception $e ) { - $response = [ - 'message' => $e->getMessage() - ]; - - wp_send_json_error( $response ); - } - } - - /** - * Update Credentials for production - */ - public function update_credential_production() { - $this->validate_ajax_nonce(); - - foreach ( WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS as $gateway ) { - $key = 'woocommerce_' . $gateway::get_id() . '_settings'; - $options = get_option( $key ); - if ( ! empty( $options ) ) { - $old_credential_is_prod = array_key_exists( 'checkout_credential_prod', $options ) && isset( $options['checkout_credential_prod'] ) ? $options['checkout_credential_prod'] : 'no'; - $has_new_key = array_key_exists( 'checkbox_checkout_test_mode', $options ) && isset( $options['checkbox_checkout_test_mode'] ); - $options['checkbox_checkout_test_mode'] = $has_new_key && 'deprecated' === $old_credential_is_prod - ? $options['checkbox_checkout_test_mode'] - : ( 'yes' === $old_credential_is_prod ? 'no' : 'yes' ); - $options['checkout_credential_prod'] = 'deprecated'; - - /** - * Update if options were changed. - * - * @since 3.0.1 - */ - update_option( $key, apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $gateway::get_id(), $options ) ); - } - } - } - - /** - * Get payment class properties - */ - public function mp_get_payment_class_properties() { - try { - $this->validate_ajax_nonce(); - - $payments_gateways = WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS; - $payment_gateway_properties = array(); - $payment_methods = ( new WC_WooMercadoPago_Configs() )->get_available_payment_methods(); - - foreach ( $payments_gateways as $payment_gateway ) { - if ( ! in_array( $payment_gateway, $payment_methods, true ) ) { - continue; - } - - $gateway = new $payment_gateway(); - - $additional_info = [ - 'woo-mercado-pago-basic' => [ 'icon' => 'mp-settings-icon-mp' ], - 'woo-mercado-pago-credits' => [ 'icon' => 'mp-settings-icon-mp' ], - 'woo-mercado-pago-custom' => [ 'icon' => 'mp-settings-icon-card' ], - 'woo-mercado-pago-ticket' => [ 'icon' => 'mp-settings-icon-code' ], - 'woo-mercado-pago-pix' => [ 'icon' => 'mp-settings-icon-pix' ], - ]; - - $payment_gateway_properties[] = array( - 'id' => $gateway->id, - 'title_gateway' => $gateway->title_gateway, - 'description' => $gateway->description, - 'title' => $gateway->title, - 'enabled' => $gateway->settings['enabled'], - 'icon' => $additional_info[ $gateway->id ]['icon'], - 'link' => admin_url( 'admin.php?page=wc-settings&tab=checkout§ion=' ) . $gateway->id, - 'badge_translator' => [ - 'yes' => __( 'Enabled', 'woocommerce-mercadopago' ), - 'no' => __( 'Disabled', 'woocommerce-mercadopago' ) - ], - ); - } - - wp_send_json_success( $payment_gateway_properties ); - } catch ( Exception $e ) { - $response = [ - 'message' => $e->getMessage() - ]; - - wp_send_json_error( $response ); - } - } - - /** - * Validate credentials tips - */ - public function mp_validate_credentials_tips() { - try { - $this->validate_ajax_nonce(); - - $public_key_test = $this->options->get_public_key_test(); - $access_token_test = $this->options->get_access_token_test(); - $public_key_prod = $this->options->get_public_key_prod(); - $access_token_prod = $this->options->get_access_token_prod(); - - if ( ! ( $public_key_test xor $access_token_test ) && $public_key_prod && $access_token_prod ) { - wp_send_json_success( __( 'Valid Credentials', 'woocommerce-mercadopago' ) ); - } - - throw new Exception( __( 'Credentials couldn\'t be validated', 'woocommerce-mercadopago' ) ); - } catch ( Exception $e ) { - $response = [ - 'message' => $e->getMessage() - ]; - - wp_send_json_error( $response ); - } - } - - - /** - * Validate store tips - */ - public function mp_validate_store_tips() { - try { - $this->validate_ajax_nonce(); - - $statement_descriptor = $this->options->get_store_name_on_invoice(); - $category_id = $this->options->get_store_category(); - $identificator = $this->options->get_store_id(); - - if ( $statement_descriptor && $category_id && $identificator ) { - wp_send_json_success( __( 'Store business fields are valid', 'woocommerce-mercadopago' ) ); - } - - throw new Exception( __( 'Store business fields couldn\'t be validated', 'woocommerce-mercadopago' ) ); - } catch ( Exception $e ) { - $response = [ - 'message' => $e->getMessage() - ]; - - wp_send_json_error( $response ); - } - } - - /** - * Validate field payment - */ - public function mp_validate_payment_tips() { - try { - $this->validate_ajax_nonce(); - - $payments_gateways = WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS; - - foreach ( $payments_gateways as $payment_gateway ) { - $gateway = new $payment_gateway(); - - if ( 'yes' === $gateway->settings['enabled'] ) { - wp_send_json_success( __( 'At least one paymet method is enabled', 'woocommerce-mercadopago' ) ); - } - } - throw new Exception( __( 'No payment method enabled', 'woocommerce-mercadopago' ) ); - } catch ( Exception $e ) { - $response = [ - 'message' => $e->getMessage() - ]; - - wp_send_json_error( $response ); - } - } - - /** - * Validate ajax nonce - * - * @return void - */ - private function validate_ajax_nonce() { - $this->current_user->validate_user_needed_permissions(); - $this->nonce->validate_nonce( - self::SETTINGS_NONCE_ID, - WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'nonce' ) - ); - } + public const PRIORITY_ON_MENU = 90; + + public const SETTINGS_NONCE_ID = 'mp_settings_nonce'; + protected $options; + protected $nonce; + protected $current_user; + + /** + * WC_WooMercadoPago_MercadoPago_Settings constructor + * + * @param WC_WooMercadoPago_Options $options + * @param WC_WooMercadoPago_Helper_Nonce $nonce + * @param WC_WooMercadoPago_Helper_Current_User $current_user + */ + public function __construct( + WC_WooMercadoPago_Options $options, + WC_WooMercadoPago_Helper_Nonce $nonce, + WC_WooMercadoPago_Helper_Current_User $current_user + ) { + $this->options = $options; + $this->nonce = $nonce; + $this->current_user = $current_user; + } + + /** + * Action to insert Mercado Pago in WooCommerce Menu and Load JavaScript and CSS + */ + public function init(): void { + $this->load_menu(); + $this->register_endpoints(); + $this->load_scripts_and_styles(); + } + + /** + * Load menu + */ + public function load_menu(): void { + add_action( 'admin_menu', array($this, 'register_mercadopago_in_woocommerce_menu'), self::PRIORITY_ON_MENU ); + } + + /** + * Load Scripts + * + * @return void + */ + public function load_scripts_and_styles(): void { + add_action( 'admin_enqueue_scripts', array($this, 'load_admin_scripts') ); + add_action( 'admin_enqueue_scripts', array($this, 'load_admin_style') ); + add_action( 'admin_enqueue_scripts', array($this, 'load_research_script') ); + } + + /** + * Load CSS + */ + public function load_admin_style(): void { + if ( is_admin() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) ) ) { + wp_register_style( + 'mercadopago_settings_admin_css', + $this->get_url( '../../../assets/css/mercadopago-settings/mercadopago_settings', '.css' ), + false, + WC_WooMercadoPago_Constants::VERSION + ); + wp_enqueue_style( 'mercadopago_settings_admin_css' ); + } + } + + /** + * Load JavaScripts + */ + public function load_admin_scripts(): void { + if ( + is_admin() && ( + WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || + WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) + ) + ) { + $script_name = 'mercadopago_settings_javascript'; + + wp_enqueue_script( + $script_name, + $this->get_url( '../../../assets/js/mercadopago-settings/mercadopago_settings', '.js' ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + + wp_localize_script($script_name, $script_name . '_vars', array( + 'nonce' => $this->nonce->generate_nonce(self::SETTINGS_NONCE_ID), + )); + } + } + + /** + * Load Caronte Research Scripts + */ + public function load_research_script(): void { + if ( + is_admin() && ( + WC_WooMercadoPago_Helper_Current_Url::validate_page( 'mercadopago-settings' ) || + WC_WooMercadoPago_Helper_Current_Url::validate_section( 'woo-mercado-pago' ) + ) + ) { + global $woocommerce; + + wp_enqueue_script( + 'mercadopago_research_javascript', + plugins_url( '../../assets/js/caronte/caronte-client' . $this->get_suffix() . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + + wp_localize_script( + 'mercadopago_research_javascript', + 'wc_mercadopago_params', + array( + 'locale' => get_locale(), + 'site_id' => $this->options->get_site_id() ? strtoupper( $this->options->get_site_id() ) : 'MLA', + 'platform_id' => WC_WooMercadoPago_Constants::PLATAFORM_ID, + 'platform_version' => $woocommerce->version, + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'public_key_element_id' => 'mp-public-key-prod', + 'reference_element_id' => 'reference' + ) + ); + } + } + + /** + * Register Mercado Pago Option in WooCommerce Menu + */ + public function register_mercadopago_in_woocommerce_menu(): void { + add_submenu_page( + 'woocommerce', + __( 'Mercado Pago Settings', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'Mercado Pago', + 'manage_options', + 'mercadopago-settings', + array($this, 'mercadopago_submenu_page_callback') + ); + } + + /** + * Mercado Pago Template Call + */ + public function mercadopago_submenu_page_callback(): void { + $categories_store = WC_WooMercadoPago_Module::$categories; + $category_selected = false === $this->options->get_store_category() ? 'others' : $this->options->get_store_category(); + $category_id = false === $this->options->get_store_id() ? 'WC-' : $this->options->get_store_id(); + $store_identificator = false === $this->options->get_store_name_on_invoice() ? 'Mercado Pago' : $this->options->get_store_name_on_invoice(); + $integrator_id = $this->options->get_integrator_id(); + $devsite_links = WC_WooMercadoPago_Helper_Links::get_mp_devsite_links(); + $debug_mode = false === $this->options->get_debug_mode() ? 'no' : $this->options->get_debug_mode(); + $url_ipn = $this->options->get_custom_domain(); + $url_ipn_options_checked = $this->options->get_custom_domain_options() ? 'checked="checked"' : ''; + $links = WC_WooMercadoPago_Helper_Links::woomercadopago_settings_links(); + $checkbox_checkout_test_mode = false === $this->options->get_checkbox_checkout_test_mode() ? 'yes' : $this->options->get_checkbox_checkout_test_mode(); + $options_credentials = $this->options->get_access_token_and_public_key(); + $translation_header = self::mp_translation_admin_header(); + $translation_credential = self::mp_translation_admin_credential(); + $translation_store = self::mp_translation_admin_store(); + $translation_payment = self::mp_translation_admin_payment(); + $translation_test_mode = self::mp_translation_admin_test_mode(); + + include __DIR__ . '/../../../templates/mercadopago-settings/mercadopago-settings.php'; + } + + /** + * Register Mercado Pago Endpoints + */ + public function register_endpoints(): void { + add_action( 'wp_ajax_mp_get_requirements', array($this, 'mercadopago_get_requirements') ); + add_action( 'wp_ajax_mp_validate_credentials', array($this, 'mp_validate_credentials') ); + add_action( 'wp_ajax_mp_update_store_information', array($this, 'mp_update_store_info') ); + add_action( 'wp_ajax_mp_store_mode', array($this, 'mp_set_mode') ); + add_action( 'wp_ajax_mp_get_payment_properties', array($this, 'mp_get_payment_class_properties') ); + add_action( 'wp_ajax_mp_validate_store_tips', array($this, 'mp_validate_store_tips') ); + add_action( 'wp_ajax_mp_validate_credentials_tips', array($this, 'mp_validate_credentials_tips') ); + add_action( 'wp_ajax_mp_validate_payment_tips', array($this, 'mp_validate_payment_tips') ); + add_action( 'wp_ajax_mp_update_option_credentials', array($this, 'mp_update_option_credentials') ); + } + + /** + * Admin translation header + * + * @return array + */ + public function mp_translation_admin_header() { + return array( + 'title_head_part_one' => __( 'Accept ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_head_part_two' => __( 'payments on the spot ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_head_part_three' => __( 'with', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_head_part_four' => __( 'the ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_head_part_six' => __( 'security ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_head_part_seven' => __( 'from Mercado Pago', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_requirements' => __( 'Technical requirements', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'ssl' => __( 'SSL', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'gd_extensions' => __( 'GD Extensions', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'curl' => __( 'Curl', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description_ssl' => __( 'Implementation responsible for transmitting data to Mercado Pago in a secure and encrypted way.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description_gd_extensions' => __( 'These extensions are responsible for the implementation and operation of Pix in your store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description_curl' => __( 'It is an extension responsible for making payments via requests from the plugin to Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_installments' => __( 'Collections and installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descripition_installments' => __( 'Choose ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descripition_installments_one' => __( 'when you want to receive the money ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descripition_installments_two' => __( 'from your sales and if you want to offer ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descripition_installments_three' => __( 'interest-free installments ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descripition_installments_four' => __( 'to your clients.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_installments' => __( 'Set deadlines and fees', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_questions' => __( 'Questions? ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descripition_questions_one' => __( 'Review the step-by-step of ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descripition_questions_two' => __( 'how to integrate the Mercado Pago Plugin ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descripition_questions_three' => __( 'on our webiste for developers.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_questions' => __( 'Plugin manual', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + } + + /** + * Admin translation credential + * + * @return array + */ + public function mp_translation_admin_credential() { + return array( + 'title_credentials' => __( '1. Integrate your store with Mercado Pago ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_credentials_one' => __( 'To enable orders, you must create and activate production credentials in your Mercado Pago Account. ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_credentials_two' => __( 'Copy and paste the credentials below.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_link_credentials' => __( 'Check credentials', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_credential_test' => __( 'Test credentials ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_credential_test' => __( 'Enable Mercado Pago checkouts for test purchases in the store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'public_key' => __( 'Public key', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'access_token' => __( 'Access Token', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_credential_prod' => __( 'Production credentials', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_credential_prod' => __( 'Enable Mercado Pago checkouts to receive real payments in the store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'placeholder_public_key' => __( 'Paste your Public Key here', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'placeholder_access_token' => __( 'Paste your Access Token here', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_credentials' => __( 'Save and continue', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + } + + /** + * Admin translation store + * + * @return array + */ + public function mp_translation_admin_store() { + return array( + 'title_store' => __( '2. Customize your business', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_store' => __( 'Fill out the following information to have a better experience and offer more information to your clients', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_info_store' => __( 'Your store information', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_name_store' => __( "Name of your store in your client's invoice", LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'placeholder_name_store' => __( "Eg: Mary's store", LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'helper_name_store' => __( 'If this field is empty, the purchase will be identified as Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_activities_store' => __( 'Identification in Activities of Mercad Pago', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'placeholder_activities_store' => __( 'Eg: Marystore', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'helper_activities_store' => __( 'In Activities, you will view this term before the order number', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_category_store' => __( 'Store category', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'placeholder_category_store' => __( 'Select', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'helper_category_store' => __( 'Select ”Other” if you do not find the appropriate category.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_advanced_store' => __( 'Advanced integration options (optional)', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_advanced_store' => __( 'For further integration of your store with Mercado Pago (IPN, Certified Partners, Debug Mode)', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'accordion_advanced_store' => __( 'View advanced options', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_url' => __( 'URL for IPN ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'placeholder_url' => __( 'Eg: https://examples.com/my-custom-ipn-url', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'helper_url' => __( 'Add the URL to receive payments notifications. Find out more information in the ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'helper_url_link' => __( 'guides.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'options_url' => __( 'Add plugin default params', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_integrator' => __( 'integrator_id', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'placeholder_integrator' => __( 'Eg: 14987126498', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'helper_integrator' => __( 'If you are a Mercado Pago Certified Partner, make sure to add your integrator_id. If you do not have the code, please ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'helper_integrator_link' => __( 'request it now. ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_debug' => __( 'Debug and Log Mode', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_debug' => __( "We record your store's actions in order to provide a better assistance.", LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_store' => __( 'Save and continue', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + } + + /** + * Admin translation payment + * + * @return array + */ + public function mp_translation_admin_payment() { + return array( + 'title_payments' => __( '3. Set payment methods', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_payments' => __( 'To view more options, please select a payment method below', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'settings_payment' => __( 'Settings', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_payment' => __( 'Continue', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + } + + /** + * Admin translation test mode + * + * @return array + */ + public function mp_translation_admin_test_mode() { + return array( + 'title_test_mode' => __( '4. Test your store before you sell', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_test_mode' => __( 'Test the experience in Test Mode and then enable the Sale Mode (Production) to sell.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_mode' => __( 'Choose how you want to operate your store:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_test' => __( 'Test Mode', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_test' => __( 'Mercado Pago Checkouts disabled for real collections. ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_test_link' => __( 'Test Mode rules.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_prod' => __( 'Sale Mode (Production)', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_prod' => __( 'Mercado Pago Checkouts enabled for real collections.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_message_prod' => __( 'Mercado Pago payment methods in Production Mode', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_message_prod' => __( 'The clients can make real purchases in your store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_message_test' => __( 'Mercado Pago payment methods in Test Mode', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_test1' => __( 'Create your ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_link_test1' => __( 'test user ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_message_test1' => __( '(Optional. Can be used in Production Mode and Test Mode, to test payments).', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_link_test2' => __( 'Use our test cards, ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_test2' => __( 'never use real cards. ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_link_test3' => __( 'Visit your store ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_test3' => __( 'to test purchases', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_mode' => __( 'Save changes', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'badge_test' => __( 'Store under test', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'badge_mode' => __( 'Store in sale mode (Production)', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_alert_test' => __( 'Enter test credentials', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_alert_test' => __( 'To enable test mode, ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_alert_test_link' => __( 'copy your test credentials ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_alert_tes_one' => __( 'and paste them above in section 1 of this page.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } + + /** + * Requirements + */ + public function mercadopago_get_requirements(): void { + $this->validate_ajax_nonce(); + + $hasCurl = in_array( 'curl', get_loaded_extensions(), true ); + $hasGD = in_array( 'gd', get_loaded_extensions(), true ); + $hasSSL = is_ssl(); + + wp_send_json_success(array( + 'ssl' => $hasSSL, + 'gd_ext' => $hasGD, + 'curl_ext' => $hasCurl + )); + } + + /** + * Validate credentials Ajax + */ + public function mp_validate_credentials(): void { + try { + $this->validate_ajax_nonce(); + + $access_token = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'access_token' ); + $public_key = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'public_key' ); + $is_test = ( WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'is_test' ) === 'true' ); + + $mp = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + + if ( $access_token ) { + $validate_access_token = $mp->get_credentials_wrapper( $access_token, null ); + if ( ! $validate_access_token || $validate_access_token['is_test'] !== $is_test ) { + wp_send_json_error( __( 'Invalid Access Token', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + wp_send_json_success( __( 'Valid Access Token', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + + if ( $public_key ) { + $validate_public_key = $mp->get_credentials_wrapper( null, $public_key ); + if ( ! $validate_public_key || $validate_public_key['is_test'] !== $is_test ) { + wp_send_json_error( __( 'Invalid Public Key', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + wp_send_json_success( __( 'Valid Public Key', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + + throw new Exception( __( 'Credentials must be valid', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } catch ( Exception $e ) { + $response = array( + 'message' => $e->getMessage() + ); + + wp_send_json_error( $response ); + } + } + + /** + * Update option Credentials + */ + public function mp_update_option_credentials(): void { + try { + $this->validate_ajax_nonce(); + + $public_key_test = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'public_key_test' ); + $access_token_test = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'access_token_test' ); + $public_key_prod = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'public_key_prod' ); + $access_token_prod = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'access_token_prod' ); + + $mp = WC_WooMercadoPago_Module::get_mp_instance_singleton(); + + $validate_public_key_test = $mp->get_credentials_wrapper( null, $public_key_test ); + $validate_access_token_test = $mp->get_credentials_wrapper( $access_token_test, null ); + $validate_public_key_prod = $mp->get_credentials_wrapper( null, $public_key_prod ); + $validate_access_token_prod = $mp->get_credentials_wrapper( $access_token_prod, null ); + $me = $mp->get_me( $access_token_prod ); + + if ( $validate_public_key_prod && $validate_access_token_prod && false === $validate_public_key_prod['is_test'] && false === $validate_access_token_prod['is_test'] ) { + update_option( WC_WooMercadoPago_Options::CREDENTIALS_ACCESS_TOKEN_PROD, $access_token_prod, true ); + update_option( WC_WooMercadoPago_Options::CREDENTIALS_PUBLIC_KEY_PROD, $public_key_prod, true ); + update_option( WC_WooMercadoPago_Options::CHECKOUT_COUNTRY, $me['site_id'], true ); + update_option( WC_WooMercadoPago_Options::SITE_ID, $me['site_id'], true ); + if ( ( empty( $public_key_test ) && empty( $access_token_test ) ) + || ( true === $validate_public_key_test['is_test'] && true === $validate_access_token_test['is_test'] ) ) { + update_option( WC_WooMercadoPago_Options::CREDENTIALS_PUBLIC_KEY_TEST, $public_key_test, true ); + update_option( WC_WooMercadoPago_Options::CREDENTIALS_ACCESS_TOKEN_TEST, $access_token_test, true ); + WC_WooMercadoPago_Credentials::mercadopago_payment_update(); + if ( empty( $public_key_test ) && empty( $access_token_test ) && ( 'yes' === get_option( 'checkbox_checkout_test_mode', '' ) ) ) { + $response = array( + 'message' => __( 'Your store has exited Test Mode and is making real sales in Production Mode.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'To test the store, re-enter both test credentials.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'alert', + 'test_mode' => 'no' + ); + update_option( 'checkbox_checkout_test_mode', 'no' ); + throw new Exception(); + } else { + wp_send_json_success( __( 'Credentials were updated', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + } + } + $links = WC_WooMercadoPago_Helper_Links::woomercadopago_settings_links(); + $response = array( + 'message' => __( 'Invalid credentials', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'See our manual to learn ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_one' => __( 'how to enter the credentials the right way.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle_one_link' => $links['link_credentials'], + 'type' => 'error', + 'test_mode' => get_option( 'checkbox_checkout_test_mode' ) + ); + + throw new Exception(); + } catch ( Exception $e ) { + wp_send_json_error( $response ); + } + } + + /** + * Get URL with path + * + * @param $path + * @param $extension + * + * @return string + */ + public function get_url( $path, $extension ) { + return sprintf( + '%s%s%s%s', + plugin_dir_url( __FILE__ ), + $path, + $this->get_suffix(), + $extension + ); + } + + /** + * Get suffix to static files + * + * @return string + */ + public function get_suffix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Validate store info Ajax + */ + public function mp_update_store_info(): void { + try { + $this->validate_ajax_nonce(); + + $store_info = array( + 'mp_statement_descriptor' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_identificator' ), + '_mp_category_id' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_categories' ), + '_mp_store_identificator' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_category_id' ), + '_mp_custom_domain' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_url_ipn' ), + '_mp_custom_domain_options' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_url_ipn_options' ), + '_mp_integrator_id' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_integrator_id' ), + '_mp_debug_mode' => WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'store_debug_mode' ), + ); + + foreach ( $store_info as $key => $value ) { + update_option( $key, $value, true ); + } + + wp_send_json_success( __( 'Store information is valid', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } catch ( Exception $e ) { + $response = array( + 'message' => $e->getMessage() + ); + + wp_send_json_error( $response ); + } + } + + /** + * Switch store mode + */ + public function mp_set_mode(): void { + try { + $this->validate_ajax_nonce(); + + $checkout_test_mode = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'input_mode_value' ); + + $verify_alert_test_mode = WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'input_verify_alert_test_mode' ); + $without_test_credentials = ( ( '' === get_option( WC_WooMercadoPago_Options::CREDENTIALS_PUBLIC_KEY_TEST, '' ) || '' === get_option( WC_WooMercadoPago_Options::CREDENTIALS_ACCESS_TOKEN_TEST, '' ) ) ); + + if ( 'yes' === $verify_alert_test_mode || ( 'yes' === $checkout_test_mode && $without_test_credentials ) ) { + throw new Exception( __( 'Invalid credentials for test mode', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } else { + $this->update_credential_production(); + update_option( 'checkbox_checkout_test_mode', $checkout_test_mode, true ); + + $response = 'yes' === $checkout_test_mode ? + __( 'Mercado Pago\'s Payment Methods in Test Mode', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) : + __( 'Mercado Pago\'s Payment Methods in Production Mode', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + + wp_send_json_success( $response ); + } + } catch ( Exception $e ) { + $response = array( + 'message' => $e->getMessage() + ); + + wp_send_json_error( $response ); + } + } + + /** + * Update Credentials for production + */ + public function update_credential_production(): void { + $this->validate_ajax_nonce(); + + foreach ( WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS as $gateway ) { + $key = 'woocommerce_' . $gateway::get_id() . '_settings'; + $options = get_option( $key ); + if ( ! empty( $options ) ) { + $old_credential_is_prod = array_key_exists( 'checkout_credential_prod', $options ) && isset( $options['checkout_credential_prod'] ) ? $options['checkout_credential_prod'] : 'no'; + $has_new_key = array_key_exists( 'checkbox_checkout_test_mode', $options ) && isset( $options['checkbox_checkout_test_mode'] ); + $options['checkbox_checkout_test_mode'] = $has_new_key && 'deprecated' === $old_credential_is_prod + ? $options['checkbox_checkout_test_mode'] + : ( 'yes' === $old_credential_is_prod ? 'no' : 'yes' ); + $options['checkout_credential_prod'] = 'deprecated'; + + /** + * Update if options were changed. + * + * @since 3.0.1 + */ + update_option( $key, apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $gateway::get_id(), $options ) ); + } + } + } + + /** + * Get payment class properties + */ + public function mp_get_payment_class_properties(): void { + try { + $this->validate_ajax_nonce(); + + $payments_gateways = WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS; + $payment_gateway_properties = array(); + $payment_methods = ( new WC_WooMercadoPago_Configs() )->get_available_payment_methods(); + + foreach ( $payments_gateways as $payment_gateway ) { + if ( ! in_array( $payment_gateway, $payment_methods, true ) ) { + continue; + } + + $gateway = new $payment_gateway(); + + $additional_info = array( + 'woo-mercado-pago-basic' => array('icon' => 'mp-settings-icon-mp'), + 'woo-mercado-pago-credits' => array('icon' => 'mp-settings-icon-mp'), + 'woo-mercado-pago-custom' => array('icon' => 'mp-settings-icon-card'), + 'woo-mercado-pago-ticket' => array('icon' => 'mp-settings-icon-code'), + 'woo-mercado-pago-pix' => array('icon' => 'mp-settings-icon-pix'), + ); + + $payment_gateway_properties[] = array( + 'id' => $gateway->id, + 'title_gateway' => $gateway->title_gateway, + 'description' => $gateway->description, + 'title' => $gateway->title, + 'enabled' => $gateway->settings['enabled'], + 'icon' => $additional_info[ $gateway->id ]['icon'], + 'link' => admin_url( 'admin.php?page=wc-settings&tab=checkout§ion=' ) . $gateway->id, + 'badge_translator' => array( + 'yes' => __( 'Enabled', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'no' => __( 'Disabled', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ), + ); + } + + wp_send_json_success( $payment_gateway_properties ); + } catch ( Exception $e ) { + $response = array( + 'message' => $e->getMessage() + ); + + wp_send_json_error( $response ); + } + } + + /** + * Validate credentials tips + */ + public function mp_validate_credentials_tips(): void { + try { + $this->validate_ajax_nonce(); + + $public_key_test = $this->options->get_public_key_test(); + $access_token_test = $this->options->get_access_token_test(); + $public_key_prod = $this->options->get_public_key_prod(); + $access_token_prod = $this->options->get_access_token_prod(); + + if ( ! ( $public_key_test xor $access_token_test ) && $public_key_prod && $access_token_prod ) { + wp_send_json_success( __( 'Valid Credentials', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + + throw new Exception( __( 'Credentials couldn\'t be validated', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } catch ( Exception $e ) { + $response = array( + 'message' => $e->getMessage() + ); + + wp_send_json_error( $response ); + } + } + + /** + * Validate store tips + */ + public function mp_validate_store_tips(): void { + try { + $this->validate_ajax_nonce(); + + $statement_descriptor = $this->options->get_store_name_on_invoice(); + $category_id = $this->options->get_store_category(); + $identificator = $this->options->get_store_id(); + + if ( $statement_descriptor && $category_id && $identificator ) { + wp_send_json_success( __( 'Store business fields are valid', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + + throw new Exception( __( 'Store business fields couldn\'t be validated', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } catch ( Exception $e ) { + $response = array( + 'message' => $e->getMessage() + ); + + wp_send_json_error( $response ); + } + } + + /** + * Validate field payment + */ + public function mp_validate_payment_tips(): void { + try { + $this->validate_ajax_nonce(); + + $payments_gateways = WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS; + + foreach ( $payments_gateways as $payment_gateway ) { + $gateway = new $payment_gateway(); + + if ( 'yes' === $gateway->settings['enabled'] ) { + wp_send_json_success( __( 'At least one paymet method is enabled', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + } + throw new Exception( __( 'No payment method enabled', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } catch ( Exception $e ) { + $response = array( + 'message' => $e->getMessage() + ); + + wp_send_json_error( $response ); + } + } + + /** + * Validate ajax nonce + * + * @return void + */ + private function validate_ajax_nonce(): void { + $this->current_user->validate_user_needed_permissions(); + $this->nonce->validate_nonce( + self::SETTINGS_NONCE_ID, + WC_WooMercadoPago_Helper_Filter::get_sanitize_text_from_post( 'nonce' ) + ); + } } diff --git a/includes/module/order/class-wc-woomercadopago-order.php b/includes/module/order/class-wc-woomercadopago-order.php index 1d29ae8d8..c812053ca 100644 --- a/includes/module/order/class-wc-woomercadopago-order.php +++ b/includes/module/order/class-wc-woomercadopago-order.php @@ -1,325 +1,317 @@ 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 ); - } - } - - /** - * Rule of approved payment - * - * @param array $data Payment data. - * @param object $order Order. - * @param string $used_gateway Class of gateway. - */ - public function mp_rule_approved( $data, $order, $used_gateway ) { - if ( 'partially_refunded' === $data['status_detail'] ) { - return; - } - - $status = $order->get_status(); - - if ( 'pending' === $status || 'on-hold' === $status || 'failed' === $status ) { - $order->add_order_note( 'Mercado Pago: ' . __( 'Payment approved.', 'woocommerce-mercadopago' ) ); - - /** - * Apply filters woocommerce_payment_complete_order_status. - * - * @since 3.0.1 - */ - $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_Ticket_Gateway': - if ( 'no' === get_option( 'stock_reduce_mode', 'no' ) ) { - $order->payment_complete(); - if ( 'completed' !== $payment_completed_status ) { - $order->update_status( self::get_wc_status_for_mp_status( 'approved' ) ); - } - } - break; - - default: - $order->payment_complete(); - if ( 'completed' !== $payment_completed_status ) { - $order->update_status( self::get_wc_status_for_mp_status( 'approved' ) ); - } - break; - } - } - } - } - - /** - * Rule of pending - * - * @param array $data Payment data. - * @param object $order Order. - * @param string $used_gateway Gateway Class. - */ - public function mp_rule_pending( $data, $order, $used_gateway ) { - if ( $this->can_update_order_status( $order ) ) { - $order->update_status( self::get_wc_status_for_mp_status( 'pending' ) ); - switch ( $used_gateway ) { - case 'WC_WooMercadoPago_Pix_Gateway': - $notes = $order->get_customer_order_notes(); - if ( count( $notes ) > 1 ) { - break; - } - - $order->add_order_note( - 'Mercado Pago: ' . __( 'Waiting for the Pix payment.', 'woocommerce-mercadopago' ) - ); - - $order->add_order_note( - 'Mercado Pago: ' . __( 'Waiting for the Pix payment.', 'woocommerce-mercadopago' ), - 1, - false - ); - break; - - case 'WC_WooMercadoPago_Ticket_Gateway': - $notes = $order->get_customer_order_notes(); - if ( count( $notes ) > 1 ) { - break; - } - - $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->validate_order_note_type( $data, $order, 'pending' ); - } - } - - /** - * Rule of In Process - * - * @param array $data Payment data. - * @param object $order Order. - */ - public function mp_rule_in_process( $data, $order ) { - if ( $this->can_update_order_status( $order ) ) { - $order->update_status( - self::get_wc_status_for_mp_status( 'inprocess' ), - 'Mercado Pago: ' . __( 'Payment is pending review.', 'woocommerce-mercadopago' ) - ); - } else { - $this->validate_order_note_type( $data, $order, 'in_process' ); - } - } - - /** - * Rule of Rejected - * - * @param array $data Payment data. - * @param object $order Order. - */ - public function mp_rule_rejected( $data, $order ) { - if ( $this->can_update_order_status( $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->validate_order_note_type( $data, $order, 'rejected' ); - } - } - - /** - * Rule of Refunded - * - * @param object $order 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' ) - ); - } - - /** - * Rule of Cancelled - * - * @param array $data Payment data. - * @param object $order Order. - */ - public function mp_rule_cancelled( $data, $order ) { - if ( $this->can_update_order_status( $order ) ) { - $order->update_status( - self::get_wc_status_for_mp_status( 'cancelled' ), - 'Mercado Pago: ' . __( 'Payment was canceled.', 'woocommerce-mercadopago' ) - ); - } else { - $this->validate_order_note_type( $data, $order, 'cancelled' ); - } - } - - /** - * Rule of In mediation - * - * @param object $order 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' ) - ); - } - - /** - * Rule of Charged back - * - * @param object $order 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' - ) - ); - } - - /** - * Mercado Pago status - * - * @param string $mp_status Status. - * @return string - */ - 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 ); - } - - /** - * Can update order status? - * - * @param object $order Order. - * - * @return bool - */ - protected function can_update_order_status( $order ) { - return method_exists( $order, 'get_status' ) && - $order->get_status() !== 'completed' && - $order->get_status() !== 'processing'; - } - - /** - * Validate Order Note by Type - * - * @param array $data Payment Data. - * @param object $order Order. - * @param string $status Status. - */ - protected function validate_order_note_type( $data, $order, $status ) { - $payment_id = $data['id']; - - if ( isset( $data['ipn_type'] ) && 'merchant_order' === $data['ipn_type'] ) { - $payments = array(); - - foreach ( $data['payments'] as $payment ) { - $payments[] = $payment['id']; - } - - $payment_id = implode( ',', $payments ); - } - - $order->add_order_note( - sprintf( - /* translators: 1: payment_id 2: status */ - __( 'Mercado Pago: The payment %1$s was notified by Mercado Pago with status %2$s.', 'woocommerce-mercadopago' ), - $payment_id, - $status - ) - ); - } - + /** + * Process order status + * + * @param string $processed_status + * @param array $data + * @param object $order + * @param string $used_gateway + * + * @throws WC_WooMercadoPago_Exception Invalid status response. + */ + public function process_status( $processed_status, $data, $order, $used_gateway ): void { + 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 ); + } + } + + /** + * Rule of approved payment + * + * @param array $data Payment data. + * @param object $order Order. + * @param string $used_gateway Class of gateway. + */ + public function mp_rule_approved( $data, $order, $used_gateway ): void { + if ( 'partially_refunded' === $data['status_detail'] ) { + return; + } + + $status = $order->get_status(); + + if ( 'pending' === $status || 'on-hold' === $status || 'failed' === $status ) { + $order->add_order_note( 'Mercado Pago: ' . __( 'Payment approved.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + + /** + * Apply filters woocommerce_payment_complete_order_status. + * + * @since 3.0.1 + */ + $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_Ticket_Gateway': + if ( 'no' === get_option( 'stock_reduce_mode', 'no' ) ) { + $order->payment_complete(); + if ( 'completed' !== $payment_completed_status ) { + $order->update_status( self::get_wc_status_for_mp_status( 'approved' ) ); + } + } + break; + + default: + $order->payment_complete(); + if ( 'completed' !== $payment_completed_status ) { + $order->update_status( self::get_wc_status_for_mp_status( 'approved' ) ); + } + break; + } + } + } + } + + /** + * Rule of pending + * + * @param array $data Payment data. + * @param object $order Order. + * @param string $used_gateway Gateway Class. + */ + public function mp_rule_pending( $data, $order, $used_gateway ): void { + if ( $this->can_update_order_status( $order ) ) { + $order->update_status( self::get_wc_status_for_mp_status( 'pending' ) ); + switch ( $used_gateway ) { + case 'WC_WooMercadoPago_Pix_Gateway': + $notes = $order->get_customer_order_notes(); + if ( count( $notes ) > 1 ) { + break; + } + + $order->add_order_note( + 'Mercado Pago: ' . __( 'Waiting for the Pix payment.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + + $order->add_order_note( + 'Mercado Pago: ' . __( 'Waiting for the Pix payment.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 1, + false + ); + break; + + case 'WC_WooMercadoPago_Ticket_Gateway': + $notes = $order->get_customer_order_notes(); + if ( count( $notes ) > 1 ) { + break; + } + + $order->add_order_note( + 'Mercado Pago: ' . __( 'Waiting for the ticket payment.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + + $order->add_order_note( + 'Mercado Pago: ' . __( 'Waiting for the ticket payment.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 1, + false + ); + break; + + default: + $order->add_order_note( + 'Mercado Pago: ' . __( 'The customer has not made the payment yet.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + break; + } + } else { + $this->validate_order_note_type( $data, $order, 'pending' ); + } + } + + /** + * Rule of In Process + * + * @param array $data Payment data. + * @param object $order Order. + */ + public function mp_rule_in_process( $data, $order ): void { + if ( $this->can_update_order_status( $order ) ) { + $order->update_status( + self::get_wc_status_for_mp_status( 'inprocess' ), + 'Mercado Pago: ' . __( 'Payment is pending review.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } else { + $this->validate_order_note_type( $data, $order, 'in_process' ); + } + } + + /** + * Rule of Rejected + * + * @param array $data Payment data. + * @param object $order Order. + */ + public function mp_rule_rejected( $data, $order ): void { + if ( $this->can_update_order_status( $order ) ) { + $order->update_status( + self::get_wc_status_for_mp_status( 'rejected' ), + 'Mercado Pago: ' . __( 'Payment was declined. The customer can try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } else { + $this->validate_order_note_type( $data, $order, 'rejected' ); + } + } + + /** + * Rule of Refunded + * + * @param object $order Order. + */ + public function mp_rule_refunded( $order ): void { + $order->update_status( + self::get_wc_status_for_mp_status( 'refunded' ), + 'Mercado Pago: ' . __( 'Payment was returned to the customer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } + + /** + * Rule of Cancelled + * + * @param array $data Payment data. + * @param object $order Order. + */ + public function mp_rule_cancelled( $data, $order ): void { + if ( $this->can_update_order_status( $order ) ) { + $order->update_status( + self::get_wc_status_for_mp_status( 'cancelled' ), + 'Mercado Pago: ' . __( 'Payment was canceled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } else { + $this->validate_order_note_type( $data, $order, 'cancelled' ); + } + } + + /** + * Rule of In mediation + * + * @param object $order Order. + */ + public function mp_rule_in_mediation( $order ): void { + $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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } + + /** + * Rule of Charged back + * + * @param object $order Order. + */ + public function mp_rule_charged_back( $order ): void { + $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.', + LKN_WC_MERCADOPAGO_TEXT_DOMAIN + ) + ); + } + + /** + * Mercado Pago status + * + * @param string $mp_status Status. + * @return string + */ + 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 ); + } + + /** + * Can update order status? + * + * @param object $order Order. + * + * @return bool + */ + protected function can_update_order_status( $order ) { + return method_exists( $order, 'get_status' ) && + $order->get_status() !== 'completed' && + $order->get_status() !== 'processing'; + } + + /** + * Validate Order Note by Type + * + * @param array $data Payment Data. + * @param object $order Order. + * @param string $status Status. + */ + protected function validate_order_note_type( $data, $order, $status ): void { + $payment_id = $data['id']; + + if ( isset( $data['ipn_type'] ) && 'merchant_order' === $data['ipn_type'] ) { + $payments = array(); + + foreach ( $data['payments'] as $payment ) { + $payments[] = $payment['id']; + } + + $payment_id = implode( ',', $payments ); + } + + $order->add_order_note( + sprintf( + /* translators: 1: payment_id 2: status */ + __( 'Mercado Pago: The payment %1$s was notified by Mercado Pago with status %2$s.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + $payment_id, + $status + ) + ); + } } diff --git a/includes/module/preference/analytics/class-wc-woomercadopago-preferenceanalytics.php b/includes/module/preference/analytics/class-wc-woomercadopago-preferenceanalytics.php index 423e9941a..6fec2ac2c 100644 --- a/includes/module/preference/analytics/class-wc-woomercadopago-preferenceanalytics.php +++ b/includes/module/preference/analytics/class-wc-woomercadopago-preferenceanalytics.php @@ -1,98 +1,89 @@ get_settings( 'woocommerce_woo-mercado-pago-basic_settings' ); - } - - /** - * Get custom settings function - * - * @return array get_custom_settings - */ - public function get_custom_settings() { - return $this->get_settings( 'woocommerce_woo-mercado-pago-custom_settings' ); - } + /** + * Get basic settings function + * + * @return array get_basic_settings + */ + public function get_basic_settings() { + return $this->get_settings( 'woocommerce_woo-mercado-pago-basic_settings' ); + } - /** - * Get ticket settings function - * - * @return array get_ticket_settings - */ - public function get_ticket_settings() { - return $this->get_settings( 'woocommerce_woo-mercado-pago-ticket_settings' ); - } + /** + * Get custom settings function + * + * @return array get_custom_settings + */ + public function get_custom_settings() { + return $this->get_settings( 'woocommerce_woo-mercado-pago-custom_settings' ); + } - /** - * Get pix settings function - * - * @return array get_pix_settings - */ - public function get_pix_settings() { - return $this->get_settings( 'woocommerce_woo-mercado-pago-pix_settings' ); - } + /** + * Get ticket settings function + * + * @return array get_ticket_settings + */ + public function get_ticket_settings() { + return $this->get_settings( 'woocommerce_woo-mercado-pago-ticket_settings' ); + } - /** - * Get credits settings function - * - * @return array get_credits_settings - */ - public function get_credits_settings() { - return $this->get_settings( 'woocommerce_woo-mercado-pago-credits_settings' ); - } + /** + * Get pix settings function + * + * @return array get_pix_settings + */ + public function get_pix_settings() { + return $this->get_settings( 'woocommerce_woo-mercado-pago-pix_settings' ); + } - /** - * Get settings function - * - * @param string $option - * @return array - */ - public function get_settings( $option ) { - $db_options = get_option( $option, array() ); - $valid_values = array(); + /** + * Get credits settings function + * + * @return array get_credits_settings + */ + public function get_credits_settings() { + return $this->get_settings( 'woocommerce_woo-mercado-pago-credits_settings' ); + } - foreach ( $db_options as $key => $value ) { - if ( ! empty( $value ) && ! in_array( $key, self::$ignore_fields, true ) ) { - $valid_values[ $key ] = $value; - } - } + /** + * Get settings function + * + * @param string $option + * @return array + */ + public function get_settings( $option ) { + $db_options = get_option( $option, array() ); + $valid_values = array(); - return $valid_values; - } + foreach ( $db_options as $key => $value ) { + if ( ! empty( $value ) && ! in_array( $key, self::$ignore_fields, true ) ) { + $valid_values[ $key ] = $value; + } + } + return $valid_values; + } } diff --git a/includes/module/preference/analytics/index.php b/includes/module/preference/analytics/index.php index 258f3fae9..891711d6d 100644 --- a/includes/module/preference/analytics/index.php +++ b/includes/module/preference/analytics/index.php @@ -1,12 +1,5 @@ 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->is_test_user(); - $this->test_user_v1 = get_option( '_test_user_v1', '' ); - $this->site_id = strtolower(get_option( '_site_id_v1', '' )); - $this->site_data = WC_WooMercadoPago_Module::$country_configs; - $this->order = $order; - $this->checkout = $request_checkout; - - 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 ( count( $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() ); - } - - $this->sdk = $payment->get_sdk_instance(); - } - - /** - * Number format value - * - * @param mixed $value Value. - * @return float - */ - protected function number_format_value( $value ) { - return (float) number_format( $value, 2, '.', '' ); - } - - /** - * Prepare shipping - * - * @return array - */ - protected function prepare_shipping() { - $result = array(); - - if ( $this->ship_cost > 0 ) { - $result[] = $this->ship_cost_item(); - } - - return $result; - } - - /** - * Make common transaction - */ - public function make_common_transaction() { - $this->transaction->__set('binary_mode', $this->get_binary_mode( $this->payment )); - $this->transaction->__set('external_reference', $this->get_external_reference( $this->payment )); - $this->transaction->__set('notification_url', $this->get_notification_url()); - $this->transaction->__set('statement_descriptor', get_option( 'mp_statement_descriptor', 'Mercado Pago' )); - $this->transaction->__set('metadata', $this->get_internal_metadata()); - - if ( ! $this->test_user_v1 && ! $this->sandbox ) { - $this->transaction->__set('sponsor_id', $this->get_sponsor_id()); - } - } - - /** - * Get currency conversion - * - * @return int - */ - public function get_currency_conversion() { - return WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->ratio( $this->payment ); - } - - /** - * Get e-mail - * - * @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; - } - } - - /** - * Get payer custom - * - * @return array - */ - public function get_payer_custom() { - return 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 ) ), - 'phone' => array( - '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_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 - ), - ), - ); - } - - /** - * Get items build array - * - * @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_name' ) ? $product->get_name() : $product->post->post_title; - $product_content = method_exists( $product, 'get_description' ) ? $product->get_description() : $product->post->post_content; - $product_image = method_exists( $product, 'get_image_id' ) ? wp_get_attachment_url( $product->get_image_id() ) : plugins_url( '../../assets/images/cart.png', plugin_dir_path( __FILE__ ) ); - // 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. - $this->list_of_items[] = $product_title . ' x ' . $item['qty']; - $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' => $product_image, - '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; - } - - /** - * Shipping cost item - * - * @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 ), - ); - } - - /** - * Fees cost item - * - * @return array - */ - public function fees_cost_item() { - $items = array(); - foreach ( $this->order->get_fees() as $fee ) { - $final = ( $fee['total'] + $fee['total_tax'] ) * $this->currency_ratio; - - $this->order_total += $this->number_format_value( $final ); - $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; - } - - /** - * Shipments receiver address - * - * @return array - */ - public function shipments_receiver_address() { - return array( - 'receiver_address' => array( - 'zip_code' => html_entity_decode( ( is_object($this->order) && method_exists( $this->order, 'get_shipping_postcode' ) ) ? - $this->order->get_shipping_postcode() : $this->order->shipping_postcode ), - 'street_name' => html_entity_decode( ( is_object($this->order) && - 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 - ), - 'apartment' => ( is_object($this->order) && method_exists( $this->order, 'get_shipping_address_2' ) ) ? - $this->order->get_shipping_address_2() : $this->order->shipping_address_2, - 'city_name' => ( is_object($this->order) && method_exists( $this->order, 'get_shipping_city' ) ) ? - $this->order->get_shipping_city() : $this->order->shipping_city, - 'state_name' => ( is_object($this->order) && method_exists( $this->order, 'get_shipping_state' ) ) ? - $this->order->get_shipping_state() : $this->order->shipping_state, - ), - ); - } - - /** - * Get notification type - * - * @param $notification_url - * @param $notification_class - * - * @return string - */ - public function get_notification_type( $notification_url, $notification_class ) { - $type = WC_WooMercadoPago_Module::get_notification_type($notification_class); - $url_join_character = preg_match('#/wc-api/#', $notification_url) ? '?' : '&'; - return sprintf('%s%ssource_news=%s', $notification_url, $url_join_character, $type); - } - - /** - * Get notification url - * - * @return string|void - */ - public function get_notification_url() { - $notification_url = $this->payment->custom_domain; - $notification_url_options = $this->payment->custom_domain_options; - - if ( ! empty( $notification_url ) && ( - strrpos( $notification_url, 'localhost' ) === false || - filter_var( $notification_url, FILTER_VALIDATE_URL ) === false - ) ) { - if ( $notification_url_options ) { - return $this->get_notification_type( - WC_WooMercadoPago_Module::fix_url_ampersand(esc_url($notification_url . '/wc-api/' . $this->notification_class . '/')), - $this->notification_class - ); - } else { - return WC_WooMercadoPago_Module::fix_url_ampersand(esc_url($notification_url)); - } - } - - if ( empty( $notification_url ) && ! strrpos( get_site_url(), 'localhost' ) ) { - return $this->get_notification_type( - WC()->api_request_url( $this->notification_class ), - $this->notification_class - ); - } - } - - /** - * Get binary_mode - * - * @param WC_WooMercadoPago_Payment_Abstract $payment Payment. - * @return bool - */ - public function get_binary_mode( $payment = null ) { - $binary_mode = ! is_null( $payment ) ? $payment->get_option_mp( 'binary_mode', 'no' ) : 'no'; - - if ( 'no' !== $binary_mode ) { - return true; - } - - return false; - } - - /** - * Get sponsor id - * - * @return string - */ - public function get_sponsor_id() { - return WC_WooMercadoPago_Module::get_sponsor_id(); - } - - /** - * Get external reference - * - * @param null|WC_WooMercadoPago_Payment_Abstract $payment Payment. - * @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; - } - } - - /** - * Get transaction - * - * @param string $transactionType - * - * @return Payment|Preference - */ - public function get_transaction( $transactionType = 'Preference' ) { - $transaction_log = clone $this->transaction; - - if ( isset( $transaction_log->token ) ) { - unset( $transaction_log->token ); - } - - $this->log->write_log( __FUNCTION__, $transactionType . ': ' . wp_json_encode( $transaction_log, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - return $this->transaction; - } - - /** - * Get transaction amount - * - * @return float - */ - public function get_transaction_amount() { - return $this->number_format_value( $this->order_total ); - } - - /** - * Add discounts - * - * @return array - */ - public function add_discounts() { - return 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' => ( 'COP' === $this->site_data[ $this->site_id ]['currency'] || 'CLP' === $this->site_data[ $this->site_id ]['currency'] ) ? - -round( $this->checkout['discount'] * $this->currency_ratio ) : -round( $this->checkout['discount'] * $this->currency_ratio * 100 ) / 100, - ); - } - - /** - * Discount Campaign - * - * @return array - */ - public function add_discounts_campaign() { - return array( - 'campaign_id' => (int) $this->checkout['campaign_id'], - 'coupon_code' => strtoupper( $this->checkout['coupon_code'] ), - 'coupon_amount' => ( 'COP' === $this->site_data[ $this->site_id ]['currency'] || 'CLP' === $this->site_data[ $this->site_id ]['currency'] ) - ? round( $this->checkout['discount'] * $this->currency_ratio ) - : round( $this->checkout['discount'] * $this->currency_ratio * 100 ) / 100, - ); - } - - /** - * Get internal metadata - * - * @return array - */ - public function get_internal_metadata() { - $access_token = get_option( '_mp_access_token_prod', '' ); - $test_mode = false; - - if ( 'yes' === get_option( 'checkbox_checkout_test_mode', '' ) ) { - $test_mode = true; - $access_token = get_option( '_mp_access_token_test', '' ); - } - - if ( empty( $access_token ) ) { - return array(); - } - - $analytics = new WC_WooMercadoPago_PreferenceAnalytics(); - - $w = WC_WooMercadoPago_Module::woocommerce_instance(); - $seller = get_option( '_collector_id_v1', '' ); - $user_id = get_current_user_id(); - - return array( - 'platform' => WC_WooMercadoPago_Constants::PLATAFORM_ID, - 'platform_version' => $w->version, - 'module_version' => WC_WooMercadoPago_Constants::VERSION, - 'php_version' => PHP_VERSION, - 'site_id' => strtolower(get_option( '_site_id_v1' )), - 'sponsor_id' => $this->get_sponsor_id(), - 'collector' => $seller, - 'test_mode' => $test_mode, - 'details' => '', - 'basic_settings' => $analytics->get_basic_settings(), - 'custom_settings' => $analytics->get_custom_settings(), - 'ticket_settings' => $analytics->get_ticket_settings(), - 'pix_settings' => $analytics->get_pix_settings(), - 'credits_settings' => $analytics->get_credits_settings(), - 'seller_website' => get_option('siteurl'), - 'billing_address' => array( - 'zip_code' => html_entity_decode(str_replace('-', '', ( is_object($this->order) && - method_exists( $this->order, 'get_billing_postcode' ) ? - $this->order->get_billing_postcode() : $this->order->billing_postcode )) - ), - 'street_name' => html_entity_decode( - method_exists( $this->order, 'get_billing_address_1' ) ? - $this->order->get_billing_address_1() : $this->order->billing_address_1 - ), - 'city_name' => html_entity_decode( is_object($this->order) && - method_exists( $this->order, 'get_billing_city' ) ? - $this->order->get_billing_city() : $this->order->billing_city - ), - 'state_name' => html_entity_decode( is_object($this->order) && - method_exists( $this->order, 'get_billing_state' ) ? - $this->order->get_billing_state() : $this->order->billing_state - ), - 'country_name' => html_entity_decode( is_object($this->order) && - method_exists( $this->order, 'get_billing_country' ) ? - $this->order->get_billing_country() : $this->order->billing_country - ), - ), - 'user' => array( - 'registered_user' => ( null !== $user_id && '' !== $user_id && 0 !== $user_id ) ? 'yes' : 'no', - 'user_email' => ( null !== $user_id && '' !== $user_id && 0 !== $user_id ) ? get_userdata( $user_id )->user_email : null, - 'user_registration_date' => ( null !== $user_id && ' ' !== $user_id && 0 !== $user_id ) ? gmdate('Y-m-d\TH:i:s.vP', strtotime(get_userdata($user_id)->user_registered) ) : null, - ), - ); - } - - /** - * Calculate price - * - * @param mixed $amount - * - * @return float - */ - private function calculate_price( $amount ) { - if ( 'COP' === $this->site_data[ $this->site_id ]['currency'] || 'CLP' === $this->site_data[ $this->site_id ]['currency'] ) { - return number_format( $amount * $this->currency_ratio, 0, '.', '' ); - } - return number_format( $amount * $this->currency_ratio * 100, 2, '.', '' ) / 100; - } - - /** - * Get date of expiration - * - * @param string $date_expiration - * - * @return string date - */ - public function get_date_of_expiration( $date_expiration ) { - if ( '' !== $date_expiration ) { - return gmdate( 'Y-m-d\TH:i:s.000O', strtotime( '+' . $date_expiration ) ); - } - } + /** + * Sdk + */ + protected $sdk; + + /** + * Transaction + * + * @var Payment|Preference + */ + protected $transaction; + + /** + * Order + * + * @var object + */ + protected $order; + + /** + * Payment + * + * @var WC_WooMercadoPago_Payment_Abstract + */ + protected $payment; + + /** + * Logger + * + * @var WC_WooMercadoPago_Log + */ + protected $log; + + /** + * Checkout + * + * @var null + */ + protected $checkout; + + /** + * Discount + * + * @var mixed|string + */ + protected $gateway_discount; + + /** + * Commission + * + * @var mixed|string + */ + protected $commission; + + /** + * Currency ratio + * + * @var int + */ + protected $currency_ratio; + + /** + * Items + * + * @var array + */ + protected $items; + + /** + * Order total + * + * @var int + */ + protected $order_total; + + /** + * List of items + * + * @var array + */ + protected $list_of_items; + + /** + * Preference + * + * @var array + */ + protected $preference; + + /** + * Selected shipping + * + * @var mixed + */ + protected $selected_shipping; + + /** + * Shipping cost + * + * @var mixed + */ + protected $ship_cost; + + /** + * Site id + * + * @var false|mixed|void + */ + protected $site_id; + + /** + * Site data + * + * @var array + */ + protected $site_data; + + /** + * Test user v1 + * + * @var false|mixed|void + */ + protected $test_user_v1; + + /** + * Is sandbox? + * + * @var bool + */ + protected $sandbox; + + /** + * Notification class + * + * @var false|string + */ + protected $notification_class; + + /** + * Payments + * + * @var array + */ + protected $ex_payments; + + /** + * Installments + * + * @var string + */ + protected $installments; + + /** + * WC_WooMercadoPago_PreferenceAbstract constructor. + * + * @param WC_WooMercadoPago_Payment_Abstract $payment Payment. + * @param object $order Order. + * @param null $request_checkout Request checkout. + * @throws Exception Preference Init abstract exception. + */ + public function __construct( $payment, $order, $request_checkout = 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->is_test_user(); + $this->test_user_v1 = get_option( '_test_user_v1', '' ); + $this->site_id = strtolower(get_option( '_site_id_v1', '' )); + $this->site_data = WC_WooMercadoPago_Module::$country_configs; + $this->order = $order; + $this->checkout = $request_checkout; + + 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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + + $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 ( count( $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() ); + } + + $this->sdk = $payment->get_sdk_instance(); + } + + /** + * Number format value + * + * @param mixed $value Value. + * @return float + */ + protected function number_format_value( $value ) { + return (float) number_format( $value, 2, '.', '' ); + } + + /** + * Prepare shipping + * + * @return array + */ + protected function prepare_shipping() { + $result = array(); + + if ( $this->ship_cost > 0 ) { + $result[] = $this->ship_cost_item(); + } + + return $result; + } + + /** + * Make common transaction + */ + public function make_common_transaction(): void { + $this->transaction->__set('binary_mode', $this->get_binary_mode( $this->payment )); + $this->transaction->__set('external_reference', $this->get_external_reference( $this->payment )); + $this->transaction->__set('notification_url', $this->get_notification_url()); + $this->transaction->__set('statement_descriptor', get_option( 'mp_statement_descriptor', 'Mercado Pago' )); + $this->transaction->__set('metadata', $this->get_internal_metadata()); + + if ( ! $this->test_user_v1 && ! $this->sandbox ) { + $this->transaction->__set('sponsor_id', $this->get_sponsor_id()); + } + } + + /** + * Get currency conversion + * + * @return int + */ + public function get_currency_conversion() { + return WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->ratio( $this->payment ); + } + + /** + * Get e-mail + * + * @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; + } + } + + /** + * Get payer custom + * + * @return array + */ + public function get_payer_custom() { + return 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 ) ), + 'phone' => array( + '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_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 + ), + ), + ); + } + + /** + * Get items build array + * + * @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'] ); + // TODO Maybe add option to activate or deactivate anonymous products + $product_title = "Product"; + $product_content = ""; + $product_image = plugins_url( '../../assets/images/cart.png', plugin_dir_path( __FILE__ ) ); + // 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. + $this->list_of_items[] = $product_title . ' x ' . $item['qty']; + $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' => $product_image, + '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; + } + + /** + * Shipping cost item + * + * @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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'category_id' => get_option( '_mp_category_id', 'others' ), + 'quantity' => 1, + 'unit_price' => $this->number_format_value( $ship_cost ), + ); + } + + /** + * Fees cost item + * + * @return array + */ + public function fees_cost_item() { + $items = array(); + foreach ( $this->order->get_fees() as $fee ) { + $final = ( $fee['total'] + $fee['total_tax'] ) * $this->currency_ratio; + + $this->order_total += $this->number_format_value( $final ); + $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; + } + + /** + * Shipments receiver address + * + * @return array + */ + public function shipments_receiver_address() { + return array( + 'receiver_address' => array( + 'zip_code' => html_entity_decode( ( is_object($this->order) && method_exists( $this->order, 'get_shipping_postcode' ) ) ? + $this->order->get_shipping_postcode() : $this->order->shipping_postcode ), + 'street_name' => html_entity_decode( + ( is_object($this->order) && + 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 + ), + 'apartment' => ( is_object($this->order) && method_exists( $this->order, 'get_shipping_address_2' ) ) ? + $this->order->get_shipping_address_2() : $this->order->shipping_address_2, + 'city_name' => ( is_object($this->order) && method_exists( $this->order, 'get_shipping_city' ) ) ? + $this->order->get_shipping_city() : $this->order->shipping_city, + 'state_name' => ( is_object($this->order) && method_exists( $this->order, 'get_shipping_state' ) ) ? + $this->order->get_shipping_state() : $this->order->shipping_state, + ), + ); + } + + /** + * Get notification type + * + * @param $notification_url + * @param $notification_class + * + * @return string + */ + public function get_notification_type( $notification_url, $notification_class ) { + $type = WC_WooMercadoPago_Module::get_notification_type($notification_class); + $url_join_character = preg_match('#/wc-api/#', $notification_url) ? '?' : '&'; + return sprintf('%s%ssource_news=%s', $notification_url, $url_join_character, $type); + } + + /** + * Get notification url + * + * @return string|void + */ + public function get_notification_url() { + $notification_url = $this->payment->custom_domain; + $notification_url_options = $this->payment->custom_domain_options; + + if ( ! empty( $notification_url ) && ( + strrpos( $notification_url, 'localhost' ) === false || + filter_var( $notification_url, \FILTER_VALIDATE_URL ) === false + ) ) { + if ( $notification_url_options ) { + return $this->get_notification_type( + WC_WooMercadoPago_Module::fix_url_ampersand(esc_url($notification_url . '/wc-api/' . $this->notification_class . '/')), + $this->notification_class + ); + } else { + return WC_WooMercadoPago_Module::fix_url_ampersand(esc_url($notification_url)); + } + } + + if ( empty( $notification_url ) && ! strrpos( get_site_url(), 'localhost' ) ) { + return $this->get_notification_type( + WC()->api_request_url( $this->notification_class ), + $this->notification_class + ); + } + } + + /** + * Get binary_mode + * + * @param WC_WooMercadoPago_Payment_Abstract $payment Payment. + * @return bool + */ + public function get_binary_mode( $payment = null ) { + $binary_mode = ! is_null( $payment ) ? $payment->get_option_mp( 'binary_mode', 'no' ) : 'no'; + + if ( 'no' !== $binary_mode ) { + return true; + } + + return false; + } + + /** + * Get sponsor id + * + * @return string + */ + public function get_sponsor_id() { + return WC_WooMercadoPago_Module::get_sponsor_id(); + } + + /** + * Get external reference + * + * @param WC_WooMercadoPago_Payment_Abstract|null $payment Payment. + * @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; + } + } + + /** + * Get transaction + * + * @param string $transactionType + * + * @return Payment|Preference + */ + public function get_transaction( $transactionType = 'Preference' ) { + $transaction_log = clone $this->transaction; + + if ( isset( $transaction_log->token ) ) { + unset( $transaction_log->token ); + } + + $this->log->write_log( __FUNCTION__, $transactionType . ': ' . wp_json_encode( $transaction_log, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + return $this->transaction; + } + + /** + * Get transaction amount + * + * @return float + */ + public function get_transaction_amount() { + return $this->number_format_value( $this->order_total ); + } + + /** + * Add discounts + * + * @return array + */ + public function add_discounts() { + return array( + 'title' => __( 'Discount provided by store', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'description' => __( 'Discount provided by store', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'quantity' => 1, + 'category_id' => get_option( '_mp_category_name', 'others' ), + 'unit_price' => ( 'COP' === $this->site_data[ $this->site_id ]['currency'] || 'CLP' === $this->site_data[ $this->site_id ]['currency'] ) ? + -round( $this->checkout['discount'] * $this->currency_ratio ) : -round( $this->checkout['discount'] * $this->currency_ratio * 100 ) / 100, + ); + } + + /** + * Discount Campaign + * + * @return array + */ + public function add_discounts_campaign() { + return array( + 'campaign_id' => (int) $this->checkout['campaign_id'], + 'coupon_code' => strtoupper( $this->checkout['coupon_code'] ), + 'coupon_amount' => ( 'COP' === $this->site_data[ $this->site_id ]['currency'] || 'CLP' === $this->site_data[ $this->site_id ]['currency'] ) + ? round( $this->checkout['discount'] * $this->currency_ratio ) + : round( $this->checkout['discount'] * $this->currency_ratio * 100 ) / 100, + ); + } + + /** + * Get internal metadata + * + * @return array + */ + public function get_internal_metadata() { + $access_token = get_option( '_mp_access_token_prod', '' ); + $test_mode = false; + + if ( 'yes' === get_option( 'checkbox_checkout_test_mode', '' ) ) { + $test_mode = true; + $access_token = get_option( '_mp_access_token_test', '' ); + } + + if ( empty( $access_token ) ) { + return array(); + } + + $analytics = new WC_WooMercadoPago_PreferenceAnalytics(); + + $w = WC_WooMercadoPago_Module::woocommerce_instance(); + $seller = get_option( '_collector_id_v1', '' ); + $user_id = get_current_user_id(); + + return array( + 'platform' => WC_WooMercadoPago_Constants::PLATAFORM_ID, + 'platform_version' => $w->version, + 'module_version' => WC_WooMercadoPago_Constants::VERSION, + 'php_version' => \PHP_VERSION, + 'site_id' => strtolower(get_option( '_site_id_v1' )), + 'sponsor_id' => $this->get_sponsor_id(), + 'collector' => $seller, + 'test_mode' => $test_mode, + 'details' => '', + 'basic_settings' => $analytics->get_basic_settings(), + 'custom_settings' => $analytics->get_custom_settings(), + 'ticket_settings' => $analytics->get_ticket_settings(), + 'pix_settings' => $analytics->get_pix_settings(), + 'credits_settings' => $analytics->get_credits_settings(), + 'seller_website' => get_option('siteurl'), + 'billing_address' => array( + 'zip_code' => html_entity_decode( + str_replace('-', '', ( is_object($this->order) && + method_exists( $this->order, 'get_billing_postcode' ) ? + $this->order->get_billing_postcode() : $this->order->billing_postcode )) + ), + 'street_name' => html_entity_decode( + method_exists( $this->order, 'get_billing_address_1' ) ? + $this->order->get_billing_address_1() : $this->order->billing_address_1 + ), + 'city_name' => html_entity_decode( + is_object($this->order) && + method_exists( $this->order, 'get_billing_city' ) ? + $this->order->get_billing_city() : $this->order->billing_city + ), + 'state_name' => html_entity_decode( + is_object($this->order) && + method_exists( $this->order, 'get_billing_state' ) ? + $this->order->get_billing_state() : $this->order->billing_state + ), + 'country_name' => html_entity_decode( + is_object($this->order) && + method_exists( $this->order, 'get_billing_country' ) ? + $this->order->get_billing_country() : $this->order->billing_country + ), + ), + 'user' => array( + 'registered_user' => ( null !== $user_id && '' !== $user_id && 0 !== $user_id ) ? 'yes' : 'no', + 'user_email' => ( null !== $user_id && '' !== $user_id && 0 !== $user_id ) ? get_userdata( $user_id )->user_email : null, + 'user_registration_date' => ( null !== $user_id && ' ' !== $user_id && 0 !== $user_id ) ? gmdate('Y-m-d\TH:i:s.vP', strtotime(get_userdata($user_id)->user_registered) ) : null, + ), + ); + } + + /** + * Calculate price + * + * @param mixed $amount + * + * @return float + */ + private function calculate_price( $amount ) { + if ( 'COP' === $this->site_data[ $this->site_id ]['currency'] || 'CLP' === $this->site_data[ $this->site_id ]['currency'] ) { + return number_format( $amount * $this->currency_ratio, 0, '.', '' ); + } + return number_format( $amount * $this->currency_ratio * 100, 2, '.', '' ) / 100; + } + + /** + * Get date of expiration + * + * @param string $date_expiration + * + * @return string date + */ + public function get_date_of_expiration( $date_expiration ) { + if ( '' !== $date_expiration ) { + return gmdate( 'Y-m-d\TH:i:s.000O', strtotime( '+' . $date_expiration ) ); + } + } } diff --git a/includes/module/preference/class-wc-woomercadopago-preference-basic.php b/includes/module/preference/class-wc-woomercadopago-preference-basic.php index 15b52fcb7..8fa28a542 100644 --- a/includes/module/preference/class-wc-woomercadopago-preference-basic.php +++ b/includes/module/preference/class-wc-woomercadopago-preference-basic.php @@ -1,139 +1,131 @@ transaction = $this->sdk->getPreferenceInstance(); - /** - * WC_WooMercadoPago_Preference_Basic constructor. - * - * @param WC_WooMercadoPago_Payment_Abstract $payment Payment. - * @param object $order Order. - */ - public function __construct( $payment, $order ) { - parent::__construct( $payment, $order ); - $this->transaction = $this->sdk->getPreferenceInstance(); - - $this->make_common_transaction(); - $this->transaction->__get('items')->setEntity( $this->items ); - $this->transaction->__get('payer')->setEntity( $this->get_payer_basic() ); - $this->transaction->__get('back_urls')->setEntity( $this->get_back_urls() ); - $this->transaction->__get('shipments')->setEntity( $this->shipments_receiver_address() ); - $this->transaction->__get('payment_methods')->setEntity( $this->get_payment_methods( $this->ex_payments, $this->installments ) ); - $this->transaction->__set('auto_return', $this->auto_return()); - } + $this->make_common_transaction(); + $this->transaction->__get('items')->setEntity( $this->items ); + $this->transaction->__get('payer')->setEntity( $this->get_payer_basic() ); + $this->transaction->__get('back_urls')->setEntity( $this->get_back_urls() ); + $this->transaction->__get('shipments')->setEntity( $this->shipments_receiver_address() ); + $this->transaction->__get('payment_methods')->setEntity( $this->get_payment_methods( $this->ex_payments, $this->installments ) ); + $this->transaction->__set('auto_return', $this->auto_return()); + } - public function get_internal_metadata() { - $metadata = parent::get_internal_metadata(); - $metadata['checkout'] = 'smart'; - $metadata['checkout_type'] = $this->payment->get_option_mp( 'method', 'redirect' ); - return $metadata; - } + public function get_internal_metadata() { + $metadata = parent::get_internal_metadata(); + $metadata['checkout'] = 'smart'; + $metadata['checkout_type'] = $this->payment->get_option_mp( 'method', 'redirect' ); + return $metadata; + } - /** - * Get payer basic - * - * @return array - */ - public function get_payer_basic() { - return 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( - '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_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 - ), - ), - ); - } + /** + * Get payer basic + * + * @return array + */ + public function get_payer_basic() { + return 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( + '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_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 + ), + ), + ); + } - /** - * Get back URLs - * - * @return array - */ - public function get_back_urls() { - $success_url = $this->payment->get_option_mp( 'success_url', '' ); - $failure_url = $this->payment->get_option_mp( 'failure_url', '' ); - $pending_url = $this->payment->get_option_mp( 'pending_url', '' ); - return 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, - ); - } + /** + * Get back URLs + * + * @return array + */ + public function get_back_urls() { + $success_url = $this->payment->get_option_mp( 'success_url', '' ); + $failure_url = $this->payment->get_option_mp( 'failure_url', '' ); + $pending_url = $this->payment->get_option_mp( 'pending_url', '' ); + return 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, + ); + } - /** - * Get payment methods - * - * @param array $ex_payments Ex. payments. - * @param mixed $installments Installments. - * @return array - */ - public function get_payment_methods( $ex_payments, $installments ) { - $excluded_payment_methods = array(); + /** + * Get payment methods + * + * @param array $ex_payments Ex. payments. + * @param mixed $installments 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, - ) - ); - } - } + if ( is_array( $ex_payments ) && count( $ex_payments ) !== 0 ) { + foreach ( $ex_payments as $excluded ) { + array_push( + $excluded_payment_methods, + array( + 'id' => $excluded, + ) + ); + } + } - return array( - 'installments' => $this->payment->get_valid_installments($installments), - 'excluded_payment_methods' => $excluded_payment_methods, - ); - } + return array( + 'installments' => $this->payment->get_valid_installments($installments), + 'excluded_payment_methods' => $excluded_payment_methods, + ); + } - /** - * Auto return - * - * @return string|void - */ - public function auto_return() { - $auto_return = get_option( 'auto_return', 'yes' ); - if ( 'yes' === $auto_return ) { - return 'approved'; - } - } + /** + * Auto return + * + * @return string|void + */ + public function auto_return() { + $auto_return = get_option( 'auto_return', 'yes' ); + if ( 'yes' === $auto_return ) { + return 'approved'; + } + } } diff --git a/includes/module/preference/class-wc-woomercadopago-preference-credits.php b/includes/module/preference/class-wc-woomercadopago-preference-credits.php index 01f4a0e46..41f414488 100644 --- a/includes/module/preference/class-wc-woomercadopago-preference-credits.php +++ b/includes/module/preference/class-wc-woomercadopago-preference-credits.php @@ -1,44 +1,35 @@ transaction->__set('purpose', 'onboarding_credits'); + } - /** - * WC_WooMercadoPago_Preference_Credits constructor. - * - * @param $payment - * @param $order - */ - public function __construct( $payment, $order ) { - parent::__construct( $payment, $order ); - $this->transaction->__set('purpose', 'onboarding_credits'); - } - - /** - * Overwrite the default method to set Wallet Button Data - * - * @return string[] - */ - public function get_internal_metadata() { - $metadata = parent::get_internal_metadata(); - $metadata['checkout'] = 'pro'; - $metadata['checkout_type'] = 'credits'; - return $metadata; - } - + /** + * Overwrite the default method to set Wallet Button Data + * + * @return string[] + */ + public function get_internal_metadata() { + $metadata = parent::get_internal_metadata(); + $metadata['checkout'] = 'pro'; + $metadata['checkout_type'] = 'credits'; + return $metadata; + } } diff --git a/includes/module/preference/class-wc-woomercadopago-preference-custom-wallet-button.php b/includes/module/preference/class-wc-woomercadopago-preference-custom-wallet-button.php index 62cc14648..9d61f323a 100644 --- a/includes/module/preference/class-wc-woomercadopago-preference-custom-wallet-button.php +++ b/includes/module/preference/class-wc-woomercadopago-preference-custom-wallet-button.php @@ -1,44 +1,35 @@ transaction->__set('purpose', 'wallet_purchase'); + } - /** - * WC_WooMercadoPago_Preference_Custom_Wallet_Button constructor. - * - * @param $payment - * @param $order - */ - public function __construct( $payment, $order ) { - parent::__construct( $payment, $order ); - $this->transaction->__set('purpose', 'wallet_purchase'); - } - - /** - * Overwrite the default method to set Wallet Button Data - * - * @return string[] - */ - public function get_internal_metadata() { - $metadata = parent::get_internal_metadata(); - $metadata['checkout'] = 'pro'; - $metadata['checkout_type'] = 'wallet_button'; - return $metadata; - } - + /** + * Overwrite the default method to set Wallet Button Data + * + * @return string[] + */ + public function get_internal_metadata() { + $metadata = parent::get_internal_metadata(); + $metadata['checkout'] = 'pro'; + $metadata['checkout_type'] = 'wallet_button'; + return $metadata; + } } diff --git a/includes/module/preference/class-wc-woomercadopago-preference-custom.php b/includes/module/preference/class-wc-woomercadopago-preference-custom.php index cd5c78db0..c7f58beea 100755 --- a/includes/module/preference/class-wc-woomercadopago-preference-custom.php +++ b/includes/module/preference/class-wc-woomercadopago-preference-custom.php @@ -1,102 +1,93 @@ transaction = $this->sdk->getPaymentInstance(); - $this->make_common_transaction(); - - $this->transaction->__set('transaction_amount', $this->get_transaction_amount()); - $this->transaction->__set('description', implode( ', ', $this->list_of_items )); - $this->transaction->__set('installments', (int) $this->checkout['installments']); - $this->transaction->__set('payment_method_id', $this->checkout['paymentMethodId']); - $this->transaction->__get('payer')->email = $this->get_email(); - $this->transaction->__set('token', $this->checkout['token']); - $this->transaction->__set('session_id', $this->checkout['session_id']); + $this->transaction = $this->sdk->getPaymentInstance(); + $this->make_common_transaction(); - if ( array_key_exists( 'token', $this->checkout ) ) { - $this->transaction->metadata['token'] = $this->checkout['token']; - if ( ! empty( $this->checkout['CustomerId'] ) ) { - $this->transaction->__get('payer')->id = $this->checkout['CustomerId']; - } - if ( ! empty( $this->checkout['issuer'] ) ) { - $this->transaction->__set('issuer_id', (int) $this->checkout['issuer']); - } - } + $this->transaction->__set('transaction_amount', $this->get_transaction_amount()); + $this->transaction->__set('description', implode( ', ', $this->list_of_items )); + $this->transaction->__set('installments', (int) $this->checkout['installments']); + $this->transaction->__set('payment_method_id', $this->checkout['paymentMethodId']); + $this->transaction->__get('payer')->email = $this->get_email(); + $this->transaction->__set('token', $this->checkout['token']); + $this->transaction->__set('session_id', $this->checkout['session_id']); - $this->transaction->__get('additional_info')->items = $this->items; - $this->transaction->__get('additional_info')->payer = $this->get_payer_custom(); - $this->transaction->__get('additional_info')->shipments = $this->shipments_receiver_address(); + if ( array_key_exists( 'token', $this->checkout ) ) { + $this->transaction->metadata['token'] = $this->checkout['token']; + if ( ! empty( $this->checkout['CustomerId'] ) ) { + $this->transaction->__get('payer')->id = $this->checkout['CustomerId']; + } + if ( ! empty( $this->checkout['issuer'] ) ) { + $this->transaction->__set('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 && 'woo-mercado-pago-custom' === WC()->session->chosen_payment_method - ) { - $this->transaction->__get('additional_info')->items[] = $this->add_discounts(); - $this->transaction = array_merge( $this->preference, $this->add_discounts_campaign() ); - } - } + $this->transaction->__get('additional_info')->items = $this->items; + $this->transaction->__get('additional_info')->payer = $this->get_payer_custom(); + $this->transaction->__get('additional_info')->shipments = $this->shipments_receiver_address(); - public function get_internal_metadata() { - $metadata = parent::get_internal_metadata(); - $metadata['checkout'] = 'custom'; - $metadata['checkout_type'] = 'credit_card'; - return $metadata; - } + if ( + isset( $this->checkout['discount'] ) && ! empty( $this->checkout['discount'] ) && + isset( $this->checkout['coupon_code'] ) && ! empty( $this->checkout['coupon_code'] ) && + $this->checkout['discount'] > 0 && 'woo-mercado-pago-custom' === WC()->session->chosen_payment_method + ) { + $this->transaction->__get('additional_info')->items[] = $this->add_discounts(); + $this->transaction = array_merge( $this->preference, $this->add_discounts_campaign() ); + } + } - /** - * Ship cost item - * - * @return array - */ - public function ship_cost_item() { - $item = parent::ship_cost_item(); - if ( isset( $item['currency_id'] ) ) { - unset( $item['currency_id'] ); - } - return $item; - } + public function get_internal_metadata() { + $metadata = parent::get_internal_metadata(); + $metadata['checkout'] = 'custom'; + $metadata['checkout_type'] = 'credit_card'; + return $metadata; + } - /** - * Get items build array - * - * @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'] ); - } - } + /** + * Ship cost item + * + * @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; - } + /** + * Get items build array + * + * @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; + } } diff --git a/includes/module/preference/class-wc-woomercadopago-preference-pix.php b/includes/module/preference/class-wc-woomercadopago-preference-pix.php index 1a87a5653..55b758fac 100644 --- a/includes/module/preference/class-wc-woomercadopago-preference-pix.php +++ b/includes/module/preference/class-wc-woomercadopago-preference-pix.php @@ -1,102 +1,94 @@ adjust_pix_date_expiration(); + $this->transaction = $this->sdk->getPaymentInstance(); + $this->make_common_transaction(); - /** - * WC_WooMercadoPago_PreferencePix constructor. - * - * @param WC_WooMercadoPago_Payment_Abstract $payment Payment. - * @param object $order Order. - * @param mixed $pix_checkout Pix checkout. - */ - public function __construct( $payment, $order, $pix_checkout ) { - parent::__construct( $payment, $order, $pix_checkout ); - $pix_date_expiration = $this->adjust_pix_date_expiration(); - - $this->transaction = $this->sdk->getPaymentInstance(); - $this->make_common_transaction(); - - $this->transaction->__set('date_of_expiration', $this->get_date_of_expiration( $pix_date_expiration )); - $this->transaction->__set('transaction_amount', $this->get_transaction_amount()); - $this->transaction->__set('description', implode( ', ', $this->list_of_items )); - $this->transaction->__set('payment_method_id', 'pix'); - $this->transaction->__set('external_reference', $this->get_external_reference()); - $this->transaction->__get('point_of_interaction')->type = 'CHECKOUT'; + $this->transaction->__set('date_of_expiration', $this->get_date_of_expiration( $pix_date_expiration )); + $this->transaction->__set('transaction_amount', $this->get_transaction_amount()); + $this->transaction->__set('description', implode( ', ', $this->list_of_items )); + $this->transaction->__set('payment_method_id', 'pix'); + $this->transaction->__set('external_reference', $this->get_external_reference()); + $this->transaction->__get('point_of_interaction')->type = 'CHECKOUT'; - $this->transaction->__get('payer')->email = $this->get_email(); - $this->transaction->__get('payer')->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 ) ); - $this->transaction->__get('payer')->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 ) ); + $this->transaction->__get('payer')->email = $this->get_email(); + $this->transaction->__get('payer')->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 ) ); + $this->transaction->__get('payer')->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 ) ); - $this->transaction->__get('payer')->address->zip_code = html_entity_decode( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_postcode() : $this->order->billing_postcode ); - $this->transaction->__get('payer')->address->street_name = html_entity_decode( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_address_1() : $this->order->billing_address_1 ); - $this->transaction->__get('payer')->address->street_number = ''; - $this->transaction->__get('payer')->address->neighborhood = ''; - $this->transaction->__get('payer')->address->city = html_entity_decode( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_city() : $this->order->billing_city ); - $this->transaction->__get('payer')->address->federal_unit = html_entity_decode( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_state() : $this->order->billing_state ); + $this->transaction->__get('payer')->address->zip_code = html_entity_decode( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_postcode() : $this->order->billing_postcode ); + $this->transaction->__get('payer')->address->street_name = html_entity_decode( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_address_1() : $this->order->billing_address_1 ); + $this->transaction->__get('payer')->address->street_number = ''; + $this->transaction->__get('payer')->address->neighborhood = ''; + $this->transaction->__get('payer')->address->city = html_entity_decode( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_city() : $this->order->billing_city ); + $this->transaction->__get('payer')->address->federal_unit = html_entity_decode( method_exists( $this->order, 'get_id' ) ? $this->order->get_billing_state() : $this->order->billing_state ); - $this->transaction->__get('additional_info')->items = $this->items; - $this->transaction->__get('additional_info')->payer = $this->get_payer_custom(); - $this->transaction->__get('additional_info')->shipments = $this->shipments_receiver_address(); - } + $this->transaction->__get('additional_info')->items = $this->items; + $this->transaction->__get('additional_info')->payer = $this->get_payer_custom(); + $this->transaction->__get('additional_info')->shipments = $this->shipments_receiver_address(); + } - public function get_internal_metadata() { - $metadata = parent::get_internal_metadata(); - $metadata['checkout'] = 'custom'; - $metadata['checkout_type'] = 'pix'; - return $metadata; - } + public function get_internal_metadata() { + $metadata = parent::get_internal_metadata(); + $metadata['checkout'] = 'custom'; + $metadata['checkout_type'] = 'pix'; + return $metadata; + } - /** - * Get items build array - * - * @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'] ); - } - } + /** + * Get items build array + * + * @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 $items; + } - /** - * Adjust old format of pix date expiration - * - * @return string - */ - public function adjust_pix_date_expiration() { - $old_date_expiration = $this->payment->get_option_mp( 'checkout_pix_date_expiration', '' ); + /** + * Adjust old format of pix date expiration + * + * @return string + */ + public function adjust_pix_date_expiration() { + $old_date_expiration = $this->payment->get_option_mp( 'checkout_pix_date_expiration', '' ); - if ( 1 === strlen( $old_date_expiration ) && '1' === $old_date_expiration ) { - $new_date_expiration = '24 hours'; - $this->payment->update_option( 'checkout_pix_date_expiration', $new_date_expiration, true); - return $new_date_expiration; - } elseif ( 1 === strlen( $old_date_expiration ) ) { - $new_date_expiration = $old_date_expiration . ' days'; - $this->payment->update_option( 'checkout_pix_date_expiration', $new_date_expiration, true); - return $new_date_expiration; - } + if ( 1 === strlen( $old_date_expiration ) && '1' === $old_date_expiration ) { + $new_date_expiration = '24 hours'; + $this->payment->update_option( 'checkout_pix_date_expiration', $new_date_expiration, true); + return $new_date_expiration; + } + if ( 1 === strlen( $old_date_expiration ) ) { + $new_date_expiration = $old_date_expiration . ' days'; + $this->payment->update_option( 'checkout_pix_date_expiration', $new_date_expiration, true); + return $new_date_expiration; + } - return $old_date_expiration; - } + return $old_date_expiration; + } } diff --git a/includes/module/preference/class-wc-woomercadopago-preference-ticket.php b/includes/module/preference/class-wc-woomercadopago-preference-ticket.php index 8b381865a..6fa803cb1 100644 --- a/includes/module/preference/class-wc-woomercadopago-preference-ticket.php +++ b/includes/module/preference/class-wc-woomercadopago-preference-ticket.php @@ -1,127 +1,119 @@ transaction = $this->sdk->getPaymentInstance(); - - $helper = new WC_WooMercadoPago_Composite_Id_Helper(); - $id = $ticket_checkout['paymentMethodId']; - $date_expiration = $payment->get_option( 'date_expiration', WC_WooMercadoPago_Constants::DATE_EXPIRATION ) . ' days'; - $this->paymentPlaceId = $helper->getPaymentPlaceId($id); - - $this->transaction = $this->sdk->getPaymentInstance(); - $this->make_common_transaction(); - - $this->transaction->__set('payment_method_id', $helper->getPaymentMethodId($id)); - $this->transaction->__set('date_of_expiration', $this->get_date_of_expiration( $date_expiration )); - $this->transaction->__set('transaction_amount', $this->get_transaction_amount()); - $this->transaction->__set('description', implode( ', ', $this->list_of_items )); - $this->transaction->__set('external_reference', $this->get_external_reference()); - - $this->transaction->__get('payer')->setEntity($this->get_payer_ticket($ticket_checkout)); - - if ( 'webpay' === $ticket_checkout['paymentMethodId'] ) { - $this->set_webpay_properties(); - } - - $this->transaction->__get('additional_info')->items->setEntity($this->items); - $this->transaction->__get('additional_info')->payer->setEntity($this->get_payer_custom()); - $this->transaction->__get('additional_info')->shipments->setEntity($this->shipments_receiver_address()); - - if ( - isset( $this->checkout['discount'] ) && ! empty( $this->checkout['discount'] ) && - isset( $this->checkout['coupon_code'] ) && ! empty( $this->checkout['coupon_code'] ) && - $this->checkout['discount'] > 0 && 'woo-mercado-pago-ticket' === WC()->session->chosen_payment_method - ) { - $this->transaction->__get('additional_info')->items->setEntity($this->add_discounts()); - $this->transaction->setEntity($this->add_discounts_campaign()); - } - } - - public function get_internal_metadata() { - $metadata = parent::get_internal_metadata(); - $metadata['checkout'] = 'custom'; - $metadata['checkout_type'] = 'ticket'; - - if ( $this->paymentPlaceId ) { - $metadata['payment_option_id'] = $this->paymentPlaceId; - } - - return $metadata; - } - - public function set_webpay_properties() { - $this->transaction->__get('transaction_details')->financial_institution = '1234'; - $this->transaction->__set('callback_url', get_site_url()); - $this->transaction->__get('additional_info')->ip_address = '127.0.0.1'; - $this->transaction->__get('payer')->identification->type = 'RUT'; - $this->transaction->__get('payer')->identification->number = '0'; - $this->transaction->__get('payer')->entity_type = 'individual'; - } - - public function get_payer_ticket( $ticket_checkout ) { - $payer = $this->get_payer_custom(); - $payer['email'] = $this->get_email(); - unset($payer['phone']); - - if ( 'BRL' === $this->site_data[ $this->site_id ]['currency'] ) { - $this->transaction->__get('payer')->identification->type = 14 === strlen( $this->checkout['docNumber'] ) ? 'CPF' : 'CNPJ'; - $this->transaction->__get('payer')->identification->number = $this->checkout['docNumber']; - } - - if ( 'UYU' === $this->site_data[ $this->site_id ]['currency'] ) { - $this->transaction->__get('payer')->identification->type = $ticket_checkout['docType']; - $this->transaction->__get('payer')->identification->number = $ticket_checkout['docNumber']; - } - - return $payer; - } - - /** - * Get items build array - * - * @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; - } + /** + * Payment place id + * + * @var mixed + */ + private $paymentPlaceId; + + /** + * WC_WooMercadoPago_PreferenceTicket constructor. + * + * @param WC_WooMercadoPago_Payment_Abstract $payment Payment. + * @param object $order Order. + * @param mixed $ticket_checkout Ticket checkout. + */ + public function __construct( $payment, $order, $ticket_checkout ) { + parent::__construct( $payment, $order, $ticket_checkout ); + $this->transaction = $this->sdk->getPaymentInstance(); + + $helper = new WC_WooMercadoPago_Composite_Id_Helper(); + $id = $ticket_checkout['paymentMethodId']; + $date_expiration = $payment->get_option( 'date_expiration', WC_WooMercadoPago_Constants::DATE_EXPIRATION ) . ' days'; + $this->paymentPlaceId = $helper->getPaymentPlaceId($id); + + $this->transaction = $this->sdk->getPaymentInstance(); + $this->make_common_transaction(); + + $this->transaction->__set('payment_method_id', $helper->getPaymentMethodId($id)); + $this->transaction->__set('date_of_expiration', $this->get_date_of_expiration( $date_expiration )); + $this->transaction->__set('transaction_amount', $this->get_transaction_amount()); + $this->transaction->__set('description', implode( ', ', $this->list_of_items )); + $this->transaction->__set('external_reference', $this->get_external_reference()); + + $this->transaction->__get('payer')->setEntity($this->get_payer_ticket($ticket_checkout)); + + if ( 'webpay' === $ticket_checkout['paymentMethodId'] ) { + $this->set_webpay_properties(); + } + + $this->transaction->__get('additional_info')->items->setEntity($this->items); + $this->transaction->__get('additional_info')->payer->setEntity($this->get_payer_custom()); + $this->transaction->__get('additional_info')->shipments->setEntity($this->shipments_receiver_address()); + + if ( + isset( $this->checkout['discount'] ) && ! empty( $this->checkout['discount'] ) && + isset( $this->checkout['coupon_code'] ) && ! empty( $this->checkout['coupon_code'] ) && + $this->checkout['discount'] > 0 && 'woo-mercado-pago-ticket' === WC()->session->chosen_payment_method + ) { + $this->transaction->__get('additional_info')->items->setEntity($this->add_discounts()); + $this->transaction->setEntity($this->add_discounts_campaign()); + } + } + + public function get_internal_metadata() { + $metadata = parent::get_internal_metadata(); + $metadata['checkout'] = 'custom'; + $metadata['checkout_type'] = 'ticket'; + + if ( $this->paymentPlaceId ) { + $metadata['payment_option_id'] = $this->paymentPlaceId; + } + + return $metadata; + } + + public function set_webpay_properties(): void { + $this->transaction->__get('transaction_details')->financial_institution = '1234'; + $this->transaction->__set('callback_url', get_site_url()); + $this->transaction->__get('additional_info')->ip_address = '127.0.0.1'; + $this->transaction->__get('payer')->identification->type = 'RUT'; + $this->transaction->__get('payer')->identification->number = '0'; + $this->transaction->__get('payer')->entity_type = 'individual'; + } + + public function get_payer_ticket( $ticket_checkout ) { + $payer = $this->get_payer_custom(); + $payer['email'] = $this->get_email(); + unset($payer['phone']); + + if ( 'BRL' === $this->site_data[ $this->site_id ]['currency'] ) { + $this->transaction->__get('payer')->identification->type = 14 === strlen( $this->checkout['docNumber'] ) ? 'CPF' : 'CNPJ'; + $this->transaction->__get('payer')->identification->number = $this->checkout['docNumber']; + } + + if ( 'UYU' === $this->site_data[ $this->site_id ]['currency'] ) { + $this->transaction->__get('payer')->identification->type = $ticket_checkout['docType']; + $this->transaction->__get('payer')->identification->number = $ticket_checkout['docNumber']; + } + + return $payer; + } + + /** + * Get items build array + * + * @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; + } } diff --git a/includes/module/preference/index.php b/includes/module/preference/index.php index 258f3fae9..891711d6d 100644 --- a/includes/module/preference/index.php +++ b/includes/module/preference/index.php @@ -1,12 +1,5 @@ 2 || $i < 1 ) { - throw new WC_WooMercadoPago_Exception( 'Invalid arguments. Use CLIENT_ID and CLIENT SECRET, or ACCESS_TOKEN' ); - } - - if ( 1 === $i ) { - $this->ll_access_token = func_get_arg( 0 ); - } - - if ( 2 === $i ) { - $this->client_id = func_get_arg( 0 ); - $this->client_secret = func_get_arg( 1 ); - } - } - - /** - * Set e-mail - * - * @param string $email E-mail. - */ - public function set_email( $email ) { - MP_Rest_Client::set_email( $email ); - Meli_Rest_Client::set_email( $email ); - } - - /** - * Set Locale - * - * @param string $country_code Country code. - */ - public function set_locale( $country_code ) { - MP_Rest_Client::set_locale( $country_code ); - Meli_Rest_Client::set_locale( $country_code ); - } - - /** - * Sandbox is enable? - * - * @param bool|null $enable Is enable. - * - * @return bool - */ - public function sandbox_mode( $enable = null ) { - if ( ! is_null( $enable ) ) { - $this->sandbox = true === $enable; - } - - return $this->sandbox; - } - - /** - * Get Access Token - * - * @return mixed|null - * @throws WC_WooMercadoPago_Exception Get Access Token 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->access_token_by_client ) ) { - return $this->access_token_by_client; - } - - $app_client_values = array( - 'client_id' => $this->client_id, - 'client_secret' => $this->client_secret, - 'grant_type' => 'client_credentials', - ); - - $access_data = MP_Rest_Client::post( - array( - 'uri' => '/oauth/token', - 'data' => $app_client_values, - 'headers' => array( - 'content-type' => 'application/x-www-form-urlencoded', - ), - ) - ); - - if ( 200 !== $access_data['status'] ) { - return null; - } - - $response = $access_data['response']; - $this->access_token_by_client = $response['access_token']; - - return $this->access_token_by_client; - } - - /** - * Search Payment V1 - * - * @param string $id Payment Id. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Search Payment V1 Exception. - */ - public function search_payment_v1( $id, $token = null ) { - $key = sprintf( '%s%s', __FUNCTION__, $id ); - - $cache = $this->get_cache_response( $key ); - - if ( ! empty( $cache ) ) { - $this->debug_mode_log( - 'mercadopago_requests', - __FUNCTION__, - __( 'Response from cache', 'woocommerce-mercadopago' ) - ); - - return $cache; - } - - $request = array( - 'uri' => '/v1/payments/' . $id, - 'headers' => array( - 'Authorization' => 'Bearer ' . ( is_null( $token ) ? $this->get_access_token() : $token ), - ) - ); - - return MP_Rest_Client::get( $request ); - } - - // === CUSTOMER CARDS FUNCTIONS === - - /** - * Get or Create Customer - * - * @param string $payer_email Payer e-mail. - * - * @return array|mixed|null - * @throws WC_WooMercadoPago_Exception Get or create customer exception. - */ - public function get_or_create_customer( $payer_email ) { - - $customer = $this->search_customer( $payer_email ); - - if ( 200 === $customer['status'] && $customer['response']['paging']['total'] > 0 ) { - $customer = $customer['response']['results'][0]; - } else { - $resp = $this->create_customer( $payer_email ); - $customer = $resp['response']; - } - - return $customer; - } - - /** - * Create Customer - * - * @param string $email E-mail. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Create customer exception. - */ - public function create_customer( $email ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/v1/customers', - 'data' => array( - 'email' => $email, - ), - ); - - return MP_Rest_Client::post( $request ); - } - - /** - * Search customer - * - * @param string $email E-mail. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Search customer exception. - */ - public function search_customer( $email ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/v1/customers/search', - 'params' => array( - 'email' => $email, - ), - ); - - return MP_Rest_Client::get( $request ); - } - - /** - * Create card in customer - * - * @param string $customer_id Customer id. - * @param string $token Token. - * @param string|null $payment_method_id Payment method id. - * @param string|null $issuer_id Issuer id. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Create card in customer 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, - ), - ); - - return MP_Rest_Client::post( $request ); - } - - /** - * Get all customer cards. - * - * @param string $customer_id Customer Id. - * @param string $token Token. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Get all customer cards 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', - ); - - return MP_Rest_Client::get( $request ); - } - - // === COUPOM AND DISCOUNTS FUNCTIONS === - - /** - * Check discount campaigns - * - * @param string $transaction_amount Amount. - * @param string $payer_email Payer e-mail. - * @param string $coupon_code Coupon code. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Check Discount Campaigns 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, - ), - ); - - return MP_Rest_Client::get( $request ); - } - - // === CHECKOUT AUXILIARY FUNCTIONS === - - /** - * Get Authorized Payment Id - * - * @param string $id Authorized Payment Id. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Get Authorized Payment Exception. - */ - public function get_authorized_payment( $id ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/authorized_payments/{$id}', - ); - - return MP_Rest_Client::get( $request ); - } - - /** - * Create Preference - * - * @param array $preference Preference data. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Create Preference 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, - ); - - return MP_Rest_Client::post( $request ); - } - - /** - * Update Preference - * - * @param string $id Preference Id. - * @param array $preference Preference data. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Update Preference Exception. - */ - public function update_preference( $id, $preference ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/checkout/preferences/{$id}', - 'data' => $preference, - ); - - return MP_Rest_Client::put( $request ); - } - - /** - * Get Preference - * - * @param string $id Preference id. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Get Preference. - */ - public function get_preference( $id ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/checkout/preferences/{$id}', - ); - - return MP_Rest_Client::get( $request ); - } - - /** - * Create Payment - * - * @param array $preference Preference. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Create Payment. - */ - 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, - ); - - return MP_Rest_Client::post( $request ); - } - - /** - * Create Preapproval Payment - * - * @param array $preapproval_payment Preapproval Payment. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Create Preapproval Payment. - */ - public function create_preapproval_payment( $preapproval_payment ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/preapproval', - 'data' => $preapproval_payment, - ); - - return MP_Rest_Client::post( $request ); - } - - /** - * Get Preapproval Payment - * - * @param string $id Payment Id. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Get Preapproval payment exception. - */ - public function get_preapproval_payment( $id ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/preapproval/' . $id, - ); - - return MP_Rest_Client::get( $request ); - } - - /** - * Update Preapproval payment - * - * @param string $id Payment Id. - * @param array $preapproval_payment Pre Approval Payment. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Update preapproval payment 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, - ); - - return MP_Rest_Client::put( $request ); - } - - /** - * Cancel preapproval payment - * - * @param string $id Preapproval Id. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Cancel Preapproval payment. - */ - public function cancel_preapproval_payment( $id ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/preapproval/' . $id, - 'data' => array( - 'status' => 'cancelled', - ), - ); - - return MP_Rest_Client::put( $request ); - } - - // === REFUND AND CANCELING FLOW FUNCTIONS === - - /** - * Refund payment - * - * @param string $id Payment id. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Refund payment exception. - */ - public function refund_payment( $id ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/v1/payments/' . $id . '/refunds', - ); - - return MP_Rest_Client::post( $request ); - } - - /** - * Partial refund payment - * - * @param string $id Payment id. - * @param string|float $amount Amount. - * @param string $reason Reason. - * @param string $external_reference External reference. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Partial refund 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, - ), - ), - ); - - return MP_Rest_Client::post( $request ); - } - - /** - * Cancel payment - * - * @param string $id Payment id. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Cancel payment exception. - */ - public function cancel_payment( $id ) { - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $this->get_access_token(), - ), - 'uri' => '/v1/payments/' . $id, - 'data' => '{"status":"cancelled"}', - ); - - return MP_Rest_Client::put( $request ); - } - - /** - * Get payment method - * - * @param string $access_token Access token. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Get payment method exception. - */ - public function get_payment_methods( $access_token ) { - $key = sprintf( '%s%s', __FUNCTION__, $access_token ); - - $cache = $this->get_cache_response( $key ); - - if ( ! empty( $cache ) ) { - $this->debug_mode_log( - 'mercadopago_requests', - __FUNCTION__, - __( 'Response from cache', 'woocommerce-mercadopago' ) - ); - - return $cache; - } - - $request = array( - 'headers' => array( - 'Authorization' => 'Bearer ' . $access_token, - ), - 'uri' => '/v1/payment_methods', - ); - - $response = MP_Rest_Client::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 ); - - $this->build_payment_places( $response['response'] ); - $this->set_cache_response( $key, $response ); - - return $response; - } - - /** - * Validate if the seller is homologated - * - * @param string|null $access_token Access token. - * @param string|null $public_key Public key. - * - * @return array|null|false - * @throws WC_WooMercadoPago_Exception Get credentials wrapper. - */ - public function get_credentials_wrapper( $access_token = null, $public_key = null ) { - $key = sprintf( '%sat%spk%s', __FUNCTION__, $access_token, $public_key ); - - $cache = $this->get_cache_response( $key ); - - if ( ! empty( $cache ) ) { - $this->debug_mode_log( - 'mercadopago_requests', - __FUNCTION__, - __( 'Response from cache', 'woocommerce-mercadopago' ) - ); - - return $cache; - } - - $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 = MP_Rest_Client::get( $request ); - - $log = WC_WooMercadoPago_Log::init_mercado_pago_log( __FUNCTION__ ); - - if ( isset($response['status']) ) { - - if ( $response['status'] > 202 ) { - $log->write_log( 'API GET Credentials Wrapper error:', wp_json_encode( $response ) ); - return false; - } - - $this->set_cache_response( $key, $response['response'] ); - return $response['response']; - } - $log->write_log( 'API Response status is empty', wp_json_encode( $response ) ); - return false; - } - - public function get_me( $access_token ) { - $key = sprintf( '%s%s', __FUNCTION__, $access_token ); - - $cache = $this->get_cache_response( $key ); - - if ( ! empty( $cache ) ) { - $this->debug_mode_log( - 'mercadopago_requests', - __FUNCTION__, - __( 'Response from cache', 'woocommerce-mercadopago' ) - ); - - return $cache; - } - - $request = array( - 'uri' => '/users/me', - 'headers' => array( 'Authorization' => 'Bearer ' . $access_token ) - ); - - $response = MP_Rest_Client::get( $request ); - - if ( $response['status'] > 202 ) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log( __FUNCTION__ ); - $log->write_log( 'API GET users me error:', wp_json_encode( $response ) ); - - return false; - } - - $this->set_cache_response( $key, $response['response'] ); - - return $response['response']; - } - - // === GENERIC RESOURCE CALL METHODS === - - /** - * Get call - * - * @param string|array $request Request. - * @param array $headers Headers. - * @param bool $authenticate Is authenticate. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Get 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'] ) || false !== $request['authenticate'] ) { - $access_token = $this->get_access_token(); - if ( ! empty( $access_token ) ) { - $request['headers'] = array( 'Authorization' => 'Bearer ' . $access_token ); - } - } - - return MP_Rest_Client::get( $request ); - } - - /** - * Post call - * - * @param array|string $request Request. - * @param null $data Request data. - * @param null $params Request params. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Post 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(); - - return MP_Rest_Client::post( $request ); - } - - /** - * Put call - * - * @param array|string $request Request. - * @param null $data Request data. - * @param null $params Request params. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Put 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(); - - return MP_Rest_Client::put( $request ); - } - - /** - * Delete call - * - * @param array|string $request Request. - * @param null|array $params Params. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Delete 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(); - - return MP_Rest_Client::delete( $request ); - } - - /** - * Set payment class - * - * @param null|WC_WooMercadoPago_Payment_Abstract $payment Payment class. - */ - public function set_payment_class( $payment = null ) { - if ( ! is_null( $payment ) ) { - $this->payment_class = get_class( $payment ); - } - } - - /** - * Get payment class - * - * @return WC_WooMercadoPago_Payment_Abstract - */ - public function get_payment_class() { - return $this->payment_class; - } - - - /** - * Get response from cache - * - * @param $key - * - * @return mixed - */ - protected function get_cache_response( $key ) { - $key = sha1( $key ); - - return get_transient( $key ); - } - - /** - * Save a response to cache - * - * @param $key - * @param $value - * @param int $ttl - */ - protected function set_cache_response( $key, $value, $ttl = MINUTE_IN_SECONDS ) { - $key = sha1( $key ); - - set_transient( $key, $value, $ttl ); - } - - /** - * Set log when WordPress in Debug Mode - * - * @param $log_id - * @param $function - * @param $message - */ - protected function debug_mode_log( $log_id, $function, $message ) { - if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log( $log_id ); - $log->write_log( $function, $message ); - } - } - - /** - * Buil array payment places - * - * @param $lpayment_id - */ - private function build_payment_places( &$api_response ) { - - $payment_places = - [ - 'paycash' => [ - [ - 'payment_option_id' => '7eleven', - 'name' => '7 Eleven', - 'status' => 'active', - 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/417ddb90-34ab-11e9-b8b8-15cad73057aa-s.png' - ], - [ - 'payment_option_id' => 'circlek', - 'name' => 'Circle K', - 'status' => 'active', - 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/6f952c90-34ab-11e9-8357-f13e9b392369-s.png' - ], - [ - 'payment_option_id' => 'soriana', - 'name' => 'Soriana', - 'status' => 'active', - 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/dac0bf10-01eb-11ec-ad92-052532916206-s.png' - ], - [ - 'payment_option_id' => 'extra', - 'name' => 'Extra', - 'status' => 'active', - 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/9c8f26b0-34ab-11e9-b8b8-15cad73057aa-s.png' - ], - [ - 'payment_option_id' => 'calimax', - 'name' => 'Calimax', - 'status' => 'active', - 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/52efa730-01ec-11ec-ba6b-c5f27048193b-s.png' - ], - ], - ]; - - foreach ( $api_response as $k => $method ) { - if ( isset( $payment_places[ $method['id'] ] ) ) { - $api_response[ $k ]['payment_places'] = $payment_places[ $method['id'] ]; - } - } - - } - - public function get_payment_response_by_sites( $site ) { - $key = sprintf( '%s%s', __FUNCTION__, $site ); - $cache = $this->get_cache_response( $key ); - - if ( ! empty( $cache ) ) { - $this->debug_mode_log( - 'get_payment_response_by_sites', - __FUNCTION__, - __( 'Response from cache', 'woocommerce-mercadopago' ) - ); - - return $cache; - } - - if ( ! empty( $site ) ) { - $payments = $this->get( '/sites/' . $site . '/payment_methods'); - - if ( isset( $payments['response'] ) ) { - $this->set_cache_response( $key, $payments['response']); - $this->debug_mode_log( - 'get_payment_response_by_sites', - __FUNCTION__, - __( 'Response from API', 'woocommerce-mercadopago' ) - ); - - return $payments['response']; - } - } - - return []; - } + /** + * Client Id + * + * @var false|mixed + */ + private $client_id; + + /** + * Client secret + * + * @var false|mixed + */ + private $client_secret; + + /** + * LL access token + * + * @var false|mixed + */ + private $ll_access_token; + + /** + * Is sandbox? + * + * @var bool + */ + private $sandbox = false; + + /** + * Access token by client + * + * @var string + */ + private $access_token_by_client; + + /** + * Payment class + * + * @var WC_WooMercadoPago_Payment_Abstract + */ + private $payment_class; + + /** + * MP constructor. + * + * @throws WC_WooMercadoPago_Exception MP Class exception. + */ + public function __construct() { + $includes_path = __DIR__; + require_once $includes_path . '/rest-client/class-meli-rest-client.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 ( 1 === $i ) { + $this->ll_access_token = func_get_arg( 0 ); + } + + if ( 2 === $i ) { + $this->client_id = func_get_arg( 0 ); + $this->client_secret = func_get_arg( 1 ); + } + } + + /** + * Set e-mail + * + * @param string $email E-mail. + */ + public function set_email( $email ): void { + MP_Rest_Client::set_email( $email ); + Meli_Rest_Client::set_email( $email ); + } + + /** + * Set Locale + * + * @param string $country_code Country code. + */ + public function set_locale( $country_code ): void { + MP_Rest_Client::set_locale( $country_code ); + Meli_Rest_Client::set_locale( $country_code ); + } + + /** + * Sandbox is enable? + * + * @param bool|null $enable Is enable. + * + * @return bool + */ + public function sandbox_mode( $enable = null ) { + if ( ! is_null( $enable ) ) { + $this->sandbox = true === $enable; + } + + return $this->sandbox; + } + + /** + * Get Access Token + * + * @return mixed|null + * @throws WC_WooMercadoPago_Exception Get Access Token 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->access_token_by_client ) ) { + return $this->access_token_by_client; + } + + $app_client_values = array( + 'client_id' => $this->client_id, + 'client_secret' => $this->client_secret, + 'grant_type' => 'client_credentials', + ); + + $access_data = MP_Rest_Client::post( + array( + 'uri' => '/oauth/token', + 'data' => $app_client_values, + 'headers' => array( + 'content-type' => 'application/x-www-form-urlencoded', + ), + ) + ); + + if ( 200 !== $access_data['status'] ) { + return null; + } + + $response = $access_data['response']; + $this->access_token_by_client = $response['access_token']; + + return $this->access_token_by_client; + } + + /** + * Search Payment V1 + * + * @param string $id Payment Id. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Search Payment V1 Exception. + */ + public function search_payment_v1( $id, $token = null ) { + $key = sprintf( '%s%s', __FUNCTION__, $id ); + + $cache = $this->get_cache_response( $key ); + + if ( ! empty( $cache ) ) { + $this->debug_mode_log( + 'mercadopago_requests', + __FUNCTION__, + __( 'Response from cache', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + + return $cache; + } + + $request = array( + 'uri' => '/v1/payments/' . $id, + 'headers' => array( + 'Authorization' => 'Bearer ' . ( is_null( $token ) ? $this->get_access_token() : $token ), + ) + ); + + return MP_Rest_Client::get( $request ); + } + + // === CUSTOMER CARDS FUNCTIONS === + + /** + * Get or Create Customer + * + * @param string $payer_email Payer e-mail. + * + * @return array|mixed|null + * @throws WC_WooMercadoPago_Exception Get or create customer exception. + */ + public function get_or_create_customer( $payer_email ) { + $customer = $this->search_customer( $payer_email ); + + if ( 200 === $customer['status'] && $customer['response']['paging']['total'] > 0 ) { + $customer = $customer['response']['results'][0]; + } else { + $resp = $this->create_customer( $payer_email ); + $customer = $resp['response']; + } + + return $customer; + } + + /** + * Create Customer + * + * @param string $email E-mail. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Create customer exception. + */ + public function create_customer( $email ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/customers', + 'data' => array( + 'email' => $email, + ), + ); + + return MP_Rest_Client::post( $request ); + } + + /** + * Search customer + * + * @param string $email E-mail. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Search customer exception. + */ + public function search_customer( $email ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/customers/search', + 'params' => array( + 'email' => $email, + ), + ); + + return MP_Rest_Client::get( $request ); + } + + /** + * Create card in customer + * + * @param string $customer_id Customer id. + * @param string $token Token. + * @param string|null $payment_method_id Payment method id. + * @param string|null $issuer_id Issuer id. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Create card in customer 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, + ), + ); + + return MP_Rest_Client::post( $request ); + } + + /** + * Get all customer cards. + * + * @param string $customer_id Customer Id. + * @param string $token Token. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Get all customer cards 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', + ); + + return MP_Rest_Client::get( $request ); + } + + // === COUPOM AND DISCOUNTS FUNCTIONS === + + /** + * Check discount campaigns + * + * @param string $transaction_amount Amount. + * @param string $payer_email Payer e-mail. + * @param string $coupon_code Coupon code. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Check Discount Campaigns 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, + ), + ); + + return MP_Rest_Client::get( $request ); + } + + // === CHECKOUT AUXILIARY FUNCTIONS === + + /** + * Get Authorized Payment Id + * + * @param string $id Authorized Payment Id. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Get Authorized Payment Exception. + */ + public function get_authorized_payment( $id ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/authorized_payments/{$id}', + ); + + return MP_Rest_Client::get( $request ); + } + + /** + * Create Preference + * + * @param array $preference Preference data. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Create Preference 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, + ); + + return MP_Rest_Client::post( $request ); + } + + /** + * Update Preference + * + * @param string $id Preference Id. + * @param array $preference Preference data. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Update Preference Exception. + */ + public function update_preference( $id, $preference ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/checkout/preferences/{$id}', + 'data' => $preference, + ); + + return MP_Rest_Client::put( $request ); + } + + /** + * Get Preference + * + * @param string $id Preference id. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Get Preference. + */ + public function get_preference( $id ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/checkout/preferences/{$id}', + ); + + return MP_Rest_Client::get( $request ); + } + + /** + * Create Payment + * + * @param array $preference Preference. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Create Payment. + */ + 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, + ); + + return MP_Rest_Client::post( $request ); + } + + /** + * Create Preapproval Payment + * + * @param array $preapproval_payment Preapproval Payment. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Create Preapproval Payment. + */ + public function create_preapproval_payment( $preapproval_payment ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/preapproval', + 'data' => $preapproval_payment, + ); + + return MP_Rest_Client::post( $request ); + } + + /** + * Get Preapproval Payment + * + * @param string $id Payment Id. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Get Preapproval payment exception. + */ + public function get_preapproval_payment( $id ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/preapproval/' . $id, + ); + + return MP_Rest_Client::get( $request ); + } + + /** + * Update Preapproval payment + * + * @param string $id Payment Id. + * @param array $preapproval_payment Pre Approval Payment. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Update preapproval payment 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, + ); + + return MP_Rest_Client::put( $request ); + } + + /** + * Cancel preapproval payment + * + * @param string $id Preapproval Id. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Cancel Preapproval payment. + */ + public function cancel_preapproval_payment( $id ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/preapproval/' . $id, + 'data' => array( + 'status' => 'cancelled', + ), + ); + + return MP_Rest_Client::put( $request ); + } + + // === REFUND AND CANCELING FLOW FUNCTIONS === + + /** + * Refund payment + * + * @param string $id Payment id. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Refund payment exception. + */ + public function refund_payment( $id ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/payments/' . $id . '/refunds', + ); + + return MP_Rest_Client::post( $request ); + } + + /** + * Partial refund payment + * + * @param string $id Payment id. + * @param string|float $amount Amount. + * @param string $reason Reason. + * @param string $external_reference External reference. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Partial refund 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, + ), + ), + ); + + return MP_Rest_Client::post( $request ); + } + + /** + * Cancel payment + * + * @param string $id Payment id. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Cancel payment exception. + */ + public function cancel_payment( $id ) { + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $this->get_access_token(), + ), + 'uri' => '/v1/payments/' . $id, + 'data' => '{"status":"cancelled"}', + ); + + return MP_Rest_Client::put( $request ); + } + + /** + * Get payment method + * + * @param string $access_token Access token. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Get payment method exception. + */ + public function get_payment_methods( $access_token ) { + $key = sprintf( '%s%s', __FUNCTION__, $access_token ); + + $cache = $this->get_cache_response( $key ); + + if ( ! empty( $cache ) ) { + $this->debug_mode_log( + 'mercadopago_requests', + __FUNCTION__, + __( 'Response from cache', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + + return $cache; + } + + $request = array( + 'headers' => array( + 'Authorization' => 'Bearer ' . $access_token, + ), + 'uri' => '/v1/payment_methods', + ); + + $response = MP_Rest_Client::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 ); + + $this->build_payment_places( $response['response'] ); + $this->set_cache_response( $key, $response ); + + return $response; + } + + /** + * Validate if the seller is homologated + * + * @param string|null $access_token Access token. + * @param string|null $public_key Public key. + * + * @return array|false|null + * @throws WC_WooMercadoPago_Exception Get credentials wrapper. + */ + public function get_credentials_wrapper( $access_token = null, $public_key = null ) { + $key = sprintf( '%sat%spk%s', __FUNCTION__, $access_token, $public_key ); + + $cache = $this->get_cache_response( $key ); + + if ( ! empty( $cache ) ) { + $this->debug_mode_log( + 'mercadopago_requests', + __FUNCTION__, + __( 'Response from cache', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + + return $cache; + } + + $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 = MP_Rest_Client::get( $request ); + + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( __FUNCTION__ ); + + if ( isset($response['status']) ) { + if ( $response['status'] > 202 ) { + $log->write_log( 'API GET Credentials Wrapper error:', wp_json_encode( $response ) ); + return false; + } + + $this->set_cache_response( $key, $response['response'] ); + return $response['response']; + } + $log->write_log( 'API Response status is empty', wp_json_encode( $response ) ); + return false; + } + + public function get_me( $access_token ) { + $key = sprintf( '%s%s', __FUNCTION__, $access_token ); + + $cache = $this->get_cache_response( $key ); + + if ( ! empty( $cache ) ) { + $this->debug_mode_log( + 'mercadopago_requests', + __FUNCTION__, + __( 'Response from cache', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + + return $cache; + } + + $request = array( + 'uri' => '/users/me', + 'headers' => array('Authorization' => 'Bearer ' . $access_token) + ); + + $response = MP_Rest_Client::get( $request ); + + if ( $response['status'] > 202 ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( __FUNCTION__ ); + $log->write_log( 'API GET users me error:', wp_json_encode( $response ) ); + + return false; + } + + $this->set_cache_response( $key, $response['response'] ); + + return $response['response']; + } + + // === GENERIC RESOURCE CALL METHODS === + + /** + * Get call + * + * @param string|array $request Request. + * @param array $headers Headers. + * @param bool $authenticate Is authenticate. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Get 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'] ) || false !== $request['authenticate'] ) { + $access_token = $this->get_access_token(); + if ( ! empty( $access_token ) ) { + $request['headers'] = array('Authorization' => 'Bearer ' . $access_token); + } + } + + return MP_Rest_Client::get( $request ); + } + + /** + * Post call + * + * @param array|string $request Request. + * @param null $data Request data. + * @param null $params Request params. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Post 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(); + + return MP_Rest_Client::post( $request ); + } + + /** + * Put call + * + * @param array|string $request Request. + * @param null $data Request data. + * @param null $params Request params. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Put 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(); + + return MP_Rest_Client::put( $request ); + } + + /** + * Delete call + * + * @param array|string $request Request. + * @param array|null $params Params. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Delete 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(); + + return MP_Rest_Client::delete( $request ); + } + + /** + * Set payment class + * + * @param WC_WooMercadoPago_Payment_Abstract|null $payment Payment class. + */ + public function set_payment_class( $payment = null ): void { + if ( ! is_null( $payment ) ) { + $this->payment_class = get_class( $payment ); + } + } + + /** + * Get payment class + * + * @return WC_WooMercadoPago_Payment_Abstract + */ + public function get_payment_class() { + return $this->payment_class; + } + + /** + * Get response from cache + * + * @param $key + * + * @return mixed + */ + protected function get_cache_response( $key ) { + $key = sha1( $key ); + + return get_transient( $key ); + } + + /** + * Save a response to cache + * + * @param $key + * @param $value + * @param int $ttl + */ + protected function set_cache_response( $key, $value, $ttl = MINUTE_IN_SECONDS ): void { + $key = sha1( $key ); + + set_transient( $key, $value, $ttl ); + } + + /** + * Set log when WordPress in Debug Mode + * + * @param $log_id + * @param $function + * @param $message + */ + protected function debug_mode_log( $log_id, $function, $message ): void { + if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( $log_id ); + $log->write_log( $function, $message ); + } + } + + /** + * Buil array payment places + * + * @param $lpayment_id + */ + private function build_payment_places( &$api_response ): void { + $payment_places = + array( + 'paycash' => array( + array( + 'payment_option_id' => '7eleven', + 'name' => '7 Eleven', + 'status' => 'active', + 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/417ddb90-34ab-11e9-b8b8-15cad73057aa-s.png' + ), + array( + 'payment_option_id' => 'circlek', + 'name' => 'Circle K', + 'status' => 'active', + 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/6f952c90-34ab-11e9-8357-f13e9b392369-s.png' + ), + array( + 'payment_option_id' => 'soriana', + 'name' => 'Soriana', + 'status' => 'active', + 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/dac0bf10-01eb-11ec-ad92-052532916206-s.png' + ), + array( + 'payment_option_id' => 'extra', + 'name' => 'Extra', + 'status' => 'active', + 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/9c8f26b0-34ab-11e9-b8b8-15cad73057aa-s.png' + ), + array( + 'payment_option_id' => 'calimax', + 'name' => 'Calimax', + 'status' => 'active', + 'thumbnail' => 'https://http2.mlstatic.com/storage/logos-api-admin/52efa730-01ec-11ec-ba6b-c5f27048193b-s.png' + ), + ), + ); + + foreach ( $api_response as $k => $method ) { + if ( isset( $payment_places[ $method['id'] ] ) ) { + $api_response[ $k ]['payment_places'] = $payment_places[ $method['id'] ]; + } + } + } + + public function get_payment_response_by_sites( $site ) { + $key = sprintf( '%s%s', __FUNCTION__, $site ); + $cache = $this->get_cache_response( $key ); + + if ( ! empty( $cache ) ) { + $this->debug_mode_log( + 'get_payment_response_by_sites', + __FUNCTION__, + __( 'Response from cache', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + + return $cache; + } + + if ( ! empty( $site ) ) { + $payments = $this->get( '/sites/' . $site . '/payment_methods'); + + if ( isset( $payments['response'] ) ) { + $this->set_cache_response( $key, $payments['response']); + $this->debug_mode_log( + 'get_payment_response_by_sites', + __FUNCTION__, + __( 'Response from API', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + + return $payments['response']; + } + } + + return array(); + } } diff --git a/includes/module/sdk/lib/index.php b/includes/module/sdk/lib/index.php index 258f3fae9..891711d6d 100644 --- a/includes/module/sdk/lib/index.php +++ b/includes/module/sdk/lib/index.php @@ -1,12 +1,5 @@ $v ) { - if ( 'content-type' === $h ) { - $default_content_type = false; - $json_content = 'application/json' === $v; - $form_content = 'application/x-www-form-urlencoded' === $v; - } - $headers[] = $h . ': ' . $v; - } - } - if ( $default_content_type ) { - $headers[] = 'content-type: application/json'; - } - - //@codingStandardsIgnoreStart - $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 ); - //@codingStandardsIgnoreEnd - - 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'] ); - } - } - // @codingStandardsIgnoreLine - curl_setopt( $connect, CURLOPT_URL, $url . $request['uri'] ); - - if ( isset( $request['data'] ) ) { - if ( $json_content ) { - if ( is_string( $request['data'] ) ) { - json_decode( $request['data'], true ); - } else { - $request['data'] = wp_json_encode( $request['data'] ); - } - if ( function_exists( 'json_last_error' ) ) { - $json_error = json_last_error(); - if ( JSON_ERROR_NONE !== $json_error ) { - throw new WC_WooMercadoPago_Exception( "JSON Error [{$json_error}] - Data: " . $request['data'] ); - } - } - } elseif ( $form_content ) { - $request['data'] = self::build_query( $request['data'] ); - } - // @codingStandardsIgnoreLine - curl_setopt( $connect, CURLOPT_POSTFIELDS, $request['data'] ); - } - - return $connect; - } - - /** - * Execute curl - * - * @param array $request Request data. - * @param CurlHandle $connect Curl Handle Connection. - * - * @return array|null - * @throws WC_WooMercadoPago_Exception Execute call exception. - */ - public static function execute( $request, $connect ) { - $response = null; - // @codingStandardsIgnoreLine - $api_result = curl_exec( $connect ); - // @codingStandardsIgnoreLine - if ( curl_errno( $connect ) ) { - // @codingStandardsIgnoreLine - throw new WC_WooMercadoPago_Exception( curl_error( $connect ) ); - } - - $info = curl_getinfo( $connect ); //phpcs:ignore - $api_http_code = $info['http_code']; //phpcs:ignore - - if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { - $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'mercadopago_requests' ); - $log->write_log( - 'Execute cURL', - sprintf( - /* translators: 1: total_time currency 2: url */ - __('Took %1$s seconds to transfer a request to %2$s', 'woocommerce-mercadopago'), - $info['total_time'], - $info['url'] - ) - ); - } - - if ( null !== $api_http_code && null !== $api_result ) { - $response = array( - 'status' => $api_http_code, - 'response' => json_decode( $api_result, true ), - ); - } - - curl_close( $connect ); //phpcs:ignore - - return $response; - } - - /** - * Build query - * - * @param array $params 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}=" . rawurldecode( $value ); - } - - return implode( '&', $elements ); - } - } - - /** - * Set e-mail - * - * @param string $email E-mail. - */ - public static function set_email( $email ) { - self::$email_admin = $email; - } - - /** - * Set Country code - * - * @param string $country_code Country code. - */ - public static function set_locale( $country_code ) { - self::$site_locale = $country_code; - } + /** + * E-mail admin + * + * @var string + */ + public static $email_admin = ''; + + /** + * Site locale + * + * @var string + */ + public static $site_locale = ''; + + /** + * Check loop + * + * @var int + */ + public static $check_loop = 0; + + /** + * Exec ABS + * + * @param array $request Request. + * @param string $url URL. + * + * @return array|null + */ + public static function exec_abs( $request, $url ) { + try { + $connect = self::build_request( $request, $url ); + + return self::execute( $request, $connect ); + } catch ( Exception $e ) { + return null; + } + } + + /** + * Build request + * + * @param array $request Request data. + * @param string $url URL. + * + * @return CurlHandle|false|resource + * @throws WC_WooMercadoPago_Exception Build request 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 ( 'POST' === $request['method'] ) { + $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 ( 'content-type' === $h ) { + $default_content_type = false; + $json_content = 'application/json' === $v; + $form_content = 'application/x-www-form-urlencoded' === $v; + } + $headers[] = $h . ': ' . $v; + } + } + if ( $default_content_type ) { + $headers[] = 'content-type: application/json'; + } + + //@codingStandardsIgnoreStart + $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 ); + //@codingStandardsIgnoreEnd + + 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'] ); + } + } + // @codingStandardsIgnoreLine + curl_setopt( $connect, \CURLOPT_URL, $url . $request['uri'] ); + + if ( isset( $request['data'] ) ) { + if ( $json_content ) { + if ( is_string( $request['data'] ) ) { + json_decode( $request['data'], true ); + } else { + $request['data'] = wp_json_encode( $request['data'] ); + } + if ( function_exists( 'json_last_error' ) ) { + $json_error = json_last_error(); + if ( \JSON_ERROR_NONE !== $json_error ) { + throw new WC_WooMercadoPago_Exception( "JSON Error [{$json_error}] - Data: " . $request['data'] ); + } + } + } elseif ( $form_content ) { + $request['data'] = self::build_query( $request['data'] ); + } + // @codingStandardsIgnoreLine + curl_setopt( $connect, \CURLOPT_POSTFIELDS, $request['data'] ); + } + + return $connect; + } + + /** + * Execute curl + * + * @param array $request Request data. + * @param CurlHandle $connect Curl Handle Connection. + * + * @return array|null + * @throws WC_WooMercadoPago_Exception Execute call exception. + */ + public static function execute( $request, $connect ) { + $response = null; + // @codingStandardsIgnoreLine + $api_result = curl_exec( $connect ); + // @codingStandardsIgnoreLine + if ( curl_errno( $connect ) ) { + // @codingStandardsIgnoreLine + throw new WC_WooMercadoPago_Exception( curl_error( $connect ) ); + } + + $info = curl_getinfo( $connect ); //phpcs:ignore + $api_http_code = $info['http_code']; //phpcs:ignore + + if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { + $log = WC_WooMercadoPago_Log::init_mercado_pago_log( 'mercadopago_requests' ); + $log->write_log( + 'Execute cURL', + sprintf( + /* translators: 1: total_time currency 2: url */ + __('Took %1$s seconds to transfer a request to %2$s', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + $info['total_time'], + $info['url'] + ) + ); + } + + if ( null !== $api_http_code && null !== $api_result ) { + $response = array( + 'status' => $api_http_code, + 'response' => json_decode( $api_result, true ), + ); + } + + curl_close( $connect ); //phpcs:ignore + + return $response; + } + + /** + * Build query + * + * @param array $params 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}=" . rawurldecode( $value ); + } + + return implode( '&', $elements ); + } + } + + /** + * Set e-mail + * + * @param string $email E-mail. + */ + public static function set_email( $email ): void { + self::$email_admin = $email; + } + + /** + * Set Country code + * + * @param string $country_code Country code. + */ + public static function set_locale( $country_code ): void { + self::$site_locale = $country_code; + } } diff --git a/includes/module/sdk/lib/rest-client/class-mp-rest-client.php b/includes/module/sdk/lib/rest-client/class-mp-rest-client.php index 009e56a36..43737e64b 100644 --- a/includes/module/sdk/lib/rest-client/class-mp-rest-client.php +++ b/includes/module/sdk/lib/rest-client/class-mp-rest-client.php @@ -1,69 +1,60 @@ payment = $payment; - $this->mp = $payment->mp; - $this->log = $payment->log; - $this->sandbox = $payment->sandbox; - - add_action( 'woocommerce_api_' . strtolower( get_class( $payment ) ), array( $this, 'check_ipn_response' ) ); - // @todo remove when 5 is the most used. - add_action( 'woocommerce_api_' . strtolower( preg_replace( '/_gateway/i', 'Gateway', 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 ); - } - - /** - * Mercado Pago status - * - * @param string $mp_status Status. - * @return string|string[] - */ - 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 ); - } - - /** - * Log IPN response - */ - public function check_ipn_response() { - // @todo need to be analyzed better - // @codingStandardsIgnoreLine - @ob_clean(); - // phpcs:ignore WordPress.Security.NonceVerification - $this->log->write_log( __FUNCTION__, 'received _get content: ' . wp_json_encode( $_GET, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - } - - - /** - * Process successful request - * - * @param array $data Preference 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->set_response( 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->set_response( 422, null, 'Order is invalid' ); - } - - if ( $order->get_id() !== $id ) { - $this->log->write_log( __FUNCTION__, 'Order error' ); - $this->set_response( 422, null, 'Order error' ); - } - - $this->log->write_log( __FUNCTION__, 'updating metadata and status with data: ' . wp_json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - - return $order; - } - - /** - * Process order status - * - * @param string $processed_status Status. - * @param array $data Payment data. - * @param object $order Order. - * - * @throws WC_WooMercadoPago_Exception Invalid status response. - */ - public function process_status( $processed_status, $data, $order ) { - $used_gateway = get_class( $this->payment ); - ( new WC_WooMercadoPago_Order() )->process_status( $processed_status, $data, $order, $used_gateway ); - } - - /** - * Process cancel Order - * - * @param object $order Order. - * @throws WC_WooMercadoPago_Exception - */ - public function process_cancel_order_meta_box_actions( $order ) { - $order_payment = wc_get_order( $order ); - $used_gateway = $order_payment->get_meta( '_used_gateway' ); - $payments = $order_payment->get_meta( '_Mercado_Pago_Payment_IDs' ); - - if ( 'WC_WooMercadoPago_Custom_Gateway' === $used_gateway ) { - return; - } - - $this->log->write_log( __FUNCTION__, 'cancelling payments for ' . $payments ); - - // Canceling the order and all of its payments. - if ( null !== $this->mp && ! 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' ); - } - } - - /** - * Check and save customer card - * - * @param array $checkout_info Checkout info. - */ - public function check_and_save_customer_card( $checkout_info ) { - $this->log->write_log( __FUNCTION__, 'checking info to create card: ' . wp_json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - $cost_id = null; - $token = null; - $issuer_id = null; - $payment_method_id = null; - - if ( isset( $checkout_info['payer']['id'] ) && ! empty( $checkout_info['payer']['id'] ) ) { - $cost_id = $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( $cost_id, $token, $payment_method_id, $issuer_id ); - } catch ( WC_WooMercadoPago_Exception $ex ) { - $this->log->write_log( __FUNCTION__, 'card creation failed: ' . wp_json_encode( $ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - } - } - - /** - * Set response - * - * @param int $code HTTP Code. - * @param string $code_message Message. - * @param string $body Body. - */ - public function set_response( $code, $code_message, $body ) { - status_header( $code, $code_message ); - die ( wp_kses_post ($body )); - } - - public function update_meta( $order, $key, $value ) { - $order->update_meta_data( $key, $value ); - } + /** + * Mercado Pago Module + * + * @var WC_WooMercadoPago_Module + */ + public $mp; + + /** + * Is sandbox? + * + * @var true + */ + public $sandbox; + + /** + * Mergado Pago Log + * + * @var WC_WooMercadoPago_Log + */ + public $log; + + /** + * Self! + * + * @var WC_WooMercadoPago_Payment_Abstract + */ + public $payment; + + /** + * WC_WooMercadoPago_Notification_Abstract constructor. + * + * @param WC_WooMercadoPago_Payment_Abstract $payment payment class. + */ + public function __construct( $payment ) { + $this->payment = $payment; + $this->mp = $payment->mp; + $this->log = $payment->log; + $this->sandbox = $payment->sandbox; + + add_action( 'woocommerce_api_' . strtolower( get_class( $payment ) ), array($this, 'check_ipn_response') ); + // @todo remove when 5 is the most used. + add_action( 'woocommerce_api_' . strtolower( preg_replace( '/_gateway/i', 'Gateway', 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 ); + } + + /** + * Mercado Pago status + * + * @param string $mp_status Status. + * @return string|string[] + */ + 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 ); + } + + /** + * Log IPN response + */ + public function check_ipn_response(): void { + // @todo need to be analyzed better + // @codingStandardsIgnoreLine + @ob_clean(); + // phpcs:ignore WordPress.Security.NonceVerification + $this->log->write_log( __FUNCTION__, 'received _get content: ' . wp_json_encode( $_GET, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + } + + /** + * Process successful request + * + * @param array $data Preference 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->set_response( 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->set_response( 422, null, 'Order is invalid' ); + } + + if ( $order->get_id() !== $id ) { + $this->log->write_log( __FUNCTION__, 'Order error' ); + $this->set_response( 422, null, 'Order error' ); + } + + $this->log->write_log( __FUNCTION__, 'updating metadata and status with data: ' . wp_json_encode( $data, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + + return $order; + } + + /** + * Process order status + * + * @param string $processed_status Status. + * @param array $data Payment data. + * @param object $order Order. + * + * @throws WC_WooMercadoPago_Exception Invalid status response. + */ + public function process_status( $processed_status, $data, $order ): void { + $used_gateway = get_class( $this->payment ); + ( new WC_WooMercadoPago_Order() )->process_status( $processed_status, $data, $order, $used_gateway ); + } + + /** + * Process cancel Order + * + * @param object $order Order. + * @throws WC_WooMercadoPago_Exception + */ + public function process_cancel_order_meta_box_actions( $order ): void { + $order_payment = wc_get_order( $order ); + $used_gateway = $order_payment->get_meta( '_used_gateway' ); + $payments = $order_payment->get_meta( '_Mercado_Pago_Payment_IDs' ); + + if ( 'WC_WooMercadoPago_Custom_Gateway' === $used_gateway ) { + return; + } + + $this->log->write_log( __FUNCTION__, 'cancelling payments for ' . $payments ); + + // Canceling the order and all of its payments. + if ( null !== $this->mp && ! 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' ); + } + } + + /** + * Check and save customer card + * + * @param array $checkout_info Checkout info. + */ + public function check_and_save_customer_card( $checkout_info ): void { + $this->log->write_log( __FUNCTION__, 'checking info to create card: ' . wp_json_encode( $checkout_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + $cost_id = null; + $token = null; + $issuer_id = null; + $payment_method_id = null; + + if ( isset( $checkout_info['payer']['id'] ) && ! empty( $checkout_info['payer']['id'] ) ) { + $cost_id = $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( $cost_id, $token, $payment_method_id, $issuer_id ); + } catch ( WC_WooMercadoPago_Exception $ex ) { + $this->log->write_log( __FUNCTION__, 'card creation failed: ' . wp_json_encode( $ex, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + } + } + + /** + * Set response + * + * @param int $code HTTP Code. + * @param string $code_message Message. + * @param string $body Body. + */ + public function set_response( $code, $code_message, $body ): void { + status_header( $code, $code_message ); + die ( wp_kses_post ($body )); + } + + public function update_meta( $order, $key, $value ): void { + $order->update_meta_data( $key, $value ); + } } diff --git a/includes/notification/class-wc-woomercadopago-notification-core.php b/includes/notification/class-wc-woomercadopago-notification-core.php index 87daa76b4..b9f5f109e 100644 --- a/includes/notification/class-wc-woomercadopago-notification-core.php +++ b/includes/notification/class-wc-woomercadopago-notification-core.php @@ -1,153 +1,144 @@ get_sdk_instance(); - $this->sdkNotification = $sdk->getNotificationInstance(); - } - - /** - * IPN - */ - public function check_ipn_response() { - parent::check_ipn_response(); - - $notification_id = json_decode(file_get_contents('php://input')); - - // handling old notifications - if ( gettype($notification_id) === 'object' ) { - $class = get_class( $this->payment ); - - if ( 'WC_WooMercadoPago_Basic_Gateway' === $class ) { - $notification_handler = new WC_WooMercadoPago_Notification_IPN( $this->payment ); - } else { - $notification_handler = new WC_WooMercadoPago_Notification_Webhook( $this->payment ); - } - - $notification_handler->check_ipn_response(); - return; - } - - status_header( 200, 'OK' ); - - $this->log->write_log( __FUNCTION__, 'Receiving Core Notification with ID: ' . $notification_id ); - - try { - $notificationEntity = $this->sdkNotification->read(array('id' => $notification_id)); - - /** - * Do action valid_mercadopago_ipn_request. - * - * @since 3.0.1 - */ - do_action( 'valid_mercadopago_ipn_request', $notificationEntity->toArray() ); - - $this->set_response( 200, 'OK', 'Successfully Notification by Core' ); - } catch ( Exception $e ) { - $this->log->write_log( __FUNCTION__, 'receive notification failed: ' . $e->getMessage() ); - $this->set_response(500, 'Internal Server Error', $e->getMessage()); - } - } - - /** - * Process success response - * - * @param array $data Payment data. - * - * @return void - */ - 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->process_status( $processed_status, $data, $order ); - } catch ( Exception $e ) { - $this->set_response( 422, null, $e->getMessage() ); - $this->log->write_log( __FUNCTION__, $e->getMessage() ); - } - } - - /** - * Process status - * - * @param array $data Payment data. - * @param object $order Order. - * @return string - */ - public function process_status_mp_business( $data, $order ) { - $status = $data['status']; - try { - // Updates the type of gateway. - $this->update_meta( $order, '_used_gateway', get_class( $this->payment ) ); - - if ( ! empty( $data['payer']['email'] ) ) { - $this->update_meta( $order, __( 'Buyer email', 'woocommerce-mercadopago' ), $data['payer']['email'] ); - } - - if ( ! empty( $data['payments_details'] ) ) { - $payment_ids = array(); - - foreach ( $data['payments_details'] as $payment ) { - $payment_ids[] = $payment['id']; - - $this->update_meta( - $order, - 'Mercado Pago - Payment ' . $payment['id'], - '[Date ' . gmdate('Y-m-d H:i:s') . - ']/[Amount ' . $payment['total_amount'] . - ']/[Payment Type ' . $payment['payment_type_id'] . - ']/[Payment Method ' . $payment['payment_method_id'] . - ']/[Paid ' . $payment['paid_amount'] . - ']/[Coupon ' . $payment['coupon_amount'] . - ']/[Refund ' . $data['total_refunded'] . ']' - ); - $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - payment_type', $payment['payment_type_id']); - - if ( strpos($payment['payment_type_id'], 'card') !== false ) { - $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - installments', $payment['payment_method_info']['installments']); - $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - installment_amount', $payment['payment_method_info']['installment_amount']); - $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - transaction_amount', $payment['total_amount']); - $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - total_paid_amount', $payment['paid_amount']); - $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - card_last_four_digits', $payment['payment_method_info']['last_four_digits']); - } - } - } - - if ( count( $payment_ids ) > 0 ) { - $this->update_meta( $order, '_Mercado_Pago_Payment_IDs', implode( ', ', $payment_ids ) ); - } - - $order->save(); - - } catch ( Exception $e ) { - $this->log->write_log( __FUNCTION__, $e->getMessage() ); - } - - return $status; - } + /** + * SDK Preference + */ + protected $sdkNotification; + + public function __construct( $payment ) { + parent::__construct($payment); + + $sdk = $payment->get_sdk_instance(); + $this->sdkNotification = $sdk->getNotificationInstance(); + } + + /** + * IPN + */ + public function check_ipn_response(): void { + parent::check_ipn_response(); + + $notification_id = json_decode(file_get_contents('php://input')); + + // handling old notifications + if ( gettype($notification_id) === 'object' ) { + $class = get_class( $this->payment ); + + if ( 'WC_WooMercadoPago_Basic_Gateway' === $class ) { + $notification_handler = new WC_WooMercadoPago_Notification_IPN( $this->payment ); + } else { + $notification_handler = new WC_WooMercadoPago_Notification_Webhook( $this->payment ); + } + + $notification_handler->check_ipn_response(); + return; + } + + status_header( 200, 'OK' ); + + $this->log->write_log( __FUNCTION__, 'Receiving Core Notification with ID: ' . $notification_id ); + + try { + $notificationEntity = $this->sdkNotification->read(array('id' => $notification_id)); + + /** + * Do action valid_mercadopago_ipn_request. + * + * @since 3.0.1 + */ + do_action( 'valid_mercadopago_ipn_request', $notificationEntity->toArray() ); + + $this->set_response( 200, 'OK', 'Successfully Notification by Core' ); + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, 'receive notification failed: ' . $e->getMessage() ); + $this->set_response(500, 'Internal Server Error', $e->getMessage()); + } + } + + /** + * Process success response + * + * @param array $data Payment data. + * + * @return void + */ + public function successful_request( $data ): void { + 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->process_status( $processed_status, $data, $order ); + } catch ( Exception $e ) { + $this->set_response( 422, null, $e->getMessage() ); + $this->log->write_log( __FUNCTION__, $e->getMessage() ); + } + } + + /** + * Process status + * + * @param array $data Payment data. + * @param object $order Order. + * @return string + */ + public function process_status_mp_business( $data, $order ) { + $status = $data['status']; + try { + // Updates the type of gateway. + $this->update_meta( $order, '_used_gateway', get_class( $this->payment ) ); + + if ( ! empty( $data['payer']['email'] ) ) { + $this->update_meta( $order, __( 'Buyer email', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), $data['payer']['email'] ); + } + + if ( ! empty( $data['payments_details'] ) ) { + $payment_ids = array(); + + foreach ( $data['payments_details'] as $payment ) { + $payment_ids[] = $payment['id']; + + $this->update_meta( + $order, + 'Mercado Pago - Payment ' . $payment['id'], + '[Date ' . gmdate('Y-m-d H:i:s') . + ']/[Amount ' . $payment['total_amount'] . + ']/[Payment Type ' . $payment['payment_type_id'] . + ']/[Payment Method ' . $payment['payment_method_id'] . + ']/[Paid ' . $payment['paid_amount'] . + ']/[Coupon ' . $payment['coupon_amount'] . + ']/[Refund ' . $data['total_refunded'] . ']' + ); + $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - payment_type', $payment['payment_type_id']); + + if ( strpos($payment['payment_type_id'], 'card') !== false ) { + $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - installments', $payment['payment_method_info']['installments']); + $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - installment_amount', $payment['payment_method_info']['installment_amount']); + $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - transaction_amount', $payment['total_amount']); + $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - total_paid_amount', $payment['paid_amount']); + $this->update_meta($order, 'Mercado Pago - ' . $payment['id'] . ' - card_last_four_digits', $payment['payment_method_info']['last_four_digits']); + } + } + } + + if ( count( $payment_ids ) > 0 ) { + $this->update_meta( $order, '_Mercado_Pago_Payment_IDs', implode( ', ', $payment_ids ) ); + } + + $order->save(); + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, $e->getMessage() ); + } + + return $status; + } } diff --git a/includes/notification/class-wc-woomercadopago-notification-ipn.php b/includes/notification/class-wc-woomercadopago-notification-ipn.php index fe1ce4171..ba713413c 100644 --- a/includes/notification/class-wc-woomercadopago-notification-ipn.php +++ b/includes/notification/class-wc-woomercadopago-notification-ipn.php @@ -1,174 +1,167 @@ log->write_log( __FUNCTION__, 'No ID or TOPIC param in Request IPN.' ); - $this->set_response( 422, null, __( 'No ID or TOPIC param in Request IPN', 'woocommerce-mercadopago' ) ); - } - - if ( 'payment' === $data['topic'] || 'merchant_order' !== $data['topic'] ) { - $this->set_response( 200, null, __( 'Discarded notification. This notification is already processed as webhook-payment.', 'woocommerce-mercadopago' ) ); - } - - $access_token = $this->mp->get_access_token(); - if ( 'merchant_order' === $data['topic'] ) { - $merchant_order_id = preg_replace( '/[^\d]/', '', $data['id'] ); - - $ipn_info = $this->mp->get( - '/merchant_orders/' . $merchant_order_id, - array( 'Authorization' => 'Bearer ' . $access_token ), - false - ); - - if ( is_wp_error( $ipn_info ) || ( 200 !== $ipn_info['status'] && 201 !== $ipn_info['status'] ) ) { - $this->log->write_log( __FUNCTION__, ' IPN merchant_order not found ' . wp_json_encode( $ipn_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - $this->set_response( 422, null, __( 'IPN merchant_order not found', 'woocommerce-mercadopago' ) ); - } - - $payments = $ipn_info['response']['payments']; - if ( count( $payments ) < 1 ) { - $this->log->write_log( __FUNCTION__, 'Not found Payments into Merchant_Order' ); - $this->set_response( 422, null, __( 'Not found Payments into Merchant_Order', 'woocommerce-mercadopago' ) ); - } - - $ipn_info['response']['ipn_type'] = 'merchant_order'; - - /** - * Do action valid_mercadopago_ipn_request. - * - * @since 3.0.1 - */ - do_action( 'valid_mercadopago_ipn_request', $ipn_info['response'] ); - - $this->set_response( 200, 'OK', 'Notification IPN Successfull' ); - } - } - - /** - * Process success response - * - * @param array $data Payment data. - * - * @return bool|void|WC_Order|WC_Order_Refund - */ - 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->process_status( $processed_status, $data, $order ); - } catch ( Exception $e ) { - $this->set_response( 422, null, $e->getMessage() ); - $this->log->write_log( __FUNCTION__, $e->getMessage() ); - } - } - - /** - * Process status - * - * @param array $data Payment data. - * @param object $order Order. - * @return string - */ - public function process_status_mp_business( $data, $order ) { - $status = 'pending'; - $payments = $data['payments']; - - if ( is_array($payments) ) { - $total = $data['shipping_cost'] + $data['total_amount']; - $total_paid = 0.00; - $total_refund = 0.00; - // Grab some information... - foreach ( $data['payments'] as $payment ) { - $coupon_mp = $this->get_payment_info($payment['id']); - - if ( $coupon_mp > 0 ) { - $total_paid += (float) $coupon_mp; - } - - if ( 'approved' === $payment['status'] ) { - // Get the total paid amount, considering only approved incomings. - $total_paid += (float) $payment['total_paid_amount']; - } elseif ( 'refunded' === $payment['status'] ) { - // 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. - // Updates the type of gateway. - $order->update_meta_data( '_used_gateway', 'WC_WooMercadoPago_Basic_Gateway' ); - 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 type', 'woocommerce-mercadopago' ), $data['payment_type_id'] ); - } - if ( ! empty( $data['payment_method_id'] ) ) { - $order->update_meta_data( __( 'Payment method', 'woocommerce-mercadopago' ), $data['payment_method_id'] ); - } - if ( ! empty( $data['payments'] ) ) { - $payment_ids = array(); - foreach ( $data['payments'] as $payment ) { - $coupon_mp = $this->get_payment_info($payment['id']); - $payment_ids[] = $payment['id']; - $order->update_meta_data( - 'Mercado Pago - Payment ' . $payment['id'], - '[Date ' . gmdate( 'Y-m-d H:i:s', strtotime( $payment['date_created'] ) ) . - ']/[Amount ' . $payment['transaction_amount'] . - ']/[Paid ' . $payment['total_paid_amount'] . - ']/[Coupon ' . $coupon_mp . - ']/[Refund ' . $payment['amount_refunded'] . ']' - ); - } - if ( count( $payment_ids ) > 0 ) { - $order->update_meta_data( '_Mercado_Pago_Payment_IDs', implode( ', ', $payment_ids ) ); - } - } - $order->save(); - return $status; - } - public function get_payment_info( $id ) { - $payment_info = $this->mp->search_payment_v1($id); - $coupon_amount = (float) $payment_info['response']['coupon_amount']; - - return $coupon_amount; - } + /** + * IPN + */ + public function check_ipn_response(): void { + parent::check_ipn_response(); + + $data = $_GET; // phpcs:ignore WordPress.Security.NonceVerification + + if ( isset( $data['data_id'] ) && isset( $data['type'] ) ) { + status_header( 200, 'OK' ); + } + + if ( ! isset( $data['id'] ) || ! isset( $data['topic'] ) ) { + $this->log->write_log( __FUNCTION__, 'No ID or TOPIC param in Request IPN.' ); + $this->set_response( 422, null, __( 'No ID or TOPIC param in Request IPN', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + + if ( 'payment' === $data['topic'] || 'merchant_order' !== $data['topic'] ) { + $this->set_response( 200, null, __( 'Discarded notification. This notification is already processed as webhook-payment.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + + $access_token = $this->mp->get_access_token(); + if ( 'merchant_order' === $data['topic'] ) { + $merchant_order_id = preg_replace( '/[^\d]/', '', $data['id'] ); + + $ipn_info = $this->mp->get( + '/merchant_orders/' . $merchant_order_id, + array('Authorization' => 'Bearer ' . $access_token), + false + ); + + if ( is_wp_error( $ipn_info ) || ( 200 !== $ipn_info['status'] && 201 !== $ipn_info['status'] ) ) { + $this->log->write_log( __FUNCTION__, ' IPN merchant_order not found ' . wp_json_encode( $ipn_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + $this->set_response( 422, null, __( 'IPN merchant_order not found', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + + $payments = $ipn_info['response']['payments']; + if ( count( $payments ) < 1 ) { + $this->log->write_log( __FUNCTION__, 'Not found Payments into Merchant_Order' ); + $this->set_response( 422, null, __( 'Not found Payments into Merchant_Order', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + } + + $ipn_info['response']['ipn_type'] = 'merchant_order'; + + /** + * Do action valid_mercadopago_ipn_request. + * + * @since 3.0.1 + */ + do_action( 'valid_mercadopago_ipn_request', $ipn_info['response'] ); + + $this->set_response( 200, 'OK', 'Notification IPN Successfull' ); + } + } + + /** + * Process success response + * + * @param array $data Payment data. + * + * @return bool|void|WC_Order|WC_Order_Refund + */ + 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->process_status( $processed_status, $data, $order ); + } catch ( Exception $e ) { + $this->set_response( 422, null, $e->getMessage() ); + $this->log->write_log( __FUNCTION__, $e->getMessage() ); + } + } + + /** + * Process status + * + * @param array $data Payment data. + * @param object $order Order. + * @return string + */ + public function process_status_mp_business( $data, $order ) { + $status = 'pending'; + $payments = $data['payments']; + + if ( is_array($payments) ) { + $total = $data['shipping_cost'] + $data['total_amount']; + $total_paid = 0.00; + $total_refund = 0.00; + // Grab some information... + foreach ( $data['payments'] as $payment ) { + $coupon_mp = $this->get_payment_info($payment['id']); + + if ( $coupon_mp > 0 ) { + $total_paid += (float) $coupon_mp; + } + + if ( 'approved' === $payment['status'] ) { + // Get the total paid amount, considering only approved incomings. + $total_paid += (float) $payment['total_paid_amount']; + } elseif ( 'refunded' === $payment['status'] ) { + // 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. + // Updates the type of gateway. + $order->update_meta_data( '_used_gateway', 'WC_WooMercadoPago_Basic_Gateway' ); + if ( ! empty( $data['payer']['email'] ) ) { + $order->update_meta_data( __( 'Buyer email', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), $data['payer']['email'] ); + } + if ( ! empty( $data['payment_type_id'] ) ) { + $order->update_meta_data( __( 'Payment type', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), $data['payment_type_id'] ); + } + if ( ! empty( $data['payment_method_id'] ) ) { + $order->update_meta_data( __( 'Payment method', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), $data['payment_method_id'] ); + } + if ( ! empty( $data['payments'] ) ) { + $payment_ids = array(); + foreach ( $data['payments'] as $payment ) { + $coupon_mp = $this->get_payment_info($payment['id']); + $payment_ids[] = $payment['id']; + $order->update_meta_data( + 'Mercado Pago - Payment ' . $payment['id'], + '[Date ' . gmdate( 'Y-m-d H:i:s', strtotime( $payment['date_created'] ) ) . + ']/[Amount ' . $payment['transaction_amount'] . + ']/[Paid ' . $payment['total_paid_amount'] . + ']/[Coupon ' . $coupon_mp . + ']/[Refund ' . $payment['amount_refunded'] . ']' + ); + } + if ( count( $payment_ids ) > 0 ) { + $order->update_meta_data( '_Mercado_Pago_Payment_IDs', implode( ', ', $payment_ids ) ); + } + } + $order->save(); + return $status; + } + + public function get_payment_info( $id ) { + $payment_info = $this->mp->search_payment_v1($id); + $coupon_amount = (float) $payment_info['response']['coupon_amount']; + + return $coupon_amount; + } } diff --git a/includes/notification/class-wc-woomercadopago-notification-webhook.php b/includes/notification/class-wc-woomercadopago-notification-webhook.php index 560b54bfe..6612a2780 100644 --- a/includes/notification/class-wc-woomercadopago-notification-webhook.php +++ b/includes/notification/class-wc-woomercadopago-notification-webhook.php @@ -1,187 +1,180 @@ mp->check_discount_campaigns( $data['amount'], $data['payer'], $data['coupon_id'] ); - header( 'Content-Type: application/json' ); - echo wp_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 wp_json_encode( $obj ); - } - exit( 0 ); - } elseif ( ! isset( $data['data_id'] ) || ! isset( $data['type'] ) ) { - $this->log->write_log( - __FUNCTION__, - 'data_id or type not set: ' . - wp_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: ' . - wp_json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) - ); - $this->set_response( 422, null, 'Mercado Pago Request failure' ); - } - } else { - if ( 'payment' === $data['type'] ) { - $payment_id = preg_replace( '/[^\d]/', '', $data['data_id'] ); - $access_token = $this->mp->get_access_token(); + 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 wp_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', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'error' => 'payer_not_found', + 'status' => 404, + 'cause' => array(), + ); + header( 'HTTP/1.1 200 OK' ); + header( 'Content-Type: application/json' ); + echo wp_json_encode( $obj ); + } + exit( 0 ); + } + if ( ! isset( $data['data_id'] ) || ! isset( $data['type'] ) ) { + $this->log->write_log( + __FUNCTION__, + 'data_id or type not set: ' . + wp_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: ' . + wp_json_encode( $data, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) + ); + $this->set_response( 422, null, 'Mercado Pago Request failure' ); + } + } else { + if ( 'payment' === $data['type'] ) { + $payment_id = preg_replace( '/[^\d]/', '', $data['data_id'] ); + $access_token = $this->mp->get_access_token(); - $payment_info = $this->mp->get( - '/v1/payments/' . $payment_id, - array( 'Authorization' => 'Bearer ' . $access_token ), - false - ); + $payment_info = $this->mp->get( + '/v1/payments/' . $payment_id, + array('Authorization' => 'Bearer ' . $access_token), + false + ); - if ( ! is_wp_error( $payment_info ) && ( 200 === $payment_info['status'] || 201 === $payment_info['status'] ) ) { - if ( $payment_info['response'] ) { - /** - * Do action valid_mercadopago_ipn_request. - * - * @since 3.0.1 - */ - do_action( 'valid_mercadopago_ipn_request', $payment_info['response'] ); + if ( ! is_wp_error( $payment_info ) && ( 200 === $payment_info['status'] || 201 === $payment_info['status'] ) ) { + if ( $payment_info['response'] ) { + /** + * Do action valid_mercadopago_ipn_request. + * + * @since 3.0.1 + */ + do_action( 'valid_mercadopago_ipn_request', $payment_info['response'] ); - $this->set_response( 200, 'OK', 'Webhook Notification Successfull' ); - } - } else { - $this->log->write_log( __FUNCTION__, 'error when processing received data: ' . wp_json_encode( $payment_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - } - } - } - $this->set_response( 422, null, 'Mercado Pago Invalid Requisition' ); - } + $this->set_response( 200, 'OK', 'Webhook Notification Successfull' ); + } + } else { + $this->log->write_log( __FUNCTION__, 'error when processing received data: ' . wp_json_encode( $payment_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + } + } + } + $this->set_response( 422, null, 'Mercado Pago Invalid Requisition' ); + } - /** - * Process success response - * - * @param array $data Payment data. - * - * @return bool|void|WC_Order|WC_Order_Refund - */ - 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->process_status( $status, $data, $order ); - } catch ( Exception $e ) { - $this->log->write_log( __FUNCTION__, $e->getMessage() ); - } - } + /** + * Process success response + * + * @param array $data Payment data. + * + * @return bool|void|WC_Order|WC_Order_Refund + */ + 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->process_status( $status, $data, $order ); + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, $e->getMessage() ); + } + } - /** - * Check and save customer card - * - * @param array $checkout_info Checkout info. - */ - public function check_and_save_customer_card( $checkout_info ) { - $this->log->write_log( __FUNCTION__, 'checking info to create card: ' . wp_json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - $cost_id = null; - $token = null; - $issuer_id = null; - $payment_method_id = null; - if ( isset( $checkout_info['payer']['id'] ) && ! empty( $checkout_info['payer']['id'] ) ) { - $cost_id = $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( $cost_id, $token, $payment_method_id, $issuer_id ); - } catch ( WC_WooMercadoPago_Exception $ex ) { - $this->log->write_log( __FUNCTION__, 'card creation failed: ' . wp_json_encode( $ex, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - } - } + /** + * Check and save customer card + * + * @param array $checkout_info Checkout info. + */ + public function check_and_save_customer_card( $checkout_info ): void { + $this->log->write_log( __FUNCTION__, 'checking info to create card: ' . wp_json_encode( $checkout_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + $cost_id = null; + $token = null; + $issuer_id = null; + $payment_method_id = null; + if ( isset( $checkout_info['payer']['id'] ) && ! empty( $checkout_info['payer']['id'] ) ) { + $cost_id = $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( $cost_id, $token, $payment_method_id, $issuer_id ); + } catch ( WC_WooMercadoPago_Exception $ex ) { + $this->log->write_log( __FUNCTION__, 'card creation failed: ' . wp_json_encode( $ex, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + } + } - /** - * Process status mercado pago business - * - * @param array $data Payment data. - * @param object $order Order. - * - * @return mixed|string - */ - public function process_status_mp_business( $data, $order ) { - $status = $data['status'] ?? 'pending'; - $total_paid = $data['transaction_details']['total_paid_amount'] ?? 0.00; - $total_refund = $data['transaction_amount_refunded'] ?? 0.00; - $coupon_amount = $data['coupon_amount'] ?? 0.00; - // WooCommerce 3.0 or later. - // Updates the type of gateway. - $order->update_meta_data( '_used_gateway', get_class( $this->payment ) ); - 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 type', 'woocommerce-mercadopago' ), $data['payment_type_id'] ); - } - if ( ! empty( $data['payment_method_id'] ) ) { - $order->update_meta_data( __( 'Payment method', 'woocommerce-mercadopago' ), $data['payment_method_id'] ); - } - $order->update_meta_data( - 'Mercado Pago - Payment ' . $data['id'], - '[Date ' . gmdate( 'Y-m-d H:i:s', strtotime( $data['date_created'] ) ) . - ']/[Amount ' . $data['transaction_amount'] . - ']/[Paid ' . $total_paid . - ']/[Coupon ' . $coupon_amount . - ']/[Refund ' . $total_refund . ']' - ); - $order->update_meta_data( '_Mercado_Pago_Payment_IDs', $data['id'] ); - $order->save(); + /** + * Process status mercado pago business + * + * @param array $data Payment data. + * @param object $order Order. + * + * @return mixed|string + */ + public function process_status_mp_business( $data, $order ) { + $status = $data['status'] ?? 'pending'; + $total_paid = $data['transaction_details']['total_paid_amount'] ?? 0.00; + $total_refund = $data['transaction_amount_refunded'] ?? 0.00; + $coupon_amount = $data['coupon_amount'] ?? 0.00; + // WooCommerce 3.0 or later. + // Updates the type of gateway. + $order->update_meta_data( '_used_gateway', get_class( $this->payment ) ); + if ( ! empty( $data['payer']['email'] ) ) { + $order->update_meta_data( __( 'Buyer email', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), $data['payer']['email'] ); + } + if ( ! empty( $data['payment_type_id'] ) ) { + $order->update_meta_data( __( 'Payment type', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), $data['payment_type_id'] ); + } + if ( ! empty( $data['payment_method_id'] ) ) { + $order->update_meta_data( __( 'Payment method', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), $data['payment_method_id'] ); + } + $order->update_meta_data( + 'Mercado Pago - Payment ' . $data['id'], + '[Date ' . gmdate( 'Y-m-d H:i:s', strtotime( $data['date_created'] ) ) . + ']/[Amount ' . $data['transaction_amount'] . + ']/[Paid ' . $total_paid . + ']/[Coupon ' . $coupon_amount . + ']/[Refund ' . $total_refund . ']' + ); + $order->update_meta_data( '_Mercado_Pago_Payment_IDs', $data['id'] ); + $order->save(); - return $status; - } + return $status; + } } diff --git a/includes/notification/index.php b/includes/notification/index.php index 258f3fae9..891711d6d 100644 --- a/includes/notification/index.php +++ b/includes/notification/index.php @@ -1,12 +1,5 @@ id = self::ID; - $this->title = __('Checkout Pro', 'woocommerce-mercadopago'); - $this->title_gateway = __('Checkout Pro', 'woocommerce-mercadopago'); - $this->description = __('Debit, Credit and invoice in Mercado Pago environment', 'woocommerce-mercadopago'); - $this->mp_options = $this->get_mp_options(); - - if ( ! $this->validate_section() ) { - return; - } - - $this->form_fields = array(); - $this->method_title = __( 'Mercado Pago - Checkout Pro', 'woocommerce-mercadopago' ); - $this->method = $this->get_option_mp( 'method', 'redirect' ); - $this->title = $this->get_option_mp( 'title', __( 'Your saved cards or money in Mercado Pago', 'woocommerce-mercadopago' ) ); - $this->method_description = $this->description; - $this->auto_return = $this->get_option('auto_return', 'yes'); - $this->success_url = $this->get_option('success_url', ''); - $this->failure_url = $this->get_option('failure_url', ''); - $this->pending_url = $this->get_option('pending_url', ''); - $this->installments = $this->get_option('installments', '24'); - $this->gateway_discount = $this->get_option('gateway_discount', 0); - $this->clientid_old_version = $this->get_client_id(); - $this->field_forms_order = $this->get_fields_sequence(); - $this->ex_payments = $this->get_ex_payments(); - - parent::__construct(); - $this->credits_helper = new WC_WooMercadoPago_Helper_Credits(); - $this->form_fields = $this->get_form_mp_fields(); - $this->hook = new WC_WooMercadoPago_Hook_Basic($this); - $this->notification = new WC_WooMercadoPago_Notification_Core($this); - $this->currency_convertion = true; - $this->icon = $this->get_checkout_icon(); - } - - /** - * Get MP fields label - * - * @return array - */ - public function get_form_mp_fields() { - if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { - $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, - true - ); - } - - if ( empty( $this->checkout_country ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); - } - - if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); - } - - $form_fields = array(); - - if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { - $form_fields['checkout_header'] = $this->field_checkout_header(); - $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(); - $form_fields['ex_payments'] = $this->field_ex_payments(); - } - - $form_fields_abs = parent::get_form_mp_fields(); - if ( count($form_fields_abs) === 1 ) { - return $form_fields_abs; - } - $form_fields_merge = array_merge($form_fields_abs, $form_fields); - return $this->sort_form_fields($form_fields_merge, $this->field_forms_order); - } - - /** - * Get fields sequence - * - * @return array - */ - public function get_fields_sequence() { - return array( - // Necessary to run. - 'description', - // Checkout Básico. Acepta todos los medios de pago y lleva tus cobros a otro nivel. - 'checkout_header', - // No olvides de homologar tu cuenta. - 'checkout_card_homolog', - // Set up the payment experience in your store. - 'checkout_card_validate', - 'enabled', - 'title', - WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, - 'ex_payments', - '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', - ); - } - - /** - * Field Installments - * - * @return array - */ - public function field_installments() { - return array( - 'title' => __('Maximum number of installments', 'woocommerce-mercadopago'), - 'type' => 'select', - 'description' => __('What is the maximum quota with which a customer can buy?', 'woocommerce-mercadopago'), - 'default' => '24', - 'options' => array( - '1' => __('1 installment', 'woocommerce-mercadopago'), - '2' => __('2 installments', 'woocommerce-mercadopago'), - '3' => __('3 installments', 'woocommerce-mercadopago'), - '4' => __('4 installments', 'woocommerce-mercadopago'), - '5' => __('5 installments', 'woocommerce-mercadopago'), - '6' => __('6 installments', 'woocommerce-mercadopago'), - '10' => __('10 installments', 'woocommerce-mercadopago'), - '12' => __('12 installments', 'woocommerce-mercadopago'), - '15' => __('15 installments', 'woocommerce-mercadopago'), - '18' => __('18 installments', 'woocommerce-mercadopago'), - '24' => __('24 installments', 'woocommerce-mercadopago'), - ), - ); - } - - /** - * Is available? - * - * @return bool - * @throws WC_WooMercadoPago_Exception Load access token exception. - */ - public function is_available() { - if ( parent::is_available() ) { - return true; - } - - if ( isset($this->settings['enabled']) && 'yes' === $this->settings['enabled'] ) { - if ( $this->mp instanceof MP ) { - $access_token = $this->mp->get_access_token(); - if ( - false === WC_WooMercadoPago_Credentials::validate_credentials_test($this->mp, $access_token) - && true === $this->sandbox - ) { - return false; - } - - if ( - false === WC_WooMercadoPago_Credentials::validate_credentials_prod($this->mp, $access_token) - && false === $this->sandbox - ) { - return false; - } - return true; - } - } - return false; - } - - /** - * Get clientID when update version 3.0.17 to 4 latest - * - * @return string - */ - public function get_client_id() { - $client_id = $this->mp_options->get_client_id(); - if ( ! empty($client_id) ) { - return true; - } - return false; - } - - /** - * Get Payments - * - * @return array - */ - private function get_ex_payments() { - $ex_payments = array(); - $get_ex_payment_options = get_option('_all_payment_methods_v0', ''); - if ( ! empty($get_ex_payment_options) ) { - $options = explode(',', $get_ex_payment_options); - foreach ( $options as $option ) { - if ( 'no' === $this->get_option('ex_payments_' . $option, 'yes') ) { - $ex_payments[] = $option; - } - } - } - return $ex_payments; - } - - /** - * Field enabled - * - * @return array - */ - public function field_enabled() { - return array( - 'title' => __('Enable the checkout', 'woocommerce-mercadopago'), - 'subtitle' => __('By disabling it, you will disable all payments from Mercado Pago Checkout at Mercado Pago website by redirect.', 'woocommerce-mercadopago'), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'descriptions' => array( - 'enabled' => __('The checkout is enabled.', 'woocommerce-mercadopago'), - 'disabled' => __('The checkout is disabled.', 'woocommerce-mercadopago'), - ), - ); - } - - /** - * Field checkout header - * - * @return array - */ - public function field_checkout_header() { - return array( - 'title' => sprintf( - '
+ /** + * ID + * + * @const + */ + public const ID = 'woo-mercado-pago-basic'; + + /** + * Credits Helper Class + * + * @var WC_WooMercadoPago_Helper_Credits + */ + private $credits_helper; + + /** + * WC_WooMercadoPago_BasicGateway constructor. + * + * @throws WC_WooMercadoPago_Exception On load payment exception. + */ + public function __construct() { + $this->id = self::ID; + $this->title = __('Checkout Pro', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + $this->title_gateway = __('Checkout Pro', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + $this->description = __('Debit, Credit and invoice in Mercado Pago environment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + $this->mp_options = $this->get_mp_options(); + + if ( ! $this->validate_section() ) { + return; + } + + $this->form_fields = array(); + $this->method_title = __( 'Mercado Pago - Checkout Pro', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->method = $this->get_option_mp( 'method', 'redirect' ); + $this->title = $this->get_option_mp( 'title', __( 'Your saved cards or money in Mercado Pago', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + $this->method_description = $this->description; + $this->auto_return = $this->get_option('auto_return', 'yes'); + $this->success_url = $this->get_option('success_url', ''); + $this->failure_url = $this->get_option('failure_url', ''); + $this->pending_url = $this->get_option('pending_url', ''); + $this->installments = $this->get_option('installments', '24'); + $this->gateway_discount = $this->get_option('gateway_discount', 0); + $this->clientid_old_version = $this->get_client_id(); + $this->field_forms_order = $this->get_fields_sequence(); + $this->ex_payments = $this->get_ex_payments(); + + parent::__construct(); + $this->credits_helper = new WC_WooMercadoPago_Helper_Credits(); + $this->form_fields = $this->get_form_mp_fields(); + $this->hook = new WC_WooMercadoPago_Hook_Basic($this); + $this->notification = new WC_WooMercadoPago_Notification_Core($this); + $this->currency_convertion = true; + $this->icon = $this->get_checkout_icon(); + } + + /** + * Get MP fields label + * + * @return array + */ + public function get_form_mp_fields() { + if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { + $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, + true + ); + } + + if ( empty( $this->checkout_country ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); + } + + if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); + } + + $form_fields = array(); + + if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { + $form_fields['checkout_header'] = $this->field_checkout_header(); + $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(); + $form_fields['ex_payments'] = $this->field_ex_payments(); + } + + $form_fields_abs = parent::get_form_mp_fields(); + if ( count($form_fields_abs) === 1 ) { + return $form_fields_abs; + } + $form_fields_merge = array_merge($form_fields_abs, $form_fields); + return $this->sort_form_fields($form_fields_merge, $this->field_forms_order); + } + + /** + * Get fields sequence + * + * @return array + */ + public function get_fields_sequence() { + return array( + // Necessary to run. + 'description', + // Checkout Básico. Acepta todos los medios de pago y lleva tus cobros a otro nivel. + 'checkout_header', + // No olvides de homologar tu cuenta. + 'checkout_card_homolog', + // Set up the payment experience in your store. + 'checkout_card_validate', + 'enabled', + 'title', + WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, + 'ex_payments', + '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', + ); + } + + /** + * Field Installments + * + * @return array + */ + public function field_installments() { + return array( + 'title' => __('Maximum number of installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'select', + 'description' => __('What is the maximum quota with which a customer can buy?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'default' => '24', + 'options' => array( + '1' => __('1 installment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '2' => __('2 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '3' => __('3 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '4' => __('4 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '5' => __('5 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '6' => __('6 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '10' => __('10 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '12' => __('12 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '15' => __('15 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '18' => __('18 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + '24' => __('24 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + ), + ); + } + + /** + * Is available? + * + * @return bool + * @throws WC_WooMercadoPago_Exception Load access token exception. + */ + public function is_available() { + if ( parent::is_available() ) { + return true; + } + + if ( isset($this->settings['enabled']) && 'yes' === $this->settings['enabled'] ) { + if ( $this->mp instanceof MP ) { + $access_token = $this->mp->get_access_token(); + if ( + false === WC_WooMercadoPago_Credentials::validate_credentials_test($this->mp, $access_token) + && true === $this->sandbox + ) { + return false; + } + + if ( + false === WC_WooMercadoPago_Credentials::validate_credentials_prod($this->mp, $access_token) + && false === $this->sandbox + ) { + return false; + } + return true; + } + } + return false; + } + + /** + * Get clientID when update version 3.0.17 to 4 latest + * + * @return string + */ + public function get_client_id() { + $client_id = $this->mp_options->get_client_id(); + if ( ! empty($client_id) ) { + return true; + } + return false; + } + + /** + * Get Payments + * + * @return array + */ + private function get_ex_payments() { + $ex_payments = array(); + $get_ex_payment_options = get_option('_all_payment_methods_v0', ''); + if ( ! empty($get_ex_payment_options) ) { + $options = explode(',', $get_ex_payment_options); + foreach ( $options as $option ) { + if ( 'no' === $this->get_option('ex_payments_' . $option, 'yes') ) { + $ex_payments[] = $option; + } + } + } + return $ex_payments; + } + + /** + * Field enabled + * + * @return array + */ + public function field_enabled() { + return array( + 'title' => __('Enable the checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('By disabling it, you will disable all payments from Mercado Pago Checkout at Mercado Pago website by redirect.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'descriptions' => array( + 'enabled' => __('The checkout is enabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'disabled' => __('The checkout is disabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + ), + ); + } + + /** + * Field checkout header + * + * @return array + */ + public function field_checkout_header() { + return array( + 'title' => sprintf( + '
- ' . __('Checkout Pro', 'woocommerce-mercadopago') . ' + ' . __('Checkout Pro', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . '

- ' . __('With Checkout Pro you sell with all the safety inside Mercado Pago environment.', 'woocommerce-mercadopago') . ' + ' . __('With Checkout Pro you sell with all the safety inside Mercado Pago environment.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . '

' - ), - 'type' => 'title', - 'class' => 'mp_title_header', - ); - } - - /** - * Field checkout payments advanced title - * - * @return array - */ - public function field_checkout_payments_advanced_title() { - return array( - 'title' => __('Advanced settings', 'woocommerce-mercadopago'), - 'type' => 'title', - 'class' => 'mp_subtitle_bd', - ); - } - - /** - * Field method - * - * @return array - */ - public function field_method() { - return 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' => ( 'iframe' === $this->method ) ? 'redirect' : $this->method, - 'options' => array( - 'redirect' => __('Redirect', 'woocommerce-mercadopago'), - 'modal' => __('Modal', 'woocommerce-mercadopago'), - ), - ); - } - - /** - * Field success url - * - * @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'); - } - return array( - 'title' => __('Success URL', 'woocommerce-mercadopago'), - 'type' => 'text', - 'description' => $success_back_url_message, - 'default' => '', - ); - } - - /** - * Field failure 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'); - } - return array( - 'title' => __('Payment URL rejected', 'woocommerce-mercadopago'), - 'type' => 'text', - 'description' => $fail_back_url_message, - 'default' => '', - ); - } - - /** - * Field pending - * - * @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'); - } - return array( - 'title' => __('Payment URL pending', 'woocommerce-mercadopago'), - 'type' => 'text', - 'description' => $pending_back_url_message, - 'default' => '', - ); - } - - /** - * Field payments - * - * @return array - */ - public function field_ex_payments() { - $payment_list = array( - 'description' => __('Enable the payment methods available to your clients.', 'woocommerce-mercadopago'), - 'title' => __('Choose the payment methods you accept in your store', 'woocommerce-mercadopago'), - 'type' => 'mp_checkbox_list', - 'payment_method_types' => array( - 'credit_card' => array( - 'label' => __('Credit Cards', 'woocommerce-mercadopago'), - 'list' => array(), - ), - 'debit_card' => array( - 'label' => __('Debit Cards', 'woocommerce-mercadopago'), - 'list' => array(), - ), - 'other' => array( - 'label' => __('Other Payment Methods', 'woocommerce-mercadopago'), - 'list' => array(), - ), - ), - ); - - $all_payments = get_option('_checkout_payments_methods', ''); - - if ( empty($all_payments) ) { - return $payment_list; - } - - foreach ( $all_payments as $payment_method ) { - if ( 'credit_card' === $payment_method['type'] ) { - $payment_list['payment_method_types']['credit_card']['list'][] = array( - 'id' => 'ex_payments_' . $payment_method['id'], - 'field_key' => $this->get_field_key('ex_payments_' . $payment_method['id']), - 'label' => $payment_method['name'], - 'value' => $this->get_option('ex_payments_' . $payment_method['id'], 'yes'), - 'type' => 'checkbox', - ); - } elseif ( 'debit_card' === $payment_method['type'] || 'prepaid_card' === $payment_method['type'] ) { - $payment_list['payment_method_types']['debit_card']['list'][] = array( - 'id' => 'ex_payments_' . $payment_method['id'], - 'field_key' => $this->get_field_key('ex_payments_' . $payment_method['id']), - 'label' => $payment_method['name'], - 'value' => $this->get_option('ex_payments_' . $payment_method['id'], 'yes'), - 'type' => 'checkbox', - ); - } else { - $payment_list['payment_method_types']['other']['list'][] = array( - 'id' => 'ex_payments_' . $payment_method['id'], - 'field_key' => $this->get_field_key('ex_payments_' . $payment_method['id']), - 'label' => $payment_method['name'], - 'value' => $this->get_option('ex_payments_' . $payment_method['id'], 'yes'), - 'type' => 'checkbox', - ); - } - } - - return $payment_list; - } - - /** - * Field auto return - * - * @return array - */ - public function field_auto_return() { - return array( - 'title' => __('Return to the store', 'woocommerce-mercadopago'), - 'subtitle' => __('Do you want your customer to automatically return to the store after payment?', 'woocommerce-mercadopago'), - 'type' => 'mp_toggle_switch', - 'default' => 'yes', - 'descriptions' => array( - 'enabled' => __('The buyer will be automatically redirected to the store.', 'woocommerce-mercadopago'), - 'disabled' => __('The buyer will not be automatically redirected to the store.', 'woocommerce-mercadopago'), - ), - ); - } - - /** - * Payment Fields - */ - public function payment_fields() { - $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; - - // add css. - wp_enqueue_style( - 'woocommerce-mercadopago-narciso-styles', - plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - - // validate active payments methods. - $method = $this->get_option_mp( 'method', 'redirect' ); - $test_mode_link = $this->get_mp_devsite_link( $this->checkout_country ); - $site = strtoupper( $this->mp_options->get_site_id() ); - - $payment_methods = $this->get_payment_methods(); - $payment_methods_title = count($payment_methods) !== 0 ? __('Available payment methods', 'woocommerce-mercadopago') : ''; - - $checkout_benefits_items = $this->get_benefits( $site ); - - $parameters = [ - 'method' => $method, - 'test_mode' => ! $this->is_production_mode(), - 'test_mode_link' => $test_mode_link, - 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, - 'checkout_redirect_src' => plugins_url( '../assets/images/cho-pro-redirect-v2.png', plugin_dir_path( __FILE__ ) ), - 'payment_methods' => wp_json_encode( $payment_methods ), - 'payment_methods_title' => $payment_methods_title, - 'checkout_benefits_items' => wp_json_encode( $checkout_benefits_items ) - ]; - - $parameters = array_merge( $parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions() ); - wc_get_template( 'checkout/basic-checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); - } - - /** - * Process payment - * - * @param int $order_id Order Id. - * @return array - */ - public function process_payment( $order_id ) { - $order = wc_get_order($order_id); - $amount = $this->get_order_total(); - $shipping_taxes = floatval($order->get_shipping_total()); - - $order->update_meta_data('is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no'); - $order->update_meta_data('_used_gateway', get_class($this)); - - if ( ! empty($this->gateway_discount) ) { - $discount = ( $amount - $shipping_taxes ) * $this->gateway_discount / 100; - $order->update_meta_data('Mercado Pago: discount', __('discount of', 'woocommerce-mercadopago') . ' ' . $this->gateway_discount . '% / ' . __('discount of', 'woocommerce-mercadopago') . ' = ' . $discount); - $order->set_total($amount - $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(); - - 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), - ); - } - } - - /** - * Create preference - * - * @param object $order Order. - * @return bool - */ - public function create_preference( $order ) { - $preference_basic = new WC_WooMercadoPago_Preference_Basic( $this, $order ); - $preference = $preference_basic->get_transaction( 'Preference' ); - - try { - $checkout_info = $preference->save(); - $this->log->write_log( __FUNCTION__, 'Created Preference: ' . wp_json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - return ( $this->sandbox ) ? $checkout_info['sandbox_init_point'] : $checkout_info['init_point']; - } catch ( Exception $e ) { - $this->log->write_log( __FUNCTION__, 'preference creation failed with error: ' . $e->getMessage() ); - return false; - } - } - - /** - * Get Id - * - * @return string - */ - public static function get_id() { - return self::ID; - } - - /** - * Get Mercado Pago Icon - * - * @return mixed - */ - public function get_checkout_icon() { - /** - * Add Mercado Pago icon. - * - * @since 3.0.1 - */ - return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/mercadopago.png', plugin_dir_path( __FILE__ ) ) ); - } - - /** - * Get payment methods - * - * @return array - */ - public function get_payment_methods() { - $payment_methods_options = get_option( '_checkout_payments_methods', '' ); - $payment_methods = []; - - if ( $this->credits_helper->is_credits() ) { - $payment_methods[] = [ - 'src' => plugins_url( '../assets/images/mercado-credito.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Credits image' - ]; - } - - foreach ( $payment_methods_options as $payment_method_option ) { - if ( 'yes' === $this->get_option_mp( $payment_method_option[ 'config' ], '' ) ) { - $payment_methods[] = [ - 'src' => $payment_method_option[ 'image' ], - 'alt' => $payment_method_option[ 'id' ] - ]; - } - } - - return $payment_methods; - } - - /** - * Get benefits items - * - * @param string $site - * @return array - */ - public function get_benefits( $site ) { - $benefits = array( - 'MLB' => array( - array( - 'title' => __('Easy login', 'woocommerce-mercadopago'), - 'subtitle' => __('Log in with the same email and password you use in Mercado Libre.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-phone.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue phone image' - ) - ), - array( - 'title' => __('Quick payments', 'woocommerce-mercadopago'), - 'subtitle' => __('Use your saved cards, Pix or available balance.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-wallet.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue wallet image' - ) - ), - array( - 'title' => __('Protected purchases', 'woocommerce-mercadopago'), - 'subtitle' => __('Get your money back in case you don\'t receive your product.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-protection.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue protection image' - ) - ) - ), - 'MLM' => array( - array( - 'title' => __('Easy login', 'woocommerce-mercadopago'), - 'subtitle' => __('Log in with the same email and password you use in Mercado Libre.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-phone.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue phone image' - ) - ), - array( - 'title' => __('Quick payments', 'woocommerce-mercadopago'), - 'subtitle' => __('Use your available Mercado Pago Wallet balance or saved cards.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-wallet.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue wallet image' - ) - ), - array( - 'title' => __('Protected purchases', 'woocommerce-mercadopago'), - 'subtitle' => __('Get your money back in case you don\'t receive your product.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-protection.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue protection image' - ) - ) - ), - 'MLA' => array( - array( - 'title' => __('Quick payments', 'woocommerce-mercadopago'), - 'subtitle' => __('Use your available money or saved cards.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-wallet.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue wallet image' - ) - ), - array( - 'title' => __('Installments option', 'woocommerce-mercadopago'), - 'subtitle' => __('Pay with or without a credit card.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-phone-installments.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue phone installments image' - ) - ), - array( - 'title' => __('Reliable purchases', 'woocommerce-mercadopago'), - 'subtitle' => __('Get help if you have a problem with your purchase.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-protection.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue protection image' - ) - ) - ), - 'ROLA' => array( - array( - 'title' => __('Easy login', 'woocommerce-mercadopago'), - 'subtitle' => __('Log in with the same email and password you use in Mercado Libre.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-phone.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue phone image' - ) - ), - array( - 'title' => __('Quick payments', 'woocommerce-mercadopago'), - 'subtitle' => __('Use your available money or saved cards.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-wallet.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue wallet image' - ) - ), - array( - 'title' => __('Installments option', 'woocommerce-mercadopago'), - 'subtitle' => __('Interest-free installments with selected banks.', 'woocommerce-mercadopago'), - 'image' => array( - 'src' => plugins_url( '../assets/images/blue-phone-installments.png', plugin_dir_path(__FILE__) ), - 'alt' => 'Blue phone installments image' - ) - ) - ), - ); - - return array_key_exists( $site, $benefits ) ? $benefits[ $site ] : $benefits[ 'ROLA' ]; - } + ), + 'type' => 'title', + 'class' => 'mp_title_header', + ); + } + + /** + * Field checkout payments advanced title + * + * @return array + */ + public function field_checkout_payments_advanced_title() { + return array( + 'title' => __('Advanced settings', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'title', + 'class' => 'mp_subtitle_bd', + ); + } + + /** + * Field method + * + * @return array + */ + public function field_method() { + return array( + 'title' => __('Payment experience', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'select', + 'description' => __('Define what payment experience your customers will have, whether inside or outside your store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'default' => ( 'iframe' === $this->method ) ? 'redirect' : $this->method, + 'options' => array( + 'redirect' => __('Redirect', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'modal' => __('Modal', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + ), + ); + } + + /** + * Field success url + * + * @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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' '; + } else { + $success_back_url_message = __('Choose the URL that we will show your customers when they finish their purchase.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + } + return array( + 'title' => __('Success URL', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'text', + 'description' => $success_back_url_message, + 'default' => '', + ); + } + + /** + * Field failure 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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' '; + } 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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + } + return array( + 'title' => __('Payment URL rejected', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'text', + 'description' => $fail_back_url_message, + 'default' => '', + ); + } + + /** + * Field pending + * + * @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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' '; + } else { + $pending_back_url_message = __('Choose the URL that we will show to your customers when they have a payment pending approval.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + } + return array( + 'title' => __('Payment URL pending', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'text', + 'description' => $pending_back_url_message, + 'default' => '', + ); + } + + /** + * Field payments + * + * @return array + */ + public function field_ex_payments() { + $payment_list = array( + 'description' => __('Enable the payment methods available to your clients.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'title' => __('Choose the payment methods you accept in your store', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'mp_checkbox_list', + 'payment_method_types' => array( + 'credit_card' => array( + 'label' => __('Credit Cards', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'list' => array(), + ), + 'debit_card' => array( + 'label' => __('Debit Cards', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'list' => array(), + ), + 'other' => array( + 'label' => __('Other Payment Methods', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'list' => array(), + ), + ), + ); + + $all_payments = get_option('_checkout_payments_methods', ''); + + if ( empty($all_payments) ) { + return $payment_list; + } + + foreach ( $all_payments as $payment_method ) { + if ( 'credit_card' === $payment_method['type'] ) { + $payment_list['payment_method_types']['credit_card']['list'][] = array( + 'id' => 'ex_payments_' . $payment_method['id'], + 'field_key' => $this->get_field_key('ex_payments_' . $payment_method['id']), + 'label' => $payment_method['name'], + 'value' => $this->get_option('ex_payments_' . $payment_method['id'], 'yes'), + 'type' => 'checkbox', + ); + } elseif ( 'debit_card' === $payment_method['type'] || 'prepaid_card' === $payment_method['type'] ) { + $payment_list['payment_method_types']['debit_card']['list'][] = array( + 'id' => 'ex_payments_' . $payment_method['id'], + 'field_key' => $this->get_field_key('ex_payments_' . $payment_method['id']), + 'label' => $payment_method['name'], + 'value' => $this->get_option('ex_payments_' . $payment_method['id'], 'yes'), + 'type' => 'checkbox', + ); + } else { + $payment_list['payment_method_types']['other']['list'][] = array( + 'id' => 'ex_payments_' . $payment_method['id'], + 'field_key' => $this->get_field_key('ex_payments_' . $payment_method['id']), + 'label' => $payment_method['name'], + 'value' => $this->get_option('ex_payments_' . $payment_method['id'], 'yes'), + 'type' => 'checkbox', + ); + } + } + + return $payment_list; + } + + /** + * Field auto return + * + * @return array + */ + public function field_auto_return() { + return array( + 'title' => __('Return to the store', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Do you want your customer to automatically return to the store after payment?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'mp_toggle_switch', + 'default' => 'yes', + 'descriptions' => array( + 'enabled' => __('The buyer will be automatically redirected to the store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'disabled' => __('The buyer will not be automatically redirected to the store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + ), + ); + } + + /** + * Payment Fields + */ + public function payment_fields(): void { + $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; + + // add css. + wp_enqueue_style( + 'woocommerce-mercadopago-narciso-styles', + plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + + // validate active payments methods. + $method = $this->get_option_mp( 'method', 'redirect' ); + $test_mode_link = $this->get_mp_devsite_link( $this->checkout_country ); + $site = strtoupper( $this->mp_options->get_site_id() ); + + $payment_methods = $this->get_payment_methods(); + $payment_methods_title = count($payment_methods) !== 0 ? __('Available payment methods', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) : ''; + + $checkout_benefits_items = $this->get_benefits( $site ); + + $parameters = array( + 'method' => $method, + 'test_mode' => ! $this->is_production_mode(), + 'test_mode_link' => $test_mode_link, + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'checkout_redirect_src' => plugins_url( '../assets/images/cho-pro-redirect-v2.png', plugin_dir_path( __FILE__ ) ), + 'payment_methods' => wp_json_encode( $payment_methods ), + 'payment_methods_title' => $payment_methods_title, + 'checkout_benefits_items' => wp_json_encode( $checkout_benefits_items ) + ); + + $parameters = array_merge( $parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions() ); + wc_get_template( 'checkout/basic-checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); + } + + /** + * Process payment + * + * @param int $order_id Order Id. + * @return array + */ + public function process_payment( $order_id ) { + $order = wc_get_order($order_id); + $amount = $this->get_order_total(); + $shipping_taxes = (float) ($order->get_shipping_total()); + + $order->update_meta_data('is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no'); + $order->update_meta_data('_used_gateway', get_class($this)); + + if ( ! empty($this->gateway_discount) ) { + $discount = ( $amount - $shipping_taxes ) * $this->gateway_discount / 100; + $order->update_meta_data('Mercado Pago: discount', __('discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' ' . $this->gateway_discount . '% / ' . __('discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' = ' . $discount); + $order->set_total($amount - $discount); + } + + if ( ! empty($this->commission) ) { + $comission = $amount * ( $this->commission / 100 ); + $order->update_meta_data('Mercado Pago: comission', __('fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' ' . $this->commission . '% / ' . __('fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' = ' . $comission); + } + $order->save(); + + 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), + ); + } + if ( '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), + ); + } + } + + /** + * Create preference + * + * @param object $order Order. + * @return bool + */ + public function create_preference( $order ) { + $preference_basic = new WC_WooMercadoPago_Preference_Basic( $this, $order ); + $preference = $preference_basic->get_transaction( 'Preference' ); + + try { + $checkout_info = $preference->save(); + $this->log->write_log( __FUNCTION__, 'Created Preference: ' . wp_json_encode( $checkout_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + return ( $this->sandbox ) ? $checkout_info['sandbox_init_point'] : $checkout_info['init_point']; + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, 'preference creation failed with error: ' . $e->getMessage() ); + return false; + } + } + + /** + * Get Id + * + * @return string + */ + public static function get_id() { + return self::ID; + } + + /** + * Get Mercado Pago Icon + * + * @return mixed + */ + public function get_checkout_icon() { + /** + * Add Mercado Pago icon. + * + * @since 3.0.1 + */ + return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/mercadopago.png', plugin_dir_path( __FILE__ ) ) ); + } + + /** + * Get payment methods + * + * @return array + */ + public function get_payment_methods() { + $payment_methods_options = get_option( '_checkout_payments_methods', '' ); + $payment_methods = array(); + + if ( $this->credits_helper->is_credits() ) { + $payment_methods[] = array( + 'src' => plugins_url( '../assets/images/mercado-credito.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Credits image' + ); + } + + foreach ( $payment_methods_options as $payment_method_option ) { + if ( 'yes' === $this->get_option_mp( $payment_method_option[ 'config' ], '' ) ) { + $payment_methods[] = array( + 'src' => $payment_method_option[ 'image' ], + 'alt' => $payment_method_option[ 'id' ] + ); + } + } + + return $payment_methods; + } + + /** + * Get benefits items + * + * @param string $site + * @return array + */ + public function get_benefits( $site ) { + $benefits = array( + 'MLB' => array( + array( + 'title' => __('Easy login', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Log in with the same email and password you use in Mercado Libre.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-phone.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue phone image' + ) + ), + array( + 'title' => __('Quick payments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Use your saved cards, Pix or available balance.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-wallet.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue wallet image' + ) + ), + array( + 'title' => __('Protected purchases', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Get your money back in case you don\'t receive your product.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-protection.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue protection image' + ) + ) + ), + 'MLM' => array( + array( + 'title' => __('Easy login', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Log in with the same email and password you use in Mercado Libre.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-phone.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue phone image' + ) + ), + array( + 'title' => __('Quick payments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Use your available Mercado Pago Wallet balance or saved cards.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-wallet.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue wallet image' + ) + ), + array( + 'title' => __('Protected purchases', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Get your money back in case you don\'t receive your product.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-protection.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue protection image' + ) + ) + ), + 'MLA' => array( + array( + 'title' => __('Quick payments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Use your available money or saved cards.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-wallet.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue wallet image' + ) + ), + array( + 'title' => __('Installments option', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Pay with or without a credit card.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-phone-installments.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue phone installments image' + ) + ), + array( + 'title' => __('Reliable purchases', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Get help if you have a problem with your purchase.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-protection.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue protection image' + ) + ) + ), + 'ROLA' => array( + array( + 'title' => __('Easy login', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Log in with the same email and password you use in Mercado Libre.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-phone.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue phone image' + ) + ), + array( + 'title' => __('Quick payments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Use your available money or saved cards.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-wallet.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue wallet image' + ) + ), + array( + 'title' => __('Installments option', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Interest-free installments with selected banks.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => array( + 'src' => plugins_url( '../assets/images/blue-phone-installments.png', plugin_dir_path(__FILE__) ), + 'alt' => 'Blue phone installments image' + ) + ) + ), + ); + + return array_key_exists( $site, $benefits ) ? $benefits[ $site ] : $benefits[ 'ROLA' ]; + } } diff --git a/includes/payments/class-wc-woomercadopago-credits-gateway.php b/includes/payments/class-wc-woomercadopago-credits-gateway.php index bad7c0f61..af3413f69 100755 --- a/includes/payments/class-wc-woomercadopago-credits-gateway.php +++ b/includes/payments/class-wc-woomercadopago-credits-gateway.php @@ -1,502 +1,504 @@ id = self::ID; - $this->title = __('Installments without card', 'woocommerce-mercadopago'); - $this->title_gateway = __('Installments without card', 'woocommerce-mercadopago'); - $this->description = __('Customers who buy on spot and pay later in up to 12 installments', 'woocommerce-mercadopago'); - $this->mp_options = $this->get_mp_options(); - - if ( ! $this->validate_section() ) { - return; - } - - add_action( 'admin_enqueue_scripts', [$this, 'load_admin_scripts'] ); - - $this->form_fields = array(); - $this->method_title = __( 'Mercado Pago - Installments without card', 'woocommerce-mercadopago' ); - $this->method = $this->get_option_mp( 'method', 'redirect' ); - $this->title = $this->get_option_mp( 'title', __( 'Checkout without card', 'woocommerce-mercadopago' ) ); - $this->method_description = $this->description; - $this->credits_banner = $this->get_option('credits_banner', 'no'); - $this->gateway_discount = $this->get_option('gateway_discount', 0); - $this->clientid_old_version = $this->get_client_id(); - $this->field_forms_order = $this->get_fields_sequence(); - - parent::__construct(); - $this->form_fields = $this->get_form_mp_fields(); - $this->hook = new WC_WooMercadoPago_Hook_Credits($this); - $this->notification = new WC_WooMercadoPago_Notification_Core($this); - $this->currency_convertion = true; - $this->icon = $this->get_checkout_icon(); - } - - public function load_admin_scripts() { - if ( is_admin() && $this->is_manage_section() && ( - WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || - WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') - ) ) { - $siteId = strtolower( $this->mp_options->get_site_id() ); - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - - wp_enqueue_style( - 'woocommerce-mercadopago-info-admin-credits-style', - plugins_url( '../assets/css/credits/example-info' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - - wp_enqueue_script( - 'woocommerce-mercadopago-credits-config-script', - plugins_url( '../assets/js/credits_config_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - - wp_enqueue_script( - 'woocommerce-mercadopago-info-admin-credits-script', - plugins_url( '../assets/js/credits/example-info' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - - wp_localize_script( - 'woocommerce-mercadopago-info-admin-credits-script', - 'wc_mp_icon_images', - array( - 'computerBlueIcon' => plugins_url( '../assets/images/credits/desktop-blue-icon.png', plugin_dir_path( __FILE__ ) ), - 'computerGrayIcon' => plugins_url( '../assets/images/credits/desktop-gray-icon.png', plugin_dir_path( __FILE__ ) ), - 'cellphoneBlueIcon' => plugins_url( '../assets/images/credits/cellphone-blue-icon.png', plugin_dir_path( __FILE__ ) ), - 'cellphoneGrayIcon' => plugins_url( '../assets/images/credits/cellphone-gray-icon.png', plugin_dir_path( __FILE__ ) ), - 'viewMobile' => plugins_url( $this->get_mercado_credits_gif_path( $siteId, 'mobile' ), plugin_dir_path( __FILE__ ) ), - 'viewDesktop' => plugins_url( $this->get_mercado_credits_gif_path( $siteId, 'desktop' ), plugin_dir_path( __FILE__ ) ), - 'footerDesktop' => __( 'Banner on the product page | Computer version', 'woocommerce-mercadopago' ), - 'footerCellphone' => __( 'Banner on the product page | Cellphone version', 'woocommerce-mercadopago' ), - ) - ); - } - } - - /** - * Get MP fields label - * - * @return array - */ - public function get_form_mp_fields() { - if ( empty( $this->checkout_country ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); - } - - if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); - } - - $form_fields = array(); - - if ( - ! empty( $this->checkout_country ) && - ! empty( $this->get_access_token() ) && - ! empty( $this->get_public_key() ) - ) { - $form_fields['checkout_header'] = $this->field_checkout_header(); - $form_fields['checkout_payments_advanced_title'] = $this->field_checkout_payments_advanced_title(); - $form_fields['credits_banner'] = $this->field_credits_banner_mode(); - $form_fields['checkout_visualization_title'] = $this->title_separator(); - $form_fields['checkout_visualization'] = $this->field_checkout_visualization(); - $form_fields['checkout_banner_title'] = $this->title_separator(); - $form_fields['credits_banner_visualization'] = $this->field_credits_banner_visualization(); - } - - $form_fields_abs = parent::get_form_mp_fields(); - - if ( count($form_fields_abs) === 1 ) { - return $form_fields_abs; - } - - $form_fields_merge = array_merge($form_fields_abs, $form_fields); - - return $this->sort_form_fields($form_fields_merge, $this->field_forms_order); - } - - /** - * Get fields sequence - * - * @return array - */ - public function get_fields_sequence() { - return array( - // Necessary to run. - 'description', - - // Checkout Básico. Acepta todos los medios de pago y lleva tus cobros a otro nivel. - 'checkout_header', - - // No olvides de homologar tu cuenta. - 'checkout_card_homolog', - - // Set up the payment experience in your store. - 'checkout_card_validate', - 'enabled', - 'checkout_visualization_title', - 'checkout_visualization', - 'title', - WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, - 'credits_banner', - 'checkout_banner_title', - 'credits_banner_visualization', - - // Advanced settings. - 'checkout_payments_advanced_title', - 'checkout_payments_advanced_description', - 'method', - 'gateway_discount', - 'commission', - ); - } - - /** - * Is available? - * - * @return bool - * @throws WC_WooMercadoPago_Exception Load access token exception. - */ - public function is_available() { - if ( parent::is_available() ) { - return true; - } - - if ( isset($this->settings['enabled']) && 'yes' === $this->settings['enabled'] ) { - if ( $this->mp instanceof MP ) { - $access_token = $this->mp->get_access_token(); - if ( - false === WC_WooMercadoPago_Credentials::validate_credentials_test($this->mp, $access_token) - && true === $this->sandbox - ) { - return false; - } - - if ( - false === WC_WooMercadoPago_Credentials::validate_credentials_prod($this->mp, $access_token) - && false === $this->sandbox - ) { - return false; - } - return true; - } - } - return false; - } - - /** - * Get clientID when update version 3.0.17 to 4 latest - * - * @return string - */ - public function get_client_id() { - $client_id = $this->mp_options->get_client_id(); - if ( ! empty($client_id) ) { - return true; - } - return false; - } - - /** - * Field enabled - * - * @return array - */ - public function field_enabled() { - return array( - 'title' => __('Activate installments without card in your store checkout ', 'woocommerce-mercadopago'), - 'subtitle' => __('Offer the option to pay in installments without card directly from your store\'s checkout.', 'woocommerce-mercadopago'), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'descriptions' => array( - 'enabled' => __('Payment in installments without card in the store checkout is active', 'woocommerce-mercadopago'), - 'disabled' => __('Payment in installments without card in the store checkout is inactive', 'woocommerce-mercadopago'), - ), - ); - } - - public function title_separator() { - return array( - 'title' => '', - 'type' => 'title', - ); - } - - public function field_checkout_visualization() { - $siteId = strtolower( $this->mp_options->get_site_id() ); - - return array( - 'type' => 'mp_checkout_visualization', - 'value' => array( - 'title' => __('Checkout visualization', 'woocommerce-mercadopago'), - 'subtitle' => __('Check below how this feature will be displayed to your customers:', 'woocommerce-mercadopago'), - 'footer' => __('Checkout Preview', 'woocommerce-mercadopago'), - 'pill_text' => __('PREVIEW', 'woocommerce-mercadopago'), - 'image' => plugins_url($this->get_mercado_credits_preview_image($siteId), plugin_dir_path(__FILE__)), - ), - ); - } - - public function field_credits_banner_visualization() { - return array( - 'type' => 'mp_credits_banner_visualization', - 'value' => array( - 'desktop' => __('Computer', 'woocommerce-mercadopago'), - 'cellphone' => __('Mobile', 'woocommerce-mercadopago'), - 'footer' => __('Banner on the product page | Computer version', 'woocommerce-mercadopago'), - 'title' => __('Component visualization', 'woocommerce-mercadopago'), - 'subtitle' => __('Check below how this feature will be displayed to your customers:', 'woocommerce-mercadopago'), - ), - ); - } - - /** - * Get image path for mercado credits checkout preview - * - * @param $siteId - * - * @return string - */ - protected function get_mercado_credits_preview_image( $siteId ) { - $siteIds = [ - 'mla' => 'HISPANO_', - 'mlb' => 'MLB_', - 'mlm' => 'HISPANO_', - ]; - - $prefix = $siteIds[ $siteId ] ?? ''; - - return sprintf('../assets/images/credits/%scheckout_preview.jpg', $prefix); - } - - /** - * Field checkout header - * - * @return array - */ - public function field_checkout_header() { - return array( - 'title' => sprintf( - '
+ /** + * Const ID + * + * @var string + */ + public const ID = 'woo-mercado-pago-credits'; + + /** + * Credits banner + * + * @var string + */ + public $credits_banner; + + /** + * WC_WooMercadoPago_CreditsGateway constructor. + * + * @throws WC_WooMercadoPago_Exception On load payment exception. + */ + public function __construct() { + $this->id = self::ID; + $this->title = __('Installments without card', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + $this->title_gateway = __('Installments without card', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + $this->description = __('Customers who buy on spot and pay later in up to 12 installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); + $this->mp_options = $this->get_mp_options(); + + if ( ! $this->validate_section() ) { + return; + } + + add_action( 'admin_enqueue_scripts', array($this, 'load_admin_scripts') ); + + $this->form_fields = array(); + $this->method_title = __( 'Mercado Pago - Installments without card', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->method = $this->get_option_mp( 'method', 'redirect' ); + $this->title = $this->get_option_mp( 'title', __( 'Checkout without card', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + $this->method_description = $this->description; + $this->credits_banner = $this->get_option('credits_banner', 'no'); + $this->gateway_discount = $this->get_option('gateway_discount', 0); + $this->clientid_old_version = $this->get_client_id(); + $this->field_forms_order = $this->get_fields_sequence(); + + parent::__construct(); + $this->form_fields = $this->get_form_mp_fields(); + $this->hook = new WC_WooMercadoPago_Hook_Credits($this); + $this->notification = new WC_WooMercadoPago_Notification_Core($this); + $this->currency_convertion = true; + $this->icon = $this->get_checkout_icon(); + } + + public function load_admin_scripts(): void { + if ( is_admin() && $this->is_manage_section() && ( + WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || + WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') + ) ) { + $siteId = strtolower( $this->mp_options->get_site_id() ); + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + wp_enqueue_style( + 'woocommerce-mercadopago-info-admin-credits-style', + plugins_url( '../assets/css/credits/example-info' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + + wp_enqueue_script( + 'woocommerce-mercadopago-credits-config-script', + plugins_url( '../assets/js/credits_config_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + + wp_enqueue_script( + 'woocommerce-mercadopago-info-admin-credits-script', + plugins_url( '../assets/js/credits/example-info' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + + wp_localize_script( + 'woocommerce-mercadopago-info-admin-credits-script', + 'wc_mp_icon_images', + array( + 'computerBlueIcon' => plugins_url( '../assets/images/credits/desktop-blue-icon.png', plugin_dir_path( __FILE__ ) ), + 'computerGrayIcon' => plugins_url( '../assets/images/credits/desktop-gray-icon.png', plugin_dir_path( __FILE__ ) ), + 'cellphoneBlueIcon' => plugins_url( '../assets/images/credits/cellphone-blue-icon.png', plugin_dir_path( __FILE__ ) ), + 'cellphoneGrayIcon' => plugins_url( '../assets/images/credits/cellphone-gray-icon.png', plugin_dir_path( __FILE__ ) ), + 'viewMobile' => plugins_url( $this->get_mercado_credits_gif_path( $siteId, 'mobile' ), plugin_dir_path( __FILE__ ) ), + 'viewDesktop' => plugins_url( $this->get_mercado_credits_gif_path( $siteId, 'desktop' ), plugin_dir_path( __FILE__ ) ), + 'footerDesktop' => __( 'Banner on the product page | Computer version', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'footerCellphone' => __( 'Banner on the product page | Cellphone version', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ) + ); + } + } + + /** + * Get MP fields label + * + * @return array + */ + public function get_form_mp_fields() { + if ( empty( $this->checkout_country ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); + } + + if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); + } + + $form_fields = array(); + + if ( + ! empty( $this->checkout_country ) && + ! empty( $this->get_access_token() ) && + ! empty( $this->get_public_key() ) + ) { + $form_fields['checkout_header'] = $this->field_checkout_header(); + $form_fields['checkout_payments_advanced_title'] = $this->field_checkout_payments_advanced_title(); + $form_fields['credits_banner'] = $this->field_credits_banner_mode(); + $form_fields['checkout_visualization_title'] = $this->title_separator(); + $form_fields['checkout_visualization'] = $this->field_checkout_visualization(); + $form_fields['checkout_banner_title'] = $this->title_separator(); + $form_fields['credits_banner_visualization'] = $this->field_credits_banner_visualization(); + } + + $form_fields_abs = parent::get_form_mp_fields(); + + if ( count($form_fields_abs) === 1 ) { + return $form_fields_abs; + } + + $form_fields_merge = array_merge($form_fields_abs, $form_fields); + + return $this->sort_form_fields($form_fields_merge, $this->field_forms_order); + } + + /** + * Get fields sequence + * + * @return array + */ + public function get_fields_sequence() { + return array( + // Necessary to run. + 'description', + + // Checkout Básico. Acepta todos los medios de pago y lleva tus cobros a otro nivel. + 'checkout_header', + + // No olvides de homologar tu cuenta. + 'checkout_card_homolog', + + // Set up the payment experience in your store. + 'checkout_card_validate', + 'enabled', + 'checkout_visualization_title', + 'checkout_visualization', + 'title', + WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, + 'credits_banner', + 'checkout_banner_title', + 'credits_banner_visualization', + + // Advanced settings. + 'checkout_payments_advanced_title', + 'checkout_payments_advanced_description', + 'method', + 'gateway_discount', + 'commission', + ); + } + + /** + * Is available? + * + * @return bool + * @throws WC_WooMercadoPago_Exception Load access token exception. + */ + public function is_available() { + if ( parent::is_available() ) { + return true; + } + + if ( isset($this->settings['enabled']) && 'yes' === $this->settings['enabled'] ) { + if ( $this->mp instanceof MP ) { + $access_token = $this->mp->get_access_token(); + if ( + false === WC_WooMercadoPago_Credentials::validate_credentials_test($this->mp, $access_token) + && true === $this->sandbox + ) { + return false; + } + + if ( + false === WC_WooMercadoPago_Credentials::validate_credentials_prod($this->mp, $access_token) + && false === $this->sandbox + ) { + return false; + } + return true; + } + } + return false; + } + + /** + * Get clientID when update version 3.0.17 to 4 latest + * + * @return string + */ + public function get_client_id() { + $client_id = $this->mp_options->get_client_id(); + if ( ! empty($client_id) ) { + return true; + } + return false; + } + + /** + * Field enabled + * + * @return array + */ + public function field_enabled() { + return array( + 'title' => __('Activate installments without card in your store checkout ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Offer the option to pay in installments without card directly from your store\'s checkout.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'descriptions' => array( + 'enabled' => __('Payment in installments without card in the store checkout is active', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'disabled' => __('Payment in installments without card in the store checkout is inactive', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + ), + ); + } + + public function title_separator() { + return array( + 'title' => '', + 'type' => 'title', + ); + } + + public function field_checkout_visualization() { + $siteId = strtolower( $this->mp_options->get_site_id() ); + + return array( + 'type' => 'mp_checkout_visualization', + 'value' => array( + 'title' => __('Checkout visualization', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Check below how this feature will be displayed to your customers:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'footer' => __('Checkout Preview', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'pill_text' => __('PREVIEW', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'image' => plugins_url($this->get_mercado_credits_preview_image($siteId), plugin_dir_path(__FILE__)), + ), + ); + } + + public function field_credits_banner_visualization() { + return array( + 'type' => 'mp_credits_banner_visualization', + 'value' => array( + 'desktop' => __('Computer', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'cellphone' => __('Mobile', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'footer' => __('Banner on the product page | Computer version', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'title' => __('Component visualization', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Check below how this feature will be displayed to your customers:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + ), + ); + } + + /** + * Get image path for mercado credits checkout preview + * + * @param $siteId + * + * @return string + */ + protected function get_mercado_credits_preview_image( $siteId ) { + $siteIds = array( + 'mla' => 'HISPANO_', + 'mlb' => 'MLB_', + 'mlm' => 'HISPANO_', + ); + + $prefix = $siteIds[ $siteId ] ?? ''; + + return sprintf('../assets/images/credits/%scheckout_preview.jpg', $prefix); + } + + /** + * Field checkout header + * + * @return array + */ + public function field_checkout_header() { + return array( + 'title' => sprintf( + '
- ' . __('Installments without card', 'woocommerce-mercadopago') . ' + ' . __('Installments without card', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . '

- ' . __('Reach millions of buyers by offering Mercado Credito as a payment method. Our flexible payment options give your customers the possibility to buy today whatever they want in up to 12 installments without the need to use a credit card.', 'woocommerce-mercadopago') . ' + ' . __('Reach millions of buyers by offering Mercado Credito as a payment method. Our flexible payment options give your customers the possibility to buy today whatever they want in up to 12 installments without the need to use a credit card.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . '

- ' . __('For your business, the approval of the purchase is immediate and guaranteed.', 'woocommerce-mercadopago') . ' + ' . __('For your business, the approval of the purchase is immediate and guaranteed.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . '

' - ), - 'type' => 'title', - 'class' => 'mp_title_header', - ); - } - - /** - * Field checkout payments advanced title - * - * @return array - */ - public function field_checkout_payments_advanced_title() { - return array( - 'title' => __('Advanced settings', 'woocommerce-mercadopago'), - 'type' => 'title', - 'class' => 'mp_subtitle_bd', - ); - } - - /** - * Payment Fields - */ - public function payment_fields() { - $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; - - // add css. - wp_enqueue_style( - 'woocommerce-mercadopago-narciso-styles', - plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - - $test_mode_link = $this->get_mp_devsite_link( $this->checkout_country ); - - $parameters = [ - 'test_mode' => ! $this->is_production_mode(), - 'test_mode_link' => $test_mode_link, - 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, - 'redirect_image' => plugins_url( '../assets/images/cho-pro-redirect-v2.png', plugin_dir_path( __FILE__ ) ), - ]; - - $parameters = array_merge($parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions()); - - wc_get_template( - 'checkout/credits-checkout.php', - $parameters, - 'woo/mercado/pago/module/', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Field Banner Credits - * - * @return array - */ - public function field_credits_banner_mode() { - return array( - 'title' => __('Inform your customers about the option of paying in installments without card', 'woocommerce-mercadopago'), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'subtitle' => __('By activating the installments without card component, you increase your chances of selling.', 'woocommerce-mercadopago'), - 'descriptions' => array( - 'enabled' => __('The installments without card component is active.', 'woocommerce-mercadopago'), - 'disabled' => __('The installments without card component is inactive.', 'woocommerce-mercadopago'), - ), - ); - } - - /** - * Get git image path for mercado credits demonstration - * - * @param $siteId - * @param $view - * - * @return string - */ - protected function get_mercado_credits_gif_path( $siteId, $view ) { - $siteIds = [ - 'mla' => 'HISPANO_', - 'mlb' => 'MLB_', - 'mlm' => 'HISPANO_', - ]; - - $prefix = isset($siteIds[$siteId]) ? $siteIds[$siteId] : ''; - - return sprintf('../assets/images/credits/%sview_%s.gif', $prefix, $view); - } - - /** - * Process payment - * - * @param int $order_id Order Id. - * @return array - */ - public function process_payment( $order_id ) { - $order = wc_get_order($order_id); - $amount = $this->get_order_total(); - $shipping_taxes = floatval($order->get_shipping_total()); - - $order->update_meta_data('is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no'); - $order->update_meta_data('_used_gateway', get_class($this)); - - if ( ! empty($this->gateway_discount) ) { - $discount = ( $amount - $shipping_taxes ) * $this->gateway_discount / 100; - $order->update_meta_data('Mercado Pago: discount', __('discount of', 'woocommerce-mercadopago') . ' ' . $this->gateway_discount . '% / ' . __('discount of', 'woocommerce-mercadopago') . ' = ' . $discount); - $order->set_total($amount - $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(); - - $this->log->write_log(__FUNCTION__, 'customer being redirected to Mercado Pago.'); - return array( - 'result' => 'success', - 'redirect' => $this->create_preference($order), - ); - } - - /** - * Create preference - * - * @param object $order Order. - * @return bool - */ - public function create_preference( $order ) { - $preference_credits = new WC_WooMercadoPago_Preference_Credits( $this, $order ); - $preference = $preference_credits->get_transaction( 'Preference' ); - - try { - $checkout_info = $preference->save(); - $this->log->write_log( __FUNCTION__, 'Created Preference: ' . wp_json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - $this->log->write_log( __FUNCTION__, 'payment link generated with success from mercado pago, with structure as follow: ' . wp_json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - return ( $this->sandbox ) ? $checkout_info['sandbox_init_point'] : $checkout_info['init_point']; - } catch ( Exception $e ) { - $this->log->write_log( __FUNCTION__, 'payment creation failed with exception: ' . wp_json_encode( $e, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - return false; - } - } - - /** - * Get Id - * - * @return string - */ - public static function get_id() { - return self::ID; - } - - /** - * Get Mercado Pago Icon - * - * @return mixed - */ - public function get_checkout_icon() { - /** - * Add Mercado Pago icon. - * - * @since 3.0.1 - */ - return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/mercadopago.png', plugin_dir_path( __FILE__ ) ) ); - } + ), + 'type' => 'title', + 'class' => 'mp_title_header', + ); + } + + /** + * Field checkout payments advanced title + * + * @return array + */ + public function field_checkout_payments_advanced_title() { + return array( + 'title' => __('Advanced settings', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'title', + 'class' => 'mp_subtitle_bd', + ); + } + + /** + * Payment Fields + */ + public function payment_fields(): void { + $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; + + // add css. + wp_enqueue_style( + 'woocommerce-mercadopago-narciso-styles', + plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + + $test_mode_link = $this->get_mp_devsite_link( $this->checkout_country ); + + $parameters = array( + 'test_mode' => ! $this->is_production_mode(), + 'test_mode_link' => $test_mode_link, + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'redirect_image' => plugins_url( '../assets/images/cho-pro-redirect-v2.png', plugin_dir_path( __FILE__ ) ), + ); + + $parameters = array_merge($parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions()); + + wc_get_template( + 'checkout/credits-checkout.php', + $parameters, + 'woo/mercado/pago/module/', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Field Banner Credits + * + * @return array + */ + public function field_credits_banner_mode() { + return array( + 'title' => __('Inform your customers about the option of paying in installments without card', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'subtitle' => __('By activating the installments without card component, you increase your chances of selling.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'descriptions' => array( + 'enabled' => __('The installments without card component is active.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'disabled' => __('The installments without card component is inactive.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + ), + ); + } + + /** + * Get git image path for mercado credits demonstration + * + * @param $siteId + * @param $view + * + * @return string + */ + protected function get_mercado_credits_gif_path( $siteId, $view ) { + $siteIds = array( + 'mla' => 'HISPANO_', + 'mlb' => 'MLB_', + 'mlm' => 'HISPANO_', + ); + + $prefix = isset($siteIds[$siteId]) ? $siteIds[$siteId] : ''; + + return sprintf('../assets/images/credits/%sview_%s.gif', $prefix, $view); + } + + /** + * Process payment + * + * @param int $order_id Order Id. + * @return array + */ + public function process_payment( $order_id ) { + $order = wc_get_order($order_id); + $amount = $this->get_order_total(); + $shipping_taxes = (float) ($order->get_shipping_total()); + + $order->update_meta_data('is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no'); + $order->update_meta_data('_used_gateway', get_class($this)); + + if ( ! empty($this->gateway_discount) ) { + $discount = ( $amount - $shipping_taxes ) * $this->gateway_discount / 100; + $order->update_meta_data('Mercado Pago: discount', __('discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' ' . $this->gateway_discount . '% / ' . __('discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' = ' . $discount); + $order->set_total($amount - $discount); + } + + if ( ! empty($this->commission) ) { + $comission = $amount * ( $this->commission / 100 ); + $order->update_meta_data('Mercado Pago: comission', __('fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' ' . $this->commission . '% / ' . __('fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) . ' = ' . $comission); + } + + $order->save(); + + $this->log->write_log(__FUNCTION__, 'customer being redirected to Mercado Pago.'); + return array( + 'result' => 'success', + 'redirect' => $this->create_preference($order), + ); + } + + /** + * Create preference + * + * @param object $order Order. + * @return bool + */ + public function create_preference( $order ) { + $preference_credits = new WC_WooMercadoPago_Preference_Credits( $this, $order ); + $preference = $preference_credits->get_transaction( 'Preference' ); + + try { + $checkout_info = $preference->save(); + $this->log->write_log( __FUNCTION__, 'Created Preference: ' . wp_json_encode( $checkout_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + $this->log->write_log( __FUNCTION__, 'payment link generated with success from mercado pago, with structure as follow: ' . wp_json_encode( $checkout_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + return ( $this->sandbox ) ? $checkout_info['sandbox_init_point'] : $checkout_info['init_point']; + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, 'payment creation failed with exception: ' . wp_json_encode( $e, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + return false; + } + } + + /** + * Get Id + * + * @return string + */ + public static function get_id() { + return self::ID; + } + + /** + * Get Mercado Pago Icon + * + * @return mixed + */ + public function get_checkout_icon() { + /** + * Add Mercado Pago icon. + * + * @since 3.0.1 + */ + return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/mercadopago.png', plugin_dir_path( __FILE__ ) ) ); + } + + /** + * Enable Credits by default + * + * @return mixed + */ + public function active_by_default() { + $this->update_option_default('enabled', 'yes'); + $this->update_option_default('credits_banner', 'yes'); + } } diff --git a/includes/payments/class-wc-woomercadopago-custom-gateway.php b/includes/payments/class-wc-woomercadopago-custom-gateway.php index d0c2177b7..c85d658f5 100755 --- a/includes/payments/class-wc-woomercadopago-custom-gateway.php +++ b/includes/payments/class-wc-woomercadopago-custom-gateway.php @@ -1,798 +1,790 @@ id = self::ID; - $this->title = __( 'Debit and Credit', 'woocommerce-mercadopago' ); - $this->title_gateway = __( 'Debit and Credit', 'woocommerce-mercadopago' ); - $this->description = __( 'Transparent Checkout in your store environment', 'woocommerce-mercadopago' ); - $this->mp_options = $this->get_mp_options(); - - if ( ! $this->validate_section() ) { - return; - } - - $this->form_fields = array(); - $this->method_title = __( 'Mercado pago - Customized Checkout', 'woocommerce-mercadopago' ); - $this->title = $this->get_option( 'title', __( 'Debit and Credit', 'woocommerce-mercadopago' ) ); - $this->method_description = $this->description; - $this->coupon_mode = $this->get_option( 'coupon_mode', 'no' ); - $this->wallet_button = $this->get_option( 'wallet_button', 'yes' ); - $this->field_forms_order = $this->get_fields_sequence(); - - parent::__construct(); - $this->form_fields = $this->get_form_mp_fields(); - $this->hook = new WC_WooMercadoPago_Hook_Custom( $this ); - $this->notification = new WC_WooMercadoPago_Notification_Core( $this ); - $this->currency_convertion = true; - $this->icon = $this->get_checkout_icon(); - } - - /** - * Get Form Mercado Pago fields - * - * @return array - */ - public function get_form_mp_fields() { - if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { - $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, - false - ); - } - - if ( empty( $this->checkout_country ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); - } - - if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); - } - - $form_fields = array(); - if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { - $form_fields['checkout_custom_header'] = $this->field_checkout_custom_header(); - $form_fields['binary_mode'] = $this->field_binary_mode(); - $form_fields['field_checkout_about_fees'] = $this->field_checkout_about_fees(); - $form_fields['field_checkout_custom_card_info_fees'] = $this->field_checkout_custom_card_info_fees(); - $form_fields['checkout_custom_payments_advanced_title'] = $this->field_checkout_custom_payments_advanced_title(); - $form_fields['coupon_mode'] = $this->field_coupon_mode(); - $form_fields['wallet_button'] = $this->field_checkout_custom_wallet_button_title(); - } - $form_fields_abs = parent::get_form_mp_fields(); - if ( 1 === count( $form_fields_abs ) ) { - return $form_fields_abs; - } - $form_fields_merge = array_merge( $form_fields_abs, $form_fields ); - $fields = $this->sort_form_fields( $form_fields_merge, $this->field_forms_order ); - - return $fields; - } - - /** - * Get fields sequence - * - * @return array - */ - public function get_fields_sequence() { - return array( - // Necessary to run. - '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', - // No olvides de homologar tu cuenta. - 'checkout_card_homolog', - // Configure the personalized payment experience in your store. - 'checkout_card_validate', - 'checkout_custom_payments_title', - 'checkout_payments_subtitle', - 'enabled', - 'title', - // About card info pcj and fees. - 'field_checkout_about_fees', - 'field_checkout_custom_card_info_fees', - WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, - 'checkout_custom_wallet_button_toggle', - 'wallet_button', - // Advanced configuration of the personalized payment experience. - 'checkout_custom_payments_advanced_title', - 'checkout_payments_advanced_description', - 'coupon_mode', - 'binary_mode', - 'gateway_discount', - 'commission', - ); - } - - /** - * Field enabled - * - * @return array - */ - public function field_enabled() { - return array( - 'title' => __( 'Enable the checkout', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'By disabling it, you will disable all credit cards payments from Mercado Pago Transparent Checkout.', 'woocommerce-mercadopago' ), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'descriptions' => array( - 'enabled' => __( 'Transparent Checkout for credit cards is enabled.', 'woocommerce-mercadopago' ), - 'disabled' => __( 'Transparent checkout for credit cards is disabled.', 'woocommerce-mercadopago' ), - ), - ); - } - - /** - * Field checkout about fees - * - * @return array - */ - public function field_checkout_about_fees() { - return array( - 'title' => '', - 'type' => 'title', - ); - } - - /** - * Field checkout card info - * - * @return array - */ - public function field_checkout_custom_card_info_fees() { - $links = WC_WooMercadoPago_Helper_Links::woomercadopago_settings_links(); - $value = array( - 'title' => __('Installments Fees', 'woocommerce-mercadopago'), - 'subtitle' => __('Set installment fees and whether they will be charged from the store or from the buyer.', 'woocommerce-mercadopago'), - 'button_text' => __('Set fees', 'woocommerce-mercadopago'), - 'button_url' => $links['link_costs'], - 'icon' => 'mp-icon-badge-info', - 'color_card' => 'mp-alert-color-sucess', - 'size_card' => 'mp-card-body-size', - 'target' => '_blank', - ); - - return array( - 'type' => 'mp_card_info', - 'value' => $value, - ); - } - - /** - * Field checkout custom header - * - * @return array - */ - public function field_checkout_custom_header() { - $checkout_custom_header = array( - 'title' => sprintf( - /* translators: %s card */ - '
+ /** + * ID + * + * @const + */ + public const ID = 'woo-mercado-pago-custom'; + + /** + * Is enable Wallet Button? + * + * @var string + */ + protected $wallet_button; + + /** + * WC_WooMercadoPago_CustomGateway constructor. + * + * @throws WC_WooMercadoPago_Exception Exception load payment. + */ + public function __construct() { + $this->id = self::ID; + $this->title = __( 'Debit and Credit', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->title_gateway = __( 'Debit and Credit', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->description = __( 'Transparent Checkout in your store environment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->mp_options = $this->get_mp_options(); + + if ( ! $this->validate_section() ) { + return; + } + + $this->form_fields = array(); + $this->method_title = __( 'Mercado pago - Customized Checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->title = $this->get_option( 'title', __( 'Debit and Credit', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + $this->method_description = $this->description; + $this->coupon_mode = $this->get_option( 'coupon_mode', 'no' ); + $this->wallet_button = $this->get_option( 'wallet_button', 'yes' ); + $this->field_forms_order = $this->get_fields_sequence(); + + parent::__construct(); + $this->form_fields = $this->get_form_mp_fields(); + $this->hook = new WC_WooMercadoPago_Hook_Custom( $this ); + $this->notification = new WC_WooMercadoPago_Notification_Core( $this ); + $this->currency_convertion = true; + $this->icon = $this->get_checkout_icon(); + } + + /** + * Get Form Mercado Pago fields + * + * @return array + */ + public function get_form_mp_fields() { + if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { + $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, + false + ); + } + + if ( empty( $this->checkout_country ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); + } + + if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); + } + + $form_fields = array(); + if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { + $form_fields['checkout_custom_header'] = $this->field_checkout_custom_header(); + $form_fields['binary_mode'] = $this->field_binary_mode(); + $form_fields['field_checkout_about_fees'] = $this->field_checkout_about_fees(); + $form_fields['field_checkout_custom_card_info_fees'] = $this->field_checkout_custom_card_info_fees(); + $form_fields['checkout_custom_payments_advanced_title'] = $this->field_checkout_custom_payments_advanced_title(); + $form_fields['coupon_mode'] = $this->field_coupon_mode(); + $form_fields['wallet_button'] = $this->field_checkout_custom_wallet_button_title(); + } + $form_fields_abs = parent::get_form_mp_fields(); + if ( 1 === count( $form_fields_abs ) ) { + return $form_fields_abs; + } + $form_fields_merge = array_merge( $form_fields_abs, $form_fields ); + $fields = $this->sort_form_fields( $form_fields_merge, $this->field_forms_order ); + + return $fields; + } + + /** + * Get fields sequence + * + * @return array + */ + public function get_fields_sequence() { + return array( + // Necessary to run. + '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', + // No olvides de homologar tu cuenta. + 'checkout_card_homolog', + // Configure the personalized payment experience in your store. + 'checkout_card_validate', + 'checkout_custom_payments_title', + 'checkout_payments_subtitle', + 'enabled', + 'title', + // About card info pcj and fees. + 'field_checkout_about_fees', + 'field_checkout_custom_card_info_fees', + WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, + 'checkout_custom_wallet_button_toggle', + 'wallet_button', + // Advanced configuration of the personalized payment experience. + 'checkout_custom_payments_advanced_title', + 'checkout_payments_advanced_description', + 'coupon_mode', + 'binary_mode', + 'gateway_discount', + 'commission', + ); + } + + /** + * Field enabled + * + * @return array + */ + public function field_enabled() { + return array( + 'title' => __( 'Enable the checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'By disabling it, you will disable all credit cards payments from Mercado Pago Transparent Checkout.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'descriptions' => array( + 'enabled' => __( 'Transparent Checkout for credit cards is enabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'disabled' => __( 'Transparent checkout for credit cards is disabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + ); + } + + /** + * Field checkout about fees + * + * @return array + */ + public function field_checkout_about_fees() { + return array( + 'title' => '', + 'type' => 'title', + ); + } + + /** + * Field checkout card info + * + * @return array + */ + public function field_checkout_custom_card_info_fees() { + $links = WC_WooMercadoPago_Helper_Links::woomercadopago_settings_links(); + $value = array( + 'title' => __('Installments Fees', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Set installment fees and whether they will be charged from the store or from the buyer.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'button_text' => __('Set fees', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'button_url' => $links['link_costs'], + 'icon' => 'mp-icon-badge-info', + 'color_card' => 'mp-alert-color-sucess', + 'size_card' => 'mp-card-body-size', + 'target' => '_blank', + ); + + return array( + 'type' => 'mp_card_info', + 'value' => $value, + ); + } + + /** + * Field checkout custom header + * + * @return array + */ + public function field_checkout_custom_header() { + $checkout_custom_header = array( + 'title' => sprintf( + /* translators: %s card */ + '
- ' . __( 'Transparent Checkout | Credit card ', 'woocommerce-mercadopago' ) . ' + ' . __( 'Transparent Checkout | Credit card ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . '

- ' . __( 'With the Transparent Checkout, you can sell inside your store environment, without redirection and with the security from Mercado Pago.', 'woocommerce-mercadopago' ) . ' + ' . __( 'With the Transparent Checkout, you can sell inside your store environment, without redirection and with the security from Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . '

' - ), - 'type' => 'title', - 'class' => 'mp_title_header', - ); - return $checkout_custom_header; - } - - /** - * Field checkout custom payment advanced 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; - } - - /** - * Field Wallet Button toggle - * - * @return array - */ - public function field_checkout_custom_wallet_button_title() { - return array( - 'title' => __( 'Payments via Mercado Pago account', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'Your customers pay faster with saved cards, money balance or other available methods in their Mercado Pago accounts.', 'woocommerce-mercadopago' ), - 'type' => 'mp_toggle_switch', - 'default' => 'yes', - 'descriptions' => array( - 'enabled' => __( 'Payments via Mercado Pago accounts are active.', 'woocommerce-mercadopago' ), - 'disabled' => __( 'Payments via Mercado Pago accounts are inactive.', 'woocommerce-mercadopago' ), - ), - 'after_toggle' => $this->wallet_button_preview(), - ); - } - - /** - * Generate Wallet Button HTML - * - * @param $key field key - * @param $settings settings array - * - * @return array - */ - public function wallet_button_preview() { - return wc_get_template_html( - 'components/wallet-button.php', - array ( - 'img_wallet_button_uri' => $this->get_wallet_button_example_uri(), - 'img_wallet_button_description' => __( 'Check an example of how it will appear in your store:', 'woocommerce-mercadopago' ), - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Returns wallet button URI based on current store locale - * - * @return string - */ - public function get_wallet_button_example_uri() { - $locale = substr( strtolower(get_locale()), 0, 2 ); - - if ( 'pt' !== $locale && 'es' !== $locale ) { - $locale = 'en'; - } - - return plugins_url( '../assets/images/pix-admin/example-' . $locale . '.png', plugin_dir_path( __FILE__ ) ); - } - - /** - * Get Order Status - * - * @param string $status_detail Status. - * @return string|void - */ - 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_card_error': - 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_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' ); - 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-narciso-styles', - plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - - $total = $this->get_order_total(); - $subtotal = (float) WC()->cart->subtotal; - $tax = $total - $subtotal; - $discount = $subtotal * ( $this->gateway_discount / 100 ); - $comission = $subtotal * ( $this->commission / 100 ); - $amount = $subtotal - $discount + $comission; - $amount = $amount + $tax; - - $banner_url = $this->get_option( '_mp_custom_banner' ); - $test_mode_link = $this->get_mp_devsite_link($this->checkout_country); - 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 ( 'credit_card' === $tarjeta['type'] ) { - $credit_card[] = array( - 'src' => $tarjeta['image'], - 'alt' => $tarjeta['name'] - ); - } elseif ( 'debit_card' === $tarjeta['type'] || 'prepaid_card' === $tarjeta['type'] ) { - $debit_card[] = array( - 'src' => $tarjeta['image'], - 'alt' => $tarjeta['name'] - ); - } - } - - $payment_methods = array(); - - if ( 0 !== count( $credit_card ) ) { - $payment_methods[] = array( - 'title' => __( 'Credit cards', 'woocommerce-mercadopago' ), - 'label' => __( 'Up to ' , 'woocommerce-mercadopago' ) . 12 . __( ' installments' , 'woocommerce-mercadopago' ), - 'payment_methods' => $credit_card, - ); - } - - if ( 0 !== count( $debit_card ) ) { - $payment_methods[] = array( - 'title' => __( 'Debit cards', 'woocommerce-mercadopago' ), - 'payment_methods' => $debit_card, - ); - } - - try { - $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->ratio( $this ); - } catch ( Exception $e ) { - $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::DEFAULT_RATIO; - } - - $parameters = array( - 'test_mode' => ! $this->is_production_mode(), - 'test_mode_link' => $test_mode_link, - 'amount' => $amount, - 'site_id' => $this->mp_options->get_site_id(), - 'public_key' => $this->get_public_key(), - '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'], - 'payment_methods' => $payment_methods, - 'wallet_button' => $this->wallet_button, - ); - - $parameters = array_merge($parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions()); - wc_get_template( 'checkout/custom-checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); - } - - /** - * Process payment - * - * @param int $order_id Order Id. - * @return array|void - */ - public function process_payment( $order_id ) { - // phpcs:ignore WordPress.Security.NonceVerification - if ( ! isset( $_POST['mercadopago_custom']) ) { - return $this->process_result_fail( - __FUNCTION__, - __( 'A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago' ), - __( 'A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago' ) - ); - } - - // phpcs:ignore WordPress.Security.NonceVerification - $custom_checkout = map_deep($_POST['mercadopago_custom'], 'sanitize_text_field'); - $custom_checkout_log = $custom_checkout; - - if ( isset($custom_checkout_log['token']) ) { - unset($custom_checkout_log['token']); - } - - $this->log->write_log( __FUNCTION__, 'POST Custom: ' . wp_json_encode( $custom_checkout_log, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - - $order = wc_get_order( $order_id ); - - $this->process_discount_and_commission( $order_id, $order ); - - if ( 'wallet_button' === $custom_checkout['checkout_type'] ) { - $this->log->write_log( __FUNCTION__, 'preparing to render wallet button checkout.' ); - $response = $this->process_custom_checkout_wallet_button_flow( $order ); - } else { - $this->log->write_log( __FUNCTION__, 'preparing to get response of custom checkout.' ); - $response = $this->process_custom_checkout_flow( $custom_checkout, $order ); - } - - if ( $response ) { - return $response; - } - - return $this->process_result_fail( - __FUNCTION__, - __( 'A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago' ), - __( 'A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago' ) - ); - } - - /** - * Process Custom Wallet Button Flow - * - * @param WC_Order $order - * - * @return array - */ - protected function process_custom_checkout_wallet_button_flow( $order ) { - return array( - 'result' => 'success', - 'redirect' => add_query_arg( - array( - 'wallet_button' => 'open' - ), - $order->get_checkout_payment_url( true ) - ), - ); - } - - /** - * Process Custom Payment Flow - * - * @param array $custom_checkout - * @param WC_Order $order - * - * @return array|string[] - * @throws WC_Data_Exception - */ - protected function process_custom_checkout_flow( $custom_checkout, $order ) { - 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'] ) && - -1 !== $custom_checkout['installments'] - ) { - $response = $this->create_payment( $order, $custom_checkout ); - - if ( ! is_array( $response ) ) { - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - - $installments = (float) $response['installments']; - $installment_amount = (float) $response['transaction_details']['installment_amount']; - $transaction_amount = (float) $response['transaction_amount']; - $total_paid_amount = (float) $response['transaction_details']['total_paid_amount']; - $last_four_digits = (float) $response['transaction_details']['last_four_digits']; - $id_payment = (float) $response['id']; - - // Old - $order->add_meta_data('mp_installments', $installments); - $order->add_meta_data('mp_transaction_details', $installment_amount); - $order->add_meta_data('mp_transaction_amount', $transaction_amount); - $order->add_meta_data('mp_total_paid_amount', $total_paid_amount); - $order->save(); - - // New key names - $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - installments', $installments); - $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - installment_amount', $installment_amount); - $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - transaction_amount', $transaction_amount); - $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - total_paid_amount', $total_paid_amount); - $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - card_last_four_digits', $last_four_digits); - $order->save(); - - $this->hook->update_mp_order_payments_metadata( $order->get_id(), [ $response['id'] ] ); - - // 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' ); - $this->set_order_to_pending_on_retry( $order ); - return array( - 'result' => 'success', - 'redirect' => $order->get_checkout_order_received_url(), - ); - case 'pending': - // Order approved/pending, we just redirect to the thankyou page. - return array( - 'result' => 'success', - 'redirect' => $order->get_checkout_order_received_url(), - ); - 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 ), - ); - 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 ), - ); - case 'cancelled': - case 'in_mediation': - case 'charged_back': - // If we enter here (an order generating a direct [cancelled, in_mediation, or charged_back] status), - // then there must be something very wrong! - break; - default: - break; - } - } - - // Process when fields are incomplete. - return $this->process_result_fail( - __FUNCTION__, - __( 'A problem was occurred when processing your payment. Are you sure you have correctly filled all information in the checkout form?', 'woocommerce-mercadopago' ), - __( '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 ) - ); - } - } - - /** - * Display installment fee as an order attachment item - * - * @param $order_id - */ - public function display_installment_fee_order( $order_id ) { - $order = wc_get_order( $order_id ); - $order->get_meta_data(); - - $gatewayName = $order->get_meta( '_used_gateway' ); - if ( strpos($gatewayName, 'Custom_Gateway') ) { - $total_paid_amount = $order->get_meta( 'mp_total_paid_amount' ); - $transaction_amount = $order->get_meta( 'mp_transaction_amount' ); - $installment_fee_amount = (float) $total_paid_amount - (float) $transaction_amount; - $total_with_fees = $installment_fee_amount + (float) $transaction_amount; - - if ( $installment_fee_amount > 0 ) { - $this->display_order_note( [ - 'tip_text' => __('Represents the installment fee charged by Mercado Pago.', 'woocommerce-mercadopago'), - 'title' => __('Mercado Pago Installment Fee:', 'woocommerce-mercadopago'), - 'value' => wc_price($installment_fee_amount, []), - ] ); - - $this->display_order_note( [ - 'tip_text' => __('Represents the total purchase plus the installment fee charged by Mercado Pago.', 'woocommerce-mercadopago'), - 'title' => __('Mercado Pago Total:', 'woocommerce-mercadopago'), - 'value' => wc_price($total_with_fees, []), - ] ); - } - } - } - - /** - * Display generic template for order notes - * - * @param array $params - */ - public function display_order_note( $params ) { - wc_get_template( - 'order/generic-order-note.php', - $params, - 'woo/mercado/pago/module/', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Fill a commission and discount information - * - * @param $order_id - * @param $order - */ - protected function process_discount_and_commission( $order_id, $order ) { - $amount = (float) WC()->cart->subtotal; - $shipping_taxes = floatval($order->get_shipping_total()); - - $order->update_meta_data( 'is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no' ); - $order->update_meta_data( '_used_gateway', get_class( $this ) ); - - if ( ! empty( $this->gateway_discount ) ) { - $discount = ( $amount * $this->gateway_discount / 100 ); - $order->set_total($amount - $discount + $shipping_taxes); - } - - if ( ! empty( $this->commission ) ) { - $comission = $amount * ( $this->commission / 100 ); - $order->update_meta_data( 'Mercado Pago: commission', __( 'fee of', 'woocommerce-mercadopago' ) . ' ' . $this->commission . '% / ' . __( 'fee of', 'woocommerce-mercadopago' ) . ' = ' . $comission ); - } - $order->save(); - } - - /** - * Process if result is fail - * - * @param $function - * @param $log_message - * @param $notice_message - * - * @return string[] - */ - protected function process_result_fail( $function, $log_message, $notice_message ) { - $this->log->write_log( $function, $log_message ); - - wc_add_notice( - '

' . $notice_message . '

', - 'error' - ); - - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - - /** - * Create Payment - * - * @param object $order Order. - * @param mixed $custom_checkout Checkout info. - * @return string|array - */ - protected function create_payment( $order, $custom_checkout ) { - $preferences_custom = new WC_WooMercadoPago_Preference_Custom( $this, $order, $custom_checkout ); - $payment = $preferences_custom->get_transaction( 'Payment' ); - - try { - $checkout_info = $payment->save(); - $this->log->write_log( __FUNCTION__, 'Payment created: ' . wp_json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - return $checkout_info; - } catch ( Exception $e ) { - $this->log->write_log( __FUNCTION__, 'payment creation failed with error: ' . $e->getMessage() ); - return $e->getMessage(); - } - } - - /** - * Create Wallet Button Preference - * - * @param $order - * - * @return false|mixed - */ - public function create_preference_wallet_button( $order ) { - $this->installments = 12; - $preference_wallet_button = new WC_WooMercadoPago_Preference_Custom_Wallet_Button( $this, $order ); - $preference = $preference_wallet_button->get_transaction( 'Preference' ); - - try { - $checkout_info = $preference->save(); - $this->log->write_log( __FUNCTION__, 'Created Preference: ' . wp_json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - return $checkout_info; - } catch ( Exception $e ) { - $this->log->write_log( __FUNCTION__, 'preference creation failed with error: ' . $e->getMessage() ); - return false; - } - } - - /** - * Is available? - * - * @return bool - */ - public function is_available() { - if ( ! parent::is_available() ) { - return false; - } - - $_mp_access_token = $this->mp_options->get_access_token_prod(); - $is_prod_credentials = false === WC_WooMercadoPago_Credentials::validate_credentials_test( $this->mp, $_mp_access_token, null ); - - if ( ( empty( $_SERVER['HTTPS'] ) || 'off' === $_SERVER['HTTPS'] ) && $is_prod_credentials ) { - $this->log->write_log( __FUNCTION__, 'NO HTTPS, Custom unavailable.' ); - return false; - } - - return true; - } - - /** - * Get Id - * - * @return string - */ - public static function get_id() { - return self::ID; - } - - /** - * Get Mercado Pago Icon - * - * @return mixed - */ - public function get_checkout_icon() { - /** - * Add Mercado Pago icon. - * - * @since 3.0.1 - */ - return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/card.png', plugin_dir_path( __FILE__ ) ) ); - } - + ), + 'type' => 'title', + 'class' => 'mp_title_header', + ); + return $checkout_custom_header; + } + + /** + * Field checkout custom payment advanced 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', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'title', + 'class' => 'mp_subtitle_bd', + ); + return $checkout_custom_payments_advanced_title; + } + + /** + * Field Wallet Button toggle + * + * @return array + */ + public function field_checkout_custom_wallet_button_title() { + return array( + 'title' => __( 'Payments via Mercado Pago account', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'Your customers pay faster with saved cards, money balance or other available methods in their Mercado Pago accounts.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_toggle_switch', + 'default' => 'yes', + 'descriptions' => array( + 'enabled' => __( 'Payments via Mercado Pago accounts are active.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'disabled' => __( 'Payments via Mercado Pago accounts are inactive.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'after_toggle' => $this->wallet_button_preview(), + ); + } + + /** + * Generate Wallet Button HTML + * + * @param $key field key + * @param $settings settings array + * + * @return array + */ + public function wallet_button_preview() { + return wc_get_template_html( + 'components/wallet-button.php', + array ( + 'img_wallet_button_uri' => $this->get_wallet_button_example_uri(), + 'img_wallet_button_description' => __( 'Check an example of how it will appear in your store:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Returns wallet button URI based on current store locale + * + * @return string + */ + public function get_wallet_button_example_uri() { + $locale = substr( strtolower(get_locale()), 0, 2 ); + + if ( 'pt' !== $locale && 'es' !== $locale ) { + $locale = 'en'; + } + + return plugins_url( '../assets/images/pix-admin/example-' . $locale . '.png', plugin_dir_path( __FILE__ ) ); + } + + /** + * Get Order Status + * + * @param string $status_detail Status. + * @return string|void + */ + public function get_order_status( $status_detail ) { + switch ( $status_detail ) { + case 'accredited': + return __( 'That’s it, payment accepted!', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'pending_contingency': + return __( 'We are processing your payment. In less than an hour we will send you the result by email.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + 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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_bad_filled_card_number': + return __( 'Check the card number.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_bad_filled_date': + return __( 'Check the expiration date.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_bad_filled_other': + return __( 'Check the information provided.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_bad_filled_security_code': + return __( 'Check the informed security code.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_card_error': + case 'cc_rejected_blacklist': + return __( 'Your payment cannot be processed.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_call_for_authorize': + return __( 'You must authorize payments for your orders.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_card_disabled': + return __( 'Contact your card issuer to activate it. The phone is on the back of your card.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + 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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_high_risk': + return __( 'Your payment was declined. Please select another payment method. It is recommended in cash.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_insufficient_amount': + return __( 'Your payment does not have sufficient funds.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_invalid_installments': + return __( 'Payment cannot process the selected fee.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + case 'cc_rejected_max_attempts': + return __( 'You have reached the limit of allowed attempts. Choose another card or other payment method.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + default: + return __( 'This payment method cannot process your payment.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + } + } + + /** + * Payment Fields + */ + public function payment_fields(): void { + // add css. + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + wp_enqueue_style( + 'woocommerce-mercadopago-narciso-styles', + plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + + $total = $this->get_order_total(); + $subtotal = (float) WC()->cart->subtotal; + $tax = $total - $subtotal; + $discount = $subtotal * ( $this->gateway_discount / 100 ); + $comission = $subtotal * ( $this->commission / 100 ); + $amount = $subtotal - $discount + $comission; + $amount = $amount + $tax; + + $banner_url = $this->get_option( '_mp_custom_banner' ); + $test_mode_link = $this->get_mp_devsite_link($this->checkout_country); + 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 ( 'credit_card' === $tarjeta['type'] ) { + $credit_card[] = array( + 'src' => $tarjeta['image'], + 'alt' => $tarjeta['name'] + ); + } elseif ( 'debit_card' === $tarjeta['type'] || 'prepaid_card' === $tarjeta['type'] ) { + $debit_card[] = array( + 'src' => $tarjeta['image'], + 'alt' => $tarjeta['name'] + ); + } + } + + $payment_methods = array(); + + if ( 0 !== count( $credit_card ) ) { + $payment_methods[] = array( + 'title' => __( 'Credit cards', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'label' => __( 'Up to ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . 12 . __( ' installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'payment_methods' => $credit_card, + ); + } + + if ( 0 !== count( $debit_card ) ) { + $payment_methods[] = array( + 'title' => __( 'Debit cards', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'payment_methods' => $debit_card, + ); + } + + try { + $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->ratio( $this ); + } catch ( Exception $e ) { + $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::DEFAULT_RATIO; + } + + $parameters = array( + 'test_mode' => ! $this->is_production_mode(), + 'test_mode_link' => $test_mode_link, + 'amount' => $amount, + 'site_id' => $this->mp_options->get_site_id(), + 'public_key' => $this->get_public_key(), + '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'], + 'payment_methods' => $payment_methods, + 'wallet_button' => $this->wallet_button, + ); + + $parameters = array_merge($parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions()); + wc_get_template( 'checkout/custom-checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); + } + + /** + * Process payment + * + * @param int $order_id Order Id. + * @return array|void + */ + public function process_payment( $order_id ) { + // phpcs:ignore WordPress.Security.NonceVerification + if ( ! isset( $_POST['mercadopago_custom']) ) { + return $this->process_result_fail( + __FUNCTION__, + __( 'A problem was occurred when processing your payment. Please, try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + __( 'A problem was occurred when processing your payment. Please, try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } + + // phpcs:ignore WordPress.Security.NonceVerification + $custom_checkout = map_deep($_POST['mercadopago_custom'], 'sanitize_text_field'); + $custom_checkout_log = $custom_checkout; + + if ( isset($custom_checkout_log['token']) ) { + unset($custom_checkout_log['token']); + } + + $this->log->write_log( __FUNCTION__, 'POST Custom: ' . wp_json_encode( $custom_checkout_log, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + + $order = wc_get_order( $order_id ); + + $this->process_discount_and_commission( $order_id, $order ); + + if ( 'wallet_button' === $custom_checkout['checkout_type'] ) { + $this->log->write_log( __FUNCTION__, 'preparing to render wallet button checkout.' ); + $response = $this->process_custom_checkout_wallet_button_flow( $order ); + } else { + $this->log->write_log( __FUNCTION__, 'preparing to get response of custom checkout.' ); + $response = $this->process_custom_checkout_flow( $custom_checkout, $order ); + } + + if ( $response ) { + return $response; + } + + return $this->process_result_fail( + __FUNCTION__, + __( 'A problem was occurred when processing your payment. Please, try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + __( 'A problem was occurred when processing your payment. Please, try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } + + /** + * Process Custom Wallet Button Flow + * + * @param WC_Order $order + * + * @return array + */ + protected function process_custom_checkout_wallet_button_flow( $order ) { + return array( + 'result' => 'success', + 'redirect' => add_query_arg( + array( + 'wallet_button' => 'open' + ), + $order->get_checkout_payment_url( true ) + ), + ); + } + + /** + * Process Custom Payment Flow + * + * @param array $custom_checkout + * @param WC_Order $order + * + * @return array|string[] + * @throws WC_Data_Exception + */ + protected function process_custom_checkout_flow( $custom_checkout, $order ) { + 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'] ) && + -1 !== $custom_checkout['installments'] + ) { + $response = $this->create_payment( $order, $custom_checkout ); + + if ( ! is_array( $response ) ) { + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + + $installments = (float) $response['installments']; + $installment_amount = (float) $response['transaction_details']['installment_amount']; + $transaction_amount = (float) $response['transaction_amount']; + $total_paid_amount = (float) $response['transaction_details']['total_paid_amount']; + $last_four_digits = (float) $response['transaction_details']['last_four_digits']; + $id_payment = (float) $response['id']; + + // Old + $order->add_meta_data('mp_installments', $installments); + $order->add_meta_data('mp_transaction_details', $installment_amount); + $order->add_meta_data('mp_transaction_amount', $transaction_amount); + $order->add_meta_data('mp_total_paid_amount', $total_paid_amount); + $order->save(); + + // New key names + $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - installments', $installments); + $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - installment_amount', $installment_amount); + $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - transaction_amount', $transaction_amount); + $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - total_paid_amount', $total_paid_amount); + $order->add_meta_data('Mercado Pago - ' . $id_payment . ' - card_last_four_digits', $last_four_digits); + $order->save(); + + $this->hook->update_mp_order_payments_metadata( $order->get_id(), array($response['id']) ); + + // 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' ); + $this->set_order_to_pending_on_retry( $order ); + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_order_received_url(), + ); + case 'pending': + // Order approved/pending, we just redirect to the thankyou page. + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_order_received_url(), + ); + 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', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

', + 'notice' + ); + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_payment_url( true ), + ); + 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.', + LKN_WC_MERCADOPAGO_TEXT_DOMAIN + ) . '
' . + $this->get_order_status( $response['status_detail'] ) . + '

' . + '

' . + __( 'Click to try again', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

', + 'error' + ); + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_payment_url( true ), + ); + case 'cancelled': + case 'in_mediation': + case 'charged_back': + // If we enter here (an order generating a direct [cancelled, in_mediation, or charged_back] status), + // then there must be something very wrong! + break; + default: + break; + } + } + + // Process when fields are incomplete. + return $this->process_result_fail( + __FUNCTION__, + __( 'A problem was occurred when processing your payment. Are you sure you have correctly filled all information in the checkout form?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + __( 'A problem was occurred when processing your payment. Are you sure you have correctly filled all information in the checkout form?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' MERCADO PAGO: ' . + WC_WooMercadoPago_Module::get_common_error_messages( $response ) + ); + } + } + + /** + * Display installment fee as an order attachment item + * + * @param $order_id + */ + public function display_installment_fee_order( $order_id ): void { + $order = wc_get_order( $order_id ); + $order->get_meta_data(); + + $gatewayName = $order->get_meta( '_used_gateway' ); + if ( strpos($gatewayName, 'Custom_Gateway') ) { + $total_paid_amount = $order->get_meta( 'mp_total_paid_amount' ); + $transaction_amount = $order->get_meta( 'mp_transaction_amount' ); + $installment_fee_amount = (float) $total_paid_amount - (float) $transaction_amount; + $total_with_fees = $installment_fee_amount + (float) $transaction_amount; + + if ( $installment_fee_amount > 0 ) { + $this->display_order_note( array( + 'tip_text' => __('Represents the installment fee charged by Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'title' => __('Mercado Pago Installment Fee:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'value' => wc_price($installment_fee_amount, array()), + ) ); + + $this->display_order_note( array( + 'tip_text' => __('Represents the total purchase plus the installment fee charged by Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'title' => __('Mercado Pago Total:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'value' => wc_price($total_with_fees, array()), + ) ); + } + } + } + + /** + * Display generic template for order notes + * + * @param array $params + */ + public function display_order_note( $params ): void { + wc_get_template( + 'order/generic-order-note.php', + $params, + 'woo/mercado/pago/module/', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Fill a commission and discount information + * + * @param $order_id + * @param $order + */ + protected function process_discount_and_commission( $order_id, $order ): void { + $amount = (float) WC()->cart->subtotal; + $shipping_taxes = (float) ($order->get_shipping_total()); + + $order->update_meta_data( 'is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no' ); + $order->update_meta_data( '_used_gateway', get_class( $this ) ); + + if ( ! empty( $this->gateway_discount ) ) { + $discount = ( $amount * $this->gateway_discount / 100 ); + $order->set_total($amount - $discount + $shipping_taxes); + } + + if ( ! empty( $this->commission ) ) { + $comission = $amount * ( $this->commission / 100 ); + $order->update_meta_data( 'Mercado Pago: commission', __( 'fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . $this->commission . '% / ' . __( 'fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' = ' . $comission ); + } + $order->save(); + } + + /** + * Process if result is fail + * + * @param $function + * @param $log_message + * @param $notice_message + * + * @return string[] + */ + protected function process_result_fail( $function, $log_message, $notice_message ) { + $this->log->write_log( $function, $log_message ); + + wc_add_notice( + '

' . $notice_message . '

', + 'error' + ); + + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + + /** + * Create Payment + * + * @param object $order Order. + * @param mixed $custom_checkout Checkout info. + * @return string|array + */ + protected function create_payment( $order, $custom_checkout ) { + $preferences_custom = new WC_WooMercadoPago_Preference_Custom( $this, $order, $custom_checkout ); + $payment = $preferences_custom->get_transaction( 'Payment' ); + + try { + $checkout_info = $payment->save(); + $this->log->write_log( __FUNCTION__, 'Payment created: ' . wp_json_encode( $checkout_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + return $checkout_info; + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, 'payment creation failed with error: ' . $e->getMessage() ); + return $e->getMessage(); + } + } + + /** + * Create Wallet Button Preference + * + * @param $order + * + * @return false|mixed + */ + public function create_preference_wallet_button( $order ) { + $this->installments = 12; + $preference_wallet_button = new WC_WooMercadoPago_Preference_Custom_Wallet_Button( $this, $order ); + $preference = $preference_wallet_button->get_transaction( 'Preference' ); + + try { + $checkout_info = $preference->save(); + $this->log->write_log( __FUNCTION__, 'Created Preference: ' . wp_json_encode( $checkout_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + return $checkout_info; + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, 'preference creation failed with error: ' . $e->getMessage() ); + return false; + } + } + + /** + * Is available? + * + * @return bool + */ + public function is_available() { + if ( ! parent::is_available() ) { + return false; + } + + $_mp_access_token = $this->mp_options->get_access_token_prod(); + $is_prod_credentials = false === WC_WooMercadoPago_Credentials::validate_credentials_test( $this->mp, $_mp_access_token, null ); + + if ( ( empty( $_SERVER['HTTPS'] ) || 'off' === $_SERVER['HTTPS'] ) && $is_prod_credentials ) { + $this->log->write_log( __FUNCTION__, 'NO HTTPS, Custom unavailable.' ); + return false; + } + + return true; + } + + /** + * Get Id + * + * @return string + */ + public static function get_id() { + return self::ID; + } + + /** + * Get Mercado Pago Icon + * + * @return mixed + */ + public function get_checkout_icon() { + /** + * Add Mercado Pago icon. + * + * @since 3.0.1 + */ + return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/card.png', plugin_dir_path( __FILE__ ) ) ); + } } diff --git a/includes/payments/class-wc-woomercadopago-payment-abstract.php b/includes/payments/class-wc-woomercadopago-payment-abstract.php index 1d33f230a..ae3270347 100755 --- a/includes/payments/class-wc-woomercadopago-payment-abstract.php +++ b/includes/payments/class-wc-woomercadopago-payment-abstract.php @@ -1,16 +1,9 @@ mp_options = $this->get_mp_options(); - $this->mp_nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); - $this->mp_public_key_test = $this->mp_options->get_public_key_test(); - $this->mp_access_token_test = $this->mp_options->get_access_token_test(); - $this->mp_public_key_prod = $this->mp_options->get_public_key_prod(); - $this->mp_access_token_prod = $this->mp_options->get_access_token_prod(); - $this->checkout_country = $this->mp_options->get_checkout_country(); - $this->wc_country = $this->mp_options->get_woocommerce_country(); - $this->mp_category_id = false === $this->mp_options->get_store_category() ? 'others' : $this->mp_options->get_store_category(); - $this->store_identificator = false === $this->mp_options->get_store_id() ? 'WC-' : $this->mp_options->get_store_id(); - $this->integrator_id = $this->mp_options->get_integrator_id(); - $this->debug_mode = false === $this->mp_options->get_debug_mode() ? 'no' : $this->mp_options->get_debug_mode(); - $this->custom_domain = $this->mp_options->get_custom_domain(); - $this->custom_domain_options = $this->mp_options->get_custom_domain_options(); - $this->binary_mode = $this->get_option( 'binary_mode', 'no' ); - $this->gateway_discount = $this->get_activable_value('gateway_discount', 0); - $this->commission = $this->get_activable_value('commission', 0); - $this->sandbox = $this->is_test_user(); - $this->supports = array( 'products', 'refunds' ); - $this->site_data = WC_WooMercadoPago_Module::get_site_data(); - $this->log = new WC_WooMercadoPago_Log( $this ); - $this->mp = $this->get_mp_instance(); - $this->homolog_validate = WC_WooMercadoPago_Credentials::get_homolog_validate( $this->is_production_mode(), $this->mp_access_token_prod ); - $this->application_id = $this->get_application_id( $this->mp_access_token_prod ); - $this->logged_user_email = ( 0 !== wp_get_current_user()->ID ) ? wp_get_current_user()->user_email : null; - $this->discount_action_url = get_site_url() . '/index.php/woocommerce-mercadopago/?wc-api=' . get_class( $this ); - $prior_user = wp_get_current_user(); - $this->prior_uid = (int) $prior_user->ID; - - add_action( 'woocommerce_after_settings_checkout', array($this, 'mercadopago_after_form') ); - } - - /** - * Get SDK instance - * - * @return SDK - */ - public function get_sdk_instance() { - $is_production_mode = $this->is_production_mode(); - - $access_token = 'no' === $is_production_mode || ! $is_production_mode - ? get_option( '_mp_access_token_test' ) - : get_option( '_mp_access_token_prod' ); - - $platform_id = WC_WooMercadoPago_Constants::PLATAFORM_ID; - $product_id = WC_WooMercadoPago_Module::is_mobile() ? WC_WooMercadoPago_Constants::PRODUCT_ID_MOBILE : WC_WooMercadoPago_Constants::PRODUCT_ID_DESKTOP; - $integrator_id = $this->integrator_id; - - return new Sdk($access_token, $platform_id, $product_id, $integrator_id); - } - - public function mercadopago_after_form() { - wc_get_template( - 'components/research-fields.php', - array ( - 'field_key' => 'mp-public-key-prod', - 'field_value' => $this->get_public_key(), - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - - $page = [ - 'woo-mercado-pago-basic' => 'checkout-pro', - 'woo-mercado-pago-custom' => 'checkout-custom', - 'woo-mercado-pago-ticket' => 'checkout-ticket', - 'woo-mercado-pago-pix' => 'checkout-pix', - 'woo-mercado-pago-credits' => 'checkout-credits' - ]; - - wc_get_template( - 'components/research-fields.php', - array ( - 'field_key' => 'reference', - 'field_value' => '{"mp-screen-name":"' . $page[$this->get_id()] . '"}', - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Get Id - * - * @return string - */ - public static function get_id() { - return 'abstract'; - } - - /** - * Get Options - * - * @return mixed - */ - public function get_mp_options() { - if ( null === $this->mp_options ) { - $this->mp_options = WC_WooMercadoPago_Options::get_instance(); - } - return $this->mp_options; - } - - /** - * Get Access token - * - * @return mixed|string - */ - public function get_access_token() { - if ( ! $this->is_production_mode() ) { - return $this->mp_access_token_test; - } - return $this->mp_access_token_prod; - } - - /** - * Public key - * - * @return mixed|string - */ - public function get_public_key() { - if ( ! $this->is_production_mode() ) { - return $this->mp_public_key_test; - } - return $this->mp_public_key_prod; - } - - /** - * Configs - * - * @return array - */ - public function get_common_config() { - return array( - '_mp_public_key_test' => $this->mp_options->get_public_key_test(), - '_mp_access_token_test' => $this->mp_options->get_access_token_test(), - '_mp_public_key_prod' => $this->mp_options->get_public_key_prod(), - '_mp_access_token_prod' => $this->mp_options->get_access_token_prod(), - 'checkout_country' => $this->mp_options->get_checkout_country(), - 'mp_statement_descriptor' => $this->mp_options->get_store_name_on_invoice(), - '_mp_category_id' => $this->mp_options->get_store_category(), - '_mp_store_identificator' => $this->mp_options->get_store_id(), - '_mp_integrator_id' => $this->mp_options->get_integrator_id(), - '_mp_custom_domain' => $this->mp_options->get_custom_domain(), - '_mp_custom_domain_options' => $this->mp_options->get_custom_domain_options(), - 'installments' => $this->get_option('installments'), - 'auto_return' => $this->get_option('auto_return'), - ); - } - - /** - * Get options Mercado Pago - * - * @param string $key key. - * @param string $default default. - * @return mixed|string - */ - public function get_option_mp( $key, $default = '' ) { - $wordpress_configs = self::COMMON_CONFIGS; - if ( in_array( $key, $wordpress_configs, true ) ) { - 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 normalize_common_admin_fields() { - if ( empty( $this->mp_access_token_test ) && empty( $this->mp_access_token_prod ) ) { - if ( isset( $this->settings['enabled'] ) && 'yes' === $this->settings['enabled'] ) { - $this->settings['enabled'] = 'no'; - $this->disable_all_payments_methods_mp(); - } - } - - $changed = false; - $options = self::get_common_config(); - foreach ( $options as $config => $common_option ) { - if ( isset( $this->settings[ $config ] ) && $this->settings[ $config ] !== $common_option ) { - $changed = true; - $this->settings[ $config ] = $common_option; - } - } - - if ( $changed ) { - /** - * Update if options were changed. - * - * @since 3.0.1 - */ - update_option( $this->get_option_key(), apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings ) ); - } - } - - public function get_activable_value( $option_key, $default ) { - $active = $this->get_option( $option_key . '_checkbox', false ); - - if ( $active && 'yes' === $active ) { - return $this->get_option( $option_key, $default ); - } - - return $default; - } - - /** - * Validate section - * - * @return bool - */ - public function validate_section() { - - if ( - // phpcs:ignore WordPress.Security.NonceVerification - isset( $_GET['section'] ) && ! empty( $_GET['section'] - ) + /** + * Common configs for payments + * + * @const + */ + public const COMMON_CONFIGS = array( + '_mp_public_key_test', + '_mp_access_token_test', + '_mp_public_key_prod', + '_mp_access_token_prod', + 'checkout_country', + 'mp_statement_descriptor', + '_mp_category_id', + '_mp_store_identificator', + '_mp_integrator_id', + '_mp_custom_domain', + '_mp_custom_domain_options', + 'installments', + 'auto_return', + ); + + /** + * Allowed classes in plugin + * + * @const + */ + public const ALLOWED_CLASSES = array( + 'WC_WooMercadoPago_Basic_Gateway', + 'WC_WooMercadoPago_Custom_Gateway', + 'WC_WooMercadoPago_Ticket_Gateway', + ); + + /** + * Field forms order + * + * @var array + */ + public $field_forms_order; + + /** + * Id + * + * @var string + */ + public $id; + + /** + * Method Title + * + * @var string + */ + public $method_title; + + /** + * Title + * + * @var string + */ + public $title; + + /** + * Description + * + * @var string + */ + public $description; + + /** + * Payments + * + * @var array + */ + public $ex_payments = array(); + + /** + * Method + * + * @var string + */ + public $method; + + /** + * Method description + * + * @var string + */ + public $method_description; + + /** + * Auto return + * + * @var string + */ + public $auto_return; + + /** + * Success url + * + * @var string + */ + public $success_url; + + /** + * Failure url + * + * @var string + */ + public $failure_url; + + /** + * Pending url + * + * @var string + */ + public $pending_url; + + /** + * Installments + * + * @var string + */ + public $installments = 1; + + /** + * Form fields + * + * @var array + */ + public $form_fields; + + /** + * Coupon Mode + * + * @var string + */ + public $coupon_mode; + + /** + * Payment Type + * + * @var string + */ + public $payment_type; + + /** + * Checkout type + * + * @var string + */ + public $checkout_type; + + /** + * Stock reduce mode + * + * @var string + */ + public $stock_reduce_mode; + + /** + * Expiration date + * + * @var int + */ + public $date_expiration; + + /** + * Hook + * + * @var WC_WooMercadoPago_Hook_Abstract + */ + public $hook; + + /** + * Supports + * + * @var string[] + */ + public $supports; + + /** + * Icon + * + * @var mixed + */ + public $icon; + + /** + * Category Id + * + * @var mixed|string + */ + public $mp_category_id; + + /** + * Store Identificator + * + * @var mixed|string + */ + public $store_identificator; + + /** + * Integrator Id + * + * @var mixed|string + */ + public $integrator_id; + + /** + * Is debug mode + * + * @var mixed|string + */ + public $debug_mode; + + /** + * Custom domain + * + * @var mixed|string + */ + public $custom_domain; + + /** + * Custom domain + * + * @var bool + */ + public $custom_domain_options; + + /** + * Is binary mode + * + * @var mixed|string + */ + public $binary_mode; + + /** + * Gateway discount + * + * @var mixed|string + */ + public $gateway_discount; + + /** + * Site data + * + * @var string|null + */ + public $site_data; + + /** + * Logs + * + * @var WC_WooMercadoPago_Log + */ + public $log; + + /** + * Is sandbox? + * + * @var bool + */ + public $sandbox; + + /** + * Mercado Pago + * + * @var MP|null + */ + public $mp; + + /** + * Public key test + * + * @var mixed|string + */ + public $mp_public_key_test; + + /** + * Access token test + * + * @var mixed|string + */ + public $mp_access_token_test; + + /** + * Public key prod + * + * @var mixed|string + */ + public $mp_public_key_prod; + + /** + * Access token prod + * + * @var mixed|string + */ + public $mp_access_token_prod; + + /** + * Notification + * + * @var WC_WooMercadoPago_Notification_Abstract + */ + public $notification; + + /** + * Checkout country + * + * @var string + */ + public $checkout_country; + + /** + * Country + * + * @var string + */ + public $wc_country; + + /** + * Comission + * + * @var mixed|string + */ + public $commission; + + /** + * Application Id + * + * @var string + */ + public $application_id; + + /** + * Type payments + * + * @var string + */ + public $type_payments; + + /** + * Actived payments + * + * @var array + */ + public $activated_payment; + + /** + * Is validate homolog + * + * @var int|mixed + */ + public $homolog_validate; + + /** + * Client Id old version + * + * @var string + */ + public $clientid_old_version; + + /** + * Customer + * + * @var array|mixed|null + */ + public $customer; + + /** + * Logged user + * + * @var string|null + */ + public $logged_user_email; + + /** + * Currency convertion? + * + * @var boolean + */ + public $currency_convertion; + + /** + * Options + * + * @var WC_WooMercadoPago_Options + */ + public $mp_options; + + /** + * Nonce + * + * @var WC_WooMercadoPago_Helper_Nonce + */ + public $mp_nonce; + + /** + * Gateway title + * + * @var string + */ + public $title_gateway; + + /** + * User id + * + * @var int + */ + public $prior_uid; + + /** + * Discount action URL + * + * @var string + */ + public $discount_action_url; + + /** + * WC_WooMercadoPago_PaymentAbstract constructor. + * + * @throws WC_WooMercadoPago_Exception Load payment exception. + */ + public function __construct() { + $this->mp_options = $this->get_mp_options(); + $this->mp_nonce = WC_WooMercadoPago_Helper_Nonce::get_instance(); + $this->mp_public_key_test = $this->mp_options->get_public_key_test(); + $this->mp_access_token_test = $this->mp_options->get_access_token_test(); + $this->mp_public_key_prod = $this->mp_options->get_public_key_prod(); + $this->mp_access_token_prod = $this->mp_options->get_access_token_prod(); + $this->checkout_country = $this->mp_options->get_checkout_country(); + $this->wc_country = $this->mp_options->get_woocommerce_country(); + $this->mp_category_id = false === $this->mp_options->get_store_category() ? 'others' : $this->mp_options->get_store_category(); + $this->store_identificator = false === $this->mp_options->get_store_id() ? 'WC-' : $this->mp_options->get_store_id(); + $this->integrator_id = $this->mp_options->get_integrator_id(); + $this->debug_mode = false === $this->mp_options->get_debug_mode() ? 'no' : $this->mp_options->get_debug_mode(); + $this->custom_domain = $this->mp_options->get_custom_domain(); + $this->custom_domain_options = $this->mp_options->get_custom_domain_options(); + $this->binary_mode = $this->get_option( 'binary_mode', 'no' ); + $this->gateway_discount = $this->get_activable_value('gateway_discount', 0); + $this->commission = $this->get_activable_value('commission', 0); + $this->sandbox = $this->is_test_user(); + $this->supports = array('products', 'refunds'); + $this->site_data = WC_WooMercadoPago_Module::get_site_data(); + $this->log = new WC_WooMercadoPago_Log( $this ); + $this->mp = $this->get_mp_instance(); + $this->homolog_validate = WC_WooMercadoPago_Credentials::get_homolog_validate( $this->is_production_mode(), $this->mp_access_token_prod ); + $this->application_id = $this->get_application_id( $this->mp_access_token_prod ); + $this->logged_user_email = ( 0 !== wp_get_current_user()->ID ) ? wp_get_current_user()->user_email : null; + $this->discount_action_url = get_site_url() . '/index.php/woocommerce-mercadopago/?wc-api=' . get_class( $this ); + $prior_user = wp_get_current_user(); + $this->prior_uid = (int) $prior_user->ID; + + add_action( 'woocommerce_after_settings_checkout', array($this, 'mercadopago_after_form') ); + } + + /** + * Get SDK instance + * + * @return SDK + */ + public function get_sdk_instance() { + $is_production_mode = $this->is_production_mode(); + + $access_token = 'no' === $is_production_mode || ! $is_production_mode + ? get_option( '_mp_access_token_test' ) + : get_option( '_mp_access_token_prod' ); + + $platform_id = WC_WooMercadoPago_Constants::PLATAFORM_ID; + $product_id = WC_WooMercadoPago_Module::is_mobile() ? WC_WooMercadoPago_Constants::PRODUCT_ID_MOBILE : WC_WooMercadoPago_Constants::PRODUCT_ID_DESKTOP; + $integrator_id = $this->integrator_id; + + return new Sdk($access_token, $platform_id, $product_id, $integrator_id); + } + + public function mercadopago_after_form(): void { + wc_get_template( + 'components/research-fields.php', + array ( + 'field_key' => 'mp-public-key-prod', + 'field_value' => $this->get_public_key(), + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + + $page = array( + 'woo-mercado-pago-basic' => 'checkout-pro', + 'woo-mercado-pago-custom' => 'checkout-custom', + 'woo-mercado-pago-ticket' => 'checkout-ticket', + 'woo-mercado-pago-pix' => 'checkout-pix', + 'woo-mercado-pago-credits' => 'checkout-credits' + ); + + wc_get_template( + 'components/research-fields.php', + array ( + 'field_key' => 'reference', + 'field_value' => '{"mp-screen-name":"' . $page[$this->get_id()] . '"}', + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Get Id + * + * @return string + */ + public static function get_id() { + return 'abstract'; + } + + /** + * Get Options + * + * @return mixed + */ + public function get_mp_options() { + if ( null === $this->mp_options ) { + $this->mp_options = WC_WooMercadoPago_Options::get_instance(); + } + return $this->mp_options; + } + + /** + * Get Access token + * + * @return mixed|string + */ + public function get_access_token() { + if ( ! $this->is_production_mode() ) { + return $this->mp_access_token_test; + } + return $this->mp_access_token_prod; + } + + /** + * Public key + * + * @return mixed|string + */ + public function get_public_key() { + if ( ! $this->is_production_mode() ) { + return $this->mp_public_key_test; + } + return $this->mp_public_key_prod; + } + + /** + * Configs + * + * @return array + */ + public function get_common_config() { + return array( + '_mp_public_key_test' => $this->mp_options->get_public_key_test(), + '_mp_access_token_test' => $this->mp_options->get_access_token_test(), + '_mp_public_key_prod' => $this->mp_options->get_public_key_prod(), + '_mp_access_token_prod' => $this->mp_options->get_access_token_prod(), + 'checkout_country' => $this->mp_options->get_checkout_country(), + 'mp_statement_descriptor' => $this->mp_options->get_store_name_on_invoice(), + '_mp_category_id' => $this->mp_options->get_store_category(), + '_mp_store_identificator' => $this->mp_options->get_store_id(), + '_mp_integrator_id' => $this->mp_options->get_integrator_id(), + '_mp_custom_domain' => $this->mp_options->get_custom_domain(), + '_mp_custom_domain_options' => $this->mp_options->get_custom_domain_options(), + 'installments' => $this->get_option('installments'), + 'auto_return' => $this->get_option('auto_return'), + ); + } + + /** + * Get options Mercado Pago + * + * @param string $key key. + * @param string $default default. + * @return mixed|string + */ + public function get_option_mp( $key, $default = '' ) { + $wordpress_configs = self::COMMON_CONFIGS; + if ( in_array( $key, $wordpress_configs, true ) ) { + 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 normalize_common_admin_fields(): void { + if ( empty( $this->mp_access_token_test ) && empty( $this->mp_access_token_prod ) ) { + if ( isset( $this->settings['enabled'] ) && 'yes' === $this->settings['enabled'] ) { + $this->settings['enabled'] = 'no'; + $this->disable_all_payments_methods_mp(); + } + } + + $changed = false; + $options = self::get_common_config(); + foreach ( $options as $config => $common_option ) { + if ( isset( $this->settings[ $config ] ) && $this->settings[ $config ] !== $common_option ) { + $changed = true; + $this->settings[ $config ] = $common_option; + } + } + + if ( $changed ) { + /** + * Update if options were changed. + * + * @since 3.0.1 + */ + update_option( $this->get_option_key(), apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings ) ); + } + } + + public function get_activable_value( $option_key, $default ) { + $active = $this->get_option( $option_key . '_checkbox', false ); + + if ( $active && 'yes' === $active ) { + return $this->get_option( $option_key, $default ); + } + + return $default; + } + + /** + * Validate section + * + * @return bool + */ + public function validate_section() { + if ( + // phpcs:ignore WordPress.Security.NonceVerification + isset( $_GET['section'] ) && ! empty( $_GET['section'] + ) && ( - // phpcs:ignore WordPress.Security.NonceVerification - $this->id !== $_GET['section'] ) && ! in_array( $_GET['section'], self::ALLOWED_CLASSES, true ) - ) { - return false; - } - - return true; - } - - /** - * Is manage section? - * - * @return bool - */ - public function is_manage_section() { - // phpcs:ignore WordPress.Security.NonceVerification - if ( ! isset( $_GET['section'] ) || ( $this->id !== $_GET['section'] ) && ! in_array( $_GET['section'], self::ALLOWED_CLASSES, true ) - ) { - return false; - } - - return true; - } - - /** - * Get Mercado Pago Icon - * - * @return mixed - */ - public function get_mp_icon() { - /** - * Add Mercado Pago icon. - * - * @since 3.0.1 - */ - return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/mercadopago.png', plugin_dir_path( __FILE__ ) ) ); - } - - /** - * Update Option - * - * @param string $key key. - * @param string $value value. - * @return bool - */ - public function update_option( $key, $value = '' ) { - if ( 'enabled' === $key && 'yes' === $value ) { - if ( empty( $this->mp->get_access_token() ) ) { - $message = __( 'Configure your credentials to enable Mercado Pago payment methods.', 'woocommerce-mercadopago' ); - $this->log->write_log( __FUNCTION__, $message ); - echo wp_json_encode( - array( - 'success' => false, - 'data' => $message, - ) - ); - die(); - } - } - return parent::update_option( $key, $value ); - } - - /** - * Get Mercado Pago form fields - * - * @return array - */ - public function get_form_mp_fields() { - $this->init_form_fields(); - $this->init_settings(); - $form_fields = array(); - - if ( ! empty( $this->checkout_country ) ) { - if ( ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { - if ( 0 === $this->homolog_validate ) { - $form_fields['checkout_card_homolog'] = $this->field_checkout_card_homolog(); - } - $form_fields['enabled'] = $this->field_enabled(); - $form_fields['title'] = $this->field_title(); - $form_fields['description'] = $this->field_description(); - $form_fields['gateway_discount'] = $this->field_gateway_discount(); - $form_fields['commission'] = $this->field_commission(); - $form_fields['checkout_payments_advanced_description'] = $this->field_checkout_payments_advanced_description(); - $form_fields[ WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY ] = $this->field_currency_conversion( $this ); - } - } - - if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { - $this->load_custom_credentials_js(); - } - - if ( is_admin() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { - $this->load_custom_js_for_checkbox(); - $this->normalize_common_admin_fields(); - } - $form_fields['checkout_card_validate'] = $this->field_checkout_card_validate(); - return $form_fields; - } - - /** - * Field title - * - * @return array - */ - public function field_title() { - $field_title = array( - 'title' => __( 'Title in the store Checkout', 'woocommerce-mercadopago' ), - 'type' => 'text', - 'description' => __('Change the display text in Checkout, maximum characters: 85', 'woocommerce-mercadopago'), - 'maxlength' => 100, - 'desc_tip' => __( 'The text inserted here will not be translated to other languages', 'woocommerce-mercadopago' ), - 'class' => 'limit-title-max-length', - 'default' => $this->title, - ); - return $field_title; - } - - /** - * Field description - * - * @return array - */ - public function field_description() { - $field_description = array( - 'title' => __( 'Description', 'woocommerce-mercadopago' ), - 'type' => 'text', - 'class' => 'hidden-field-mp-desc', - 'description' => '', - 'default' => $this->method_description, - ); - return $field_description; - } - - /** - * Sort form fields - * - * @param array $form_fields fields. - * @param array $ordination ordination. - * - * @return array - */ - public function sort_form_fields( $form_fields, $ordination ) { - $array = array(); - foreach ( $ordination as $order => $key ) { - if ( ! isset( $form_fields[ $key ] ) ) { - continue; - } - $array[ $key ] = $form_fields[ $key ]; - unset( $form_fields[ $key ] ); - } - return array_merge_recursive( $array, $form_fields ); - } - - /** - * Field checkout card validate - * - * @return array - */ - public function field_checkout_card_validate() { - - $value = array( - 'title' => __('Important! To sell you must enter your credentials.', 'woocommerce-mercadopago'), - 'subtitle' => __('You must enter production credentials.', 'woocommerce-mercadopago'), - 'button_text' => __('Enter credentials', 'woocommerce-mercadopago'), - 'button_url' => admin_url( 'admin.php?page=mercadopago-settings' ), - 'icon' => 'mp-icon-badge-warning', - 'color_card' => 'mp-alert-color-error', - 'size_card' => 'mp-card-body-size', - 'target' => '_self', - ); - - if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { - $value = array( - 'title' => __('Mercado Pago Plugin general settings', 'woocommerce-mercadopago'), __('Important! To sell you must enter your credentials.' , 'woocommerce-mercadopago'), - 'subtitle' => __('Set the deadlines and fees, test your store or access the Plugin manual.', 'woocommerce-mercadopago'), - 'button_text' => __('Go to Settings', 'woocommerce-mercadopago'), - 'button_url' => admin_url( 'admin.php?page=mercadopago-settings' ), - 'icon' => 'mp-icon-badge-info', - 'color_card' => 'mp-alert-color-sucess', - 'size_card' => 'mp-card-body-size', - 'target' => '_self', - ); - } - - return array( - 'type' => 'mp_card_info', - 'value' => $value, - ); - } - - /** - * Field checkout card homolog - * - * @return array - */ - public function field_checkout_card_homolog() { - $country_link = strtolower($this->checkout_country); - $application_id = $this->application_id; - $value = array( - 'title' => __( 'Activate your credentials to be able to sell', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'Credentials are codes that you must enter to enable sales. Go below on Activate Credentials. On the next screen, use again the Activate Credentials button and fill in the fields with the requested information.', 'woocommerce-mercadopago' ), - 'button_text' => __( 'Activate credentials', 'woocommerce-mercadopago' ), - 'button_url' => 'https://www.mercadopago.com/' . $country_link . '/account/credentials/appliance?application_id=' . $application_id, - 'icon' => 'mp-icon-badge-warning', - 'color_card' => 'mp-alert-color-alert', - 'size_card' => 'mp-card-body-size-homolog', - 'target' => '_blank' - ); - - return array( - 'type' => 'mp_card_info', - 'value' => $value, - ); - } - - - /** - * Get Application Id - * - * @param string $mp_access_token_prod access token. - * - * @return mixed|string - * @throws WC_WooMercadoPago_Exception Application Id not found exception. - */ - public function get_application_id( $mp_access_token_prod ) { - if ( empty( $mp_access_token_prod ) ) { - return ''; - } else { - $application_id = $this->mp_options->get_application_id(); - if ( $application_id && '' !== $application_id ) { - return $application_id; - } - $application_id = $this->mp->get_credentials_wrapper( $this->mp_access_token_prod ); - if ( is_array( $application_id ) && isset( $application_id['client_id'] ) ) { - update_option('mp_application_id', $application_id['client_id']); - return $application_id['client_id']; - } - return ''; - } - } - - /** - * Field enabled - * - * @return array - */ - public function field_enabled() { - return array( - 'title' => __( 'Enable the checkout', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'By disabling it, you will disable all payment methods of this checkout.', 'woocommerce-mercadopago' ), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'descriptions' => array( - 'enabled' => __( 'The checkout is enabled.', 'woocommerce-mercadopago' ), - 'disabled' => __( 'The checkout is disabled.', 'woocommerce-mercadopago' ), - ), - ); - } - - /** - * Get suffix to static files - * - * @return String - */ - private function get_suffix() { - return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - } - - /** - * Load Custom JS For Checkbox - * - * @return void - */ - private function load_custom_js_for_checkbox() { - $suffix = $this->get_suffix(); - - wp_enqueue_script( - 'woocommerce-mercadopago-components', - plugins_url( '../assets/js/components_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - } - - /** - * Load Custom JS For Checkbox - * - * @return void - */ - private function load_custom_credentials_js() { - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - - wp_enqueue_script( - 'woocommerce-mercadopago-credentials', - plugins_url( '../assets/js/validate-credentials' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - } - - /** - * Field Checkout Payments Subtitle - * - * @return array - */ - public function field_checkout_payments_subtitle() { - return array( - 'title' => __( 'Basic Configuration', 'woocommerce-mercadopago' ), - 'type' => 'title', - 'class' => 'mp_subtitle mp-mt-5 mp-mb-0', - ); - } - - /** - * Field Coupon Mode - * - * @return array - */ - public function field_coupon_mode() { - return array( - 'title' => __( 'Discount coupons', 'woocommerce-mercadopago' ), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'subtitle' => __( 'Will you offer discount coupons to customers who buy with Mercado Pago?', 'woocommerce-mercadopago' ), - 'descriptions' => array( - 'enabled' => __( 'Discount coupons is active.', 'woocommerce-mercadopago' ), - 'disabled' => __( 'Discount coupons is disabled.', 'woocommerce-mercadopago' ), - ), - ); - } - - /** - * Field Binary Mode - * - * @return array - */ - public function field_binary_mode() { - return array( - 'title' => __( 'Automatic decline of payments without instant approval', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'Enable it if you want to automatically decline payments that are not instantly approved by banks or other institutions. ', 'woocommerce-mercadopago' ), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'descriptions' => array( - 'enabled' => __( 'Pending payments will be automatically declined.', 'woocommerce-mercadopago' ), - 'disabled' => __( 'Pending payments will not be automatically declined.', 'woocommerce-mercadopago' ), - ), - ); - } - - /** - * Field Gateway Discount - * - * @return array - */ - public function field_gateway_discount() { - return array( - 'title' => __( 'Discount in Mercado Pago Checkouts', 'woocommerce-mercadopago' ), - 'type' => 'mp_activable_input', - 'input_type' => 'number', - 'description' => __( 'Choose a percentage value that you want to discount your customers for paying with Mercado Pago.', 'woocommerce-mercadopago' ), - 'checkbox_label' => __( 'Activate and show this information on Mercado Pago Checkout', 'woocommerce-mercadopago' ), - 'default' => '0', - 'custom_attributes' => array( - 'step' => '0.01', - 'min' => '0', - 'max' => '99', - ), - ); - } - - /** - * Field Commission - * - * @return array - */ - public function field_commission() { - return array( - 'title' => __( 'Commission in Mercado Pago Checkouts', 'woocommerce-mercadopago' ), - 'type' => 'mp_activable_input', - 'input_type' => 'number', - 'description' => __( 'Choose an additional percentage value that you want to charge as commission to your customers for paying with Mercado Pago.', 'woocommerce-mercadopago' ), - 'checkbox_label' => __( 'Activate and show this information on Mercado Pago Checkout', 'woocommerce-mercadopago' ), - 'default' => '0', - 'custom_attributes' => array( - 'step' => '0.01', - 'min' => '0', - 'max' => '99', - ), - ); - } - - /** - * Field Currency Conversion - * - * @param WC_WooMercadoPago_Payment_Abstract $method Payment abstract. - * @return array - */ - public function field_currency_conversion( WC_WooMercadoPago_Payment_Abstract $method ) { - $description = WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->get_description( $method ); - - return array( - 'title' => __( 'Convert Currency', 'woocommerce-mercadopago' ), - 'subtitle' => $description, - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'descriptions' => array( - 'enabled' => __( 'Currency convertion is enabled.', 'woocommerce-mercadopago' ), - 'disabled' => __( 'Currency convertion is disabled.', 'woocommerce-mercadopago' ), - ), - ); - } - - /** - * Is available? - * - * @return bool - */ - public function is_available() { - if ( ! did_action( 'wp_loaded' ) ) { - return false; - } - global $woocommerce; - $w_cart = $woocommerce->cart; - // Check for recurrent product checkout. - if ( isset( $w_cart ) ) { - if ( WC_WooMercadoPago_Module::is_subscription( $w_cart->get_cart() ) ) { - return false; - } - } - - $_mp_public_key = $this->get_public_key(); - $_mp_access_token = $this->get_access_token(); - $_site_id_v1 = $this->mp_options->get_site_id(); - - if ( ! isset( $this->settings['enabled'] ) ) { - return false; - } - - return ( 'yes' === $this->settings['enabled'] ) && ! empty( $_mp_public_key ) && ! empty( $_mp_access_token ) && ! empty( $_site_id_v1 ); - } - - /** - * Get Admin Url - * - * @return mixed - */ - public function admin_url() { - if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '2.1', '>=' ) ) { - return admin_url( 'admin.php?page=wc-settings&tab=checkout§ion=' . $this->id ); - } - return admin_url( 'admin.php?page=woocommerce_settings&tab=payment_gateways§ion=' . get_class( $this ) ); - } - - /** - * Get common configs - * - * @return array - */ - public function get_common_configs() { - return self::COMMON_CONFIGS; - } - - /** - * Is test user? - * - * @return bool - */ - public function is_test_user() { - if ( $this->is_production_mode() ) { - return false; - } - return true; - } - - /** - * Get Mercado Pago Instance - * - * @return false|MP|null - * @throws WC_WooMercadoPago_Exception Get mercado pago instance error. - */ - public function get_mp_instance() { - $mp = WC_WooMercadoPago_Module::get_mp_instance_singleton( $this ); - if ( ! empty( $mp ) ) { - $mp->sandbox_mode( $this->sandbox ); - } - return $mp; - } - - /** - * Disable Payments MP - */ - public function disable_all_payments_methods_mp() { - foreach ( WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS as $gateway ) { - $key = 'woocommerce_' . $gateway::get_id() . '_settings'; - $options = get_option( $key ); - - if ( ! empty( $options ) ) { - if ( isset( $options['checkbox_checkout_test_mode'] ) && 'no' === $options['checkbox_checkout_test_mode'] && ! empty( $this->mp_access_token_prod ) ) { - continue; - } - - if ( isset( $options['checkbox_checkout_test_mode'] ) && 'yes' === $options['checkbox_checkout_test_mode'] && ! empty( $this->mp_access_token_test ) ) { - continue; - } - - $options['enabled'] = 'no'; - - /** - * Update if options were changed - * - * @since 3.0.1 - */ - update_option( $key, apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $gateway::get_id(), $options ) ); - } - } - } - - /** - * Field Checkout Payments Advanced Description - * - * @return array - */ - public function field_checkout_payments_advanced_description() { - return array( - 'title' => __( 'Edit these advanced fields only when you want to modify the preset values.', 'woocommerce-mercadopago' ), - 'type' => 'title', - 'class' => 'mp_small_text mp-mt--12 mp-mb-18', - ); - } - - /** - * Is currency convertable? - * - * @return bool - */ - public function is_currency_convertable() { - return $this->currency_convertion; - } - - /** - * Is production mode? - * - * @return bool - */ - public function is_production_mode() { - return 'no' === get_option( WC_WooMercadoPago_Options::CHECKBOX_CHECKOUT_TEST_MODE, 'yes' ); - } - - /** - * Get Country Domain By MELI Acronym - * - * @return String - */ - public function get_country_domain_by_meli_acronym( $meliAcronym ) { - $countries = array( - 'mla' => 'ar', - 'mlb' => 'br', - 'mlc' => 'cl', - 'mco' => 'co', - 'mlm' => 'mx', - 'mpe' => 'pe', - 'mlu' => 'uy', - ); - - return $countries[$meliAcronym]; - } - - /** - * Get Mercado Pago Devsite Page Link - * - * @param String $country Country Acronym - * - * @return String - */ - public function get_mp_devsite_link( $country ) { - $country_links = [ - 'mla' => 'https://www.mercadopago.com.ar/developers/es/docs/woocommerce/integration-test', - 'mlb' => 'https://www.mercadopago.com.br/developers/pt/docs/woocommerce/integration-test', - 'mlc' => 'https://www.mercadopago.cl/developers/es/docs/woocommerce/integration-test', - 'mco' => 'https://www.mercadopago.com.co/developers/es/docs/woocommerce/integration-test', - 'mlm' => 'https://www.mercadopago.com.mx/developers/es/docs/woocommerce/integration-test', - 'mpe' => 'https://www.mercadopago.com.pe/developers/es/docs/woocommerce/integration-test', - 'mlu' => 'https://www.mercadopago.com.uy/developers/es/docs/woocommerce/integration-test', - ]; - $link = array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; - - return $link; - } - - /** - * Set Order to Status Pending when is a new attempt - * - * @param $order - */ - public function set_order_to_pending_on_retry( $order ) { - if ( $order->get_status() === 'failed' ) { - $order->set_status('pending'); - $order->save(); - } - } - - /** - * Get Country Link to Mercado Pago - * - * @return string[] - */ - public static function get_country_link_mp_terms() { - $country_link = [ - 'mla' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.ar/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Argentinian. - ], - 'mlb' => [ - 'help' => 'ajuda', - 'sufix_url' => 'com.br/', - 'translate' => 'pt', - 'term_conditition' => '/termos-e-politicas_194', //Brasil - ], - 'mlc' => [ - 'help' => 'ayuda', - 'sufix_url' => 'cl/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Chile. - ], - 'mco' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.co/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Colombia. - ], - 'mlm' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.mx/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Mexico. - ], - 'mpe' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.pe/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Peru. - ], - 'mlu' => [ - 'help' => 'ayuda', - 'sufix_url' => 'com.uy/', - 'translate' => 'es', - 'term_conditition' => '/terminos-y-politicas_194', // Uruguay. - ], - ]; - - $checkout_country = strtolower(get_option( 'checkout_country', '' )); - - return $country_link[ $checkout_country ]; - } - - /** - * - * Define terms and conditions link - * - * @return array - */ - public static function mp_define_terms_and_conditions() { - $links_mp = self::get_country_link_mp_terms(); - $link_prefix_mp = 'https://www.mercadopago.'; - - return array ( - 'link_terms_and_conditions' => $link_prefix_mp . $links_mp['sufix_url'] . $links_mp['help'] . $links_mp['term_conditition'] - ); - } - - /** - * Validate if installments is equal to zero - * - * @return int - */ - public function get_valid_installments( $installments ) { - $installments = (int) $installments; - - if ( 0 === $installments ) { - return 12; - } - - return $installments; - } - - public function generate_mp_activable_input_html( $key, $settings ) { - return wc_get_template_html( - 'components/activable-input.php', - array ( - 'field_key' => $this->get_field_key( $key ), - 'field_key_checkbox' => $this->get_field_key( $key . '_checkbox' ), - 'value' => $this->get_option( $key ), - 'enabled' => $this->get_option( $key . '_checkbox' ), - 'custom_attributes' => $this->get_custom_attribute_html( $settings ), - 'settings' => $settings, - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Generates the toggle switch template - * - * @param string $key key, $settings settings array - * @return string html toggle switch template - */ - public function generate_mp_toggle_switch_html( $key, $settings ) { - return wc_get_template_html( - 'components/toggle-switch.php', - array ( - 'field_key' => $this->get_field_key( $key ), - 'field_value' => $this->get_option( $key, $settings['default'] ), - 'settings' => $settings, - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Generates tip information template - * - * @param string $key key, $settings settings array - * @return string html tip information template - */ - public function generate_mp_card_info_html( $key, $settings ) { - return wc_get_template_html( - 'components/card-info.php', - array ( - 'settings' => $settings, - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Generates the toggle switch template - * - * @param string $key key, $settings settings array - * @return string html toggle switch template - */ - public function generate_mp_checkbox_list_html( $key, $settings ) { - return wc_get_template_html( - 'components/checkbox-list.php', - array ( - 'settings' => $settings, - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Generate checkout visualization template - * - * @param $key - * @param $settings - * - * @return string - */ - public function generate_mp_checkout_visualization_html( $key, $settings ) { - return wc_get_template_html( - 'components/credits-checkout-example.php', - array( - 'settings' => $settings, - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - - /** - * Generate credits banner template - * - * @return string - */ - public function generate_mp_credits_banner_visualization_html( $key, $settings ) { - return wc_get_template_html( - 'components/credits-info-example.php', - array( - 'settings' => $settings, - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - } + // phpcs:ignore WordPress.Security.NonceVerification + $this->id !== $_GET['section'] + ) && ! in_array( $_GET['section'], self::ALLOWED_CLASSES, true ) + ) { + return false; + } + + return true; + } + + /** + * Is manage section? + * + * @return bool + */ + public function is_manage_section() { + // phpcs:ignore WordPress.Security.NonceVerification + if ( ! isset( $_GET['section'] ) || ( $this->id !== $_GET['section'] ) && ! in_array( $_GET['section'], self::ALLOWED_CLASSES, true ) + ) { + return false; + } + + return true; + } + + /** + * Get Mercado Pago Icon + * + * @return mixed + */ + public function get_mp_icon() { + /** + * Add Mercado Pago icon. + * + * @since 3.0.1 + */ + return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/mercadopago.png', plugin_dir_path( __FILE__ ) ) ); + } + + /** + * Update Option + * + * @param string $key key. + * @param string $value value. + * @return bool + */ + public function update_option( $key, $value = '' ) { + if ( 'enabled' === $key && 'yes' === $value ) { + if ( empty( $this->mp->get_access_token() ) ) { + $message = __( 'Configure your credentials to enable Mercado Pago payment methods.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->log->write_log( __FUNCTION__, $message ); + echo wp_json_encode( + array( + 'success' => false, + 'data' => $message, + ) + ); + die(); + } + } + return parent::update_option( $key, $value ); + } + + /** + * Update Option Default + * + * @param string $key key. + * @param string $value value. + * @return bool + */ + public function update_option_default( $key, $value = '' ) { + return parent::update_option( $key, $value ); + } + + /** + * Get Mercado Pago form fields + * + * @return array + */ + public function get_form_mp_fields() { + $this->init_form_fields(); + $this->init_settings(); + $form_fields = array(); + + if ( ! empty( $this->checkout_country ) ) { + if ( ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { + if ( 0 === $this->homolog_validate ) { + $form_fields['checkout_card_homolog'] = $this->field_checkout_card_homolog(); + } + $form_fields['enabled'] = $this->field_enabled(); + $form_fields['title'] = $this->field_title(); + $form_fields['description'] = $this->field_description(); + $form_fields['gateway_discount'] = $this->field_gateway_discount(); + $form_fields['commission'] = $this->field_commission(); + $form_fields['checkout_payments_advanced_description'] = $this->field_checkout_payments_advanced_description(); + $form_fields[ WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY ] = $this->field_currency_conversion( $this ); + } + } + + if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { + $this->load_custom_credentials_js(); + } + + if ( is_admin() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { + $this->load_custom_js_for_checkbox(); + $this->normalize_common_admin_fields(); + } + $form_fields['checkout_card_validate'] = $this->field_checkout_card_validate(); + return $form_fields; + } + + /** + * Field title + * + * @return array + */ + public function field_title() { + $field_title = array( + 'title' => __( 'Title in the store Checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'text', + 'description' => __('Change the display text in Checkout, maximum characters: 85', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'maxlength' => 100, + 'desc_tip' => __( 'The text inserted here will not be translated to other languages', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'class' => 'limit-title-max-length', + 'default' => $this->title, + ); + return $field_title; + } + + /** + * Field description + * + * @return array + */ + public function field_description() { + $field_description = array( + 'title' => __( 'Description', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'text', + 'class' => 'hidden-field-mp-desc', + 'description' => '', + 'default' => $this->method_description, + ); + return $field_description; + } + + /** + * Sort form fields + * + * @param array $form_fields fields. + * @param array $ordination ordination. + * + * @return array + */ + public function sort_form_fields( $form_fields, $ordination ) { + $array = array(); + foreach ( $ordination as $order => $key ) { + if ( ! isset( $form_fields[ $key ] ) ) { + continue; + } + $array[ $key ] = $form_fields[ $key ]; + unset( $form_fields[ $key ] ); + } + return array_merge_recursive( $array, $form_fields ); + } + + /** + * Field checkout card validate + * + * @return array + */ + public function field_checkout_card_validate() { + $value = array( + 'title' => __('Important! To sell you must enter your credentials.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('You must enter production credentials.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'button_text' => __('Enter credentials', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'button_url' => admin_url( 'admin.php?page=mercadopago-settings' ), + 'icon' => 'mp-icon-badge-warning', + 'color_card' => 'mp-alert-color-error', + 'size_card' => 'mp-card-body-size', + 'target' => '_self', + ); + + if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { + $value = array( + 'title' => __('Mercado Pago Plugin general settings', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), __('Important! To sell you must enter your credentials.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('Set the deadlines and fees, test your store or access the Plugin manual.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'button_text' => __('Go to Settings', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'button_url' => admin_url( 'admin.php?page=mercadopago-settings' ), + 'icon' => 'mp-icon-badge-info', + 'color_card' => 'mp-alert-color-sucess', + 'size_card' => 'mp-card-body-size', + 'target' => '_self', + ); + } + + return array( + 'type' => 'mp_card_info', + 'value' => $value, + ); + } + + /** + * Field checkout card homolog + * + * @return array + */ + public function field_checkout_card_homolog() { + $country_link = strtolower($this->checkout_country); + $application_id = $this->application_id; + $value = array( + 'title' => __( 'Activate your credentials to be able to sell', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'Credentials are codes that you must enter to enable sales. Go below on Activate Credentials. On the next screen, use again the Activate Credentials button and fill in the fields with the requested information.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_text' => __( 'Activate credentials', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_url' => 'https://www.mercadopago.com/' . $country_link . '/account/credentials/appliance?application_id=' . $application_id, + 'icon' => 'mp-icon-badge-warning', + 'color_card' => 'mp-alert-color-alert', + 'size_card' => 'mp-card-body-size-homolog', + 'target' => '_blank' + ); + + return array( + 'type' => 'mp_card_info', + 'value' => $value, + ); + } + + /** + * Get Application Id + * + * @param string $mp_access_token_prod access token. + * + * @return mixed|string + * @throws WC_WooMercadoPago_Exception Application Id not found exception. + */ + public function get_application_id( $mp_access_token_prod ) { + if ( empty( $mp_access_token_prod ) ) { + return ''; + } else { + $application_id = $this->mp_options->get_application_id(); + if ( $application_id && '' !== $application_id ) { + return $application_id; + } + $application_id = $this->mp->get_credentials_wrapper( $this->mp_access_token_prod ); + if ( is_array( $application_id ) && isset( $application_id['client_id'] ) ) { + update_option('mp_application_id', $application_id['client_id']); + return $application_id['client_id']; + } + return ''; + } + } + + /** + * Field enabled + * + * @return array + */ + public function field_enabled() { + return array( + 'title' => __( 'Enable the checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'By disabling it, you will disable all payment methods of this checkout.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'descriptions' => array( + 'enabled' => __( 'The checkout is enabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'disabled' => __( 'The checkout is disabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + ); + } + + /** + * Get suffix to static files + * + * @return String + */ + private function get_suffix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Load Custom JS For Checkbox + * + * @return void + */ + private function load_custom_js_for_checkbox(): void { + $suffix = $this->get_suffix(); + + wp_enqueue_script( + 'woocommerce-mercadopago-components', + plugins_url( '../assets/js/components_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + } + + /** + * Load Custom JS For Checkbox + * + * @return void + */ + private function load_custom_credentials_js(): void { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + wp_enqueue_script( + 'woocommerce-mercadopago-credentials', + plugins_url( '../assets/js/validate-credentials' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + } + + /** + * Field Checkout Payments Subtitle + * + * @return array + */ + public function field_checkout_payments_subtitle() { + return array( + 'title' => __( 'Basic Configuration', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'title', + 'class' => 'mp_subtitle mp-mt-5 mp-mb-0', + ); + } + + /** + * Field Coupon Mode + * + * @return array + */ + public function field_coupon_mode() { + return array( + 'title' => __( 'Discount coupons', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'subtitle' => __( 'Will you offer discount coupons to customers who buy with Mercado Pago?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descriptions' => array( + 'enabled' => __( 'Discount coupons is active.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'disabled' => __( 'Discount coupons is disabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + ); + } + + /** + * Field Binary Mode + * + * @return array + */ + public function field_binary_mode() { + return array( + 'title' => __( 'Automatic decline of payments without instant approval', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'Enable it if you want to automatically decline payments that are not instantly approved by banks or other institutions. ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'descriptions' => array( + 'enabled' => __( 'Pending payments will be automatically declined.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'disabled' => __( 'Pending payments will not be automatically declined.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + ); + } + + /** + * Field Gateway Discount + * + * @return array + */ + public function field_gateway_discount() { + return array( + 'title' => __( 'Discount in Mercado Pago Checkouts', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_activable_input', + 'input_type' => 'number', + 'description' => __( 'Choose a percentage value that you want to discount your customers for paying with Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'checkbox_label' => __( 'Activate and show this information on Mercado Pago Checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'default' => '0', + 'custom_attributes' => array( + 'step' => '0.01', + 'min' => '0', + 'max' => '99', + ), + ); + } + + /** + * Field Commission + * + * @return array + */ + public function field_commission() { + return array( + 'title' => __( 'Commission in Mercado Pago Checkouts', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_activable_input', + 'input_type' => 'number', + 'description' => __( 'Choose an additional percentage value that you want to charge as commission to your customers for paying with Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'checkbox_label' => __( 'Activate and show this information on Mercado Pago Checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'default' => '0', + 'custom_attributes' => array( + 'step' => '0.01', + 'min' => '0', + 'max' => '99', + ), + ); + } + + /** + * Field Currency Conversion + * + * @param WC_WooMercadoPago_Payment_Abstract $method Payment abstract. + * @return array + */ + public function field_currency_conversion( WC_WooMercadoPago_Payment_Abstract $method ) { + $description = WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->get_description( $method ); + + return array( + 'title' => __( 'Convert Currency', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => $description, + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'descriptions' => array( + 'enabled' => __( 'Currency convertion is enabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'disabled' => __( 'Currency convertion is disabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + ); + } + + /** + * Is available? + * + * @return bool + */ + public function is_available() { + if ( ! did_action( 'wp_loaded' ) ) { + return false; + } + global $woocommerce; + $w_cart = $woocommerce->cart; + // Check for recurrent product checkout. + if ( isset( $w_cart ) ) { + if ( WC_WooMercadoPago_Module::is_subscription( $w_cart->get_cart() ) ) { + return false; + } + } + + $_mp_public_key = $this->get_public_key(); + $_mp_access_token = $this->get_access_token(); + $_site_id_v1 = $this->mp_options->get_site_id(); + + if ( ! isset( $this->settings['enabled'] ) ) { + return false; + } + + return ( 'yes' === $this->settings['enabled'] ) && ! empty( $_mp_public_key ) && ! empty( $_mp_access_token ) && ! empty( $_site_id_v1 ); + } + + /** + * Get Admin Url + * + * @return mixed + */ + public function admin_url() { + if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '2.1', '>=' ) ) { + return admin_url( 'admin.php?page=wc-settings&tab=checkout§ion=' . $this->id ); + } + return admin_url( 'admin.php?page=woocommerce_settings&tab=payment_gateways§ion=' . get_class( $this ) ); + } + + /** + * Get common configs + * + * @return array + */ + public function get_common_configs() { + return self::COMMON_CONFIGS; + } + + /** + * Is test user? + * + * @return bool + */ + public function is_test_user() { + if ( $this->is_production_mode() ) { + return false; + } + return true; + } + + /** + * Get Mercado Pago Instance + * + * @return false|MP|null + * @throws WC_WooMercadoPago_Exception Get mercado pago instance error. + */ + public function get_mp_instance() { + $mp = WC_WooMercadoPago_Module::get_mp_instance_singleton( $this ); + if ( ! empty( $mp ) ) { + $mp->sandbox_mode( $this->sandbox ); + } + return $mp; + } + + /** + * Disable Payments MP + */ + public function disable_all_payments_methods_mp(): void { + foreach ( WC_WooMercadoPago_Constants::PAYMENT_GATEWAYS as $gateway ) { + $key = 'woocommerce_' . $gateway::get_id() . '_settings'; + $options = get_option( $key ); + + if ( ! empty( $options ) ) { + if ( isset( $options['checkbox_checkout_test_mode'] ) && 'no' === $options['checkbox_checkout_test_mode'] && ! empty( $this->mp_access_token_prod ) ) { + continue; + } + + if ( isset( $options['checkbox_checkout_test_mode'] ) && 'yes' === $options['checkbox_checkout_test_mode'] && ! empty( $this->mp_access_token_test ) ) { + continue; + } + + $options['enabled'] = 'no'; + + /** + * Update if options were changed + * + * @since 3.0.1 + */ + update_option( $key, apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $gateway::get_id(), $options ) ); + } + } + } + + /** + * Field Checkout Payments Advanced Description + * + * @return array + */ + public function field_checkout_payments_advanced_description() { + return array( + 'title' => __( 'Edit these advanced fields only when you want to modify the preset values.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'title', + 'class' => 'mp_small_text mp-mt--12 mp-mb-18', + ); + } + + /** + * Is currency convertable? + * + * @return bool + */ + public function is_currency_convertable() { + return $this->currency_convertion; + } + + /** + * Is production mode? + * + * @return bool + */ + public function is_production_mode() { + return 'no' === get_option( WC_WooMercadoPago_Options::CHECKBOX_CHECKOUT_TEST_MODE, 'yes' ); + } + + /** + * Get Country Domain By MELI Acronym + * + * @return String + */ + public function get_country_domain_by_meli_acronym( $meliAcronym ) { + $countries = array( + 'mla' => 'ar', + 'mlb' => 'br', + 'mlc' => 'cl', + 'mco' => 'co', + 'mlm' => 'mx', + 'mpe' => 'pe', + 'mlu' => 'uy', + ); + + return $countries[$meliAcronym]; + } + + /** + * Get Mercado Pago Devsite Page Link + * + * @param String $country Country Acronym + * + * @return String + */ + public function get_mp_devsite_link( $country ) { + $country_links = array( + 'mla' => 'https://www.mercadopago.com.ar/developers/es/docs/woocommerce/integration-test', + 'mlb' => 'https://www.mercadopago.com.br/developers/pt/docs/woocommerce/integration-test', + 'mlc' => 'https://www.mercadopago.cl/developers/es/docs/woocommerce/integration-test', + 'mco' => 'https://www.mercadopago.com.co/developers/es/docs/woocommerce/integration-test', + 'mlm' => 'https://www.mercadopago.com.mx/developers/es/docs/woocommerce/integration-test', + 'mpe' => 'https://www.mercadopago.com.pe/developers/es/docs/woocommerce/integration-test', + 'mlu' => 'https://www.mercadopago.com.uy/developers/es/docs/woocommerce/integration-test', + ); + $link = array_key_exists($country, $country_links) ? $country_links[$country] : $country_links['mla']; + + return $link; + } + + /** + * Set Order to Status Pending when is a new attempt + * + * @param $order + */ + public function set_order_to_pending_on_retry( $order ): void { + if ( $order->get_status() === 'failed' ) { + $order->set_status('pending'); + $order->save(); + } + } + + /** + * Get Country Link to Mercado Pago + * + * @return string[] + */ + public static function get_country_link_mp_terms() { + $country_link = array( + 'mla' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.ar/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Argentinian. + ), + 'mlb' => array( + 'help' => 'ajuda', + 'sufix_url' => 'com.br/', + 'translate' => 'pt', + 'term_conditition' => '/termos-e-politicas_194', //Brasil + ), + 'mlc' => array( + 'help' => 'ayuda', + 'sufix_url' => 'cl/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Chile. + ), + 'mco' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.co/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Colombia. + ), + 'mlm' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.mx/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Mexico. + ), + 'mpe' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.pe/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Peru. + ), + 'mlu' => array( + 'help' => 'ayuda', + 'sufix_url' => 'com.uy/', + 'translate' => 'es', + 'term_conditition' => '/terminos-y-politicas_194', // Uruguay. + ), + ); + + $checkout_country = strtolower(get_option( 'checkout_country', '' )); + + return $country_link[ $checkout_country ]; + } + + /** + * + * Define terms and conditions link + * + * @return array + */ + public static function mp_define_terms_and_conditions() { + $links_mp = self::get_country_link_mp_terms(); + $link_prefix_mp = 'https://www.mercadopago.'; + + return array ( + 'link_terms_and_conditions' => $link_prefix_mp . $links_mp['sufix_url'] . $links_mp['help'] . $links_mp['term_conditition'] + ); + } + + /** + * Validate if installments is equal to zero + * + * @return int + */ + public function get_valid_installments( $installments ) { + $installments = (int) $installments; + + if ( 0 === $installments ) { + return 12; + } + + return $installments; + } + + public function generate_mp_activable_input_html( $key, $settings ) { + return wc_get_template_html( + 'components/activable-input.php', + array ( + 'field_key' => $this->get_field_key( $key ), + 'field_key_checkbox' => $this->get_field_key( $key . '_checkbox' ), + 'value' => $this->get_option( $key ), + 'enabled' => $this->get_option( $key . '_checkbox' ), + 'custom_attributes' => $this->get_custom_attribute_html( $settings ), + 'settings' => $settings, + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Generates the toggle switch template + * + * @param string $key key, $settings settings array + * @return string html toggle switch template + */ + public function generate_mp_toggle_switch_html( $key, $settings ) { + return wc_get_template_html( + 'components/toggle-switch.php', + array ( + 'field_key' => $this->get_field_key( $key ), + 'field_value' => $this->get_option( $key, $settings['default'] ), + 'settings' => $settings, + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Generates tip information template + * + * @param string $key key, $settings settings array + * @return string html tip information template + */ + public function generate_mp_card_info_html( $key, $settings ) { + return wc_get_template_html( + 'components/card-info.php', + array ( + 'settings' => $settings, + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Generates the toggle switch template + * + * @param string $key key, $settings settings array + * @return string html toggle switch template + */ + public function generate_mp_checkbox_list_html( $key, $settings ) { + return wc_get_template_html( + 'components/checkbox-list.php', + array ( + 'settings' => $settings, + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Generate checkout visualization template + * + * @param $key + * @param $settings + * + * @return string + */ + public function generate_mp_checkout_visualization_html( $key, $settings ) { + return wc_get_template_html( + 'components/credits-checkout-example.php', + array( + 'settings' => $settings, + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + + /** + * Generate credits banner template + * + * @return string + */ + public function generate_mp_credits_banner_visualization_html( $key, $settings ) { + return wc_get_template_html( + 'components/credits-info-example.php', + array( + 'settings' => $settings, + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + } } diff --git a/includes/payments/class-wc-woomercadopago-pix-gateway.php b/includes/payments/class-wc-woomercadopago-pix-gateway.php index 11d2da93b..08e8b2013 100755 --- a/includes/payments/class-wc-woomercadopago-pix-gateway.php +++ b/includes/payments/class-wc-woomercadopago-pix-gateway.php @@ -1,653 +1,640 @@ id = self::ID; - $this->title = __( 'Pix', 'woocommerce-mercadopago' ); - $this->title_gateway = __( 'Pix', 'woocommerce-mercadopago' ); - $this->description = __( 'Transparent Checkout in your store environment', 'woocommerce-mercadopago' ); - $this->mp_options = $this->get_mp_options(); - - if ( ! $this->validate_section() ) { - return; - } - - $this->form_fields = array(); - $this->method_title = __( 'Mercado pago - Customized Checkout', 'woocommerce-mercadopago' ); - $this->title = $this->get_option( 'title', __( 'Pix', 'woocommerce-mercadopago' ) ); - $this->method_description = $this->description; - $this->date_expiration = (int) $this->get_option( 'checkout_pix_date_expiration', '1' ); - $this->type_payments = $this->get_option( 'type_payments', 'no' ); - $this->payment_type = 'pix'; - $this->checkout_type = 'custom'; - $this->activated_payment = get_option( '_mp_payment_methods_pix', '' ); - $this->field_forms_order = $this->get_fields_sequence(); - - parent::__construct(); - - $this->update_pix_method(); - $this->form_fields = $this->get_form_mp_fields(); - $this->hook = new WC_WooMercadoPago_Hook_Pix( $this ); - $this->notification = new WC_WooMercadoPago_Notification_Core( $this ); - $this->currency_convertion = true; - $this->icon = $this->get_checkout_icon(); - - add_action( 'woocommerce_email_before_order_table', array(__CLASS__,'get_pix_template'), 20, 4 ); - add_action( 'woocommerce_order_details_after_order_table', array(__CLASS__,'get_pix_template_order_details') ); - } - - /** - * Get form mp fields - * - * @param string $label Label. - * @return array - */ - public function get_form_mp_fields() { - if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - wp_enqueue_script( - 'woocommerce-mercadopago-pix-config-script', - plugins_url( '../assets/js/pix_config_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - false - ); - } - - if ( empty( $this->checkout_country ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); - } - - if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); - } - - $form_fields = array(); - if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { - $form_fields['checkout_pix_header'] = $this->field_checkout_pix_header(); - if ( empty( $this->activated_payment ) || ! is_array( $this->activated_payment ) || ! in_array( 'pix', $this->activated_payment['pix'], true ) ) { - $form_fields['checkout_steps_pix'] = $this->field_checkout_steps_pix(); - - // phpcs:ignore WordPress.Security.NonceVerification - if ( isset( $_GET['section'] ) && $_GET['section'] === $this->id ) { - add_action( 'admin_notices', array( $this, 'enable_pix_payment_notice' ) ); - } - } - $form_fields['checkout_pix_payments_advanced_title'] = $this->field_checkout_pix_payments_advanced_title(); - $form_fields['checkout_pix_date_expiration'] = $this->field_pix_date_expiration(); - $form_fields['checkout_about_pix'] = $this->field_checkout_about_pix(); - $form_fields['checkout_pix_card_info'] = $this->field_checkout_pix_card_info(); - } - - $form_fields_abs = parent::get_form_mp_fields(); - if ( 1 === count( $form_fields_abs ) ) { - return $form_fields_abs; - } - $form_fields_merge = array_merge( $form_fields_abs, $form_fields ); - $fields = $this->sort_form_fields( $form_fields_merge, $this->field_forms_order ); - - if ( empty( $this->activated_payment ) || ! is_array( $this->activated_payment ) || ! in_array( 'pix', $this->activated_payment['pix'], true ) ) { - $form_fields_not_show = array_flip( $this->get_fields_not_show() ); - $fields = array_diff_key( $fields, $form_fields_not_show ); - } - - return $fields; - } - - /** - * Update Pix Method - * - * @return void - */ - public function update_pix_method() { - $wc_country = WC_WooMercadoPago_Module::get_woocommerce_default_country(); - $site_id = $this->mp_options->get_site_id(); - $_mp_access_token = $this->get_access_token(); - if ( ( 'BR' === $wc_country && '' === $site_id ) || ( 'mlb' === $site_id ) ) { - WC_WooMercadoPago_Credentials::update_pix_method( $this->mp, $_mp_access_token ); - } - } - - /** - * Get fields sequence - * - * @return array - */ - public function get_fields_sequence() { - return array( - // Necessary to run. - 'description', - // Checkout de pagos con dinero en efectivo
Aceptá pagos al instante y maximizá la conversión de tu negocio. - 'checkout_pix_header', - // No olvides de homologar tu cuenta. - 'checkout_card_homolog', - // Steps configuration pix. - 'checkout_steps_pix', - // Configure the personalized payment experience in your store. - 'checkout_payments_subtitle', - 'checkout_card_validate', - 'enabled', - 'title', - 'checkout_pix_date_expiration', - WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, - // About PIX. - 'checkout_about_pix', - 'checkout_pix_card_info', - // Advanced configuration of the personalized payment experience. - 'checkout_pix_payments_advanced_title', - 'checkout_payments_advanced_description', - 'gateway_discount', - 'commission', - ); - } - - /** - * Get fields NOT allow to show - * - * @return array - */ - public function get_fields_not_show() { - return array( - // Configure the personalized payment experience in your store. - 'checkout_payments_subtitle', - 'enabled', - 'title', - 'checkout_pix_date_expiration', - WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, - // About PIX. - 'checkout_about_pix', - 'checkout_pix_card_info', - // Advanced configuration of the personalized payment experience. - 'checkout_pix_payments_advanced_title', - 'checkout_payments_advanced_description', - 'gateway_discount', - 'commission', - ); - } - - /** - * Field enabled - * - * @return array - */ - public function field_enabled() { - return array( - 'title' => __( 'Enable the checkout', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'By disabling it, you will disable all Pix payments from Mercado Pago Transparent Checkout.', 'woocommerce-mercadopago' ), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'descriptions' => array( - 'enabled' => __( 'The transparent checkout for Pix payment is enabled.', 'woocommerce-mercadopago' ), - 'disabled' => __( 'The transparent checkout for Pix payment is disabled.', 'woocommerce-mercadopago' ), - ), - ); - } - - - /** - * Field checkout steps - * - * @return array - */ - public function field_checkout_steps_pix() { - $steps_content = wc_get_template_html( - 'checkout/credential/steps-pix.php', - array( - 'title' => __( 'To activate Pix, you must have a key registered in Mercado Pago.', 'woocommerce-mercadopago' ), - 'step_one_text' => __( 'Download the Mercado Pago app on your cell phone.', 'woocommerce-mercadopago' ), - 'step_two_text_one' => __( 'Go to the ', 'woocommerce-mercadopago' ), - 'step_two_text_two' => __( 'area and choose the ', 'woocommerce-mercadopago' ), - 'step_two_text_highlight_one' => __( 'Your Profile ', 'woocommerce-mercadopago' ), - 'step_two_text_highlight_two' => __( 'Your Pix Keys section.', 'woocommerce-mercadopago' ), - 'step_three_text' => __( 'Choose which data to register as Pix keys. After registering, you can set up Pix in your checkout.', 'woocommerce-mercadopago' ), - 'observation_one' => __( 'Remember that, for the time being, the Central Bank of Brazil is open Monday through Friday, from 9am to 6pm.', 'woocommerce-mercadopago' ), - 'observation_two' => __( 'If you requested your registration outside these hours, we will confirm it within the next business day.', 'woocommerce-mercadopago' ), - 'button_about_pix' => __( 'Learn more about Pix', 'woocommerce-mercadopago' ), - 'observation_three' => __( 'If you have already registered a Pix key at Mercado Pago and cannot activate Pix in the checkout, ', 'woocommerce-mercadopago' ), - 'link_title_one' => __( 'click here.', 'woocommerce-mercadopago' ), - 'link_url_one' => 'https://www.mercadopago.com.br/pix/', - 'link_url_two' => 'https://www.mercadopago.com.br/developers/pt/support/contact', - ), - 'woo/mercado/pago/steps/', - WC_WooMercadoPago_Module::get_templates_path() - ); - - return array( - 'title' => $steps_content, - 'type' => 'title', - 'class' => 'mp_title_checkout', - ); - } - - /** - * Field checkout pix header - * - * @return array - */ - public function field_checkout_pix_header() { - return array( - 'title' => sprintf( - '
+ /** + * ID + * + * @const + */ + public const ID = 'woo-mercado-pago-pix'; + + /** + * WC_WooMercadoPago_PixGateway constructor. + * + * @throws WC_WooMercadoPago_Exception Load payment exception. + */ + public function __construct() { + $this->id = self::ID; + $this->title = __( 'Pix', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->title_gateway = __( 'Pix', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->description = __( 'Transparent Checkout in your store environment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->mp_options = $this->get_mp_options(); + + if ( ! $this->validate_section() ) { + return; + } + + $this->form_fields = array(); + $this->method_title = __( 'Mercado pago - Customized Checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->title = $this->get_option( 'title', __( 'Pix', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + $this->method_description = $this->description; + $this->date_expiration = (int) $this->get_option( 'checkout_pix_date_expiration', '1' ); + $this->type_payments = $this->get_option( 'type_payments', 'no' ); + $this->payment_type = 'pix'; + $this->checkout_type = 'custom'; + $this->activated_payment = get_option( '_mp_payment_methods_pix', '' ); + $this->field_forms_order = $this->get_fields_sequence(); + + parent::__construct(); + + $this->update_pix_method(); + $this->form_fields = $this->get_form_mp_fields(); + $this->hook = new WC_WooMercadoPago_Hook_Pix( $this ); + $this->notification = new WC_WooMercadoPago_Notification_Core( $this ); + $this->currency_convertion = true; + $this->icon = $this->get_checkout_icon(); + + add_action( 'woocommerce_email_before_order_table', array(__CLASS__, 'get_pix_template'), 20, 4 ); + add_action( 'woocommerce_order_details_after_order_table', array(__CLASS__, 'get_pix_template_order_details') ); + } + + /** + * Get form mp fields + * + * @param string $label Label. + * @return array + */ + public function get_form_mp_fields() { + if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + wp_enqueue_script( + 'woocommerce-mercadopago-pix-config-script', + plugins_url( '../assets/js/pix_config_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + false + ); + } + + if ( empty( $this->checkout_country ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); + } + + if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); + } + + $form_fields = array(); + if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { + $form_fields['checkout_pix_header'] = $this->field_checkout_pix_header(); + if ( empty( $this->activated_payment ) || ! is_array( $this->activated_payment ) || ! in_array( 'pix', $this->activated_payment['pix'], true ) ) { + $form_fields['checkout_steps_pix'] = $this->field_checkout_steps_pix(); + + // phpcs:ignore WordPress.Security.NonceVerification + if ( isset( $_GET['section'] ) && $_GET['section'] === $this->id ) { + add_action( 'admin_notices', array($this, 'enable_pix_payment_notice') ); + } + } + $form_fields['checkout_pix_payments_advanced_title'] = $this->field_checkout_pix_payments_advanced_title(); + $form_fields['checkout_pix_date_expiration'] = $this->field_pix_date_expiration(); + $form_fields['checkout_about_pix'] = $this->field_checkout_about_pix(); + $form_fields['checkout_pix_card_info'] = $this->field_checkout_pix_card_info(); + } + + $form_fields_abs = parent::get_form_mp_fields(); + if ( 1 === count( $form_fields_abs ) ) { + return $form_fields_abs; + } + $form_fields_merge = array_merge( $form_fields_abs, $form_fields ); + $fields = $this->sort_form_fields( $form_fields_merge, $this->field_forms_order ); + + if ( empty( $this->activated_payment ) || ! is_array( $this->activated_payment ) || ! in_array( 'pix', $this->activated_payment['pix'], true ) ) { + $form_fields_not_show = array_flip( $this->get_fields_not_show() ); + $fields = array_diff_key( $fields, $form_fields_not_show ); + } + + return $fields; + } + + /** + * Update Pix Method + * + * @return void + */ + public function update_pix_method(): void { + $wc_country = WC_WooMercadoPago_Module::get_woocommerce_default_country(); + $site_id = $this->mp_options->get_site_id(); + $_mp_access_token = $this->get_access_token(); + if ( ( 'BR' === $wc_country && '' === $site_id ) || ( 'mlb' === $site_id ) ) { + WC_WooMercadoPago_Credentials::update_pix_method( $this->mp, $_mp_access_token ); + } + } + + /** + * Get fields sequence + * + * @return array + */ + public function get_fields_sequence() { + return array( + // Necessary to run. + 'description', + // Checkout de pagos con dinero en efectivo
Aceptá pagos al instante y maximizá la conversión de tu negocio. + 'checkout_pix_header', + // No olvides de homologar tu cuenta. + 'checkout_card_homolog', + // Steps configuration pix. + 'checkout_steps_pix', + // Configure the personalized payment experience in your store. + 'checkout_payments_subtitle', + 'checkout_card_validate', + 'enabled', + 'title', + 'checkout_pix_date_expiration', + WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, + // About PIX. + 'checkout_about_pix', + 'checkout_pix_card_info', + // Advanced configuration of the personalized payment experience. + 'checkout_pix_payments_advanced_title', + 'checkout_payments_advanced_description', + 'gateway_discount', + 'commission', + ); + } + + /** + * Get fields NOT allow to show + * + * @return array + */ + public function get_fields_not_show() { + return array( + // Configure the personalized payment experience in your store. + 'checkout_payments_subtitle', + 'enabled', + 'title', + 'checkout_pix_date_expiration', + WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, + // About PIX. + 'checkout_about_pix', + 'checkout_pix_card_info', + // Advanced configuration of the personalized payment experience. + 'checkout_pix_payments_advanced_title', + 'checkout_payments_advanced_description', + 'gateway_discount', + 'commission', + ); + } + + /** + * Field enabled + * + * @return array + */ + public function field_enabled() { + return array( + 'title' => __( 'Enable the checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'By disabling it, you will disable all Pix payments from Mercado Pago Transparent Checkout.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'descriptions' => array( + 'enabled' => __( 'The transparent checkout for Pix payment is enabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'disabled' => __( 'The transparent checkout for Pix payment is disabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + ); + } + + /** + * Field checkout steps + * + * @return array + */ + public function field_checkout_steps_pix() { + $steps_content = wc_get_template_html( + 'checkout/credential/steps-pix.php', + array( + 'title' => __( 'To activate Pix, you must have a key registered in Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_one_text' => __( 'Download the Mercado Pago app on your cell phone.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_two_text_one' => __( 'Go to the ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_two_text_two' => __( 'area and choose the ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_two_text_highlight_one' => __( 'Your Profile ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_two_text_highlight_two' => __( 'Your Pix Keys section.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_three_text' => __( 'Choose which data to register as Pix keys. After registering, you can set up Pix in your checkout.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'observation_one' => __( 'Remember that, for the time being, the Central Bank of Brazil is open Monday through Friday, from 9am to 6pm.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'observation_two' => __( 'If you requested your registration outside these hours, we will confirm it within the next business day.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'button_about_pix' => __( 'Learn more about Pix', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'observation_three' => __( 'If you have already registered a Pix key at Mercado Pago and cannot activate Pix in the checkout, ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'link_title_one' => __( 'click here.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'link_url_one' => 'https://www.mercadopago.com.br/pix/', + 'link_url_two' => 'https://www.mercadopago.com.br/developers/pt/support/contact', + ), + 'woo/mercado/pago/steps/', + WC_WooMercadoPago_Module::get_templates_path() + ); + + return array( + 'title' => $steps_content, + 'type' => 'title', + 'class' => 'mp_title_checkout', + ); + } + + /** + * Field checkout pix header + * + * @return array + */ + public function field_checkout_pix_header() { + return array( + 'title' => sprintf( + '
- ' . __( 'Transparent Checkout | Pix', 'woocommerce-mercadopago' ) . ' + ' . __( 'Transparent Checkout | Pix', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . '

- ' . __( 'With the Transparent Checkout, you can sell inside your store environment, without redirection and all the safety from Mercado Pago. ', 'woocommerce-mercadopago' ) . ' + ' . __( 'With the Transparent Checkout, you can sell inside your store environment, without redirection and all the safety from Mercado Pago. ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . '

' - ), - 'type' => 'title', - 'class' => 'mp_title_header', - ); - } - - /** - * Field checkout pix payments advanced title - * - * @return array - */ - public function field_checkout_pix_payments_advanced_title() { - return array( - 'title' => __( 'Advanced configuration of the Pix experience', 'woocommerce-mercadopago' ), - 'type' => 'title', - 'class' => 'mp_subtitle_bd', - ); - } - - /** - * Field date expiration - * - * @return array - */ - public function field_pix_date_expiration() { - $pix_expiration_values = array( - '15 minutes' => __( '15 minutes', 'woocommerce-mercadopago' ), - '30 minutes' => __( '30 minutes (recommended)', 'woocommerce-mercadopago' ), - '60 minutes' => __( '60 minutes', 'woocommerce-mercadopago' ), - '12 hours' => __( '12 hours', 'woocommerce-mercadopago' ), - '24 hours' => __( '24 hours', 'woocommerce-mercadopago' ), - '2 days' => __( '2 days', 'woocommerce-mercadopago' ), - '3 days' => __( '3 days', 'woocommerce-mercadopago' ), - '4 days' => __( '4 days', 'woocommerce-mercadopago' ), - '5 days' => __( '5 days', 'woocommerce-mercadopago' ), - '6 days' => __( '6 days', 'woocommerce-mercadopago' ), - '7 days' => __( '7 days', 'woocommerce-mercadopago' ), - ); - - return array( - 'title' => __( 'Expiration for payments via Pix', 'woocommerce-mercadopago' ), - 'type' => 'select', - 'description' => __( 'Set the limit in minutes for your clients to pay via Pix.', 'woocommerce-mercadopago' ), - 'default' => '30 minutes', - 'options' => $pix_expiration_values, - ); - } - - /** - * Field checkout about pix - * - * @return array - */ - public function field_checkout_about_pix() { - $link_content = wc_get_template_html( - 'checkout/credential/generic-alert.php', - array( - 'title' => __( 'Want to learn how Pix works?', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'We have created a page to explain how this new payment method works and its advantages.', 'woocommerce-mercadopago' ), - 'url_link' => 'https://www.mercadopago.com.br/pix/', - 'button_text' => __( 'Learn more about Pix', 'woocommerce-mercadopago' ), - ), - 'woo/mercado/pago/about-pix/', - WC_WooMercadoPago_Module::get_templates_path() - ); - - return array( - 'title' => $link_content, - 'type' => 'title', - ); - } - - /** - * Field checkout card info - * - * @return array - */ - public function field_checkout_pix_card_info() { - $value = array( - 'title' => __('Would you like to know how Pix works?', 'woocommerce-mercadopago'), __('Important! To sell you must enter your credentials.' , 'woocommerce-mercadopago'), - 'subtitle' => __('We have a dedicated page where we explain how it works and its advantages.', 'woocommerce-mercadopago'), - 'button_text' => __('Find out more about Pix', 'woocommerce-mercadopago'), - 'button_url' => 'https://www.mercadopago.com.br/pix/', - 'icon' => 'mp-icon-badge-info', - 'color_card' => 'mp-alert-color-sucess', - 'size_card' => 'mp-card-body-size', - 'target' => '_blank' - ); - return array( - 'type' => 'mp_card_info', - 'value' => $value, - ); - } - - /** - * Payment fields - */ - public function payment_fields() { - // add css. - wp_enqueue_style( - 'woocommerce-mercadopago-narciso-styles', - plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - - $parameters = [ - 'test_mode' => ! $this->is_production_mode(), - 'pix_image' => plugins_url( '../assets/images/pix.png', plugin_dir_path( __FILE__ ) ), - ]; - - $parameters = array_merge($parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions()); - wc_get_template( 'checkout/pix-checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); - } - - /** - * Process payment - * - * @param int $order_id Order Id. - * @return array|string[] - */ - public function process_payment( $order_id ) { - // phpcs:ignore WordPress.Security.NonceVerification - $pix_checkout = map_deep($_POST, 'sanitize_text_field'); - $this->log->write_log( __FUNCTION__, 'Payment via Pix POST: ' ); - $order = wc_get_order( $order_id ); - $shipping_taxes = floatval($order->get_shipping_total()); - - $amount = $this->get_order_total(); - - $order->update_meta_data( 'is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no' ); - $order->update_meta_data( '_used_gateway', get_class( $this ) ); - - if ( ! empty( $this->gateway_discount ) ) { - $discount = ( $amount - $shipping_taxes ) * $this->gateway_discount / 100; - $order->update_meta_data( 'Mercado Pago: discount', __( 'discount of', 'woocommerce-mercadopago' ) . ' ' . $this->gateway_discount . '% / ' . __( 'discount of', 'woocommerce-mercadopago' ) . ' = ' . $discount ); - $order->set_total($amount - $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(); - - if ( filter_var( $order->get_billing_email(), FILTER_VALIDATE_EMAIL ) ) { - $response = $this->create_payment( $order, $pix_checkout ); - - if ( is_array( $response ) && array_key_exists( 'status', $response ) ) { - $this->hook->update_mp_order_payments_metadata( $order->get_id(), [ $response['id'] ] ); - - if ( 'pending' === $response['status'] ) { - if ( 'pending_waiting_payment' === $response['status_detail'] || 'pending_waiting_transfer' === $response['status_detail'] ) { - WC()->cart->empty_cart(); - // WooCommerce 3.0 or later. - $order->update_meta_data( 'mp_transaction_amount', $response['transaction_amount'] ); - $order->update_meta_data( 'mp_pix_qr_base64', $response['point_of_interaction']['transaction_data']['qr_code_base64'] ); - $order->update_meta_data( 'mp_pix_qr_code', $response['point_of_interaction']['transaction_data']['qr_code'] ); - $order->update_meta_data( 'checkout_pix_date_expiration', __( $this->get_option( 'checkout_pix_date_expiration', '30 minutes' ), 'woocommerce-mercadopago' ) ); - $order->update_meta_data( 'pix_on', 1 ); - $order->save(); - - // Shows some info in checkout page. - $order->add_order_note( - 'Mercado Pago: ' . - __( 'The customer has not paid yet.', 'woocommerce-mercadopago' ) - ); - - if ( 'pix' === $response['payment_method_id'] ) { - $order->add_order_note( - '

Mercado Pago: ' . __( 'Now you just need to pay with Pix to finalize your purchase.', 'woocommerce-mercadopago' ) . ' ' . - __( 'Scan the QR code below or copy and paste the code into your bank\'s application.', 'woocommerce-mercadopago' ) . '

', - 1, - false - ); - } - - return array( - 'result' => 'success', - 'redirect' => $order->get_checkout_order_received_url(), - ); - } - } - } else { - // Process when fields are imcomplete. - wc_add_notice( - '

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

', - 'error' - ); - - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - } else { - // Process when fields are incomplete. - wc_add_notice( - '

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

', - 'error' - ); - - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - } - - /** - * Create payment - * - * @param object $order Order. - * @param array $pix_checkout Picket checkout. - * @return string|array - */ - public function create_payment( $order, $pix_checkout ) { - $preferences_pix = new WC_WooMercadoPago_Preference_Pix( $this, $order, $pix_checkout ); - $payment = $preferences_pix->get_transaction( 'Payment' ); - - try { - $checkout_info = $payment->save(); - $this->log->write_log( __FUNCTION__, 'Created Payment: ' . wp_json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - return $checkout_info; - } catch ( Exception $e ) { - $this->log->write_log( __FUNCTION__, 'payment creation failed with error: ' . $e->getMessage() ); - return $e->getMessage(); - } - } - - /** - * Is available? - * - * @return bool - */ - public function is_available() { - if ( ! parent::is_available() ) { - return false; - } - - $payment_methods = $this->activated_payment; - if ( empty( $payment_methods ) || ! is_array( $payment_methods ) || ! in_array( 'pix', $payment_methods['pix'], true ) ) { - $this->log->write_log( __FUNCTION__, 'Pix key not found in payment_methods API, no active Pix payment method. ' ); - return false; - } - - $_mp_access_token = $this->mp_options->get_access_token_prod(); - $is_prod_credentials = false === WC_WooMercadoPago_Credentials::validate_credentials_test( $this->mp, $_mp_access_token, null ); - - if ( ( empty( $_SERVER['HTTPS'] ) || 'off' === $_SERVER['HTTPS'] ) && $is_prod_credentials ) { - $this->log->write_log( __FUNCTION__, 'NO HTTPS, Pix unavailable.' ); - return false; - } - - return true; - } - - /** - * Enable pix payment notice - * - * @return void - */ - public function enable_pix_payment_notice() { - $type = 'notice-warning'; - $message = wc_get_template_html( - 'checkout/credential/alert/alert-pix-not-registered.php', - array( - 'message' => __( 'Please note that to receive payments via Pix at our checkout, you must have a Pix key registered in your Mercado Pago account.', 'woocommerce-mercadopago' ), - 'text_link' => __( 'Register your Pix key at Mercado Pago.', 'woocommerce-mercadopago' ), - 'url_link' => 'https://www.mercadopago.com.br/stop/pix?url=https%3A%2F%2Fwww.mercadopago.com.br%2Fadmin-pix-keys%2Fmy-keys&authentication_mode=required', - ), - 'woo/mercado/pago/alert-pix-not-registered.php/', - WC_WooMercadoPago_Module::get_templates_path() - ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * Get Id - * - * @return string - */ - public static function get_id() { - return self::ID; - } - - /** - * Get pix template - * - * @param object $order Order. - * @return string - */ - public static function get_pix_template( $order ) { - $pix_on = (array) $order->get_meta( 'pix_on' ); - $pix_on = (int) array_pop( $pix_on ); - - if ( 1 === $pix_on && 'pending' === $order->get_status() ) { - $mp_pix_qr_code = $order->get_meta( 'mp_pix_qr_code' ); - $mp_pix_qr_base64 = $order->get_meta( 'mp_pix_qr_base64' ); - $checkout_pix_date_expiration = $order->get_meta( 'checkout_pix_date_expiration'); - - if ( is_array($mp_pix_qr_code) ) { - $mp_pix_qr_code = array_pop( $mp_pix_qr_code ); - } - if ( is_array($mp_pix_qr_base64) ) { - $mp_pix_qr_base64 = array_pop( $mp_pix_qr_base64 ); - } - if ( is_array( $checkout_pix_date_expiration ) ) { - $checkout_pix_date_expiration = array_pop( $checkout_pix_date_expiration ); - } - - $qr_code = $mp_pix_qr_code; - $qr_image = $mp_pix_qr_base64; - $src = 'data:image/jpeg;base64'; - $expiration_date = $checkout_pix_date_expiration; - - $order = $order->get_id(); - $qr_code_image = get_option('siteurl') . '/?wc-api=wc_mp_pix_image&id=' . $order; - - if ( ! in_array( 'gd', get_loaded_extensions(), true ) ) { - $qr_code_image = $src . ',' . $qr_image; - } - - $pix_template = wc_get_template( - 'pix/pix-image-template.php', - array( - 'qr_code' => $qr_code, - 'expiration_date' => $expiration_date, - 'text_expiration_date' => __( 'Code valid for ', 'woocommerce-mercadopago' ), - 'qr_code_image' => $qr_code_image, - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - - return $pix_template; - } - } - - /** - * Get pix template to send via email - * - * @param object $order Order. - * @param bool $sent_to_admin. - * @param bool $plain_text. - * @param $email - * @return string|array - */ - public static function get_pix_template_email( $order, $sent_to_admin, $plain_text, $email ) { - - return self::get_pix_template( $order ); - - } - - /** - * Get pix template to show in order details - * - * @param object $order Order. - * @return string|array - */ - public static function get_pix_template_order_details( $order ) { - - return self::get_pix_template( $order ); - - } - - /** - * Get Mercado Pago Icon - * - * @return mixed - */ - public function get_checkout_icon() { - /** - * Add Mercado Pago icon. - * - * @since 3.0.1 - */ - return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/pix.png', plugin_dir_path( __FILE__ ) ) ); - } - + ), + 'type' => 'title', + 'class' => 'mp_title_header', + ); + } + + /** + * Field checkout pix payments advanced title + * + * @return array + */ + public function field_checkout_pix_payments_advanced_title() { + return array( + 'title' => __( 'Advanced configuration of the Pix experience', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'title', + 'class' => 'mp_subtitle_bd', + ); + } + + /** + * Field date expiration + * + * @return array + */ + public function field_pix_date_expiration() { + $pix_expiration_values = array( + '15 minutes' => __( '15 minutes', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '30 minutes' => __( '30 minutes (recommended)', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '60 minutes' => __( '60 minutes', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '12 hours' => __( '12 hours', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '24 hours' => __( '24 hours', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '2 days' => __( '2 days', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '3 days' => __( '3 days', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '4 days' => __( '4 days', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '5 days' => __( '5 days', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '6 days' => __( '6 days', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '7 days' => __( '7 days', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + + return array( + 'title' => __( 'Expiration for payments via Pix', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'select', + 'description' => __( 'Set the limit in minutes for your clients to pay via Pix.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'default' => '30 minutes', + 'options' => $pix_expiration_values, + ); + } + + /** + * Field checkout about pix + * + * @return array + */ + public function field_checkout_about_pix() { + $link_content = wc_get_template_html( + 'checkout/credential/generic-alert.php', + array( + 'title' => __( 'Want to learn how Pix works?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'We have created a page to explain how this new payment method works and its advantages.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'url_link' => 'https://www.mercadopago.com.br/pix/', + 'button_text' => __( 'Learn more about Pix', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'woo/mercado/pago/about-pix/', + WC_WooMercadoPago_Module::get_templates_path() + ); + + return array( + 'title' => $link_content, + 'type' => 'title', + ); + } + + /** + * Field checkout card info + * + * @return array + */ + public function field_checkout_pix_card_info() { + $value = array( + 'title' => __('Would you like to know how Pix works?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), __('Important! To sell you must enter your credentials.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'subtitle' => __('We have a dedicated page where we explain how it works and its advantages.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'button_text' => __('Find out more about Pix', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'button_url' => 'https://www.mercadopago.com.br/pix/', + 'icon' => 'mp-icon-badge-info', + 'color_card' => 'mp-alert-color-sucess', + 'size_card' => 'mp-card-body-size', + 'target' => '_blank' + ); + return array( + 'type' => 'mp_card_info', + 'value' => $value, + ); + } + + /** + * Payment fields + */ + public function payment_fields(): void { + // add css. + wp_enqueue_style( + 'woocommerce-mercadopago-narciso-styles', + plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + + $parameters = array( + 'test_mode' => ! $this->is_production_mode(), + 'pix_image' => plugins_url( '../assets/images/pix.png', plugin_dir_path( __FILE__ ) ), + ); + + $parameters = array_merge($parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions()); + wc_get_template( 'checkout/pix-checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); + } + + /** + * Process payment + * + * @param int $order_id Order Id. + * @return array|string[] + */ + public function process_payment( $order_id ) { + // phpcs:ignore WordPress.Security.NonceVerification + $pix_checkout = map_deep($_POST, 'sanitize_text_field'); + $this->log->write_log( __FUNCTION__, 'Payment via Pix POST: ' ); + $order = wc_get_order( $order_id ); + $shipping_taxes = (float) ($order->get_shipping_total()); + + $amount = $this->get_order_total(); + + $order->update_meta_data( 'is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no' ); + $order->update_meta_data( '_used_gateway', get_class( $this ) ); + + if ( ! empty( $this->gateway_discount ) ) { + $discount = ( $amount - $shipping_taxes ) * $this->gateway_discount / 100; + $order->update_meta_data( 'Mercado Pago: discount', __( 'discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . $this->gateway_discount . '% / ' . __( 'discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' = ' . $discount ); + $order->set_total($amount - $discount); + } + + if ( ! empty( $this->commission ) ) { + $comission = $amount * ( $this->commission / 100 ); + $order->update_meta_data( 'Mercado Pago: comission', __( 'fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . $this->commission . '% / ' . __( 'fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' = ' . $comission ); + } + $order->save(); + + if ( filter_var( $order->get_billing_email(), \FILTER_VALIDATE_EMAIL ) ) { + $response = $this->create_payment( $order, $pix_checkout ); + + if ( is_array( $response ) && array_key_exists( 'status', $response ) ) { + $this->hook->update_mp_order_payments_metadata( $order->get_id(), array($response['id']) ); + + if ( 'pending' === $response['status'] ) { + if ( 'pending_waiting_payment' === $response['status_detail'] || 'pending_waiting_transfer' === $response['status_detail'] ) { + WC()->cart->empty_cart(); + // WooCommerce 3.0 or later. + $order->update_meta_data( 'mp_transaction_amount', $response['transaction_amount'] ); + $order->update_meta_data( 'mp_pix_qr_base64', $response['point_of_interaction']['transaction_data']['qr_code_base64'] ); + $order->update_meta_data( 'mp_pix_qr_code', $response['point_of_interaction']['transaction_data']['qr_code'] ); + $order->update_meta_data( 'checkout_pix_date_expiration', __( $this->get_option( 'checkout_pix_date_expiration', '30 minutes' ), LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + $order->update_meta_data( 'pix_on', 1 ); + $order->save(); + + // Shows some info in checkout page. + $order->add_order_note( + 'Mercado Pago: ' . + __( 'The customer has not paid yet.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + + if ( 'pix' === $response['payment_method_id'] ) { + $order->add_order_note( + '

Mercado Pago: ' . __( 'Now you just need to pay with Pix to finalize your purchase.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . + __( 'Scan the QR code below or copy and paste the code into your bank\'s application.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . '

', + 1, + false + ); + } + + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_order_received_url(), + ); + } + } + } else { + // Process when fields are imcomplete. + wc_add_notice( + '

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

', + 'error' + ); + + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + } else { + // Process when fields are incomplete. + wc_add_notice( + '

' . + __( 'A problem occurred when processing your payment. Please try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

', + 'error' + ); + + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + } + + /** + * Create payment + * + * @param object $order Order. + * @param array $pix_checkout Picket checkout. + * @return string|array + */ + public function create_payment( $order, $pix_checkout ) { + $preferences_pix = new WC_WooMercadoPago_Preference_Pix( $this, $order, $pix_checkout ); + $payment = $preferences_pix->get_transaction( 'Payment' ); + + try { + $checkout_info = $payment->save(); + $this->log->write_log( __FUNCTION__, 'Created Payment: ' . wp_json_encode( $checkout_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + return $checkout_info; + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, 'payment creation failed with error: ' . $e->getMessage() ); + return $e->getMessage(); + } + } + + /** + * Is available? + * + * @return bool + */ + public function is_available() { + if ( ! parent::is_available() ) { + return false; + } + + $payment_methods = $this->activated_payment; + if ( empty( $payment_methods ) || ! is_array( $payment_methods ) || ! in_array( 'pix', $payment_methods['pix'], true ) ) { + $this->log->write_log( __FUNCTION__, 'Pix key not found in payment_methods API, no active Pix payment method. ' ); + return false; + } + + $_mp_access_token = $this->mp_options->get_access_token_prod(); + $is_prod_credentials = false === WC_WooMercadoPago_Credentials::validate_credentials_test( $this->mp, $_mp_access_token, null ); + + if ( ( empty( $_SERVER['HTTPS'] ) || 'off' === $_SERVER['HTTPS'] ) && $is_prod_credentials ) { + $this->log->write_log( __FUNCTION__, 'NO HTTPS, Pix unavailable.' ); + return false; + } + + return true; + } + + /** + * Enable pix payment notice + * + * @return void + */ + public function enable_pix_payment_notice(): void { + $type = 'notice-warning'; + $message = wc_get_template_html( + 'checkout/credential/alert/alert-pix-not-registered.php', + array( + 'message' => __( 'Please note that to receive payments via Pix at our checkout, you must have a Pix key registered in your Mercado Pago account.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'text_link' => __( 'Register your Pix key at Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'url_link' => 'https://www.mercadopago.com.br/stop/pix?url=https%3A%2F%2Fwww.mercadopago.com.br%2Fadmin-pix-keys%2Fmy-keys&authentication_mode=required', + ), + 'woo/mercado/pago/alert-pix-not-registered.php/', + WC_WooMercadoPago_Module::get_templates_path() + ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * Get Id + * + * @return string + */ + public static function get_id() { + return self::ID; + } + + /** + * Get pix template + * + * @param object $order Order. + * @return string + */ + public static function get_pix_template( $order ) { + $pix_on = (array) $order->get_meta( 'pix_on' ); + $pix_on = (int) array_pop( $pix_on ); + + if ( 1 === $pix_on && 'pending' === $order->get_status() ) { + $mp_pix_qr_code = $order->get_meta( 'mp_pix_qr_code' ); + $mp_pix_qr_base64 = $order->get_meta( 'mp_pix_qr_base64' ); + $checkout_pix_date_expiration = $order->get_meta( 'checkout_pix_date_expiration'); + + if ( is_array($mp_pix_qr_code) ) { + $mp_pix_qr_code = array_pop( $mp_pix_qr_code ); + } + if ( is_array($mp_pix_qr_base64) ) { + $mp_pix_qr_base64 = array_pop( $mp_pix_qr_base64 ); + } + if ( is_array( $checkout_pix_date_expiration ) ) { + $checkout_pix_date_expiration = array_pop( $checkout_pix_date_expiration ); + } + + $qr_code = $mp_pix_qr_code; + $qr_image = $mp_pix_qr_base64; + $src = 'data:image/jpeg;base64'; + $expiration_date = $checkout_pix_date_expiration; + + $order = $order->get_id(); + $qr_code_image = get_option('siteurl') . '/?wc-api=wc_mp_pix_image&id=' . $order; + + if ( ! in_array( 'gd', get_loaded_extensions(), true ) ) { + $qr_code_image = $src . ',' . $qr_image; + } + + $pix_template = wc_get_template( + 'pix/pix-image-template.php', + array( + 'qr_code' => $qr_code, + 'expiration_date' => $expiration_date, + 'text_expiration_date' => __( 'Code valid for ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'qr_code_image' => $qr_code_image, + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + + return $pix_template; + } + } + + /** + * Get pix template to send via email + * + * @param object $order Order. + * @param bool $sent_to_admin. + * @param bool $plain_text. + * @param $email + * @return string|array + */ + public static function get_pix_template_email( $order, $sent_to_admin, $plain_text, $email ) { + return self::get_pix_template( $order ); + } + + /** + * Get pix template to show in order details + * + * @param object $order Order. + * @return string|array + */ + public static function get_pix_template_order_details( $order ) { + return self::get_pix_template( $order ); + } + + /** + * Get Mercado Pago Icon + * + * @return mixed + */ + public function get_checkout_icon() { + /** + * Add Mercado Pago icon. + * + * @since 3.0.1 + */ + return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/pix.png', plugin_dir_path( __FILE__ ) ) ); + } } diff --git a/includes/payments/class-wc-woomercadopago-ticket-gateway.php b/includes/payments/class-wc-woomercadopago-ticket-gateway.php index 4e89f1390..40192e8d1 100755 --- a/includes/payments/class-wc-woomercadopago-ticket-gateway.php +++ b/includes/payments/class-wc-woomercadopago-ticket-gateway.php @@ -1,668 +1,657 @@ id = self::ID; - $this->title = __( 'Invoice', 'woocommerce-mercadopago' ); - $this->title_gateway = __( 'Invoice', 'woocommerce-mercadopago' ); - $this->description = __( 'Transparent Checkout in your store environment', 'woocommerce-mercadopago' ); - $this->mp_options = $this->get_mp_options(); - - if ( ! $this->validate_section() ) { - return; - } - - $this->form_fields = array(); - $this->method_title = __( 'Mercado pago - Customized Checkout', 'woocommerce-mercadopago' ); - $this->title = $this->get_option( 'title', __( 'Invoice', 'woocommerce-mercadopago' ) ); - $this->method_description = $this->description; - $this->coupon_mode = $this->get_option( 'coupon_mode', 'no' ); - $this->stock_reduce_mode = $this->get_option( 'stock_reduce_mode', 'no' ); - $this->date_expiration = (int) $this->get_option( 'date_expiration', WC_WooMercadoPago_Constants::DATE_EXPIRATION ); - $this->type_payments = $this->get_option( 'type_payments', 'no' ); - $this->payment_type = 'ticket'; - $this->checkout_type = 'custom'; - $this->activated_payment = $this->get_activated_payment(); - $this->field_forms_order = $this->get_fields_sequence(); - - parent::__construct(); - $this->form_fields = $this->get_form_mp_fields(); - $this->hook = new WC_WooMercadoPago_Hook_Ticket( $this ); - $this->notification = new WC_WooMercadoPago_Notification_Core( $this ); - $this->currency_convertion = true; - $this->icon = $this->get_checkout_icon(); - } - - /** - * Get form mp fields - * - * @param string $label Label. - * @return array - */ - public function get_form_mp_fields() { - if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - wp_enqueue_script( - 'woocommerce-mercadopago-ticket-config-script', - plugins_url( '../assets/js/ticket_config_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - false - ); - } - - if ( empty( $this->checkout_country ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); - } - - if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { - $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); - } - - $form_fields = array(); - if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { - $form_fields['checkout_ticket_header'] = $this->field_checkout_ticket_header(); - $form_fields['checkout_ticket_payments_advanced_title'] = $this->field_checkout_ticket_payments_advanced_title(); - $form_fields['coupon_mode'] = $this->field_coupon_mode(); - $form_fields['stock_reduce_mode'] = $this->field_stock_reduce_mode(); - $form_fields['date_expiration'] = $this->field_date_expiration(); - $form_fields['field_ticket_payments'] = $this->field_ticket_payments(); - } - - $form_fields_abs = parent::get_form_mp_fields(); - if ( 1 === count( $form_fields_abs ) ) { - return $form_fields_abs; - } - $form_fields_merge = array_merge( $form_fields_abs, $form_fields ); - $fields = $this->sort_form_fields( $form_fields_merge, $this->field_forms_order ); - - return $fields; - } - - /** - * Get fields sequence - * - * @return array - */ - public function get_fields_sequence() { - return array( - // Necessary to run. - 'description', - // Checkout de pagos con dinero en efectivo
Aceptá pagos al instante y maximizá la conversión de tu negocio. - 'checkout_ticket_header', - // No olvides de homologar tu cuenta. - 'checkout_card_homolog', - // Configure the personalized payment experience in your store. - 'checkout_card_validate', - 'enabled', - 'title', - WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, - 'field_ticket_payments', - 'date_expiration', - // Advanced configuration of the personalized payment experience. - 'checkout_ticket_payments_advanced_title', - 'checkout_payments_advanced_description', - 'coupon_mode', - 'stock_reduce_mode', - 'gateway_discount', - 'commission', - ); - } - - /** - * Get activated payment - * - * @return array - */ - public static function get_activated_payment() { - $activated_payment = array(); - $treated_payments = array(); - $get_payment_methods_ticket = get_option( '_all_payment_methods_ticket', '' ); - - if ( ! empty( $get_payment_methods_ticket ) ) { - $saved_options = get_option( 'woocommerce_woo-mercado-pago-ticket_settings', '' ); - - if ( ! is_array( $get_payment_methods_ticket ) ) { - $get_payment_methods_ticket = json_decode( $get_payment_methods_ticket, true ); - } - - foreach ( $get_payment_methods_ticket as $payment_methods_ticket ) { - if ( ! isset( $saved_options[ $payment_methods_ticket['id'] ] ) - || 'yes' === $saved_options[ $payment_methods_ticket['id'] ] ) { - array_push( $activated_payment, $payment_methods_ticket ); - sort($activated_payment); - } - } - } - - foreach ( $activated_payment as $payment ) { - $treated_payment = []; - if ( isset($payment['payment_places']) ) { - foreach ( $payment['payment_places'] as $place ) { - $payment_place_id = ( new WC_WooMercadoPago_Composite_Id_Helper() )->generateIdFromPlace($payment['id'], $place['payment_option_id']); - $treated_payment['id'] = $payment_place_id; - $treated_payment['value'] = $payment_place_id; - $treated_payment['rowText'] = $place['name']; - $treated_payment['img'] = $place['thumbnail']; - $treated_payment['alt'] = $place['name']; - array_push( $treated_payments, $treated_payment); - } - } else { - $treated_payment['id'] = $payment['id']; - $treated_payment['value'] = $payment['id']; - $treated_payment['rowText'] = $payment['name']; - $treated_payment['img'] = $payment['secure_thumbnail']; - $treated_payment['alt'] = $payment['name']; - array_push( $treated_payments, $treated_payment); - } - } - return $treated_payments; - } - - /** - * Field enabled - * - * @return array - */ - public function field_enabled() { - return array( - 'title' => __( 'Enable the checkout', 'woocommerce-mercadopago' ), - 'subtitle' => __( 'By disabling it, you will disable all invoice payments from Mercado Pago Transparent Checkout.', 'woocommerce-mercadopago' ), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'descriptions' => array( - 'enabled' => __( 'The transparent checkout for tickets is enabled.', 'woocommerce-mercadopago' ), - 'disabled' => __( 'The transparent checkout for tickets is disabled.', 'woocommerce-mercadopago' ), - ), - ); - } - - /** - * Field checkout ticket header - * - * @return array - */ - public function field_checkout_ticket_header() { - return array( - 'title' => sprintf( - '
+ /** + * ID + * + * @const + */ + public const ID = 'woo-mercado-pago-ticket'; + + /** + * WC_WooMercadoPago_TicketGateway constructor. + * + * @throws WC_WooMercadoPago_Exception Load payment exception. + */ + public function __construct() { + $this->id = self::ID; + $this->title = __( 'Invoice', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->title_gateway = __( 'Invoice', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->description = __( 'Transparent Checkout in your store environment', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->mp_options = $this->get_mp_options(); + + if ( ! $this->validate_section() ) { + return; + } + + $this->form_fields = array(); + $this->method_title = __( 'Mercado pago - Customized Checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + $this->title = $this->get_option( 'title', __( 'Invoice', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) ); + $this->method_description = $this->description; + $this->coupon_mode = $this->get_option( 'coupon_mode', 'no' ); + $this->stock_reduce_mode = $this->get_option( 'stock_reduce_mode', 'no' ); + $this->date_expiration = (int) $this->get_option( 'date_expiration', WC_WooMercadoPago_Constants::DATE_EXPIRATION ); + $this->type_payments = $this->get_option( 'type_payments', 'no' ); + $this->payment_type = 'ticket'; + $this->checkout_type = 'custom'; + $this->activated_payment = $this->get_activated_payment(); + $this->field_forms_order = $this->get_fields_sequence(); + + parent::__construct(); + $this->form_fields = $this->get_form_mp_fields(); + $this->hook = new WC_WooMercadoPago_Hook_Ticket( $this ); + $this->notification = new WC_WooMercadoPago_Notification_Core( $this ); + $this->currency_convertion = true; + $this->icon = $this->get_checkout_icon(); + } + + /** + * Get form mp fields + * + * @param string $label Label. + * @return array + */ + public function get_form_mp_fields() { + if ( is_admin() && $this->is_manage_section() && ( WC_WooMercadoPago_Helper_Current_Url::validate_page('mercadopago-settings') || WC_WooMercadoPago_Helper_Current_Url::validate_section('woo-mercado-pago') ) ) { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + wp_enqueue_script( + 'woocommerce-mercadopago-ticket-config-script', + plugins_url( '../assets/js/ticket_config_mercadopago' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + false + ); + } + + if ( empty( $this->checkout_country ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 7 ); + } + + if ( ! empty( $this->checkout_country ) && empty( $this->get_access_token() ) && empty( $this->get_public_key() ) ) { + $this->field_forms_order = array_slice( $this->field_forms_order, 0, 22 ); + } + + $form_fields = array(); + if ( ! empty( $this->checkout_country ) && ! empty( $this->get_access_token() ) && ! empty( $this->get_public_key() ) ) { + $form_fields['checkout_ticket_header'] = $this->field_checkout_ticket_header(); + $form_fields['checkout_ticket_payments_advanced_title'] = $this->field_checkout_ticket_payments_advanced_title(); + $form_fields['coupon_mode'] = $this->field_coupon_mode(); + $form_fields['stock_reduce_mode'] = $this->field_stock_reduce_mode(); + $form_fields['date_expiration'] = $this->field_date_expiration(); + $form_fields['field_ticket_payments'] = $this->field_ticket_payments(); + } + + $form_fields_abs = parent::get_form_mp_fields(); + if ( 1 === count( $form_fields_abs ) ) { + return $form_fields_abs; + } + $form_fields_merge = array_merge( $form_fields_abs, $form_fields ); + $fields = $this->sort_form_fields( $form_fields_merge, $this->field_forms_order ); + + return $fields; + } + + /** + * Get fields sequence + * + * @return array + */ + public function get_fields_sequence() { + return array( + // Necessary to run. + 'description', + // Checkout de pagos con dinero en efectivo
Aceptá pagos al instante y maximizá la conversión de tu negocio. + 'checkout_ticket_header', + // No olvides de homologar tu cuenta. + 'checkout_card_homolog', + // Configure the personalized payment experience in your store. + 'checkout_card_validate', + 'enabled', + 'title', + WC_WooMercadoPago_Helpers_CurrencyConverter::CONFIG_KEY, + 'field_ticket_payments', + 'date_expiration', + // Advanced configuration of the personalized payment experience. + 'checkout_ticket_payments_advanced_title', + 'checkout_payments_advanced_description', + 'coupon_mode', + 'stock_reduce_mode', + 'gateway_discount', + 'commission', + ); + } + + /** + * Get activated payment + * + * @return array + */ + public static function get_activated_payment() { + $activated_payment = array(); + $treated_payments = array(); + $get_payment_methods_ticket = get_option( '_all_payment_methods_ticket', '' ); + + if ( ! empty( $get_payment_methods_ticket ) ) { + $saved_options = get_option( 'woocommerce_woo-mercado-pago-ticket_settings', '' ); + + if ( ! is_array( $get_payment_methods_ticket ) ) { + $get_payment_methods_ticket = json_decode( $get_payment_methods_ticket, true ); + } + + foreach ( $get_payment_methods_ticket as $payment_methods_ticket ) { + if ( ! isset( $saved_options[ $payment_methods_ticket['id'] ] ) + || 'yes' === $saved_options[ $payment_methods_ticket['id'] ] ) { + array_push( $activated_payment, $payment_methods_ticket ); + sort($activated_payment); + } + } + } + + foreach ( $activated_payment as $payment ) { + $treated_payment = array(); + if ( isset($payment['payment_places']) ) { + foreach ( $payment['payment_places'] as $place ) { + $payment_place_id = ( new WC_WooMercadoPago_Composite_Id_Helper() )->generateIdFromPlace($payment['id'], $place['payment_option_id']); + $treated_payment['id'] = $payment_place_id; + $treated_payment['value'] = $payment_place_id; + $treated_payment['rowText'] = $place['name']; + $treated_payment['img'] = $place['thumbnail']; + $treated_payment['alt'] = $place['name']; + array_push( $treated_payments, $treated_payment); + } + } else { + $treated_payment['id'] = $payment['id']; + $treated_payment['value'] = $payment['id']; + $treated_payment['rowText'] = $payment['name']; + $treated_payment['img'] = $payment['secure_thumbnail']; + $treated_payment['alt'] = $payment['name']; + array_push( $treated_payments, $treated_payment); + } + } + return $treated_payments; + } + + /** + * Field enabled + * + * @return array + */ + public function field_enabled() { + return array( + 'title' => __( 'Enable the checkout', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'subtitle' => __( 'By disabling it, you will disable all invoice payments from Mercado Pago Transparent Checkout.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'descriptions' => array( + 'enabled' => __( 'The transparent checkout for tickets is enabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'disabled' => __( 'The transparent checkout for tickets is disabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + ); + } + + /** + * Field checkout ticket header + * + * @return array + */ + public function field_checkout_ticket_header() { + return array( + 'title' => sprintf( + '
- ' . __( 'Transparent Checkout | Invoice or Loterica', 'woocommerce-mercadopago' ) . ' + ' . __( 'Transparent Checkout | Invoice or Loterica', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . '

- ' . __( 'With the Transparent Checkout, you can sell inside your store environment, without redirection and all the safety from Mercado Pago.', 'woocommerce-mercadopago' ) . ' + ' . __( 'With the Transparent Checkout, you can sell inside your store environment, without redirection and all the safety from Mercado Pago.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . '

' - ), - 'type' => 'title', - 'class' => 'mp_title_header', - ); - } - - /** - * Field checkout ticket payments advanced title - * - * @return array - */ - public function field_checkout_ticket_payments_advanced_title() { - return array( - 'title' => __( 'Advanced configuration of the cash payment experience', 'woocommerce-mercadopago' ), - 'type' => 'title', - 'class' => 'mp_subtitle_bd', - ); - } - - /** - * Field sotck reduce mode - * - * @return array - */ - public function field_stock_reduce_mode() { - return array( - 'title' => __( 'Reduce inventory', 'woocommerce-mercadopago' ), - 'type' => 'mp_toggle_switch', - 'default' => 'no', - 'subtitle' => __( '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.', 'woocommerce-mercadopago' ), - 'descriptions' => array( - 'enabled' => __( 'Reduce inventory is enabled.', 'woocommerce-mercadopago' ), - 'disabled' => __( 'Reduce inventory is disabled.', 'woocommerce-mercadopago' ), - ), - ); - } - - /** - * Field date expiration - * - * @return array - */ - public function field_date_expiration() { - return array( - 'title' => __( 'Payment Due', 'woocommerce-mercadopago' ), - 'type' => 'number', - 'description' => __( 'In how many days will cash payments expire.', 'woocommerce-mercadopago' ), - 'default' => WC_WooMercadoPago_Constants::DATE_EXPIRATION, - ); - } - - /** - * Field ticket payments - * - * @return array - */ - public function field_ticket_payments() { - $get_payment_methods_ticket = get_option( '_all_payment_methods_ticket', '[]' ); - - $count_payment = 0; - - if ( ! is_array( $get_payment_methods_ticket ) ) { - $get_payment_methods_ticket = json_decode( $get_payment_methods_ticket, true ); - } - - $payment_list = array( - 'description' => __( 'Enable the available payment methods', 'woocommerce-mercadopago' ), - 'title' => __( 'Payment methods', 'woocommerce-mercadopago' ), - 'desc_tip' => __( 'Choose the available payment methods in your store.', 'woocommerce-mercadopago' ), - 'type' => 'mp_checkbox_list', - 'payment_method_types' => array( - 'ticket' => array( - 'label' => __('All payment methods', 'woocommerce-mercadopago'), - 'list' => array(), - ), - ), - ); - - foreach ( $get_payment_methods_ticket as $payment_method_ticket ) { - $payment_list['payment_method_types']['ticket']['list'][] = array( - 'id' => $payment_method_ticket['id'], - 'field_key' => $this->get_field_key($payment_method_ticket['id']), - 'label' => array_key_exists('payment_places', $payment_method_ticket) ? $payment_method_ticket['name'] . ' (' . $this->build_paycash_payments_string() . ')' : $payment_method_ticket['name'], - 'value' => $this->get_option($payment_method_ticket['id'], 'yes'), - 'type' => 'checkbox', - ); - } - - return $payment_list; - } - - /** - * Payment fields - */ - public function payment_fields() { - // add css. - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - - wp_enqueue_style( - 'woocommerce-mercadopago-narciso-styles', - plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - - $amount = $this->get_order_total(); - $discount = $amount * ( $this->gateway_discount / 100 ); - $comission = $amount * ( $this->commission / 100 ); - $amount = $amount - $discount + $comission; - - $logged_user_email = ( 0 !== wp_get_current_user()->ID ) ? wp_get_current_user()->user_email : null; - $address = get_user_meta( wp_get_current_user()->ID, 'billing_address_1', true ); - $address_2 = get_user_meta( wp_get_current_user()->ID, 'billing_address_2', true ); - $address .= ( ! empty( $address_2 ) ? ' - ' . $address_2 : '' ); - $country = get_user_meta( wp_get_current_user()->ID, 'billing_country', true ); - $address .= ( ! empty( $country ) ? ' - ' . $country : '' ); - $test_mode_link = $this->get_mp_devsite_link($this->checkout_country); - - try { - $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->ratio( $this ); - } catch ( Exception $e ) { - $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::DEFAULT_RATIO; - } - - $parameters = array( - 'test_mode' => ! $this->is_production_mode(), - 'test_mode_link' => $test_mode_link, - 'amount' => $amount, - 'payment_methods' => $this->activated_payment, - 'site_id' => $this->mp_options->get_site_id(), - 'coupon_mode' => isset( $logged_user_email ) ? $this->coupon_mode : 'no', - 'discount_action_url' => $this->discount_action_url, - 'payer_email' => esc_js( $logged_user_email ), - 'currency_ratio' => $currency_ratio, - 'woocommerce_currency' => get_woocommerce_currency(), - 'account_currency' => $this->site_data['currency'], - 'images_path' => plugins_url( '../assets/images/', plugin_dir_path( __FILE__ ) ), - 'febraban' => ( 0 !== wp_get_current_user()->ID ) ? - array( - 'firstname' => esc_js( wp_get_current_user()->user_firstname ), - 'lastname' => esc_js( wp_get_current_user()->user_lastname ), - 'docNumber' => '', - 'address' => esc_js( $address ), - 'number' => '', - 'city' => esc_js( get_user_meta( wp_get_current_user()->ID, 'billing_city', true ) ), - 'state' => esc_js( get_user_meta( wp_get_current_user()->ID, 'billing_state', true ) ), - 'zipcode' => esc_js( get_user_meta( wp_get_current_user()->ID, 'billing_postcode', true ) ), - ) : - array( - 'firstname' => '', - 'lastname' => '', - 'docNumber' => '', - 'address' => '', - 'number' => '', - 'city' => '', - 'state' => '', - 'zipcode' => '', - ), - ); - - $parameters = array_merge($parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions()); - wc_get_template( 'checkout/ticket-checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); - } - - /** - * Process payment - * - * @param int $order_id Order Id. - * @return array|string[] - */ - public function process_payment( $order_id ) { - // phpcs:ignore WordPress.Security.NonceVerification - if ( ! isset( $_POST['mercadopago_ticket'] ) ) { - return $this->process_result_fail( - __FUNCTION__, - __( 'A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago' ), - __( 'A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago' ) - ); - } - // phpcs:ignore WordPress.Security.NonceVerification - $ticket_checkout = map_deep($_POST['mercadopago_ticket'], 'sanitize_text_field'); - $this->log->write_log( __FUNCTION__, 'Ticket POST: ' . wp_json_encode( $ticket_checkout, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - - $order = wc_get_order( $order_id ); - $amount = $this->get_order_total(); - $shipping_taxes = floatval($order->get_shipping_total()); - - $order->update_meta_data( 'is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no' ); - $order->update_meta_data( '_used_gateway', get_class( $this ) ); - - if ( ! empty( $this->gateway_discount ) ) { - $discount = ( $amount - $shipping_taxes ) * $this->gateway_discount / 100; - $order->update_meta_data( 'Mercado Pago: discount', __( 'discount of', 'woocommerce-mercadopago' ) . ' ' . $this->gateway_discount . '% / ' . __( 'discount of', 'woocommerce-mercadopago' ) . ' = ' . $discount ); - $order->set_total($amount - $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(); - - // Check for brazilian FEBRABAN rules. - if ( 'mlb' === $this->mp_options->get_site_id() ) { - if ( ! isset( $ticket_checkout['docNumber'] ) || empty( $ticket_checkout['docNumber'] ) ) { - - if ( isset( $ticket_checkout['docNumberError'] ) || ! empty( $ticket_checkout['docNumberError'] ) ) { - wc_add_notice( - '

' . - __( 'Your document data is invalid', 'woocommerce-mercadopago' ) . - '

', - 'error' - ); - } else { - wc_add_notice( - '

' . - __( 'There was a problem processing your payment. Are you sure you have correctly filled out all the information on the payment form?', 'woocommerce-mercadopago' ) . - '

', - 'error' - ); - } - - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - } - - if ( 'mlu' === $this->mp_options->get_site_id() ) { - if ( - ! isset( $ticket_checkout['docNumber'] ) || empty( $ticket_checkout['docNumber'] ) || - ! isset( $ticket_checkout['docType'] ) || empty( $ticket_checkout['docType'] ) - ) { - if ( isset( $ticket_checkout['docNumberError'] ) || ! empty( $ticket_checkout['docNumberError'] ) ) { - wc_add_notice( - '

' . - __( 'Your document data is invalid', 'woocommerce-mercadopago' ) . - '

', - 'error' - ); - } else { - wc_add_notice( - '

' . - __( 'There was a problem processing your payment. Are you sure you have correctly filled out all the information on the payment form?', 'woocommerce-mercadopago' ) . - '

', - 'error' - ); - } - - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - } - - if ( isset( $ticket_checkout['amount'] ) && ! empty( $ticket_checkout['amount'] ) && - isset( $ticket_checkout['paymentMethodId'] ) && ! empty( $ticket_checkout['paymentMethodId'] ) ) { - $response = $this->create_payment( $order, $ticket_checkout ); - - if ( is_array( $response ) && array_key_exists( 'status', $response ) ) { - $this->hook->update_mp_order_payments_metadata( $order->get_id(), [ $response['id'] ] ); - - if ( 'pending' === $response['status'] ) { - if ( 'pending_waiting_payment' === $response['status_detail'] || 'pending_waiting_transfer' === $response['status_detail'] ) { - WC()->cart->empty_cart(); - if ( 'yes' === $this->stock_reduce_mode ) { - wc_reduce_stock_levels( $order_id ); - } - // WooCommerce 3.0 or later. - $order->update_meta_data( '_transaction_details_ticket', $response['transaction_details']['external_resource_url'] ); - $order->save(); - // Shows some info in checkout page. - $order->add_order_note( - 'Mercado Pago: ' . - __( 'The customer has not paid yet.', 'woocommerce-mercadopago' ) - ); - if ( 'bank_transfer' !== $response['payment_type_id'] ) { - $order->add_order_note( - 'Mercado Pago: ' . - __( 'To print the ticket again click', 'woocommerce-mercadopago' ) . - ' ' . - __( 'here', 'woocommerce-mercadopago' ) . - '', - 1, - false - ); - } - - return array( - 'result' => 'success', - 'redirect' => $order->get_checkout_order_received_url(), - ); - } - } - } else { - // Process when fields are imcomplete. - wc_add_notice( - '

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

', - 'error' - ); - - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - } else { - // Process when fields are incomplete. - return $this->process_result_fail( - __FUNCTION__, - __( 'A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago' ), - __( 'A problem was occurred when processing your payment. Please, try again.', 'woocommerce-mercadopago' ) - ); - } - } - - /** - * Process if result is fail - * - * @param $function - * @param $log_message - * @param $notice_message - * - * @return string[] - */ - protected function process_result_fail( $function, $log_message, $notice_message ) { - $this->log->write_log( $function, $log_message ); - - wc_add_notice( - '

' . $notice_message . '

', - 'error' - ); - - return array( - 'result' => 'fail', - 'redirect' => '', - ); - } - - /** - * Create payment - * - * @param object $order Order. - * @param array $ticket_checkout Ticket checkout. - * @return string|array - */ - public function create_payment( $order, $ticket_checkout ) { - $preferences_ticket = new WC_WooMercadoPago_Preference_Ticket( $this, $order, $ticket_checkout ); - $payment = $preferences_ticket->get_transaction( 'Payment' ); - - try { - $checkout_info = $payment->save(); - $this->log->write_log( __FUNCTION__, 'Created Payment: ' . wp_json_encode( $checkout_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); - return $checkout_info; - } catch ( Exception $e ) { - $this->log->write_log( __FUNCTION__, 'payment creation failed with error: ' . $e->getMessage() ); - return $e->getMessage(); - } - } - - /** - * Is available? - * - * @return bool - */ - public function is_available() { - if ( ! parent::is_available() ) { - return false; - } - - $payment_methods = $this->activated_payment; - if ( 0 === count( $payment_methods ) ) { - $this->log->write_log( __FUNCTION__, 'Ticket unavailable, no active payment methods. ' ); - return false; - } - - return true; - } - - /** - * Get Id - * - * @return string - */ - public static function get_id() { - return self::ID; - } - - /** - * Build Paycash Payments String - * - * @return string - */ - public static function build_paycash_payments_string() { - - $get_payment_methods_ticket = get_option( '_all_payment_methods_ticket', '[]' ); - - foreach ( $get_payment_methods_ticket as $payment ) { - - if ( 'paycash' === $payment['id'] ) { - $payments = array_column( $payment['payment_places'] , 'name'); - } - } - - $last_element = array_pop( $payments ); - $paycash_payments = implode(', ', $payments); - - return implode( __(' and ', 'woocommerce-mercadopago') , array( $paycash_payments, $last_element )); - } - - /** - * Get Mercado Pago Icon - * - * @return mixed - */ - public function get_checkout_icon() { - $country = $this->get_option_mp( '_site_id_v1' ); - - if ( 'MLB' !== $country ) { - /** - * Add Mercado Pago icon. - * - * @since 3.0.1 - */ - return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/ticket.png', plugin_dir_path( __FILE__ ) ) ); - } - - /** - * Add Mercado Pago icon. - * - * @since 3.0.1 - */ - return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/ticket_mlb.png', plugin_dir_path( __FILE__ ) ) ); - } - + ), + 'type' => 'title', + 'class' => 'mp_title_header', + ); + } + + /** + * Field checkout ticket payments advanced title + * + * @return array + */ + public function field_checkout_ticket_payments_advanced_title() { + return array( + 'title' => __( 'Advanced configuration of the cash payment experience', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'title', + 'class' => 'mp_subtitle_bd', + ); + } + + /** + * Field sotck reduce mode + * + * @return array + */ + public function field_stock_reduce_mode() { + return array( + 'title' => __( 'Reduce inventory', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_toggle_switch', + 'default' => 'no', + 'subtitle' => __( '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.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'descriptions' => array( + 'enabled' => __( 'Reduce inventory is enabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'disabled' => __( 'Reduce inventory is disabled.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + ); + } + + /** + * Field date expiration + * + * @return array + */ + public function field_date_expiration() { + return array( + 'title' => __( 'Payment Due', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'number', + 'description' => __( 'In how many days will cash payments expire.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'default' => WC_WooMercadoPago_Constants::DATE_EXPIRATION, + ); + } + + /** + * Field ticket payments + * + * @return array + */ + public function field_ticket_payments() { + $get_payment_methods_ticket = get_option( '_all_payment_methods_ticket', '[]' ); + + $count_payment = 0; + + if ( ! is_array( $get_payment_methods_ticket ) ) { + $get_payment_methods_ticket = json_decode( $get_payment_methods_ticket, true ); + } + + $payment_list = array( + 'description' => __( 'Enable the available payment methods', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title' => __( 'Payment methods', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'desc_tip' => __( 'Choose the available payment methods in your store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'type' => 'mp_checkbox_list', + 'payment_method_types' => array( + 'ticket' => array( + 'label' => __('All payment methods', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'list' => array(), + ), + ), + ); + + foreach ( $get_payment_methods_ticket as $payment_method_ticket ) { + $payment_list['payment_method_types']['ticket']['list'][] = array( + 'id' => $payment_method_ticket['id'], + 'field_key' => $this->get_field_key($payment_method_ticket['id']), + 'label' => array_key_exists('payment_places', $payment_method_ticket) ? $payment_method_ticket['name'] . ' (' . $this->build_paycash_payments_string() . ')' : $payment_method_ticket['name'], + 'value' => $this->get_option($payment_method_ticket['id'], 'yes'), + 'type' => 'checkbox', + ); + } + + return $payment_list; + } + + /** + * Payment fields + */ + public function payment_fields(): void { + // add css. + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + wp_enqueue_style( + 'woocommerce-mercadopago-narciso-styles', + plugins_url( '../assets/css/mp-plugins-components.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + + $amount = $this->get_order_total(); + $discount = $amount * ( $this->gateway_discount / 100 ); + $comission = $amount * ( $this->commission / 100 ); + $amount = $amount - $discount + $comission; + + $logged_user_email = ( 0 !== wp_get_current_user()->ID ) ? wp_get_current_user()->user_email : null; + $address = get_user_meta( wp_get_current_user()->ID, 'billing_address_1', true ); + $address_2 = get_user_meta( wp_get_current_user()->ID, 'billing_address_2', true ); + $address .= ( ! empty( $address_2 ) ? ' - ' . $address_2 : '' ); + $country = get_user_meta( wp_get_current_user()->ID, 'billing_country', true ); + $address .= ( ! empty( $country ) ? ' - ' . $country : '' ); + $test_mode_link = $this->get_mp_devsite_link($this->checkout_country); + + try { + $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->ratio( $this ); + } catch ( Exception $e ) { + $currency_ratio = WC_WooMercadoPago_Helpers_CurrencyConverter::DEFAULT_RATIO; + } + + $parameters = array( + 'test_mode' => ! $this->is_production_mode(), + 'test_mode_link' => $test_mode_link, + 'amount' => $amount, + 'payment_methods' => $this->activated_payment, + 'site_id' => $this->mp_options->get_site_id(), + 'coupon_mode' => isset( $logged_user_email ) ? $this->coupon_mode : 'no', + 'discount_action_url' => $this->discount_action_url, + 'payer_email' => esc_js( $logged_user_email ), + 'currency_ratio' => $currency_ratio, + 'woocommerce_currency' => get_woocommerce_currency(), + 'account_currency' => $this->site_data['currency'], + 'images_path' => plugins_url( '../assets/images/', plugin_dir_path( __FILE__ ) ), + 'febraban' => ( 0 !== wp_get_current_user()->ID ) ? + array( + 'firstname' => esc_js( wp_get_current_user()->user_firstname ), + 'lastname' => esc_js( wp_get_current_user()->user_lastname ), + 'docNumber' => '', + 'address' => esc_js( $address ), + 'number' => '', + 'city' => esc_js( get_user_meta( wp_get_current_user()->ID, 'billing_city', true ) ), + 'state' => esc_js( get_user_meta( wp_get_current_user()->ID, 'billing_state', true ) ), + 'zipcode' => esc_js( get_user_meta( wp_get_current_user()->ID, 'billing_postcode', true ) ), + ) : + array( + 'firstname' => '', + 'lastname' => '', + 'docNumber' => '', + 'address' => '', + 'number' => '', + 'city' => '', + 'state' => '', + 'zipcode' => '', + ), + ); + + $parameters = array_merge($parameters, WC_WooMercadoPago_Helper_Links::mp_define_terms_and_conditions()); + wc_get_template( 'checkout/ticket-checkout.php', $parameters, 'woo/mercado/pago/module/', WC_WooMercadoPago_Module::get_templates_path() ); + } + + /** + * Process payment + * + * @param int $order_id Order Id. + * @return array|string[] + */ + public function process_payment( $order_id ) { + // phpcs:ignore WordPress.Security.NonceVerification + if ( ! isset( $_POST['mercadopago_ticket'] ) ) { + return $this->process_result_fail( + __FUNCTION__, + __( 'A problem was occurred when processing your payment. Please, try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + __( 'A problem was occurred when processing your payment. Please, try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } + // phpcs:ignore WordPress.Security.NonceVerification + $ticket_checkout = map_deep($_POST['mercadopago_ticket'], 'sanitize_text_field'); + $this->log->write_log( __FUNCTION__, 'Ticket POST: ' . wp_json_encode( $ticket_checkout, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + + $order = wc_get_order( $order_id ); + $amount = $this->get_order_total(); + $shipping_taxes = (float) ($order->get_shipping_total()); + + $order->update_meta_data( 'is_production_mode', 'no' === $this->mp_options->get_checkbox_checkout_test_mode() ? 'yes' : 'no' ); + $order->update_meta_data( '_used_gateway', get_class( $this ) ); + + if ( ! empty( $this->gateway_discount ) ) { + $discount = ( $amount - $shipping_taxes ) * $this->gateway_discount / 100; + $order->update_meta_data( 'Mercado Pago: discount', __( 'discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . $this->gateway_discount . '% / ' . __( 'discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' = ' . $discount ); + $order->set_total($amount - $discount); + } + + if ( ! empty( $this->commission ) ) { + $comission = $amount * ( $this->commission / 100 ); + $order->update_meta_data( 'Mercado Pago: comission', __( 'fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . $this->commission . '% / ' . __( 'fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' = ' . $comission ); + } + + $order->save(); + + // Check for brazilian FEBRABAN rules. + if ( 'mlb' === $this->mp_options->get_site_id() ) { + if ( ! isset( $ticket_checkout['docNumber'] ) || empty( $ticket_checkout['docNumber'] ) ) { + if ( isset( $ticket_checkout['docNumberError'] ) || ! empty( $ticket_checkout['docNumberError'] ) ) { + wc_add_notice( + '

' . + __( 'Your document data is invalid', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

', + 'error' + ); + } else { + wc_add_notice( + '

' . + __( 'There was a problem processing your payment. Are you sure you have correctly filled out all the information on the payment form?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

', + 'error' + ); + } + + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + } + + if ( 'mlu' === $this->mp_options->get_site_id() ) { + if ( + ! isset( $ticket_checkout['docNumber'] ) || empty( $ticket_checkout['docNumber'] ) || + ! isset( $ticket_checkout['docType'] ) || empty( $ticket_checkout['docType'] ) + ) { + if ( isset( $ticket_checkout['docNumberError'] ) || ! empty( $ticket_checkout['docNumberError'] ) ) { + wc_add_notice( + '

' . + __( 'Your document data is invalid', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

', + 'error' + ); + } else { + wc_add_notice( + '

' . + __( 'There was a problem processing your payment. Are you sure you have correctly filled out all the information on the payment form?', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

', + 'error' + ); + } + + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + } + + if ( isset( $ticket_checkout['amount'] ) && ! empty( $ticket_checkout['amount'] ) && + isset( $ticket_checkout['paymentMethodId'] ) && ! empty( $ticket_checkout['paymentMethodId'] ) ) { + $response = $this->create_payment( $order, $ticket_checkout ); + + if ( is_array( $response ) && array_key_exists( 'status', $response ) ) { + $this->hook->update_mp_order_payments_metadata( $order->get_id(), array($response['id']) ); + + if ( 'pending' === $response['status'] ) { + if ( 'pending_waiting_payment' === $response['status_detail'] || 'pending_waiting_transfer' === $response['status_detail'] ) { + WC()->cart->empty_cart(); + if ( 'yes' === $this->stock_reduce_mode ) { + wc_reduce_stock_levels( $order_id ); + } + // WooCommerce 3.0 or later. + $order->update_meta_data( '_transaction_details_ticket', $response['transaction_details']['external_resource_url'] ); + $order->save(); + // Shows some info in checkout page. + $order->add_order_note( + 'Mercado Pago: ' . + __( 'The customer has not paid yet.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + if ( 'bank_transfer' !== $response['payment_type_id'] ) { + $order->add_order_note( + 'Mercado Pago: ' . + __( 'To print the ticket again click', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + ' ' . + __( 'here', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '', + 1, + false + ); + } + + return array( + 'result' => 'success', + 'redirect' => $order->get_checkout_order_received_url(), + ); + } + } + } else { + // Process when fields are imcomplete. + wc_add_notice( + '

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

', + 'error' + ); + + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + } else { + // Process when fields are incomplete. + return $this->process_result_fail( + __FUNCTION__, + __( 'A problem was occurred when processing your payment. Please, try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + __( 'A problem was occurred when processing your payment. Please, try again.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) + ); + } + } + + /** + * Process if result is fail + * + * @param $function + * @param $log_message + * @param $notice_message + * + * @return string[] + */ + protected function process_result_fail( $function, $log_message, $notice_message ) { + $this->log->write_log( $function, $log_message ); + + wc_add_notice( + '

' . $notice_message . '

', + 'error' + ); + + return array( + 'result' => 'fail', + 'redirect' => '', + ); + } + + /** + * Create payment + * + * @param object $order Order. + * @param array $ticket_checkout Ticket checkout. + * @return string|array + */ + public function create_payment( $order, $ticket_checkout ) { + $preferences_ticket = new WC_WooMercadoPago_Preference_Ticket( $this, $order, $ticket_checkout ); + $payment = $preferences_ticket->get_transaction( 'Payment' ); + + try { + $checkout_info = $payment->save(); + $this->log->write_log( __FUNCTION__, 'Created Payment: ' . wp_json_encode( $checkout_info, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ) ); + return $checkout_info; + } catch ( Exception $e ) { + $this->log->write_log( __FUNCTION__, 'payment creation failed with error: ' . $e->getMessage() ); + return $e->getMessage(); + } + } + + /** + * Is available? + * + * @return bool + */ + public function is_available() { + if ( ! parent::is_available() ) { + return false; + } + + $payment_methods = $this->activated_payment; + if ( 0 === count( $payment_methods ) ) { + $this->log->write_log( __FUNCTION__, 'Ticket unavailable, no active payment methods. ' ); + return false; + } + + return true; + } + + /** + * Get Id + * + * @return string + */ + public static function get_id() { + return self::ID; + } + + /** + * Build Paycash Payments String + * + * @return string + */ + public static function build_paycash_payments_string() { + $get_payment_methods_ticket = get_option( '_all_payment_methods_ticket', '[]' ); + + foreach ( $get_payment_methods_ticket as $payment ) { + if ( 'paycash' === $payment['id'] ) { + $payments = array_column( $payment['payment_places'], 'name'); + } + } + + $last_element = array_pop( $payments ); + $paycash_payments = implode(', ', $payments); + + return implode( __(' and ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), array($paycash_payments, $last_element)); + } + + /** + * Get Mercado Pago Icon + * + * @return mixed + */ + public function get_checkout_icon() { + $country = $this->get_option_mp( '_site_id_v1' ); + + if ( 'MLB' !== $country ) { + /** + * Add Mercado Pago icon. + * + * @since 3.0.1 + */ + return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/ticket.png', plugin_dir_path( __FILE__ ) ) ); + } + + /** + * Add Mercado Pago icon. + * + * @since 3.0.1 + */ + return apply_filters( 'woocommerce_mercadopago_icon', plugins_url( '../assets/images/icons/ticket_mlb.png', plugin_dir_path( __FILE__ ) ) ); + } } diff --git a/includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php b/includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php index 03c11a0c5..26f1b36d7 100755 --- a/includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php +++ b/includes/payments/hooks/class-wc-woomercadopago-hook-abstract.php @@ -1,620 +1,612 @@ payment = $payment; - $this->class = get_class( $payment ); - $this->mp_instance = $payment->mp; - $this->public_key = $payment->get_public_key(); - $this->test_user = get_option( '_test_user_v1' ); - $this->site_id = strtolower(get_option( '_site_id_v1' )); - - $this->load_hooks(); - } - - /** - * Load Hooks - */ - public function load_hooks() { - add_action( 'woocommerce_update_options_payment_gateways_' . $this->payment->id, array( $this, 'custom_process_admin_options' ) ); - add_action( 'woocommerce_cart_calculate_fees', array( $this, 'add_discount' ), 10 ); - add_filter( 'woocommerce_gateway_title', array( $this, 'get_payment_method_title' ), 10, 2 ); - - add_action( - 'admin_notices', - function() { - WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->notices( $this->payment ); - } - ); - - if ( ! empty( $this->payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { - add_action( 'woocommerce_after_checkout_form', array( $this, 'add_mp_settings_script' ) ); - add_action( 'woocommerce_thankyou', array( $this, 'update_mp_settings_script' ) ); - } - } - - /** - * Add discount - * - * @param array $checkout Checkout information. - */ - public function add_discount_abst( $checkout ) { - if ( - isset( $checkout['discount'] ) - && ! empty( $checkout['discount'] ) - && isset( $checkout['coupon_code'] ) - && ! empty( $checkout['coupon_code'] ) - && $checkout['discount'] > 0 - && WC()->session->chosen_payment_method === $this->payment->id - ) { - $this->payment->log->write_log( __FUNCTION__, $this->class . 'trying to apply discount...' ); - - $value = ( 'COP' === $this->payment->site_data['currency'] || 'CLP' === $this->payment->site_data['currency'] ) - ? floor( $checkout['discount'] / $checkout['currency_ratio'] ) - : floor( $checkout['discount'] / $checkout['currency_ratio'] * 100 ) / 100; - - global $woocommerce; - - /** - * Apply discount filter. - * - * @since 3.0.1 - */ - if ( apply_filters( 'wc_mercadopago_custommodule_apply_discount', 0 < $value, $woocommerce->cart ) ) { - $woocommerce->cart->add_fee( - sprintf( - /* translators: %s coupon */ - __( 'Discount for coupon %s', 'woocommerce-mercadopago' ), - esc_attr( $checkout['campaign'] ) - ), - ( $value * -1 ), - false - ); - } - } - } - - /** - * Get payment method title - * - * @param string $title Title. - * @param string $id Id. - * - * @return string - */ - public function get_payment_method_title( $title, $id ) { - if ( ! preg_match( '/woo-mercado-pago/', $id ) ) { - return $title; - } - - if ( $id !== $this->payment->id ) { - return $title; - } - - if ( ! is_checkout() && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) { - return $title; - } - if ( $title !== $this->payment->title && ( 0 === $this->payment->commission && 0 === $this->payment->gateway_discount ) ) { - return $title; - } - if ( ! is_numeric( $this->payment->gateway_discount ) || $this->payment->commission > 99 || $this->payment->gateway_discount > 99 ) { - return $title; - } - - $total = (float) WC()->cart->subtotal; - $price_discount = $total * ( $this->payment->gateway_discount / 100 ); - $price_commission = $total * ( $this->payment->commission / 100 ); - - if ( $this->payment->gateway_discount > 0 && $this->payment->commission > 0 ) { - $title .= ' (' . __( 'discount of', 'woocommerce-mercadopago' ) . ' ' . wp_strip_all_tags( wc_price( $price_discount ) ) . __( ' and fee of', 'woocommerce-mercadopago' ) . ' ' . wp_strip_all_tags( wc_price( $price_commission ) ) . ')'; - } elseif ( $this->payment->gateway_discount > 0 ) { - $title .= ' (' . __( 'discount of', 'woocommerce-mercadopago' ) . ' ' . wp_strip_all_tags( wc_price( $price_discount ) ) . ')'; - } elseif ( $this->payment->commission > 0 ) { - $title .= ' (' . __( 'fee of', 'woocommerce-mercadopago' ) . ' ' . wp_strip_all_tags( wc_price( $price_commission ) ) . ')'; - } - return $title; - } - - /** - * MP Settings Script - */ - public function add_mp_settings_script() { - if ( ! empty( $this->public_key ) && ! $this->test_user && isset( WC()->payment_gateways ) ) { - $woo = WC_WooMercadoPago_Module::woocommerce_instance(); - $gateways = $woo->payment_gateways->get_available_payment_gateways(); - - $available_payments = array(); - foreach ( $gateways as $gateway ) { - $available_payments[] = $gateway->id; - } - - $available_payments = str_replace( '-', '_', implode( ', ', $available_payments ) ); - $logged_user_email = null; - if ( 0 !== wp_get_current_user()->ID ) { - $logged_user_email = wp_get_current_user()->user_email; - } - } - } - - /** - * Settings script - * - * @param int $order_id - * - * @return void - */ - public function update_mp_settings_script( $order_id ) { - // Do nothing - } - - /** - * Update order payments metadata - * - * @param string $order_id - * @param array $payments_id - * - * @return void - */ - public function update_mp_order_payments_metadata( $order_id, $payments_id ) { - $order = wc_get_order( $order_id ); - $payments_id_meta_key = '_Mercado_Pago_Payment_IDs'; - $payments_id_metadata = (bool) $order->get_meta( $payments_id_meta_key ); - if ( count( $payments_id ) > 0 ) { - if ( ! $payments_id_metadata ) { - $order->update_meta_data( $payments_id_meta_key, implode( ', ', $payments_id ) ); - $order->save(); - } - - foreach ( $payments_id as $payment_id ) { - $payment_detail_meta_key = 'Mercado Pago - Payment ' . $payment_id; - $payment_detail_metadata = count ( (array) $order->get_meta( $payment_detail_meta_key ) ); - - if ( 0 === $payment_detail_metadata ) { - $order->update_meta_data( $payment_detail_meta_key, '[Date ' . gmdate('Y-m-d H:i:s') . ']' ); - $order->save(); - } - } - } - } - - /** - * Sort By Checkout Mode First - * - * @param array $form_fields Form fields - * - * @return array $sorted_array Sorted array - */ - public function sort_by_checkout_mode_first( $form_fields ) { - $sort_credentials_first = array( - 'checkout_subtitle_checkout_mode', - 'checkbox_checkout_test_mode', - 'checkbox_checkout_production_mode', - '_mp_public_key_prod', - '_mp_access_token_prod', - '_mp_public_key_test', - '_mp_access_token_test', - ); - - return $this->payment->sort_form_fields( $form_fields, $sort_credentials_first ); - } - - /** - * Custom process admin options - * - * @return bool - * @throws WC_WooMercadoPago_Exception Admin Options Exception. - */ - public function custom_process_admin_options() { - $old_data = array(); - $value_credential_production = null; - - $this->payment->init_settings(); - - $post_data = $this->payment->get_post_data(); - $form_fields = $this->payment->get_form_fields(); - - $form_fields = $this->handle_mp_components($form_fields); - $sorted_form_fields = $this->sort_by_checkout_mode_first( $form_fields ); - - foreach ( $sorted_form_fields as $key => $field ) { - if ( 'title' !== $this->payment->get_field_type( $field ) ) { - $value = $this->payment->get_field_value( $key, $field, $post_data ); - $old_data[ $key ] = isset( $this->payment->settings[ $key ] ) ? $this->payment->settings[ $key ] : null; - - if ( 'checkbox_checkout_test_mode' === $key ) { - $value_credential_production = 'yes' === $value ? 'no' : 'yes'; - } - - $common_configs = $this->payment->get_common_configs(); - - if ( in_array( $key, $common_configs, true ) ) { - if ( $this->validate_credentials( $key, $value, $value_credential_production ) ) { - continue; - } - - update_option( $key, $value, true ); - } - - $value = $this->payment->get_field_value( $key, $field, $post_data ); - $this->payment->settings[ $key ] = $value; - } - } - - WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->schedule_notice( - $this->payment, - $old_data, - $this->payment->settings - ); - - /** - * Update if options were changed. - * - * @since 3.0.1 - */ - return update_option( $this->payment->get_option_key(), apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $this->payment->id, $this->payment->settings ) ); - } - - /** - * Handles custom components for better integration with native hooks - * - * @param array $form_fields all the form fields - * - * @return array - */ - public function handle_mp_components( $form_fields ) { - foreach ( $form_fields as $key => $form_field ) { - //separating payment methods - if ( 'mp_checkbox_list' === $form_field['type'] ) { - $form_fields += $this->separate_checkboxes($form_fields[$key]); - unset($form_fields[$key]); - } - - //separating checkboxes from activable inputs - if ( 'mp_activable_input' === $form_field['type'] && ! isset( $form_fields[$key . '_checkbox'] ) ) { - $form_fields[$key . '_checkbox'] = array( - 'type' => 'checkbox', - ); - } - - //setting toggle as checkbox - if ( 'mp_toggle_switch' === $form_field['type'] ) { - $form_fields[$key]['type'] = 'checkbox'; - } - } - - return $form_fields; - } - - /** - * Separates multiple ex_payments checkbox into an array - * - * @param array $ex_payments ex_payments form field - * - * @return array - */ - public function separate_checkboxes( $ex_payments ) { - $payment_methods = array(); - foreach ( $ex_payments['payment_method_types'] as $payment_method_type ) { - $payment_methods += $this->separate_checkboxes_list($payment_method_type['list']); - } - return $payment_methods; - } - - /** - * Separates multiple ex_payments checkbox into an array - * - * @param array $ex_payments list of payment_methods - * - * @return array - */ - public function separate_checkboxes_list( $ex_payments_list ) { - $payment_methods = array(); - foreach ( $ex_payments_list as $payment ) { - $payment_methods[$payment['id']] = $payment; - } - return $payment_methods; - } - - /** - * Build Woocommerce settings key - * - * @param String $gateway_id Constant ID - * - * @return String - */ - private function build_woocommerce_settings_key( $gateway_id ) { - return 'woocommerce_' . $gateway_id . '_settings'; - } - - /** - * Validate credentials - * - * @param string $key Key. - * @param string $value Value. - * @param string|null $value_credential_production Production credentials. - * - * @return bool - * @throws WC_WooMercadoPago_Exception Invalid credentials exception. - */ - private function validate_credentials( $key, $value, $value_credential_production = null ) { - if ( $this->validate_public_key( $key, $value ) ) { - return true; - } - - if ( $this->validate_access_token( $key, $value, $value_credential_production ) ) { - return true; - } - - return false; - } - - /** - * Validate Public Key - * - * @param string $key key. - * @param string $value value. - * - * @return bool - */ - private function validate_public_key( $key, $value ) { - if ( '_mp_public_key_test' !== $key && '_mp_public_key_prod' !== $key ) { - return false; - } - - if ( '_mp_public_key_prod' === $key ) { - if ( null === $value || '' === $value ) { - add_action( 'admin_notices', array( $this, 'notice_blank_public_key_prod' ) ); - return true; - } - - if ( false === WC_WooMercadoPago_Credentials::validate_credentials_prod( $this->mp_instance, null, $value ) ) { - update_option( $key, '', true ); - add_action( 'admin_notices', array( $this, 'notice_invalid_public_key_prod' ) ); - return true; - } - } - - if ( '_mp_public_key_test' === $key ) { - if ( null === $value || '' === $value ) { - add_action( 'admin_notices', array( $this, 'notice_blank_public_key_test' ) ); - return true; - } - - if ( false === WC_WooMercadoPago_Credentials::validate_credentials_test( $this->mp_instance, null, $value ) ) { - update_option( $key, '', true ); - add_action( 'admin_notices', array( $this, 'notice_invalid_public_key_test' ) ); - return true; - } - } - - return false; - } - - /** - * Validate Access Token - * - * @param string $key Key. - * @param string $value Value. - * @param string|null $is_production Is Production. - * - * @return bool - * @throws WC_WooMercadoPago_Exception Invalid Access Token Exception. - */ - private function validate_access_token( $key, $value, $is_production = null ) { - if ( '_mp_access_token_prod' !== $key && '_mp_access_token_test' !== $key ) { - return false; - } - - if ( '_mp_access_token_prod' === $key ) { - if ( null === $value || '' === $value ) { - add_action( 'admin_notices', array( $this, 'notice_blank_prod_credentials' ) ); - return true; - } - - if ( false === WC_WooMercadoPago_Credentials::validate_credentials_prod( $this->mp_instance, $value, null ) ) { - add_action( 'admin_notices', array( $this, 'notice_invalid_prod_credentials' ) ); - update_option( $key, '', true ); - return true; - } - } - - if ( '_mp_access_token_test' === $key ) { - if ( null === $value || '' === $value ) { - add_action( 'admin_notices', array( $this, 'notice_blank_test_credentials' ) ); - return true; - } - - if ( false === WC_WooMercadoPago_Credentials::validate_credentials_test( $this->mp_instance, $value, null ) ) { - add_action( 'admin_notices', array( $this, 'notice_invalid_test_credentials' ) ); - update_option( $key, '', true ); - return true; - } - } - - if ( empty( $is_production ) ) { - $is_production = $this->payment->is_production_mode(); - } - - if ( WC_WooMercadoPago_Credentials::access_token_is_valid( $value ) ) { - update_option( $key, $value, true ); - - if ( '_mp_access_token_prod' === $key ) { - $homolog_validate = $this->mp_instance->get_credentials_wrapper( $value ); - $homolog_validate = isset( $homolog_validate['homologated'] ) && true === $homolog_validate['homologated'] ? 1 : 0; - update_option( 'homolog_validate', $homolog_validate, true ); - if ( 'yes' === $is_production && 0 === $homolog_validate ) { - add_action( 'admin_notices', array( $this, 'enable_payment_notice' ) ); - } - } - - if ( - ( '_mp_access_token_prod' === $key && 'yes' === $is_production ) || ( '_mp_access_token_test' === $key && 'no' === $is_production ) - ) { - WC_WooMercadoPago_Credentials::update_payment_methods( $this->mp_instance, $value ); - WC_WooMercadoPago_Credentials::update_ticket_method( $this->mp_instance, $value ); - $wc_country = WC_WooMercadoPago_Module::get_woocommerce_default_country(); - $site_id = strtolower(get_option( '_site_id_v1', '' )); - if ( ( 'BR' === $wc_country && '' === $site_id ) || ( 'mlb' === $site_id ) ) { - WC_WooMercadoPago_Credentials::update_pix_method( $this->mp_instance, $value ); - } - } - return true; - } - - if ( '_mp_access_token_prod' === $key ) { - update_option( '_mp_public_key_prod', '', true ); - WC_WooMercadoPago_Credentials::set_no_credentials(); - add_action( 'admin_notices', array( $this, 'notice_invalid_prod_credentials' ) ); - } else { - update_option( '_mp_public_key_test', '', true ); - add_action( 'admin_notices', array( $this, 'notice_invalid_test_credentials' ) ); - } - - update_option( $key, '', true ); - return true; - } - - /** - * ADMIN NOTICE - */ - public function notice_invalid_public_key_prod() { - $type = 'error'; - $message = __( 'Public Key production credential is invalid. Review the field to receive real payments.', 'woocommerce-mercadopago' ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * ADMIN NOTICE - */ - public function notice_invalid_public_key_test() { - $type = 'error'; - $message = __( 'Public Key test credential is invalid. Review the field to perform tests in your store.', 'woocommerce-mercadopago' ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * ADMIN NOTICE - */ - public function notice_invalid_prod_credentials() { - $type = 'error'; - $message = __( 'Access Token production credential is invalid. Remember that it must be complete to receive real payments.', 'woocommerce-mercadopago' ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * ADMIN NOTICE - */ - public function notice_invalid_test_credentials() { - $type = 'error'; - $message = __( 'Access Token test credential is invalid. Review the field to perform tests in your store.', 'woocommerce-mercadopago' ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * Enable payment notice - */ - public function enable_payment_notice() { - $type = 'notice-warning'; - $message = __( 'Fill in your credentials to enable payment methods.', 'woocommerce-mercadopago' ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * ADMIN NOTICE - */ - public function notice_blank_public_key_test() { - $type = 'error'; - $message = __( 'Public Key test credential is blank. Review the field to perform tests in your store.', 'woocommerce-mercadopago' ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * ADMIN NOTICE - */ - public function notice_blank_public_key_prod() { - $type = 'error'; - $message = __( 'Public Key production credential is blank. Review the field to receive real payments.', 'woocommerce-mercadopago' ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * ADMIN NOTICE - */ - public function notice_blank_test_credentials() { - $type = 'error'; - $message = __( 'Access Token test credential is blank. Review the field to perform tests in your store.', 'woocommerce-mercadopago' ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } - - /** - * ADMIN NOTICE - */ - public function notice_blank_prod_credentials() { - $type = 'error'; - $message = __( 'Access Token production credential is blank. Remember that it must be complete to receive real payments.', 'woocommerce-mercadopago' ); - WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); - } + /** + * Payment class + * + * @var WC_WooMercadoPago_Payment_Abstract|WC_WooMercadoPago_Basic_Gateway|WC_WooMercadoPago_Custom_Gateway + */ + public $payment; + + /** + * Payment class + * + * @var WC_WooMercadoPago_Payment_Abstract + */ + public $class; + + /** + * Logger + * + * @var MP|null + */ + public $mp_instance; + + /** + * Public Key + * + * @var string + */ + public $public_key; + + /** + * Is test user? + * + * @var string + */ + public $test_user; + + /** + * Site Id + * + * @var string + */ + public $site_id; + + /** + * WC_WooMercadoPago_Hook_Abstract constructor. + * + * @param WC_WooMercadoPago_Payment_Abstract $payment Payment method. + */ + public function __construct( $payment ) { + $this->payment = $payment; + $this->class = get_class( $payment ); + $this->mp_instance = $payment->mp; + $this->public_key = $payment->get_public_key(); + $this->test_user = get_option( '_test_user_v1' ); + $this->site_id = strtolower(get_option( '_site_id_v1' )); + + $this->load_hooks(); + } + + /** + * Load Hooks + */ + public function load_hooks(): void { + add_action( 'woocommerce_update_options_payment_gateways_' . $this->payment->id, array($this, 'custom_process_admin_options') ); + add_action( 'woocommerce_cart_calculate_fees', array($this, 'add_discount'), 10 ); + add_filter( 'woocommerce_gateway_title', array($this, 'get_payment_method_title'), 10, 2 ); + + add_action( + 'admin_notices', + function(): void { + WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->notices( $this->payment ); + } + ); + + if ( ! empty( $this->payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { + add_action( 'woocommerce_after_checkout_form', array($this, 'add_mp_settings_script') ); + add_action( 'woocommerce_thankyou', array($this, 'update_mp_settings_script') ); + } + } + + /** + * Add discount + * + * @param array $checkout Checkout information. + */ + public function add_discount_abst( $checkout ): void { + if ( + isset( $checkout['discount'] ) + && ! empty( $checkout['discount'] ) + && isset( $checkout['coupon_code'] ) + && ! empty( $checkout['coupon_code'] ) + && $checkout['discount'] > 0 + && WC()->session->chosen_payment_method === $this->payment->id + ) { + $this->payment->log->write_log( __FUNCTION__, $this->class . 'trying to apply discount...' ); + + $value = ( 'COP' === $this->payment->site_data['currency'] || 'CLP' === $this->payment->site_data['currency'] ) + ? floor( $checkout['discount'] / $checkout['currency_ratio'] ) + : floor( $checkout['discount'] / $checkout['currency_ratio'] * 100 ) / 100; + + global $woocommerce; + + /** + * Apply discount filter. + * + * @since 3.0.1 + */ + if ( apply_filters( 'wc_mercadopago_custommodule_apply_discount', 0 < $value, $woocommerce->cart ) ) { + $woocommerce->cart->add_fee( + sprintf( + /* translators: %s coupon */ + __( 'Discount for coupon %s', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + esc_attr( $checkout['campaign'] ) + ), + ( $value * -1 ), + false + ); + } + } + } + + /** + * Get payment method title + * + * @param string $title Title. + * @param string $id Id. + * + * @return string + */ + public function get_payment_method_title( $title, $id ) { + if ( ! preg_match( '/woo-mercado-pago/', $id ) ) { + return $title; + } + + if ( $id !== $this->payment->id ) { + return $title; + } + + if ( ! is_checkout() && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) { + return $title; + } + if ( $title !== $this->payment->title && ( 0 === $this->payment->commission && 0 === $this->payment->gateway_discount ) ) { + return $title; + } + if ( ! is_numeric( $this->payment->gateway_discount ) || $this->payment->commission > 99 || $this->payment->gateway_discount > 99 ) { + return $title; + } + + $total = (float) WC()->cart->subtotal; + $price_discount = $total * ( $this->payment->gateway_discount / 100 ); + $price_commission = $total * ( $this->payment->commission / 100 ); + + if ( $this->payment->gateway_discount > 0 && $this->payment->commission > 0 ) { + $title .= ' (' . __( 'discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . wp_strip_all_tags( wc_price( $price_discount ) ) . __( ' and fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . wp_strip_all_tags( wc_price( $price_commission ) ) . ')'; + } elseif ( $this->payment->gateway_discount > 0 ) { + $title .= ' (' . __( 'discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . wp_strip_all_tags( wc_price( $price_discount ) ) . ')'; + } elseif ( $this->payment->commission > 0 ) { + $title .= ' (' . __( 'fee of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . ' ' . wp_strip_all_tags( wc_price( $price_commission ) ) . ')'; + } + return $title; + } + + /** + * MP Settings Script + */ + public function add_mp_settings_script(): void { + if ( ! empty( $this->public_key ) && ! $this->test_user && isset( WC()->payment_gateways ) ) { + $woo = WC_WooMercadoPago_Module::woocommerce_instance(); + $gateways = $woo->payment_gateways->get_available_payment_gateways(); + + $available_payments = array(); + foreach ( $gateways as $gateway ) { + $available_payments[] = $gateway->id; + } + + $available_payments = str_replace( '-', '_', implode( ', ', $available_payments ) ); + $logged_user_email = null; + if ( 0 !== wp_get_current_user()->ID ) { + $logged_user_email = wp_get_current_user()->user_email; + } + } + } + + /** + * Settings script + * + * @param int $order_id + * + * @return void + */ + public function update_mp_settings_script( $order_id ): void { + // Do nothing + } + + /** + * Update order payments metadata + * + * @param string $order_id + * @param array $payments_id + * + * @return void + */ + public function update_mp_order_payments_metadata( $order_id, $payments_id ): void { + $order = wc_get_order( $order_id ); + $payments_id_meta_key = '_Mercado_Pago_Payment_IDs'; + $payments_id_metadata = (bool) $order->get_meta( $payments_id_meta_key ); + if ( count( $payments_id ) > 0 ) { + if ( ! $payments_id_metadata ) { + $order->update_meta_data( $payments_id_meta_key, implode( ', ', $payments_id ) ); + $order->save(); + } + + foreach ( $payments_id as $payment_id ) { + $payment_detail_meta_key = 'Mercado Pago - Payment ' . $payment_id; + $payment_detail_metadata = count ( (array) $order->get_meta( $payment_detail_meta_key ) ); + + if ( 0 === $payment_detail_metadata ) { + $order->update_meta_data( $payment_detail_meta_key, '[Date ' . gmdate('Y-m-d H:i:s') . ']' ); + $order->save(); + } + } + } + } + + /** + * Sort By Checkout Mode First + * + * @param array $form_fields Form fields + * + * @return array $sorted_array Sorted array + */ + public function sort_by_checkout_mode_first( $form_fields ) { + $sort_credentials_first = array( + 'checkout_subtitle_checkout_mode', + 'checkbox_checkout_test_mode', + 'checkbox_checkout_production_mode', + '_mp_public_key_prod', + '_mp_access_token_prod', + '_mp_public_key_test', + '_mp_access_token_test', + ); + + return $this->payment->sort_form_fields( $form_fields, $sort_credentials_first ); + } + + /** + * Custom process admin options + * + * @return bool + * @throws WC_WooMercadoPago_Exception Admin Options Exception. + */ + public function custom_process_admin_options() { + $old_data = array(); + $value_credential_production = null; + + $this->payment->init_settings(); + + $post_data = $this->payment->get_post_data(); + $form_fields = $this->payment->get_form_fields(); + + $form_fields = $this->handle_mp_components($form_fields); + $sorted_form_fields = $this->sort_by_checkout_mode_first( $form_fields ); + + foreach ( $sorted_form_fields as $key => $field ) { + if ( 'title' !== $this->payment->get_field_type( $field ) ) { + $value = $this->payment->get_field_value( $key, $field, $post_data ); + $old_data[ $key ] = isset( $this->payment->settings[ $key ] ) ? $this->payment->settings[ $key ] : null; + + if ( 'checkbox_checkout_test_mode' === $key ) { + $value_credential_production = 'yes' === $value ? 'no' : 'yes'; + } + + $common_configs = $this->payment->get_common_configs(); + + if ( in_array( $key, $common_configs, true ) ) { + if ( $this->validate_credentials( $key, $value, $value_credential_production ) ) { + continue; + } + + update_option( $key, $value, true ); + } + + $value = $this->payment->get_field_value( $key, $field, $post_data ); + $this->payment->settings[ $key ] = $value; + } + } + + WC_WooMercadoPago_Helpers_CurrencyConverter::get_instance()->schedule_notice( + $this->payment, + $old_data, + $this->payment->settings + ); + + /** + * Update if options were changed. + * + * @since 3.0.1 + */ + return update_option( $this->payment->get_option_key(), apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $this->payment->id, $this->payment->settings ) ); + } + + /** + * Handles custom components for better integration with native hooks + * + * @param array $form_fields all the form fields + * + * @return array + */ + public function handle_mp_components( $form_fields ) { + foreach ( $form_fields as $key => $form_field ) { + //separating payment methods + if ( 'mp_checkbox_list' === $form_field['type'] ) { + $form_fields += $this->separate_checkboxes($form_fields[$key]); + unset($form_fields[$key]); + } + + //separating checkboxes from activable inputs + if ( 'mp_activable_input' === $form_field['type'] && ! isset( $form_fields[$key . '_checkbox'] ) ) { + $form_fields[$key . '_checkbox'] = array( + 'type' => 'checkbox', + ); + } + + //setting toggle as checkbox + if ( 'mp_toggle_switch' === $form_field['type'] ) { + $form_fields[$key]['type'] = 'checkbox'; + } + } + + return $form_fields; + } + + /** + * Separates multiple ex_payments checkbox into an array + * + * @param array $ex_payments ex_payments form field + * + * @return array + */ + public function separate_checkboxes( $ex_payments ) { + $payment_methods = array(); + foreach ( $ex_payments['payment_method_types'] as $payment_method_type ) { + $payment_methods += $this->separate_checkboxes_list($payment_method_type['list']); + } + return $payment_methods; + } + + /** + * Separates multiple ex_payments checkbox into an array + * + * @param array $ex_payments list of payment_methods + * + * @return array + */ + public function separate_checkboxes_list( $ex_payments_list ) { + $payment_methods = array(); + foreach ( $ex_payments_list as $payment ) { + $payment_methods[$payment['id']] = $payment; + } + return $payment_methods; + } + + /** + * Build Woocommerce settings key + * + * @param String $gateway_id Constant ID + * + * @return String + */ + private function build_woocommerce_settings_key( $gateway_id ) { + return 'woocommerce_' . $gateway_id . '_settings'; + } + + /** + * Validate credentials + * + * @param string $key Key. + * @param string $value Value. + * @param string|null $value_credential_production Production credentials. + * + * @return bool + * @throws WC_WooMercadoPago_Exception Invalid credentials exception. + */ + private function validate_credentials( $key, $value, $value_credential_production = null ) { + if ( $this->validate_public_key( $key, $value ) ) { + return true; + } + + if ( $this->validate_access_token( $key, $value, $value_credential_production ) ) { + return true; + } + + return false; + } + + /** + * Validate Public Key + * + * @param string $key key. + * @param string $value value. + * + * @return bool + */ + private function validate_public_key( $key, $value ) { + if ( '_mp_public_key_test' !== $key && '_mp_public_key_prod' !== $key ) { + return false; + } + + if ( '_mp_public_key_prod' === $key ) { + if ( null === $value || '' === $value ) { + add_action( 'admin_notices', array($this, 'notice_blank_public_key_prod') ); + return true; + } + + if ( false === WC_WooMercadoPago_Credentials::validate_credentials_prod( $this->mp_instance, null, $value ) ) { + update_option( $key, '', true ); + add_action( 'admin_notices', array($this, 'notice_invalid_public_key_prod') ); + return true; + } + } + + if ( '_mp_public_key_test' === $key ) { + if ( null === $value || '' === $value ) { + add_action( 'admin_notices', array($this, 'notice_blank_public_key_test') ); + return true; + } + + if ( false === WC_WooMercadoPago_Credentials::validate_credentials_test( $this->mp_instance, null, $value ) ) { + update_option( $key, '', true ); + add_action( 'admin_notices', array($this, 'notice_invalid_public_key_test') ); + return true; + } + } + + return false; + } + + /** + * Validate Access Token + * + * @param string $key Key. + * @param string $value Value. + * @param string|null $is_production Is Production. + * + * @return bool + * @throws WC_WooMercadoPago_Exception Invalid Access Token Exception. + */ + private function validate_access_token( $key, $value, $is_production = null ) { + if ( '_mp_access_token_prod' !== $key && '_mp_access_token_test' !== $key ) { + return false; + } + + if ( '_mp_access_token_prod' === $key ) { + if ( null === $value || '' === $value ) { + add_action( 'admin_notices', array($this, 'notice_blank_prod_credentials') ); + return true; + } + + if ( false === WC_WooMercadoPago_Credentials::validate_credentials_prod( $this->mp_instance, $value, null ) ) { + add_action( 'admin_notices', array($this, 'notice_invalid_prod_credentials') ); + update_option( $key, '', true ); + return true; + } + } + + if ( '_mp_access_token_test' === $key ) { + if ( null === $value || '' === $value ) { + add_action( 'admin_notices', array($this, 'notice_blank_test_credentials') ); + return true; + } + + if ( false === WC_WooMercadoPago_Credentials::validate_credentials_test( $this->mp_instance, $value, null ) ) { + add_action( 'admin_notices', array($this, 'notice_invalid_test_credentials') ); + update_option( $key, '', true ); + return true; + } + } + + if ( empty( $is_production ) ) { + $is_production = $this->payment->is_production_mode(); + } + + if ( WC_WooMercadoPago_Credentials::access_token_is_valid( $value ) ) { + update_option( $key, $value, true ); + + if ( '_mp_access_token_prod' === $key ) { + $homolog_validate = $this->mp_instance->get_credentials_wrapper( $value ); + $homolog_validate = isset( $homolog_validate['homologated'] ) && true === $homolog_validate['homologated'] ? 1 : 0; + update_option( 'homolog_validate', $homolog_validate, true ); + if ( 'yes' === $is_production && 0 === $homolog_validate ) { + add_action( 'admin_notices', array($this, 'enable_payment_notice') ); + } + } + + if ( + ( '_mp_access_token_prod' === $key && 'yes' === $is_production ) || ( '_mp_access_token_test' === $key && 'no' === $is_production ) + ) { + WC_WooMercadoPago_Credentials::update_payment_methods( $this->mp_instance, $value ); + WC_WooMercadoPago_Credentials::update_ticket_method( $this->mp_instance, $value ); + $wc_country = WC_WooMercadoPago_Module::get_woocommerce_default_country(); + $site_id = strtolower(get_option( '_site_id_v1', '' )); + if ( ( 'BR' === $wc_country && '' === $site_id ) || ( 'mlb' === $site_id ) ) { + WC_WooMercadoPago_Credentials::update_pix_method( $this->mp_instance, $value ); + } + } + return true; + } + + if ( '_mp_access_token_prod' === $key ) { + update_option( '_mp_public_key_prod', '', true ); + WC_WooMercadoPago_Credentials::set_no_credentials(); + add_action( 'admin_notices', array($this, 'notice_invalid_prod_credentials') ); + } else { + update_option( '_mp_public_key_test', '', true ); + add_action( 'admin_notices', array($this, 'notice_invalid_test_credentials') ); + } + + update_option( $key, '', true ); + return true; + } + + /** + * ADMIN NOTICE + */ + public function notice_invalid_public_key_prod(): void { + $type = 'error'; + $message = __( 'Public Key production credential is invalid. Review the field to receive real payments.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * ADMIN NOTICE + */ + public function notice_invalid_public_key_test(): void { + $type = 'error'; + $message = __( 'Public Key test credential is invalid. Review the field to perform tests in your store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * ADMIN NOTICE + */ + public function notice_invalid_prod_credentials(): void { + $type = 'error'; + $message = __( 'Access Token production credential is invalid. Remember that it must be complete to receive real payments.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * ADMIN NOTICE + */ + public function notice_invalid_test_credentials(): void { + $type = 'error'; + $message = __( 'Access Token test credential is invalid. Review the field to perform tests in your store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * Enable payment notice + */ + public function enable_payment_notice(): void { + $type = 'notice-warning'; + $message = __( 'Fill in your credentials to enable payment methods.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * ADMIN NOTICE + */ + public function notice_blank_public_key_test(): void { + $type = 'error'; + $message = __( 'Public Key test credential is blank. Review the field to perform tests in your store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * ADMIN NOTICE + */ + public function notice_blank_public_key_prod(): void { + $type = 'error'; + $message = __( 'Public Key production credential is blank. Review the field to receive real payments.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * ADMIN NOTICE + */ + public function notice_blank_test_credentials(): void { + $type = 'error'; + $message = __( 'Access Token test credential is blank. Review the field to perform tests in your store.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } + + /** + * ADMIN NOTICE + */ + public function notice_blank_prod_credentials(): void { + $type = 'error'; + $message = __( 'Access Token production credential is blank. Remember that it must be complete to receive real payments.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ); + WC_WooMercadoPago_Notices::get_alert_frame( $message, $type ); + } } diff --git a/includes/payments/hooks/class-wc-woomercadopago-hook-basic.php b/includes/payments/hooks/class-wc-woomercadopago-hook-basic.php index 864ea400f..d8fdf3eb7 100755 --- a/includes/payments/hooks/class-wc-woomercadopago-hook-basic.php +++ b/includes/payments/hooks/class-wc-woomercadopago-hook-basic.php @@ -1,154 +1,145 @@ payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { - add_action( 'wp_enqueue_scripts', array( $this, 'add_checkout_scripts_basic' ) ); - add_action( 'woocommerce_after_checkout_form', array( $this, 'add_mp_settings_script_basic' ) ); - add_action( 'woocommerce_thankyou', array( $this, 'update_mp_settings_script_basic' ) ); - } - - add_action( - 'woocommerce_receipt_' . $this->payment->id, - function ( $order ) { - // phpcs:ignore WordPress.Security.EscapeOutput - echo $this->render_order_form( $order ); - } - ); - - add_action( - 'wp_head', - function () { - if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '2.1', '>=' ) ) { - $page_id = wc_get_page_id( 'checkout' ); - } else { - $page_id = woocommerce_get_page_id( 'checkout' ); - } - if ( is_page( $page_id ) ) { - echo '' . PHP_EOL; - } - } - ); - } - - /** - * Get Order Form - * - * @param string $order_id Order Id. - * - * @return string - */ - public function render_order_form( $order_id ) { - $order = wc_get_order( $order_id ); - $url = $this->payment->create_preference( $order ); - - if ( 'modal' === $this->payment->method && $url ) { - $this->payment->log->write_log( __FUNCTION__, 'rendering Mercado Pago lightbox (modal window).' ); - - $html = '' . \PHP_EOL; + } + } + ); + } + + /** + * Get Order Form + * + * @param string $order_id Order Id. + * + * @return string + */ + public function render_order_form( $order_id ) { + $order = wc_get_order( $order_id ); + $url = $this->payment->create_preference( $order ); + + if ( 'modal' === $this->payment->method && $url ) { + $this->payment->log->write_log( __FUNCTION__, 'rendering Mercado Pago lightbox (modal window).' ); + + $html = ''; - // mlstatic is a domain for the Mercado Pago CDN. - // This script is used to render the checkout pro in the modal function, avoiding redirection from the store to Mercado Pago. - // @todo use wp_enqueue_script - // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript - $html .= ''; - $html .= ''; + $html .= ''; - $html .= '' . - __( 'Pay with Mercado Pago', 'woocommerce-mercadopago' ) . - ' ' . - __( 'Cancel & Clear Cart', 'woocommerce-mercadopago' ) . - ''; - return $html; - } else { - $this->payment->log->write_log( __FUNCTION__, 'unable to build Checkout Pro URL.' ); - $html = '

' . - __( 'There was an error processing your payment. Please try again or contact us for Assistance.', 'woocommerce-mercadopago' ) . - '

' . - '' . - __( 'Click to try again', 'woocommerce-mercadopago' ) . - ' + $html .= '' . + __( 'Pay with Mercado Pago', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + ' ' . + __( 'Cancel & Clear Cart', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + ''; + return $html; + } else { + $this->payment->log->write_log( __FUNCTION__, 'unable to build Checkout Pro URL.' ); + $html = '

' . + __( 'There was an error processing your payment. Please try again or contact us for Assistance.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

' . + '' . + __( 'Click to try again', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + ' '; - return $html; - } - } - - /** - * Add Checkout Scripts - */ - public function add_checkout_scripts_basic() { - if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - - wp_enqueue_script( - 'woocommerce-mercadopago-narciso-scripts', - plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), - array( 'jquery' ), - WC_WooMercadoPago_Constants::VERSION, - true - ); - } - } - - /** - * Scripts to basic - */ - public function add_mp_settings_script_basic() { - parent::add_mp_settings_script(); - } - - /** - * Update settings script basic - * - * @param string $order_id Order Id. - */ - public function update_mp_settings_script_basic( $order_id ) { - parent::update_mp_settings_script( $order_id ); - - $payments_id = []; - $collection_id = sanitize_text_field($_GET['collection_id'] ?? ''); // phpcs:ignore - - if ( ! empty( $collection_id ) ) { - $collection_id = explode( ',', $collection_id ); - foreach ( $collection_id as $payment_id ) { - $payments_id[] = preg_replace( '/\D/', '', $payment_id ); - } - } - - $this->update_mp_order_payments_metadata( $order_id, $payments_id ); - } - - /** - * Discount not apply - */ - public function add_discount() { - // Do nothing. - } - + return $html; + } + } + + /** + * Add Checkout Scripts + */ + public function add_checkout_scripts_basic(): void { + if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + wp_enqueue_script( + 'woocommerce-mercadopago-narciso-scripts', + plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), + array('jquery'), + WC_WooMercadoPago_Constants::VERSION, + true + ); + } + } + + /** + * Scripts to basic + */ + public function add_mp_settings_script_basic(): void { + parent::add_mp_settings_script(); + } + + /** + * Update settings script basic + * + * @param string $order_id Order Id. + */ + public function update_mp_settings_script_basic( $order_id ): void { + parent::update_mp_settings_script( $order_id ); + + $payments_id = array(); + $collection_id = sanitize_text_field($_GET['collection_id'] ?? ''); // phpcs:ignore + + if ( ! empty( $collection_id ) ) { + $collection_id = explode( ',', $collection_id ); + foreach ( $collection_id as $payment_id ) { + $payments_id[] = preg_replace( '/\D/', '', $payment_id ); + } + } + + $this->update_mp_order_payments_metadata( $order_id, $payments_id ); + } + + /** + * Discount not apply + */ + public function add_discount(): void { + // Do nothing. + } } diff --git a/includes/payments/hooks/class-wc-woomercadopago-hook-credits.php b/includes/payments/hooks/class-wc-woomercadopago-hook-credits.php index c9d4b22e6..3577c337b 100755 --- a/includes/payments/hooks/class-wc-woomercadopago-hook-credits.php +++ b/includes/payments/hooks/class-wc-woomercadopago-hook-credits.php @@ -1,152 +1,143 @@ payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { - add_action( 'wp_enqueue_scripts', array( $this, 'add_checkout_scripts_basic' ) ); - add_action( 'woocommerce_after_checkout_form', array( $this, 'add_mp_settings_script_basic' ) ); - add_action( 'woocommerce_thankyou', array( $this, 'update_mp_settings_script_basic' ) ); - } - - add_action( - 'woocommerce_receipt_' . $this->payment->id, - function ( $order ) { - // phpcs:ignore WordPress.Security.EscapeOutput - echo $this->render_order_form( $order ); - } - ); - - add_action( - 'wp_head', - function () { - if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '2.1', '>=' ) ) { - $page_id = wc_get_page_id( 'checkout' ); - } else { - $page_id = woocommerce_get_page_id( 'checkout' ); - } - if ( is_page( $page_id ) ) { - echo '' . PHP_EOL; - } - } - ); - } - - /** - * Get Order Form - * - * @param string $order_id Order Id. - * - * @return string - */ - public function render_order_form( $order_id ) { - $order = wc_get_order( $order_id ); - $url = $this->payment->create_preference( $order ); - - if ( 'modal' === $this->payment->method && $url ) { - $this->payment->log->write_log( __FUNCTION__, 'rendering Mercado Pago lightbox (modal window).' ); - - $html = '' . \PHP_EOL; + } + } + ); + } + + /** + * Get Order Form + * + * @param string $order_id Order Id. + * + * @return string + */ + public function render_order_form( $order_id ) { + $order = wc_get_order( $order_id ); + $url = $this->payment->create_preference( $order ); + + if ( 'modal' === $this->payment->method && $url ) { + $this->payment->log->write_log( __FUNCTION__, 'rendering Mercado Pago lightbox (modal window).' ); + + $html = ''; - // @todo use wp_enqueue_script - // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript - $html .= ''; - $html .= ''; + $html .= ''; - $html .= '' . - __( 'Pay with Mercado Pago', 'woocommerce-mercadopago' ) . - ' ' . - __( 'Cancel & Clear Cart', 'woocommerce-mercadopago' ) . - ''; - return $html; - } else { - $this->payment->log->write_log( __FUNCTION__, 'unable to build Checkout Pro URL.' ); - $html = '

' . - __( 'There was an error processing your payment. Please try again or contact us for Assistance.', 'woocommerce-mercadopago' ) . - '

' . - '' . - __( 'Click to try again', 'woocommerce-mercadopago' ) . - ' + $html .= '' . + __( 'Pay with Mercado Pago', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + ' ' . + __( 'Cancel & Clear Cart', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + ''; + return $html; + } else { + $this->payment->log->write_log( __FUNCTION__, 'unable to build Checkout Pro URL.' ); + $html = '

' . + __( 'There was an error processing your payment. Please try again or contact us for Assistance.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + '

' . + '' . + __( 'Click to try again', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ) . + ' '; - return $html; - } - } - - /** - * Add Checkout Scripts - */ - public function add_checkout_scripts_basic() { - if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - - wp_enqueue_script( - 'woocommerce-mercadopago-narciso-scripts', - plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), - array( 'jquery' ), - WC_WooMercadoPago_Constants::VERSION, - true - ); - } - } - - /** - * Scripts to basic - */ - public function add_mp_settings_script_basic() { - parent::add_mp_settings_script(); - } - - /** - * Update settings script basic - * - * @param string $order_id Order Id. - */ - public function update_mp_settings_script_basic( $order_id ) { - parent::update_mp_settings_script( $order_id ); - - $payments_id = []; - $collection_id = sanitize_text_field($_GET['collection_id'] ?? ''); // phpcs:ignore - - if ( ! empty( $collection_id ) ) { - $collection_id = explode( ',', $collection_id ); - foreach ( $collection_id as $payment_id ) { - $payments_id[] = preg_replace( '/\D/', '', $payment_id ); - } - } - - $this->update_mp_order_payments_metadata( $order_id, $payments_id ); - } - - /** - * Discount not apply - */ - public function add_discount() { - // Do nothing. - } - + return $html; + } + } + + /** + * Add Checkout Scripts + */ + public function add_checkout_scripts_basic(): void { + if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + wp_enqueue_script( + 'woocommerce-mercadopago-narciso-scripts', + plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), + array('jquery'), + WC_WooMercadoPago_Constants::VERSION, + true + ); + } + } + + /** + * Scripts to basic + */ + public function add_mp_settings_script_basic(): void { + parent::add_mp_settings_script(); + } + + /** + * Update settings script basic + * + * @param string $order_id Order Id. + */ + public function update_mp_settings_script_basic( $order_id ): void { + parent::update_mp_settings_script( $order_id ); + + $payments_id = array(); + $collection_id = sanitize_text_field($_GET['collection_id'] ?? ''); // phpcs:ignore + + if ( ! empty( $collection_id ) ) { + $collection_id = explode( ',', $collection_id ); + foreach ( $collection_id as $payment_id ) { + $payments_id[] = preg_replace( '/\D/', '', $payment_id ); + } + } + + $this->update_mp_order_payments_metadata( $order_id, $payments_id ); + } + + /** + * Discount not apply + */ + public function add_discount(): void { + // Do nothing. + } } diff --git a/includes/payments/hooks/class-wc-woomercadopago-hook-custom.php b/includes/payments/hooks/class-wc-woomercadopago-hook-custom.php index 7f1c00bb6..636d0bc28 100644 --- a/includes/payments/hooks/class-wc-woomercadopago-hook-custom.php +++ b/includes/payments/hooks/class-wc-woomercadopago-hook-custom.php @@ -1,280 +1,271 @@ payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { - add_action( 'wp_enqueue_scripts', array( $this, 'add_checkout_scripts_custom' ) ); - add_action( 'woocommerce_after_checkout_form', array( $this, 'add_mp_settings_script_custom' ) ); - add_action( 'woocommerce_thankyou_' . $this->payment->id, array( $this, 'update_mp_settings_script_custom' ) ); - add_action( 'woocommerce_order_details_after_order_table', array( $this, 'update_mp_settings_script_custom' ) ); - add_action( 'woocommerce_review_order_before_payment', array( $this, 'add_init_cardform_checkout')); - add_action( 'woocommerce_admin_order_totals_after_total', function( $order_id ) { - $this->payment->display_installment_fee_order( $order_id ); - }); - } - - add_action( - 'woocommerce_receipt_' . $this->payment->id, - function ( $order ) { - $this->render_order_form( $order ); - } - ); - } + if ( ! empty( $this->payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { + add_action( 'wp_enqueue_scripts', array($this, 'add_checkout_scripts_custom') ); + add_action( 'woocommerce_after_checkout_form', array($this, 'add_mp_settings_script_custom') ); + add_action( 'woocommerce_thankyou_' . $this->payment->id, array($this, 'update_mp_settings_script_custom') ); + add_action( 'woocommerce_order_details_after_order_table', array($this, 'update_mp_settings_script_custom') ); + add_action( 'woocommerce_review_order_before_payment', array($this, 'add_init_cardform_checkout')); + add_action( 'woocommerce_admin_order_totals_after_total', function( $order_id ): void { + $this->payment->display_installment_fee_order( $order_id ); + }); + } - /** - * Add Init Cardform on Checkout Page - */ - public function add_init_cardform_checkout() { - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - wp_enqueue_script( - 'woocommerce-mercadopago-checkout-init-cardform', - plugins_url( '../../assets/js/securityFields/checkoutSecurityFields' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - } + add_action( + 'woocommerce_receipt_' . $this->payment->id, + function ( $order ): void { + $this->render_order_form( $order ); + } + ); + } - /** - * Add Discount - */ - public function add_discount() { - // phpcs:ignore WordPress.Security.NonceVerification - if ( ! isset( $_POST['mercadopago_custom'] ) ) { - return; - } - if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || is_cart() ) { - return; - } + /** + * Add Init Cardform on Checkout Page + */ + public function add_init_cardform_checkout(): void { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + wp_enqueue_script( + 'woocommerce-mercadopago-checkout-init-cardform', + plugins_url( '../../assets/js/securityFields/checkoutSecurityFields' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + } - // phpcs:ignore WordPress.Security.NonceVerification - $custom_checkout = map_deep($_POST['mercadopago_custom'], 'sanitize_text_field'); - parent::add_discount_abst( $custom_checkout ); - } + /** + * Add Discount + */ + public function add_discount(): void { + // phpcs:ignore WordPress.Security.NonceVerification + if ( ! isset( $_POST['mercadopago_custom'] ) ) { + return; + } + if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || is_cart() ) { + return; + } - /** - * Add Checkout Scripts - */ - public function add_checkout_scripts_custom() { - if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { - global $woocommerce; + // phpcs:ignore WordPress.Security.NonceVerification + $custom_checkout = map_deep($_POST['mercadopago_custom'], 'sanitize_text_field'); + parent::add_discount_abst( $custom_checkout ); + } - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + /** + * Add Checkout Scripts + */ + public function add_checkout_scripts_custom(): void { + if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { + global $woocommerce; - wp_enqueue_script( - 'woocommerce-mercadopago-sdk', - 'https://sdk.mercadopago.com/js/v2', - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - wp_enqueue_script( - 'woocommerce-mercadopago-checkout', - plugins_url( '../../assets/js/securityFields/securityFields' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); + wp_enqueue_script( + 'woocommerce-mercadopago-sdk', + 'https://sdk.mercadopago.com/js/v2', + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); - wp_enqueue_script( - 'woocommerce-mercadopago-security-session', - plugins_url( '../../assets/js/securityFields/session' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); + wp_enqueue_script( + 'woocommerce-mercadopago-checkout', + plugins_url( '../../assets/js/securityFields/securityFields' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); - wp_enqueue_script( - 'woocommerce-mercadopago-checkout-page', - plugins_url( '../../assets/js/securityFields/pageObjects/checkoutPage' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); + wp_enqueue_script( + 'woocommerce-mercadopago-security-session', + plugins_url( '../../assets/js/securityFields/session' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); - wp_enqueue_script( - 'woocommerce-mercadopago-checkout-elements', - plugins_url( '../../assets/js/securityFields/elements/checkoutElements' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); + wp_enqueue_script( + 'woocommerce-mercadopago-checkout-page', + plugins_url( '../../assets/js/securityFields/pageObjects/checkoutPage' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); - wp_enqueue_script( - 'woocommerce-mercadopago-narciso-scripts', - plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); + wp_enqueue_script( + 'woocommerce-mercadopago-checkout-elements', + plugins_url( '../../assets/js/securityFields/elements/checkoutElements' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); - wp_localize_script( - 'woocommerce-mercadopago-checkout', - 'wc_mercadopago_params', - array( - 'site_id' => strtolower(get_option( '_site_id_v1' )), - 'public_key' => $this->payment->get_public_key(), - 'coupon_mode' => isset( $this->payment->logged_user_email ) ? $this->payment->coupon_mode : 'no', - 'discount_action_url' => $this->payment->discount_action_url, - 'payer_email' => esc_js( $this->payment->logged_user_email ), - 'apply' => __( 'Apply', 'woocommerce-mercadopago' ), - 'remove' => __( 'Remove', 'woocommerce-mercadopago' ), - 'coupon_empty' => __( 'Please, inform your coupon code', 'woocommerce-mercadopago' ), - 'choose' => __( 'To choose', 'woocommerce-mercadopago' ), - 'other_bank' => __( 'Other bank', 'woocommerce-mercadopago' ), - 'discount_info1' => __( 'You will save', 'woocommerce-mercadopago' ), - 'discount_info2' => __( 'with discount of', 'woocommerce-mercadopago' ), - 'discount_info3' => __( 'Total of your purchase:', 'woocommerce-mercadopago' ), - 'discount_info4' => __( 'Total of your purchase with discount:', 'woocommerce-mercadopago' ), - 'discount_info5' => __( '*After payment approval', 'woocommerce-mercadopago' ), - 'discount_info6' => __( 'Terms and conditions of use', 'woocommerce-mercadopago' ), - 'rate_text' => __( 'No fee', 'woocommerce-mercadopago' ), - 'more_installments_text' => __( 'More options', 'woocommerce-mercadopago' ), - 'loading' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'loading.gif', - 'check' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'check.png', - 'error' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'error.png', - 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, - 'currency' => $this->payment->site_data['currency'], - 'intl' => $this->payment->site_data['intl'], - 'placeholders' => array( - 'cardExpirationDate' => __( 'mm/yy', 'woocommerce-mercadopago' ), - 'issuer' => __( 'Issuer', 'woocommerce-mercadopago' ), - 'installments' => __( 'Installments', 'woocommerce-mercadopago' ), - ), - 'cvvHint' => array( - 'back' => __( 'on the back', 'woocommerce-mercadopago' ), - 'front' => __( 'on the front', 'woocommerce-mercadopago' ), - ), - 'cvvText' => __( 'digits', 'woocommerce-mercadopago' ), - 'installmentObsFee' => __( 'No fee', 'woocommerce-mercadopago' ), - 'installmentButton' => __( 'More options', 'woocommerce-mercadopago' ), - 'bankInterestText' => __( 'If interest is applicable, it will be charged by your bank.', 'woocommerce-mercadopago' ), - 'interestText' => __( 'Interest', 'woocommerce-mercadopago' ), - 'input_helper_message' => array( - 'cardNumber' => array( - 'invalid_type' => __( 'Card number is required', 'woocommerce-mercadopago' ), - 'invalid_length' => __( 'Card number invalid', 'woocommerce-mercadopago' ), - ), - 'cardholderName' => array( - '221' => __( 'Holder name is required', 'woocommerce-mercadopago' ), - '316' => __( 'Holder name invalid', 'woocommerce-mercadopago' ), - ), - 'expirationDate' => array( - 'invalid_type' => __( 'Expiration date invalid', 'woocommerce-mercadopago' ), - 'invalid_length' => __( 'Expiration date incomplete', 'woocommerce-mercadopago' ), - 'invalid_value' => __( 'Expiration date invalid', 'woocommerce-mercadopago' ), - ), - 'securityCode' => array( - 'invalid_type' => __( 'Security code is required', 'woocommerce-mercadopago' ), - 'invalid_length' => __( 'Security code incomplete', 'woocommerce-mercadopago' ), - ) - ), - 'theme' => get_stylesheet(), - 'location' => '/checkout', - 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, - 'platform_version' => $woocommerce->version, - ) - ); - } - } + wp_enqueue_script( + 'woocommerce-mercadopago-narciso-scripts', + plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); - /** - * Add custom script - */ - public function add_mp_settings_script_custom() { - parent::add_mp_settings_script(); - } + wp_localize_script( + 'woocommerce-mercadopago-checkout', + 'wc_mercadopago_params', + array( + 'site_id' => strtolower(get_option( '_site_id_v1' )), + 'public_key' => $this->payment->get_public_key(), + 'coupon_mode' => isset( $this->payment->logged_user_email ) ? $this->payment->coupon_mode : 'no', + 'discount_action_url' => $this->payment->discount_action_url, + 'payer_email' => esc_js( $this->payment->logged_user_email ), + 'apply' => __( 'Apply', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'remove' => __( 'Remove', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'coupon_empty' => __( 'Please, inform your coupon code', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'choose' => __( 'To choose', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'other_bank' => __( 'Other bank', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info1' => __( 'You will save', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info2' => __( 'with discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info3' => __( 'Total of your purchase:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info4' => __( 'Total of your purchase with discount:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info5' => __( '*After payment approval', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info6' => __( 'Terms and conditions of use', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'rate_text' => __( 'No fee', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'more_installments_text' => __( 'More options', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'loading' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'loading.gif', + 'check' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'check.png', + 'error' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'error.png', + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'currency' => $this->payment->site_data['currency'], + 'intl' => $this->payment->site_data['intl'], + 'placeholders' => array( + 'cardExpirationDate' => __( 'mm/yy', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'issuer' => __( 'Issuer', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'installments' => __( 'Installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cvvHint' => array( + 'back' => __( 'on the back', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'front' => __( 'on the front', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cvvText' => __( 'digits', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'installmentObsFee' => __( 'No fee', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'installmentButton' => __( 'More options', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'bankInterestText' => __( 'If interest is applicable, it will be charged by your bank.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'interestText' => __( 'Interest', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'input_helper_message' => array( + 'cardNumber' => array( + 'invalid_type' => __( 'Card number is required', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'invalid_length' => __( 'Card number invalid', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'cardholderName' => array( + '221' => __( 'Holder name is required', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + '316' => __( 'Holder name invalid', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'expirationDate' => array( + 'invalid_type' => __( 'Expiration date invalid', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'invalid_length' => __( 'Expiration date incomplete', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'invalid_value' => __( 'Expiration date invalid', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ), + 'securityCode' => array( + 'invalid_type' => __( 'Security code is required', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'invalid_length' => __( 'Security code incomplete', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ) + ), + 'theme' => get_stylesheet(), + 'location' => '/checkout', + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'platform_version' => $woocommerce->version, + ) + ); + } + } - /** - * Add script custom - * - * @param string $order_id Order Id. - */ - public function update_mp_settings_script_custom( $order_id ) { - parent::update_mp_settings_script( $order_id ); + /** + * Add custom script + */ + public function add_mp_settings_script_custom(): void { + parent::add_mp_settings_script(); + } - $order = wc_get_order( $order_id ); - $order->get_meta_data(); - $installments = $order->get_meta('mp_installments'); - $installment_amount = $order->get_meta('mp_transaction_details'); - $transaction_amount = $order->get_meta('mp_transaction_amount'); - $total_paid_amount = $order->get_meta('mp_total_paid_amount'); - $currency_symbol = WC_WooMercadoPago_Configs::get_country_configs(); - $total_diff_cost = (float) $total_paid_amount - (float) $transaction_amount; + /** + * Add script custom + * + * @param string $order_id Order Id. + */ + public function update_mp_settings_script_custom( $order_id ): void { + parent::update_mp_settings_script( $order_id ); - if ( $total_diff_cost > 0 ) { - $parameters_custom = array( - 'title_installment_cost' => __( 'Cost of installments', 'woocommerce-mercadopago' ), - 'title_installment_total' => __( 'Total with installments', 'woocommerce-mercadopago' ), - 'text_installments' => __( 'installments of', 'woocommerce-mercadopago' ), - 'currency' => $currency_symbol[ strtolower(get_option( '_site_id_v1' )) ]['currency_symbol'], - 'total_paid_amount' => number_format( floatval($total_paid_amount), 2, ',', '.' ), - 'transaction_amount' => number_format( floatval($transaction_amount), 2, ',', '.' ), - 'total_diff_cost' => number_format( floatval($total_diff_cost), 2, ',', '.' ), - 'installment_amount' => number_format( floatval($installment_amount), 2, ',', '.' ), - 'installments' => number_format( floatval($installments) ), - ); + $order = wc_get_order( $order_id ); + $order->get_meta_data(); + $installments = $order->get_meta('mp_installments'); + $installment_amount = $order->get_meta('mp_transaction_details'); + $transaction_amount = $order->get_meta('mp_transaction_amount'); + $total_paid_amount = $order->get_meta('mp_total_paid_amount'); + $currency_symbol = WC_WooMercadoPago_Configs::get_country_configs(); + $total_diff_cost = (float) $total_paid_amount - (float) $transaction_amount; - wc_get_template( - 'order-received/show-custom.php', - $parameters_custom, - 'woo/mercado/pago/module/', - WC_WooMercadoPago_Module::get_templates_path() - ); - } + if ( $total_diff_cost > 0 ) { + $parameters_custom = array( + 'title_installment_cost' => __( 'Cost of installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_installment_total' => __( 'Total with installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'text_installments' => __( 'installments of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'currency' => $currency_symbol[ strtolower(get_option( '_site_id_v1' )) ]['currency_symbol'], + 'total_paid_amount' => number_format( (float) $total_paid_amount, 2, ',', '.' ), + 'transaction_amount' => number_format( (float) $transaction_amount, 2, ',', '.' ), + 'total_diff_cost' => number_format( (float) $total_diff_cost, 2, ',', '.' ), + 'installment_amount' => number_format( (float) $installment_amount, 2, ',', '.' ), + 'installments' => number_format( (float) $installments ), + ); - } + wc_get_template( + 'order-received/show-custom.php', + $parameters_custom, + 'woo/mercado/pago/module/', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + } - /** - * Render wallet button page - * - * @param $order_id - */ - public function render_order_form( $order_id ) { - $isWallet = get_query_var('wallet_button', false); + /** + * Render wallet button page + * + * @param $order_id + */ + public function render_order_form( $order_id ): void { + $isWallet = get_query_var('wallet_button', false); - if ( $isWallet ) { - /** - * WooCommerce Order - * - * @var WC_Order $order - */ - $order = wc_get_order( $order_id ); - $preference = $this->payment->create_preference_wallet_button( $order ); + if ( $isWallet ) { + /** + * WooCommerce Order + * + * @var WC_Order $order + */ + $order = wc_get_order( $order_id ); + $preference = $this->payment->create_preference_wallet_button( $order ); - wc_get_template( - 'receipt/custom-checkout.php', - array( - 'preference_id' => $preference['id'], - 'cancel_url' => $order->get_cancel_order_url(), - 'public_key' => $this->payment->get_public_key(), - ), - 'woo/mercado/pago/module/', - WC_WooMercadoPago_Module::get_templates_path() - ); - } - } + wc_get_template( + 'receipt/custom-checkout.php', + array( + 'preference_id' => $preference['id'], + 'cancel_url' => $order->get_cancel_order_url(), + 'public_key' => $this->payment->get_public_key(), + ), + 'woo/mercado/pago/module/', + WC_WooMercadoPago_Module::get_templates_path() + ); + } + } } diff --git a/includes/payments/hooks/class-wc-woomercadopago-hook-pix.php b/includes/payments/hooks/class-wc-woomercadopago-hook-pix.php index 3c3beaa49..8578fc4ea 100644 --- a/includes/payments/hooks/class-wc-woomercadopago-hook-pix.php +++ b/includes/payments/hooks/class-wc-woomercadopago-hook-pix.php @@ -1,162 +1,156 @@ payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { - add_action( 'wp_enqueue_scripts', array( $this, 'add_checkout_scripts_pix' ) ); - add_action( 'woocommerce_after_checkout_form', array( $this, 'add_mp_settings_script_pix' ) ); - add_action( 'woocommerce_thankyou_' . $this->payment->id, array( $this, 'update_mp_settings_script_pix' ) ); - } - } - - /** - * Add Discount - */ - public function add_discount() { - // @codingStandardsIgnoreLine - if ( ! isset( $_POST['mercadopago_pix'] ) ) { - return; - } - - if ( is_admin() && ! defined( 'DOING_AJAX' ) || is_cart() ) { - return; - } - - // phpcs:ignore WordPress.Security.NonceVerification - $pix_checkout = map_deep( $_POST['mercadopago_pix'], 'sanitize_text_field' ); - parent::add_discount_abst( $pix_checkout ); - } - - /** - * Add Checkout Scripts - */ - public function add_checkout_scripts_pix() { - if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - - wp_enqueue_script( - 'woocommerce-mercadopago-narciso-scripts', - plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), - array( 'jquery' ), - WC_WooMercadoPago_Constants::VERSION, - true - ); - - wp_localize_script( - 'woocommerce-mercadopago-pix-checkout', - 'wc_mercadopago_pix_params', - array( - 'site_id' => strtolower(get_option( '_site_id_v1' )), - 'discount_action_url' => $this->payment->discount_action_url, - 'payer_email' => esc_js( $this->payment->logged_user_email ), - 'apply' => __( 'Apply', 'woocommerce-mercadopago' ), - 'remove' => __( 'Remove', 'woocommerce-mercadopago' ), - 'coupon_empty' => __( 'Please, inform your coupon code', 'woocommerce-mercadopago' ), - 'choose' => __( 'To choose', 'woocommerce-mercadopago' ), - 'other_bank' => __( 'Other bank', 'woocommerce-mercadopago' ), - 'discount_info1' => __( 'You will save', 'woocommerce-mercadopago' ), - 'discount_info2' => __( 'with discount of', 'woocommerce-mercadopago' ), - 'discount_info3' => __( 'Total of your purchase:', 'woocommerce-mercadopago' ), - 'discount_info4' => __( 'Total of your purchase with discount:', 'woocommerce-mercadopago' ), - 'discount_info5' => __( '*After payment approval', 'woocommerce-mercadopago' ), - 'discount_info6' => __( 'Terms and conditions of use', 'woocommerce-mercadopago' ), - 'loading' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'loading.gif', - 'check' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'check.png', - 'error' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'error.png', - )); - } - } - - /** - * MP Settings pix - */ - public function add_mp_settings_script_pix() { - parent::add_mp_settings_script(); - } - - /** - * Update settings script pix - * - * @param string $order_id Order Id. - */ - public function update_mp_settings_script_pix( $order_id ) { - parent::update_mp_settings_script( $order_id ); - - $order = wc_get_order( $order_id ); - $qr_base64 = $order->get_meta( 'mp_pix_qr_base64' ); - $qr_code = $order->get_meta( 'mp_pix_qr_code' ); - $transaction_amount = $order->get_meta( 'mp_transaction_amount' ); - $currency_symbol = WC_WooMercadoPago_Configs::get_country_configs(); - - if ( empty( $qr_base64 ) && empty( $qr_code ) ) { - return; - } - - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - - // add js - wp_enqueue_script( - 'woocommerce-mercadopago-pix-order-recived', - plugins_url( '../../assets/js/pix_mercadopago_order_received' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - false - ); - - // add css - wp_enqueue_style( - 'woocommerce-mercadopago-pix-checkout', - plugins_url( '../../assets/css/basic_checkout_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - - $parameters = array( - 'img_pix' => plugins_url( '../../assets/images/img-pix.png', plugin_dir_path( __FILE__ ) ), - 'amount' => number_format( $transaction_amount, 2, ',', '.' ), - 'qr_base64' => $qr_base64, - 'title_purchase_pix' => __( 'Now you just need to pay with Pix to finalize your purchase', 'woocommerce-mercadopago' ), - 'title_how_to_pay' => __( 'How to pay with Pix:', 'woocommerce-mercadopago' ), - 'step_one' => __( 'Go to your bank\'s app or website', 'woocommerce-mercadopago' ), - 'step_two' => __( 'Search for the option to pay with Pix', 'woocommerce-mercadopago' ), - 'step_three' => __( 'Scan the QR code or Pix code', 'woocommerce-mercadopago' ), - 'step_four' => __( 'Done! You will see the payment confirmation', 'woocommerce-mercadopago' ), - 'text_amount' => __( 'Value: ', 'woocommerce-mercadopago' ), - 'currency' => $currency_symbol[ strtolower(get_option( '_site_id_v1' )) ]['currency_symbol'], - 'text_scan_qr' => __( 'Scan the QR code:', 'woocommerce-mercadopago' ), - 'text_time_qr_one' => __( 'Code valid for ', 'woocommerce-mercadopago' ), - 'qr_date_expiration' => __($this->payment->get_option_mp( 'checkout_pix_date_expiration', '30 minutes' ), 'woocommerce-mercadopago' ), - 'text_description_qr' => __( 'If you prefer, you can pay by copying and pasting the following code', 'woocommerce-mercadopago' ), - 'qr_code' => $qr_code, - 'text_button' => __( 'Copy code', 'woocommerce-mercadopago' ), - ); - - wc_get_template( - 'order-received/show-pix.php', - $parameters, - 'woo/mercado/pago/module/', - WC_WooMercadoPago_Module::get_templates_path() - ); - } + /** + * Load Hooks + */ + public function load_hooks(): void { + parent::load_hooks(); + + if ( ! empty( $this->payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { + add_action( 'wp_enqueue_scripts', array($this, 'add_checkout_scripts_pix') ); + add_action( 'woocommerce_after_checkout_form', array($this, 'add_mp_settings_script_pix') ); + add_action( 'woocommerce_thankyou_' . $this->payment->id, array($this, 'update_mp_settings_script_pix') ); + } + } + + /** + * Add Discount + */ + public function add_discount(): void { + // @codingStandardsIgnoreLine + if ( ! isset( $_POST['mercadopago_pix'] ) ) { + return; + } + + if ( is_admin() && ! defined( 'DOING_AJAX' ) || is_cart() ) { + return; + } + + // phpcs:ignore WordPress.Security.NonceVerification + $pix_checkout = map_deep( $_POST['mercadopago_pix'], 'sanitize_text_field' ); + parent::add_discount_abst( $pix_checkout ); + } + + /** + * Add Checkout Scripts + */ + public function add_checkout_scripts_pix(): void { + if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + wp_enqueue_script( + 'woocommerce-mercadopago-narciso-scripts', + plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), + array('jquery'), + WC_WooMercadoPago_Constants::VERSION, + true + ); + + wp_localize_script( + 'woocommerce-mercadopago-pix-checkout', + 'wc_mercadopago_pix_params', + array( + 'site_id' => strtolower(get_option( '_site_id_v1' )), + 'discount_action_url' => $this->payment->discount_action_url, + 'payer_email' => esc_js( $this->payment->logged_user_email ), + 'apply' => __( 'Apply', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'remove' => __( 'Remove', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'coupon_empty' => __( 'Please, inform your coupon code', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'choose' => __( 'To choose', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'other_bank' => __( 'Other bank', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info1' => __( 'You will save', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info2' => __( 'with discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info3' => __( 'Total of your purchase:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info4' => __( 'Total of your purchase with discount:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info5' => __( '*After payment approval', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info6' => __( 'Terms and conditions of use', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'loading' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'loading.gif', + 'check' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'check.png', + 'error' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'error.png', + ) + ); + } + } + + /** + * MP Settings pix + */ + public function add_mp_settings_script_pix(): void { + parent::add_mp_settings_script(); + } + + /** + * Update settings script pix + * + * @param string $order_id Order Id. + */ + public function update_mp_settings_script_pix( $order_id ): void { + parent::update_mp_settings_script( $order_id ); + + $order = wc_get_order( $order_id ); + $qr_base64 = $order->get_meta( 'mp_pix_qr_base64' ); + $qr_code = $order->get_meta( 'mp_pix_qr_code' ); + $transaction_amount = $order->get_meta( 'mp_transaction_amount' ); + $currency_symbol = WC_WooMercadoPago_Configs::get_country_configs(); + + if ( empty( $qr_base64 ) && empty( $qr_code ) ) { + return; + } + + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + + // add js + wp_enqueue_script( + 'woocommerce-mercadopago-pix-order-recived', + plugins_url( '../../assets/js/pix_mercadopago_order_received' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + false + ); + + // add css + wp_enqueue_style( + 'woocommerce-mercadopago-pix-checkout', + plugins_url( '../../assets/css/basic_checkout_mercadopago' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + + $parameters = array( + 'img_pix' => plugins_url( '../../assets/images/img-pix.png', plugin_dir_path( __FILE__ ) ), + 'amount' => number_format( $transaction_amount, 2, ',', '.' ), + 'qr_base64' => $qr_base64, + 'title_purchase_pix' => __( 'Now you just need to pay with Pix to finalize your purchase', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'title_how_to_pay' => __( 'How to pay with Pix:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_one' => __( 'Go to your bank\'s app or website', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_two' => __( 'Search for the option to pay with Pix', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_three' => __( 'Scan the QR code or Pix code', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'step_four' => __( 'Done! You will see the payment confirmation', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'text_amount' => __( 'Value: ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'currency' => $currency_symbol[ strtolower(get_option( '_site_id_v1' )) ]['currency_symbol'], + 'text_scan_qr' => __( 'Scan the QR code:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'text_time_qr_one' => __( 'Code valid for ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'qr_date_expiration' => __($this->payment->get_option_mp( 'checkout_pix_date_expiration', '30 minutes' ), LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'text_description_qr' => __( 'If you prefer, you can pay by copying and pasting the following code', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'qr_code' => $qr_code, + 'text_button' => __( 'Copy code', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + ); + + wc_get_template( + 'order-received/show-pix.php', + $parameters, + 'woo/mercado/pago/module/', + WC_WooMercadoPago_Module::get_templates_path() + ); + } } diff --git a/includes/payments/hooks/class-wc-woomercadopago-hook-ticket.php b/includes/payments/hooks/class-wc-woomercadopago-hook-ticket.php index d26535cc0..366792b7c 100644 --- a/includes/payments/hooks/class-wc-woomercadopago-hook-ticket.php +++ b/includes/payments/hooks/class-wc-woomercadopago-hook-ticket.php @@ -1,129 +1,120 @@ payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { - add_action( 'wp_enqueue_scripts', array( $this, 'add_checkout_scripts_ticket' ) ); - add_action( 'woocommerce_after_checkout_form', array( $this, 'add_mp_settings_script_ticket' ) ); - add_action( 'woocommerce_thankyou_' . $this->payment->id, array( $this, 'update_mp_settings_script_ticket' ) ); - } - } - - /** - * Add Discount - */ - public function add_discount() { + if ( ! empty( $this->payment->settings['enabled'] ) && 'yes' === $this->payment->settings['enabled'] ) { + add_action( 'wp_enqueue_scripts', array($this, 'add_checkout_scripts_ticket') ); + add_action( 'woocommerce_after_checkout_form', array($this, 'add_mp_settings_script_ticket') ); + add_action( 'woocommerce_thankyou_' . $this->payment->id, array($this, 'update_mp_settings_script_ticket') ); + } + } - // phpcs:ignore WordPress.Security.NonceVerification - if ( ! isset( $_POST['mercadopago_ticket'] ) ) { - return; - } - if ( is_admin() && ! defined( 'DOING_AJAX' ) || is_cart() ) { - return; - } - // phpcs:ignore WordPress.Security.NonceVerification - $ticket_checkout = map_deep($_POST['mercadopago_ticket'], 'sanitize_text_field'); - parent::add_discount_abst( $ticket_checkout ); - } + /** + * Add Discount + */ + public function add_discount(): void { + // phpcs:ignore WordPress.Security.NonceVerification + if ( ! isset( $_POST['mercadopago_ticket'] ) ) { + return; + } + if ( is_admin() && ! defined( 'DOING_AJAX' ) || is_cart() ) { + return; + } + // phpcs:ignore WordPress.Security.NonceVerification + $ticket_checkout = map_deep($_POST['mercadopago_ticket'], 'sanitize_text_field'); + parent::add_discount_abst( $ticket_checkout ); + } - /** - * Add Checkout Scripts - */ - public function add_checkout_scripts_ticket() { - if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { - $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + /** + * Add Checkout Scripts + */ + public function add_checkout_scripts_ticket(): void { + if ( is_checkout() && $this->payment->is_available() && ! get_query_var( 'order-received' ) ) { + $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - wp_enqueue_script( - 'woocommerce-mercadopago-ticket-checkout', - plugins_url( '../../assets/js/ticket' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array( 'jquery' ), - WC_WooMercadoPago_Constants::VERSION, - true - ); + wp_enqueue_script( + 'woocommerce-mercadopago-ticket-checkout', + plugins_url( '../../assets/js/ticket' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array('jquery'), + WC_WooMercadoPago_Constants::VERSION, + true + ); - wp_enqueue_script( - 'woocommerce-mercadopago-narciso-scripts', - plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), - array( 'jquery' ), - WC_WooMercadoPago_Constants::VERSION, - true - ); + wp_enqueue_script( + 'woocommerce-mercadopago-narciso-scripts', + plugins_url( '../../assets/js/mp-plugins-components.js', plugin_dir_path( __FILE__ ) ), + array('jquery'), + WC_WooMercadoPago_Constants::VERSION, + true + ); - wp_localize_script( - 'woocommerce-mercadopago-ticket-checkout', - 'wc_mercadopago_ticket_params', - array( - 'site_id' => strtolower(get_option( '_site_id_v1' )), - 'coupon_mode' => isset( $this->payment->logged_user_email ) ? $this->payment->coupon_mode : 'no', - 'discount_action_url' => $this->payment->discount_action_url, - 'payer_email' => esc_js( $this->payment->logged_user_email ), - 'apply' => __( 'Apply', 'woocommerce-mercadopago' ), - 'remove' => __( 'Remove', 'woocommerce-mercadopago' ), - 'coupon_empty' => __( 'Please, inform your coupon code', 'woocommerce-mercadopago' ), - 'choose' => __( 'To choose', 'woocommerce-mercadopago' ), - 'other_bank' => __( 'Other bank', 'woocommerce-mercadopago' ), - 'discount_info1' => __( 'You will save', 'woocommerce-mercadopago' ), - 'discount_info2' => __( 'with discount of', 'woocommerce-mercadopago' ), - 'discount_info3' => __( 'Total of your purchase:', 'woocommerce-mercadopago' ), - 'discount_info4' => __( 'Total of your purchase with discount:', 'woocommerce-mercadopago' ), - 'discount_info5' => __( '*After payment approval', 'woocommerce-mercadopago' ), - 'discount_info6' => __( 'Terms and conditions of use', 'woocommerce-mercadopago' ), - 'loading' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'loading.gif', - 'check' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'check.png', - 'error' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'error.png', - ) - ); - } - } + wp_localize_script( + 'woocommerce-mercadopago-ticket-checkout', + 'wc_mercadopago_ticket_params', + array( + 'site_id' => strtolower(get_option( '_site_id_v1' )), + 'coupon_mode' => isset( $this->payment->logged_user_email ) ? $this->payment->coupon_mode : 'no', + 'discount_action_url' => $this->payment->discount_action_url, + 'payer_email' => esc_js( $this->payment->logged_user_email ), + 'apply' => __( 'Apply', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'remove' => __( 'Remove', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'coupon_empty' => __( 'Please, inform your coupon code', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'choose' => __( 'To choose', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'other_bank' => __( 'Other bank', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info1' => __( 'You will save', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info2' => __( 'with discount of', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info3' => __( 'Total of your purchase:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info4' => __( 'Total of your purchase with discount:', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info5' => __( '*After payment approval', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'discount_info6' => __( 'Terms and conditions of use', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'loading' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'loading.gif', + 'check' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'check.png', + 'error' => plugins_url( '../../assets/images/', plugin_dir_path( __FILE__ ) ) . 'error.png', + ) + ); + } + } - /** - * MP Settings Ticket - */ - public function add_mp_settings_script_ticket() { - parent::add_mp_settings_script(); - } + /** + * MP Settings Ticket + */ + public function add_mp_settings_script_ticket(): void { + parent::add_mp_settings_script(); + } - /** - * Update settings script ticket - * - * @param string $order_id Order Id. - */ - public function update_mp_settings_script_ticket( $order_id ) { - parent::update_mp_settings_script( $order_id ); - $order = wc_get_order( $order_id ); - $transaction_details = $order->get_meta( '_transaction_details_ticket' ); + /** + * Update settings script ticket + * + * @param string $order_id Order Id. + */ + public function update_mp_settings_script_ticket( $order_id ): void { + parent::update_mp_settings_script( $order_id ); + $order = wc_get_order( $order_id ); + $transaction_details = $order->get_meta( '_transaction_details_ticket' ); - if ( empty( $transaction_details ) ) { - return; - } + if ( empty( $transaction_details ) ) { + return; + } - wc_get_template( - 'order-received/show-ticket.php', - array( 'transaction_details' => $transaction_details ), - 'woo/mercado/pago/module/', - WC_WooMercadoPago_Module::get_templates_path() - ); - } + wc_get_template( + 'order-received/show-ticket.php', + array('transaction_details' => $transaction_details), + 'woo/mercado/pago/module/', + WC_WooMercadoPago_Module::get_templates_path() + ); + } } diff --git a/includes/payments/hooks/index.php b/includes/payments/hooks/index.php index 258f3fae9..891711d6d 100644 --- a/includes/payments/hooks/index.php +++ b/includes/payments/hooks/index.php @@ -1,12 +1,5 @@ '/v1/payments/' . $payment_id[0], - 'headers' => array( - 'Authorization' => 'Bearer ' . $access_token, - ) - ); - - return MP_Rest_Client::get($request); - } - - /** - * Get qr code image - */ - public function get_image_qr() { - $payment_data = self::get_payment_data(); - - $pix = $payment_data['response']['point_of_interaction']['transaction_data']; - - if ( is_null($pix) || empty($pix) || ! array_key_exists('qr_code_base64', $pix ) ) { - self::get_error_image(); - } - - $pix_base64 = $payment_data['response']['point_of_interaction']['transaction_data']['qr_code_base64']; - - header('Content-type: image/png'); - - // @codingStandardsIgnoreLine - $pix_qr_image = base64_decode($pix_base64); - $pix_qr_image = imagecreatefromstring($pix_qr_image); - - $pix_qr_image = imagescale($pix_qr_image, 447); - - imagepng($pix_qr_image); - - imagedestroy($pix_qr_image); - - exit(); - } - - - /** - * Get Access Data - * - * @return array - */ - public static function get_access_data() { - - $id_payment = sanitize_key( isset($_GET['id']) ? $_GET['id'] : null); // phpcs:disable WordPress.Security.NonceVerification - - if ( is_null($id_payment) || empty($id_payment) || ! is_numeric($id_payment) ) { - self::get_error_image(); - exit(); - } - - $order = wc_get_order($id_payment); - - if ( is_null($order) || empty($order) ) { - self::get_error_image(); - exit(); - } - - $payment_method = $order->get_payment_method(); - $is_mercadopago_payment_method = in_array($payment_method, WC_WooMercadoPago_Constants::GATEWAYS_IDS, true); - $payment_ids = explode(',', $order->get_meta('_Mercado_Pago_Payment_IDs')); - - if ( ! $is_mercadopago_payment_method || empty($payment_ids) ) { - return; - } - - $is_production_mode = $order->get_meta('is_production_mode'); - $access_token = 'no' === $is_production_mode || ! $is_production_mode - ? get_option('_mp_access_token_test') - : get_option('_mp_access_token_prod'); - - $data = array( - 'payment_id' => $payment_ids, - 'access_token' => $access_token, - ); - - return $data; - } - - /** - * Init Mercado Pago Image Generator Class - * - * @return WC_WooMercadoPago_Image_Generator|null - * Singleton - */ - public static function init_image_generator_class() { - if ( null === self::$instance ) { - self::$instance = new self(); - } - - return self::$instance; - } - - /** - * Get Error Image - */ - public static function get_error_image() { - header('Content-type: image/png'); - $png_image = dirname(__FILE__) . '/../../assets/images/pix_has_expired.png'; - $png_image = imagecreatefrompng($png_image); - $png_image = imagescale($png_image, 447); - imagepng($png_image); - imagedestroy($png_image); - exit(); - } + /** + * Static Instance + */ + public static $instance = null; + + /** + * WC_WooMercadoPago_Image_Generator constructor. + */ + public function __construct() { + add_action('woocommerce_api_wc_mp_pix_image', array($this, 'get_image_qr')); + } + + /** + * Get Pix Payment Data + * + * @return array + */ + public static function get_payment_data() { + $data = self::get_access_data(); + $payment_id = $data['payment_id']; + $access_token = $data['access_token']; + $request = array( + 'uri' => '/v1/payments/' . $payment_id[0], + 'headers' => array( + 'Authorization' => 'Bearer ' . $access_token, + ) + ); + + return MP_Rest_Client::get($request); + } + + /** + * Get qr code image + */ + public function get_image_qr(): void { + $payment_data = self::get_payment_data(); + + $pix = $payment_data['response']['point_of_interaction']['transaction_data']; + + if ( is_null($pix) || empty($pix) || ! array_key_exists('qr_code_base64', $pix ) ) { + self::get_error_image(); + } + + $pix_base64 = $payment_data['response']['point_of_interaction']['transaction_data']['qr_code_base64']; + + header('Content-type: image/png'); + + // @codingStandardsIgnoreLine + $pix_qr_image = base64_decode($pix_base64, true); + $pix_qr_image = imagecreatefromstring($pix_qr_image); + + $pix_qr_image = imagescale($pix_qr_image, 447); + + imagepng($pix_qr_image); + + imagedestroy($pix_qr_image); + + exit(); + } + + /** + * Get Access Data + * + * @return array + */ + public static function get_access_data() { + $id_payment = sanitize_key( isset($_GET['id']) ? $_GET['id'] : null); // phpcs:disable WordPress.Security.NonceVerification + + if ( is_null($id_payment) || empty($id_payment) || ! is_numeric($id_payment) ) { + self::get_error_image(); + exit(); + } + + $order = wc_get_order($id_payment); + + if ( is_null($order) || empty($order) ) { + self::get_error_image(); + exit(); + } + + $payment_method = $order->get_payment_method(); + $is_mercadopago_payment_method = in_array($payment_method, WC_WooMercadoPago_Constants::GATEWAYS_IDS, true); + $payment_ids = explode(',', $order->get_meta('_Mercado_Pago_Payment_IDs')); + + if ( ! $is_mercadopago_payment_method || empty($payment_ids) ) { + return; + } + + $is_production_mode = $order->get_meta('is_production_mode'); + $access_token = 'no' === $is_production_mode || ! $is_production_mode + ? get_option('_mp_access_token_test') + : get_option('_mp_access_token_prod'); + + $data = array( + 'payment_id' => $payment_ids, + 'access_token' => $access_token, + ); + + return $data; + } + + /** + * Init Mercado Pago Image Generator Class + * + * @return WC_WooMercadoPago_Image_Generator|null + * Singleton + */ + public static function init_image_generator_class() { + if ( null === self::$instance ) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * Get Error Image + */ + public static function get_error_image(): void { + header('Content-type: image/png'); + $png_image = __DIR__ . '/../../assets/images/pix_has_expired.png'; + $png_image = imagecreatefrompng($png_image); + $png_image = imagescale($png_image, 447); + imagepng($png_image); + imagedestroy($png_image); + exit(); + } } diff --git a/includes/products/hooks/class-wc-woomercadopago-products-hook-credits.php b/includes/products/hooks/class-wc-woomercadopago-products-hook-credits.php index 97e60e200..3e2987897 100755 --- a/includes/products/hooks/class-wc-woomercadopago-products-hook-credits.php +++ b/includes/products/hooks/class-wc-woomercadopago-products-hook-credits.php @@ -1,162 +1,154 @@ credits_helper = new WC_WooMercadoPago_Helper_Credits(); - $this->mp_options = WC_WooMercadoPago_Options::get_instance(); - - if ( ! is_admin() ) { - $credits_configs = get_option( 'woocommerce_woo-mercado-pago-credits_settings', '' ); - $this->credits_enabled = 'no'; - $this->site_id = strtolower(get_option( '_site_id_v1' )); - $is_credits = $this->credits_helper->is_credits(); - - if ( isset( $credits_configs['enabled'] ) && isset( $credits_configs['credits_banner'] ) ) { - $this->credits_enabled = $credits_configs['enabled']; - $this->credits_banner = $credits_configs['credits_banner']; - } - - if ( 'yes' === $this->credits_enabled && 'yes' === $this->credits_banner ) { - if ( $is_credits ) { - $this->load_hooks(); - } - } - } - } - - /** - * Get sufix to static files - */ - private function get_suffix() { - return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; - } - - /** - * Load Hooks - */ - public function load_hooks() { - add_action( 'woocommerce_before_add_to_cart_form', array( $this, 'before_add_to_cart_form' ) ); - } - - public function before_add_to_cart_form() { - $site = strtolower($this->mp_options->get_site_id()); - $links = WC_WooMercadoPago_Helper_Links::get_mc_blog_link($site); - global $woocommerce; - $suffix = $this->get_suffix(); - - wp_enqueue_style( - 'mp-credits-modal-style', - plugins_url( '../../assets/css/credits/modal' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION - ); - - wc_get_template( - 'credits/mp-credits-modal.php', - array ( - 'banner_title' => __( 'Pay in', 'woocommerce-mercadopago' ), - 'banner_title_bold' => __('installments', 'woocommerce-mercadopago' ), - 'banner_title_end' => __('with Mercado Pago', 'woocommerce-mercadopago' ), - 'banner_link' => __( 'Read more', 'woocommerce-mercadopago' ), - 'modal_title' => __( 'Buy now and pay in installments with no card later!', 'woocommerce-mercadopago' ), - 'modal_subtitle' => __( '100% online,', 'woocommerce-mercadopago' ), - 'modal_subtitle_2' => __( 'without paperwork or monthly fees', 'woocommerce-mercadopago' ), - 'modal_step_1' => __( 'When paying, choose', 'woocommerce-mercadopago' ), - 'modal_step_1_end' => __('. Login to your account or create one in a few steps.', 'woocommerce-mercadopago'), - 'modal_step_2' => __( 'Search for', 'woocommerce-mercadopago' ), - 'modal_step_2_end' => __('among the options, select it and choose in how many installments you would like to pay.', 'woocommerce-mercadopago'), - 'modal_step_3' => __( 'Pay your installments monthly as you wish, in the Mercado Pago app.', 'woocommerce-mercadopago' ), - 'modal_footer' => __( 'Questions? ', 'woocommerce-mercadopago' ), - 'modal_footer_help_link' => $links['FAQ_link'], - 'modal_footer_link' => __('Check our FAQ', 'woocommerce-mercadopago'), - 'modal_footer_end' => __('. Credit subject to approval.', 'woocommerce-mercadopago') - ), - '', - WC_WooMercadoPago_Module::get_templates_path() - ); - - wp_enqueue_script( - 'mp-credits-modal-js', - plugins_url( '../../assets/js/credits/script' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - false - ); - - wp_enqueue_script( - 'mercadopago_melidata', - plugins_url( '../../assets/js/melidata/melidata-client' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), - array(), - WC_WooMercadoPago_Constants::VERSION, - true - ); - - wp_localize_script( - 'mercadopago_melidata', - 'wc_melidata_params', - array( - 'type' => 'buyer', - 'site_id' => $this->site_id ? strtoupper( $this->site_id ) : 'MLA', - 'location' => '/products', - 'payment_method' => null, - 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, - 'platform_version' => $woocommerce->version, - ) - ); - } + /** + * Site Id + * + * @var string + */ + public $site_id; + + /** + * Checkout Credits Enabled + * + * @var boolean + */ + public $credits_enabled; + + /** + * Credits Banner Enabled + * + * @var boolean + */ + public $credits_banner; + + /** + * Credits Helper Class + * + * @var WC_WooMercadoPago_Helper_Credits + */ + public $credits_helper; + + /** + * Options + * + * @var WC_WooMercadoPago_Options + */ + public $mp_options; + + /** + * WC_WooMercadoPago_Products_Hook_Credits constructor. + * + */ + public function __construct() { + $this->credits_helper = new WC_WooMercadoPago_Helper_Credits(); + $this->mp_options = WC_WooMercadoPago_Options::get_instance(); + + if ( ! is_admin() ) { + $credits_configs = get_option( 'woocommerce_woo-mercado-pago-credits_settings', '' ); + $this->credits_enabled = 'no'; + $this->site_id = strtolower(get_option( '_site_id_v1' )); + $is_credits = $this->credits_helper->is_credits(); + + if ( isset( $credits_configs['enabled'] ) && isset( $credits_configs['credits_banner'] ) ) { + $this->credits_enabled = $credits_configs['enabled']; + $this->credits_banner = $credits_configs['credits_banner']; + } + + if ( 'yes' === $this->credits_enabled && 'yes' === $this->credits_banner ) { + if ( $is_credits ) { + $this->load_hooks(); + } + } + } + } + + /** + * Get sufix to static files + */ + private function get_suffix() { + return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; + } + + /** + * Load Hooks + */ + public function load_hooks(): void { + add_action( 'woocommerce_before_add_to_cart_form', array($this, 'before_add_to_cart_form') ); + } + + public function before_add_to_cart_form(): void { + $site = strtolower($this->mp_options->get_site_id()); + $links = WC_WooMercadoPago_Helper_Links::get_mc_blog_link($site); + global $woocommerce; + $suffix = $this->get_suffix(); + + wp_enqueue_style( + 'mp-credits-modal-style', + plugins_url( '../../assets/css/credits/modal' . $suffix . '.css', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION + ); + + wc_get_template( + 'credits/mp-credits-modal.php', + array ( + 'banner_title' => __( 'Pay in', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'banner_title_bold' => __('installments', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'banner_title_end' => __('with Mercado Pago', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'banner_link' => __( 'Read more', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'modal_title' => __( 'Buy now and pay in installments with no card later!', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'modal_subtitle' => __( '100% online,', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'modal_subtitle_2' => __( 'without paperwork or monthly fees', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'modal_step_1' => __( 'When paying, choose', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'modal_step_1_end' => __('. Login to your account or create one in a few steps.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'modal_step_2' => __( 'Search for', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'modal_step_2_end' => __('among the options, select it and choose in how many installments you would like to pay.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'modal_step_3' => __( 'Pay your installments monthly as you wish, in the Mercado Pago app.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'modal_footer' => __( 'Questions? ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN ), + 'modal_footer_help_link' => $links['FAQ_link'], + 'modal_footer_link' => __('Check our FAQ', LKN_WC_MERCADOPAGO_TEXT_DOMAIN), + 'modal_footer_end' => __('. Credit subject to approval.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN) + ), + '', + WC_WooMercadoPago_Module::get_templates_path() + ); + + wp_enqueue_script( + 'mp-credits-modal-js', + plugins_url( '../../assets/js/credits/script' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + false + ); + + wp_enqueue_script( + 'mercadopago_melidata', + plugins_url( '../../assets/js/melidata/melidata-client' . $suffix . '.js', plugin_dir_path( __FILE__ ) ), + array(), + WC_WooMercadoPago_Constants::VERSION, + true + ); + + wp_localize_script( + 'mercadopago_melidata', + 'wc_melidata_params', + array( + 'type' => 'buyer', + 'site_id' => $this->site_id ? strtoupper( $this->site_id ) : 'MLA', + 'location' => '/products', + 'payment_method' => null, + 'plugin_version' => WC_WooMercadoPago_Constants::VERSION, + 'platform_version' => $woocommerce->version, + ) + ); + } } diff --git a/includes/stock/class-wc-woomercadopago-stock-manager.php b/includes/stock/class-wc-woomercadopago-stock-manager.php index 813e1e8eb..47b5f6462 100644 --- a/includes/stock/class-wc-woomercadopago-stock-manager.php +++ b/includes/stock/class-wc-woomercadopago-stock-manager.php @@ -1,86 +1,78 @@ get_payment_method() !== 'woo-mercado-pago-ticket' ) { - return; - } + if ( $order->get_payment_method() !== 'woo-mercado-pago-ticket' ) { + return; + } - $mp_ticket_settings = get_option( 'woocommerce_woo-mercado-pago-ticket_settings' ); - if ( empty( $mp_ticket_settings ) || in_array( 'stock_reduce_mode', $mp_ticket_settings, true ) || 'no' === $mp_ticket_settings['stock_reduce_mode'] ) { - return; - } + $mp_ticket_settings = get_option( 'woocommerce_woo-mercado-pago-ticket_settings' ); + if ( empty( $mp_ticket_settings ) || in_array( 'stock_reduce_mode', $mp_ticket_settings, true ) || 'no' === $mp_ticket_settings['stock_reduce_mode'] ) { + return; + } - foreach ( $order->get_items() as $item ) { - if ( $item['product_id'] > 0 ) { - $_product = wc_get_product( $item['product_id'] ); + foreach ( $order->get_items() as $item ) { + if ( $item['product_id'] > 0 ) { + $_product = wc_get_product( $item['product_id'] ); - if ( $_product && $_product->exists() && $_product->managing_stock() ) { - /** - * Apply filters woocommerce_order_item_quantity. - * - * @since 3.0.1 - */ - $qty = apply_filters( 'woocommerce_order_item_quantity', $item['qty'], $order, $item ); + if ( $_product && $_product->exists() && $_product->managing_stock() ) { + /** + * Apply filters woocommerce_order_item_quantity. + * + * @since 3.0.1 + */ + $qty = apply_filters( 'woocommerce_order_item_quantity', $item['qty'], $order, $item ); - wc_update_product_stock( $_product, $qty, 'increase' ); + wc_update_product_stock( $_product, $qty, 'increase' ); - /** - * Do action woocommerce_auto_stock_restored. - * - * @since 3.0.1 - */ - do_action( 'woocommerce_auto_stock_restored', $_product, $item ); - } - } - } - } + /** + * Do action woocommerce_auto_stock_restored. + * + * @since 3.0.1 + */ + do_action( 'woocommerce_auto_stock_restored', $_product, $item ); + } + } + } + } } new WC_WooMercadoPago_Stock_Manager(); diff --git a/includes/stock/index.php b/includes/stock/index.php index 258f3fae9..891711d6d 100644 --- a/includes/stock/index.php +++ b/includes/stock/index.php @@ -1,12 +1,5 @@ ', src: ['includes/**/*.php', 'templates/**/*.php'] }); diff --git a/package-lock.json b/package-lock.json index 4007ab688..3686c6c92 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,279 +1,355 @@ { "name": "cart-woocommerce", - "version": "6.9.1", - "lockfileVersion": 1, + "version": "6.9.2", + "lockfileVersion": 3, "requires": true, - "dependencies": { - "@jridgewell/gen-mapping": { + "packages": { + "": { + "name": "cart-woocommerce", + "version": "6.9.2", + "devDependencies": { + "husky": "^7.0.0", + "jshint": "^2.13.4", + "minify": "^7.2.2", + "wp-pot": "^1.9.9" + } + }, + "node_modules/@jridgewell/gen-mapping": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz", "integrity": "sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==", "dev": true, - "requires": { + "dependencies": { "@jridgewell/set-array": "^1.0.1", "@jridgewell/sourcemap-codec": "^1.4.10", "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" } }, - "@jridgewell/resolve-uri": { + "node_modules/@jridgewell/resolve-uri": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", - "dev": true + "dev": true, + "engines": { + "node": ">=6.0.0" + } }, - "@jridgewell/set-array": { + "node_modules/@jridgewell/set-array": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", - "dev": true + "dev": true, + "engines": { + "node": ">=6.0.0" + } }, - "@jridgewell/source-map": { + "node_modules/@jridgewell/source-map": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.2.tgz", "integrity": "sha512-m7O9o2uR8k2ObDysZYzdfhb08VuEml5oWGiosa1VdaPZ/A6QyPkAJuwN0Q1lhULOf6B7MtQmHENS743hWtCrgw==", "dev": true, - "requires": { + "dependencies": { "@jridgewell/gen-mapping": "^0.3.0", "@jridgewell/trace-mapping": "^0.3.9" } }, - "@jridgewell/sourcemap-codec": { + "node_modules/@jridgewell/sourcemap-codec": { "version": "1.4.14", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", "dev": true }, - "@jridgewell/trace-mapping": { + "node_modules/@jridgewell/trace-mapping": { "version": "0.3.15", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.15.tgz", "integrity": "sha512-oWZNOULl+UbhsgB51uuZzglikfIKSUBO/M9W2OfEjn7cmqoAiCgmv9lyACTUacZwBz0ITnJ2NqjU8Tx0DHL88g==", "dev": true, - "requires": { + "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, - "acorn": { + "node_modules/acorn": { "version": "8.8.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.0.tgz", "integrity": "sha512-QOxyigPVrpZ2GXT+PFyZTl6TtOFc5egxHIP9IlQ+RbupQuX4RkT/Bee4/kQuC02Xkzg84JcT7oLYtDIQxp+v7w==", - "dev": true + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } }, - "acorn-jsx": { + "node_modules/acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true + "dev": true, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } }, - "balanced-match": { + "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, - "brace-expansion": { + "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, - "requires": { + "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, - "buffer-from": { + "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, - "camel-case": { + "node_modules/camel-case": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/camel-case/-/camel-case-4.1.2.tgz", "integrity": "sha512-gxGWBrTT1JuMx6R+o5PTXMmUnhnVzLQ9SNutD4YqKtI6ap897t3tKECYla6gCWEkplXnlNybEkZg9GEGxKFCgw==", "dev": true, - "requires": { + "dependencies": { "pascal-case": "^3.1.2", "tslib": "^2.0.3" } }, - "clean-css": { + "node_modules/clean-css": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-5.3.1.tgz", "integrity": "sha512-lCr8OHhiWCTw4v8POJovCoh4T7I9U11yVsPjMWWnnMmp9ZowCxyad1Pathle/9HjaDp+fdQKjO9fQydE6RHTZg==", "dev": true, - "requires": { + "dependencies": { "source-map": "~0.6.0" + }, + "engines": { + "node": ">= 10.0" } }, - "cli": { + "node_modules/cli": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cli/-/cli-1.0.1.tgz", "integrity": "sha512-41U72MB56TfUMGndAKK8vJ78eooOD4Z5NOL4xEfjc0c23s+6EYKXlXsmACBVclLP1yOfWCgEganVzddVrSNoTg==", "dev": true, - "requires": { + "dependencies": { "exit": "0.1.2", "glob": "^7.1.1" + }, + "engines": { + "node": ">=0.2.5" } }, - "commander": { + "node_modules/commander": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", - "dev": true + "dev": true, + "engines": { + "node": ">= 12" + } }, - "concat-map": { + "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, - "console-browserify": { + "node_modules/console-browserify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", "integrity": "sha512-duS7VP5pvfsNLDvL1O4VOEbw37AI3A4ZUQYemvDlnpGrNu9tprR7BYWpDYwC0Xia0Zxz5ZupdiIrUp0GH1aXfg==", "dev": true, - "requires": { + "dependencies": { "date-now": "^0.1.4" } }, - "core-util-is": { + "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "dev": true }, - "css-b64-images": { + "node_modules/css-b64-images": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/css-b64-images/-/css-b64-images-0.2.5.tgz", "integrity": "sha1-QgBdgyBLK0pdk7axpWRBM7WSegI=", - "dev": true + "dev": true, + "bin": { + "css-b64-images": "bin/css-b64-images" + }, + "engines": { + "node": "*" + } }, - "date-now": { + "node_modules/date-now": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", "integrity": "sha512-AsElvov3LoNB7tf5k37H2jYSB+ZZPMT5sG2QjJCcdlV5chIv6htBUBUui2IKRjgtKAKtCBN7Zbwa+MtwLjSeNw==", "dev": true }, - "debug": { + "node_modules/debug": { "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", "dev": true, - "requires": { + "dependencies": { "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "dom-serializer": { + "node_modules/dom-serializer": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.2.2.tgz", "integrity": "sha512-2/xPb3ORsQ42nHYiSunXkDjPLBaEj/xTwUO4B7XCZQTRk7EBtTOPaygh10YAAh2OI1Qrp6NWfpAhzswj0ydt9g==", "dev": true, - "requires": { + "dependencies": { "domelementtype": "^2.0.1", "entities": "^2.0.0" - }, - "dependencies": { - "domelementtype": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", - "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", - "dev": true - }, - "entities": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", - "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", - "dev": true + } + }, + "node_modules/dom-serializer/node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" } + ] + }, + "node_modules/dom-serializer/node_modules/entities": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", + "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", + "dev": true, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" } }, - "domelementtype": { + "node_modules/domelementtype": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==", "dev": true }, - "domhandler": { + "node_modules/domhandler": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.3.0.tgz", "integrity": "sha512-q9bUwjfp7Eif8jWxxxPSykdRZAb6GkguBGSgvvCrhI9wB71W2K/Kvv4E61CF/mcCfnVJDeDWx/Vb/uAqbDj6UQ==", "dev": true, - "requires": { + "dependencies": { "domelementtype": "1" } }, - "domutils": { + "node_modules/domutils": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", "integrity": "sha512-gSu5Oi/I+3wDENBsOWBiRK1eoGxcywYSqg3rR960/+EfY0CF4EX1VPkgHOZ3WiS/Jg2DtliF6BhWcHlfpYUcGw==", "dev": true, - "requires": { + "dependencies": { "dom-serializer": "0", "domelementtype": "1" } }, - "dot-case": { + "node_modules/dot-case": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/dot-case/-/dot-case-3.0.4.tgz", "integrity": "sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==", "dev": true, - "requires": { + "dependencies": { "no-case": "^3.0.4", "tslib": "^2.0.3" } }, - "entities": { + "node_modules/entities": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/entities/-/entities-1.0.0.tgz", "integrity": "sha512-LbLqfXgJMmy81t+7c14mnulFHJ170cM6E+0vMXR9k/ZiZwgX8i5pNgjTCX3SO4VeUsFLV+8InixoretwU+MjBQ==", "dev": true }, - "eslint-visitor-keys": { + "node_modules/eslint-visitor-keys": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", - "dev": true + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } }, - "espree": { + "node_modules/espree": { "version": "9.4.0", "resolved": "https://registry.npmjs.org/espree/-/espree-9.4.0.tgz", "integrity": "sha512-DQmnRpLj7f6TgN/NYb0MTzJXL+vJF9h3pHy4JhCIs3zwcgez8xmGg3sXHcEO97BrmO2OSvCwMdfdlyl+E9KjOw==", "dev": true, - "requires": { + "dependencies": { "acorn": "^8.8.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^3.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" } }, - "exit": { + "node_modules/exit": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.8.0" + } }, - "find-up": { + "node_modules/find-up": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-6.3.0.tgz", "integrity": "sha512-v2ZsoEuVHYy8ZIlYqwPe/39Cy+cFDzp4dXPaxNvkEuouymu+2Jbz0PxpKarJHYJTmv2HWT3O382qY8l4jMWthw==", "dev": true, - "requires": { + "dependencies": { "locate-path": "^7.1.0", "path-exists": "^5.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "fs.realpath": { + "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", "dev": true }, - "glob": { + "node_modules/glob": { "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", "dev": true, - "requires": { + "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", @@ -281,30 +357,40 @@ "once": "^1.3.0", "path-is-absolute": "^1.0.0" }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, "dependencies": { - "minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "requires": { - "brace-expansion": "^1.1.7" - } - } + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" } }, - "he": { + "node_modules/he": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", - "dev": true + "dev": true, + "bin": { + "he": "bin/he" + } }, - "html-minifier-terser": { + "node_modules/html-minifier-terser": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz", "integrity": "sha512-YXxSlJBZTP7RS3tWnQw74ooKa6L9b9i9QYXY21eUEvhZ3u9XLfv6OnFsQq6RxkhHygsaUMvYsZRV5rU/OVNZxw==", "dev": true, - "requires": { + "dependencies": { "camel-case": "^4.1.2", "clean-css": "^5.2.2", "commander": "^8.3.0", @@ -312,14 +398,20 @@ "param-case": "^3.0.4", "relateurl": "^0.2.7", "terser": "^5.10.0" + }, + "bin": { + "html-minifier-terser": "cli.js" + }, + "engines": { + "node": ">=12" } }, - "htmlparser2": { + "node_modules/htmlparser2": { "version": "3.8.3", "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.8.3.tgz", "integrity": "sha512-hBxEg3CYXe+rPIua8ETe7tmG3XDn9B0edOE/e9wH2nLczxzgdu0m0aNHY+5wFZiviLWLdANPJTssa92dMcXQ5Q==", "dev": true, - "requires": { + "dependencies": { "domelementtype": "1", "domhandler": "2.3", "domutils": "1.5", @@ -327,46 +419,55 @@ "readable-stream": "1.1" } }, - "husky": { + "node_modules/husky": { "version": "7.0.4", "resolved": "https://registry.npmjs.org/husky/-/husky-7.0.4.tgz", "integrity": "sha512-vbaCKN2QLtP/vD4yvs6iz6hBEo6wkSzs8HpRah1Z6aGmF2KW5PdYuAd7uX5a+OyBZHBhd+TFLqgjUgytQr4RvQ==", - "dev": true + "dev": true, + "bin": { + "husky": "lib/bin.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } }, - "inflight": { + "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "dev": true, - "requires": { + "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, - "inherits": { + "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, - "isarray": { + "node_modules/isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", "integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==", "dev": true }, - "jju": { + "node_modules/jju": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/jju/-/jju-1.4.0.tgz", "integrity": "sha1-o6vicYryQaKykE+EpiWXDzia4yo=", "dev": true }, - "jshint": { + "node_modules/jshint": { "version": "2.13.5", "resolved": "https://registry.npmjs.org/jshint/-/jshint-2.13.5.tgz", "integrity": "sha512-dB2n1w3OaQ35PLcBGIWXlszjbPZwsgZoxsg6G8PtNf2cFMC1l0fObkYLUuXqTTdi6tKw4sAjfUseTdmDMHQRcg==", "dev": true, - "requires": { + "dependencies": { "cli": "~1.0.0", "console-browserify": "1.1.x", "exit": "0.1.x", @@ -374,48 +475,63 @@ "lodash": "~4.17.21", "minimatch": "~3.0.2", "strip-json-comments": "1.0.x" + }, + "bin": { + "jshint": "bin/jshint" } }, - "locate-path": { + "node_modules/locate-path": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-7.1.1.tgz", "integrity": "sha512-vJXaRMJgRVD3+cUZs3Mncj2mxpt5mP0EmNOsxRSZRMlbqjvxzDEOIUWXGmavo0ZC9+tNZCBLQ66reA11nbpHZg==", "dev": true, - "requires": { + "dependencies": { "p-locate": "^6.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "lodash": { + "node_modules/lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, - "lower-case": { + "node_modules/lower-case": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-2.0.2.tgz", "integrity": "sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==", "dev": true, - "requires": { + "dependencies": { "tslib": "^2.0.3" } }, - "matched": { + "node_modules/matched": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/matched/-/matched-5.0.1.tgz", "integrity": "sha512-E1fhSTPRyhAlNaNvGXAgZQlq1hL0bgYMTk/6bktVlIhzUnX/SZs7296ACdVeNJE8xFNGSuvd9IpI7vSnmcqLvw==", "dev": true, - "requires": { + "dependencies": { "glob": "^7.1.6", "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" } }, - "minify": { + "node_modules/minify": { "version": "7.2.2", "resolved": "https://registry.npmjs.org/minify/-/minify-7.2.2.tgz", "integrity": "sha512-AcgoqXRQX0o/PRrydK8klB5OD09lFjJ/OYVHGxmWmbg/DQP/ETmmPM4aA10NZBiGdlLeUnC9sCgrgJAt0P14mA==", "dev": true, - "requires": { + "dependencies": { "clean-css": "^5.0.1", "css-b64-images": "~0.2.5", "debug": "^4.1.0", @@ -425,227 +541,294 @@ "terser": "^5.3.2", "try-catch": "^3.0.0", "try-to-catch": "^3.0.0" + }, + "bin": { + "minify": "bin/minify.js" + }, + "engines": { + "node": ">=14" } }, - "minimatch": { + "node_modules/minimatch": { "version": "3.0.8", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.8.tgz", "integrity": "sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q==", "dev": true, - "requires": { + "dependencies": { "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" } }, - "ms": { + "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", "dev": true }, - "no-case": { + "node_modules/no-case": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/no-case/-/no-case-3.0.4.tgz", "integrity": "sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==", "dev": true, - "requires": { + "dependencies": { "lower-case": "^2.0.2", "tslib": "^2.0.3" } }, - "once": { + "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, - "requires": { + "dependencies": { "wrappy": "1" } }, - "p-limit": { + "node_modules/p-limit": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-4.0.0.tgz", "integrity": "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==", "dev": true, - "requires": { + "dependencies": { "yocto-queue": "^1.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "p-locate": { + "node_modules/p-locate": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-6.0.0.tgz", "integrity": "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==", "dev": true, - "requires": { + "dependencies": { "p-limit": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "param-case": { + "node_modules/param-case": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/param-case/-/param-case-3.0.4.tgz", "integrity": "sha512-RXlj7zCYokReqWpOPH9oYivUzLYZ5vAPIfEmCTNViosC78F8F0H9y7T7gG2M39ymgutxF5gcFEsyZQSph9Bp3A==", "dev": true, - "requires": { + "dependencies": { "dot-case": "^3.0.4", "tslib": "^2.0.3" } }, - "pascal-case": { + "node_modules/pascal-case": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/pascal-case/-/pascal-case-3.1.2.tgz", "integrity": "sha512-uWlGT3YSnK9x3BQJaOdcZwrnV6hPpd8jFH1/ucpiLRPh/2zCVJKS19E4GvYHvaCcACn3foXZ0cLB9Wrx1KGe5g==", "dev": true, - "requires": { + "dependencies": { "no-case": "^3.0.4", "tslib": "^2.0.3" } }, - "path-exists": { + "node_modules/path-exists": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", "integrity": "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==", - "dev": true + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } }, - "path-is-absolute": { + "node_modules/path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "path-sort": { + "node_modules/path-sort": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/path-sort/-/path-sort-0.1.0.tgz", "integrity": "sha1-ywF11Oy/paGP5nTMbXIL/hXguAU=", "dev": true }, - "php-parser": { + "node_modules/php-parser": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/php-parser/-/php-parser-3.1.1.tgz", "integrity": "sha512-HUxWIWpJoGhnSVzM6nPI1O2RePd7eJKzJoL3VZr6/KUUdcHKBex2Cp7p6pWOV1WxgKI/oYgRPMywwLCP789OYA==", "dev": true }, - "picomatch": { + "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } }, - "readable-stream": { + "node_modules/readable-stream": { "version": "1.1.14", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", "integrity": "sha512-+MeVjFf4L44XUkhM1eYbD8fyEsxcV81pqMSR5gblfcLCHfZvbrqy4/qYHE+/R5HoBUT11WV5O08Cr1n3YXkWVQ==", "dev": true, - "requires": { + "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.1", "isarray": "0.0.1", "string_decoder": "~0.10.x" } }, - "readjson": { + "node_modules/readjson": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/readjson/-/readjson-2.2.2.tgz", "integrity": "sha512-PdeC9tsmLWBiL8vMhJvocq+OezQ3HhsH2HrN7YkhfYcTjQSa/iraB15A7Qvt7Xpr0Yd2rDNt6GbFwVQDg3HcAw==", "dev": true, - "requires": { + "dependencies": { "jju": "^1.4.0", "try-catch": "^3.0.0" + }, + "engines": { + "node": ">=10" } }, - "relateurl": { + "node_modules/relateurl": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz", "integrity": "sha1-VNvzd+UUQKypCkzSdGANP/LYiKk=", - "dev": true + "dev": true, + "engines": { + "node": ">= 0.10" + } }, - "source-map": { + "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true + "dev": true, + "engines": { + "node": ">=0.10.0" + } }, - "source-map-support": { + "node_modules/source-map-support": { "version": "0.5.21", "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", "dev": true, - "requires": { + "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, - "string_decoder": { + "node_modules/string_decoder": { "version": "0.10.31", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", "integrity": "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==", "dev": true }, - "strip-json-comments": { + "node_modules/strip-json-comments": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz", "integrity": "sha512-AOPG8EBc5wAikaG1/7uFCNFJwnKOuQwFTpYBdTW6OvWHeZBQBrAA/amefHGrEiOnCPcLFZK6FUPtWVKpQVIRgg==", - "dev": true + "dev": true, + "bin": { + "strip-json-comments": "cli.js" + }, + "engines": { + "node": ">=0.8.0" + } }, - "terser": { + "node_modules/terser": { "version": "5.15.0", "resolved": "https://registry.npmjs.org/terser/-/terser-5.15.0.tgz", "integrity": "sha512-L1BJiXVmheAQQy+as0oF3Pwtlo4s3Wi1X2zNZ2NxOB4wx9bdS9Vk67XQENLFdLYGCK/Z2di53mTj/hBafR+dTA==", "dev": true, - "requires": { + "dependencies": { "@jridgewell/source-map": "^0.3.2", "acorn": "^8.5.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, - "dependencies": { - "commander": { - "version": "2.20.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", - "dev": true - } + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" } }, - "try-catch": { + "node_modules/terser/node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "node_modules/try-catch": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/try-catch/-/try-catch-3.0.1.tgz", "integrity": "sha512-91yfXw1rr/P6oLpHSyHDOHm0vloVvUoo9FVdw8YwY05QjJQG9OT0LUxe2VRAzmHG+0CUOmI3nhxDUMLxDN/NEQ==", - "dev": true + "dev": true, + "engines": { + "node": ">=6" + } }, - "try-to-catch": { + "node_modules/try-to-catch": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/try-to-catch/-/try-to-catch-3.0.1.tgz", "integrity": "sha512-hOY83V84Hx/1sCzDSaJA+Xz2IIQOHRvjxzt+F0OjbQGPZ6yLPLArMA0gw/484MlfUkQbCpKYMLX3VDCAjWKfzQ==", - "dev": true + "dev": true, + "engines": { + "node": ">=6" + } }, - "tslib": { + "node_modules/tslib": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==", "dev": true }, - "wp-pot": { + "node_modules/wp-pot": { "version": "1.10.2", "resolved": "https://registry.npmjs.org/wp-pot/-/wp-pot-1.10.2.tgz", "integrity": "sha512-NJ9+dsSilghAYMiuGdURJSbKFf9Z2mH+P6ojT8Nw1Pp8KuwvHdRTFTYK73THlYzohUEXlQGpvKkz+mJb8K1ToA==", "dev": true, - "requires": { + "dependencies": { "espree": "^9.3.1", "matched": "^5.0.1", "path-sort": "^0.1.0", "php-parser": "^3.0.3" + }, + "engines": { + "node": ">=14" } }, - "wrappy": { + "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, - "yocto-queue": { + "node_modules/yocto-queue": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.0.0.tgz", "integrity": "sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==", - "dev": true + "dev": true, + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } } } } diff --git a/packages/plugin-updater/Puc/Autoloader.php b/packages/plugin-updater/Puc/Autoloader.php new file mode 100644 index 000000000..ec8511461 --- /dev/null +++ b/packages/plugin-updater/Puc/Autoloader.php @@ -0,0 +1,57 @@ +rootDir = dirname(__FILE__) . '/'; + $nameParts = explode('_', __CLASS__, 3); + $this->prefix = $nameParts[0] . '_' . $nameParts[1] . '_'; + + $this->libraryDir = $this->rootDir . '../..'; + if ( !self::isPhar() ) { + $this->libraryDir = realpath($this->libraryDir); + } + $this->libraryDir = $this->libraryDir . '/'; + + spl_autoload_register([$this, 'autoload']); + } + + /** + * Determine if this file is running as part of a Phar archive. + * + * @return bool + */ + private static function isPhar() { + //Check if the current file path starts with "phar://". + static $pharProtocol = 'phar://'; + return (substr(__FILE__, 0, strlen($pharProtocol)) === $pharProtocol); + } + + public function autoload($className) { + if ( isset($this->staticMap[$className]) && file_exists($this->libraryDir . $this->staticMap[$className]) ) { + /** @noinspection PhpIncludeInspection */ + include $this->libraryDir . $this->staticMap[$className]; + return; + } + + if (strpos($className, $this->prefix) === 0) { + $path = substr($className, strlen($this->prefix)); + $path = str_replace('_', '/', $path); + $path = $this->rootDir . $path . '.php'; + + if (file_exists($path)) { + /** @noinspection PhpIncludeInspection */ + include $path; + } + } + } + } + +endif; diff --git a/packages/plugin-updater/Puc/InstalledPackage.php b/packages/plugin-updater/Puc/InstalledPackage.php new file mode 100644 index 000000000..6fa4f75fa --- /dev/null +++ b/packages/plugin-updater/Puc/InstalledPackage.php @@ -0,0 +1,102 @@ +updateChecker = $updateChecker; + } + + /** + * Get the currently installed version of the plugin or theme. + * + * @return string|null Version number. + */ + abstract public function getInstalledVersion(); + + /** + * Get the full path of the plugin or theme directory (without a trailing slash). + * + * @return string + */ + abstract public function getAbsoluteDirectoryPath(); + + /** + * Check whether a regular file exists in the package's directory. + * + * @param string $relativeFileName File name relative to the package directory. + * @return bool + */ + public function fileExists($relativeFileName) { + return is_file( + $this->getAbsoluteDirectoryPath() + . DIRECTORY_SEPARATOR + . ltrim($relativeFileName, '/\\') + ); + } + + /* ------------------------------------------------------------------- + * File header parsing + * ------------------------------------------------------------------- + */ + + /** + * Parse plugin or theme metadata from the header comment. + * + * This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php. + * It's intended as a utility for subclasses that detect updates by parsing files in a VCS. + * + * @param string|null $content File contents. + * @return string[] + */ + public function getFileHeader($content) { + $content = (string)$content; + + //WordPress only looks at the first 8 KiB of the file, so we do the same. + $content = substr($content, 0, 8192); + //Normalize line endings. + $content = str_replace("\r", "\n", $content); + + $headers = $this->getHeaderNames(); + $results = []; + foreach ($headers as $field => $name) { + $success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches); + + if ( ($success === 1) && $matches[1] ) { + $value = $matches[1]; + if ( function_exists('_cleanup_header_comment') ) { + $value = _cleanup_header_comment($value); + } + $results[$field] = $value; + } else { + $results[$field] = ''; + } + } + + return $results; + } + + /** + * @return array Format: ['HeaderKey' => 'Header Name'] + */ + abstract protected function getHeaderNames(); + + /** + * Get the value of a specific plugin or theme header. + * + * @param string $headerName + * @return string Either the value of the header, or an empty string if the header doesn't exist. + */ + abstract public function getHeaderValue($headerName); + } +endif; diff --git a/packages/plugin-updater/Puc/Metadata.php b/packages/plugin-updater/Puc/Metadata.php new file mode 100644 index 000000000..cb974d1f3 --- /dev/null +++ b/packages/plugin-updater/Puc/Metadata.php @@ -0,0 +1,131 @@ +validateMetadata($apiResponse); + if ( is_wp_error($valid) ) { + do_action('puc_api_error', $valid); + trigger_error($valid->get_error_message(), E_USER_NOTICE); + return false; + } + + foreach (get_object_vars($apiResponse) as $key => $value) { + $target->$key = $value; + } + + return true; + } + + /** + * No validation by default! Subclasses should check that the required fields are present. + * + * @param StdClass $apiResponse + * @return bool|WP_Error + */ + protected function validateMetadata(/** @noinspection PhpUnusedParameterInspection */ $apiResponse) { + return true; + } + + /** + * Create a new instance by copying the necessary fields from another object. + * + * @abstract + * @param StdClass|self $object The source object. + * @return self The new copy. + */ + public static function fromObject(/** @noinspection PhpUnusedParameterInspection */ $object) { + throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses'); + } + + /** + * Create an instance of StdClass that can later be converted back to an + * update or info container. Useful for serialization and caching, as it + * avoids the "incomplete object" problem if the cached value is loaded + * before this class. + * + * @return StdClass + */ + public function toStdClass() { + $object = new stdClass(); + $this->copyFields($this, $object); + return $object; + } + + /** + * Transform the metadata into the format used by WordPress core. + * + * @return object + */ + abstract public function toWpFormat(); + + /** + * Copy known fields from one object to another. + * + * @param StdClass|self $from + * @param StdClass|self $to + */ + protected function copyFields($from, $to) { + $fields = $this->getFieldNames(); + + if ( property_exists($from, 'slug') && !empty($from->slug) ) { + //Let plugins add extra fields without having to create subclasses. + $fields = apply_filters($this->getPrefixedFilter('retain_fields') . '-' . $from->slug, $fields); + } + + foreach ($fields as $field) { + if ( property_exists($from, $field) ) { + $to->$field = $from->$field; + } + } + } + + /** + * @return string[] + */ + protected function getFieldNames() { + return []; + } + + /** + * @param string $tag + * @return string + */ + protected function getPrefixedFilter($tag) { + return 'puc_' . $tag; + } + } + +endif; diff --git a/packages/plugin-updater/Puc/Plugin/Info.php b/packages/plugin-updater/Puc/Plugin/Info.php new file mode 100644 index 000000000..fde1e0c25 --- /dev/null +++ b/packages/plugin-updater/Puc/Plugin/Info.php @@ -0,0 +1,131 @@ +sections = (array)$instance->sections; + $instance->icons = (array)$instance->icons; + + return $instance; + } + + /** + * Very, very basic validation. + * + * @param StdClass $apiResponse + * @return bool|WP_Error + */ + protected function validateMetadata($apiResponse) { + if ( + !isset($apiResponse->name, $apiResponse->version) + || empty($apiResponse->name) + || empty($apiResponse->version) + ) { + return new WP_Error( + 'puc-invalid-metadata', + "The plugin metadata file does not contain the required 'name' and/or 'version' keys." + ); + } + return true; + } + + /** + * Transform plugin info into the format used by the native WordPress.org API + * + * @return object + */ + public function toWpFormat() { + $info = new stdClass; + + //The custom update API is built so that many fields have the same name and format + //as those returned by the native WordPress.org API. These can be assigned directly. + $sameFormat = [ + 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice', + 'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated', + 'requires_php', + ]; + foreach ($sameFormat as $field) { + if ( isset($this->$field) ) { + $info->$field = $this->$field; + } else { + $info->$field = null; + } + } + + //Other fields need to be renamed and/or transformed. + $info->download_link = $this->download_url; + $info->author = $this->getFormattedAuthor(); + $info->sections = array_merge(['description' => ''], $this->sections); + + if ( !empty($this->banners) ) { + //WP expects an array with two keys: "high" and "low". Both are optional. + //Docs: https://wordpress.org/plugins/about/faq/#banners + $info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners; + $info->banners = array_intersect_key($info->banners, ['high' => true, 'low' => true]); + } + + return $info; + } + + protected function getFormattedAuthor() { + if ( !empty($this->author_homepage) ) { + /** @noinspection HtmlUnknownTarget */ + return sprintf('%s', $this->author_homepage, $this->author); + } + return $this->author; + } + } + +endif; diff --git a/packages/plugin-updater/Puc/Plugin/Package.php b/packages/plugin-updater/Puc/Plugin/Package.php new file mode 100644 index 000000000..f51076d32 --- /dev/null +++ b/packages/plugin-updater/Puc/Plugin/Package.php @@ -0,0 +1,205 @@ +pluginAbsolutePath = $pluginAbsolutePath; + $this->pluginFile = plugin_basename($this->pluginAbsolutePath); + + parent::__construct($updateChecker); + + //Clear the version number cache when something - anything - is upgraded or WP clears the update cache. + add_filter('upgrader_post_install', [$this, 'clearCachedVersion']); + add_action('delete_site_transient_update_plugins', [$this, 'clearCachedVersion']); + } + + public function getInstalledVersion() { + if ( isset($this->cachedInstalledVersion) ) { + return $this->cachedInstalledVersion; + } + + $pluginHeader = $this->getPluginHeader(); + if ( isset($pluginHeader['Version']) ) { + $this->cachedInstalledVersion = $pluginHeader['Version']; + return $pluginHeader['Version']; + } else { + //This can happen if the filename points to something that is not a plugin. + $this->updateChecker->triggerError( + sprintf( + "Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.", + $this->updateChecker->pluginFile + ), + E_USER_WARNING + ); + return null; + } + } + + /** + * Clear the cached plugin version. This method can be set up as a filter (hook) and will + * return the filter argument unmodified. + * + * @param mixed $filterArgument + * @return mixed + */ + public function clearCachedVersion($filterArgument = null) { + $this->cachedInstalledVersion = null; + return $filterArgument; + } + + public function getAbsoluteDirectoryPath() { + return dirname($this->pluginAbsolutePath); + } + + /** + * Get the value of a specific plugin or theme header. + * + * @param string $headerName + * @param string $defaultValue + * @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty. + */ + public function getHeaderValue($headerName, $defaultValue = '') { + $headers = $this->getPluginHeader(); + if ( isset($headers[$headerName]) && ($headers[$headerName] !== '') ) { + return $headers[$headerName]; + } + return $defaultValue; + } + + protected function getHeaderNames() { + return [ + 'Name' => 'Plugin Name', + 'PluginURI' => 'Plugin URI', + 'Version' => 'Version', + 'Description' => 'Description', + 'Author' => 'Author', + 'AuthorURI' => 'Author URI', + 'TextDomain' => 'Text Domain', + 'DomainPath' => 'Domain Path', + 'Network' => 'Network', + + //The newest WordPress version that this plugin requires or has been tested with. + //We support several different formats for compatibility with other libraries. + 'Tested WP' => 'Tested WP', + 'Requires WP' => 'Requires WP', + 'Tested up to' => 'Tested up to', + 'Requires at least' => 'Requires at least', + ]; + } + + /** + * Get the translated plugin title. + * + * @return string + */ + public function getPluginTitle() { + $title = ''; + $header = $this->getPluginHeader(); + if ( $header && !empty($header['Name']) && isset($header['TextDomain']) ) { + $title = translate($header['Name'], $header['TextDomain']); + } + return $title; + } + + /** + * Get plugin's metadata from its file header. + * + * @return array + */ + public function getPluginHeader() { + if ( !is_file($this->pluginAbsolutePath) ) { + //This can happen if the plugin filename is wrong. + $this->updateChecker->triggerError( + sprintf( + "Can't to read the plugin header for '%s'. The file does not exist.", + $this->updateChecker->pluginFile + ), + E_USER_WARNING + ); + return []; + } + + if ( !function_exists('get_plugin_data') ) { + /** @noinspection PhpIncludeInspection */ + require_once ABSPATH . '/wp-admin/includes/plugin.php'; + } + return get_plugin_data($this->pluginAbsolutePath, false, false); + } + + public function removeHooks() { + remove_filter('upgrader_post_install', [$this, 'clearCachedVersion']); + remove_action('delete_site_transient_update_plugins', [$this, 'clearCachedVersion']); + } + + /** + * Check if the plugin file is inside the mu-plugins directory. + * + * @return bool + */ + public function isMuPlugin() { + static $cachedResult = null; + + if ( $cachedResult === null ) { + if ( !defined('WPMU_PLUGIN_DIR') || !is_string(WPMU_PLUGIN_DIR) ) { + $cachedResult = false; + return $cachedResult; + } + + //Convert both paths to the canonical form before comparison. + $muPluginDir = realpath(WPMU_PLUGIN_DIR); + $pluginPath = realpath($this->pluginAbsolutePath); + //If realpath() fails, just normalize the syntax instead. + if (($muPluginDir === false) || ($pluginPath === false)) { + $muPluginDir = self::normalizePath(WPMU_PLUGIN_DIR); + $pluginPath = self::normalizePath($this->pluginAbsolutePath); + } + + $cachedResult = (strpos($pluginPath, $muPluginDir) === 0); + } + + return $cachedResult; + } + + /** + * + * Normalize a filesystem path. Introduced in WP 3.9. + * Copying here allows use of the class on earlier versions. + * This version adapted from WP 4.8.2 (unchanged since 4.5.0) + * + * @param string $path Path to normalize. + * @return string Normalized path. + */ + public static function normalizePath($path) { + if ( function_exists('wp_normalize_path') ) { + return wp_normalize_path($path); + } + $path = str_replace('\\', '/', $path); + $path = preg_replace('|(?<=.)/+|', '/', $path); + if ( substr($path, 1, 1) === ':' ) { + $path = ucfirst($path); + } + return $path; + } + } + +endif; diff --git a/packages/plugin-updater/Puc/Plugin/Ui.php b/packages/plugin-updater/Puc/Plugin/Ui.php new file mode 100644 index 000000000..3625b0d9e --- /dev/null +++ b/packages/plugin-updater/Puc/Plugin/Ui.php @@ -0,0 +1,282 @@ +updateChecker = $updateChecker; + $this->manualCheckErrorTransient = $this->updateChecker->getUniqueName('manual_check_errors'); + + add_action('admin_init', [$this, 'onAdminInit']); + } + + public function onAdminInit() { + if ( $this->updateChecker->userCanInstallUpdates() ) { + $this->handleManualCheck(); + + add_filter('plugin_row_meta', [$this, 'addViewDetailsLink'], 10, 3); + add_filter('plugin_row_meta', [$this, 'addCheckForUpdatesLink'], 10, 2); + add_action('all_admin_notices', [$this, 'displayManualCheckResult']); + } + } + + /** + * Add a "View Details" link to the plugin row in the "Plugins" page. By default, + * the new link will appear before the "Visit plugin site" link (if present). + * + * You can change the link text by using the "puc_view_details_link-$slug" filter. + * Returning an empty string from the filter will disable the link. + * + * You can change the position of the link using the + * "puc_view_details_link_position-$slug" filter. + * Returning 'before' or 'after' will place the link immediately before/after + * the "Visit plugin site" link. + * Returning 'append' places the link after any existing links at the time of the hook. + * Returning 'replace' replaces the "Visit plugin site" link. + * Returning anything else disables the link when there is a "Visit plugin site" link. + * + * If there is no "Visit plugin site" link 'append' is always used! + * + * @param array $pluginMeta Array of meta links. + * @param string $pluginFile + * @param array $pluginData Array of plugin header data. + * @return array + */ + public function addViewDetailsLink($pluginMeta, $pluginFile, $pluginData = []) { + if ( $this->isMyPluginFile($pluginFile) && !isset($pluginData['slug']) ) { + $linkText = apply_filters($this->updateChecker->getUniqueName('view_details_link'), __('View details')); + if ( !empty($linkText) ) { + $viewDetailsLinkPosition = 'append'; + + //Find the "Visit plugin site" link (if present). + $visitPluginSiteLinkIndex = count($pluginMeta) - 1; + if ( $pluginData['PluginURI'] ) { + $escapedPluginUri = esc_url($pluginData['PluginURI']); + foreach ($pluginMeta as $linkIndex => $existingLink) { + if ( strpos($existingLink, $escapedPluginUri) !== false ) { + $visitPluginSiteLinkIndex = $linkIndex; + $viewDetailsLinkPosition = apply_filters( + $this->updateChecker->getUniqueName('view_details_link_position'), + 'before' + ); + break; + } + } + } + + $viewDetailsLink = sprintf('%s', + esc_url(network_admin_url('plugin-install.php?tab=plugin-information&plugin=' . urlencode($this->updateChecker->slug) . + '&TB_iframe=true&width=600&height=550')), + esc_attr(sprintf(__('More information about %s'), $pluginData['Name'])), + esc_attr($pluginData['Name']), + $linkText + ); + switch ($viewDetailsLinkPosition) { + case 'before': + array_splice($pluginMeta, $visitPluginSiteLinkIndex, 0, $viewDetailsLink); + break; + case 'after': + array_splice($pluginMeta, $visitPluginSiteLinkIndex + 1, 0, $viewDetailsLink); + break; + case 'replace': + $pluginMeta[$visitPluginSiteLinkIndex] = $viewDetailsLink; + break; + case 'append': + default: + $pluginMeta[] = $viewDetailsLink; + break; + } + } + } + return $pluginMeta; + } + + /** + * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default, + * the new link will appear after the "Visit plugin site" link if present, otherwise + * after the "View plugin details" link. + * + * You can change the link text by using the "puc_manual_check_link-$slug" filter. + * Returning an empty string from the filter will disable the link. + * + * @param array $pluginMeta Array of meta links. + * @param string $pluginFile + * @return array + */ + public function addCheckForUpdatesLink($pluginMeta, $pluginFile) { + if ( $this->isMyPluginFile($pluginFile) ) { + $linkUrl = wp_nonce_url( + add_query_arg( + [ + 'puc_check_for_updates' => 1, + 'puc_slug' => $this->updateChecker->slug, + ], + self_admin_url('plugins.php') + ), + 'puc_check_for_updates' + ); + + $linkText = apply_filters( + $this->updateChecker->getUniqueName('manual_check_link'), + __('Check for updates', 'plugin-update-checker') + ); + if ( !empty($linkText) ) { + /** @noinspection HtmlUnknownTarget */ + $pluginMeta[] = sprintf('%s', esc_attr($linkUrl), $linkText); + } + } + return $pluginMeta; + } + + protected function isMyPluginFile($pluginFile) { + return ($pluginFile == $this->updateChecker->pluginFile) + || (!empty($this->updateChecker->muPluginFile) && ($pluginFile == $this->updateChecker->muPluginFile)); + } + + /** + * Check for updates when the user clicks the "Check for updates" link. + * + * @see self::addCheckForUpdatesLink() + * + * @return void + */ + public function handleManualCheck() { + $shouldCheck = + isset($_GET['puc_check_for_updates'], $_GET['puc_slug']) + && $_GET['puc_slug'] == $this->updateChecker->slug + && check_admin_referer('puc_check_for_updates'); + + if ( $shouldCheck ) { + $update = $this->updateChecker->checkForUpdates(); + $status = ($update === null) ? 'no_update' : 'update_available'; + $lastRequestApiErrors = $this->updateChecker->getLastRequestApiErrors(); + + if ( ($update === null) && !empty($lastRequestApiErrors) ) { + //Some errors are not critical. For example, if PUC tries to retrieve the readme.txt + //file from GitHub and gets a 404, that's an API error, but it doesn't prevent updates + //from working. Maybe the plugin simply doesn't have a readme. + //Let's only show important errors. + $foundCriticalErrors = false; + $questionableErrorCodes = [ + 'puc-github-http-error', + 'puc-gitlab-http-error', + 'puc-bitbucket-http-error', + ]; + + foreach ($lastRequestApiErrors as $item) { + $wpError = $item['error']; + /** @var WP_Error $wpError */ + if ( !in_array($wpError->get_error_code(), $questionableErrorCodes) ) { + $foundCriticalErrors = true; + break; + } + } + + if ( $foundCriticalErrors ) { + $status = 'error'; + set_site_transient($this->manualCheckErrorTransient, $lastRequestApiErrors, 60); + } + } + + wp_redirect(add_query_arg( + [ + 'puc_update_check_result' => $status, + 'puc_slug' => $this->updateChecker->slug, + ], + self_admin_url('plugins.php') + )); + exit; + } + } + + /** + * Display the results of a manual update check. + * + * @see self::handleManualCheck() + * + * You can change the result message by using the "puc_manual_check_message-$slug" filter. + */ + public function displayManualCheckResult() { + if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->updateChecker->slug) ) { + $status = strval($_GET['puc_update_check_result']); + $title = $this->updateChecker->getInstalledPackage()->getPluginTitle(); + $noticeClass = 'updated notice-success'; + $details = ''; + + if ( $status == 'no_update' ) { + $message = sprintf(_x('The %s plugin is up to date.', 'the plugin title', 'plugin-update-checker'), $title); + } else { + if ( $status == 'update_available' ) { + $message = sprintf(_x('A new version of the %s plugin is available.', 'the plugin title', 'plugin-update-checker'), $title); + } else { + if ( $status === 'error' ) { + $message = sprintf(_x('Could not determine if updates are available for %s.', 'the plugin title', 'plugin-update-checker'), $title); + $noticeClass = 'error notice-error'; + + $details = $this->formatManualCheckErrors(get_site_transient($this->manualCheckErrorTransient)); + delete_site_transient($this->manualCheckErrorTransient); + } else { + $message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status)); + $noticeClass = 'error notice-error'; + } + } + } + printf( + '

%s

%s
', + $noticeClass, + apply_filters($this->updateChecker->getUniqueName('manual_check_message'), $message, $status), + $details + ); + } + } + + /** + * Format the list of errors that were thrown during an update check. + * + * @param array $errors + * @return string + */ + protected function formatManualCheckErrors($errors) { + if ( empty($errors) ) { + return ''; + } + $output = ''; + + $showAsList = count($errors) > 1; + if ( $showAsList ) { + $output .= '
    '; + $formatString = '
  1. %1$s %2$s
  2. '; + } else { + $formatString = '

    %1$s %2$s

    '; + } + foreach ($errors as $item) { + $wpError = $item['error']; + /** @var WP_Error $wpError */ + $output .= sprintf( + $formatString, + $wpError->get_error_message(), + $wpError->get_error_code() + ); + } + if ( $showAsList ) { + $output .= '
'; + } + + return $output; + } + + public function removeHooks() { + remove_action('admin_init', [$this, 'onAdminInit']); + remove_filter('plugin_row_meta', [$this, 'addViewDetailsLink'], 10); + remove_filter('plugin_row_meta', [$this, 'addCheckForUpdatesLink'], 10); + remove_action('all_admin_notices', [$this, 'displayManualCheckResult']); + } + } +endif; diff --git a/packages/plugin-updater/Puc/Plugin/Update.php b/packages/plugin-updater/Puc/Plugin/Update.php new file mode 100644 index 000000000..165bc357c --- /dev/null +++ b/packages/plugin-updater/Puc/Plugin/Update.php @@ -0,0 +1,112 @@ +copyFields($object, $update); + return $update; + } + + /** + * @return string[] + */ + protected function getFieldNames() { + return array_merge(parent::getFieldNames(), self::$extraFields); + } + + /** + * Transform the update into the format used by WordPress native plugin API. + * + * @return object + */ + public function toWpFormat() { + $update = parent::toWpFormat(); + + $update->id = $this->id; + $update->url = $this->homepage; + $update->tested = $this->tested; + $update->requires_php = $this->requires_php; + $update->plugin = $this->filename; + + if ( !empty($this->upgrade_notice) ) { + $update->upgrade_notice = $this->upgrade_notice; + } + + if ( !empty($this->icons) && is_array($this->icons) ) { + //This should be an array with up to 4 keys: 'svg', '1x', '2x' and 'default'. + //Docs: https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons + $icons = array_intersect_key( + $this->icons, + ['svg' => true, '1x' => true, '2x' => true, 'default' => true] + ); + if ( !empty($icons) ) { + $update->icons = $icons; + + //It appears that the 'default' icon isn't used anywhere in WordPress 4.9, + //but lets set it just in case a future release needs it. + if ( !isset($update->icons['default']) ) { + $update->icons['default'] = current($update->icons); + } + } + } + + return $update; + } + } + +endif; diff --git a/packages/plugin-updater/Puc/Plugin/UpdateChecker.php b/packages/plugin-updater/Puc/Plugin/UpdateChecker.php new file mode 100644 index 000000000..2412a40ba --- /dev/null +++ b/packages/plugin-updater/Puc/Plugin/UpdateChecker.php @@ -0,0 +1,410 @@ +pluginAbsolutePath = $pluginFile; + $this->pluginFile = plugin_basename($this->pluginAbsolutePath); + $this->muPluginFile = $muPluginFile; + + //If no slug is specified, use the name of the main plugin file as the slug. + //For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'. + if ( empty($slug) ) { + $slug = basename($this->pluginFile, '.php'); + } + + //Plugin slugs must be unique. + $slugCheckFilter = 'puc_is_slug_in_use-' . $slug; + $slugUsedBy = apply_filters($slugCheckFilter, false); + if ( $slugUsedBy ) { + $this->triggerError(sprintf( + 'Plugin slug "%s" is already in use by %s. Slugs must be unique.', + htmlentities($slug), + htmlentities($slugUsedBy) + ), E_USER_ERROR); + } + add_filter($slugCheckFilter, [$this, 'getAbsolutePath']); + + parent::__construct($metadataUrl, dirname($this->pluginFile), $slug, $checkPeriod, $optionName); + + //Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume + //it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir). + if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) { + $this->muPluginFile = $this->pluginFile; + } + + //To prevent a crash during plugin uninstallation, remove updater hooks when the user removes the plugin. + //Details: https://github.com/YahnisElsts/plugin-update-checker/issues/138#issuecomment-335590964 + add_action('uninstall_' . $this->pluginFile, [$this, 'removeHooks']); + + $this->extraUi = new Lkn_Puc_Plugin_Ui($this); + } + + /** + * Create an instance of the scheduler. + * + * @param int $checkPeriod + * @return Lkn_Puc_Scheduler + */ + protected function createScheduler($checkPeriod) { + $scheduler = new Lkn_Puc_Scheduler($this, $checkPeriod, ['load-plugins.php']); + register_deactivation_hook($this->pluginFile, [$scheduler, 'removeUpdaterCron']); + return $scheduler; + } + + /** + * Install the hooks required to run periodic update checks and inject update info + * into WP data structures. + * + * @return void + */ + protected function installHooks() { + //Override requests for plugin information + add_filter('plugins_api', [$this, 'injectInfo'], 20, 3); + + parent::installHooks(); + } + + /** + * Remove update checker hooks. + * + * The intent is to prevent a fatal error that can happen if the plugin has an uninstall + * hook. During uninstallation, WP includes the main plugin file (which creates a PUC instance), + * the uninstall hook runs, WP deletes the plugin files and then updates some transients. + * If PUC hooks are still around at this time, they could throw an error while trying to + * autoload classes from files that no longer exist. + * + * The "site_transient_{$transient}" filter is the main problem here, but let's also remove + * most other PUC hooks to be safe. + * + * @internal + */ + public function removeHooks() { + parent::removeHooks(); + $this->extraUi->removeHooks(); + $this->package->removeHooks(); + + remove_filter('plugins_api', [$this, 'injectInfo'], 20); + } + + /** + * Retrieve plugin info from the configured API endpoint. + * + * @uses wp_remote_get() + * + * @param array $queryArgs Additional query arguments to append to the request. Optional. + * @return Lkn_Puc_Plugin_Info + */ + public function requestInfo($queryArgs = []) { + list($pluginInfo, $result) = $this->requestMetadata('Lkn_Puc_Plugin_Info', $queryArgs); + + if ( $pluginInfo !== null ) { + /** @var Lkn_Puc_Plugin_Info $pluginInfo */ + $pluginInfo->filename = $this->pluginFile; + $pluginInfo->slug = $this->slug; + } + + $pluginInfo = apply_filters($this->getUniqueName('request_info_result'), $pluginInfo, $result); + return $pluginInfo; + } + + /** + * Retrieve the latest update (if any) from the configured API endpoint. + * + * @uses PluginUpdateChecker::requestInfo() + * + * @return Lkn_Puc_Update|null An instance of Plugin_Update, or NULL when no updates are available. + */ + public function requestUpdate() { + //For the sake of simplicity, this function just calls requestInfo() + //and transforms the result accordingly. + $pluginInfo = $this->requestInfo(['checking_for_updates' => '1']); + if ( $pluginInfo === null ) { + return null; + } + $update = Lkn_Puc_Plugin_Update::fromPluginInfo($pluginInfo); + + $update = $this->filterUpdateResult($update); + + return $update; + } + + /** + * Intercept plugins_api() calls that request information about our plugin and + * use the configured API endpoint to satisfy them. + * + * @see plugins_api() + * + * @param mixed $result + * @param string $action + * @param array|object $args + * @return mixed + */ + public function injectInfo($result, $action = null, $args = null) { + $relevant = ($action == 'plugin_information') && isset($args->slug) && ( + ($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile)) + ); + if ( !$relevant ) { + return $result; + } + + $pluginInfo = $this->requestInfo(); + $this->fixSupportedWordpressVersion($pluginInfo); + + $pluginInfo = apply_filters($this->getUniqueName('pre_inject_info'), $pluginInfo); + if ( $pluginInfo ) { + return $pluginInfo->toWpFormat(); + } + + return $result; + } + + protected function shouldShowUpdates() { + //No update notifications for mu-plugins unless explicitly enabled. The MU plugin file + //is usually different from the main plugin file so the update wouldn't show up properly anyway. + return !$this->isUnknownMuPlugin(); + } + + /** + * @param stdClass|null $updates + * @param stdClass $updateToAdd + * @return stdClass + */ + protected function addUpdateToList($updates, $updateToAdd) { + if ( $this->package->isMuPlugin() ) { + //WP does not support automatic update installation for mu-plugins, but we can + //still display a notice. + $updateToAdd->package = null; + } + return parent::addUpdateToList($updates, $updateToAdd); + } + + /** + * @param stdClass|null $updates + * @return stdClass|null + */ + protected function removeUpdateFromList($updates) { + $updates = parent::removeUpdateFromList($updates); + if ( !empty($this->muPluginFile) && isset($updates, $updates->response) ) { + unset($updates->response[$this->muPluginFile]); + } + return $updates; + } + + /** + * For plugins, the update array is indexed by the plugin filename relative to the "plugins" + * directory. Example: "plugin-name/plugin.php". + * + * @return string + */ + protected function getUpdateListKey() { + if ( $this->package->isMuPlugin() ) { + return $this->muPluginFile; + } + return $this->pluginFile; + } + + protected function getNoUpdateItemFields() { + return array_merge( + parent::getNoUpdateItemFields(), + [ + 'id' => $this->pluginFile, + 'slug' => $this->slug, + 'plugin' => $this->pluginFile, + 'icons' => [], + 'banners' => [], + 'banners_rtl' => [], + 'tested' => '', + 'compatibility' => new stdClass(), + ] + ); + } + + /** + * Alias for isBeingUpgraded(). + * + * @deprecated + * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. + * @return bool + */ + public function isPluginBeingUpgraded($upgrader = null) { + return $this->isBeingUpgraded($upgrader); + } + + /** + * Is there an update being installed for this plugin, right now? + * + * @param WP_Upgrader|null $upgrader + * @return bool + */ + public function isBeingUpgraded($upgrader = null) { + return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader); + } + + /** + * Get the details of the currently available update, if any. + * + * If no updates are available, or if the last known update version is below or equal + * to the currently installed version, this method will return NULL. + * + * Uses cached update data. To retrieve update information straight from + * the metadata URL, call requestUpdate() instead. + * + * @return Lkn_Puc_Plugin_Update|null + */ + public function getUpdate() { + $update = parent::getUpdate(); + if ( isset($update) ) { + /** @var Lkn_Puc_Plugin_Update $update */ + $update->filename = $this->pluginFile; + } + return $update; + } + + /** + * Get the translated plugin title. + * + * @deprecated + * @return string + */ + public function getPluginTitle() { + return $this->package->getPluginTitle(); + } + + /** + * Check if the current user has the required permissions to install updates. + * + * @return bool + */ + public function userCanInstallUpdates() { + return current_user_can('update_plugins'); + } + + /** + * Check if the plugin file is inside the mu-plugins directory. + * + * @deprecated + * @return bool + */ + protected function isMuPlugin() { + return $this->package->isMuPlugin(); + } + + /** + * MU plugins are partially supported, but only when we know which file in mu-plugins + * corresponds to this plugin. + * + * @return bool + */ + protected function isUnknownMuPlugin() { + return empty($this->muPluginFile) && $this->package->isMuPlugin(); + } + + /** + * Get absolute path to the main plugin file. + * + * @return string + */ + public function getAbsolutePath() { + return $this->pluginAbsolutePath; + } + + /** + * Register a callback for filtering query arguments. + * + * The callback function should take one argument - an associative array of query arguments. + * It should return a modified array of query arguments. + * + * @uses add_filter() This method is a convenience wrapper for add_filter(). + * + * @param callable $callback + * @return void + */ + public function addQueryArgFilter($callback) { + $this->addFilter('request_info_query_args', $callback); + } + + /** + * Register a callback for filtering arguments passed to wp_remote_get(). + * + * The callback function should take one argument - an associative array of arguments - + * and return a modified array or arguments. See the WP documentation on wp_remote_get() + * for details on what arguments are available and how they work. + * + * @uses add_filter() This method is a convenience wrapper for add_filter(). + * + * @param callable $callback + * @return void + */ + public function addHttpRequestArgFilter($callback) { + $this->addFilter('request_info_options', $callback); + } + + /** + * Register a callback for filtering the plugin info retrieved from the external API. + * + * The callback function should take two arguments. If the plugin info was retrieved + * successfully, the first argument passed will be an instance of PluginInfo. Otherwise, + * it will be NULL. The second argument will be the corresponding return value of + * wp_remote_get (see WP docs for details). + * + * The callback function should return a new or modified instance of PluginInfo or NULL. + * + * @uses add_filter() This method is a convenience wrapper for add_filter(). + * + * @param callable $callback + * @return void + */ + public function addResultFilter($callback) { + $this->addFilter('request_info_result', $callback, 10, 2); + } + + /** + * Create a package instance that represents this plugin or theme. + * + * @return Lkn_Puc_InstalledPackage + */ + protected function createInstalledPackage() { + return new Lkn_Puc_Plugin_Package($this->pluginAbsolutePath, $this); + } + + /** + * @return Lkn_Puc_Plugin_Package + */ + public function getInstalledPackage() { + return $this->package; + } + } + +endif; diff --git a/packages/plugin-updater/Puc/Scheduler.php b/packages/plugin-updater/Puc/Scheduler.php new file mode 100644 index 000000000..74347c253 --- /dev/null +++ b/packages/plugin-updater/Puc/Scheduler.php @@ -0,0 +1,254 @@ +updateChecker = $updateChecker; + $this->checkPeriod = $checkPeriod; + + //Set up the periodic update checks + $this->cronHook = $this->updateChecker->getUniqueName('cron_check_updates'); + if ( $this->checkPeriod > 0 ) { + //Trigger the check via Cron. + //Try to use one of the default schedules if possible as it's less likely to conflict + //with other plugins and their custom schedules. + $defaultSchedules = [ + 1 => 'hourly', + 12 => 'twicedaily', + 24 => 'daily', + ]; + if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) { + $scheduleName = $defaultSchedules[$this->checkPeriod]; + } else { + //Use a custom cron schedule. + $scheduleName = 'every' . $this->checkPeriod . 'hours'; + add_filter('cron_schedules', [$this, '_addCustomSchedule']); + } + + if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) { + //Randomly offset the schedule to help prevent update server traffic spikes. Without this + //most checks may happen during times of day when people are most likely to install new plugins. + $firstCheckTime = time() - rand(0, max($this->checkPeriod * 3600 - 15 * 60, 1)); + $firstCheckTime = apply_filters( + $this->updateChecker->getUniqueName('first_check_time'), + $firstCheckTime + ); + wp_schedule_event($firstCheckTime, $scheduleName, $this->cronHook); + } + add_action($this->cronHook, [$this, 'maybeCheckForUpdates']); + + //In case Cron is disabled or unreliable, we also manually trigger + //the periodic checks while the user is browsing the Dashboard. + add_action( 'admin_init', [$this, 'maybeCheckForUpdates'] ); + + //Like WordPress itself, we check more often on certain pages. + /** @see wp_update_plugins */ + add_action('load-update-core.php', [$this, 'maybeCheckForUpdates']); + //"load-update.php" and "load-plugins.php" or "load-themes.php". + $this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks); + foreach ($this->hourlyCheckHooks as $hook) { + add_action($hook, [$this, 'maybeCheckForUpdates']); + } + //This hook fires after a bulk update is complete. + add_action('upgrader_process_complete', [$this, 'upgraderProcessComplete'], 11, 2); + } else { + //Periodic checks are disabled. + wp_clear_scheduled_hook($this->cronHook); + } + } + + /** + * Runs upon the WP action upgrader_process_complete. + * + * We look at the parameters to decide whether to call maybeCheckForUpdates() or not. + * We also check if the update checker has been removed by the update. + * + * @param WP_Upgrader $upgrader WP_Upgrader instance + * @param array $upgradeInfo extra information about the upgrade + */ + public function upgraderProcessComplete( + /** @noinspection PhpUnusedParameterInspection */ + $upgrader, $upgradeInfo + ) { + //Cancel all further actions if the current version of PUC has been deleted or overwritten + //by a different version during the upgrade. If we try to do anything more in that situation, + //we could trigger a fatal error by trying to autoload a deleted class. + clearstatcache(); + if ( !file_exists(__FILE__) ) { + $this->removeHooks(); + $this->updateChecker->removeHooks(); + return; + } + + //Sanity check and limitation to relevant types. + if ( + !is_array($upgradeInfo) || !isset($upgradeInfo['type'], $upgradeInfo['action']) + || 'update' !== $upgradeInfo['action'] || !in_array($upgradeInfo['type'], ['plugin', 'theme']) + ) { + return; + } + + if ( is_a($this->updateChecker, 'Lkn_Puc_Plugin_UpdateChecker') ) { + if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) { + return; + } + + //Themes pass in directory names in the information array, but plugins use the relative plugin path. + if ( !in_array( + strtolower($this->updateChecker->directoryName), + array_map('dirname', array_map('strtolower', $upgradeInfo['plugins'])) + ) ) { + return; + } + } + + $this->maybeCheckForUpdates(); + } + + /** + * Check for updates if the configured check interval has already elapsed. + * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron. + * + * You can override the default behaviour by using the "puc_check_now-$slug" filter. + * The filter callback will be passed three parameters: + * - Current decision. TRUE = check updates now, FALSE = don't check now. + * - Last check time as a Unix timestamp. + * - Configured check period in hours. + * Return TRUE to check for updates immediately, or FALSE to cancel. + * + * This method is declared public because it's a hook callback. Calling it directly is not recommended. + */ + public function maybeCheckForUpdates() { + if ( empty($this->checkPeriod) ) { + return; + } + + $state = $this->updateChecker->getUpdateState(); + $shouldCheck = ($state->timeSinceLastCheck() >= $this->getEffectiveCheckPeriod()); + + //Let plugin authors substitute their own algorithm. + $shouldCheck = apply_filters( + $this->updateChecker->getUniqueName('check_now'), + $shouldCheck, + $state->getLastCheck(), + $this->checkPeriod + ); + + if ( $shouldCheck ) { + $this->updateChecker->checkForUpdates(); + } + } + + /** + * Calculate the actual check period based on the current status and environment. + * + * @return int Check period in seconds. + */ + protected function getEffectiveCheckPeriod() { + $currentFilter = current_filter(); + if ( in_array($currentFilter, ['load-update-core.php', 'upgrader_process_complete']) ) { + //Check more often when the user visits "Dashboard -> Updates" or does a bulk update. + $period = 60; + } else { + if ( in_array($currentFilter, $this->hourlyCheckHooks) ) { + //Also check more often on /wp-admin/update.php and the "Plugins" or "Themes" page. + $period = 3600; + } else { + if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) { + //Check less frequently if it's already known that an update is available. + $period = $this->throttledCheckPeriod * 3600; + } else { + if ( defined('DOING_CRON') && constant('DOING_CRON') ) { + //WordPress cron schedules are not exact, so lets do an update check even + //if slightly less than $checkPeriod hours have elapsed since the last check. + $cronFuzziness = 20 * 60; + $period = $this->checkPeriod * 3600 - $cronFuzziness; + } else { + $period = $this->checkPeriod * 3600; + } + } + } + } + + return $period; + } + + /** + * Add our custom schedule to the array of Cron schedules used by WP. + * + * @param array $schedules + * @return array + */ + public function _addCustomSchedule($schedules) { + if ( $this->checkPeriod && ($this->checkPeriod > 0) ) { + $scheduleName = 'every' . $this->checkPeriod . 'hours'; + $schedules[$scheduleName] = [ + 'interval' => $this->checkPeriod * 3600, + 'display' => sprintf('Every %d hours', $this->checkPeriod), + ]; + } + return $schedules; + } + + /** + * Remove the scheduled cron event that the library uses to check for updates. + * + * @return void + */ + public function removeUpdaterCron() { + wp_clear_scheduled_hook($this->cronHook); + } + + /** + * Get the name of the update checker's WP-cron hook. Mostly useful for debugging. + * + * @return string + */ + public function getCronHookName() { + return $this->cronHook; + } + + /** + * Remove most hooks added by the scheduler. + */ + public function removeHooks() { + remove_filter('cron_schedules', [$this, '_addCustomSchedule']); + remove_action('admin_init', [$this, 'maybeCheckForUpdates']); + remove_action('load-update-core.php', [$this, 'maybeCheckForUpdates']); + + if ( $this->cronHook !== null ) { + remove_action($this->cronHook, [$this, 'maybeCheckForUpdates']); + } + if ( !empty($this->hourlyCheckHooks) ) { + foreach ($this->hourlyCheckHooks as $hook) { + remove_action($hook, [$this, 'maybeCheckForUpdates']); + } + } + } + } + +endif; diff --git a/packages/plugin-updater/Puc/StateStore.php b/packages/plugin-updater/Puc/StateStore.php new file mode 100644 index 000000000..53008324c --- /dev/null +++ b/packages/plugin-updater/Puc/StateStore.php @@ -0,0 +1,220 @@ +optionName = $optionName; + } + + /** + * Get time elapsed since the last update check. + * + * If there are no recorded update checks, this method returns a large arbitrary number + * (i.e. time since the Unix epoch). + * + * @return int Elapsed time in seconds. + */ + public function timeSinceLastCheck() { + $this->lazyLoad(); + return time() - $this->lastCheck; + } + + /** + * @return int + */ + public function getLastCheck() { + $this->lazyLoad(); + return $this->lastCheck; + } + + /** + * Set the time of the last update check to the current timestamp. + * + * @return $this + */ + public function setLastCheckToNow() { + $this->lazyLoad(); + $this->lastCheck = time(); + return $this; + } + + /** + * @return null|Lkn_Puc_Update + */ + public function getUpdate() { + $this->lazyLoad(); + return $this->update; + } + + /** + * @param Lkn_Puc_Update|null $update + * @return $this + */ + public function setUpdate(Lkn_Puc_Update $update = null) { + $this->lazyLoad(); + $this->update = $update; + return $this; + } + + /** + * @return string + */ + public function getCheckedVersion() { + $this->lazyLoad(); + return $this->checkedVersion; + } + + /** + * @param string $version + * @return $this + */ + public function setCheckedVersion($version) { + $this->lazyLoad(); + $this->checkedVersion = strval($version); + return $this; + } + + /** + * Get translation updates. + * + * @return array + */ + public function getTranslations() { + $this->lazyLoad(); + if ( isset($this->update, $this->update->translations) ) { + return $this->update->translations; + } + return []; + } + + /** + * Set translation updates. + * + * @param array $translationUpdates + */ + public function setTranslations($translationUpdates) { + $this->lazyLoad(); + if ( isset($this->update) ) { + $this->update->translations = $translationUpdates; + $this->save(); + } + } + + /** + * Saves the updated state of the plugin on the database + */ + public function save() { + $state = new stdClass(); + + $state->lastCheck = $this->lastCheck; + $state->checkedVersion = $this->checkedVersion; + + if ( isset($this->update)) { + $state->update = $this->update->toStdClass(); + + $updateClass = get_class($this->update); + $state->updateClass = $updateClass; + $prefix = $this->getLibPrefix(); + if ( Lkn_Puc_Utils::startsWith($updateClass, $prefix) ) { + $state->updateBaseClass = substr($updateClass, strlen($prefix)); + } + } + + update_site_option($this->optionName, $state); + $this->isLoaded = true; + } + + /** + * Checks if the database already has a state + * + * @return $this + */ + public function lazyLoad() { + if ( !$this->isLoaded ) { + $this->load(); + } + return $this; + } + + /** + * Load the state version + */ + protected function load() { + $this->isLoaded = true; + + $state = get_site_option($this->optionName, null); + + if ( !is_object($state) ) { + $this->lastCheck = 0; + $this->checkedVersion = ''; + $this->update = null; + return; + } + + $this->lastCheck = intval(Lkn_Puc_Utils::get($state, 'lastCheck', 0)); + $this->checkedVersion = Lkn_Puc_Utils::get($state, 'checkedVersion', ''); + $this->update = null; + + if ( isset($state->update) ) { + //This mess is due to the fact that the want the update class from this version + //of the library, not the version that saved the update. + + $updateClass = null; + if ( isset($state->updateBaseClass) ) { + $updateClass = $this->getLibPrefix() . $state->updateBaseClass; + } else { + if ( isset($state->updateClass) && class_exists($state->updateClass) ) { + $updateClass = $state->updateClass; + } + } + + if ( $updateClass !== null ) { + $this->update = call_user_func([$updateClass, 'fromObject'], $state->update); + } + } + } + + /** + * Delete the option name from database + */ + public function delete() { + delete_site_option($this->optionName); + + $this->lastCheck = 0; + $this->checkedVersion = ''; + $this->update = null; + } + + private function getLibPrefix() { + $parts = explode('_', __CLASS__, 3); + return $parts[0] . '_' . $parts[1] . '_'; + } + } + +endif; diff --git a/packages/plugin-updater/Puc/Update.php b/packages/plugin-updater/Puc/Update.php new file mode 100644 index 000000000..c8ad6baab --- /dev/null +++ b/packages/plugin-updater/Puc/Update.php @@ -0,0 +1,37 @@ +slug = $this->slug; + $update->new_version = $this->version; + $update->package = $this->download_url; + + return $update; + } + } + +endif; diff --git a/packages/plugin-updater/Puc/UpdateChecker.php b/packages/plugin-updater/Puc/UpdateChecker.php new file mode 100644 index 000000000..d0c6b10f3 --- /dev/null +++ b/packages/plugin-updater/Puc/UpdateChecker.php @@ -0,0 +1,949 @@ +debugMode = (bool)(constant('WP_DEBUG')); + $this->metadataUrl = $metadataUrl; + $this->directoryName = $directoryName; + $this->slug = !empty($slug) ? $slug : $this->directoryName; + + $this->optionName = $optionName; + if ( empty($this->optionName) ) { + //BC: Initially the library only supported plugin updates and didn't use type prefixes + //in the option name. Lets use the same prefix-less name when possible. + if ( $this->filterSuffix === '' ) { + $this->optionName = 'external_updates-' . $this->slug; + } else { + $this->optionName = $this->getUniqueName('external_updates'); + } + } + + $this->package = $this->createInstalledPackage(); + $this->scheduler = $this->createScheduler($checkPeriod); + $this->upgraderStatus = new Lkn_Puc_UpgraderStatus(); + $this->updateState = new Lkn_Puc_StateStore($this->optionName); + + if ( did_action('init') ) { + $this->loadTextDomain(); + } else { + add_action('init', [$this, 'loadTextDomain']); + } + + $this->installHooks(); + } + + /** + * @internal + */ + public function loadTextDomain() { + //We're not using load_plugin_textdomain() or its siblings because figuring out where + //the library is located (plugin, mu-plugin, theme, custom wp-content paths) is messy. + $domain = 'plugin-update-checker'; + $locale = apply_filters( + 'plugin_locale', + (is_admin() && function_exists('get_user_locale')) ? get_user_locale() : get_locale(), + $domain + ); + + $moFile = $domain . '-' . $locale . '.mo'; + $path = realpath(dirname(__FILE__) . '/../languages'); + + if ($path && file_exists($path)) { + load_textdomain($domain, $path . '/' . $moFile); + } + } + + protected function installHooks() { + //Insert our update info into the update array maintained by WP. + add_filter('site_transient_' . $this->updateTransient, [$this, 'injectUpdate']); + + //Insert translation updates into the update list. + add_filter('site_transient_' . $this->updateTransient, [$this, 'injectTranslationUpdates']); + + //Clear translation updates when WP clears the update cache. + //This needs to be done directly because the library doesn't actually remove obsolete plugin updates, + //it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O. + add_action( + 'delete_site_transient_' . $this->updateTransient, + [$this, 'clearCachedTranslationUpdates'] + ); + + //Rename the update directory to be the same as the existing directory. + if ( $this->directoryName !== '.' ) { + add_filter('upgrader_source_selection', [$this, 'fixDirectoryName'], 10, 3); + } + + //Allow HTTP requests to the metadata URL even if it's on a local host. + add_filter('http_request_host_is_external', [$this, 'allowMetadataHost'], 10, 2); + } + + /** + * Remove hooks that were added by this update checker instance. + */ + public function removeHooks() { + remove_filter('site_transient_' . $this->updateTransient, [$this, 'injectUpdate']); + remove_filter('site_transient_' . $this->updateTransient, [$this, 'injectTranslationUpdates']); + remove_action( + 'delete_site_transient_' . $this->updateTransient, + [$this, 'clearCachedTranslationUpdates'] + ); + + remove_filter('upgrader_source_selection', [$this, 'fixDirectoryName'], 10); + remove_filter('http_request_host_is_external', [$this, 'allowMetadataHost'], 10); + + remove_action('init', [$this, 'loadTextDomain']); + + if ( $this->scheduler ) { + $this->scheduler->removeHooks(); + } + } + + /** + * Check if the current user has the required permissions to install updates. + * + * @return bool + */ + abstract public function userCanInstallUpdates(); + + /** + * Explicitly allow HTTP requests to the metadata URL. + * + * WordPress has a security feature where the HTTP API will reject all requests that are sent to + * another site hosted on the same server as the current site (IP match), a local host, or a local + * IP, unless the host exactly matches the current site. + * + * This feature is opt-in (at least in WP 4.4). Apparently some people enable it. + * + * That can be a problem when you're developing your plugin and you decide to host the update information + * on the same server as your test site. Update requests will mysteriously fail. + * + * We fix that by adding an exception for the metadata host. + * + * @param bool $allow + * @param string $host + * @return bool + */ + public function allowMetadataHost($allow, $host) { + if ( $this->cachedMetadataHost === 0 ) { + $this->cachedMetadataHost = parse_url($this->metadataUrl, PHP_URL_HOST); + } + + if ( is_string($this->cachedMetadataHost) && (strtolower($host) === strtolower($this->cachedMetadataHost)) ) { + return true; + } + return $allow; + } + + /** + * Create a package instance that represents this plugin or theme. + * + * @return Lkn_Puc_InstalledPackage + */ + abstract protected function createInstalledPackage(); + + /** + * @return Lkn_Puc_InstalledPackage + */ + public function getInstalledPackage() { + return $this->package; + } + + /** + * Create an instance of the scheduler. + * + * This is implemented as a method to make it possible for plugins to subclass the update checker + * and substitute their own scheduler. + * + * @param int $checkPeriod + * @return Lkn_Puc_Scheduler + */ + abstract protected function createScheduler($checkPeriod); + + /** + * Check for updates. The results are stored in the DB option specified in $optionName. + * + * @return Lkn_Puc_Update|null + */ + public function checkForUpdates() { + $installedVersion = $this->getInstalledVersion(); + //Fail silently if we can't find the plugin/theme or read its header. + if ( $installedVersion === null ) { + $this->triggerError( + sprintf('Skipping update check for %s - installed version unknown.', $this->slug), + E_USER_WARNING + ); + return null; + } + + //Start collecting API errors. + $this->lastRequestApiErrors = []; + add_action('puc_api_error', [$this, 'collectApiErrors'], 10, 4); + + $state = $this->updateState; + $state->setLastCheckToNow() + ->setCheckedVersion($installedVersion) + ->save(); //Save before checking in case something goes wrong + + $state->setUpdate($this->requestUpdate()); + $state->save(); + + //Stop collecting API errors. + remove_action('puc_api_error', [$this, 'collectApiErrors'], 10); + + return $this->getUpdate(); + } + + /** + * Load the update checker state from the DB. + * + * @return Lkn_Puc_StateStore + */ + public function getUpdateState() { + return $this->updateState->lazyLoad(); + } + + /** + * Reset update checker state - i.e. last check time, cached update data and so on. + * + * Call this when your plugin is being uninstalled, or if you want to + * clear the update cache. + */ + public function resetUpdateState() { + $this->updateState->delete(); + } + + /** + * Get the details of the currently available update, if any. + * + * If no updates are available, or if the last known update version is below or equal + * to the currently installed version, this method will return NULL. + * + * Uses cached update data. To retrieve update information straight from + * the metadata URL, call requestUpdate() instead. + * + * @return Lkn_Puc_Update|null + */ + public function getUpdate() { + $update = $this->updateState->getUpdate(); + + //Is there an update available? + if ( isset($update) ) { + //Check if the update is actually newer than the currently installed version. + $installedVersion = $this->getInstalledVersion(); + if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ) { + return $update; + } + } + return null; + } + + /** + * Retrieve the latest update (if any) from the configured API endpoint. + * + * Subclasses should run the update through filterUpdateResult before returning it. + * + * @return Lkn_Puc_Update An instance of Update, or NULL when no updates are available. + */ + abstract public function requestUpdate(); + + /** + * Filter the result of a requestUpdate() call. + * + * @param Lkn_Puc_Update|null $update + * @param array|WP_Error|null $httpResult The value returned by wp_remote_get(), if any. + * @return Lkn_Puc_Update + */ + protected function filterUpdateResult($update, $httpResult = null) { + //Let plugins/themes modify the update. + $update = apply_filters($this->getUniqueName('request_update_result'), $update, $httpResult); + + $this->fixSupportedWordpressVersion($update); + + if ( isset($update, $update->translations) ) { + //Keep only those translation updates that apply to this site. + $update->translations = $this->filterApplicableTranslations($update->translations); + } + + return $update; + } + + /** + * The "Tested up to" field in the plugin metadata is supposed to be in the form of "major.minor", + * while WordPress core's list_plugin_updates() expects the $update->tested field to be an exact + * version, e.g. "major.minor.patch", to say it's compatible. In other case it shows + * "Compatibility: Unknown". + * The function mimics how wordpress.org API crafts the "tested" field out of "Tested up to". + * + * @param Lkn_Puc_Metadata|null $update + */ + protected function fixSupportedWordpressVersion(Lkn_Puc_Metadata $update = null) { + if ( !isset($update->tested) || !preg_match('/^\d++\.\d++$/', $update->tested) ) { + return; + } + + $actualWpVersions = []; + + $wpVersion = $GLOBALS['wp_version']; + + if ( function_exists('get_core_updates') ) { + $coreUpdates = get_core_updates(); + if ( is_array($coreUpdates) ) { + foreach ($coreUpdates as $coreUpdate) { + if ( isset($coreUpdate->current) ) { + $actualWpVersions[] = $coreUpdate->current; + } + } + } + } + + $actualWpVersions[] = $wpVersion; + + $actualWpPatchNumber = null; + foreach ($actualWpVersions as $version) { + if ( preg_match('/^(?P\d++\.\d++)(?:\.(?P\d++))?/', $version, $versionParts) ) { + if ( $versionParts['majorMinor'] === $update->tested ) { + $patch = isset($versionParts['patch']) ? intval($versionParts['patch']) : 0; + if ( $actualWpPatchNumber === null ) { + $actualWpPatchNumber = $patch; + } else { + $actualWpPatchNumber = max($actualWpPatchNumber, $patch); + } + } + } + } + if ( $actualWpPatchNumber === null ) { + $actualWpPatchNumber = 999; + } + + if ( $actualWpPatchNumber > 0 ) { + $update->tested .= '.' . $actualWpPatchNumber; + } + } + + /** + * Get the currently installed version of the plugin or theme. + * + * @return string|null Version number. + */ + public function getInstalledVersion() { + return $this->package->getInstalledVersion(); + } + + /** + * Get the full path of the plugin or theme directory. + * + * @return string + */ + public function getAbsoluteDirectoryPath() { + return $this->package->getAbsoluteDirectoryPath(); + } + + /** + * Trigger a PHP error, but only when $debugMode is enabled. + * + * @param string $message + * @param int $errorType + */ + public function triggerError($message, $errorType) { + if ( $this->isDebugModeEnabled() ) { + trigger_error($message, $errorType); + } + } + + /** + * @return bool + */ + protected function isDebugModeEnabled() { + if ( $this->debugMode === null ) { + $this->debugMode = (bool)(constant('WP_DEBUG')); + } + return $this->debugMode; + } + + /** + * Get the full name of an update checker filter, action or DB entry. + * + * This method adds the "puc_" prefix and the "-$slug" suffix to the filter name. + * For example, "pre_inject_update" becomes "puc_pre_inject_update-plugin-slug". + * + * @param string $baseTag + * @return string + */ + public function getUniqueName($baseTag) { + $name = 'puc_' . $baseTag; + if ( $this->filterSuffix !== '' ) { + $name .= '_' . $this->filterSuffix; + } + return $name . '-' . $this->slug; + } + + /** + * Store API errors that are generated when checking for updates. + * + * @internal + * @param WP_Error $error + * @param array|null $httpResponse + * @param string|null $url + * @param string|null $slug + */ + public function collectApiErrors($error, $httpResponse = null, $url = null, $slug = null) { + if ( isset($slug) && ($slug !== $this->slug) ) { + return; + } + + $this->lastRequestApiErrors[] = [ + 'error' => $error, + 'httpResponse' => $httpResponse, + 'url' => $url, + ]; + } + + /** + * @return array + */ + public function getLastRequestApiErrors() { + return $this->lastRequestApiErrors; + } + + /* ------------------------------------------------------------------- + * PUC filters and filter utilities + * ------------------------------------------------------------------- + */ + + /** + * Register a callback for one of the update checker filters. + * + * Identical to add_filter(), except it automatically adds the "puc_" prefix + * and the "-$slug" suffix to the filter name. For example, "request_info_result" + * becomes "puc_request_info_result-your_plugin_slug". + * + * @param string $tag + * @param callable $callback + * @param int $priority + * @param int $acceptedArgs + */ + public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) { + add_filter($this->getUniqueName($tag), $callback, $priority, $acceptedArgs); + } + + /* ------------------------------------------------------------------- + * Inject updates + * ------------------------------------------------------------------- + */ + + /** + * Insert the latest update (if any) into the update list maintained by WP. + * + * @param stdClass $updates Update list. + * @return stdClass Modified update list. + */ + public function injectUpdate($updates) { + //Is there an update to insert? + $update = $this->getUpdate(); + + if ( !$this->shouldShowUpdates() ) { + $update = null; + } + + if ( !empty($update) ) { + //Let plugins update is passed to WordPress. + $updates = $this->addUpdateToList($updates, $update->toWpFormat()); + } else { + //Clean up any stale update info. + $updates = $this->removeUpdateFromList($updates); + //Add a placeholder item to the "no_update" list to enable auto-update support. + //If we don't do this, the option to enable automatic updates will only show up + //when an update is available. + $updates = $this->addNoUpdateItem($updates); + } + + return $updates; + } + + /** + * @param stdClass|null $updates + * @param stdClass|array $updateToAdd + * @return stdClass + */ + protected function addUpdateToList($updates, $updateToAdd) { + if ( !is_object($updates) ) { + $updates = new stdClass(); + $updates->response = []; + } + + $updates->response[$this->getUpdateListKey()] = $updateToAdd; + return $updates; + } + + /** + * @param stdClass|null $updates + * @return stdClass|null + */ + protected function removeUpdateFromList($updates) { + if ( isset($updates, $updates->response) ) { + unset($updates->response[$this->getUpdateListKey()]); + } + return $updates; + } + + /** + * See this post for more information: + * @link https://make.wordpress.org/core/2020/07/30/recommended-usage-of-the-updates-api-to-support-the-auto-updates-ui-for-plugins-and-themes-in-wordpress-5-5/ + * + * @param stdClass|null $updates + * @return stdClass + */ + protected function addNoUpdateItem($updates) { + if ( !is_object($updates) ) { + $updates = new stdClass(); + $updates->response = []; + $updates->no_update = []; + } else { + if ( !isset($updates->no_update) ) { + $updates->no_update = []; + } + } + + $updates->no_update[$this->getUpdateListKey()] = (object) $this->getNoUpdateItemFields(); + + return $updates; + } + + /** + * Subclasses should override this method to add fields that are specific to plugins or themes. + * @return array + */ + protected function getNoUpdateItemFields() { + return [ + 'new_version' => $this->getInstalledVersion(), + 'url' => '', + 'package' => '', + 'requires_php' => '', + ]; + } + + /** + * Get the key that will be used when adding updates to the update list that's maintained + * by the WordPress core. The list is always an associative array, but the key is different + * for plugins and themes. + * + * @return string + */ + abstract protected function getUpdateListKey(); + + /** + * Should we show available updates? + * + * Usually the answer is "yes", but there are exceptions. For example, WordPress doesn't + * support automatic updates installation for mu-plugins, so PUC usually won't show update + * notifications in that case. See the plugin-specific subclass for details. + * + * Note: This method only applies to updates that are displayed (or not) in the WordPress + * admin. It doesn't affect APIs like requestUpdate and getUpdate. + * + * @return bool + */ + protected function shouldShowUpdates() { + return true; + } + + /* ------------------------------------------------------------------- + * JSON-based update API + * ------------------------------------------------------------------- + */ + + /** + * Retrieve plugin or theme metadata from the JSON document at $this->metadataUrl. + * + * @param string $metaClass Parse the JSON as an instance of this class. It must have a static fromJson method. + * @param array $queryArgs Additional query arguments. + * @return array [Lkn_Puc_Metadata|null, array|WP_Error] A metadata instance and the value returned by wp_remote_get(). + */ + protected function requestMetadata($metaClass, $queryArgs = []) { + //Query args to append to the URL. + $queryArgs = array_merge( + [ + 'installed_version' => strval($this->getInstalledVersion()), + 'php' => phpversion(), + 'locale' => get_locale(), + 's' => '4823a0e58074af39154f19e3de1f7443', + ], + $queryArgs + ); + + //Various options for the wp_remote_get() call. + $options = [ + 'timeout' => 10, //seconds + 'headers' => [ + 'Accept' => 'application/json', + ], + ]; + + //The metadata file should be at 'http://your-api.com/url/here/$slug/info.json' + $url = $this->metadataUrl; + if ( !empty($queryArgs) ) { + $url = add_query_arg($queryArgs, $url); + } + + $result = wp_remote_get($url, $options); + + //Try to parse the response + $status = $this->validateApiResponse($result); + $metadata = null; + if ( !is_wp_error($status) ) { + if ( version_compare(PHP_VERSION, '5.3', '>=') && (strpos($metaClass, '\\') === false) ) { + $metaClass = __NAMESPACE__ . '\\' . $metaClass; + } + $metadata = call_user_func([$metaClass, 'fromJson'], $result['body']); + } else { + do_action('puc_api_error', $status, $result, $url, $this->slug); + $this->triggerError( + sprintf('The URL %s does not point to a valid metadata file. ', $url) + . $status->get_error_message(), + E_USER_WARNING + ); + } + + return [$metadata, $result]; + } + + /** + * Check if $result is a successful update API response. + * + * @param array|WP_Error $result + * @return true|WP_Error + */ + protected function validateApiResponse($result) { + if ( is_wp_error($result) ) { /** @var WP_Error $result */ + return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message()); + } + + if ( !isset($result['response']['code']) ) { + return new WP_Error( + 'puc_no_response_code', + 'wp_remote_get() returned an unexpected result.' + ); + } + + if ( $result['response']['code'] !== 200 ) { + return new WP_Error( + 'puc_unexpected_response_code', + 'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)' + ); + } + + if ( empty($result['body']) ) { + return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.'); + } + + return true; + } + + /* ------------------------------------------------------------------- + * Language packs / Translation updates + * ------------------------------------------------------------------- + */ + + /** + * Filter a list of translation updates and return a new list that contains only updates + * that apply to the current site. + * + * @param array $translations + * @return array + */ + protected function filterApplicableTranslations($translations) { + $languages = array_flip(array_values(get_available_languages())); + $installedTranslations = $this->getInstalledTranslations(); + + $applicableTranslations = []; + foreach ($translations as $translation) { + //Does it match one of the available core languages? + $isApplicable = array_key_exists($translation->language, $languages); + //Is it more recent than an already-installed translation? + if ( isset($installedTranslations[$translation->language]) ) { + $updateTimestamp = strtotime($translation->updated); + $installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']); + $isApplicable = $updateTimestamp > $installedTimestamp; + } + + if ( $isApplicable ) { + $applicableTranslations[] = $translation; + } + } + + return $applicableTranslations; + } + + /** + * Get a list of installed translations for this plugin or theme. + * + * @return array + */ + protected function getInstalledTranslations() { + if ( !function_exists('wp_get_installed_translations') ) { + return []; + } + $installedTranslations = wp_get_installed_translations($this->translationType . 's'); + if ( isset($installedTranslations[$this->directoryName]) ) { + $installedTranslations = $installedTranslations[$this->directoryName]; + } else { + $installedTranslations = []; + } + return $installedTranslations; + } + + /** + * Insert translation updates into the list maintained by WordPress. + * + * @param stdClass $updates + * @return stdClass + */ + public function injectTranslationUpdates($updates) { + $translationUpdates = $this->getTranslationUpdates(); + if ( empty($translationUpdates) ) { + return $updates; + } + + //Being defensive. + if ( !is_object($updates) ) { + $updates = new stdClass(); + } + if ( !isset($updates->translations) ) { + $updates->translations = []; + } + + //In case there's a name collision with a plugin or theme hosted on wordpress.org, + //remove any preexisting updates that match our thing. + $updates->translations = array_values(array_filter( + $updates->translations, + [$this, 'isNotMyTranslation'] + )); + + //Add our updates to the list. + foreach ($translationUpdates as $update) { + $convertedUpdate = array_merge( + [ + 'type' => $this->translationType, + 'slug' => $this->directoryName, + 'autoupdate' => 0, + //AFAICT, WordPress doesn't actually use the "version" field for anything. + //But lets make sure it's there, just in case. + 'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)), + ], + (array)$update + ); + + $updates->translations[] = $convertedUpdate; + } + + return $updates; + } + + /** + * Get a list of available translation updates. + * + * This method will return an empty array if there are no updates. + * Uses cached update data. + * + * @return array + */ + public function getTranslationUpdates() { + return $this->updateState->getTranslations(); + } + + /** + * Remove all cached translation updates. + * + * @see wp_clean_update_cache + */ + public function clearCachedTranslationUpdates() { + $this->updateState->setTranslations([]); + } + + /** + * Filter callback. Keeps only translations that *don't* match this plugin or theme. + * + * @param array $translation + * @return bool + */ + protected function isNotMyTranslation($translation) { + $isMatch = isset($translation['type'], $translation['slug']) + && ($translation['type'] === $this->translationType) + && ($translation['slug'] === $this->directoryName); + + return !$isMatch; + } + + /* ------------------------------------------------------------------- + * Fix directory name when installing updates + * ------------------------------------------------------------------- + */ + + /** + * Rename the update directory to match the existing plugin/theme directory. + * + * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain + * exactly one directory, and that the directory name will be the same as the directory where + * the plugin or theme is currently installed. + * + * GitHub and other repositories provide ZIP downloads, but they often use directory names like + * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder. + * + * This is a hook callback. Don't call it from a plugin. + * + * @access protected + * + * @param string $source The directory to copy to /wp-content/plugins or /wp-content/themes. Usually a subdirectory of $remoteSource. + * @param string $remoteSource WordPress has extracted the update to this directory. + * @param WP_Upgrader $upgrader + * @return string|WP_Error + */ + public function fixDirectoryName($source, $remoteSource, $upgrader) { + global $wp_filesystem; + /** @var WP_Filesystem_Base $wp_filesystem */ + + //Basic sanity checks. + if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) { + return $source; + } + + //If WordPress is upgrading anything other than our plugin/theme, leave the directory name unchanged. + if ( !$this->isBeingUpgraded($upgrader) ) { + return $source; + } + + //Rename the source to match the existing directory. + $correctedSource = trailingslashit($remoteSource) . $this->directoryName . '/'; + if ( $source !== $correctedSource ) { + //The update archive should contain a single directory that contains the rest of plugin/theme files. + //Otherwise, WordPress will try to copy the entire working directory ($source == $remoteSource). + //We can't rename $remoteSource because that would break WordPress code that cleans up temporary files + //after update. + if ( $this->isBadDirectoryStructure($remoteSource) ) { + return new WP_Error( + 'puc-incorrect-directory-structure', + sprintf( + 'The directory structure of the update is incorrect. All files should be inside ' . + 'a directory named %s, not at the root of the ZIP archive.', + htmlentities($this->slug) + ) + ); + } + + /** @var WP_Upgrader_Skin $upgrader ->skin */ + $upgrader->skin->feedback(sprintf( + 'Renaming %s to %s…', + '' . basename($source) . '', + '' . $this->directoryName . '' + )); + + if ( $wp_filesystem->move($source, $correctedSource, true) ) { + $upgrader->skin->feedback('Directory successfully renamed.'); + return $correctedSource; + } else { + return new WP_Error( + 'puc-rename-failed', + 'Unable to rename the update to match the existing directory.' + ); + } + } + + return $source; + } + + /** + * Is there an update being installed right now, for this plugin or theme? + * + * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. + * @return bool + */ + abstract public function isBeingUpgraded($upgrader = null); + + /** + * Check for incorrect update directory structure. An update must contain a single directory, + * all other files should be inside that directory. + * + * @param string $remoteSource Directory path. + * @return bool + */ + protected function isBadDirectoryStructure($remoteSource) { + global $wp_filesystem; + /** @var WP_Filesystem_Base $wp_filesystem */ + + $sourceFiles = $wp_filesystem->dirlist($remoteSource); + if ( is_array($sourceFiles) ) { + $sourceFiles = array_keys($sourceFiles); + $firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0]; + return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath)); + } + + //Assume it's fine. + return false; + } + } + +endif; diff --git a/packages/plugin-updater/Puc/UpgraderStatus.php b/packages/plugin-updater/Puc/UpgraderStatus.php new file mode 100644 index 000000000..2b7153fb1 --- /dev/null +++ b/packages/plugin-updater/Puc/UpgraderStatus.php @@ -0,0 +1,176 @@ +isBeingUpgraded('plugin', $pluginFile, $upgrader); + } + + /** + * Check if a specific theme or plugin is being upgraded. + * + * @param string $type + * @param string $id + * @param Plugin_Upgrader|WP_Upgrader|null $upgrader + * @return bool + */ + protected function isBeingUpgraded($type, $id, $upgrader = null) { + if ( isset($upgrader) ) { + list($currentType, $currentId) = $this->getThingBeingUpgradedBy($upgrader); + if ( $currentType !== null ) { + $this->currentType = $currentType; + $this->currentId = $currentId; + } + } + return ($this->currentType === $type) && ($this->currentId === $id); + } + + /** + * Figure out which theme or plugin is being upgraded by a WP_Upgrader instance. + * + * Returns an array with two items. The first item is the type of the thing that's being + * upgraded: "plugin" or "theme". The second item is either the plugin basename or + * the theme directory name. If we can't determine what the upgrader is doing, both items + * will be NULL. + * + * Examples: + * ['plugin', 'plugin-dir-name/plugin.php'] + * ['theme', 'theme-dir-name'] + * + * @param Plugin_Upgrader|WP_Upgrader $upgrader + * @return array + */ + private function getThingBeingUpgradedBy($upgrader) { + if ( !isset($upgrader, $upgrader->skin) ) { + return [null, null]; + } + + //Figure out which plugin or theme is being upgraded. + $pluginFile = null; + + $skin = $upgrader->skin; + if ( $skin instanceof Plugin_Upgrader_Skin ) { + if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) { + $pluginFile = $skin->plugin; + } + } elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) { + //This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin + //filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can + //do is compare those headers to the headers of installed plugins. + $pluginFile = $this->identifyPluginByHeaders($skin->plugin_info); + } + + if ( $pluginFile !== null ) { + return ['plugin', $pluginFile]; + } + return [null, null]; + } + + /** + * Identify an installed plugin based on its headers. + * + * @param array $searchHeaders The plugin file header to look for. + * @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin. + */ + private function identifyPluginByHeaders($searchHeaders) { + if ( !function_exists('get_plugins') ) { + /** @noinspection PhpIncludeInspection */ + require_once ABSPATH . '/wp-admin/includes/plugin.php'; + } + + $installedPlugins = get_plugins(); + $matches = []; + foreach ($installedPlugins as $pluginBasename => $headers) { + $diff1 = array_diff_assoc($headers, $searchHeaders); + $diff2 = array_diff_assoc($searchHeaders, $headers); + if ( empty($diff1) && empty($diff2) ) { + $matches[] = $pluginBasename; + } + } + + //It's possible (though very unlikely) that there could be two plugins with identical + //headers. In that case, we can't unambiguously identify the plugin that's being upgraded. + if ( count($matches) !== 1 ) { + return null; + } + + return reset($matches); + } + + /** + * @access private + * + * @param mixed $input + * @param array $hookExtra + * @return mixed Returns $input unaltered. + */ + public function setUpgradedThing($input, $hookExtra) { + if ( !empty($hookExtra['plugin']) && is_string($hookExtra['plugin']) ) { + $this->currentId = $hookExtra['plugin']; + $this->currentType = 'plugin'; + } else { + $this->currentType = null; + $this->currentId = null; + } + return $input; + } + + /** + * @access private + * + * @param array $options + * @return array + */ + public function setUpgradedPluginFromOptions($options) { + if ( isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin']) ) { + $this->currentType = 'plugin'; + $this->currentId = $options['hook_extra']['plugin']; + } else { + $this->currentType = null; + $this->currentId = null; + } + return $options; + } + + /** + * @access private + * + * @param mixed $input + * @return mixed Returns $input unaltered. + */ + public function clearUpgradedThing($input = null) { + $this->currentId = null; + $this->currentType = null; + return $input; + } + } + +endif; diff --git a/packages/plugin-updater/Puc/Utils.php b/packages/plugin-updater/Puc/Utils.php new file mode 100644 index 000000000..faed21f24 --- /dev/null +++ b/packages/plugin-updater/Puc/Utils.php @@ -0,0 +1,71 @@ +$node) ) { + $currentValue = $currentValue->$node; + } else { + return $default; + } + } + } + + return $currentValue; + } + + /** + * Get the first array element that is not empty. + * + * @param array $values + * @param mixed|null $default Returns this value if there are no non-empty elements. + * @return mixed|null + */ + public static function findNotEmpty($values, $default = null) { + if ( empty($values) ) { + return $default; + } + + foreach ($values as $value) { + if ( !empty($value) ) { + return $value; + } + } + + return $default; + } + + /** + * Check if the input string starts with the specified prefix. + * + * @param string $input + * @param string $prefix + * @return bool + */ + public static function startsWith($input, $prefix) { + $length = strlen($prefix); + return (substr($input, 0, $length) === $prefix); + } + } + +endif; diff --git a/packages/plugin-updater/languages/plugin-update-checker-ca.mo b/packages/plugin-updater/languages/plugin-update-checker-ca.mo new file mode 100644 index 000000000..59645faba Binary files /dev/null and b/packages/plugin-updater/languages/plugin-update-checker-ca.mo differ diff --git a/packages/plugin-updater/languages/plugin-update-checker-ca.po b/packages/plugin-updater/languages/plugin-update-checker-ca.po new file mode 100644 index 000000000..36f3ad703 --- /dev/null +++ b/packages/plugin-updater/languages/plugin-update-checker-ca.po @@ -0,0 +1,48 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2017-11-24 17:02+0200\n" +"PO-Revision-Date: 2019-09-25 18:15+0200\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.2.3\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"Last-Translator: \n" +"Language: ca\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p3/Plugin/UpdateChecker.php:395 +msgid "Check for updates" +msgstr "Comprova si hi ha actualitzacions" + +#: Puc/v4p3/Plugin/UpdateChecker.php:548 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "L’extensió %s està actualitzada." + +#: Puc/v4p3/Plugin/UpdateChecker.php:550 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "Una nova versió de l’extensió %s està disponible." + +#: Puc/v4p3/Plugin/UpdateChecker.php:552 +#, php-format +msgctxt "the plugin title" +msgid "Could not determine if updates are available for %s." +msgstr "No s’ha pogut determinar si hi ha actualitzacions per a %s." + +#: Puc/v4p3/Plugin/UpdateChecker.php:558 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Estat del comprovador d’actualitzacions desconegut \"%s\"" + +#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95 +msgid "There is no changelog available." +msgstr "No hi ha cap registre de canvis disponible." diff --git a/packages/plugin-updater/languages/plugin-update-checker-pt_BR.mo b/packages/plugin-updater/languages/plugin-update-checker-pt_BR.mo new file mode 100644 index 000000000..d1c0f2832 Binary files /dev/null and b/packages/plugin-updater/languages/plugin-update-checker-pt_BR.mo differ diff --git a/packages/plugin-updater/languages/plugin-update-checker-pt_BR.po b/packages/plugin-updater/languages/plugin-update-checker-pt_BR.po new file mode 100644 index 000000000..70a0f625d --- /dev/null +++ b/packages/plugin-updater/languages/plugin-update-checker-pt_BR.po @@ -0,0 +1,48 @@ +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2017-05-19 15:41-0300\n" +"PO-Revision-Date: 2017-05-19 15:42-0300\n" +"Last-Translator: \n" +"Language-Team: \n" +"Language: pt_BR\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 1.8.8\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x;_x:1,2c\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p1/Plugin/UpdateChecker.php:358 +msgid "Check for updates" +msgstr "Verificar Atualizações" + +#: Puc/v4p1/Plugin/UpdateChecker.php:401 Puc/v4p1/Plugin/UpdateChecker.php:406 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "O plugin %s já está na sua versão mais recente." + +#: Puc/v4p1/Plugin/UpdateChecker.php:408 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "Há uma nova versão para o plugin %s disponível para download." + +#: Puc/v4p1/Plugin/UpdateChecker.php:410 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "Status \"%s\" desconhecido." + +#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83 +msgid "There is no changelog available." +msgstr "Não há um changelog disponível." + +#~ msgid "The %s plugin is up to date." +#~ msgstr "O plugin %s já está na sua versão mais recente." + +#~ msgid "A new version of the %s plugin is available." +#~ msgstr "Há uma nova versão para o plugin %s disponível para download." diff --git a/packages/plugin-updater/languages/plugin-update-checker.pot b/packages/plugin-updater/languages/plugin-update-checker.pot new file mode 100644 index 000000000..99cc24c74 --- /dev/null +++ b/packages/plugin-updater/languages/plugin-update-checker.pot @@ -0,0 +1,49 @@ +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: plugin-update-checker\n" +"POT-Creation-Date: 2020-08-08 14:36+0300\n" +"PO-Revision-Date: 2016-01-10 20:59+0100\n" +"Last-Translator: Tamás András Horváth \n" +"Language-Team: \n" +"Language: en_US\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 2.4\n" +"X-Poedit-Basepath: ..\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Poedit-SourceCharset: UTF-8\n" +"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" +"X-Poedit-SearchPath-0: .\n" + +#: Puc/v4p11/Plugin/Ui.php:128 +msgid "Check for updates" +msgstr "" + +#: Puc/v4p11/Plugin/Ui.php:213 +#, php-format +msgctxt "the plugin title" +msgid "The %s plugin is up to date." +msgstr "" + +#: Puc/v4p11/Plugin/Ui.php:215 +#, php-format +msgctxt "the plugin title" +msgid "A new version of the %s plugin is available." +msgstr "" + +#: Puc/v4p11/Plugin/Ui.php:217 +#, php-format +msgctxt "the plugin title" +msgid "Could not determine if updates are available for %s." +msgstr "" + +#: Puc/v4p11/Plugin/Ui.php:223 +#, php-format +msgid "Unknown update checker status \"%s\"" +msgstr "" + +#: Puc/v4p11/Vcs/PluginUpdateChecker.php:98 +msgid "There is no changelog available." +msgstr "" diff --git a/packages/plugin-updater/license.txt b/packages/plugin-updater/license.txt new file mode 100644 index 000000000..be948f65c --- /dev/null +++ b/packages/plugin-updater/license.txt @@ -0,0 +1,7 @@ +Copyright (c) 2017 Jānis Elsts + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/plugin-updater/load-puc.php b/packages/plugin-updater/load-puc.php new file mode 100644 index 000000000..50ebff700 --- /dev/null +++ b/packages/plugin-updater/load-puc.php @@ -0,0 +1,6 @@ +=3,<3.2.2" + }, + "require-dev": { + "doctrine/collections": "^1.6.8", + "doctrine/common": "^2.13.3 || ^3.2.2", + "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13" + }, + "type": "library", + "autoload": { + "files": [ + "src/DeepCopy/deep_copy.php" + ], + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "support": { + "issues": "https://github.com/myclabs/DeepCopy/issues", + "source": "https://github.com/myclabs/DeepCopy/tree/1.11.1" + }, + "funding": [ + { + "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy", + "type": "tidelift" + } + ], + "time": "2023-03-08T13:26:56+00:00" + }, + { + "name": "nikic/php-parser", + "version": "v4.16.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "19526a33fb561ef417e822e85f08a00db4059c17" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/19526a33fb561ef417e822e85f08a00db4059c17", + "reference": "19526a33fb561ef417e822e85f08a00db4059c17", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": ">=7.0" + }, + "require-dev": { + "ircmaxell/php-yacc": "^0.0.7", + "phpunit/phpunit": "^6.5 || ^7.0 || ^8.0 || ^9.0" + }, + "bin": [ + "bin/php-parse" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.9-dev" + } + }, + "autoload": { + "psr-4": { + "PhpParser\\": "lib/PhpParser" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "support": { + "issues": "https://github.com/nikic/PHP-Parser/issues", + "source": "https://github.com/nikic/PHP-Parser/tree/v4.16.0" + }, + "time": "2023-06-25T14:52:30+00:00" + }, + { + "name": "phar-io/manifest", + "version": "2.0.3", + "source": { + "type": "git", + "url": "https://github.com/phar-io/manifest.git", + "reference": "97803eca37d319dfa7826cc2437fc020857acb53" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/97803eca37d319dfa7826cc2437fc020857acb53", + "reference": "97803eca37d319dfa7826cc2437fc020857acb53", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-phar": "*", + "ext-xmlwriter": "*", + "phar-io/version": "^3.0.1", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", + "support": { + "issues": "https://github.com/phar-io/manifest/issues", + "source": "https://github.com/phar-io/manifest/tree/2.0.3" + }, + "time": "2021-07-20T11:28:43+00:00" + }, + { + "name": "phar-io/version", + "version": "3.2.1", + "source": { + "type": "git", + "url": "https://github.com/phar-io/version.git", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/version/zipball/4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Library for handling version information and constraints", + "support": { + "issues": "https://github.com/phar-io/version/issues", + "source": "https://github.com/phar-io/version/tree/3.2.1" + }, + "time": "2022-02-21T01:04:05+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "9.2.26", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "443bc6912c9bd5b409254a40f4b0f4ced7c80ea1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/443bc6912c9bd5b409254a40f4b0f4ced7c80ea1", + "reference": "443bc6912c9bd5b409254a40f4b0f4ced7c80ea1", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-xmlwriter": "*", + "nikic/php-parser": "^4.15", + "php": ">=7.3", + "phpunit/php-file-iterator": "^3.0.3", + "phpunit/php-text-template": "^2.0.2", + "sebastian/code-unit-reverse-lookup": "^2.0.2", + "sebastian/complexity": "^2.0", + "sebastian/environment": "^5.1.2", + "sebastian/lines-of-code": "^1.0.3", + "sebastian/version": "^3.0.1", + "theseer/tokenizer": "^1.2.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "suggest": { + "ext-pcov": "PHP extension that provides line coverage", + "ext-xdebug": "PHP extension that provides line coverage as well as branch and path coverage" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "9.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.26" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-03-06T12:58:08+00:00" + }, + { + "name": "phpunit/php-file-iterator", + "version": "3.0.6", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "cf1c2e7c203ac650e352f4cc675a7021e7d1b3cf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/cf1c2e7c203ac650e352f4cc675a7021e7d1b3cf", + "reference": "cf1c2e7c203ac650e352f4cc675a7021e7d1b3cf", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues", + "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/3.0.6" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2021-12-02T12:48:52+00:00" + }, + { + "name": "phpunit/php-invoker", + "version": "3.1.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-invoker.git", + "reference": "5a10147d0aaf65b58940a0b72f71c9ac0423cc67" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/5a10147d0aaf65b58940a0b72f71c9ac0423cc67", + "reference": "5a10147d0aaf65b58940a0b72f71c9ac0423cc67", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "ext-pcntl": "*", + "phpunit/phpunit": "^9.3" + }, + "suggest": { + "ext-pcntl": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Invoke callables with a timeout", + "homepage": "https://github.com/sebastianbergmann/php-invoker/", + "keywords": [ + "process" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-invoker/issues", + "source": "https://github.com/sebastianbergmann/php-invoker/tree/3.1.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-09-28T05:58:55+00:00" + }, + { + "name": "phpunit/php-text-template", + "version": "2.0.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "5da5f67fc95621df9ff4c4e5a84d6a8a2acf7c28" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/5da5f67fc95621df9ff4c4e5a84d6a8a2acf7c28", + "reference": "5da5f67fc95621df9ff4c4e5a84d6a8a2acf7c28", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-text-template/issues", + "source": "https://github.com/sebastianbergmann/php-text-template/tree/2.0.4" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-10-26T05:33:50+00:00" + }, + { + "name": "phpunit/php-timer", + "version": "5.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "5a63ce20ed1b5bf577850e2c4e87f4aa902afbd2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/5a63ce20ed1b5bf577850e2c4e87f4aa902afbd2", + "reference": "5a63ce20ed1b5bf577850e2c4e87f4aa902afbd2", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-timer/issues", + "source": "https://github.com/sebastianbergmann/php-timer/tree/5.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-10-26T13:16:10+00:00" + }, + { + "name": "phpunit/phpunit", + "version": "9.6.9", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "a9aceaf20a682aeacf28d582654a1670d8826778" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a9aceaf20a682aeacf28d582654a1670d8826778", + "reference": "a9aceaf20a682aeacf28d582654a1670d8826778", + "shasum": "" + }, + "require": { + "doctrine/instantiator": "^1.3.1 || ^2", + "ext-dom": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xml": "*", + "ext-xmlwriter": "*", + "myclabs/deep-copy": "^1.10.1", + "phar-io/manifest": "^2.0.3", + "phar-io/version": "^3.0.2", + "php": ">=7.3", + "phpunit/php-code-coverage": "^9.2.13", + "phpunit/php-file-iterator": "^3.0.5", + "phpunit/php-invoker": "^3.1.1", + "phpunit/php-text-template": "^2.0.3", + "phpunit/php-timer": "^5.0.2", + "sebastian/cli-parser": "^1.0.1", + "sebastian/code-unit": "^1.0.6", + "sebastian/comparator": "^4.0.8", + "sebastian/diff": "^4.0.3", + "sebastian/environment": "^5.1.3", + "sebastian/exporter": "^4.0.5", + "sebastian/global-state": "^5.0.1", + "sebastian/object-enumerator": "^4.0.3", + "sebastian/resource-operations": "^3.0.3", + "sebastian/type": "^3.2", + "sebastian/version": "^3.0.2" + }, + "suggest": { + "ext-soap": "To be able to generate mocks based on WSDL files", + "ext-xdebug": "PHP extension that provides line coverage as well as branch and path coverage" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "9.6-dev" + } + }, + "autoload": { + "files": [ + "src/Framework/Assert/Functions.php" + ], + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/phpunit/issues", + "security": "https://github.com/sebastianbergmann/phpunit/security/policy", + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.9" + }, + "funding": [ + { + "url": "https://phpunit.de/sponsors.html", + "type": "custom" + }, + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit", + "type": "tidelift" + } + ], + "time": "2023-06-11T06:13:56+00:00" + }, + { + "name": "sebastian/cli-parser", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/cli-parser.git", + "reference": "442e7c7e687e42adc03470c7b668bc4b2402c0b2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/442e7c7e687e42adc03470c7b668bc4b2402c0b2", + "reference": "442e7c7e687e42adc03470c7b668bc4b2402c0b2", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for parsing CLI options", + "homepage": "https://github.com/sebastianbergmann/cli-parser", + "support": { + "issues": "https://github.com/sebastianbergmann/cli-parser/issues", + "source": "https://github.com/sebastianbergmann/cli-parser/tree/1.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-09-28T06:08:49+00:00" + }, + { + "name": "sebastian/code-unit", + "version": "1.0.8", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit.git", + "reference": "1fc9f64c0927627ef78ba436c9b17d967e68e120" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/1fc9f64c0927627ef78ba436c9b17d967e68e120", + "reference": "1fc9f64c0927627ef78ba436c9b17d967e68e120", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the PHP code units", + "homepage": "https://github.com/sebastianbergmann/code-unit", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit/issues", + "source": "https://github.com/sebastianbergmann/code-unit/tree/1.0.8" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-10-26T13:08:54+00:00" + }, + { + "name": "sebastian/code-unit-reverse-lookup", + "version": "2.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", + "reference": "ac91f01ccec49fb77bdc6fd1e548bc70f7faa3e5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/ac91f01ccec49fb77bdc6fd1e548bc70f7faa3e5", + "reference": "ac91f01ccec49fb77bdc6fd1e548bc70f7faa3e5", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Looks up which function or method a line of code belongs to", + "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues", + "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/2.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-09-28T05:30:19+00:00" + }, + { + "name": "sebastian/comparator", + "version": "4.0.8", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/comparator.git", + "reference": "fa0f136dd2334583309d32b62544682ee972b51a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/fa0f136dd2334583309d32b62544682ee972b51a", + "reference": "fa0f136dd2334583309d32b62544682ee972b51a", + "shasum": "" + }, + "require": { + "php": ">=7.3", + "sebastian/diff": "^4.0", + "sebastian/exporter": "^4.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + } + ], + "description": "Provides the functionality to compare PHP values for equality", + "homepage": "https://github.com/sebastianbergmann/comparator", + "keywords": [ + "comparator", + "compare", + "equality" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/comparator/issues", + "source": "https://github.com/sebastianbergmann/comparator/tree/4.0.8" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2022-09-14T12:41:17+00:00" + }, + { + "name": "sebastian/complexity", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/complexity.git", + "reference": "739b35e53379900cc9ac327b2147867b8b6efd88" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/739b35e53379900cc9ac327b2147867b8b6efd88", + "reference": "739b35e53379900cc9ac327b2147867b8b6efd88", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^4.7", + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for calculating the complexity of PHP code units", + "homepage": "https://github.com/sebastianbergmann/complexity", + "support": { + "issues": "https://github.com/sebastianbergmann/complexity/issues", + "source": "https://github.com/sebastianbergmann/complexity/tree/2.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-10-26T15:52:27+00:00" + }, + { + "name": "sebastian/diff", + "version": "4.0.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "74be17022044ebaaecfdf0c5cd504fc9cd5a7131" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/74be17022044ebaaecfdf0c5cd504fc9cd5a7131", + "reference": "74be17022044ebaaecfdf0c5cd504fc9cd5a7131", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3", + "symfony/process": "^4.2 || ^5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "source": "https://github.com/sebastianbergmann/diff/tree/4.0.5" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-05-07T05:35:17+00:00" + }, + { + "name": "sebastian/environment", + "version": "5.1.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/environment.git", + "reference": "830c43a844f1f8d5b7a1f6d6076b784454d8b7ed" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/830c43a844f1f8d5b7a1f6d6076b784454d8b7ed", + "reference": "830c43a844f1f8d5b7a1f6d6076b784454d8b7ed", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "suggest": { + "ext-posix": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides functionality to handle HHVM/PHP environments", + "homepage": "http://www.github.com/sebastianbergmann/environment", + "keywords": [ + "Xdebug", + "environment", + "hhvm" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/environment/issues", + "source": "https://github.com/sebastianbergmann/environment/tree/5.1.5" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-02-03T06:03:51+00:00" + }, + { + "name": "sebastian/exporter", + "version": "4.0.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/exporter.git", + "reference": "ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d", + "reference": "ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d", + "shasum": "" + }, + "require": { + "php": ">=7.3", + "sebastian/recursion-context": "^4.0" + }, + "require-dev": { + "ext-mbstring": "*", + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Provides the functionality to export PHP variables for visualization", + "homepage": "https://www.github.com/sebastianbergmann/exporter", + "keywords": [ + "export", + "exporter" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/exporter/issues", + "source": "https://github.com/sebastianbergmann/exporter/tree/4.0.5" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2022-09-14T06:03:37+00:00" + }, + { + "name": "sebastian/global-state", + "version": "5.0.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "0ca8db5a5fc9c8646244e629625ac486fa286bf2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/0ca8db5a5fc9c8646244e629625ac486fa286bf2", + "reference": "0ca8db5a5fc9c8646244e629625ac486fa286bf2", + "shasum": "" + }, + "require": { + "php": ">=7.3", + "sebastian/object-reflector": "^2.0", + "sebastian/recursion-context": "^4.0" + }, + "require-dev": { + "ext-dom": "*", + "phpunit/phpunit": "^9.3" + }, + "suggest": { + "ext-uopz": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Snapshotting of global state", + "homepage": "http://www.github.com/sebastianbergmann/global-state", + "keywords": [ + "global state" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/global-state/issues", + "source": "https://github.com/sebastianbergmann/global-state/tree/5.0.5" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2022-02-14T08:28:10+00:00" + }, + { + "name": "sebastian/lines-of-code", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/lines-of-code.git", + "reference": "c1c2e997aa3146983ed888ad08b15470a2e22ecc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/c1c2e997aa3146983ed888ad08b15470a2e22ecc", + "reference": "c1c2e997aa3146983ed888ad08b15470a2e22ecc", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^4.6", + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for counting the lines of code in PHP source code", + "homepage": "https://github.com/sebastianbergmann/lines-of-code", + "support": { + "issues": "https://github.com/sebastianbergmann/lines-of-code/issues", + "source": "https://github.com/sebastianbergmann/lines-of-code/tree/1.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-11-28T06:42:11+00:00" + }, + { + "name": "sebastian/object-enumerator", + "version": "4.0.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-enumerator.git", + "reference": "5c9eeac41b290a3712d88851518825ad78f45c71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/5c9eeac41b290a3712d88851518825ad78f45c71", + "reference": "5c9eeac41b290a3712d88851518825ad78f45c71", + "shasum": "" + }, + "require": { + "php": ">=7.3", + "sebastian/object-reflector": "^2.0", + "sebastian/recursion-context": "^4.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Traverses array structures and object graphs to enumerate all referenced objects", + "homepage": "https://github.com/sebastianbergmann/object-enumerator/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-enumerator/issues", + "source": "https://github.com/sebastianbergmann/object-enumerator/tree/4.0.4" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-10-26T13:12:34+00:00" + }, + { + "name": "sebastian/object-reflector", + "version": "2.0.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-reflector.git", + "reference": "b4f479ebdbf63ac605d183ece17d8d7fe49c15c7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/b4f479ebdbf63ac605d183ece17d8d7fe49c15c7", + "reference": "b4f479ebdbf63ac605d183ece17d8d7fe49c15c7", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Allows reflection of object attributes, including inherited and non-public ones", + "homepage": "https://github.com/sebastianbergmann/object-reflector/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-reflector/issues", + "source": "https://github.com/sebastianbergmann/object-reflector/tree/2.0.4" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-10-26T13:14:26+00:00" + }, + { + "name": "sebastian/recursion-context", + "version": "4.0.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/recursion-context.git", + "reference": "e75bd0f07204fec2a0af9b0f3cfe97d05f92efc1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/e75bd0f07204fec2a0af9b0f3cfe97d05f92efc1", + "reference": "e75bd0f07204fec2a0af9b0f3cfe97d05f92efc1", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "https://github.com/sebastianbergmann/recursion-context", + "support": { + "issues": "https://github.com/sebastianbergmann/recursion-context/issues", + "source": "https://github.com/sebastianbergmann/recursion-context/tree/4.0.5" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-02-03T06:07:39+00:00" + }, + { + "name": "sebastian/resource-operations", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/resource-operations.git", + "reference": "0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8", + "reference": "0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides a list of PHP built-in functions that operate on resources", + "homepage": "https://www.github.com/sebastianbergmann/resource-operations", + "support": { + "issues": "https://github.com/sebastianbergmann/resource-operations/issues", + "source": "https://github.com/sebastianbergmann/resource-operations/tree/3.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-09-28T06:45:17+00:00" + }, + { + "name": "sebastian/type", + "version": "3.2.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/type.git", + "reference": "75e2c2a32f5e0b3aef905b9ed0b179b953b3d7c7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/75e2c2a32f5e0b3aef905b9ed0b179b953b3d7c7", + "reference": "75e2c2a32f5e0b3aef905b9ed0b179b953b3d7c7", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the types of the PHP type system", + "homepage": "https://github.com/sebastianbergmann/type", + "support": { + "issues": "https://github.com/sebastianbergmann/type/issues", + "source": "https://github.com/sebastianbergmann/type/tree/3.2.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-02-03T06:13:03+00:00" + }, + { + "name": "sebastian/version", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "c6c1022351a901512170118436c764e473f6de8c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/c6c1022351a901512170118436c764e473f6de8c", + "reference": "c6c1022351a901512170118436c764e473f6de8c", + "shasum": "" + }, + "require": { + "php": ">=7.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "support": { + "issues": "https://github.com/sebastianbergmann/version/issues", + "source": "https://github.com/sebastianbergmann/version/tree/3.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-09-28T06:39:44+00:00" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "3.7.2", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "ed8e00df0a83aa96acf703f8c2979ff33341f879" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/ed8e00df0a83aa96acf703f8c2979ff33341f879", + "reference": "ed8e00df0a83aa96acf703f8c2979ff33341f879", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "bin": [ + "bin/phpcs", + "bin/phpcbf" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/squizlabs/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/squizlabs/PHP_CodeSniffer/issues", + "source": "https://github.com/squizlabs/PHP_CodeSniffer", + "wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki" + }, + "time": "2023-02-22T23:07:41+00:00" + }, + { + "name": "theseer/tokenizer", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/theseer/tokenizer.git", + "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/34a41e998c2183e22995f158c581e7b5e755ab9e", + "reference": "34a41e998c2183e22995f158c581e7b5e755ab9e", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + } + ], + "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", + "support": { + "issues": "https://github.com/theseer/tokenizer/issues", + "source": "https://github.com/theseer/tokenizer/tree/1.2.1" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2021-07-28T10:34:58+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": ">=7", + "ext-json": "*" + }, + "platform-dev": [], + "plugin-api-version": "2.3.0" +} \ No newline at end of file diff --git a/packages/sdk/src/Common/AbstractCollection.php b/packages/sdk/src/Common/AbstractCollection.php index c428ff59c..9433850bb 100644 --- a/packages/sdk/src/Common/AbstractCollection.php +++ b/packages/sdk/src/Common/AbstractCollection.php @@ -1,18 +1,22 @@ manager = $manager; } @@ -35,8 +38,7 @@ public function __construct(Manager $manager = null) * @param AbstractEntity $entity * @param string|null $key */ - public function addEntity(AbstractEntity $entity, string $key = null) - { + public function addEntity(AbstractEntity $entity, string $key = null): void { if (is_null($key)) { $this->collection[] = $entity; } else { @@ -49,8 +51,7 @@ public function addEntity(AbstractEntity $entity, string $key = null) * * @param $entities */ - public function setEntity($entities) - { + public function setEntity($entities): void { if (is_array($entities) || is_object($entities)) { foreach ($entities as $value) { $this->add($value); @@ -61,24 +62,21 @@ public function setEntity($entities) /** * @inheritDoc */ - public function getIterator() - { - return new \ArrayIterator($this->collection); + public function getIterator(): Traversable { + return new ArrayIterator($this->collection); } /** * @return int|null */ - public function count(): int - { + public function count(): int { return count($this->collection); } /** * @return array */ - public function jsonSerialize(): array - { + public function jsonSerialize(): array { return $this->collection; } } diff --git a/packages/sdk/src/Common/AbstractEntity.php b/packages/sdk/src/Common/AbstractEntity.php index 48aacbcdc..d7229cfe5 100644 --- a/packages/sdk/src/Common/AbstractEntity.php +++ b/packages/sdk/src/Common/AbstractEntity.php @@ -3,14 +3,17 @@ namespace MercadoPago\PP\Sdk\Common; use MercadoPago\PP\Sdk\Interfaces\EntityInterface; +use MercadoPago\PP\Sdk\Sdk; +use JsonSerializable; +use IteratorAggregate; +use Exception; /** * Class AbstractEntity * * @package MercadoPago\PP\Sdk\Common */ -abstract class AbstractEntity implements \JsonSerializable, EntityInterface -{ +abstract class AbstractEntity implements JsonSerializable, EntityInterface { /** * @var Manager */ @@ -26,8 +29,7 @@ abstract class AbstractEntity implements \JsonSerializable, EntityInterface * * @param Manager|null $manager */ - public function __construct(Manager $manager = null) - { + public function __construct(Manager $manager = null) { $this->manager = $manager; $this->setExcludedProperties(); } @@ -37,8 +39,7 @@ public function __construct(Manager $manager = null) * * @return mixed */ - public function __get(string $name) - { + public function __get(string $name) { return $this->{$name}; } @@ -46,14 +47,13 @@ public function __get(string $name) * @param string $name * @param mixed $value */ - public function __set(string $name, $value) - { - if (!property_exists($this, $name)) { + public function __set(string $name, $value): void { + if ( ! property_exists($this, $name)) { return; } - if (is_subclass_of($this->{$name}, AbstractEntity::class) || - is_subclass_of($this->{$name}, AbstractCollection::class) + if (is_subclass_of($this->{$name}, 'MercadoPago\PP\Sdk\Common\AbstractEntity') || + is_subclass_of($this->{$name}, 'MercadoPago\PP\Sdk\Common\AbstractCollection') ) { $this->{$name}->setEntity($value); } else { @@ -66,27 +66,23 @@ public function __set(string $name, $value) * * @return bool */ - public function __isset(string $name) - { + public function __isset(string $name) { return isset($this->{$name}); } /** * @param string $name */ - public function __unset(string $name) - { + public function __unset(string $name): void { unset($this->{$name}); } - /** * Set values for an entity's attributes. * * @param $data */ - public function setEntity($data) - { + public function setEntity($data): void { if (is_array($data) || is_object($data)) { foreach ($data as $key => $value) { $this->__set($key, $value); @@ -100,8 +96,7 @@ public function setEntity($data) * * @return array */ - public function getProperties(): array - { + public function getProperties(): array { return get_object_vars($this); } @@ -110,18 +105,17 @@ public function getProperties(): array * * @return array */ - public function toArray(): array - { - $data = []; - $properties = $this->getProperties(); + public function toArray(): array { + $data = array(); + $properties = $this->getProperties(); $excludedPropertiesCount = count($this->excluded_properties); foreach ($properties as $property => $value) { - if ($property === 'manager' || $property === 'excluded_properties') { + if ('manager' === $property || 'excluded_properties' === $property) { continue; } - if ($excludedPropertiesCount !== 0 && in_array($property, $this->excluded_properties)) { + if (0 !== $excludedPropertiesCount && in_array($property, $this->excluded_properties, true)) { continue; } @@ -130,7 +124,7 @@ public function toArray(): array continue; } - if (($value instanceof \IteratorAggregate) || (is_array($value) && count($value))) { + if (($value instanceof IteratorAggregate) || (is_array($value) && count($value))) { foreach ($value as $index => $item) { if ($item instanceof self) { $data[$property][$index] = $item->toArray(); @@ -153,20 +147,19 @@ public function toArray(): array * @param array $params * * @return mixed - * @throws \Exception + * @throws Exception */ - public function read(array $params = []) - { + public function read(array $params = array()) { $method = 'get'; - $class = get_called_class(); + $class = get_called_class(); $entity = new $class($this->manager); $customHeaders = $this->getHeaders()['read']; - $header = $this->manager->getHeader($customHeaders); + $header = $this->manager->getHeader($customHeaders); - $uri = $this->manager->getEntityUri($entity, $method, $params); + $uri = $this->manager->getEntityUri($entity, $method, $params); $response = $this->manager->execute($entity, $uri, $method, $header); - + $this->obfuscateAuthorizationHeader($header); return $this->manager->handleResponse($response, $method, $entity); } @@ -174,26 +167,24 @@ public function read(array $params = []) * Save method (POST). * * @return mixed - * @throws \Exception + * @throws Exception */ - public function save() - { + public function save() { $method = 'post'; $customHeaders = $this->getHeaders()['save']; - $header = $this->manager->getHeader($customHeaders); + $header = $this->manager->getHeader($customHeaders); - $uri = $this->manager->getEntityUri($this, $method); + $uri = $this->manager->getEntityUri($this, $method); $response = $this->manager->execute($this, $uri, $method, $header); - + $this->obfuscateAuthorizationHeader($header); return $this->manager->handleResponse($response, $method); } /** * @return array */ - public function jsonSerialize(): array - { + public function jsonSerialize(): array { return $this->toArray(); } @@ -202,8 +193,28 @@ public function jsonSerialize(): array * * @return void */ - public function setExcludedProperties() - { - $this->excluded_properties = []; + public function setExcludedProperties(): void { + $this->excluded_properties = array(); + } + + /** + * Obfuscate Authorization Header. + * + * @return void + */ + public function obfuscateAuthorizationHeader(array $headers): void { + Sdk::$cache['last_headers'] = preg_replace('/(Authorization: Bearer) (.*)/i', '$1 xxx', $headers); + } + + /** + * Get last Headers. + * + * @return array + */ + public function getLastHeaders(): array { + if (isset(Sdk::$cache['last_headers'])) { + return Sdk::$cache['last_headers']; + } + return array(); } } diff --git a/packages/sdk/src/Common/Config.php b/packages/sdk/src/Common/Config.php index 85b1caff4..ea11e05f3 100644 --- a/packages/sdk/src/Common/Config.php +++ b/packages/sdk/src/Common/Config.php @@ -7,8 +7,7 @@ * * @package MercadoPago\PP\Sdk\Common */ -class Config -{ +class Config { /** * @var string */ @@ -54,8 +53,7 @@ public function __construct( * * @return mixed */ - public function __get(string $name) - { + public function __get(string $name) { return $this->{$name}; } @@ -63,8 +61,7 @@ public function __get(string $name) * @param string $name * @param string $value */ - public function __set(string $name, string $value) - { + public function __set(string $name, string $value): void { if (property_exists($this, $name)) { $this->{$name} = $value; } diff --git a/packages/sdk/src/Common/Constants.php b/packages/sdk/src/Common/Constants.php index 059f94839..72eee0ed9 100644 --- a/packages/sdk/src/Common/Constants.php +++ b/packages/sdk/src/Common/Constants.php @@ -7,8 +7,8 @@ * * @package MercadoPago\PP\Sdk\Common */ -class Constants -{ - const BASEURL_MP = 'https://api.mercadopago.com'; - const BASEURL_ML = 'https://api.mercadolibre.com'; +class Constants { + public const BASEURL_MP = 'https://api.mercadopago.com'; + + public const BASEURL_ML = 'https://api.mercadolibre.com'; } diff --git a/packages/sdk/src/Common/Manager.php b/packages/sdk/src/Common/Manager.php index 9662b5932..1275f9612 100644 --- a/packages/sdk/src/Common/Manager.php +++ b/packages/sdk/src/Common/Manager.php @@ -4,14 +4,14 @@ use MercadoPago\PP\Sdk\HttpClient\HttpClientInterface; use MercadoPago\PP\Sdk\HttpClient\Response; +use Exception; /** * Class Manager * * @package MercadoPago\PP\Sdk\Common */ -class Manager -{ +class Manager { /** * @var HttpClientInterface */ @@ -28,8 +28,7 @@ class Manager * @param HttpClientInterface $client * @param Config $config */ - public function __construct(HttpClientInterface $client, Config $config) - { + public function __construct(HttpClientInterface $client, Config $config) { $this->client = $client; $this->config = $config; } @@ -44,9 +43,8 @@ public function __construct(HttpClientInterface $client, Config $config) * * @return mixed */ - public function execute(AbstractEntity $entity, string $uri, string $method = 'get', array $headers = []) - { - if ($method == 'get') { + public function execute(AbstractEntity $entity, string $uri, string $method = 'get', array $headers = array()) { + if ('get' == $method) { return $this->client->{$method}($uri, $headers); } @@ -62,13 +60,12 @@ public function execute(AbstractEntity $entity, string $uri, string $method = 'g * @param array $params * * @return mixed - * @throws \Exception + * @throws Exception */ - public function getEntityUri(AbstractEntity $entity, string $method, array $params = []) - { + public function getEntityUri(AbstractEntity $entity, string $method, array $params = array()) { if (method_exists($entity, 'getUris')) { $uri = $entity->getUris()[$method]; - $matches = []; + $matches = array(); preg_match_all('/\\:\\w+/', $uri, $matches); foreach ($matches[0] as $match) { @@ -76,7 +73,7 @@ public function getEntityUri(AbstractEntity $entity, string $method, array $para if (array_key_exists($key, $params)) { $uri = str_replace($match, $params[$key], $uri); - } elseif (property_exists($entity, $key) && !is_null($entity->{$key})) { + } elseif (property_exists($entity, $key) && ! is_null($entity->{$key})) { $uri = str_replace($match, $entity->{$key}, $uri); } else { $uri = str_replace($match, '', $uri); @@ -85,7 +82,7 @@ public function getEntityUri(AbstractEntity $entity, string $method, array $para return $uri; } else { - throw new \Exception('Method not available for ' . get_class($entity) . ' entity'); + throw new Exception('Method not available for ' . get_class($entity) . ' entity'); } } @@ -94,14 +91,13 @@ public function getEntityUri(AbstractEntity $entity, string $method, array $para * * @return array */ - public function getDefaultHeader(): array - { - return [ + public function getDefaultHeader(): array { + return array( 'Authorization: Bearer ' . $this->config->__get('access_token'), 'x-platform-id: ' . $this->config->__get('platform_id'), 'x-product-id: ' . $this->config->__get('product_id'), 'x-integrator-id: ' . $this->config->__get('integrator_id') - ]; + ); } /** @@ -110,8 +106,7 @@ public function getDefaultHeader(): array * * @return array */ - public function getHeader(array $customHeaders = []): array - { + public function getHeader(array $customHeaders = array()): array { $defaultHeaders = $this->getDefaultHeader(); return array_merge($defaultHeaders, $customHeaders); } @@ -124,20 +119,20 @@ public function getHeader(array $customHeaders = []): array * @param AbstractEntity|null $entity * * @return mixed - * @throws \Exception + * @throws Exception */ - public function handleResponse(Response $response, string $method, AbstractEntity $entity = null) - { + public function handleResponse(Response $response, string $method, AbstractEntity $entity = null) { if ($response->getStatus() == '200' || $response->getStatus() == '201') { - if ($entity && $method == 'get') { + if ($entity && 'get' == $method) { $entity->setEntity($response->getData()); return $entity; } return $response->getData(); - } elseif (intval($response->getStatus()) >= 400 && intval($response->getStatus()) < 500) { - throw new \Exception($response->getData()['message']); + } + if ((int) ($response->getStatus()) >= 400 && (int) ($response->getStatus()) < 500) { + throw new Exception($response->getData()['message']); } else { - throw new \Exception("Internal API Error"); + throw new Exception("Internal API Error"); } } } diff --git a/packages/sdk/src/Entity/Notification/Notification.php b/packages/sdk/src/Entity/Notification/Notification.php index b31889d25..56006b91e 100644 --- a/packages/sdk/src/Entity/Notification/Notification.php +++ b/packages/sdk/src/Entity/Notification/Notification.php @@ -9,28 +9,30 @@ /** * Class Notification * - * @property string $ip_address * @property string $notification_id * @property string $notification_url * @property string $status - * @property string $external_reference - * @property float $transaction_id + * @property string $transaction_id * @property string $transaction_type + * @property string $platform_id + * @property string $external_reference + * @property string $preference_id * @property float $transaction_amount - * @property float $total_pending - * @property float $total_approved * @property float $total_paid - * @property float $total_rejected + * @property float $total_approved + * @property float $total_pending * @property float $total_refunded + * @property float $total_rejected * @property float $total_cancelled * @property float $total_charged_back + * @property string $multiple_payment_transaction_id * @property array $payments_metadata - * @property PaymentDetails $payments_details + * @property PaymentDetailsList $payments_details + * @property RefundNotifyingList $refunds_notifying * * @package MercadoPago\PP\Sdk\Entity\Notification */ -class Notification extends AbstractEntity implements RequesterEntityInterface -{ +class Notification extends AbstractEntity implements RequesterEntityInterface { /** * @var string */ @@ -49,17 +51,27 @@ class Notification extends AbstractEntity implements RequesterEntityInterface /** * @var string */ - protected $external_reference; + protected $transaction_id; /** - * @var float + * @var string */ - protected $transaction_id; + protected $transaction_type; /** * @var string */ - protected $transaction_type; + protected $platform_id; + + /** + * @var string + */ + protected $external_reference; + + /** + * @var string + */ + protected $preference_id; /** * @var float @@ -69,7 +81,7 @@ class Notification extends AbstractEntity implements RequesterEntityInterface /** * @var float */ - protected $total_pending; + protected $total_paid; /** * @var float @@ -79,17 +91,17 @@ class Notification extends AbstractEntity implements RequesterEntityInterface /** * @var float */ - protected $total_paid; + protected $total_pending; /** * @var float */ - protected $total_rejected; + protected $total_refunded; /** * @var float */ - protected $total_refunded; + protected $total_rejected; /** * @var float @@ -101,25 +113,35 @@ class Notification extends AbstractEntity implements RequesterEntityInterface */ protected $total_charged_back; + /** + * @var string + */ + protected $multiple_payment_transaction_id; + /** * @var array */ protected $payments_metadata; /** - * @var PaymentDetails + * @var PaymentDetailsList */ protected $payments_details; + /** + * @var RefundNotifyingList + */ + protected $refunds_notifying; + /** * Notification constructor. * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); $this->payments_details = new PaymentDetailsList($manager); + $this->refunds_notifying = new RefundNotifyingList($manager); } /** @@ -127,9 +149,8 @@ public function __construct($manager) * * @return void */ - public function setExcludedProperties() - { - $this->excluded_properties = []; + public function setExcludedProperties(): void { + $this->excluded_properties = array(); } /** @@ -137,12 +158,11 @@ public function setExcludedProperties() * * @return array */ - public function getHeaders(): array - { - return [ - 'read' => [], - 'save' => [], - ]; + public function getHeaders(): array { + return array( + 'read' => array(), + 'save' => array(), + ); } /** @@ -150,10 +170,9 @@ public function getHeaders(): array * * @return array */ - public function getUris(): array - { + public function getUris(): array { return array( - 'get' => '/v1/bifrost/notification/status/:id', + 'get' => '/v1/asgard/notification/:id', ); } } diff --git a/packages/sdk/src/Entity/Notification/PaymentDetails.php b/packages/sdk/src/Entity/Notification/PaymentDetails.php index 2cd1559c1..11acc27f9 100644 --- a/packages/sdk/src/Entity/Notification/PaymentDetails.php +++ b/packages/sdk/src/Entity/Notification/PaymentDetails.php @@ -8,35 +8,35 @@ /** * Class PaymentDetails * - * @property float $id - * @property string $status - * @property string $status_detail - * @property string $payment_type_id + * @property int $id * @property string $payment_method_id + * @property PaymentMethodInfo $payment_method_info + * @property string $payment_type_id * @property float $total_amount * @property float $paid_amount - * @property float $coupon_amount * @property float $shipping_cost + * @property float $coupon_amount + * @property string $status + * @property string $status_detail * @property RefundList $refunds - + * * @package MercadoPago\PP\Sdk\Entity\Notification */ -class PaymentDetails extends AbstractEntity -{ +class PaymentDetails extends AbstractEntity { /** - * @var float + * @var int */ protected $id; /** * @var string */ - protected $status; + protected $payment_method_id; /** - * @var string + * @var PaymentMethodInfo */ - protected $status_detail; + protected $payment_method_info; /** * @var string @@ -44,19 +44,19 @@ class PaymentDetails extends AbstractEntity protected $payment_type_id; /** - * @var string + * @var float */ - protected $payment_method_id; + protected $total_amount; /** * @var float */ - protected $total_amount; + protected $paid_amount; /** * @var float */ - protected $paid_amount; + protected $shipping_cost; /** * @var float @@ -64,14 +64,14 @@ class PaymentDetails extends AbstractEntity protected $coupon_amount; /** - * @var float + * @var string */ - protected $shipping_cost; + protected $status; /** - * @var PaymentMethodInfo + * @var string */ - protected $payment_method_info; + protected $status_detail; /** * @var RefundList @@ -83,8 +83,7 @@ class PaymentDetails extends AbstractEntity * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); $this->refunds = new RefundList($manager); } diff --git a/packages/sdk/src/Entity/Notification/PaymentDetailsList.php b/packages/sdk/src/Entity/Notification/PaymentDetailsList.php index 55d6628fa..89d3f1e4f 100644 --- a/packages/sdk/src/Entity/Notification/PaymentDetailsList.php +++ b/packages/sdk/src/Entity/Notification/PaymentDetailsList.php @@ -9,16 +9,14 @@ * * @package MercadoPago\PP\Sdk\Entity\Notification */ -class PaymentDetailsList extends AbstractCollection -{ +class PaymentDetailsList extends AbstractCollection { /** * Add entity to collection * * @param array $entity * @param string|null $key */ - public function add(array $entity, string $key = null) - { + public function add(array $entity, string $key = null): void { $item = new PaymentDetails($this->manager); $item->setEntity($entity); parent::addEntity($item, $key); diff --git a/packages/sdk/src/Entity/Notification/PaymentMethodInfo.php b/packages/sdk/src/Entity/Notification/PaymentMethodInfo.php index 9586e164e..64680a6b5 100644 --- a/packages/sdk/src/Entity/Notification/PaymentMethodInfo.php +++ b/packages/sdk/src/Entity/Notification/PaymentMethodInfo.php @@ -7,10 +7,18 @@ /** * Class PaymentMethodInfo * + * @property string $barcode_content + * @property string $external_resource_url + * @property string $payment_method_reference_id + * @property string $date_of_expiration + * @property string $last_four_digits + * @property float $installments + * @property float $installment_rate + * @property double $installment_amount + * * @package MercadoPago\PP\Sdk\Entity\Notification */ -class PaymentMethodInfo extends AbstractEntity -{ +class PaymentMethodInfo extends AbstractEntity { /** * @var string */ @@ -27,24 +35,24 @@ class PaymentMethodInfo extends AbstractEntity protected $payment_method_reference_id; /** - * @var bool + * @var string */ protected $date_of_expiration; /** - * @var double + * @var string */ - protected $installments; + protected $last_four_digits; /** - * @var double + * @var float */ - protected $installment_rate; + protected $installments; /** - * @var string + * @var float */ - protected $last_four_digits; + protected $installment_rate; /** * @var double diff --git a/packages/sdk/src/Entity/Notification/Refund.php b/packages/sdk/src/Entity/Notification/Refund.php index 995000c0c..595f28259 100644 --- a/packages/sdk/src/Entity/Notification/Refund.php +++ b/packages/sdk/src/Entity/Notification/Refund.php @@ -7,17 +7,16 @@ /** * Class Refund * - * @property float $id + * @property int $id * @property string $status * @property bool $notifying - * @property object $metadata + * @property array $metadata * * @package MercadoPago\PP\Sdk\Entity\Notification */ -class Refund extends AbstractEntity -{ +class Refund extends AbstractEntity { /** - * @var float + * @var int */ protected $id; @@ -32,7 +31,7 @@ class Refund extends AbstractEntity protected $notifying; /** - * @var object + * @var array */ protected $metadata; } diff --git a/packages/sdk/src/Entity/Notification/RefundList.php b/packages/sdk/src/Entity/Notification/RefundList.php index 0e2261570..496ee31e6 100644 --- a/packages/sdk/src/Entity/Notification/RefundList.php +++ b/packages/sdk/src/Entity/Notification/RefundList.php @@ -9,18 +9,29 @@ * * @package MercadoPago\PP\Sdk\Entity\Notification */ -class RefundList extends AbstractCollection -{ +class RefundList extends AbstractCollection { /** * Add entity to collection * * @param array $entity * @param string|null $key */ - public function add(array $entity, string $key = null) - { + public function add(array $entity, string $key = null): void { $refund = new Refund($this->manager); $refund->setEntity($entity); parent::addEntity($refund, $key); } + + /** + * Add multiple entities to collection + * + * @param $entities + */ + public function setEntity($entities): void { + if (is_array($entities) || is_object($entities)) { + foreach ($entities as $value) { + $this->add($value, $value["id"]); + } + } + } } diff --git a/packages/sdk/src/Entity/Notification/RefundNotifying.php b/packages/sdk/src/Entity/Notification/RefundNotifying.php new file mode 100644 index 000000000..ee1915799 --- /dev/null +++ b/packages/sdk/src/Entity/Notification/RefundNotifying.php @@ -0,0 +1,31 @@ +manager); + $item->setEntity($entity); + parent::addEntity($item, $key); + } +} diff --git a/packages/sdk/src/Entity/Payment/AdditionalInfo.php b/packages/sdk/src/Entity/Payment/AdditionalInfo.php index 902157227..7784c90fb 100644 --- a/packages/sdk/src/Entity/Payment/AdditionalInfo.php +++ b/packages/sdk/src/Entity/Payment/AdditionalInfo.php @@ -9,19 +9,43 @@ * Class AdditionalInfo * * @property string $ip_address + * @property string $referral_url + * @property boolean $drop_shipping + * @property string $delivery_promise + * @property string $contrated_plan * @property ItemList $items * @property AdditionalInfoPayer $payer + * @property Seller $seller * @property Shipments $shipments * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class AdditionalInfo extends AbstractEntity -{ +class AdditionalInfo extends AbstractEntity { /** * @var string */ protected $ip_address; + /** + * @var string + */ + protected $referral_url; + + /** + * @var boolean + */ + protected $drop_shipping; + + /** + * @var string + */ + protected $delivery_promise; + + /** + * @var string + */ + protected $contrated_plan; + /** * @var ItemList */ @@ -32,6 +56,11 @@ class AdditionalInfo extends AbstractEntity */ protected $payer; + /** + * @var Seller + */ + protected $seller; + /** * @var Shipments */ @@ -42,11 +71,11 @@ class AdditionalInfo extends AbstractEntity * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); - $this->items = new ItemList($manager); - $this->payer = new AdditionalInfoPayer($manager); + $this->items = new ItemList($manager); + $this->payer = new AdditionalInfoPayer($manager); + $this->seller = new Seller($manager); $this->shipments = new Shipments($manager); } } diff --git a/packages/sdk/src/Entity/Payment/AdditionalInfoAddress.php b/packages/sdk/src/Entity/Payment/AdditionalInfoAddress.php new file mode 100644 index 000000000..bf24a2b5c --- /dev/null +++ b/packages/sdk/src/Entity/Payment/AdditionalInfoAddress.php @@ -0,0 +1,67 @@ +phone = new Phone($manager); - $this->address = new AdditionalInfoPayerAddress($manager); + $this->address = new AdditionalInfoAddress($manager); + $this->phone = new Phone($manager); + $this->mobile = new Phone($manager); + $this->identification = new Identification($manager); } } diff --git a/packages/sdk/src/Entity/Payment/AdditionalInfoPayerAddress.php b/packages/sdk/src/Entity/Payment/AdditionalInfoPayerAddress.php index 4b3dfc95d..6abcaafa2 100644 --- a/packages/sdk/src/Entity/Payment/AdditionalInfoPayerAddress.php +++ b/packages/sdk/src/Entity/Payment/AdditionalInfoPayerAddress.php @@ -12,8 +12,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class AdditionalInfoPayerAddress extends AbstractEntity -{ +class AdditionalInfoPayerAddress extends AbstractEntity { /** * @var string */ diff --git a/packages/sdk/src/Entity/Payment/Address.php b/packages/sdk/src/Entity/Payment/Address.php index d82bc7b5e..5f3a24fc9 100644 --- a/packages/sdk/src/Entity/Payment/Address.php +++ b/packages/sdk/src/Entity/Payment/Address.php @@ -16,8 +16,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class Address extends AbstractEntity -{ +class Address extends AbstractEntity { /** * @var string */ diff --git a/packages/sdk/src/Entity/Payment/ApplicationData.php b/packages/sdk/src/Entity/Payment/ApplicationData.php new file mode 100644 index 000000000..e4760e0d3 --- /dev/null +++ b/packages/sdk/src/Entity/Payment/ApplicationData.php @@ -0,0 +1,25 @@ +manager); $item->setEntity($entity); parent::addEntity($item, $key); diff --git a/packages/sdk/src/Entity/Payment/Multipayment.php b/packages/sdk/src/Entity/Payment/Multipayment.php new file mode 100644 index 000000000..7998581ac --- /dev/null +++ b/packages/sdk/src/Entity/Payment/Multipayment.php @@ -0,0 +1,29 @@ +transaction_info = new TransactionInfoList($manager); + } +} diff --git a/packages/sdk/src/Entity/Payment/MultipaymentV2.php b/packages/sdk/src/Entity/Payment/MultipaymentV2.php new file mode 100644 index 000000000..ecd0455a2 --- /dev/null +++ b/packages/sdk/src/Entity/Payment/MultipaymentV2.php @@ -0,0 +1,29 @@ +transaction_info = new TransactionInfoList($manager); + } +} diff --git a/packages/sdk/src/Entity/Payment/Payer.php b/packages/sdk/src/Entity/Payment/Payer.php index f9656422b..22ed85362 100644 --- a/packages/sdk/src/Entity/Payment/Payer.php +++ b/packages/sdk/src/Entity/Payment/Payer.php @@ -8,33 +8,44 @@ /** * Class Payer * - * @property string $id * @property string $entity_type + * @property string $type + * @property string $id * @property string $email + * @property Identification $identification * @property string $first_name * @property string $last_name - * @property PayerIdentification $identification + * @property string $operator_id * @property Address $address * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class Payer extends AbstractEntity -{ +class Payer extends AbstractEntity { /** * @var string */ - protected $id; + protected $entity_type; /** * @var string */ - protected $entity_type; + protected $type; + + /** + * @var string + */ + protected $id; /** * @var string */ protected $email; + /** + * @var Identification + */ + protected $identification; + /** * @var string */ @@ -46,9 +57,9 @@ class Payer extends AbstractEntity protected $last_name; /** - * @var PayerIdentification + * @var string */ - protected $identification; + protected $operator_id; /** * @var Address @@ -60,10 +71,9 @@ class Payer extends AbstractEntity * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); - $this->identification = new PayerIdentification($manager); - $this->address = new Address($manager); + $this->identification = new Identification($manager); + $this->address = new Address($manager); } } diff --git a/packages/sdk/src/Entity/Payment/PayerIdentification.php b/packages/sdk/src/Entity/Payment/PayerIdentification.php index f43e8907c..2fda9b8ec 100644 --- a/packages/sdk/src/Entity/Payment/PayerIdentification.php +++ b/packages/sdk/src/Entity/Payment/PayerIdentification.php @@ -12,8 +12,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class PayerIdentification extends AbstractEntity -{ +class PayerIdentification extends AbstractEntity { /** * @var string */ diff --git a/packages/sdk/src/Entity/Payment/Payment.php b/packages/sdk/src/Entity/Payment/Payment.php index 025f40a03..099746383 100644 --- a/packages/sdk/src/Entity/Payment/Payment.php +++ b/packages/sdk/src/Entity/Payment/Payment.php @@ -9,131 +9,208 @@ /** * Class Payment * - * @property string $session_id - * @property string $description - * @property string $external_reference - * @property string $notification_url - * @property int $installments - * @property double $transaction_amount - * @property string $payment_method_id - * @property string $statement_descriptor - * @property boolean $binary_mode * @property string $date_of_expiration - * @property string $callback_url - * @property string $token + * @property string $operation_type * @property string $issuer_id - * @property string $campaign_id - * @property double $coupon_amount - * @property string $coupon_code + * @property string $payment_method_id + * @property string $description + * @property string $sponsor_id + * @property string $counter_currency + * @property double $shipping_amount + * @property string $store_id * @property Payer $payer + * @property array $metadata * @property AdditionalInfo $additional_info + * @property string $external_reference + * @property double $transaction_amount + * @property double $coupon_amount + * @property int $differential_pricing_id + * @property int $installments * @property TransactionDetails $transaction_details + * @property bool $binary_mode + * @property string $statement_descriptor + * @property string $notification_url + * @property string $processing_mode + * @property string $merchant_account_id * @property PointOfInteraction $point_of_interaction - * @property object $metadata + * @property string $brand_id + * @property string $reserve_id + * @property array $collector + * @property string $callback_url + * @property double $application_fee + * @property int $campaign_id + * @property bool $capture + * @property string $coupon_code + * @property string $token + * @property string $session_id * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class Payment extends AbstractEntity implements RequesterEntityInterface -{ +class Payment extends AbstractEntity implements RequesterEntityInterface { /** * @var string */ - protected $description; + protected $date_of_expiration; /** * @var string */ - protected $external_reference; + protected $operation_type; /** * @var string */ - protected $notification_url; + protected $issuer_id; /** - * @var int + * @var string */ - protected $installments; + protected $payment_method_id; + + /** + * @var string + */ + protected $description; + + /** + * @var string + */ + protected $sponsor_id; + + /** + * @var string + */ + protected $counter_currency; /** * @var double */ - protected $transaction_amount; + protected $shipping_amount; /** * @var string */ - protected $payment_method_id; + protected $store_id; + + /** + * @var Payer + */ + protected $payer; + + /** + * @var array + */ + protected $metadata; + + /** + * @var AdditionalInfo + */ + protected $additional_info; /** * @var string */ - protected $statement_descriptor; + protected $external_reference; + + /** + * @var double + */ + protected $transaction_amount; + + /** + * @var double + */ + protected $coupon_amount; + + /** + * @var int + */ + protected $differential_pricing_id; + + /** + * @var int + */ + protected $installments; + + /** + * @var TransactionDetails + */ + protected $transaction_details; /** - * @var boolean + * @var bool */ protected $binary_mode; /** * @var string */ - protected $date_of_expiration; + protected $statement_descriptor; /** * @var string */ - protected $callback_url; + protected $notification_url; /** * @var string */ - protected $token; + protected $processing_mode; /** * @var string */ - protected $issuer_id; + protected $merchant_account_id; + + /** + * @var PointOfInteraction + */ + protected $point_of_interaction; /** * @var string */ - protected $campaign_id; + protected $brand_id; /** - * @var double + * @var string */ - protected $coupon_amount; + protected $reserve_id; + + /** + * @var array + */ + protected $collector; /** * @var string */ - protected $coupon_code; + protected $callback_url; /** - * @var Payer + * @var double */ - protected $payer; + protected $application_fee; /** - * @var AdditionalInfo + * @var int */ - protected $additional_info; + protected $campaign_id; /** - * @var TransactionDetails + * @var bool */ - protected $transaction_details; + protected $capture; /** - * @var PointOfInteraction + * @var string */ - protected $point_of_interaction; + protected $coupon_code; /** - * @var object + * @var string */ - protected $metadata; + protected $token; /** * @var string @@ -145,8 +222,7 @@ class Payment extends AbstractEntity implements RequesterEntityInterface * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); $this->payer = new Payer($manager); $this->additional_info = new AdditionalInfo($manager); @@ -159,9 +235,8 @@ public function __construct($manager) * * @return void */ - public function setExcludedProperties() - { - $this->excluded_properties = ['session_id']; + public function setExcludedProperties(): void { + $this->excluded_properties = array('session_id'); } /** @@ -169,12 +244,11 @@ public function setExcludedProperties() * * @return array */ - public function getHeaders(): array - { - return [ - 'read' => [], - 'save' => ['x-meli-session-id: ' . $this->session_id], - ]; + public function getHeaders(): array { + return array( + 'read' => array(), + 'save' => array('x-meli-session-id: ' . $this->session_id), + ); } /** @@ -182,8 +256,7 @@ public function getHeaders(): array * * @return array */ - public function getUris(): array - { + public function getUris(): array { return array( 'post' => '/v1/asgard/payments', ); diff --git a/packages/sdk/src/Entity/Payment/PaymentV2.php b/packages/sdk/src/Entity/Payment/PaymentV2.php new file mode 100644 index 000000000..132f50b73 --- /dev/null +++ b/packages/sdk/src/Entity/Payment/PaymentV2.php @@ -0,0 +1,16 @@ + '/v2/asgard/payments', + ); + } +} diff --git a/packages/sdk/src/Entity/Payment/Phone.php b/packages/sdk/src/Entity/Payment/Phone.php index baab4f25d..a6f7821f2 100644 --- a/packages/sdk/src/Entity/Payment/Phone.php +++ b/packages/sdk/src/Entity/Payment/Phone.php @@ -8,13 +8,18 @@ * Class Phone * * @property string $number + * @property string $area_code * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class Phone extends AbstractEntity -{ +class Phone extends AbstractEntity { /** * @var string */ protected $number; + + /** + * @var string + */ + protected $area_code; } diff --git a/packages/sdk/src/Entity/Payment/PointOfInteraction.php b/packages/sdk/src/Entity/Payment/PointOfInteraction.php index d42d8e214..fa6c56410 100644 --- a/packages/sdk/src/Entity/Payment/PointOfInteraction.php +++ b/packages/sdk/src/Entity/Payment/PointOfInteraction.php @@ -3,18 +3,53 @@ namespace MercadoPago\PP\Sdk\Entity\Payment; use MercadoPago\PP\Sdk\Common\AbstractEntity; +use MercadoPago\PP\Sdk\Common\Manager; /** * Class PointOfInteraction * * @property string $type + * @property string $sub_type + * @property string $linked_to + * @property ApplicationData $application_data + * @property TransactionData $transaction_data * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class PointOfInteraction extends AbstractEntity -{ +class PointOfInteraction extends AbstractEntity { /** * @var string */ protected $type; + + /** + * @var string + */ + protected $sub_type; + + /** + * @var string + */ + protected $linked_to; + + /** + * @var ApplicationData + */ + protected $application_data; + + /** + * @var TransactionData + */ + protected $transaction_data; + + /** + * Payer constructor. + * + * @param Manager|null $manager + */ + public function __construct($manager) { + parent::__construct($manager); + $this->application_data = new ApplicationData($manager); + $this->transaction_data = new TransactionData($manager); + } } diff --git a/packages/sdk/src/Entity/Payment/ReceiverAddress.php b/packages/sdk/src/Entity/Payment/ReceiverAddress.php index dcf7ee3e9..8088e467e 100644 --- a/packages/sdk/src/Entity/Payment/ReceiverAddress.php +++ b/packages/sdk/src/Entity/Payment/ReceiverAddress.php @@ -8,15 +8,16 @@ * Class ReceiverAddress * * @property string $zip_code - * @property string $state_name - * @property string $city_name * @property string $street_name + * @property string $city_name + * @property string $state_name + * @property string $street_number + * @property string $floor * @property string $apartment * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class ReceiverAddress extends AbstractEntity -{ +class ReceiverAddress extends AbstractEntity { /** * @var string */ @@ -25,7 +26,7 @@ class ReceiverAddress extends AbstractEntity /** * @var string */ - protected $state_name; + protected $street_name; /** * @var string @@ -35,7 +36,17 @@ class ReceiverAddress extends AbstractEntity /** * @var string */ - protected $street_name; + protected $state_name; + + /** + * @var string + */ + protected $street_number; + + /** + * @var string + */ + protected $floor; /** * @var string diff --git a/packages/sdk/src/Entity/Payment/Seller.php b/packages/sdk/src/Entity/Payment/Seller.php new file mode 100644 index 000000000..9a147b849 --- /dev/null +++ b/packages/sdk/src/Entity/Payment/Seller.php @@ -0,0 +1,134 @@ +identification = new Identification($manager); + $this->phone = new Phone($manager); + $this->address = new AdditionalInfoAddress($manager); + } +} diff --git a/packages/sdk/src/Entity/Payment/Shipments.php b/packages/sdk/src/Entity/Payment/Shipments.php index 388ace129..a3cd8b8d2 100644 --- a/packages/sdk/src/Entity/Payment/Shipments.php +++ b/packages/sdk/src/Entity/Payment/Shipments.php @@ -8,14 +8,55 @@ /** * Class Shipments * - * @property ReceiverAddress $receiver_address + * @property string $delivery_promise + * @property string $drop_shipping + * @property string $local_pickup + * @property string $express_shipment + * @property string $safety + * @property boolean $withdrawn + * @property Tracking $tracking + * @property AdditionalInfoAddress $receiver_address * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class Shipments extends AbstractEntity -{ +class Shipments extends AbstractEntity { /** - * @var ReceiverAddress + * @var string + */ + protected $delivery_promise; + + /** + * @var string + */ + protected $drop_shipping; + + /** + * @var string + */ + protected $local_pickup; + + /** + * @var string + */ + protected $express_shipment; + + /** + * @var string + */ + protected $safety; + + /** + * @var boolean + */ + protected $withdrawn; + + /** + * @var Tracking + */ + protected $tracking; + + /** + * @var AdditionalInfoAddress */ protected $receiver_address; @@ -24,9 +65,9 @@ class Shipments extends AbstractEntity * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); - $this->receiver_address = new ReceiverAddress(); + $this->tracking = new Tracking($manager); + $this->receiver_address = new AdditionalInfoAddress($manager); } } diff --git a/packages/sdk/src/Entity/Payment/Tracking.php b/packages/sdk/src/Entity/Payment/Tracking.php new file mode 100644 index 000000000..8eec4bcbe --- /dev/null +++ b/packages/sdk/src/Entity/Payment/Tracking.php @@ -0,0 +1,25 @@ +bank_info = new BankInfo($manager); + } +} diff --git a/packages/sdk/src/Entity/Payment/TransactionDetails.php b/packages/sdk/src/Entity/Payment/TransactionDetails.php index 8706faad6..29ae7b6ed 100644 --- a/packages/sdk/src/Entity/Payment/TransactionDetails.php +++ b/packages/sdk/src/Entity/Payment/TransactionDetails.php @@ -8,13 +8,24 @@ * Class TransactionDetails * * @property string $financial_institution + * @property string $bank_transfer_id + * @property string $transaction_id * * @package MercadoPago\PP\Sdk\Entity\Payment */ -class TransactionDetails extends AbstractEntity -{ +class TransactionDetails extends AbstractEntity { /** * @var string */ protected $financial_institution; + + /** + * @var string + */ + protected $bank_transfer_id; + + /** + * @var string + */ + protected $transaction_id; } diff --git a/packages/sdk/src/Entity/Payment/TransactionInfo.php b/packages/sdk/src/Entity/Payment/TransactionInfo.php new file mode 100644 index 000000000..0abf6d750 --- /dev/null +++ b/packages/sdk/src/Entity/Payment/TransactionInfo.php @@ -0,0 +1,37 @@ +manager); + $transactionInfo->setEntity($entity); + parent::addEntity($transactionInfo, $key); + } +} diff --git a/packages/sdk/src/Entity/Preference/Address.php b/packages/sdk/src/Entity/Preference/Address.php index 0cf2e6d95..cbab35a68 100644 --- a/packages/sdk/src/Entity/Preference/Address.php +++ b/packages/sdk/src/Entity/Preference/Address.php @@ -8,23 +8,40 @@ * Class Address * * @property string $street_name - * @property int $street_number + * @property string $street_number + * @property string $neighborhood + * @property string $city + * @property string $federal_unit * @property string $zip_code * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class Address extends AbstractEntity -{ +class Address extends AbstractEntity { /** * @var string */ protected $street_name; /** - * @var int + * @var string */ protected $street_number; + /** + * @var string + */ + protected $neighborhood; + + /** + * @var string + */ + protected $city; + + /** + * @var string + */ + protected $federal_unit; + /** * @var string */ diff --git a/packages/sdk/src/Entity/Preference/BackUrl.php b/packages/sdk/src/Entity/Preference/BackUrl.php index 868e4c507..889db8edc 100644 --- a/packages/sdk/src/Entity/Preference/BackUrl.php +++ b/packages/sdk/src/Entity/Preference/BackUrl.php @@ -13,8 +13,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class BackUrl extends AbstractEntity -{ +class BackUrl extends AbstractEntity { /** * @var string */ diff --git a/packages/sdk/src/Entity/Preference/DifferentialPricing.php b/packages/sdk/src/Entity/Preference/DifferentialPricing.php index 854c053a9..0719be6be 100644 --- a/packages/sdk/src/Entity/Preference/DifferentialPricing.php +++ b/packages/sdk/src/Entity/Preference/DifferentialPricing.php @@ -11,8 +11,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class DifferentialPricing extends AbstractEntity -{ +class DifferentialPricing extends AbstractEntity { /** * @var int */ diff --git a/packages/sdk/src/Entity/Preference/ExcludedPaymentMethod.php b/packages/sdk/src/Entity/Preference/ExcludedPaymentMethod.php index 54e5945e5..0f50136c0 100644 --- a/packages/sdk/src/Entity/Preference/ExcludedPaymentMethod.php +++ b/packages/sdk/src/Entity/Preference/ExcludedPaymentMethod.php @@ -11,8 +11,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class ExcludedPaymentMethod extends AbstractEntity -{ +class ExcludedPaymentMethod extends AbstractEntity { /** * @var string */ diff --git a/packages/sdk/src/Entity/Preference/ExcludedPaymentMethodList.php b/packages/sdk/src/Entity/Preference/ExcludedPaymentMethodList.php index 863883604..69c4efc52 100644 --- a/packages/sdk/src/Entity/Preference/ExcludedPaymentMethodList.php +++ b/packages/sdk/src/Entity/Preference/ExcludedPaymentMethodList.php @@ -9,16 +9,14 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class ExcludedPaymentMethodList extends AbstractCollection -{ +class ExcludedPaymentMethodList extends AbstractCollection { /** * Add entity to collection * * @param array $entity * @param string|null $key */ - public function add(array $entity, string $key = null) - { + public function add(array $entity, string $key = null): void { $excludedPaymentMethod = new ExcludedPaymentMethod($this->manager); $excludedPaymentMethod->setEntity($entity); parent::addEntity($excludedPaymentMethod, $key); diff --git a/packages/sdk/src/Entity/Preference/ExcludedPaymentType.php b/packages/sdk/src/Entity/Preference/ExcludedPaymentType.php index 9dcf39683..ac1a63ace 100644 --- a/packages/sdk/src/Entity/Preference/ExcludedPaymentType.php +++ b/packages/sdk/src/Entity/Preference/ExcludedPaymentType.php @@ -11,8 +11,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class ExcludedPaymentType extends AbstractEntity -{ +class ExcludedPaymentType extends AbstractEntity { /** * @var string */ diff --git a/packages/sdk/src/Entity/Preference/ExcludedPaymentTypeList.php b/packages/sdk/src/Entity/Preference/ExcludedPaymentTypeList.php index 3aad404e4..2b1a2f7a4 100644 --- a/packages/sdk/src/Entity/Preference/ExcludedPaymentTypeList.php +++ b/packages/sdk/src/Entity/Preference/ExcludedPaymentTypeList.php @@ -9,16 +9,14 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class ExcludedPaymentTypeList extends AbstractCollection -{ +class ExcludedPaymentTypeList extends AbstractCollection { /** * Add entity to collection * * @param array $entity * @param string|null $key */ - public function add(array $entity, string $key = null) - { + public function add(array $entity, string $key = null): void { $excludedPaymentType = new ExcludedPaymentType($this->manager); $excludedPaymentType->setEntity($entity); parent::addEntity($excludedPaymentType, $key); diff --git a/packages/sdk/src/Entity/Preference/FreeMethod.php b/packages/sdk/src/Entity/Preference/FreeMethod.php index 6dbb8b895..d4fc0223f 100644 --- a/packages/sdk/src/Entity/Preference/FreeMethod.php +++ b/packages/sdk/src/Entity/Preference/FreeMethod.php @@ -11,8 +11,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class FreeMethod extends AbstractEntity -{ +class FreeMethod extends AbstractEntity { /** * @var int */ diff --git a/packages/sdk/src/Entity/Preference/FreeMethodList.php b/packages/sdk/src/Entity/Preference/FreeMethodList.php index 99d6fe751..def112549 100644 --- a/packages/sdk/src/Entity/Preference/FreeMethodList.php +++ b/packages/sdk/src/Entity/Preference/FreeMethodList.php @@ -9,16 +9,14 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class FreeMethodList extends AbstractCollection -{ +class FreeMethodList extends AbstractCollection { /** * Add entity to collection * * @param array $entity * @param string|null $key */ - public function add(array $entity, string $key = null) - { + public function add(array $entity, string $key = null): void { $freeMethod = new FreeMethod($this->manager); $freeMethod->setEntity($entity); parent::addEntity($freeMethod, $key); diff --git a/packages/sdk/src/Entity/Preference/Item.php b/packages/sdk/src/Entity/Preference/Item.php index ac8b0713e..191918c5f 100644 --- a/packages/sdk/src/Entity/Preference/Item.php +++ b/packages/sdk/src/Entity/Preference/Item.php @@ -7,28 +7,27 @@ /** * Class Item * - * @property string $category_id - * @property string $currency_id - * @property string $description * @property string $id + * @property string $title + * @property string $description * @property string $picture_url + * @property string $category_id * @property int $quantity - * @property string $title + * @property string $currency_id * @property float $unit_price * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class Item extends AbstractEntity -{ +class Item extends AbstractEntity { /** * @var string */ - protected $category_id; + protected $id; /** * @var string */ - protected $currency_id; + protected $title; /** * @var string @@ -38,12 +37,12 @@ class Item extends AbstractEntity /** * @var string */ - protected $id; + protected $picture_url; /** * @var string */ - protected $picture_url; + protected $category_id; /** * @var int @@ -53,7 +52,7 @@ class Item extends AbstractEntity /** * @var string */ - protected $title; + protected $currency_id; /** * @var float diff --git a/packages/sdk/src/Entity/Preference/ItemList.php b/packages/sdk/src/Entity/Preference/ItemList.php index cb6a41ea7..648824bcf 100644 --- a/packages/sdk/src/Entity/Preference/ItemList.php +++ b/packages/sdk/src/Entity/Preference/ItemList.php @@ -9,16 +9,14 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class ItemList extends AbstractCollection -{ +class ItemList extends AbstractCollection { /** * Add entity to collection * * @param array $entity * @param string|null $key */ - public function add(array $entity, string $key = null) - { + public function add(array $entity, string $key = null): void { $item = new Item($this->manager); $item->setEntity($entity); parent::addEntity($item, $key); diff --git a/packages/sdk/src/Entity/Preference/Payer.php b/packages/sdk/src/Entity/Preference/Payer.php index e4841e407..fedcf2585 100644 --- a/packages/sdk/src/Entity/Preference/Payer.php +++ b/packages/sdk/src/Entity/Preference/Payer.php @@ -8,27 +8,35 @@ /** * Class Payer * - * @property Address $address - * @property string $date_created + * @property string $entity_type + * @property string $type + * @property string $id * @property string $email * @property PayerIdentification $identification * @property string $name - * @property Phone $phone * @property string $surname + * @property string $operator_id + * @property Address $address + * @property Phone $phone + * @property string $date_created * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class Payer extends AbstractEntity -{ +class Payer extends AbstractEntity { /** - * @var Address + * @var string */ - protected $address; + protected $entity_type; /** * @var string */ - protected $date_created; + protected $type; + + /** + * @var string + */ + protected $id; /** * @var string @@ -45,6 +53,21 @@ class Payer extends AbstractEntity */ protected $name; + /** + * @var string + */ + protected $surname; + + /** + * @var string + */ + protected $operator_id; + + /** + * @var Address + */ + protected $address; + /** * @var Phone */ @@ -53,18 +76,17 @@ class Payer extends AbstractEntity /** * @var string */ - protected $surname; + protected $date_created; /** * Payer constructor. * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); - $this->address = new Address($manager); + $this->address = new Address($manager); $this->identification = new PayerIdentification($manager); - $this->phone = new Phone($manager); + $this->phone = new Phone($manager); } } diff --git a/packages/sdk/src/Entity/Preference/PayerIdentification.php b/packages/sdk/src/Entity/Preference/PayerIdentification.php index 19b63a2a0..bfb72f72e 100644 --- a/packages/sdk/src/Entity/Preference/PayerIdentification.php +++ b/packages/sdk/src/Entity/Preference/PayerIdentification.php @@ -7,20 +7,19 @@ /** * Class PayerIdentification * - * @property string $number * @property string $type + * @property string $number * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class PayerIdentification extends AbstractEntity -{ +class PayerIdentification extends AbstractEntity { /** * @var string */ - protected $number; + protected $type; /** * @var string */ - protected $type; + protected $number; } diff --git a/packages/sdk/src/Entity/Preference/PaymentMethod.php b/packages/sdk/src/Entity/Preference/PaymentMethod.php index 200ed4815..83d1d17dd 100644 --- a/packages/sdk/src/Entity/Preference/PaymentMethod.php +++ b/packages/sdk/src/Entity/Preference/PaymentMethod.php @@ -8,35 +8,34 @@ /** * Class PaymentMethod * - * @property int $default_installments - * @property string $default_payment_method_id * @property ExcludedPaymentMethodList $excluded_payment_methods * @property ExcludedPaymentTypeList $excluded_payment_types + * @property string $default_payment_method_id + * @property int $default_installments * @property int $installments * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class PaymentMethod extends AbstractEntity -{ +class PaymentMethod extends AbstractEntity { /** - * @var int + * @var ExcludedPaymentMethodList */ - protected $default_installments; + protected $excluded_payment_methods; /** - * @var string + * @var ExcludedPaymentTypeList */ - protected $default_payment_method_id; + protected $excluded_payment_types; /** - * @var ExcludedPaymentMethodList + * @var string */ - protected $excluded_payment_methods; + protected $default_payment_method_id; /** - * @var ExcludedPaymentTypeList + * @var int */ - protected $excluded_payment_types; + protected $default_installments; /** * @var int @@ -48,8 +47,7 @@ class PaymentMethod extends AbstractEntity * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); $this->excluded_payment_methods = new ExcludedPaymentMethodList($manager); $this->excluded_payment_types = new ExcludedPaymentTypeList($manager); diff --git a/packages/sdk/src/Entity/Preference/Phone.php b/packages/sdk/src/Entity/Preference/Phone.php index ba306369c..59167cb8c 100644 --- a/packages/sdk/src/Entity/Preference/Phone.php +++ b/packages/sdk/src/Entity/Preference/Phone.php @@ -12,8 +12,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class Phone extends AbstractEntity -{ +class Phone extends AbstractEntity { /** * @var string */ diff --git a/packages/sdk/src/Entity/Preference/Preference.php b/packages/sdk/src/Entity/Preference/Preference.php index ec819f12a..49ee90e2a 100644 --- a/packages/sdk/src/Entity/Preference/Preference.php +++ b/packages/sdk/src/Entity/Preference/Preference.php @@ -5,39 +5,39 @@ use MercadoPago\PP\Sdk\Common\AbstractEntity; use MercadoPago\PP\Sdk\Common\Manager; use MercadoPago\PP\Sdk\Interfaces\RequesterEntityInterface; +use MercadoPago\PP\Sdk\Entity\Payment\AdditionalInfo; /** * Class Preference * - * @property string $additional_info + * @property AdditionalInfo $additional_info * @property string $auto_return - * @property BackUrl $back_urls - * @property boolean $binary_mode - * @property string $date_of_expiration - * @property object $differential_pricing + * @property bool $binary_mode * @property string $expiration_date_from * @property string $expiration_date_to - * @property boolean $expires + * @property bool $expires * @property string $external_reference - * @property ItemList $items - * @property string $marketplace - * @property float $marketplace_fee - * @property object $metadata * @property string $notification_url - * @property Payer $payer - * @property PaymentMethod $payment_methods * @property string $purpose + * @property string $statement_descriptor + * @property ItemList $items + * @property PaymentMethod $payment_methods + * @property BackUrl $back_urls + * @property Payer $payer * @property Shipment $shipments + * @property array $metadata + * @property string $date_of_expiration + * @property array $differential_pricing + * @property string $marketplace + * @property float $marketplace_fee * @property string $sponsor_id - * @property string $statement_descriptor * @property TrackList $tracks * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class Preference extends AbstractEntity implements RequesterEntityInterface -{ +class Preference extends AbstractEntity implements RequesterEntityInterface { /** - * @var string + * @var AdditionalInfo */ protected $additional_info; @@ -47,44 +47,44 @@ class Preference extends AbstractEntity implements RequesterEntityInterface protected $auto_return; /** - * @var BackUrl + * @var bool */ - protected $back_urls; + protected $binary_mode; /** - * @var boolean + * @var string */ - protected $binary_mode; + protected $expiration_date_from; /** * @var string */ - protected $date_of_expiration; + protected $expiration_date_to; /** - * @var object + * @var bool */ - protected $differential_pricing; + protected $expires; /** * @var string */ - protected $expiration_date_from; + protected $external_reference; /** * @var string */ - protected $expiration_date_to; + protected $notification_url; /** - * @var boolean + * @var string */ - protected $expires; + protected $purpose; /** * @var string */ - protected $external_reference; + protected $statement_descriptor; /** * @var ItemList @@ -92,54 +92,54 @@ class Preference extends AbstractEntity implements RequesterEntityInterface protected $items; /** - * @var string + * @var PaymentMethod */ - protected $marketplace; + protected $payment_methods; /** - * @var float + * @var BackUrl */ - protected $marketplace_fee; + protected $back_urls; /** - * @var object + * @var Payer */ - protected $metadata; + protected $payer; /** - * @var string + * @var Shipment */ - protected $notification_url; + protected $shipments; /** - * @var Payer + * @var array */ - protected $payer; + protected $metadata; /** - * @var PaymentMethod + * @var string */ - protected $payment_methods; + protected $date_of_expiration; /** - * @var string + * @var array */ - protected $purpose; + protected $differential_pricing; /** - * @var Shipment + * @var string */ - protected $shipments; + protected $marketplace; /** - * @var string + * @var float */ - protected $sponsor_id; + protected $marketplace_fee; /** * @var string */ - protected $statement_descriptor; + protected $sponsor_id; /** * @var TrackList @@ -151,15 +151,15 @@ class Preference extends AbstractEntity implements RequesterEntityInterface * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); - $this->back_urls = new BackUrl($manager); - $this->items = new ItemList($manager); - $this->payer = new Payer($manager); - $this->payment_methods = new PaymentMethod($manager); - $this->shipments = new Shipment($manager); - $this->tracks = new TrackList($manager); + $this->additional_info = new AdditionalInfo($manager); + $this->back_urls = new BackUrl($manager); + $this->items = new ItemList($manager); + $this->payer = new Payer($manager); + $this->payment_methods = new PaymentMethod($manager); + $this->shipments = new Shipment($manager); + $this->tracks = new TrackList($manager); } /** @@ -167,9 +167,8 @@ public function __construct($manager) * * @return void */ - public function setExcludedProperties() - { - $this->excluded_properties = []; + public function setExcludedProperties(): void { + $this->excluded_properties = array(); } /** @@ -177,12 +176,11 @@ public function setExcludedProperties() * * @return array */ - public function getHeaders(): array - { - return [ - 'read' => [], - 'save' => [], - ]; + public function getHeaders(): array { + return array( + 'read' => array(), + 'save' => array(), + ); } /** @@ -190,8 +188,7 @@ public function getHeaders(): array * * @return array */ - public function getUris(): array - { + public function getUris(): array { return array( 'post' => '/v1/asgard/preferences', ); diff --git a/packages/sdk/src/Entity/Preference/ReceiverAddress.php b/packages/sdk/src/Entity/Preference/ReceiverAddress.php index 3b6299bfa..43a53924c 100644 --- a/packages/sdk/src/Entity/Preference/ReceiverAddress.php +++ b/packages/sdk/src/Entity/Preference/ReceiverAddress.php @@ -7,32 +7,31 @@ /** * Class ReceiverAddress * - * @property string $apartment + * @property string $zip_code + * @property string $street_name * @property string $city_name - * @property string $floor * @property string $state_name - * @property string $street_name - * @property int $street_number - * @property string $zip_code + * @property string $street_number + * @property string $floor + * @property string $apartment * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class ReceiverAddress extends AbstractEntity -{ +class ReceiverAddress extends AbstractEntity { /** * @var string */ - protected $apartment; + protected $zip_code; /** * @var string */ - protected $city_name; + protected $street_name; /** * @var string */ - protected $floor; + protected $city_name; /** * @var string @@ -42,15 +41,15 @@ class ReceiverAddress extends AbstractEntity /** * @var string */ - protected $street_name; + protected $street_number; /** - * @var int + * @var string */ - protected $street_number; + protected $floor; /** * @var string */ - protected $zip_code; + protected $apartment; } diff --git a/packages/sdk/src/Entity/Preference/Shipment.php b/packages/sdk/src/Entity/Preference/Shipment.php index 1916297d3..eba3a355a 100644 --- a/packages/sdk/src/Entity/Preference/Shipment.php +++ b/packages/sdk/src/Entity/Preference/Shipment.php @@ -8,28 +8,32 @@ /** * Class Shipment * + * @property string $default_shipping_method + * @property ReceiverAddress $receiver_address * @property float $cost - * @property int $default_shipping_method * @property string $dimensions * @property FreeMethodList $free_methods * @property boolean $free_shipping * @property boolean $local_pickup * @property string $mode - * @property ReceiverAddress $receiver_address * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class Shipment extends AbstractEntity -{ +class Shipment extends AbstractEntity { /** - * @var float + * @var string */ - protected $cost; + protected $default_shipping_method; /** - * @var int + * @var ReceiverAddress */ - protected $default_shipping_method; + protected $receiver_address; + + /** + * @var float + */ + protected $cost; /** * @var string @@ -56,18 +60,12 @@ class Shipment extends AbstractEntity */ protected $mode; - /** - * @var ReceiverAddress - */ - protected $receiver_address; - /** * Shipment constructor. * * @param Manager|null $manager */ - public function __construct($manager) - { + public function __construct($manager) { parent::__construct($manager); $this->free_methods = new FreeMethodList($manager); $this->receiver_address = new ReceiverAddress($manager); diff --git a/packages/sdk/src/Entity/Preference/Track.php b/packages/sdk/src/Entity/Preference/Track.php index 34513d62b..8f2e2c3fc 100644 --- a/packages/sdk/src/Entity/Preference/Track.php +++ b/packages/sdk/src/Entity/Preference/Track.php @@ -12,8 +12,7 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class Track extends AbstractEntity -{ +class Track extends AbstractEntity { /** * @var string */ diff --git a/packages/sdk/src/Entity/Preference/TrackList.php b/packages/sdk/src/Entity/Preference/TrackList.php index 0a011bbd9..8725ae7e0 100644 --- a/packages/sdk/src/Entity/Preference/TrackList.php +++ b/packages/sdk/src/Entity/Preference/TrackList.php @@ -9,16 +9,14 @@ * * @package MercadoPago\PP\Sdk\Entity\Preference */ -class TrackList extends AbstractCollection -{ +class TrackList extends AbstractCollection { /** * Add entity to collection * * @param array $entity * @param string|null $key */ - public function add(array $entity, string $key = null) - { + public function add(array $entity, string $key = null): void { $track = new Track($this->manager); $track->setEntity($entity); parent::addEntity($track, $key); diff --git a/packages/sdk/src/HttpClient/HttpClient.php b/packages/sdk/src/HttpClient/HttpClient.php index c189800ea..7ee5c8f0a 100644 --- a/packages/sdk/src/HttpClient/HttpClient.php +++ b/packages/sdk/src/HttpClient/HttpClient.php @@ -5,14 +5,14 @@ use MercadoPago\PP\Sdk\Common\AbstractEntity; use MercadoPago\PP\Sdk\Common\AbstractCollection; use MercadoPago\PP\Sdk\HttpClient\Requester\RequesterInterface; +use Exception; /** * Class HttpClient * * @package MercadoPago\PP\Sdk\HttpClient */ -class HttpClient implements HttpClientInterface -{ +class HttpClient implements HttpClientInterface { /** * Base Url * @@ -33,41 +33,28 @@ class HttpClient implements HttpClientInterface * @param string $baseUrl * @param RequesterInterface $requester */ - public function __construct(string $baseUrl, RequesterInterface $requester) - { + public function __construct(string $baseUrl, RequesterInterface $requester) { $this->baseUrl = $baseUrl; $this->requester = $requester; } - public function get(string $uri, array $headers = []): Response - { + public function get(string $uri, array $headers = array()): Response { return $this->send('GET', $uri, $headers, null); } - public function put(string $uri, array $headers = [], $body = null): Response - { + public function put(string $uri, array $headers = array(), $body = null): Response { return $this->send('PUT', $uri, $headers, $body); } - public function post(string $uri, array $headers = [], $body = null): Response - { + public function post(string $uri, array $headers = array(), $body = null): Response { return $this->send('POST', $uri, $headers, $body); } - public function send(string $method, string $uri, array $headers = [], $body = null): Response - { - if (null !== $body && !is_string($body) && - !is_subclass_of($body, AbstractEntity::class) && !is_subclass_of($body, AbstractCollection::class) + public function send(string $method, string $uri, array $headers = array(), $body = null): Response { + if (null !== $body && ! is_string($body) && + ! is_subclass_of($body, 'MercadoPago\PP\Sdk\Common\AbstractEntity') && ! is_subclass_of($body, 'MercadoPago\PP\Sdk\Common\AbstractCollection') ) { - throw new \Exception( - sprintf( - '%s::send(): Argument #4 ($body) must be of type string|%s|%snull, %s given', - self::class, - AbstractEntity::class, - AbstractCollection::class, - gettype($body) - ) - ); + throw new Exception(sprintf('%s::send(): Argument #4 ($body) must be of type string|%s|%snull, %s given', self::class, 'MercadoPago\PP\Sdk\Common\AbstractEntity', 'MercadoPago\PP\Sdk\Common\AbstractCollection', gettype($body))); } return $this->sendRequest( @@ -80,8 +67,7 @@ public function send(string $method, string $uri, array $headers = [], $body = n * * @return resource */ - private function createRequest(string $method, string $uri, array $headers = [], $body = null) - { + private function createRequest(string $method, string $uri, array $headers = array(), $body = null) { $url = $this->baseUrl . $uri; return $this->requester->createRequest($method, $url, $headers, $body); } @@ -89,8 +75,7 @@ private function createRequest(string $method, string $uri, array $headers = [], /** * @param resource $request */ - public function sendRequest($request): Response - { + public function sendRequest($request): Response { return $this->requester->sendRequest($request); } } diff --git a/packages/sdk/src/HttpClient/HttpClientInterface.php b/packages/sdk/src/HttpClient/HttpClientInterface.php index ff56c6e9c..29458ac52 100644 --- a/packages/sdk/src/HttpClient/HttpClientInterface.php +++ b/packages/sdk/src/HttpClient/HttpClientInterface.php @@ -3,58 +3,58 @@ namespace MercadoPago\PP\Sdk\HttpClient; use MercadoPago\PP\Sdk\Common\AbstractEntity; +use Exception; /** * Interface HttpClientInterface * * @package MercadoPago\PP\Sdk\HttpClient */ -interface HttpClientInterface -{ - /** - * Sends a GET request. - * - * @param string $uri - * @param array $headers - * @return Response - * @throws \Exception - */ - public function get(string $uri, array $headers = []): Response; +interface HttpClientInterface { + /** + * Sends a GET request. + * + * @param string $uri + * @param array $headers + * @return Response + * @throws Exception + */ + public function get(string $uri, array $headers = array()): Response; - /** - * Sends a PUT request. - * - * @param string $uri - * @param array $headers - * @param string|AbstractEntity|null $body - * - * @return Response - * @throws \Exception - */ - public function put(string $uri, array $headers = [], $body = null): Response; + /** + * Sends a PUT request. + * + * @param string $uri + * @param array $headers + * @param string|AbstractEntity|null $body + * + * @return Response + * @throws Exception + */ + public function put(string $uri, array $headers = array(), $body = null): Response; - /** - * Sends a POST request. - * - * @param string $uri - * @param array $headers - * @param string|AbstractEntity|null $body - * - * @return Response - * @throws \Exception - */ - public function post(string $uri, array $headers = [], $body = null): Response; + /** + * Sends a POST request. + * + * @param string $uri + * @param array $headers + * @param string|AbstractEntity|null $body + * + * @return Response + * @throws Exception + */ + public function post(string $uri, array $headers = array(), $body = null): Response; - /** - * Sends a request with any HTTP method. - * - * @param string $method HTTP method to use - * @param string $uri - * @param array $headers - * @param string|AbstractEntity|null $body - * - * @return Response - * @throws \Exception - */ - public function send(string $method, string $uri, array $headers = [], $body = null): Response; + /** + * Sends a request with any HTTP method. + * + * @param string $method HTTP method to use + * @param string $uri + * @param array $headers + * @param string|AbstractEntity|null $body + * + * @return Response + * @throws Exception + */ + public function send(string $method, string $uri, array $headers = array(), $body = null): Response; } diff --git a/packages/sdk/src/HttpClient/Requester/CurlRequester.php b/packages/sdk/src/HttpClient/Requester/CurlRequester.php index 90d36e430..db9fba245 100644 --- a/packages/sdk/src/HttpClient/Requester/CurlRequester.php +++ b/packages/sdk/src/HttpClient/Requester/CurlRequester.php @@ -5,24 +5,22 @@ use MercadoPago\PP\Sdk\Common\AbstractCollection; use MercadoPago\PP\Sdk\Common\AbstractEntity; use MercadoPago\PP\Sdk\HttpClient\Response; +use Exception; /** * Class CurlRequester * * @package MercadoPago\PP\Sdk\HttpClient\Requester */ -class CurlRequester implements RequesterInterface -{ +class CurlRequester implements RequesterInterface { /** * CurlRequester constructor. * - * @throws \Exception + * @throws Exception */ - public function __construct() - { - if (!extension_loaded('curl')) { - throw new \Exception('cURL extension not found.' . - 'You need to enable cURL in your php.ini or another configuration you have.'); + public function __construct() { + if ( ! extension_loaded('curl')) { + throw new Exception('cURL extension not found.' . 'You need to enable cURL in your php.ini or another configuration you have.'); } } @@ -33,20 +31,19 @@ public function __construct() * @param string|AbstractEntity|AbstractCollection|array|null $body * * @return resource - * @throws \Exception + * @throws Exception */ - public function createRequest(string $method, string $uri, array $headers = [], $body = null) - { - $json_content = true; - $form_content = false; + public function createRequest(string $method, string $uri, array $headers = array(), $body = null) { + $json_content = true; + $form_content = false; $default_content_type = true; if (isset($headers) && is_array($headers)) { foreach ($headers as $h => $v) { if ('content-type' === $h) { $default_content_type = false; - $json_content = 'application/json' === $v; - $form_content = 'application/x-www-form-urlencoded' === $v; + $json_content = 'application/json' === $v; + $form_content = 'application/x-www-form-urlencoded' === $v; break; } } @@ -56,16 +53,16 @@ public function createRequest(string $method, string $uri, array $headers = [], } $connect = $this->curlInit(); - $this->setOption($connect, CURLOPT_USERAGENT, 'platform:v1-whitelabel,type:mp_sdk'); - $this->setOption($connect, CURLOPT_RETURNTRANSFER, true); + $this->setOption($connect, \CURLOPT_USERAGENT, 'platform:v1-whitelabel,type:mp_sdk'); + $this->setOption($connect, \CURLOPT_RETURNTRANSFER, true); // @TODO define CAINFO when implementing SDK // $this->setOption($connect, CURLOPT_SSL_VERIFYPEER, true); // $this->setOption( $connect, CURLOPT_CAINFO, $GLOBALS['LIB_LOCATION'] . '/cacert.pem' ); - $this->setOption($connect, CURLOPT_CUSTOMREQUEST, $method); - $this->setOption($connect, CURLOPT_HTTPHEADER, $headers); - $this->setOption($connect, CURLOPT_URL, $uri); + $this->setOption($connect, \CURLOPT_CUSTOMREQUEST, $method); + $this->setOption($connect, \CURLOPT_HTTPHEADER, $headers); + $this->setOption($connect, \CURLOPT_URL, $uri); if (isset($body)) { if ($json_content) { @@ -76,14 +73,14 @@ public function createRequest(string $method, string $uri, array $headers = [], } if (function_exists('json_last_error')) { $json_error = json_last_error(); - if (JSON_ERROR_NONE !== $json_error) { - throw new \Exception("JSON Error [{$json_error}] - Data: " . $body); + if (\JSON_ERROR_NONE !== $json_error) { + throw new Exception("JSON Error [{$json_error}] - Data: " . $body); } } } elseif ($form_content) { $body = self::buildFormData($body); } - $this->setOption($connect, CURLOPT_POSTFIELDS, $body); + $this->setOption($connect, \CURLOPT_POSTFIELDS, $body); } return $connect; @@ -92,18 +89,17 @@ public function createRequest(string $method, string $uri, array $headers = [], /** * @param resource $request * - * @throws \Exception + * @throws Exception */ - public function sendRequest($request): Response - { + public function sendRequest($request): Response { $response = new Response(); $api_result = $this->curlExec($request); if ($this->curlErrno($request)) { - throw new \Exception($this->curlError($request)); + throw new Exception($this->curlError($request)); } - $info = $this->curlGetInfo($request); + $info = $this->curlGetInfo($request); $api_http_code = $info['http_code']; // @TODO: call logging service when ready @@ -125,12 +121,11 @@ public function sendRequest($request): Response * * @return string */ - public static function buildFormData(array $params): string - { + public static function buildFormData(array $params): string { if (function_exists('http_build_query')) { return http_build_query($params, '', '&'); } else { - $elements = []; + $elements = array(); foreach ($params as $name => $value) { $elements[] = "{$name}=" . rawurldecode($value); @@ -145,56 +140,49 @@ public static function buildFormData(array $params): string * * @return resource */ - protected function curlInit() - { + protected function curlInit() { return curl_init(); } /** * @codeCoverageIgnore */ - protected function curlClose($request) - { + protected function curlClose($request): void { curl_close($request); } /** * @codeCoverageIgnore */ - protected function setOption($connect, $option, $value) - { + protected function setOption($connect, $option, $value): void { curl_setopt($connect, $option, $value); } /** * @codeCoverageIgnore */ - protected function curlExec($request) - { + protected function curlExec($request) { return curl_exec($request); } /** * @codeCoverageIgnore */ - protected function curlErrno($request): int - { + protected function curlErrno($request): int { return curl_errno($request); } /** * @codeCoverageIgnore */ - protected function curlError($request): string - { + protected function curlError($request): string { return curl_error($request); } /** * @codeCoverageIgnore */ - protected function curlGetInfo($request) - { + protected function curlGetInfo($request) { return curl_getinfo($request); } } diff --git a/packages/sdk/src/HttpClient/Requester/RequesterInterface.php b/packages/sdk/src/HttpClient/Requester/RequesterInterface.php index 2647bfefd..97f6a163a 100644 --- a/packages/sdk/src/HttpClient/Requester/RequesterInterface.php +++ b/packages/sdk/src/HttpClient/Requester/RequesterInterface.php @@ -11,14 +11,13 @@ * * @package MercadoPago\PP\Sdk\HttpClient\Requester */ -interface RequesterInterface -{ +interface RequesterInterface { /** * @param string|AbstractEntity|AbstractCollection|null $body * * @return resource */ - public function createRequest(string $method, string $uri, array $headers = [], $body = null); + public function createRequest(string $method, string $uri, array $headers = array(), $body = null); /** * @param resource $request diff --git a/packages/sdk/src/HttpClient/Response.php b/packages/sdk/src/HttpClient/Response.php index 516cedda7..0122a7e73 100644 --- a/packages/sdk/src/HttpClient/Response.php +++ b/packages/sdk/src/HttpClient/Response.php @@ -10,8 +10,7 @@ * * @package MercadoPago\PP\Sdk\HttpClient */ -class Response -{ +class Response { /** * Response status * @@ -29,8 +28,7 @@ class Response /** * Response constructor. */ - public function __construct() - { + public function __construct() { } /** @@ -38,8 +36,7 @@ public function __construct() * * @return int **/ - public function getStatus(): int - { + public function getStatus(): int { return $this->status; } @@ -50,8 +47,7 @@ public function getStatus(): int * * @return void **/ - public function setStatus(int $status) - { + public function setStatus(int $status): void { $this->status = $status; } @@ -60,8 +56,7 @@ public function setStatus(int $status) * * @return object|null **/ - public function getData() - { + public function getData() { return $this->data; } @@ -72,8 +67,7 @@ public function getData() * * @return void **/ - public function setData($data) - { + public function setData($data): void { $this->data = $data; } } diff --git a/packages/sdk/src/Interfaces/EntityInterface.php b/packages/sdk/src/Interfaces/EntityInterface.php index 2099fda98..ed2931de5 100644 --- a/packages/sdk/src/Interfaces/EntityInterface.php +++ b/packages/sdk/src/Interfaces/EntityInterface.php @@ -2,8 +2,7 @@ namespace MercadoPago\PP\Sdk\Interfaces; -interface EntityInterface -{ +interface EntityInterface { /** * @param string $name * @@ -60,5 +59,5 @@ public function jsonSerialize(): array; * * @return void */ - public function setExcludedProperties(); + public function setExcludedProperties(): void; } diff --git a/packages/sdk/src/Interfaces/RequesterEntityInterface.php b/packages/sdk/src/Interfaces/RequesterEntityInterface.php index ddb7ad073..69473301a 100644 --- a/packages/sdk/src/Interfaces/RequesterEntityInterface.php +++ b/packages/sdk/src/Interfaces/RequesterEntityInterface.php @@ -1,9 +1,9 @@ requester); + public function getEntityInstance(string $entityName, string $baseUrl) { + $client = new HttpClient($baseUrl, $this->requester); $manager = new Manager($client, $this->config); return new $entityName($manager); } @@ -66,24 +69,42 @@ public function getEntityInstance(string $entityName, string $baseUrl) /** * @return Preference */ - public function getPreferenceInstance() - { + public function getPreferenceInstance() { return $this->getEntityInstance('MercadoPago\PP\Sdk\Entity\Preference\Preference', Constants::BASEURL_MP); } /** * @return Notification */ - public function getNotificationInstance() - { + public function getNotificationInstance() { return $this->getEntityInstance('MercadoPago\PP\Sdk\Entity\Notification\Notification', Constants::BASEURL_MP); } /** * @return Payment */ - public function getPaymentInstance() - { + public function getPaymentInstance() { return $this->getEntityInstance('MercadoPago\PP\Sdk\Entity\Payment\Payment', Constants::BASEURL_MP); } + + /** + * @return PaymentV2 + */ + public function getPaymentV2Instance() { + return $this->getEntityInstance('MercadoPago\PP\Sdk\Entity\Payment\PaymentV2', Constants::BASEURL_MP); + } + + /** + * @return Multipayment + */ + public function getMultipaymentInstance() { + return $this->getEntityInstance('MercadoPago\PP\Sdk\Entity\Payment\Multipayment', Constants::BASEURL_MP); + } + + /** + * @return MultipaymentV2 + */ + public function getMultipaymentV2Instance() { + return $this->getEntityInstance('MercadoPago\PP\Sdk\Entity\Payment\MultipaymentV2', Constants::BASEURL_MP); + } } diff --git a/packages/sdk/vendor/autoload.php b/packages/sdk/vendor/autoload.php index 44b829dac..d7d5313b1 100644 --- a/packages/sdk/vendor/autoload.php +++ b/packages/sdk/vendor/autoload.php @@ -2,24 +2,24 @@ // autoload.php @generated by Composer -if (PHP_VERSION_ID < 50600) { - if (!headers_sent()) { +if (\PHP_VERSION_ID < 50600) { + if ( ! headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } - $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; - if (!ini_get('display_errors')) { - if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { - fwrite(STDERR, $err); - } elseif (!headers_sent()) { + $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running ' . \PHP_VERSION . ', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.' . \PHP_EOL; + if ( ! ini_get('display_errors')) { + if (\PHP_SAPI === 'cli' || \PHP_SAPI === 'phpdbg') { + fwrite(\STDERR, $err); + } elseif ( ! headers_sent()) { echo $err; } } trigger_error( $err, - E_USER_ERROR + \E_USER_ERROR ); } require_once __DIR__ . '/composer/autoload_real.php'; -return ComposerAutoloaderInit7df991cb6c45ae6eb5b10f00fabea309::getLoader(); +return ComposerAutoloaderInit9311624e15b6e009950b2fbe89edbcce::getLoader(); diff --git a/packages/sdk/vendor/composer/ClassLoader.php b/packages/sdk/vendor/composer/ClassLoader.php index 7824d8f7e..d33f3be1b 100644 --- a/packages/sdk/vendor/composer/ClassLoader.php +++ b/packages/sdk/vendor/composer/ClassLoader.php @@ -11,6 +11,8 @@ */ namespace Composer\Autoload; +use InvalidArgumentException; +use Closure; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. @@ -40,9 +42,8 @@ * @see https://www.php-fig.org/psr/psr-0/ * @see https://www.php-fig.org/psr/psr-4/ */ -class ClassLoader -{ - /** @var \Closure(string):void */ +class ClassLoader { + /** @var Closure(string):void */ private static $includeFile; /** @var string|null */ @@ -53,10 +54,12 @@ class ClassLoader * @var array> */ private $prefixLengthsPsr4 = array(); + /** * @var array> */ private $prefixDirsPsr4 = array(); + /** * @var list */ @@ -71,6 +74,7 @@ class ClassLoader * @var array>> */ private $prefixesPsr0 = array(); + /** * @var list */ @@ -103,8 +107,7 @@ class ClassLoader /** * @param string|null $vendorDir */ - public function __construct($vendorDir = null) - { + public function __construct($vendorDir = null) { $this->vendorDir = $vendorDir; self::initializeIncludeClosure(); } @@ -112,9 +115,8 @@ public function __construct($vendorDir = null) /** * @return array> */ - public function getPrefixes() - { - if (!empty($this->prefixesPsr0)) { + public function getPrefixes() { + if ( ! empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); } @@ -124,32 +126,28 @@ public function getPrefixes() /** * @return array> */ - public function getPrefixesPsr4() - { + public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } /** * @return list */ - public function getFallbackDirs() - { + public function getFallbackDirs() { return $this->fallbackDirsPsr0; } /** * @return list */ - public function getFallbackDirsPsr4() - { + public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } /** * @return array Array of classname => path */ - public function getClassMap() - { + public function getClassMap() { return $this->classMap; } @@ -158,8 +156,7 @@ public function getClassMap() * * @return void */ - public function addClassMap(array $classMap) - { + public function addClassMap(array $classMap): void { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { @@ -177,10 +174,9 @@ public function addClassMap(array $classMap) * * @return void */ - public function add($prefix, $paths, $prepend = false) - { + public function add($prefix, $paths, $prepend = false): void { $paths = (array) $paths; - if (!$prefix) { + if ( ! $prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( $paths, @@ -197,7 +193,7 @@ public function add($prefix, $paths, $prepend = false) } $first = $prefix[0]; - if (!isset($this->prefixesPsr0[$first][$prefix])) { + if ( ! isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = $paths; return; @@ -223,14 +219,13 @@ public function add($prefix, $paths, $prepend = false) * @param list|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * * @return void */ - public function addPsr4($prefix, $paths, $prepend = false) - { + public function addPsr4($prefix, $paths, $prepend = false): void { $paths = (array) $paths; - if (!$prefix) { + if ( ! $prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( @@ -243,11 +238,11 @@ public function addPsr4($prefix, $paths, $prepend = false) $paths ); } - } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + } elseif ( ! isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { - throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + throw new InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = $paths; @@ -275,9 +270,8 @@ public function addPsr4($prefix, $paths, $prepend = false) * * @return void */ - public function set($prefix, $paths) - { - if (!$prefix) { + public function set($prefix, $paths): void { + if ( ! $prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; @@ -291,18 +285,17 @@ public function set($prefix, $paths) * @param string $prefix The prefix/namespace, with trailing '\\' * @param list|string $paths The PSR-4 base directories * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * * @return void */ - public function setPsr4($prefix, $paths) - { - if (!$prefix) { + public function setPsr4($prefix, $paths): void { + if ( ! $prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { - throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + throw new InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; @@ -316,8 +309,7 @@ public function setPsr4($prefix, $paths) * * @return void */ - public function setUseIncludePath($useIncludePath) - { + public function setUseIncludePath($useIncludePath): void { $this->useIncludePath = $useIncludePath; } @@ -327,8 +319,7 @@ public function setUseIncludePath($useIncludePath) * * @return bool */ - public function getUseIncludePath() - { + public function getUseIncludePath() { return $this->useIncludePath; } @@ -340,8 +331,7 @@ public function getUseIncludePath() * * @return void */ - public function setClassMapAuthoritative($classMapAuthoritative) - { + public function setClassMapAuthoritative($classMapAuthoritative): void { $this->classMapAuthoritative = $classMapAuthoritative; } @@ -350,8 +340,7 @@ public function setClassMapAuthoritative($classMapAuthoritative) * * @return bool */ - public function isClassMapAuthoritative() - { + public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } @@ -362,9 +351,8 @@ public function isClassMapAuthoritative() * * @return void */ - public function setApcuPrefix($apcuPrefix) - { - $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + public function setApcuPrefix($apcuPrefix): void { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; } /** @@ -372,8 +360,7 @@ public function setApcuPrefix($apcuPrefix) * * @return string|null */ - public function getApcuPrefix() - { + public function getApcuPrefix() { return $this->apcuPrefix; } @@ -384,8 +371,7 @@ public function getApcuPrefix() * * @return void */ - public function register($prepend = false) - { + public function register($prepend = false): void { spl_autoload_register(array($this, 'loadClass'), true, $prepend); if (null === $this->vendorDir) { @@ -405,8 +391,7 @@ public function register($prepend = false) * * @return void */ - public function unregister() - { + public function unregister(): void { spl_autoload_unregister(array($this, 'loadClass')); if (null !== $this->vendorDir) { @@ -420,8 +405,7 @@ public function unregister() * @param string $class The name of the class * @return true|null True if loaded, null otherwise */ - public function loadClass($class) - { + public function loadClass($class) { if ($file = $this->findFile($class)) { $includeFile = self::$includeFile; $includeFile($file); @@ -439,8 +423,7 @@ public function loadClass($class) * * @return string|false The path if found, false otherwise */ - public function findFile($class) - { + public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; @@ -449,7 +432,7 @@ public function findFile($class) return false; } if (null !== $this->apcuPrefix) { - $file = apcu_fetch($this->apcuPrefix.$class, $hit); + $file = apcu_fetch($this->apcuPrefix . $class, $hit); if ($hit) { return $file; } @@ -463,7 +446,7 @@ public function findFile($class) } if (null !== $this->apcuPrefix) { - apcu_add($this->apcuPrefix.$class, $file); + apcu_add($this->apcuPrefix . $class, $file); } if (false === $file) { @@ -479,8 +462,7 @@ public function findFile($class) * * @return array */ - public static function getRegisteredLoaders() - { + public static function getRegisteredLoaders() { return self::$registeredLoaders; } @@ -489,10 +471,9 @@ public static function getRegisteredLoaders() * @param string $ext * @return string|false */ - private function findFileWithExtension($class, $ext) - { + private function findFileWithExtension($class, $ext) { // PSR-4 lookup - $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + $logicalPathPsr4 = strtr($class, '\\', \DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { @@ -501,7 +482,7 @@ private function findFileWithExtension($class, $ext) $subPath = substr($subPath, 0, $lastPos); $search = $subPath . '\\'; if (isset($this->prefixDirsPsr4[$search])) { - $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + $pathEnd = \DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { return $file; @@ -513,7 +494,7 @@ private function findFileWithExtension($class, $ext) // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { - if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + if (file_exists($file = $dir . \DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } @@ -522,17 +503,17 @@ private function findFileWithExtension($class, $ext) if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) - . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + . strtr(substr($logicalPathPsr4, $pos + 1), '_', \DIRECTORY_SEPARATOR); } else { // PEAR-like class name - $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + $logicalPathPsr0 = strtr($class, '_', \DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { - if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + if (file_exists($file = $dir . \DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } @@ -542,7 +523,7 @@ private function findFileWithExtension($class, $ext) // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { - if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + if (file_exists($file = $dir . \DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } @@ -558,9 +539,8 @@ private function findFileWithExtension($class, $ext) /** * @return void */ - private static function initializeIncludeClosure() - { - if (self::$includeFile !== null) { + private static function initializeIncludeClosure(): void { + if (null !== self::$includeFile) { return; } @@ -572,7 +552,7 @@ private static function initializeIncludeClosure() * @param string $file * @return void */ - self::$includeFile = \Closure::bind(static function($file) { + self::$includeFile = Closure::bind(static function($file): void { include $file; }, null, null); } diff --git a/packages/sdk/vendor/composer/InstalledVersions.php b/packages/sdk/vendor/composer/InstalledVersions.php new file mode 100644 index 000000000..859253b3f --- /dev/null +++ b/packages/sdk/vendor/composer/InstalledVersions.php @@ -0,0 +1,345 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; +use OutOfBoundsException; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions { + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || ! isset($installed['versions'][$packageName]['dev_requirement']) || false === $installed['versions'][$packageName]['dev_requirement']; + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) { + foreach (self::getInstalled() as $installed) { + if ( ! isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) { + foreach (self::getInstalled() as $installed) { + if ( ! isset($installed['versions'][$packageName])) { + continue; + } + + if ( ! isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) { + foreach (self::getInstalled() as $installed) { + if ( ! isset($installed['versions'][$packageName])) { + continue; + } + + if ( ! isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) { + foreach (self::getInstalled() as $installed) { + if ( ! isset($installed['versions'][$packageName])) { + continue; + } + + if ( ! isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) { + foreach (self::getInstalled() as $installed) { + if ( ! isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', \E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data): void { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir . '/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir . '/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; + if (null === self::$installed && strtr($vendorDir . '/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (array() !== self::$installed) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/packages/sdk/vendor/composer/autoload_classmap.php b/packages/sdk/vendor/composer/autoload_classmap.php index b31e5fc9d..0671cc9cb 100644 --- a/packages/sdk/vendor/composer/autoload_classmap.php +++ b/packages/sdk/vendor/composer/autoload_classmap.php @@ -18,20 +18,32 @@ 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\PaymentMethodInfo' => $baseDir . '/src/Entity/Notification/PaymentMethodInfo.php', 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\Refund' => $baseDir . '/src/Entity/Notification/Refund.php', 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\RefundList' => $baseDir . '/src/Entity/Notification/RefundList.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\RefundNotifying' => $baseDir . '/src/Entity/Notification/RefundNotifying.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\RefundNotifyingList' => $baseDir . '/src/Entity/Notification/RefundNotifyingList.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\AdditionalInfo' => $baseDir . '/src/Entity/Payment/AdditionalInfo.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\AdditionalInfoAddress' => $baseDir . '/src/Entity/Payment/AdditionalInfoAddress.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\AdditionalInfoPayer' => $baseDir . '/src/Entity/Payment/AdditionalInfoPayer.php', - 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\AdditionalInfoPayerAddress' => $baseDir . '/src/Entity/Payment/AdditionalInfoPayerAddress.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Address' => $baseDir . '/src/Entity/Payment/Address.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\ApplicationData' => $baseDir . '/src/Entity/Payment/ApplicationData.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\BankInfo' => $baseDir . '/src/Entity/Payment/BankInfo.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Identification' => $baseDir . '/src/Entity/Payment/Identification.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Item' => $baseDir . '/src/Entity/Payment/Item.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\ItemList' => $baseDir . '/src/Entity/Payment/ItemList.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Multipayment' => $baseDir . '/src/Entity/Payment/Multipayment.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\MultipaymentV2' => $baseDir . '/src/Entity/Payment/MultipaymentV2.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Payer' => $baseDir . '/src/Entity/Payment/Payer.php', - 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\PayerIdentification' => $baseDir . '/src/Entity/Payment/PayerIdentification.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Payment' => $baseDir . '/src/Entity/Payment/Payment.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\PaymentV2' => $baseDir . '/src/Entity/Payment/PaymentV2.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Phone' => $baseDir . '/src/Entity/Payment/Phone.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\PointOfInteraction' => $baseDir . '/src/Entity/Payment/PointOfInteraction.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\ReceiverAddress' => $baseDir . '/src/Entity/Payment/ReceiverAddress.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Seller' => $baseDir . '/src/Entity/Payment/Seller.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Shipments' => $baseDir . '/src/Entity/Payment/Shipments.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Tracking' => $baseDir . '/src/Entity/Payment/Tracking.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\TransactionData' => $baseDir . '/src/Entity/Payment/TransactionData.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\TransactionDetails' => $baseDir . '/src/Entity/Payment/TransactionDetails.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\TransactionInfo' => $baseDir . '/src/Entity/Payment/TransactionInfo.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\TransactionInfoList' => $baseDir . '/src/Entity/Payment/TransactionInfoList.php', 'MercadoPago\\PP\\Sdk\\Entity\\Preference\\Address' => $baseDir . '/src/Entity/Preference/Address.php', 'MercadoPago\\PP\\Sdk\\Entity\\Preference\\BackUrl' => $baseDir . '/src/Entity/Preference/BackUrl.php', 'MercadoPago\\PP\\Sdk\\Entity\\Preference\\DifferentialPricing' => $baseDir . '/src/Entity/Preference/DifferentialPricing.php', diff --git a/packages/sdk/vendor/composer/autoload_real.php b/packages/sdk/vendor/composer/autoload_real.php index a580f507d..2f768594f 100644 --- a/packages/sdk/vendor/composer/autoload_real.php +++ b/packages/sdk/vendor/composer/autoload_real.php @@ -2,12 +2,10 @@ // autoload_real.php @generated by Composer -class ComposerAutoloaderInit7df991cb6c45ae6eb5b10f00fabea309 -{ +class ComposerAutoloaderInit9311624e15b6e009950b2fbe89edbcce { private static $loader; - public static function loadClassLoader($class) - { + public static function loadClassLoader($class): void { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } @@ -16,20 +14,19 @@ public static function loadClassLoader($class) /** * @return \Composer\Autoload\ClassLoader */ - public static function getLoader() - { + public static function getLoader() { if (null !== self::$loader) { return self::$loader; } require __DIR__ . '/platform_check.php'; - spl_autoload_register(array('ComposerAutoloaderInit7df991cb6c45ae6eb5b10f00fabea309', 'loadClassLoader'), true, true); + spl_autoload_register(array('ComposerAutoloaderInit9311624e15b6e009950b2fbe89edbcce', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); - spl_autoload_unregister(array('ComposerAutoloaderInit7df991cb6c45ae6eb5b10f00fabea309', 'loadClassLoader')); + spl_autoload_unregister(array('ComposerAutoloaderInit9311624e15b6e009950b2fbe89edbcce', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; - call_user_func(\Composer\Autoload\ComposerStaticInit7df991cb6c45ae6eb5b10f00fabea309::getInitializer($loader)); + call_user_func(\Composer\Autoload\ComposerStaticInit9311624e15b6e009950b2fbe89edbcce::getInitializer($loader)); $loader->register(true); diff --git a/packages/sdk/vendor/composer/autoload_static.php b/packages/sdk/vendor/composer/autoload_static.php index db9c96600..cc1d00f87 100644 --- a/packages/sdk/vendor/composer/autoload_static.php +++ b/packages/sdk/vendor/composer/autoload_static.php @@ -3,23 +3,21 @@ // autoload_static.php @generated by Composer namespace Composer\Autoload; +use Closure; -class ComposerStaticInit7df991cb6c45ae6eb5b10f00fabea309 -{ +class ComposerStaticInit9311624e15b6e009950b2fbe89edbcce { public static $prefixLengthsPsr4 = array ( 'M' => array ( 'MercadoPago\\PP\\Sdk\\' => 19, ), ); - public static $prefixDirsPsr4 = array ( 'MercadoPago\\PP\\Sdk\\' => array ( 0 => __DIR__ . '/../..' . '/src', ), ); - public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', 'MercadoPago\\PP\\Sdk\\Common\\AbstractCollection' => __DIR__ . '/../..' . '/src/Common/AbstractCollection.php', @@ -33,20 +31,32 @@ class ComposerStaticInit7df991cb6c45ae6eb5b10f00fabea309 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\PaymentMethodInfo' => __DIR__ . '/../..' . '/src/Entity/Notification/PaymentMethodInfo.php', 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\Refund' => __DIR__ . '/../..' . '/src/Entity/Notification/Refund.php', 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\RefundList' => __DIR__ . '/../..' . '/src/Entity/Notification/RefundList.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\RefundNotifying' => __DIR__ . '/../..' . '/src/Entity/Notification/RefundNotifying.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Notification\\RefundNotifyingList' => __DIR__ . '/../..' . '/src/Entity/Notification/RefundNotifyingList.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\AdditionalInfo' => __DIR__ . '/../..' . '/src/Entity/Payment/AdditionalInfo.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\AdditionalInfoAddress' => __DIR__ . '/../..' . '/src/Entity/Payment/AdditionalInfoAddress.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\AdditionalInfoPayer' => __DIR__ . '/../..' . '/src/Entity/Payment/AdditionalInfoPayer.php', - 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\AdditionalInfoPayerAddress' => __DIR__ . '/../..' . '/src/Entity/Payment/AdditionalInfoPayerAddress.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Address' => __DIR__ . '/../..' . '/src/Entity/Payment/Address.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\ApplicationData' => __DIR__ . '/../..' . '/src/Entity/Payment/ApplicationData.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\BankInfo' => __DIR__ . '/../..' . '/src/Entity/Payment/BankInfo.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Identification' => __DIR__ . '/../..' . '/src/Entity/Payment/Identification.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Item' => __DIR__ . '/../..' . '/src/Entity/Payment/Item.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\ItemList' => __DIR__ . '/../..' . '/src/Entity/Payment/ItemList.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Multipayment' => __DIR__ . '/../..' . '/src/Entity/Payment/Multipayment.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\MultipaymentV2' => __DIR__ . '/../..' . '/src/Entity/Payment/MultipaymentV2.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Payer' => __DIR__ . '/../..' . '/src/Entity/Payment/Payer.php', - 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\PayerIdentification' => __DIR__ . '/../..' . '/src/Entity/Payment/PayerIdentification.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Payment' => __DIR__ . '/../..' . '/src/Entity/Payment/Payment.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\PaymentV2' => __DIR__ . '/../..' . '/src/Entity/Payment/PaymentV2.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Phone' => __DIR__ . '/../..' . '/src/Entity/Payment/Phone.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\PointOfInteraction' => __DIR__ . '/../..' . '/src/Entity/Payment/PointOfInteraction.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\ReceiverAddress' => __DIR__ . '/../..' . '/src/Entity/Payment/ReceiverAddress.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Seller' => __DIR__ . '/../..' . '/src/Entity/Payment/Seller.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Shipments' => __DIR__ . '/../..' . '/src/Entity/Payment/Shipments.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\Tracking' => __DIR__ . '/../..' . '/src/Entity/Payment/Tracking.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\TransactionData' => __DIR__ . '/../..' . '/src/Entity/Payment/TransactionData.php', 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\TransactionDetails' => __DIR__ . '/../..' . '/src/Entity/Payment/TransactionDetails.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\TransactionInfo' => __DIR__ . '/../..' . '/src/Entity/Payment/TransactionInfo.php', + 'MercadoPago\\PP\\Sdk\\Entity\\Payment\\TransactionInfoList' => __DIR__ . '/../..' . '/src/Entity/Payment/TransactionInfoList.php', 'MercadoPago\\PP\\Sdk\\Entity\\Preference\\Address' => __DIR__ . '/../..' . '/src/Entity/Preference/Address.php', 'MercadoPago\\PP\\Sdk\\Entity\\Preference\\BackUrl' => __DIR__ . '/../..' . '/src/Entity/Preference/BackUrl.php', 'MercadoPago\\PP\\Sdk\\Entity\\Preference\\DifferentialPricing' => __DIR__ . '/../..' . '/src/Entity/Preference/DifferentialPricing.php', @@ -77,13 +87,11 @@ class ComposerStaticInit7df991cb6c45ae6eb5b10f00fabea309 'MercadoPago\\PP\\Sdk\\Sdk' => __DIR__ . '/../..' . '/src/Sdk.php', ); - public static function getInitializer(ClassLoader $loader) - { - return \Closure::bind(function () use ($loader) { - $loader->prefixLengthsPsr4 = ComposerStaticInit7df991cb6c45ae6eb5b10f00fabea309::$prefixLengthsPsr4; - $loader->prefixDirsPsr4 = ComposerStaticInit7df991cb6c45ae6eb5b10f00fabea309::$prefixDirsPsr4; - $loader->classMap = ComposerStaticInit7df991cb6c45ae6eb5b10f00fabea309::$classMap; - - }, null, ClassLoader::class); + public static function getInitializer(ClassLoader $loader) { + return Closure::bind(function () use ($loader): void { + $loader->prefixLengthsPsr4 = ComposerStaticInit9311624e15b6e009950b2fbe89edbcce::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit9311624e15b6e009950b2fbe89edbcce::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit9311624e15b6e009950b2fbe89edbcce::$classMap; + }, null, 'Composer\Autoload\ClassLoader'); } } diff --git a/packages/sdk/vendor/composer/installed.json b/packages/sdk/vendor/composer/installed.json new file mode 100644 index 000000000..d4daed1c6 --- /dev/null +++ b/packages/sdk/vendor/composer/installed.json @@ -0,0 +1,5 @@ +{ + "packages": [], + "dev": false, + "dev-package-names": [] +} \ No newline at end of file diff --git a/packages/sdk/vendor/composer/installed.php b/packages/sdk/vendor/composer/installed.php new file mode 100644 index 000000000..41def5d2e --- /dev/null +++ b/packages/sdk/vendor/composer/installed.php @@ -0,0 +1,23 @@ + array( + 'name' => 'mp-plugins/php-sdk', + 'pretty_version' => '1.3.1', + 'version' => '1.3.1.0', + 'reference' => NULL, + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => false, + ), + 'versions' => array( + 'mp-plugins/php-sdk' => array( + 'pretty_version' => '1.3.1', + 'version' => '1.3.1.0', + 'reference' => NULL, + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/packages/sdk/vendor/composer/platform_check.php b/packages/sdk/vendor/composer/platform_check.php index f79e574be..8e1b592b2 100644 --- a/packages/sdk/vendor/composer/platform_check.php +++ b/packages/sdk/vendor/composer/platform_check.php @@ -4,23 +4,23 @@ $issues = array(); -if (!(PHP_VERSION_ID >= 70000)) { - $issues[] = 'Your Composer dependencies require a PHP version ">= 7.0.0". You are running ' . PHP_VERSION . '.'; +if ( ! (\PHP_VERSION_ID >= 70000)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 7.0.0". You are running ' . \PHP_VERSION . '.'; } if ($issues) { - if (!headers_sent()) { + if ( ! headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } - if (!ini_get('display_errors')) { - if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { - fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); - } elseif (!headers_sent()) { - echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; + if ( ! ini_get('display_errors')) { + if (\PHP_SAPI === 'cli' || \PHP_SAPI === 'phpdbg') { + fwrite(\STDERR, 'Composer detected issues in your platform:' . \PHP_EOL . \PHP_EOL . implode(\PHP_EOL, $issues) . \PHP_EOL . \PHP_EOL); + } elseif ( ! headers_sent()) { + echo 'Composer detected issues in your platform:' . \PHP_EOL . \PHP_EOL . str_replace('You are running ' . \PHP_VERSION . '.', '', implode(\PHP_EOL, $issues)) . \PHP_EOL . \PHP_EOL; } } trigger_error( 'Composer detected issues in your platform: ' . implode(' ', $issues), - E_USER_ERROR + \E_USER_ERROR ); } diff --git a/readme.txt b/readme.txt deleted file mode 100644 index f55c5fa2a..000000000 --- a/readme.txt +++ /dev/null @@ -1,860 +0,0 @@ -=== Mercado Pago payments for WooCommerce === -Contributors: mercadopago, mercadolivre, claudiosanches, marcelohama -Tags: ecommerce, mercadopago, woocommerce -Requires at least: 5.6 -Tested up to: 6.2 -Requires PHP: 7.2 to 8.1 -Stable tag: 6.9.2 -License: GPLv2 or later -License URI: https://www.gnu.org/licenses/gpl-2.0.html - -Offer to your clients the best experience in e-Commerce by using Mercado Pago as your payment method. - -== Description == - -The official Mercado Pago plugin allows you to process payments for your online store, allowing users to finalize their purchase with their preferred payment method. - -To install it, **you don't need to have technical knowledge:** you can follow the [step by step of how to integrate it](https://www.mercadopago.com.ar/developers/es/guides/plugins/woocommerce/introduction/). from our developer website and start selling today. - -**Warning about v6.0.0:** when updating, if you have made custom layout changes to your checkout, it is possible that some of those customizations become misconfigured. If you have a separate store environment just for testing, please update there first in order to visualize and test the changes. - -### What to do with the Mercado Pago Plugin? -* Activate **Checkout Pro** to offer logged-in payments with money in Mercado Pago account, saved cards and off means. -* Offer payments without the need of having a Mercado Pago account, through the **Custom Checkout** for cards and off means, such as cash, bank transfer and PIX (only in Brazil). -* Automatically convert the currency of your products: from Mexican pesos to U.S. dollars and vice versa. -* Sell in **installments** and offer the current promotions in Checkout Pro or apply your own discount coupon in Custom Checkout. -* Test your store before going into production with our Sandbox environment. -* **Receive the money** from your sales on the same day. -* **IMPORTANT:** At the moment the Mercado Envios service is deactivated. -* **Mercado Pago customers can use already stored cards** For your customers who use Mercado Pago to buy without having to fill in card details at the store's checkout. - -### Adapted to your business - -Prepared for any type of store and category: electronics, clothing, kitchen, bazaar, whatever you want! -Just focus on selling and **we'll take care of the security:** keep your store's payments protected with our fraud prevention and analysis tool. - -Boost your sales with Mercado Pago payments for WooCommerce! - -### Sell more with the paid market - -[Leave your details](https://www.mercadopago.com.br/quero-usar/?utm_campaign=%5BMP%20OP%5D%20Core%20Checkouts%202021&utm_source=plugin-woocommerce&utm_medium=plugin&utm_term=plugin-woocommerce&utm_content=plugin-woocommerce) to talk to our team of experts and understand how to sell more (for now only available for Brazil). - -== Screenshots == - -1. RECEIVE THE MONEY FROM YOUR SALES ON THE SAME DAY -2. This is what the Checkout Pro looks like in your store. You can choose between a modal experience or a redirect experience. -3. This is what the Customized Checkout looks like in your store. You can activate payments with cards and also cash. -4. Once you install the Mercado Pago Plugin, you will find the 3 checkouts available in the Payment settings in WooCommerce. You can activate them simultaneously or choose one of them. Remember that they must be configured before enabling them. -5. To configure it, follow the step by step indicated in each Checkout. Remember that you can review the official documentation of our plugin on the Mercado Pago developer website. -6. ACCEPT ALL PAYMENT METHODS - -== Frequently Asked Questions == - -= I had a question during setup, where can I check the documentation? = - -In our developer website you will find the step by step of [how to integrate the Mercado Pago Plugin](https://www.mercadopago.com.ar/developers/es/guides/plugins/woocommerce/introduction/) in your online store. - -= What are the requirements for the plugin to work properly? = - -You must have an SSL certificate, connecting your website with the HTTPS protocol. - -If you need to check the protocol configuration, [test it here](https://www.ssllabs.com/ssltest/). - -Finally, remember that the plugin receives IPN (Instant Payment Notification) notifications automatically, you don't need to configure it! - -= I already finished the configuration but the Sandbox environment is not working. = - -Remember that to test the Checkout Pro you must log out of your Mercado Pago account, as it is not possible to use it to sell and buy at the same time. - -Please note that with the Test Environment enabled, the Checkout Pro does not send notifications as does the Custom Checkout. - -= How do I configure the sending of emails to my customers? = - -The configuration of sending emails must be done from the WooCommerce administrator. The Mercado Pago Plugin only contemplates sending transactions made in the Checkout Pro. - -= I reviewed the documentation and these FAQs but still have problems in my store, what can I do? = - -If you have already reviewed the documentation and have not found a solution, you can contact our support team through their [contact form](https://www.mercadopago.com.ar/developers/es/support/). Please note that we guarantee a response within {7 days} of your query. - -= How can I set up PIX as a payment method? = - -PIX is a payment method that exists only in Brazil. - -To enable PIX as a payment method in the Custom Checkout of your store, you need to have your key registered in Mercado Pago. [See how to do it](https://www.mercadopago.com.br/stop/pix?url=https%3A%2F%2Fwww.mercadopago.com.br%2Fadmin-pix-keys%2Fmy-keys&authentication_mode=required). - -After registering the key, log into the WooCommerce administrator and navigate to the **Payments** section. - -Look for the option **Pague com PIX**, configure it and activate PIX. - -You can set up a time limit for customers to pay after they receive the code, among other settings. - -== Installation == - -= Minimum Technical Requirements = -* WordPress version -* Compatibility and dependency of WooCommerce VXX -* LAMP Environment (Linux, Apache, MySQL, PHP) -* SSL Certificate -* Additional configuration: safe_mode off, memory_limit higher than 256MB - -Install the module in two different ways: automatically, from the “Plugins” section of WordPress, or manually, downloading and copying the plugin files into your directory. - -Automatic Installation by WordPress admin -1. Access "Plugins" from the navigation side menu of your WordPress administrator. -2. Once inside Plugins, click on 'Add New' and search for 'Mercado Pago payments for WooCommerce' in the WordPress Plugin list -3. Click on "Install." - -Done! It will be in the "Installed Plugins" section and from there you can activate it. - -Manual Installation -1. Download the [zip] (https://github.com/mercadopago/cart-woocommerce/archive/master.zip) now or from the o WordPress Module [Directory] (https://br.wordpress.org/plugins/woocommerce-mercadopago/) -2. Unzip the folder and rename it to ”woocommerce-mercadopago” -3. Copy the "woocommerce-mercadopago" file into your WordPress directory, inside the "Plugins" folder. - -Done! - -= Installing this plugin does not affect the speed of your store! = - -If you installed it correctly, you will see it in your list of "Installed Plugins" on the WordPress work area. Please enable it and proceed to your Mercado Pago account integration and setup. - -= Mercado Pago Integration = -1. Create a Mercado Pago [seller account](https://www.mercadopago.com.br/registration-company?confirmation_url=https%3A%2F%2Fwww.mercadopago.com.br%2Fcomo-cobrar) if you don't have one yet. It's free and takes only seconds! -2. Get your [credentials](https://www.mercadopago.com.br/developers/pt/guides/localization/credentials), they are the keys that uniquely identify you within the platform. -3. Set checkout payment preferences and make other advanced settings to change default options. -4. Approve your account to go to [Production](https://www.mercadopago.com.br/developers/pt/guides/payments/api/goto-production/) and receive real payments. - -= Configuration = -Set up both the plugin and the checkouts you want to activate on your payment avenue. Follow these five steps instructions and get everything ready to receive payments: - -1. Add your **credentials** to test the store and charge with your Mercado Pago account **according to the country** where you are registered. -2. Approve your account in order to charge. -3. Fill in the basic information of your business in the plugin configuration. -4. Set up **payment preferences** for your customers. -5. Access **advanced** plugin and checkout **settings** only when you want to change the default settings. - -Check out our official documentation for more information on the specific fields to configure. - -== Changelog == - -= v6.9.2 (23/06/2023) = -* Fixed -- Fixed bug that was causing the admin panel to become unresponsive or inaccessible - -= v6.9.0 (12/06/2023) = -* Features -- Add default activation for Credits Gateway when Basic Gateway is enabled -- Declare this plugin compatible with High-Performance Order Storage (HPOS) -* Changed -- Replace post methods with equivalent methods compatible with HPOS -* Fixed -- devsite link's in readme - -= v6.8.1 (22/05/2023) = -* Fixed -- Rollback version - -= v6.8.0 (22/05/2023) = -* Features -- Add default activation for Credits Gateway when Basic Gateway is enabled - -= v6.7.5 (17/05/2023) = -* Fixed -- Fixed property discount_action_url becoming public instead private - -= v6.7.4 (15/05/2023) = -* Changed -- Changed function from str_contains to strpos to be compatible for WordPress versions lower than 5.9 -- Changed the way to handle custom notification url using or not using Mercado Pago default params - -= v6.7.3 (02/05/2023) = -* Features -- Test compatibility with WooCommerce v7.6 -- Test compatibility with WordPress v6.2 - -* Changes -- process_nonce_validation was removed from process_payment - -* Fixes -- Fix http_user_agent log using wp_is_mobile() instead regex - -= v6.7.2 (20/03/2023) = -* Features -- Add new fields in update-metadata - - Cho Pro will add the fields: ```installments, transaction_details, total_paid_amount, transaction_amount, last_four_digits, e o payment_type``` - - Cho Custom will add the fields: ```payment_type e last_four_digits``` - - In future release, all metadata field prefixed with "mp_" will be removed - -- Add security js client and retrive session id from MP_DEVICE_SESSION_ID - - this improvement will increase the credit card approval rate - -* Changes - -- Interest attached to the order total -* Bug fixes -- Fix nonce validation when "allow costumers to create an account during checkout" is enabled - -= v6.7.1 (15/02/2023) = -* Changes -- Changed Credits Tooltips experience -- Changed generic css classes name - -* Bug fixes -- Fixed PIX QR Code generation - -= v6.7.0 (23/01/2023) = -* Changes -- Added security improvements - -= v6.6.0 (11/01/2023) = -* Features -- Added manual notification sync -- Added payment ids to order metadata on callback -- Added select-id and hidden-id attributes to document - -* Changes -- Changed user permissions needed for security - -* Bug fixes -- Fixed order amount with gateway discount -- Fixed css class assignment to nonexistent element -- Fixed selection of installments when there is an inversion of checkouts - -= v6.5.0 (22/12/2022) = -* Features -- Added Mercado Credits payment method -- Added user permissions needed (administrator or editor) for security - -* Changes -- Documented use of a 3rd Party or external service -- Improved Checkout Pro layout - -* Bug fixes -- Removed nonce validation from checkouts to use WC nonce validation - -= v6.4.1 (14/12/2022) = -* Features -- Added bank interest disclaimer - -* Changes -- Removed CURLOPT_SSL_VERIFYPEER flag to get server default value - -= v6.4.0 (07/12/2022) = -* Features -- Added Mercado Pago PHP SDK -- Added min width for checkout select inputs -- Added nonce validation to avoid CSRF Vulnerabilities - -* Changes -- Changed notification flow to use PHP SDK -- Changed payments and preferences flow to use PHP SDK - -* Bug fixes -- Fixed plugin translations -- Fixed plugin configuration page links - -= v6.3.1 (13/10/2022) = -* Changes -- Improved discarded notification response -- Removed loader and timeout on custom checkout - -= v6.3.0 (27/09/2022) = -* Features -- Added interest information on the order confirmation screen for payments with custom checkout - -* Bug fixes -- Fixed timeout and error display in custom checkout -- Removed hyphen from zip code to display correct address for payments with ticket checkout -- Alignment of expiration and security code fields in custom checkout - -= v6.2.0 (13/09/2022) = -* Features -- Added Mercado Credits tooltip -- Added loader on custom checkout to avoid timeout, handle and show errors on screen -- Added validation on REST Client to avoid return empty array on requests response - -* Changes -- Changed Wallet Button layout to encourage more usage - -* Bug fixes -- Fixed email sending method for order placed with PIX - -= v6.1.0 (22/08/2022) = -* Features -- Added notices scripts on plugin -- Added validation to avoid installments equal to zero -- Added trigger to payment_method_selected event if it not triggered on checkout custom load -- Added rule in notification to allow an approved payment to update if order status is pending, on_hold or failed -- Added client to handle caronte scripts success and error - -* Changes -- Removed the test credentials requirement to configure the plugin -- Adjusted credential saving flow to avoid saving two public_key or access_token -- Changed how to load melidata script on window.load -- Send email from Pix and QRCode only for orders with pending status -- Audited npm packages - -* Bug fixes -- Fixed plugin and platform version on melidata client -- Fixed order status when a partial refund is made -- Fixed currency conversion value to display at checkout - -= v6.0.2 (13/07/2022) = -* Features -- Added preg_replace for notification external params - -= v6.0.1 (27/06/2022) = -* Bug fixes -- Added validation to invalid length on cardNumber to not clear or remove fields - -= v6.0.0 (22/06/2022) = -* Features -- Added ideal checkout template -- Added secure inputs for Checkout Custom - -* Changes -- Updated melidata script to load only on plugin pages - -= v5.8.0 (07/06/2022) = -* Features -- Added melidata script to collect metrics from plugin - -* Bug fixes -- Changed mp logo - -= v5.7.6 (19/04/2022) = -* Bug fixes -- Adjusted IPN notification to recognize discount coupon -- Added coupon information in order details -- Changed default value of checkout ticket date_expiration - -= v5.7.5 (31/03/2022) = -* Bug fixes -- Instance a non-static class to call a method (Fatal error on PHP 8) - -= v5.7.4 (25/02/2022) = -* Bug fixes -- Changed php constant - -= v5.7.3 (16/02/2022) = -* Bug fixes -- fixed cho pro excluded payments -- fixed cho ticket excluded payments -- validate if has a checkout prod set all to prod -- fixed mp order screen - -= v5.7.2 (14/02/2022) = -* Bug fixes -- Using Jquery from wp.ajax - -= v5.7.1 (14/02/2022) = -* Bug fixes -- Adjusted js and css load of mercado pago pool -- Repass all active gateways - -= v5.7.0 (14/02/2022) = -* Features -- Redesign Admin -- Performance improvements -- Added research in the Mercado Pago plugin configuration pages - -* Bug fixes -- Adjusted the css of payment ticket images and text - -= v5.6.1 (11/01/2022) = -* Bug fixes -- Set important to Mercado Pago inputs, to prevent ghost input type -- Updated Mercado Pago's logo images - -= v5.6.0 (01/12/2021) = -* Features -- Support to PayCash in Mexico -- Simplified filling for ticket - -* Bug fixes -- Adjusted term and conditions CSS -- Admin Order Details validation if is Mercado Pago order -- Updated develop dependencies - -= v5.5.0 (19/10/2021) = -* Features -- Render pix image from backend for e-mails -- Added link to terms and conditions of Mercado Pago on checkout screen - -* Bug fixes -- Fixed retry payment - -= v5.4.1 (22/09/2021) = -* Bug fixes -- On the order page, the payment was fetched with the wrong token -- When the plugin was updated the checkout mode visually went to test - -= 5.4.0 (20/09/2021) = -* Features -- Performance improvements -- Improved status of declined payments -- Improvements in store test flow -- Improved text distribution in the Wallet Button alert -- Inclusion of interest-free installment button in payment settings (PSJ) -- Inclusion of Pix code on the customer panel for later consultation -- Inclusion of visual information on the status of the credential -- Adding more QR Code expiration options to the PIX - -* Bug fixes -- Fix QR Code breaking email layout - -= 5.3.1 (12/08/2021) = -* Bug fixes -- Adjusted notification url, checking if it's a friendly url or not - -= 5.3.0 (10/08/2021) = -* Features -- Credentials order on painel -- The seller can change checkout names - -= v5.2.0 (26/07/2021) = -* Features -- New payment method Wallet Button (wallet purchase) -- Added support to PHP 8 -- Added support to PHPUnit -- Added support to source_news in notification - -* Bug fixes -- Changed pix e-mail template -- Removed gulp dependency -- New pre-commit hooks - -= v5.1.1 (22/04/2021) = -* Features - - Added WooCommerce linter - -= v5.1.0 (29/03/2021) = -* Features - - Added new Pix Gateway for Brazil - - Added Payment type at order panel - -* Bug fixes - - Fixed post in configuration page, removed html - -= v5.0.1 (10/03/2021) = -* Features - - Compatibility with old notification urls - -= v5.0.0 (24/02/2021) = -* Features - - Compatibility with WooCommerce v5.0.0 - - Compatibility with WordPress v5.6.2 - - Added Wordpress Code Standard at plugin - -* Bug fixes - - Fixed round amount - -= v4.6.4 (11/02/2021) = -* Bug fixes - - Removed payments methods in option custom checkout OFF - -= v4.6.3 (06/01/2021) = -* Features - - Compatibility with WooCommerce v4.9.2 - - Compatibility with WordPress v5.6.1 - - Added index to all directories for more security - -* Bug fixes - - Fixed wc-api request check when is ?wc_api or wc-api - - Fixed close of rating notification - -= v4.6.2 (06/01/2021) = -* Bug fixes - - Changed loading of Mercado Pago SDK at custom checkout - -= v4.6.1 (04/01/2021) = -* Features - - Add support to LearnPress - - Compatibility with Wordpress v5.6 and WooCommerce v4.8 - - Added version in SDK Mercado Pago - - Added compatibility with WooCommerce Accepted Payment Methods plugin - -* Bug fixes - - Changed event load of credit-card.js in checkout page - - Changed API to get payment_methods in Checkout Custo Offline and Checkout pro - - Changed event load in admin payments config - - Changed name Checkout Mercado Pago to Checkout Pro - -= v4.6.0 (01/12/2020) = -* Features - - Add review rating banner - - Improve security on checkouts, xss javascript sanitizer - - Support section block added in checkout settings - -* Bug fixes - - Fixed error that prevents configuring the Mercado Pago plugin - -= v4.5.0 (26/10/2020) = -* Features - - Compatibility with WooCommerce v4.6.x - - Improved security (added access token in the header for all calls to Mercado Livre and Mercado Pago endpoints) - - Add new endpoint to validate Access Token and Public key to substitute old process to validation - - Improved performance with CSS minification - -* Bug fixes - - Fixed conflict with wc-api webhook and Mercado Pago webhook/IPN. - - Fixed alert in currency conversion - - Fixed tranlate in currency conversion - - Bug fixed when updating orders that have two or more payments associated. - -* Bug fixes - - Fixed conflict with wc-api webhook and Mercado Pago webhook/IPN. - -= v4.4.0 (21/09/2020) = -* Features - - Compatibility with WooCommerce v4.5.x - -* Bug fixes - - Adjusted error when shipping is not used - -= v4.3.1 (10/09/2020) = -* Bug fixes - - Adjusted inventory (for canceled orders) on payments made at the personalized offline checkout - -= v4.3.0 (31/08/2020) = -* Features - - Improve plugin initialization - - Compatibility with Wordpress v5.5 and WooCommerce v4.4.x - -* Bug fixes - - Fixed currency conversion API - Alert added at checkout when currency conversion fails - - Adjusted inventory (for canceled orders) on payments made at the personalized offline checkout - - Adjusted translation in general - - Adjusted currency translation alert - -= v4.2.2 (27/07/2020) = -* Features - - Added feature: cancelled orders on WooCommerce are automatically cancelled on Mercado Pago - - Compatibility with Wordpress v5.4 and WooCommerce v4.3.x - -* Bug fixes - - Fixed notification bug - No longer updates completed orders - - Fixed currency conversion API - No longer allows payments without currency conversion - - Fixed payment procesisng for virtual products - - Added ABSPATH in every PHP file - - Adjusted installments translation - - Adjusted state names for Transparent Checkout in Brazil - - Adjusted currency translation translations - - Removed text in code written in Spanish - -== Changelog == -= v4.2.1 (18/05/2020) = -* Bug fixes - - Corrected CI document input validation on Uruguay Custom Offline Checkout. - -= v4.2.0 (13/05/2020) = -* Features - - Added compatibility with WooCommerce version 4.1.0 - - Added Integrator ID field on checkouts’ configuration screens - - Added validation for Public Keys - - Added alert to activate the WooCommerce plugin whenever it is inactive - - Added alert to install the WooCommerce plugin whenever it is uninstalled - - Added assets versioning - - Added minification of JS files - - Added debug mode for JS in order to use files without minification - - Added payment flow for WebPay in Chile for Checkout Custom Offline - - Updated documentation and regionalized links - -* Bug fixes - - Corrected notification status on charged_back - - Corrected issue when invalid credentials were switched - - Corrected checkout options for Store Name, Store Category and Store ID - - Corrected validation on the cardNumber field whenever card number is removed - - Corrected input masks on CPNJ and CPF; CNPJ validation and translation in Brazil for Custom Checkout Offline; - - Corrected mercadopago.js loading - - Corrected processing of payment status notifications - - Corrected personalized URLs for successful, refused and pending payments on Checkout Mercado Pago - - Added success and error messages on received payment notifications - - Added alphabetical order on offline payment methods for Checkout Custom - - Added CI document input on Custom Checkout OFF in Uruguay - - Added compatibility with third-party discount plugins which attribute value on order->fees (computation of fees_cost upon purchase) - - Added validation, focus and error messages on all JS inputs on Checkout Custom Online and Offline - - Usability improvements for Checkout Custom - Credit Card on mobile devices - - Adjusted error messages on online Checkout Custom Online - - Adjusted status updates on Checkout Custom Offline orders - - Updated documentation and guide links - -= v4.1.1 (10/01/2020) = -* Feature - - Currency Conversion in Checkout Mercado Pago added - -* Bug fixes - - Currency Conversion for CHO Custom ON and OFF fixed - - Shipping Cost in the creation of Preferences fixed - - ME2 shipping mode in the creation of Preferences removed - - Checkout Mercado Pago class instance fixed when the first configurations are saved - -= v4.1.0 (06/01/2020) = -* Feature - - Updated plugin name from "WooCommerce Mercado Pago" to "Mercado Pago payments for WooCommerce". - - Feature currency conversion returned. - - New feature to check if cURL is installed - - Refactored Javascript code for custom checkout Debit and credit card. Performance improvement, reduced number of SDK calls. Fixed validation errors. Javascript code refactored to the order review page. Removed select from mexico payment method. - -* Bug fixes - - Fixed credential issue when the plugin is upgraded from version 3.x.x to 4xx. Unable to save empty credential. - - Fixed issue to validate credential when checkout is active. The same problem occurs when removing the enabled checkout credential. - - Fixed error: Undefined index: MLA in WC_WooMercadoPago_Credentials.php on line 163. - - Fixed error: Call to a member function analytics_save_settings() in WC_WooMercadoPago_Hook_Abstract.php on line 68. Has affected users that cleared the credential and filled new credential production. - - Fixed load of WC_WooMercadoPago_Module.php file. - - Fixed error Uncaught Error: Call to a member function homologValidate(). - - Fixed error Undefined index: section in WC_WooMercadoPago_PaymentAbstract.php on line 303. Affected users who did not have homologous accounts - - Fixed issue to validate credential when checkout is active. The same problem occurs when removing the enabled checkout credential. - - Fixed issue to calculate commission and discount. - - Fixed Layout of checkout custom input. - - Fixed translation ES of Modo Producción, Habilitá and definí - - Fixed Uncaught Error call to a member function update_status() in WC_WooMercadoPago_Notification_Abstract.php. Handle Mercado Pago Notification Failures and Exceptions. - - Fix PT-BR debit card translation on admin. - - Fix PT-BR debit card translation on checkout. - - Remove "One Step Checkout" from CHO Custom Off. - - Remove Mercado Creditos from Custom CHO OFF. - - Fixed issue to check if WooCommerce plugin is installed - -* Break change - - Removed feature and support to Mercado Envios shipping. Before install the plugin verify if your store has another method of shipping configured. - -= v4.0.8 (13/09/2019) = -* Bug fixes - - Fixed mercado envios - - Fexed show fee in checkout - - Fixed translation file - - Fixed constant file - -= v4.0.7 (12/09/2019) = -* Bug fixes - - Fixed layout incompatibility - - Fixed process to validate card at custom checkout - - Fixed payment due at ticket - - Fixed spanish translation - -= v4.0.6 (09/09/2019) = -* Bug fixes - - Problem with all translations fixed - -= v4.0.5 (04/09/2019) = -* Bug fixes - - Problem with translations in Portuguese fixed - -= v4.0.4 (03/09/2019) = -* Bug fixes - - Conflict between php5.6 and php7 solved - -= v4.0.3 (03/09/2019) = -* Bug fixes - - Fixed basic checkout layout when theme uses bootstrap - - Fixed all Custom checkout layout when theme uses bootstrap - - Fixed input blank in basic checkout config - -= v4.0.2 (02/09/2019) = -* Feature All - - Performance improvement - - UX and UI improvements - - Code refactoring - - Design standards: SOLID, Abstract Factory and Singleton - - SDK Refactor: Avoid repeated external requests. - - New Credential Validation Logic - - Plugin Content Review - - Adjustment in translations - - Unification of general plugin settings with payment method setup, simplifying setup steps - - Logs to assist support and integration -* Bug fixes - - Added product_id - - Fixed payment account_money - - Fixed translation Spanish Neutral and Argentino - -= v4.0.2-Beta (13/08/2019) = -* Bug fixes - - Fixed bug when update plugin from version 3.0.17 - - Fixed bug thats change production mode of basic, custom and ticket checkout when update version. - - Added statement_descriptor in basic checkout - - Fixed title space checkout custom - -= v4.0.1-Beta (09/08/2019) = -* Bug fixes - - Fixed notification IPN and Webhook - - Fixed payment processing - - Fixed Argentina ticket checkout - - Fixed rule for custom checkout to generate token - - Fixed layout checkouts - -= v4.0.0-Beta (02/08/2019) = -* Feature All - - Performance improvement - - UX and UI improvements - - Code refactoring - - Design standards: SOLID, Abstract Factory and Singleton - - SDK Refactor: Avoid repeated external requests. - - New Credential Validation Logic - - Plugin Content Review - - Adjustment in translations - - Unification of general plugin settings with payment method setup, simplifying setup steps - - Logs to assist support and integration - -= v3.1.1 (03/05/2019) = -* Feature All - - Added alert message on all ADMIN pages for setting access_token and public_key credentials, as client_id and client_secret credentials will no longer be used. Basic Checkout will continue to work by setting these new credentials. - - We have added minor translation enhancements. - - We add error message when any API error occurs while validating credentials. - -= v3.1.0 (17/04/2019) = -* Feature All - - We are no longer using client_id and client_secret credentials. This will affect the functioning of the basic checkout. You will need to configure access_token and public_key, in the plugin settings have. You can access the link to get the credentials inside of configurations of plugin. -* Improvements - - Performance enhancements have been made, removing unnecessary requests and adding scope limitation for some functionality. - -= v3.0.17 (07/08/2018) = -* Feature All - - Adding X Product ID - - Migration from v0 (collections) to v1 - -= v3.0.16 (20/07/2018) = -* Feature MCO - - Adding PSE gateway for Colombia -* Improvements - - Some code improvements - -= v3.0.15 (15/03/2018) = -* Improvements - - Allowing customization by merchants, in ticket fields (credits to https://github.com/fernandoacosta) - - Fixed a bug in Mercado Envios processment. - -= v3.0.14 (13/03/2018) = -* Improvements - - Discount and fee by gateway accepts two leading zeros after decimal point; - - Customers now have the option to not save their credit cards; - - Checkout banner is now customizable. - -= v3.0.13 (01/03/2018) = -* Bug fixes - - Fixed a bug in modal window for Basic Checkout. - -= v3.0.12 (28/02/2018) = -* Improvements - - Added date limit for ticket payment; - - Added option for extra tax by payment gateway; - - Increased stability. - -= v3.0.11 (19/02/2018) = -* Improvements - - Improved feedback messages when an order fails; - - Improved credential validation for custom checkout by credit cards. - -= v3.0.10 (29/01/2018) = -* Improvements - - Improved layout in Credit Card and Ticket forms; - - Improved support to WordPress themes. - -= v3.0.9 (16/01/2018) = -* Bug fixes - - Fixed a bug in the URL of product image; - - Fix count error in sdk (credits to xchwarze). - -= v3.0.8 (05/01/2018) = -* Improvements - - Increased support and handling to older PHP; - - IPN/Webhook now customizable. - -= v3.0.7 (21/12/2017) = -* Improvements - - Checking presence of older versions to prevent inconsistences. - -= v3.0.6 (13/12/2017) = -* Improvements - - Added validation for dimensions of products; - - Added country code for analytics. -* Bug fixes - - Fixed a problem related to the title of payment method, that were in blank when configuring the module for the first time. - -= v3.0.5 (22/11/2017) = -* Bug fixes - - Fixed a bug in the URL of javascript source for light-box window. - -= v3.0.4 (13/11/2017) = -* Improvements - - Improved webhook of ticket printing to a less generic one. -* Bug fixes - - FIxed a bug related to payment status of tickets. - -= v3.0.3 (25/10/2017) = -* Features - - Rollout to Uruguay for Custom Checkout and Tickets. -* Bug fixes - - Not showing ticket form when not needed. - -= v3.0.2 (19/10/2017) = -* Bug fixes - - Fixed the absence of [zip_code] field in registered tickets for Brazil. - -= v3.0.1 (04/10/2017) = -* Bug fixes - - We fixed a Javascript problem that are occurring when payments were retried in custom checkout and tickets; - - Resolved the size of Mercado Pago icon in checkout form. -* Improvements - - Allowing absence of SSL if debug mode is enabled; - - Optmizations in form layout of custom checkout and tickets; - - Validating currency consistency before trying conversions; - - References to the new docummentations. - -= v3.0.0 (25/09/2017) = -* Features - - All features already present in Woo-Mercado-Pago-Module 2.x; - - Customization of status mappings between order and payments. -* Improvements - - Added CNPJ document for brazilian tickets; - - Optimization in HTTP requests and algorithms; - - Removal of several redundancies; - - HTML and Javascript separation; - - Improvements in the checklist of system status; - - More intuitive menus and admin navigations. - -= 2.0.9 (2017/03/21) = -* Improvements - - Included sponsor_id to indicate the platform to MercadoPago. - -= 2.0.8 (2016/10/24) = -* Features - - Open MercadoPago Modal when the page load; -* Bug fixes - - Changed notification_url to avoid payment notification issues. - -= 2.0.7 (2016/10/21) = -* Bug fixes - - Improve MercadoPago Modal z-index to avoid issues with any theme. - -= 2.0.6 (2016/07/29) = -* Bug fixes - - Fixed fatal error on IPN handler while log is disabled. - -= 2.0.5 (2016/07/04) = -* Improvements - - Improved Payment Notification handler; - - Added full support for Chile in the settings. - -= 2.0.4 (2016/06/22) = -* Bug fixes - - Fixed `back_urls` parameter. - -= 2.0.3 (2016/06/21) = -* Improvements - - Added support for `notification_url`. - -= 2.0.2 (2016/06/21) = -* Improvements - - Fixed support for WooCommerce 2.6. - -= 2.0.1 (2015/03/12) = -* Improvements - - Removed the SSL verification for the new MercadoPago standards. - -= 2.0.0 (2014/08/16) = -* Features - - Adicionado suporte para a moeda `COP`, lembrando que depende da configuração do seu MercadoPago para isso funcionar; - - Adicionado suporte para traduções no Transifex. -* Bug fixes - * Corrigido o nome do arquivo principal; - * Corrigida as strings de tradução; - * Corrigido o link de cancelamento. diff --git a/templates/checkout/basic-checkout.php b/templates/checkout/basic-checkout.php index b5f979e1b..a60cff21f 100644 --- a/templates/checkout/basic-checkout.php +++ b/templates/checkout/basic-checkout.php @@ -1,83 +1,71 @@
-
-
- -
- - -
- +
+
+ +
+ + +
+ -
- - -
+
+ + +
-
- - -
+
+ + +
- -
- - -
- -
-
+ +
+ + +
+ +
+
-
- - -
+
+ + +
+ if (document.getElementById("payment_method_woo-mercado-pago-custom")) { + jQuery("form.checkout").on( + "checkout_place_order_woo-mercado-pago-basic", + function() { + cardFormLoad(); + } + ); + } + \ No newline at end of file diff --git a/templates/checkout/credential/alert/alert-pix-not-registered.php b/templates/checkout/credential/alert/alert-pix-not-registered.php index bcde174f7..d1ea17aa4 100644 --- a/templates/checkout/credential/alert/alert-pix-not-registered.php +++ b/templates/checkout/credential/alert/alert-pix-not-registered.php @@ -1,20 +1,14 @@ - - - + + \ No newline at end of file diff --git a/templates/checkout/credential/generic-alert.php b/templates/checkout/credential/generic-alert.php index be539a46c..79169df3e 100644 --- a/templates/checkout/credential/generic-alert.php +++ b/templates/checkout/credential/generic-alert.php @@ -1,17 +1,10 @@ -
+
\ No newline at end of file diff --git a/templates/checkout/credential/index.php b/templates/checkout/credential/index.php index 258f3fae9..891711d6d 100644 --- a/templates/checkout/credential/index.php +++ b/templates/checkout/credential/index.php @@ -1,12 +1,5 @@ - - - - - - -
- - -
- -

-
-
+ + + + + + +
+ +

+
+ + + + \ No newline at end of file diff --git a/templates/checkout/credential/steps-pix.php b/templates/checkout/credential/steps-pix.php index b1f36ace9..752f4f7c5 100644 --- a/templates/checkout/credential/steps-pix.php +++ b/templates/checkout/credential/steps-pix.php @@ -1,63 +1,58 @@
-

-
    -
  • -

    1

    -

    - -

    -
  • -
  • -

    2

    -

    - - - - -

    -
  • -
  • -

    3

    -

    - -

    -
  • -
+

+
    +
  • +

    1

    +

    + +

    +
  • +
  • +

    2

    +

    + + + + +

    +
  • +
  • +

    3

    +

    + +

    +
  • +
-
-

-
- -

-
+
+

+
+ +

+
- + - + -
+
\ No newline at end of file diff --git a/templates/checkout/credential/steps.php b/templates/checkout/credential/steps.php index 3bc30da7e..d4260d8a4 100644 --- a/templates/checkout/credential/steps.php +++ b/templates/checkout/credential/steps.php @@ -1,55 +1,49 @@
-

-
    -
  • -

    1

    -

    - - -

    -
  • -
  • -

    2

    -

    - - -

    -
  • -
  • -

    3

    -

    - - -

    -
  • -
  • -

    4

    -

    - - -

    -
  • -
  • -

    5

    -

    - - -

    -
-
+

+

+
    +
  • +

    1

    +

    + + +

    +
  • +
  • +

    2

    +

    + + +

    +
  • +
  • +

    3

    +

    + + +

    +
  • +
  • +

    4

    +

    + + +

    +
  • +
  • +

    5

    +

    + + +

    +
+
\ No newline at end of file diff --git a/templates/checkout/credits-checkout.php b/templates/checkout/credits-checkout.php index 031d48817..b593525f7 100644 --- a/templates/checkout/credits-checkout.php +++ b/templates/checkout/credits-checkout.php @@ -1,73 +1,60 @@
-
-
- -
- - -
- +
+
+ +
+ + +
+ - Log in or create an account in Mercado Pago. If you use Mercado Libre, you already have one!', 'woocommerce-mercadopago'); ?>", - "choose how many installments
you want to pay.', 'woocommerce-mercadopago'); ?>", - "with money in your account, card of from the Mercado Pago app.', 'woocommerce-mercadopago'); ?>" - ]' - list-mode='count' - > - -
- - -
-
-
-
- - -
+ Log in or create an account in Mercado Pago. If you use Mercado Libre, you already have one!', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); ?>", + "choose how many installments you want to pay.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); ?>", + "with money in your account, card of from the Mercado Pago app.', LKN_WC_MERCADOPAGO_TEXT_DOMAIN); ?>" + ]' list-mode='count'> + +
+ + +
+
+
+
+ + +
+ if (document.getElementById("payment_method_woo-mercado-pago-custom")) { + jQuery("form.checkout").on( + "checkout_place_order_woo-mercado-pago-basic", + function() { + cardFormLoad(); + } + ); + } + \ No newline at end of file diff --git a/templates/checkout/custom-checkout.php b/templates/checkout/custom-checkout.php index 451322c65..d7271a20c 100644 --- a/templates/checkout/custom-checkout.php +++ b/templates/checkout/custom-checkout.php @@ -1,217 +1,231 @@
-
- -
- - -
- - - -
- -
- -
- -
- -
- -
- -
-
- - -
-
-
-
- -

- -

-
- - -
- -
- - - - | - - - - -
-
-
- -
-

-
- -
- - -
- -
- - - - -
- -
-
- -
-
- - -
- -
- -
-

- - -
-
- - -
- -
-

- -

- -
-
- -
-
- -
-
- -
- - - - - - -
-
-
-
-
-
-
- -
- - -
-
-
+
+ +
+ + +
+ + + +
+ +
+ +
+ +
+ +
+ +
+ +
+
+ + +
+
+
+
+ +

+ +

+
+ + +
+ +
+ + + + | + + + + +
+
+
+ +
+

+ +

+
+ +
+ + +
+ +
+ + + + +
+ +
+
+ +
+
+ + +
+ +
+ +
+

+ + +
+
+ + +
+ +
+

+ +

+ +
+
+ +
+
+ +
+
+ +
+
+ + + + + + +
+
+
+
+
+
+
+ +
+ + +
+
+
- - - - - - - - - + + + + + + + + +
+ function submitWalletButton(event) { + event.preventDefault(); + jQuery('#mp_checkout_type').val('wallet_button'); + jQuery('form.checkout, form#order_review').submit(); + } + + var availablePayment = document.getElementsByClassName('mp-checkout-custom-available-payments')[0]; + var collapsible = availablePayment.getElementsByClassName('mp-checkout-custom-available-payments-header')[0]; + + collapsible.addEventListener("click", function() { + var icon = collapsible.getElementsByClassName('mp-checkout-custom-available-payments-collapsible')[0]; + var content = availablePayment.getElementsByClassName('mp-checkout-custom-available-payments-content')[ + 0]; + + if (content.style.maxHeight) { + content.style.maxHeight = null; + content.style.padding = "0px"; + icon.src = + ""; + } else { + let hg = content.scrollHeight + 15 + "px"; + content.style.setProperty("max-height", hg, "important"); + content.style.setProperty("padding", "24px 0px 0px", "important"); + + icon.src = + ""; + } + }); + \ No newline at end of file diff --git a/templates/checkout/index.php b/templates/checkout/index.php index 258f3fae9..891711d6d 100644 --- a/templates/checkout/index.php +++ b/templates/checkout/index.php @@ -1,12 +1,5 @@
-
- -
- - -
- +
+ +
+ + +
+ - - + + -
- - -
-
+
+ + +
+
+ if (document.getElementById("payment_method_woo-mercado-pago-custom")) { + jQuery("form.checkout").on( + "checkout_place_order_woo-mercado-pago-pix", + function() { + cardFormLoad(); + } + ); + } + \ No newline at end of file diff --git a/templates/checkout/ticket-checkout.php b/templates/checkout/ticket-checkout.php index e57117748..9ff0579c6 100644 --- a/templates/checkout/ticket-checkout.php +++ b/templates/checkout/ticket-checkout.php @@ -1,114 +1,102 @@
-
-
- -
- - -
- +
+
+ +
+ + +
+ - -
- - -
- + +
+ + +
+ - -
- - -
- + +
+ + +
+ -

- -

+

+ +

- - columns='' - > - + + columns='' + > + - + - -
+ +
- -
- - - - - - -
-
+ +
+ + + + + + +
+
-
- - -
-
+
+ + +
+
+ if (document.getElementById("payment_method_woo-mercado-pago-custom")) { + jQuery("form.checkout").on( + "checkout_place_order_woo-mercado-pago-ticket", + function() { + cardFormLoad(); + } + ); + } + \ No newline at end of file diff --git a/templates/components/activable-input.php b/templates/components/activable-input.php index 1f9ee60b1..783f14caf 100644 --- a/templates/components/activable-input.php +++ b/templates/components/activable-input.php @@ -1,39 +1,51 @@ - - - - -
-
- /> -
- -
-
- - +?> + + + + + +
+
+ + /> +
+ +
+
+ + \ No newline at end of file diff --git a/templates/components/card-info.php b/templates/components/card-info.php index fb8d5245c..49f79847b 100644 --- a/templates/components/card-info.php +++ b/templates/components/card-info.php @@ -1,29 +1,33 @@
-
-
-
-
- - - -
-
-
+
+
+
+
+
+
+ + + +
+
+
\ No newline at end of file diff --git a/templates/components/checkbox-list.php b/templates/components/checkbox-list.php index 0649a455b..734431833 100644 --- a/templates/components/checkbox-list.php +++ b/templates/components/checkbox-list.php @@ -1,50 +1,57 @@ - - - - -
-

- $payment_method_type ) { ?> -
    -
  • -
    - - -
    -
  • - -
  • -
    -
    - > - -
    -
    -
  • - -
- -
- - +?> + + + + + +
+

+ +

+ $payment_method_type ) { ?> +
    +
  • +
    + + +
    +
  • + +
  • +
    +
    + > + +
    +
    +
  • + +
+ +
+ + \ No newline at end of file diff --git a/templates/components/credits-checkout-example.php b/templates/components/credits-checkout-example.php index 76d9269ae..9ee7a9156 100644 --- a/templates/components/credits-checkout-example.php +++ b/templates/components/credits-checkout-example.php @@ -1,33 +1,30 @@
- -

+ +

+

-
-

-
- example -
- -
-
+
+

+ +

+
+ example +
+ +
+
\ No newline at end of file diff --git a/templates/components/credits-info-example.php b/templates/components/credits-info-example.php index d7de25bca..0d58803c7 100644 --- a/templates/components/credits-info-example.php +++ b/templates/components/credits-info-example.php @@ -1,60 +1,56 @@
- -

+ +

+

-
-
-
-
-
- computer -
-
-

-

-
+
+
+
+
+
+ computer +
+
+

+

+
-
-
-
-
-
- cellphone -
+
+
+
+
+
+ cellphone +
-
-

-
-
-
-
-
-
- example -
- -
-
+
+

+

+
+
+
+
+
+
+ example +
+ +
+
\ No newline at end of file diff --git a/templates/components/index.php b/templates/components/index.php index 258f3fae9..891711d6d 100644 --- a/templates/components/index.php +++ b/templates/components/index.php @@ -1,12 +1,5 @@ - + \ No newline at end of file diff --git a/templates/components/toggle-switch.php b/templates/components/toggle-switch.php index c31946b40..cbc617592 100644 --- a/templates/components/toggle-switch.php +++ b/templates/components/toggle-switch.php @@ -1,48 +1,53 @@ - - - -

- - - -
- -
- + + + + +

+ +

+ + + +
+ +
+ - - +?> + + \ No newline at end of file diff --git a/templates/components/wallet-button.php b/templates/components/wallet-button.php index e34fa476d..11d4e65e0 100644 --- a/templates/components/wallet-button.php +++ b/templates/components/wallet-button.php @@ -1,23 +1,17 @@
-
-

-
- -
+
+

+

+
+ +
\ No newline at end of file diff --git a/templates/credits/mp-credits-modal.php b/templates/credits/mp-credits-modal.php index d4eff34af..bb2539576 100644 --- a/templates/credits/mp-credits-modal.php +++ b/templates/credits/mp-credits-modal.php @@ -1,91 +1,98 @@
-
-
- -
-
-
- -
- +
\ No newline at end of file diff --git a/templates/index.php b/templates/index.php index 258f3fae9..891711d6d 100644 --- a/templates/index.php +++ b/templates/index.php @@ -1,12 +1,5 @@
-
-
- -
-


-
-
-
-
-

-
-
-

- -
-
-
-
-
-
-
-

- -
-
-
-
-
-
-
-
-

-
-
-
-
-
-
-
-
-
-

-

- - -

-
- -
-
-
-
-
-

-

-
- -
-
-
-
+
+
+ +
+

+ +
+ + + +

+
+
+
+
+

+ +

+
+
+

+ +

+ +
+
+
+
+
+
+
+
+ +

+ +
+
+
+
+
+
+
+
+

+ +

+
+
+
+
+
+
+
+
+
+

+ +

+

+ + + + + +

+
+ +
+
+
+
+
+

+ +

+

+ + +

+
+ +
+
+
+
-
-
-
-
- - -
-
- -
-
- +
-
-
-
-
- - -
-
- -
-
- +
-
-
-
-
- - -
+
+
+
+
+ + +
-
- -
-
- -
-
-
-
-
- -
- - - - - - -
-
-
- -
-
- +
+ +
+
- + \ No newline at end of file diff --git a/templates/order-received/index.php b/templates/order-received/index.php index 258f3fae9..891711d6d 100644 --- a/templates/order-received/index.php +++ b/templates/order-received/index.php @@ -1,12 +1,5 @@
- - - - - - - - - - - -
( )
-
+ + + + + + + + + + + +
+ + +
+ + + + + ( + + + ) +
+
\ No newline at end of file diff --git a/templates/order-received/show-pix.php b/templates/order-received/show-pix.php index 601499e34..0b26e09f6 100644 --- a/templates/order-received/show-pix.php +++ b/templates/order-received/show-pix.php @@ -1,92 +1,94 @@

- +

-
+
-
+
- + -

- -

-
    -
  • -

    1

    -

    -
  • -
  • -

    - 2 -

    -

    -
  • -
  • -

    - 3 -

    -

    -
  • -
  • -

    - 4 -

    -

    -
  • -
+

+ +

+
    +
  • +

    1

    +

    +

    +
  • +
  • +

    + 2 +

    +

    +

    +
  • +
  • +

    + 3 +

    +

    +

    +
  • +
  • +

    + 4 +

    +

    +

    +
  • +
-
+
-
-

- - - - - - - -

-

- -

- -

- -

-
-

- -

-
- - - -
-
-
-
-
+
+

+ + + + + + + +

+

+ +

+ +

+ +

+
+

+ +

+
+ + + +
+
+
+
+
\ No newline at end of file diff --git a/templates/order-received/show-ticket.php b/templates/order-received/show-ticket.php index 756a96e71..0ea63609f 100644 --- a/templates/order-received/show-ticket.php +++ b/templates/order-received/show-ticket.php @@ -1,25 +1,21 @@

- +

-

- - +

+
+ -

+

\ No newline at end of file diff --git a/templates/order/generic-order-note.php b/templates/order/generic-order-note.php index 2cc6e140b..78e9246ce 100644 --- a/templates/order/generic-order-note.php +++ b/templates/order/generic-order-note.php @@ -1,33 +1,21 @@ - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/templates/order/index.php b/templates/order/index.php index 258f3fae9..891711d6d 100644 --- a/templates/order/index.php +++ b/templates/order/index.php @@ -1,12 +1,5 @@
-

- -

- -
-
- alert -
- -
-

- -

- -

- -

- -

- - - - - -

-
-
-
+

+ +

+ +
+
+ alert +
+ +
+

+ +

+ +

+ +

+ +

+ + + + + +

+
+
+
\ No newline at end of file diff --git a/templates/pix/pix-image-template.php b/templates/pix/pix-image-template.php index 2a8fe3d1e..35e87850a 100644 --- a/templates/pix/pix-image-template.php +++ b/templates/pix/pix-image-template.php @@ -1,22 +1,15 @@
-
- pix -
+ src="" + alt="pix"> +
-
- -
+ + -
-

- -

-
- +

+ +

+ + \ No newline at end of file diff --git a/templates/receipt/custom-checkout.php b/templates/receipt/custom-checkout.php index 79ea2d30b..e7e8b442f 100644 --- a/templates/receipt/custom-checkout.php +++ b/templates/receipt/custom-checkout.php @@ -1,45 +1,40 @@ - - - - + + + + \ No newline at end of file diff --git a/tests/bootstrap.php b/tests/bootstrap.php index e53ee6676..fdf12e6b3 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -3,12 +3,12 @@ $_tests_dir = getenv( 'WP_TESTS_DIR' ); if ( ! $_tests_dir ) { - $_tests_dir = rtrim( sys_get_temp_dir(), '/\\' ) . '/wordpress-tests-lib'; + $_tests_dir = rtrim( sys_get_temp_dir(), '/\\' ) . '/wordpress-tests-lib'; } if ( ! file_exists( $_tests_dir . '/includes/functions.php' ) ) { - echo "Could not find $_tests_dir/includes/functions.php, have you run bin/install-wp-tests.sh ?"; - exit( 1 ); + echo "Could not find $_tests_dir/includes/functions.php, have you run bin/install-wp-tests.sh ?"; + exit( 1 ); } // Give access to tests_add_filter() function. @@ -17,18 +17,18 @@ /** * Manually load the plugin being tested. */ -function _manually_load_plugin() { - require dirname( dirname( __FILE__ ) ) . '/woocommerce-mercadopago.php'; +function _manually_load_plugin(): void { + require dirname( __DIR__ ) . '/lkn-wc-mercadopago.php'; } tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' ); function is_woocommerce_active() { - return true; + return true; } function woothemes_queue_update( $file, $file_id, $product_id ) { - return true; + return true; } // Start up the WP testing environment. diff --git a/tests/includes/admin/notices/test-class-wc-woomercadopago-notices.php b/tests/includes/admin/notices/test-class-wc-woomercadopago-notices.php index bf1555de3..e2db06313 100644 --- a/tests/includes/admin/notices/test-class-wc-woomercadopago-notices.php +++ b/tests/includes/admin/notices/test-class-wc-woomercadopago-notices.php @@ -1,22 +1,23 @@ + public function tearDown(): void { + parent::tearDown(); + } + + public function test_get_alert_frame(): void { + $notices = WC_WooMercadoPago_Notices::get_alert_frame( 'unit', 'test'); + $imgSrc = str_replace( + '/tests', + '', + plugins_url( '../../assets/images/minilogo.png', plugin_dir_path( __FILE__ ) ) + ); + $assert = '
@@ -26,6 +27,6 @@ function test_get_alert_frame() {
'; - $this->assertSame( $assert, $notices ); - } + $this->assertSame( $assert, $notices ); + } } diff --git a/tests/includes/modules/test-class-wc-woomercadopago-configs.php b/tests/includes/modules/test-class-wc-woomercadopago-configs.php index a6d83aa6c..3bed37667 100644 --- a/tests/includes/modules/test-class-wc-woomercadopago-configs.php +++ b/tests/includes/modules/test-class-wc-woomercadopago-configs.php @@ -10,256 +10,255 @@ * WC_WooMercadoPago_ConfigsTest */ class WC_WooMercadoPago_ConfigsTest extends WP_UnitTestCase { + public function setUp(): void { + require_once dirname( __DIR__ ) . '/../../includes/module/class-wc-woomercadopago-configs.php'; + require_once dirname( __DIR__ ) . '/../../includes/module/class-wc-woomercadopago-credentials.php'; + require_once dirname( __DIR__ ) . '/../../includes/module/class-wc-woomercadopago-module.php'; + require_once dirname( __DIR__ ) . '/../../includes/module/class-wc-woomercadopago-options.php'; + require_once dirname( __DIR__ ) . '/../../includes/helpers/class-wc-woomercadopago-helper-credits.php'; - function setUp() { - require_once dirname( dirname( __FILE__ ) ) . '/../../includes/module/class-wc-woomercadopago-configs.php'; - require_once dirname( dirname( __FILE__ ) ) . '/../../includes/module/class-wc-woomercadopago-credentials.php'; - require_once dirname( dirname( __FILE__ ) ) . '/../../includes/module/class-wc-woomercadopago-module.php'; - require_once dirname( dirname( __FILE__ ) ) . '/../../includes/module/class-wc-woomercadopago-options.php'; - require_once dirname( dirname( __FILE__ ) ) . '/../../includes/helpers/class-wc-woomercadopago-helper-credits.php'; + update_option( 'woocommerce_default_country', 'BR:SP', true ); + } - update_option( 'woocommerce_default_country', 'BR:SP', true ); - } + /** + * Get Country Configs. + */ + public function test_get_country_configs(): void { + $country_configs = WC_WooMercadoPago_Configs::get_country_configs(); - /** - * Get Country Configs. - */ - function test_get_country_configs() { - $country_configs = WC_WooMercadoPago_Configs::get_country_configs(); + $url_mco_standard_mco = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MCO/standard_mco.jpg', plugin_dir_path( __FILE__ ) ) ); + $url_mco_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MCO/credit_card.png', plugin_dir_path( __FILE__ ) ) ); - $url_mco_standard_mco = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MCO/standard_mco.jpg', plugin_dir_path( __FILE__ ) ) ); - $url_mco_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MCO/credit_card.png', plugin_dir_path( __FILE__ ) ) ); + $url_mla_standard_mla = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLA/standard_mla.jpg', plugin_dir_path( __FILE__ ) ) ); + $url_mla_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLA/credit_card.png', plugin_dir_path( __FILE__ ) ) ); - $url_mla_standard_mla = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLA/standard_mla.jpg', plugin_dir_path( __FILE__ ) ) ); - $url_mla_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLA/credit_card.png', plugin_dir_path( __FILE__ ) ) ); + $url_mlb_standard_mlb = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLB/standard_mlb.jpg', plugin_dir_path( __FILE__ ) ) ); + $url_mlb_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLB/credit_card.png', plugin_dir_path( __FILE__ ) ) ); - $url_mlb_standard_mlb = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLB/standard_mlb.jpg', plugin_dir_path( __FILE__ ) ) ); - $url_mlb_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLB/credit_card.png', plugin_dir_path( __FILE__ ) ) ); + $url_mlc_standard_mlc = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLC/standard_mlc.gif', plugin_dir_path( __FILE__ ) ) ); + $url_mlc_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLC/credit_card.png', plugin_dir_path( __FILE__ ) ) ); - $url_mlc_standard_mlc = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLC/standard_mlc.gif', plugin_dir_path( __FILE__ ) ) ); - $url_mlc_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLC/credit_card.png', plugin_dir_path( __FILE__ ) ) ); + $url_mlm_standard_mlm = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLM/standard_mlm.jpg', plugin_dir_path( __FILE__ ) ) ); + $url_mlm_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLM/credit_card.png', plugin_dir_path( __FILE__ ) ) ); - $url_mlm_standard_mlm = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLM/standard_mlm.jpg', plugin_dir_path( __FILE__ ) ) ); - $url_mlm_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLM/credit_card.png', plugin_dir_path( __FILE__ ) ) ); + $url_mlu_standard_mlu = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLU/standard_mlu.png', plugin_dir_path( __FILE__ ) ) ); + $url_mlu_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLU/credit_card.png', plugin_dir_path( __FILE__ ) ) ); - $url_mlu_standard_mlu = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLU/standard_mlu.png', plugin_dir_path( __FILE__ ) ) ); - $url_mlu_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLU/credit_card.png', plugin_dir_path( __FILE__ ) ) ); + $url_mlv_standard_mlv = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLV/standard_mlv.jpg', plugin_dir_path( __FILE__ ) ) ); + $url_mlv_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLV/credit_card.png', plugin_dir_path( __FILE__ ) ) ); - $url_mlv_standard_mlv = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLV/standard_mlv.jpg', plugin_dir_path( __FILE__ ) ) ); - $url_mlv_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MLV/credit_card.png', plugin_dir_path( __FILE__ ) ) ); + $url_mpe_standard_mpe = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MPE/standard_mpe.png', plugin_dir_path( __FILE__ ) ) ); + $url_mpe_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MPE/credit_card.png', plugin_dir_path( __FILE__ ) ) ); - $url_mpe_standard_mpe = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MPE/standard_mpe.png', plugin_dir_path( __FILE__ ) ) ); - $url_mpe_credit_card = str_replace( '/tests', '', plugins_url( 'module/../../assets/images/MPE/credit_card.png', plugin_dir_path( __FILE__ ) ) ); + $country_configs_mock = array( + 'mco' => array( + 'site_id' => 'mco', + 'sponsor_id' => 208687643, + 'checkout_banner' => $url_mco_standard_mco, + 'checkout_banner_custom' => $url_mco_credit_card, + 'currency' => 'COP', + 'zip_code' => '110111', + 'currency_symbol' => '$', + 'intl' => 'es-CO', + ), + 'mla' => array( + 'site_id' => 'mla', + 'sponsor_id' => 208682286, + 'checkout_banner' => $url_mla_standard_mla, + 'checkout_banner_custom' => $url_mla_credit_card, + 'currency' => 'ARS', + 'zip_code' => '3039', + 'currency_symbol' => '$', + 'intl' => 'es-AR', + ), + 'mlb' => array( + 'site_id' => 'mlb', + 'sponsor_id' => 208686191, + 'checkout_banner' => $url_mlb_standard_mlb, + 'checkout_banner_custom' => $url_mlb_credit_card, + 'currency' => 'BRL', + 'zip_code' => '01310924', + 'currency_symbol' => 'R$', + 'intl' => 'pt-BR', + ), + 'mlc' => array( + 'site_id' => 'mlc', + 'sponsor_id' => 208690789, + 'checkout_banner' => $url_mlc_standard_mlc, + 'checkout_banner_custom' => $url_mlc_credit_card, + 'currency' => 'CLP', + 'zip_code' => '7591538', + 'currency_symbol' => '$', + 'intl' => 'es-CL', + ), + 'mlm' => array( + 'site_id' => 'mlm', + 'sponsor_id' => 208692380, + 'checkout_banner' => $url_mlm_standard_mlm, + 'checkout_banner_custom' => $url_mlm_credit_card, + 'currency' => 'MXN', + 'zip_code' => '11250', + 'currency_symbol' => '$', + 'intl' => 'es-MX', + ), + 'mlu' => array( + 'site_id' => 'mlu', + 'sponsor_id' => 243692679, + 'checkout_banner' => $url_mlu_standard_mlu, + 'checkout_banner_custom' => $url_mlu_credit_card, + 'currency' => 'UYU', + 'zip_code' => '11800', + 'currency_symbol' => '$', + 'intl' => 'es-UY', + ), + 'mlv' => array( + 'site_id' => 'mlv', + 'sponsor_id' => 208692735, + 'checkout_banner' => $url_mlv_standard_mlv, + 'checkout_banner_custom' => $url_mlv_credit_card, + 'currency' => 'VEF', + 'zip_code' => '1160', + 'currency_symbol' => '$', + 'intl' => 'es-VE', + ), + 'mpe' => array( + 'site_id' => 'mpe', + 'sponsor_id' => 216998692, + 'checkout_banner' => $url_mpe_standard_mpe, + 'checkout_banner_custom' => $url_mpe_credit_card, + 'currency' => 'PEN', + 'zip_code' => '15074', + 'currency_symbol' => '$', + 'intl' => 'es-PE', + ), + ); - $country_configs_mock = array( - 'mco' => array( - 'site_id' => 'mco', - 'sponsor_id' => 208687643, - 'checkout_banner' => $url_mco_standard_mco, - 'checkout_banner_custom' => $url_mco_credit_card, - 'currency' => 'COP', - 'zip_code' => '110111', - 'currency_symbol' => '$', - 'intl' => 'es-CO', - ), - 'mla' => array( - 'site_id' => 'mla', - 'sponsor_id' => 208682286, - 'checkout_banner' => $url_mla_standard_mla, - 'checkout_banner_custom' => $url_mla_credit_card, - 'currency' => 'ARS', - 'zip_code' => '3039', - 'currency_symbol' => '$', - 'intl' => 'es-AR', - ), - 'mlb' => array( - 'site_id' => 'mlb', - 'sponsor_id' => 208686191, - 'checkout_banner' => $url_mlb_standard_mlb, - 'checkout_banner_custom' => $url_mlb_credit_card, - 'currency' => 'BRL', - 'zip_code' => '01310924', - 'currency_symbol' => 'R$', - 'intl' => 'pt-BR', - ), - 'mlc' => array( - 'site_id' => 'mlc', - 'sponsor_id' => 208690789, - 'checkout_banner' => $url_mlc_standard_mlc, - 'checkout_banner_custom' => $url_mlc_credit_card, - 'currency' => 'CLP', - 'zip_code' => '7591538', - 'currency_symbol' => '$', - 'intl' => 'es-CL', - ), - 'mlm' => array( - 'site_id' => 'mlm', - 'sponsor_id' => 208692380, - 'checkout_banner' => $url_mlm_standard_mlm, - 'checkout_banner_custom' => $url_mlm_credit_card, - 'currency' => 'MXN', - 'zip_code' => '11250', - 'currency_symbol' => '$', - 'intl' => 'es-MX', - ), - 'mlu' => array( - 'site_id' => 'mlu', - 'sponsor_id' => 243692679, - 'checkout_banner' => $url_mlu_standard_mlu, - 'checkout_banner_custom' => $url_mlu_credit_card, - 'currency' => 'UYU', - 'zip_code' => '11800', - 'currency_symbol' => '$', - 'intl' => 'es-UY', - ), - 'mlv' => array( - 'site_id' => 'mlv', - 'sponsor_id' => 208692735, - 'checkout_banner' => $url_mlv_standard_mlv, - 'checkout_banner_custom' => $url_mlv_credit_card, - 'currency' => 'VEF', - 'zip_code' => '1160', - 'currency_symbol' => '$', - 'intl' => 'es-VE', - ), - 'mpe' => array( - 'site_id' => 'mpe', - 'sponsor_id' => 216998692, - 'checkout_banner' => $url_mpe_standard_mpe, - 'checkout_banner_custom' => $url_mpe_credit_card, - 'currency' => 'PEN', - 'zip_code' => '15074', - 'currency_symbol' => '$', - 'intl' => 'es-PE', - ), - ); + $this->assertEqualSets( $country_configs_mock, $country_configs ); + } - $this->assertEqualSets( $country_configs_mock , $country_configs ); - } + /** + * Get categories + * + * @return array + */ + public function test_get_categories() { + $woomercadoPago_configs = new WC_WooMercadoPago_Configs(); + $categories = $woomercadoPago_configs->get_categories(); + $categories_mock = 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', + ), + ); - /** - * Get categories - * - * @return array - */ - public function test_get_categories() { - $woomercadoPago_configs = new WC_WooMercadoPago_Configs; - $categories = $woomercadoPago_configs->get_categories(); - $categories_mock = 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', - ), - ); + $this->assertEqualSets( $categories_mock, $categories ); + } - $this->assertEqualSets( $categories_mock , $categories ); - } - - /** - * Set payment for Brazil - */ - public function test_set_payment_gateway() { - $credits_helper_mock = $this->getMockBuilder(WC_WooMercadoPago_Helper_Credits::class) - ->setMethods(['is_credits']) - ->getMock(); - $credits_helper_mock->expects($this->any()) - ->method('is_credits') - ->willReturn(1); + /** + * Set payment for Brazil + */ + public function test_set_payment_gateway(): void { + $credits_helper_mock = $this->getMockBuilder('WC_WooMercadoPago_Helper_Credits') + ->setMethods(array('is_credits')) + ->getMock(); + $credits_helper_mock->expects($this->any()) + ->method('is_credits') + ->willReturn(1); - $woomercadoPago_configs = $this->getMockBuilder(WC_WooMercadoPago_Configs::class) - ->setMethods(['get_credits_helper_instance']) - ->getMock(); - $woomercadoPago_configs->expects($this->any()) - ->method('get_credits_helper_instance') - ->willReturn($credits_helper_mock); + $woomercadoPago_configs = $this->getMockBuilder('WC_WooMercadoPago_Configs') + ->setMethods(array('get_credits_helper_instance')) + ->getMock(); + $woomercadoPago_configs->expects($this->any()) + ->method('get_credits_helper_instance') + ->willReturn($credits_helper_mock); - $payment_gateway = $woomercadoPago_configs->set_payment_gateway( [] ); - $methods_returned = array ( - 'WC_WooMercadoPago_Basic_Gateway', - 'WC_WooMercadoPago_Custom_Gateway', - 'WC_WooMercadoPago_Ticket_Gateway', - 'WC_WooMercadoPago_Pix_Gateway', - 'WC_WooMercadoPago_Credits_Gateway', - ); + $payment_gateway = $woomercadoPago_configs->set_payment_gateway( array() ); + $methods_returned = array ( + 'WC_WooMercadoPago_Basic_Gateway', + 'WC_WooMercadoPago_Custom_Gateway', + 'WC_WooMercadoPago_Ticket_Gateway', + 'WC_WooMercadoPago_Pix_Gateway', + 'WC_WooMercadoPago_Credits_Gateway', + ); - $this->assertEqualSets( $methods_returned , $payment_gateway ); - } + $this->assertEqualSets( $methods_returned, $payment_gateway ); + } - /** - * Get available payment methods for Brazil - */ - public function test_get_available_payment_methods() { - $credits_helper_mock = $this->getMockBuilder(WC_WooMercadoPago_Helper_Credits::class) - ->setMethods(['is_credits']) - ->getMock(); - $credits_helper_mock->expects($this->any()) - ->method('is_credits') - ->willReturn(1); + /** + * Get available payment methods for Brazil + */ + public function test_get_available_payment_methods(): void { + $credits_helper_mock = $this->getMockBuilder('WC_WooMercadoPago_Helper_Credits') + ->setMethods(array('is_credits')) + ->getMock(); + $credits_helper_mock->expects($this->any()) + ->method('is_credits') + ->willReturn(1); - $woomercadoPago_configs = $this->getMockBuilder(WC_WooMercadoPago_Configs::class) - ->setMethods(['get_credits_helper_instance']) - ->getMock(); - $woomercadoPago_configs->expects($this->any()) - ->method('get_credits_helper_instance') - ->willReturn($credits_helper_mock); + $woomercadoPago_configs = $this->getMockBuilder('WC_WooMercadoPago_Configs') + ->setMethods(array('get_credits_helper_instance')) + ->getMock(); + $woomercadoPago_configs->expects($this->any()) + ->method('get_credits_helper_instance') + ->willReturn($credits_helper_mock); - $payment_gateway = $woomercadoPago_configs->get_available_payment_methods( [] ); - $methods_returned = array ( - 'WC_WooMercadoPago_Basic_Gateway', - 'WC_WooMercadoPago_Custom_Gateway', - 'WC_WooMercadoPago_Ticket_Gateway', - 'WC_WooMercadoPago_Pix_Gateway', - 'WC_WooMercadoPago_Credits_Gateway', - ); + $payment_gateway = $woomercadoPago_configs->get_available_payment_methods( array() ); + $methods_returned = array ( + 'WC_WooMercadoPago_Basic_Gateway', + 'WC_WooMercadoPago_Custom_Gateway', + 'WC_WooMercadoPago_Ticket_Gateway', + 'WC_WooMercadoPago_Pix_Gateway', + 'WC_WooMercadoPago_Credits_Gateway', + ); - $this->assertEqualSets( $methods_returned , $payment_gateway ); - } + $this->assertEqualSets( $methods_returned, $payment_gateway ); + } } diff --git a/tests/test-sample.php b/tests/test-sample.php index 5dd94fb10..355836cb6 100644 --- a/tests/test-sample.php +++ b/tests/test-sample.php @@ -9,12 +9,11 @@ * Sample test case. */ class SampleTest extends WP_UnitTestCase { - - /** - * A single example test. - */ - function test_sample() { - // Replace this with some actual testing code. - $this->assertTrue( true ); - } + /** + * A single example test. + */ + public function test_sample(): void { + // Replace this with some actual testing code. + $this->assertTrue( true ); + } } diff --git a/woocommerce-mercadopago.php b/woocommerce-mercadopago.php deleted file mode 100644 index 406a9ea1a..000000000 --- a/woocommerce-mercadopago.php +++ /dev/null @@ -1,40 +0,0 @@ -