Plugin Directory

Changeset 3139956


Ignore:
Timestamp:
08/22/2024 07:52:32 PM (17 months ago)
Author:
taylor1991
Message:

Significant change, direct payment on the Place Order button, instead of within our own iframe

Location:
woo-xchange-payments/trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • woo-xchange-payments/trunk/XChange.js

    r3132372 r3139956  
    11/****************************************************************
    22 * @author      : Jekferson Diaz
    3  * @name        : Quikly Pay
    4  * @description  : Objeto de Dominio Quikly Pay
    5  * @copyright (c)  QUIKLY GROUP LTD
     3 * @name        : XChange
     4 * @description  : Objeto de Dominio XChange
     5 * @copyright (c)  Xchange
    66 *****************************************************************/
    7 XChange = (function() {
     7XChange = (function () {
    88    'use strict';
    99    /****************************************************************
     
    1111     *****************************************************************/
    1212    var $data = {};
    13     var $onAuthorize = function(response) {
     13    var $onAuthorize = function (response) {
    1414        //Custom Ajax function to process Payment via WC-AJAX
    1515        console.log(response);
     
    1818            type: "POST",
    1919            data: jQuery(".woocommerce-checkout").serialize(),
    20             success: function(respuesta) {
     20            success: function (respuesta) {
    2121                if (respuesta.result == "failure") {
    2222                    jQuery(".woocommerce-message").remove();
     
    2626                }
    2727            },
    28             error: function() {
     28            error: function () {
    2929                console.log("No se ha podido obtener la información");
    3030            }
     
    4040         * @description: Método de inicialización
    4141         */
    42         init = function(data) {
     42        init = function (data) {
    4343            try {
    44            
     44
    4545                $data = data;
    4646                console.log("data recibe", $data);
     
    6161         * @description: Método de inicialización
    6262         */
    63         Reload = function(data) {
     63        Reload = function (data) {
    6464            try {
    6565
     
    6969                console.warn(ex);
    7070            }
    71         };
     71        },
     72
     73       
    7274
    7375    return {
  • woo-xchange-payments/trunk/helpers.php

    r3132372 r3139956  
    55// Grab Admin and Payment Data for Xchange Gateway
    66
    7 function xchange_data_script() {
     7function xchange_data_script()
     8{
    89    if (!wp_script_is('jquery', 'done')) {
    9         wp_enqueue_script( 'jquery' );
    10     }
    11     wp_enqueue_script( 'xchange_paybox_script_index', "https://paybox.quikly.app/paybox/index_Wordpress.js", array("jquery"), '1.0', false );
    12     wp_enqueue_script( 'xchange_paybox_script', plugins_url() . "/woo-xchange-payments/XChange.js", array("jquery", "xchange_paybox_script_index"), '1.0', false );
     10        wp_enqueue_script('jquery');
     11    }
     12    //wp_enqueue_script('xchange_paybox_script_index', "https://paybox.quikly.app/paybox/transactionConfirm/transactionmain.js", array("jquery"), '1.0', false);
     13    wp_enqueue_script('xchange_paybox_script', plugins_url() . "/woo-xchange-payments/XChange.js", array("jquery", "xchange_paybox_script_index"), '1.0', false);
    1314
    1415    // x   
    1516
     17    // Asegúrate de que el dominio sea correcto
     18    // $domain = $_SERVER['HTTP_HOST']; // Usa el dominio actual
     19
     20    // // Establecer una cookie con SameSite=None para navegadores que requieren cookies de terceros
     21    // setcookie('mi_cookie', 'valor', [
     22    //  'expires' => time() + 3600,  // 1 hora
     23    //  'path' => '/',
     24    //  'domain' => $domain,
     25    //  'secure' => true,            // Requiere HTTPS
     26    //  'httponly' => true,
     27    //  'samesite' => 'None'         // Para cookies de terceros
     28    // ]);
     29
     30    // $data_to_pass = array(
     31    //  'order_id' => WC()->session->get('current_order_id')
     32    // );
     33
     34    // Pasa los datos al script
     35    //wp_localize_script('xchange_paybox_script', 'payboxData', $data_to_pass);
     36
     37    // Cargar el CSS de Rebilly
     38    wp_enqueue_style('rebilly_framepay_css', 'https://framepay.rebilly.com/rebilly.css');
     39
     40    // Cargar el script de Rebilly
     41    wp_enqueue_script('rebilly_framepay_js', 'https://framepay.rebilly.com/rebilly.js', array('jquery'), null, true);
     42
     43
    1644    $data_to_pass = array(
    17         'order_id' => WC()->session->get('current_order_id')
    18     );
     45        'order_id' => WC()->session->get('current_order_id')
     46    );
    1947
    20     // Pasa los datos al script
    21     wp_localize_script('xchange_paybox_script', 'payboxData', $data_to_pass);
     48    // Pasa los datos al script
     49    wp_localize_script('xchange_paybox_script', 'payboxData', $data_to_pass);
     50
    2251}
    2352
    24 function xchange_object_script_shipping() {
    25    
     53
     54
     55
     56
     57
     58function xchange_object_script_shipping()
     59{
     60
    2661    global $woocommerce;
    2762
    2863    if (!wp_script_is('jquery', 'done')) {
    29         wp_enqueue_script( 'jquery' );
     64        wp_enqueue_script('jquery');
    3065    }
    31     ?> 
    32    
    33         <script type="text/javascript">
     66    ?>
     67
     68    <script type="text/javascript">
     69
     70        var payboxAmount = "<?php echo number_format($woocommerce->cart->total, 2); ?>",
     71        console.log("payboxAmount", payboxAmount);
    3472       
    35             var data = {           
    36                 PayboxAmount: "<?php echo number_format($woocommerce->cart->total, 2); ?>",
    37             };
    3873
    39             XChange.Reload(data);
    40         </script>
     74        //XChange.Reload(data);
     75    </script>
    4176    <?php
    4277}
    4378
    4479
    45 function xchange_object_script () {
    46    
     80function xchange_object_script()
     81{
     82
    4783    global $woocommerce;
    4884    // Get product data, in this case product names
    4985    $items = $woocommerce->cart->get_cart();
    50     $product_names = array();
    51    
    52     foreach($items as $item => $values) {
    53       $_product = $values['data']->post;
    54       $product_names[] = $_product->post_title;
    55     }   // End Product Names
     86    $product_names = array();
     87
     88    foreach ($items as $item => $values) {
     89        $_product = $values['data']->post;
     90        $product_names[] = $_product->post_title;
     91    }   // End Product Names
    5692
    5793    //To get Xchange user email
    58     $adb_xchange_settings = get_option( 'woocommerce_xchange_settings' );
     94    $adb_xchange_settings = get_option('woocommerce_xchange_settings');
    5995    $adb_xchange_usermail = $adb_xchange_settings['adb_username_email'];
    6096    $adb_xchange_username = $adb_xchange_settings['adb_username'];
     
    71107    $description = "";
    72108
    73     for($x = 0; $x < $arrlength; $x++) {
    74        
    75         $description .= $product_names[$x]; 
     109    for ($x = 0; $x < $arrlength; $x++) {
     110
     111        $description .= $product_names[$x];
    76112
    77113        if (($x + 1) < $arrlength) {
     
    93129
    94130    $paybox_production = false;
    95        
    96     if ($adb_xchange_sandbox_state !== "yes") { 
    97         $paybox_production = true; 
     131
     132    if ($adb_xchange_sandbox_state !== "yes") {
     133        $paybox_production = true;
    98134    }
    99135
    100136    if (!wp_script_is('jquery', 'done')) {
    101         wp_enqueue_script( 'jquery' );
    102     }
     137        wp_enqueue_script('jquery');
     138    }
    103139
    104        
     140
    105141    ?>
    106         <script type="text/javascript">
    107             var data = {           
    108                 PayboxRemail: "<?php echo $adb_xchange_usermail; ?>",
    109                 PayboxSendmail: "<?php echo $adb_xchange_customer_email; ?>",
    110                 PayboxRename: "<?php echo $adb_xchange_username; ?>",
    111                 PayboxSendname: "<?php echo $adb_xchange_customer_firstname; ?>" + "," + "<?php echo $adb_xchange_customer_lastname; ?>",
    112                 PayboxAmount: "<?php echo number_format($woocommerce->cart->total, 2); ?>",
    113                 PayboxDescription: "<?php echo $description; ?>",
    114                 PayboxProduction: "<?php echo $paybox_production ?>",
    115                 PayboxRequired: [
    116                     <?php echo $adb_validation_fields_lista; ?>
    117                 ],
    118                 OrderKey: "<?php echo $order_key; ?>"
    119             }
    120             XChange.init(data);
    121         </script>       
     142    <script type="text/javascript">
     143        var data = {
     144            PayboxRemail: "<?php echo $adb_xchange_usermail; ?>",
     145            PayboxSendmail: "<?php echo $adb_xchange_customer_email; ?>",
     146            PayboxRename: "<?php echo $adb_xchange_username; ?>",
     147            PayboxSendname: "<?php echo $adb_xchange_customer_firstname; ?>" + "," + "<?php echo $adb_xchange_customer_lastname; ?>",
     148            PayboxAmount: "<?php echo number_format($woocommerce->cart->total, 2); ?>",
     149            PayboxDescription: "<?php echo $description; ?>",
     150            PayboxProduction: "<?php echo $paybox_production ?>",
     151            PayboxRequired: [
     152                <?php echo $adb_validation_fields_lista; ?>
     153            ],
     154        }
     155        //XChange.init(data);
     156    </script>
    122157    <?php
    123158}
    124159
    125 add_action( 'wp_enqueue_scripts', 'xchange_data_script' );
    126 add_action( 'wp_head', 'xchange_object_script' );
    127 add_action( 'woocommerce_after_shipping_rate', 'xchange_object_script_shipping' );
     160
     161
     162add_action('wp_enqueue_scripts', 'xchange_data_script');
     163add_action('wp_head', 'xchange_object_script');
     164add_action('woocommerce_after_shipping_rate', 'xchange_object_script_shipping');
  • woo-xchange-payments/trunk/readme.txt

    r3132372 r3139956  
    55Requires PHP: 5.6
    66Requires at least: 5.8
    7 Tested up to: 6.6.1
     7Tested up to: 5.8
    88Stable tag: 2.3.4
    9 Plugin URI: https://quiklypay.com/web/developer
    10 Version: 3.0
     9Plugin URI: https://pay.quikly.app/web/developer
     10Version: 2.0.1
    1111License: GPL2
    1212License URI: http://www.gnu.org/licenses/gpl-2.0.html
     
    1515 == Description ==
    1616
    17 This plugin integrates Woocommerce with Quikly Payment Facilitator button, which you can use as a Payment gateway for all major credit and debit cards. Quikly has its headquarters in London, United Kingdom and is expanding its services in Latin America. It has the lowest fees in the Latin America market, for more information you can ckeckout the official website. https://quiklypay.com
     17This plugin integrates Woocommerce with Quikly Payment Facilitator button, which you can use as a Payment gateway for all major credit cards and even Paypal accounts. Quikly has its headquarters in London, United Kingdom and is expanding its services in Latin America. It has the lowest fees in the Latin America market, for more information you can ckeckout the official website. https://pay.quikly.app
    1818
    1919 = Minimum Requirements =
     
    3333==  Plugin Configuration ==
    3434
    35 Once installed, go to Woocommerce -> Settings Pick Checkout Tab and once on that tab go to Payment gateways and click on Quikly Pay, once on Quikly Pay, click on Enable Quikly Pay, and put your Quikly Pay account data. Also, we put the default wordpress, checkout requirred fields as mandatory before the Quikly Modal pop ups like, #billing_email" if you add your custom requirred fields, please add them on the Form Validation Fields area in Quikly tab, on this format: Ex: #billing_email", "#my_custom_field", "#my_custom_field2" always use the #id css format. If requirred fields are not filled then Quikly Pay Modal is not going to PopUp. So check this detail before implementing.
     35Once installed, go to Woocommerce -> Settings Pick Checkout Tab and once on that tab go to Payment gateways and click on Quikly, once on Quikly, click on Enable Quikly, and put your Quikly account data. Also, we put the default wordpress, checkout requirred fields as mandatory before the Quikly Modal pop ups like, #billing_email" if you add your custom requirred fields, please add them on the Form Validation Fields area in Quikly tab, on this format: Ex: #billing_email", "#my_custom_field", "#my_custom_field2" always use the #id css format. If requirred fields are not filled then Quikly Modal is not going to PopUp. So check this detail before implementing.
    3636
    3737==  Security Tips ==
    3838
    39 Before using Quikly Pay, enable the sandbox option, to test the gateway. Only the paranoid survive as Andy Grove, CEO of Intel once said. So test before implementing, here is some sandbox credit card numbers and data to test, https://quiklypay.com/web/developer Once you see that the order has been marked on the checkout page as processed (not really its, sandbox), disable sandbox.  By the way, on sandbox, for security reasons, payments and are not processed in Quikly and the order is not recorded in woocommerce. If you wish to test, that order processing please contact us to guide you on how to do that on the code. For security reasons, sandbox testing is limited.
     39Before using Quikly, enable the sandbox option, to test the gateway. Only the paranoid survive as Andy Grove, CEO of Intel once said. So test before implementing, here is some sandbox credit card numbers and data to test, https://pay.quikly.app/web/developer Once you see that the order has been marked on the checkout page as processed (not really its, sandbox), disable sandbox.  By the way, on sandbox, for security reasons, payments and are not processed in Quikly and the order is not recorded in woocommerce. If you wish to test, that order processing please contact us to guide you on how to do that on the code. For security reasons, sandbox testing is limited.
    4040Also remember once the plugin is deleted all Quikly data will be erased.
    4141
     
    8080* New: Production plugin for new version
    8181
    82 = 3.0 = Released on Aug 8, 2024
    83 
    84 * New: Fixed the error when making the payment in the checkout section
    85 
    8682== Screenshots ==
    8783
     
    90863. The settings of plugin
    9187
     88
    9289==  More information ==
    9390
    94 For more information or doubts contact at https://quiklypay.com/web/developer, [email protected]
     91For more information or doubts contact at https://pay.quikly.app, [email protected]
    9592
    9693
  • woo-xchange-payments/trunk/xchange.php

    r3132372 r3139956  
    22/*
    33 * Plugin Name: WooCommerce Quikly Payments
    4  * Plugin URI: https://quiklypay.com/developer
     4 * Plugin URI: https://pay.quikly.app/developer
    55 * Description: Sell in your ecommerce with any credit / debit card through our plugin.
    66
    77 * Version: 2
    8  * Author: QUIKLY GROUP LTD
    9  * Author URI: https://quiklypay.com
     8 * Author: QUIKLY GROUP UK LTD
     9 * Author URI: https://pay.quikly.app
    1010 * License: GPL2
    1111 */
     
    3434 * This action hook registers our PHP class as a WooCommerce payment gateway
    3535 */
     36
     37
     38
    3639
    3740function xchange_add_message_listener_script()
     
    4851
    4952            // Manejar el mensaje de éxito
    50             //console.log("eventoooooo", event);
    5153            if (event.data.status === 'success') {
    52                 console.log('Pago exitoso recibido en WordPress:', event.data.paymentIntent);
    53                 console.log('Orden Id', event.data.orderId)
     54                console.log('Pago exitoso recibido en WordPress:', event);
    5455
    5556                // Llama a una función de PHP para procesar el pago exitoso
     
    5960                    data: {
    6061                        action: 'procesar_pago_exitoso',
    61                         paymentIntent: event.data.paymentIntent,
    62                         orderId: event.data.orderId // Supongamos que el orderId viene en event.data
    6362                    },
    6463                    success: function (response) {
     
    6766                    }
    6867                });
    69             } else {
     68            } else if (event.data.status === 'false') {
    7069                jQuery.ajax({
    7170                    url: "<?php echo admin_url('admin-ajax.php'); ?>",
     
    7372                    data: {
    7473                        action: 'procesar_pago_fallido',
    75                         paymentIntent: event.data.paymentIntent,
    76                         orderId: event.data.orderId // Supongamos que el orderId viene en event.data
    7774                    },
    7875                    success: function (response) {
     
    9188function procesar_pago_exitoso()
    9289{ // Elimina $order_id aquí
    93     if (isset($_POST['paymentIntent']) && isset($_POST['orderId'])) {
    94         // Obtén los datos de la transacción
    95         $paymentIntent = $_POST['paymentIntent'];
    96         $order_id = intval($_POST['orderId']); // Asegúrate de que el ID sea un número entero
    97 
    98         // Obtener la orden
    99         $order = wc_get_order($order_id);
    100 
    101         if ($order) {
    102             // Actualiza el estado del pedido a "procesando" o cualquier otro estado deseado
    103             $order->update_status('processing', __('Payment received, awaiting fulfillment', 'woocommerce'));
    104 
    105             // Reduce el inventario de productos
    106             wc_reduce_stock_levels($order_id);
    107 
    108             // Vacía el carrito
    109             WC()->cart->empty_cart();
    110 
    111             // Envía una respuesta JSON
    112             // Obtiene la URL de retorno
    113             $redirect_url = $order->get_checkout_order_received_url();
    114 
    115             // Envía una respuesta JSON
    116             wp_send_json_success(
    117                 array(
    118                     'message' => 'Pago procesado correctamente.',
    119                     'paymentIntent' => $paymentIntent,
    120                     'orderId' => $order_id,
    121                     'redirect' => $redirect_url  // Incluye la URL de redirección
    122                 )
    123             );
    124 
    125             // Retorna el resultado y redirige a la página de agradecimiento
    126             return array(
    127                 'result' => 'success',
    128                 'redirect' => get_return_url($order)
    129             );
    130         } else {
    131             wp_send_json_error('No se encontró la orden.');
    132         }
     90
     91    // Obtén los datos de la transacción
     92    $order_id = WC()->session->get('current_order_id');
     93
     94    // Obtener la orden
     95    $order = wc_get_order($order_id);
     96
     97    if ($order) {
     98        // Actualiza el estado del pedido a "procesando" o cualquier otro estado deseado
     99        $order->update_status('completed', __('Payment received, order completed', 'woocommerce'));
     100
     101        // Reduce el inventario de productos
     102        wc_reduce_stock_levels($order_id);
     103
     104        // Vacía el carrito
     105        WC()->cart->empty_cart();
     106
     107        // Envía una respuesta JSON
     108        // Obtiene la URL de retorno
     109        $redirect_url = $order->get_checkout_order_received_url();
     110
     111        // Envía una respuesta JSON
     112        wp_send_json_success(
     113            array(
     114                'message' => 'Pago procesado correctamente.',
     115                'orderId' => $order_id,
     116                'redirect' => $redirect_url  // Incluye la URL de redirección
     117            )
     118        );
     119
     120        // Retorna el resultado y redirige a la página de agradecimiento
     121        return array(
     122            'result' => 'success',
     123            'redirect' => get_return_url($order)
     124        );
    133125    } else {
    134         wp_send_json_error('Datos de transacción no recibidos.');
     126        wp_send_json_error('No se encontró la orden.');
    135127    }
    136128    wp_die();
     
    142134function procesar_pago_fallido()
    143135{
    144     if (isset($_POST['paymentIntent']) && isset($_POST['orderId'])) {
    145         // Obtén los datos de la transacción
    146         $paymentIntent = $_POST['paymentIntent'];
    147         $order_id = intval($_POST['orderId']); // Asegúrate de que el ID sea un número entero
    148 
    149         // Obtener la orden
    150         $order = wc_get_order($order_id);
    151 
    152         if ($order) {
    153             // Actualiza el estado del pedido a "failed"
    154             $order->update_status('failed', __('Payment failed, order canceled', 'woocommerce'));
    155 
    156             // Envía una respuesta JSON
    157             wp_send_json_success(
    158                 array(
    159                     'message' => 'Pago fallido, estado de la orden actualizado.',
    160                     'paymentIntent' => $paymentIntent,
    161                     'orderId' => $order_id // Incluye el orderId en la respuesta
    162                 )
    163             );
    164 
    165             // Retorna el resultado y redirige a la página de agradecimiento
    166             return array(
    167                 'result' => 'success',
    168                 'redirect' => get_return_url($order)
    169             );
    170         } else {
    171             wp_send_json_error('No se encontró la orden.');
    172         }
     136
     137    // Obtén los datos de la transacción
     138
     139    $order_id = WC()->session->get('current_order_id');
     140
     141    // Obtener la orden
     142    $order = wc_get_order($order_id);
     143
     144    // Obtener la orden
     145    $order = wc_get_order($order_id);
     146
     147    if ($order) {
     148        // Actualiza el estado del pedido a "failed"
     149        $order->update_status('failed', __('Payment failed, order canceled', 'woocommerce'));
     150
     151        // Envía una respuesta JSON
     152        wp_send_json_success(
     153            array(
     154                'message' => 'Pago fallido, estado de la orden actualizado.',
     155                'orderId' => $order_id // Incluye el orderId en la respuesta
     156            )
     157        );
     158
     159        // Retorna el resultado y redirige a la página de agradecimiento
     160        return array(
     161            'result' => 'success',
     162            'redirect' => get_return_url($order)
     163        );
    173164    } else {
    174         wp_send_json_error('Datos de transacción no recibidos.');
     165        wp_send_json_error('No se encontró la orden.');
    175166    }
     167
    176168    wp_die();
    177169}
    178170add_action('wp_ajax_procesar_pago_fallido', 'procesar_pago_fallido');
    179171add_action('wp_ajax_nopriv_procesar_pago_fallido', 'procesar_pago_fallido');
     172
     173
    180174
    181175
     
    211205            $this->supports = array('default_credit_card_form');
    212206            $this->method_title = 'Quikly Pay';
    213             $this->method_description = 'Accept credit/debit card payments in your store, sign up now and start accepting payments in just 5 minutes'; // will be displayed on the options page
     207            $this->method_description = 'Quikly pay is a method for pay'; // will be displayed on the options page
    214208            //$this->method_adb_username_email = 'XChange Username';
    215209
     
    251245            // Turn these settings into variables we can use
    252246            /*foreach ( $this->settings as $setting_key => $value ) {
    253                                                                               $this->$setting_key = $value;
    254                                                                           }*/
     247                                                                                                                                                                                                                                                                                                                                                            $this->$setting_key = $value;
     248                                                                                                                                                                                                                                                                                                                                                        }*/
    255249            ///End
    256250
     
    345339                'enabled' => array(
    346340                    'title' => 'Enable/Disable',
    347                     'label' => 'Enable Quikly Pay',
     341                    'label' => 'Enable Quikly pay',
    348342                    'type' => 'checkbox',
    349343                    'description' => '',
     
    352346
    353347                'sandbox' => array(
    354                     'title' => 'Quikly Pay Sandbox',
     348                    'title' => 'Quikly pay Sandbox',
    355349                    'label' => 'Enable SandBox',
    356350                    'type' => 'checkbox',
    357                     'description' => 'Quikly Pay sandbox can be used to test payments. Recommended before using it in production environment.',
     351                    'description' => 'Quikly pay sandbox can be used to test payments. Recommended before using it in production environment.',
    358352                    'default' => 'yes'
    359353                ),
     
    370364                    'type' => 'textarea',
    371365                    'description' => 'This controls the description which the user sees during checkout.',
    372                     'default' => 'Buy with credit/debit card in the safest way online.',
     366                    'default' => 'Buy with your credit card with our payment method.',
    373367                ),
    374368
     
    376370                    'title' => 'User Email',
    377371                    'type' => 'text',
    378                     'description' => 'Your Quikly Pay Email',
     372                    'description' => 'Your Quikly pay Email',
    379373                ),
    380374
     
    382376                    'title' => 'Username',
    383377                    'type' => 'text',
    384                     'description' => 'Your Quikly Pay Username'
     378                    'description' => 'Your Quikly pay Username'
    385379
    386380                ),
     
    442436
    443437            if ($order) {
    444                 // Actualiza el estado del pedido a "procesando" o cualquier otro estado deseado
    445                 //$order->update_status('processing', __('Payment received, awaiting fulfillment', 'woocommerce'));
    446 
    447                 // Reduce el inventario de productos
    448                 //wc_reduce_stock_levels($order_id);
    449 
    450                 // Vacía el carrito
    451                 //WC()->cart->empty_cart();
    452 
    453                 // Retorna el resultado y redirige a la página de agradecimiento
    454                 // return array(
    455                 //  'result' => 'success',
    456                 //  'redirect' => $this->get_return_url($order)
    457                 // );
    458                 $order->update_status('on-hold', __('Esperando pago', 'woocommerce'));
     438
     439
    459440                WC()->session->set('current_order_id', $order_id);
    460441
    461                 $order_key = $order->get_order_key();
    462 
    463                 // Retorna el order_id y order_key
    464                 wp_send_json_success(
    465                     array(
    466                         'order_id' => $order_id,
    467                         'order_key' => $order_key
    468                     )
     442                // Guarda el order_key en la sesión
     443                // $order_key = $order->get_order_key();
     444                // WC()->session->set('current_order_key', $order_key);
     445
     446                // No hacer más acciones después de enviar la respuesta JSON
     447
     448                //wc_add_notice(__('Pago ha sido procesado exitosamente !', 'woothemes'), 'success');
     449
     450                return array(
     451                    'result' => 'success'
    469452                );
    470453
    471                 WC()->session->set('current_order_id', $order_id);
    472 
    473                 // Guarda el order_key en la sesión
    474                 $order_key = $order->get_order_key();
    475                 WC()->session->set('current_order_key', $order_key);
    476 
    477                 // No hacer más acciones después de enviar la respuesta JSON
    478 
    479                 //wc_add_notice(__('Pago ha sido procesado exitosamente !', 'woothemes'), 'success');
    480                 return;
     454                wp_die();
    481455
    482456
     
    503477
    504478        // To add the Xchange Button on the Xchange payment box
     479
    505480        public function payment_fields()
    506481        {
    507 
    508             //Grab description data as this is erased when payment fields enabled
     482            global $woocommerce;
     483            $viewIframe = false;
     484
     485            // Obtén los datos de descripción desde las configuraciones
    509486            $adb_xchange_settings2 = get_option('woocommerce_xchange_settings');
    510487            $adb_xchange_description_admin_area = $adb_xchange_settings2['description'];
    511488
     489            // Inicia el formulario de tarjeta de crédito
    512490            do_action('woocommerce_credit_card_form_start');
    513             echo '<p>' . $adb_xchange_description_admin_area . '</p><br/><div id="ButtonPaybox"></div>';
     491
     492            // Muestra la descripción y el div ButtonPaybox
     493            echo '<p>' . $adb_xchange_description_admin_area . '
     494                <form id="payment-form">
     495                    <p id="card-error" role="alert" style="color: red !important; text-align: center;"></p>
     496                    <input class="name-input" id="cardname" data-rebilly="fullName" name="cardholdername" type="text"
     497                        placeholder="Nombre en la tarjeta" required />
     498                    <input class="email-input" id="cardemail" type="text" placeholder="Email" required />
     499                    <input class="id-input" id="cedula" type="text" placeholder="Cédula" required />
     500                    <div class="field">
     501                        <div style="height: 45px !important;" id="mounting-point"></div>
     502                        <p id="error"></p>
     503                    </div>
     504                   
     505                </form>';
     506
     507            // Agrega el div que contendrá el iframe
     508            echo '<div id="divIframe" style="display: none;"></div>';
     509
     510
     511            // Termina el formulario de tarjeta de crédito
    514512            do_action('woocommerce_credit_card_form_end');
    515513
    516         } // End Add custom button
     514
     515            // Inserta el código de inicialización de Rebilly aquí
     516            ?>
     517            <script type="text/javascript">
     518
     519
     520                function getPayment() {
     521
     522                }
     523
     524
     525                function generateUUID() {
     526                    let d = new Date().getTime();
     527                    if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
     528                        d += performance.now();
     529                    }
     530                    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
     531                        const r = (d + Math.random() * 16) % 16 | 0;
     532                        d = Math.floor(d / 16);
     533                        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
     534                    });
     535                }
     536
     537                var payboxAmount = "<?php echo number_format($woocommerce->cart->total, 2); ?>";
     538                console.log("amount", payboxAmount);
     539
     540                <?php
     541                $adb_xchange_settings = get_option('woocommerce_xchange_settings');
     542                $adb_xchange_usermail = $adb_xchange_settings['adb_username_email'];
     543                $adb_xchange_username = $adb_xchange_settings['adb_username'];
     544                ?>
     545
     546                var destinationEmail = "<?php echo $adb_xchange_usermail; ?>";
     547                var destinationName = "<?php echo $adb_xchange_username; ?>"
     548                console.log("Email destino:", destinationEmail);
     549                console.log("Nombre", destinationName)
     550
     551
     552                Rebilly.initialize({
     553                    publishableKey: 'pk_live_wuoLby1FyygWxxcjbR0i1D8GZ8UGHn1afNiW-tg',
     554                    icon: {
     555                        color: "#888da8",
     556                    },
     557                    style: {
     558                        base: {
     559                            fontSize: "16px",
     560                            boxShadow: "none",
     561                            color: "#888da8",
     562                            padding: "45px",
     563                            height: "45px",
     564                        },
     565                    },
     566                });
     567
     568                Rebilly.on("ready", function () {
     569                    var card = Rebilly.card.mount("#mounting-point");
     570                    card.on('change', function (data) {
     571                        document.getElementById('error').innerText = data.valid ? '' : data.error.message;
     572                        document.getElementById('error').style.color = data.valid ? '' : 'red';
     573                    });
     574                    $mountedFrames.push(card);
     575                    console.log("mounting", $mountedFrames);
     576                });
     577
     578
     579                var payWithCard = function (billingAddress, paymenToken, amount) {
     580                    var sendMail = document.getElementById("cardemail").value;
     581                    var transactionId = generateUUID();
     582                    var rename = billingAddress.firstName + " " + billingAddress.lastName;
     583                    console.log("transacion idGenerado", transactionId);
     584                    let urlCreateTransaction = "https://mdjc7112pd.execute-api.us-east-1.amazonaws.com/v1/xchange/dlocal/create-transaction";
     585
     586
     587                    jQuery.ajax({
     588                        type: "POST",
     589                        url: urlCreateTransaction,
     590                        dataType: "json",
     591                        data: {
     592                            idReference: transactionId,
     593                            address: billingAddress,
     594                            token: paymenToken,
     595                            amount: amount,
     596                            redirectUrl: `https://paybox.quikly.app/paybox/transactionConfirm/transaction.html?idReference=${transactionId}&wordpress=true`,
     597                            callbackUrl: "https://paybox.quikly.app/paybox/transactionConfirm/transaction.html",
     598                            destinationEmail: destinationEmail,
     599                            destinationName: destinationName,
     600                            senderEmail: sendMail,
     601                            senderName: rename,
     602                            method: "4",
     603                            exchangeRate: amount,
     604                        },
     605                        success: function (message, text, response) {
     606                            const { checkout_url, isSpecialClient } = response.responseJSON;
     607                            console.log("response.responseJSON", response.responseJSON);
     608
     609                            if (isSpecialClient) {
     610                                window.location.href = `https://paybox.quikly.app/paybox/transactionConfirm/transaction.html?isSpecialClient=${isSpecialClient}&idReference=${transactionId}`;
     611                            }
     612
     613                            if (checkout_url) {
     614                                console.log("checkout_url", checkout_url._links);
     615                                let approvalLink = checkout_url._links.find(function (link) {
     616                                    return link.rel === "approvalUrl";
     617                                });
     618
     619                                let redirect = checkout_url._links.find(function (link) {
     620                                    return link.rel === "redirectUrl";
     621                                });
     622
     623
     624                                var approvalUrl = approvalLink ? approvalLink.href : redirect.href;
     625                                if (approvalUrl) {
     626                                    // Ocultar el formulario de pago
     627                                    document.getElementById('payment-form').style.display = 'none';
     628
     629                                    // Mostrar el iframe
     630                                    var element = document.getElementById('divIframe');
     631                                    if (element) {
     632                                        element.style.display = 'block';
     633                                        element.innerHTML = '<iframe src="' + approvalUrl + '" width="100%" height="500px" frameborder="0"></iframe>';
     634                                    } else {
     635                                        console.error('El elemento no existe en el DOM');
     636                                    }
     637                                }
     638
     639                            }
     640                        },
     641                        error: function (jqXHR, textStatus, errorThrown) {
     642                            console.error("Error en la solicitud AJAX:", textStatus, errorThrown);
     643                            loading(false);
     644                        }
     645                    });
     646                };
     647            </script>
     648            <?php
     649
     650            echo "<script>
     651            jQuery(document).ready(function($) {
     652
     653                if (!window.hasPaymentScriptRun) {
     654                window.hasPaymentScriptRun = true;
     655                function handleSubmit(event) {
     656                    event.preventDefault();
     657                    console.log('El formulario ha sido enviado.');
     658
     659                    try {
     660                        const form = event.target;
     661                        Rebilly.createToken(form).then(function(result) {
     662                            var paymentToken = result.id;
     663                            var billingAddress = result.billingAddress;
     664
     665                             // Asignar valores personalizados a billingAddress
     666                            billingAddress.country = 'EC';  // Establecer el país
     667                            billingAddress.cedula = document.getElementById('cedula').value;  // Obtener el valor de Cédula
     668
     669                            var amount = payboxAmount;
     670
     671                            console.log('Token generado:', paymentToken);
     672                            console.log('Dirección de facturación:', billingAddress, amount);
     673
     674                            payWithCard(billingAddress,paymentToken,amount);
     675                        }).catch(function(error) {
     676                            console.log('Error al generar el token:', error);
     677                            document.getElementById('error').innerText = 'Error: ' + error.message;
     678                        });
     679                    } catch (error) {
     680                        console.log('Error en el manejo del submit:', error);
     681                    }
     682                }
     683
     684                    $('form.checkout').on('submit', function(event) {
     685                        setTimeout(function() {
     686                            if ($('ul.woocommerce-error').length > 0) {
     687                                console.log('Hay errores en el formulario, no se ejecutará el script.');
     688                                return; // Si hay errores, no ejecuta handleSubmit
     689                            } else {
     690                                $('div.woocommerce-error:contains(\"There was an error processing your order\")').hide();
     691                               
     692                                console.log('No hay errores, se procede a ejecutar handleSubmit.');
     693                                var paymentForm = document.getElementById('payment-form');
     694                                if (paymentForm) {
     695
     696                                setTimeout(function() {
     697                                    paymentForm.scrollIntoView({
     698                                        behavior: 'smooth',
     699                                        block: 'center'
     700                                    });
     701                                }, 3000);
     702                                handleSubmit(event);
     703                                   
     704                                } else {
     705                                    console.error('El elemento con ID  no se encontró.');
     706                                }
     707                               
     708                            }
     709                        }, 1000);
     710                    });
     711            }
     712               
     713        });
     714        </script>";
     715
     716        }
     717
     718
     719
     720        // End Add custom button
    517721    }  //End of Class WC_Xchange_Gateway extends WC_Payment_Gateway
    518722} // End of function xchange_init_gateway_class
Note: See TracChangeset for help on using the changeset viewer.