Plugin Directory

Changeset 3176106


Ignore:
Timestamp:
10/26/2024 04:27:00 PM (17 months ago)
Author:
felixmp
Message:

1.3.0 - Corrige compatibilidad con nuevo WP

Location:
metrepay/trunk
Files:
1 added
4 edited

Legend:

Unmodified
Added
Removed
  • metrepay/trunk/assets/metrepay.js

    r2962760 r3176106  
    11document.addEventListener('DOMContentLoaded', () => {
    2     if (!document.getElementById('activeDA')) return
     2    if (!document.getElementById('activeDA')) {
     3        console.log('Metrepay Plugin - No element activeDA');
     4        return
     5    }
    36
    47    const activeDA =
     
    811        ? parseInt(getCookie('mp_installments_quantity'))
    912        : null
    10     console.log('currentCartInstallments', currentCartInstallments)
     13    console.log('Metrepay Plugin - currentCartInstallments', currentCartInstallments)
    1114
    1215    const labelAllowedPaymentMethods = '<br>' +
     
    5962
    6063            if (inputPU.checked) {
    61                 console.log('Seleccionado PAGO_UNICO')
     64                console.log('Metrepay Plugin - Seleccionado PAGO_UNICO')
    6265            }
    6366
    6467            if (activeDA) {
    6568                if (inputDA.checked) {
    66                     console.log('Seleccionado DEBITO_AUTOMATICO')
     69                    console.log('Metrepay Plugin - Seleccionado DEBITO_AUTOMATICO')
    6770                }
    6871            }
  • metrepay/trunk/metrepay.php

    r2963879 r3176106  
    44Plugin URI: https://wordpress.org/plugins/metrepay
    55Description: Pasarela de pago para integracion con MetrePay y Woocomerce
    6 Version: 1.2.0
     6Version: 1.3.0
    77Author: Rugertek
    88Author URI: https://rugertek.com/
     
    6060            // Mandatory variables.
    6161            $this->id = 'metrepay_gateway';
    62             $this->icon = 'https://test.metrepay.com/res/img/logo_metrepay_blanco_sin_margen.png';
    6362            $this->has_fields = false; // in case you need a custom credit card form (Direct integration)
    6463            $this->method_title = 'MetrePay Gateway';
     
    8281            // First, get this param to modify the payment box behavior
    8382            $this->active_da = sanitize_text_field($this->get_option('active_da'));
     83
    8484            // Second, depending on the param before, the box behavior will change
    85             $this->description = "Pagá con tu tarjeta de crédito o débito.
    86                 <div id='metrepayselector'></div>
    87                 <input type='hidden' id='activeDA' value='$this->active_da'>";
     85            $this->description = "Pagá con tu tarjeta de crédito o débito.";
    8886            $this->enabled = sanitize_text_field($this->get_option('enabled'));
    8987            $this->debugging = 'yes' === sanitize_text_field($this->get_option('debugging'));
    9088            $this->auth_token = sanitize_text_field($this->get_option('auth_token'));
    9189            $this->provider_slug = sanitize_text_field($this->get_option('provider_slug'));
    92             $this->staging = sanitize_text_field($this->get_option('staging'));
     90            $this->instance = sanitize_text_field($this->get_option('instance'));
     91            $this->use_site_currency = 'no' === sanitize_text_field($this->get_option('use_site_currency'));
    9392            $this->header_token = $this->mpay_local_generate_string();
    9493
     
    9998
    10099            wp_enqueue_script('metrepay_gateway_javascript', plugins_url('/assets/metrepay.js', __FILE__));
     100            wp_enqueue_style('metrepay_gateway_styles', plugins_url('/assets/metrepay.css', __FILE__));
     101        }
     102
     103        /**
     104         * Override al método que prepara el contenido del box de medio de
     105         * pago en checkout. Aplicamos override dado que el metodo original
     106         * limpia los "<input>" y lo necesitamos para aplicar lógica de
     107         * pago unico o débito automático
     108         */
     109        public function payment_fields()
     110        {
     111            // Renderiza la descripción sin modificaciones
     112            echo "<div class='description-container'>
     113                    <img src='https://www.metrepay.com/home/img/logos/full-icon.png'>
     114                    " . wpautop(wptexturize($this->description)) . "
     115                </div>";
     116
     117            // Agrega el div y el input adicional sin pasar por filtros de seguridad
     118            echo '<div id="metrepayselector"></div>';
     119            echo '<input type="hidden" id="activeDA" value="' . esc_attr($this->active_da) . '">';
    101120        }
    102121
    103122        public function init_form_fields()
    104123        {
    105 
    106124            $this->form_fields = array(
    107125                'enabled' => array(
     
    126144                    'desc_tip'    => true,
    127145                ),
    128                 'staging' => array(
    129                     'title'       => 'Entorno de desarrollo',
    130                     'label'       => 'Staging',
    131                     'type'        => 'checkbox',
    132                     'description' => 'Marcar si la plataforma de comercio está en modo de pruebas',
    133                     'default'     => 'yes',
     146                'instance' => array(
     147                    'title'       => 'URL MetrePay',
     148                    'type'        => 'text',
     149                    'description' => 'Dirección URL del sitio MetrePay que utiliza el comercio. Ejemplo: test.metrepay.com',
     150                    'default'     => 'portal.metrepay.com',
    134151                    'desc_tip'    => true,
    135152                ),
     
    143160                    'type'        => 'text',
    144161                    'description' => 'Información adicional del comercio en MetrePay. Es proveído con el Token API Key.',
     162                ),
     163                'use_site_currency' => array(
     164                    'title'       => 'Moneda del sitio',
     165                    'label'       => 'Utilizar la moneda configurada en el sitio actual: ' . get_woocommerce_currency(),
     166                    'type'        => 'checkbox',
     167                    'description' => 'Si se activa, cada link de pago generado será con la moneda configurada en el sitio Woocommerce. Si se desactiva, la moneda será la establecida por defecto en MetrePay. La habilitación de la moneda a utilizarse está sujeta a cuál sitio MetrePay uno esté registrado. En caso de dudas, contacte con su asesor.',
     168                    'default'     => 'no'
    145169                ),
    146170                'active_da' => array(
     
    154178        }
    155179
     180        public function get_debugging()
     181        {
     182            return $this->debugging;
     183        }
     184
     185        public function get_auth_token()
     186        {
     187            return $this->auth_token;
     188        }
     189
     190        public function get_provider_slug()
     191        {
     192            return $this->provider_slug;
     193        }
     194
     195        public function get_active_da()
     196        {
     197            return $this->active_da;
     198        }
     199       
     200        public function get_instance()
     201        {
     202            return $this->instance;
     203        }
     204
     205        public function get_use_site_currency()
     206        {
     207            return $this->use_site_currency;
     208        }
     209
    156210        // Conect to the services
    157 
    158211        public function process_payment($order_id)
    159212        {
     
    163216            if ($this->get_mp_payment_method() == "PAGO_UNICO") {
    164217                $data = array(
    165                     "label" => "Pago a " . get_bloginfo("name"),
    166                     "amount" => intval($order->get_total()),
    167                     "handleValue" => $order->get_billing_email(),
    168                     "handleLabel" => "{$order->get_billing_first_name()} {$order->get_billing_last_name()}",
    169                     "customIdentifier" => get_post_meta($order->get_id(), 'CIRUC', true),
    170218                    "singlePayment" => true,
    171219                    "creditAndDebitCard" => true,
    172                     "redirectUrl" => get_bloginfo("url") . "/pago-metrepay/?order_id=" . $order_id,
    173220                );
    174221            } else {
     
    180227
    181228                $data = array(
    182                     "label" => "Pago a " . get_bloginfo("name"),
    183                     "amount" => intval($order->get_total()),
    184                     "handleValue" => $order->get_billing_email(),
    185                     "handleLabel" => "{$order->get_billing_first_name()} {$order->get_billing_last_name()}",
    186                     "customIdentifier" =>  get_post_meta($order->get_id(), 'CIRUC', true),
    187229                    "singlePayment" => false,
    188230                    "creditAndDebitCard" => true,
     
    193235                    "monthForSecondInstallment" => 1,
    194236                    "payWaitHours" => 96,
    195                     "redirectUrl" => get_bloginfo("url") . "/pago-metrepay/?order_id=" . $order_id,
    196237                );
    197238            }
    198239
    199             if ($this->get_staging() == "yes") {
    200                 $url = "https://test.metrepay.com/api/saleitems/add";
    201             } else {
    202                 $url = "https://portal.metrepay.com/api/saleitems/add";
    203             }
    204 
    205             $response = $this->mpay_local_data_post($url, $data);
     240            // Establece los campos adicionales para el link de pago
     241            $data['label'] = "Pago a " . get_bloginfo("name");
     242            $data['amount'] = intval($order->get_total());
     243            $data['handleValue'] = $order->get_billing_email();
     244            $data['handleLabel'] = "{$order->get_billing_first_name()} {$order->get_billing_last_name()}";
     245            $data['customIdentifier'] = get_post_meta($order->get_id(), 'CIRUC', true);
     246
     247            // Obtiene URL a página de pago de MP en el sitio ecommerce
     248            $query = new WP_Query( array( 'pagename' => 'pago-metrepay' ) );
     249            $redirectUrl = get_permalink($query->get_queried_object());
     250            $redirectUrl = add_query_arg('order_id', $order_id, $redirectUrl);
     251            $data['redirectUrl'] = $redirectUrl;
     252
     253            // Según el parámetro del comercio, si quiere o no utilizar la moneda configurada
     254            if ($this->get_use_site_currency() == 'yes') {
     255                $data['currency'] = get_woocommerce_currency();
     256            }
     257
     258            $response = $this->mpay_local_data_post($data);
    206259            $result = json_decode($response, true);
    207260
     
    232285            $installments_quantity = null;
    233286            // If DA is active or not
    234             $active_da = $this->get_active_da();
     287            $active_da = $this->get_active_da() == 'yes';
    235288
    236289            if (!isset(WC()->cart)) {
     
    255308
    256309            if ($can_have_da) {
     310                error_log('can_have_da: ' . $can_have_da);
    257311                // We setup the cookie
    258312                $this->mpay_local_set_cookie('mp_installments_quantity', $installments_quantity);
     
    274328        }
    275329
    276         public function get_debugging()
    277         {
    278             return $this->debugging;
    279         }
    280 
    281         public function get_auth_token()
    282         {
    283             return $this->auth_token;
    284         }
    285 
    286         public function get_provider_slug()
    287         {
    288             return $this->provider_slug;
    289         }
    290 
    291         public function get_active_da()
    292         {
    293             return $this->active_da;
    294         }
    295 
    296         public function get_staging()
    297         {
    298             return $this->staging;
    299         }
    300 
    301 
    302330        // Helpers
    303331        function mpay_local_generate_string($strength = 16)
     
    315343        }
    316344
    317         function mpay_local_data_post($url, $data) {
    318             $args = array(
    319                 'method'      => 'POST',
    320                 'body'        => json_encode($data),
    321                 'timeout'     => '5',
    322                 'httpversion' => '1.0',
    323                 'blocking'    => true,
    324                 'headers'     => array(
    325                     'Content-Type' => 'application/json',
    326                     'Api-Token'    => $this->get_auth_token()
    327                 ),
    328             );
    329             $response = wp_remote_post($url, $args);
    330             return $response['body'];
     345        function mpay_local_show_error_to_user() {
     346            wc_add_notice(__('El método de pago MetrePay debe ser revisado. Por favor, contacte al administrador'), 'error');
     347        }
     348
     349        function mpay_local_get_mp_url() {
     350            // Obtiene la instancia actual
     351            $instance = $this->get_instance();
     352
     353            // Valida que la instancia no esté vacía
     354            if (empty($instance)) {
     355                throw new Exception("Error: No se ha definido una instancia válida. Por favor, contacte al administrador.");
     356            }
     357
     358            // Formatea y sanitiza la URL
     359            $instance = trim($instance); // Elimina espacios
     360            $instance = filter_var($instance, FILTER_SANITIZE_URL); // Elimina caracteres no válidos en una URL
     361
     362            // Construye la URL final
     363            $url = "https://{$instance}/api/saleitems/add";
     364
     365            // Valida la estructura de la URL
     366            if (!filter_var($url, FILTER_VALIDATE_URL)) {
     367                throw new Exception("Error: La URL generada no es válida. Por favor, contacte al administrador.");
     368            }
     369
     370            return $url;
     371        }
     372
     373        function mpay_local_data_post($data) {
     374            try {
     375                $url = $this->mpay_local_get_mp_url();
     376                error_log(json_encode($url));
     377
     378                $args = array(
     379                    'method'      => 'POST',
     380                    'body'        => json_encode($data),
     381                    'timeout'     => '5',
     382                    'httpversion' => '1.0',
     383                    'blocking'    => true,
     384                    'headers'     => array(
     385                        'Content-Type' => 'application/json',
     386                        'Api-Token'    => $this->get_auth_token()
     387                    ),
     388                );
     389                $response = wp_remote_post($url, $args);
     390                return $response['body'];
     391
     392            } catch (Exception $e) {
     393                error_log('Message: ' .$e->getMessage());
     394                $this->mpay_local_show_error_to_user();
     395            }
    331396        }
    332397
  • metrepay/trunk/readme.md

    r2962760 r3176106  
    33Contributors: Rugertek
    44Requires at least: 5.3
    5 Tested up to: 6.0
     5Tested up to: 6.6.2
    66Requires PHP: 7.3.5
    77
  • metrepay/trunk/readme.txt

    r2963879 r3176106  
    33Tags: metrepay, payment
    44Requires at least: 5.3
    5 Tested up to: 6.3.1
    6 Stable tag: 1.2.0
     5Tested up to: 6.6.2
     6Stable tag: 1.3.0
    77Requires PHP: 7.3.5
    88License: GPLv3
     
    3030
    3131= 1.1.2 =
    32 * Improve texts into configuration form fields
     32* Improve texts into configuration form fields.
    3333
    3434= 1.2.0 =
    35 * Remove use of iframe to process payment
    36 * Update correctly the order status to "completed"
     35* Remove use of iframe to process payment.
     36* Update correctly the order status to "completed".
     37
     38= 1.3.0 =
     39* Add configuration parameter to set preferred MetrePay instance.
     40* Add parameter to use (or not) configured site currency.
     41* Remove "staging" configuration parameter.
     42* Fix URL generation considering site permalink to pos-checkout page "pago-metrepay".
     43* Fix checkout box to view options: "Single payment" or "Recurrent payment".
     44* Optimize API request body generation.
Note: See TracChangeset for help on using the changeset viewer.