Plugin Directory

Changeset 3183746


Ignore:
Timestamp:
11/07/2024 11:03:38 AM (17 months ago)
Author:
felixmp
Message:

1.4.0 - Add setting form fields for custom IDs and login requirement

Location:
metrepay/trunk
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • metrepay/trunk/includes/fields.php

    r3176106 r3183746  
    11<?php
     2
    23
    34/**
     
    1213
    1314    <?php
     15   
     16    /**
     17     * CI/RUC es requerido cuando:
     18     * 1- No tiene custom identifier 1. Es decir, necesitamos un custom ID
     19     * 2- No posee login requerido en los links de pago
     20     * Cualquiera de las 2 opciones anteriores es motivo suficiente para que sea requerido
     21     */
     22    $mg = new WC_Metrepay_Gateway;
     23    $required = !$mg->has_custom_id_1() || !$mg->get_links_login_required();
    1424
    1525    woocommerce_form_field('ciruc', array(
    1626        'type'          => 'text',
    1727        'class'         => array('my-field-class form-row-wide'),
    18         'label'         => __('CI o RUC'),
    19         'placeholder'   => __('Ej: 1234567'),
    20         'required'      => true,
     28        'label'         => __('CI (número de documento de identidad) o RUC'),
     29        'placeholder'   => __('Ej: 1200300'),
     30        'required'      => $required,
    2131    ), $checkout->get_value('ciruc'));
    2232}
     
    3545function mpay_local_validate_ciRuc()
    3646{
     47    /**
     48     * CI/RUC es requerido cuando:
     49     * 1- No tiene custom identifier 1. Es decir, necesitamos un custom ID
     50     * 2- No posee login requerido en los links de pago
     51     * Cualquiera de las 2 opciones anteriores es motivo suficiente para que sea requerido
     52     */
     53    $mg = new WC_Metrepay_Gateway;
     54    $required = !$mg->has_custom_id_1() || !$mg->get_links_login_required();
     55
    3756    // Check if set, if its not set add an error.
    38     if (empty($_POST['ciruc']))
     57    if (empty($_POST['ciruc']) && $required)
    3958        wc_add_notice(__('Por favor cargar CI o RUC.'), 'error');
    4059}
  • metrepay/trunk/metrepay.php

    r3176106 r3183746  
    5757        public function __construct()
    5858        {
    59 
    6059            // Mandatory variables.
    6160            $this->id = 'metrepay_gateway';
     
    6463            $this->method_description = 'Aquí se configuran las opciones de MetrePay.';
    6564
     65            $this->logger = wc_get_logger();
     66            $this->context = array( 'source' => 'metrepay' );
     67
    6668            // Salt configuration.
    6769            $this->salt = "PsK5fW";
     
    8082            // DA means Debito Automatico
    8183            // First, get this param to modify the payment box behavior
    82             $this->active_da = sanitize_text_field($this->get_option('active_da'));
     84            $this->active_da = 'yes' === sanitize_text_field($this->get_option('active_da'));
    8385
    8486            // Second, depending on the param before, the box behavior will change
     
    8991            $this->provider_slug = sanitize_text_field($this->get_option('provider_slug'));
    9092            $this->instance = sanitize_text_field($this->get_option('instance'));
    91             $this->use_site_currency = 'no' === sanitize_text_field($this->get_option('use_site_currency'));
     93            $this->use_site_currency = 'yes' === sanitize_text_field($this->get_option('use_site_currency'));
     94            $this->links_login_required = 'yes' === sanitize_text_field($this->get_option('links_login_required'));
     95            $this->custom_id_1 = sanitize_text_field($this->get_option('custom_id_1'));
     96            $this->custom_id_2 = 'yes' === sanitize_text_field($this->get_option('custom_id_2'));
    9297            $this->header_token = $this->mpay_local_generate_string();
    9398
     
    115120                </div>";
    116121
     122   
    117123            // Agrega el div y el input adicional sin pasar por filtros de seguridad
    118124            echo '<div id="metrepayselector"></div>';
     
    122128        public function init_form_fields()
    123129        {
     130
    124131            $this->form_fields = array(
    125132                'enabled' => array(
     
    171178                    'title'       => 'Débito automático',
    172179                    'label'       => 'Permitir pagos en cuotas por débitos automáticos',
    173                     'description' => 'Solamente aplica cuando el carrito tiene 1 producto con atributo "cuotas"',
     180                    'description' => 'Aplica cuando el carrito tiene solamente 1 producto con atributo "cuotas" y valor numérico en el mismo. Si se activa, los links de pago tienen login requerido.',
     181                    'type'        => 'checkbox',
     182                    'default'     => 'no'
     183                ),
     184                'links_login_required' => array(
     185                    'title'       => 'Links de pago con login requerido',
     186                    'label'       => 'Requerir login en links de pago generados en MetrePay',
     187                    'description' => 'Aplica si el comercio tiene la funcionalidad configurada en la instancia MetrePay asignada. Si se desactiva, no pueden utilizarse los débitos automáticos (suscripciones).',
    174188                    'type'        => 'checkbox',
    175189                    'default'     => 'yes'
    176190                ),
     191                'custom_id_1' => array(
     192                    'title'       => 'Identificador personalizado #1',
     193                    'type'        => 'text',
     194                    'description' => 'Por cada link de pago generado, se incluye un valor como identificador personalizado. Si esta casilla está vacía, solicitará al usuario su CI/RUC durante el checkout. Si incluye un valor (texto o número) en esta casilla, se utilizará este valor como identificador personalizado constante en todos los links de pago; el usuario ya no tendrá que cargar CI/RUC. Si se tiene configurado "login no requerido", el usuario sí tednrá que cargar su número de documento (CI/RUC). Recuerde configurar el ID Personalizado con su contacto comercial en la plataforma MetrePay.',
     195                    'default'     => ''
     196                ),
     197                'custom_id_2' => array(
     198                    'title'       => 'Identificador personalizado #2',
     199                    'label'       => 'Enviar el número de orden (Order ID) como identificador personalizado adicional',
     200                    'type'        => 'checkbox',
     201                    'description' => 'Si se activa, cada link de pago generado incluirá el número de orden como identificador personalizado adicional. Si se desactiva, el número de orden no será utilizado. Recuerde configurar el ID Personalizado adicional con su contacto comercial en la plataforma MetrePay.',
     202                    'default'     => 'no'
     203                ),
    177204            );
    178205        }
     
    191218        {
    192219            return $this->provider_slug;
    193         }
    194 
    195         public function get_active_da()
    196         {
    197             return $this->active_da;
    198220        }
    199221       
     
    208230        }
    209231
    210         // Conect to the services
     232        public function get_active_da()
     233        {
     234            return $this->active_da;
     235        }
     236
     237        public function get_links_login_required()
     238        {
     239            return $this->links_login_required;
     240        }
     241       
     242        public function get_custom_id_1()
     243        {
     244            return $this->custom_id_1;
     245        }
     246       
     247        public function get_custom_id_2()
     248        {
     249            return $this->custom_id_2;
     250        }
     251       
     252        public function has_custom_id_1()
     253        {
     254            return !empty(trim($this->custom_id_1));
     255        }
     256
     257        // Connect to the services
    211258        public function process_payment($order_id)
    212259        {
     
    234281                    "dayOfMonth" => 1,
    235282                    "monthForSecondInstallment" => 1,
    236                     "payWaitHours" => 96,
    237283                );
    238284            }
    239285
    240286            // Establece los campos adicionales para el link de pago
     287            $data['payWaitHours'] = 96;
    241288            $data['label'] = "Pago a " . get_bloginfo("name");
    242289            $data['amount'] = intval($order->get_total());
    243290            $data['handleValue'] = $order->get_billing_email();
    244291            $data['handleLabel'] = "{$order->get_billing_first_name()} {$order->get_billing_last_name()}";
    245             $data['customIdentifier'] = get_post_meta($order->get_id(), 'CIRUC', true);
     292           
     293            // Sobre customs IDs y números de documentos
     294            $docNumber = get_post_meta($order->get_id(), 'CIRUC', true);
     295           
     296            if (!empty($docNumber)) {
     297                $data['documentNumber'] = $docNumber;
     298            }
     299
     300            // Solo si posee algún valor fijo contigurado como custom ID 1
     301            if ($this->has_custom_id_1()) {
     302                $data['customIdentifier'] = $this->get_custom_id_1();
     303            } else {
     304                $data['customIdentifier'] = $docNumber;
     305            }
     306
     307            // Como custom ID 2, va el número de orden, solo si lo tiene activo
     308            if ($this->get_custom_id_2()) {
     309                $data['customIdentifier2'] = $order_id;
     310            }
     311
     312            if ($this->get_active_da()) {
     313                $data['noLoginRequired'] = false;
     314            } else if (!$this->get_links_login_required()) {
     315                $data['noLoginRequired'] = true;
     316            }
    246317
    247318            // Obtiene URL a página de pago de MP en el sitio ecommerce
     319            // Crea la URL de redireccionamiento para cuando el pago se finalice en MP
    248320            $query = new WP_Query( array( 'pagename' => 'pago-metrepay' ) );
    249321            $redirectUrl = get_permalink($query->get_queried_object());
     
    251323            $data['redirectUrl'] = $redirectUrl;
    252324
    253             // Según el parámetro del comercio, si quiere o no utilizar la moneda configurada
     325            // Según configuración, si quiere o no utilizar la moneda configurada
    254326            if ($this->get_use_site_currency() == 'yes') {
    255327                $data['currency'] = get_woocommerce_currency();
    256328            }
    257329
    258             $response = $this->mpay_local_data_post($data);
    259             $result = json_decode($response, true);
    260 
    261             error_log(json_encode($data));
    262             error_log(json_encode($result));
    263 
    264             // Delete the cookie
    265             $this->mpay_local_delete_cookie('mp_installments_quantity');
    266 
    267             return array(
    268                 'result' => 'success',
    269                 'redirect' => $result['publicPayUrl']
    270             );
     330
     331            try {
     332                $response = $this->mpay_local_data_post($data);
     333                $result = json_decode($response, true);
     334
     335                error_log(json_encode($data));
     336                error_log(json_encode($result));
     337
     338                // Delete the cookie
     339                $this->mpay_local_delete_cookie('mp_installments_quantity');
     340
     341                return array(
     342                    'result' => 'success',
     343                    'redirect' => $result['publicPayUrl']
     344                );
     345            } catch (\Throwable $th) {
     346                $this->mpay_local_show_error_to_user($th);
     347                $this->logger->log('error', 'Error al procesar el pago', $this->context);
     348            }
    271349        }
    272350
     
    284362            // Quantity of installments = numero de cuotas
    285363            $installments_quantity = null;
    286             // If DA is active or not
    287             $active_da = $this->get_active_da() == 'yes';
    288364
    289365            if (!isset(WC()->cart)) {
     
    293369            $cart = WC()->cart->get_cart();
    294370            // For DA just 1 item is allowed
    295             if (count($cart) == 1 && $active_da) {
     371            if (count($cart) == 1 && $this->get_active_da()) {
    296372                foreach ( $cart as $cart_item_key => $cart_item ) {
    297373                    $product = $cart_item['data'];
     
    343419        }
    344420
    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');
     421        function mpay_local_show_error_to_user($data = null) {
     422            wc_add_notice(__('El método de pago MetrePay debe ser revisado. Por favor, contacte al administrador'), 'error', $data);
    347423        }
    348424
     
    372448
    373449        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             }
     450            $url = $this->mpay_local_get_mp_url();
     451            error_log(json_encode($url));
     452            error_log('MP API REQ BODY: ' . json_encode($data));
     453
     454            $args = array(
     455                'method'      => 'POST',
     456                'body'        => json_encode($data),
     457                'timeout'     => '5',
     458                'httpversion' => '1.0',
     459                'blocking'    => true,
     460                'headers'     => array(
     461                    'Content-Type' => 'application/json',
     462                    'Api-Token'    => $this->get_auth_token()
     463                ),
     464            );
     465            $response = wp_remote_post($url, $args);
     466
     467            if (is_wp_error($response)) {
     468                error_log('Error: ' . $response->get_error_message());
     469                throw new Exception("Error Processing Request", 1);
     470            }
     471
     472            // Verifica el código de estado de la respuesta
     473            $http_code = wp_remote_retrieve_response_code($response);
     474
     475            if ($http_code >= 400) {
     476                error_log("HTTP Error Code: $http_code");
     477                error_log("Error message from server: " . wp_remote_retrieve_body($response));
     478                throw new Exception("HTTP request failed with code $http_code", $http_code);
     479            }
     480
     481            return wp_remote_retrieve_body($response);
    396482        }
    397483
     
    407493        }
    408494    }
     495
    409496}
    410497
  • metrepay/trunk/readme.txt

    r3176106 r3183746  
    44Requires at least: 5.3
    55Tested up to: 6.6.2
    6 Stable tag: 1.3.0
     6Stable tag: 1.4.0
    77Requires PHP: 7.3.5
    88License: GPLv3
     
    2020
    2121= 1.0.0 =
    22 * First version with unique and recurrent payment support.
     22* Initial release with support for unique and recurring payments.
    2323
    2424= 1.1.0 =
    25 * Add specific logic to configuration form field related to activation of recurrent payments.
    26 * In order to the value of this parameter, products must have specific field "cuotas" to use recurrent payments.
     25* Added specific logic to the setting form field related to activating recurring payments. For this parameter to be effective, products must include the "cuotas" field to enable recurring payments.
    2726
    2827= 1.1.1 =
    29 * Fix texts related to payment process.
     28* Fixed text issues related to the payment process.
    3029
    3130= 1.1.2 =
    32 * Improve texts into configuration form fields.
     31* Improved text in setting form fields.
    3332
    3433= 1.2.0 =
    35 * Remove use of iframe to process payment.
    36 * Update correctly the order status to "completed".
     34* Removed use of iframe for payment processing.
     35* Correctly updated the order status to "completed."
    3736
    3837= 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.
     38* Added a setting parameter to select the preferred MetrePay instance.
     39* Added a parameter to enable or disable the use of the configured site currency.
     40* Removed the "staging" setting parameter.
     41* Fixed URL generation to consider site permalinks for the "pago-metrepay" pos-checkout page.
     42* Fixed checkout box options to display "Single payment" or "Recurring payment."
     43* Optimized API request body generation.
     44
     45= 1.4.0 =
     46* Added a setting form field to manage login requirements for generated payment links.
     47* Added a setting form field to set a constant value for the custom identifier (#1) in payment links.
     48* Added a setting form field to enable sending the Order ID as an additional custom identifier (#2) in payment links.
     49* Fixed logic to require the client document number at checkout when either login is not required or the custom identifier (#1) is empty.
Note: See TracChangeset for help on using the changeset viewer.