Advertisement
Guest User

webpay 2

a guest
Dec 24th, 2013
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 28.73 KB | None | 0 0
  1. <?php
  2. /*
  3.   Plugin Name: Woocommerce Webpay ( Chilean Payment Gateway )
  4.   Description: Sistema de pagos de WooCommerce con WebPay
  5.   Author: Cristian Tala Sánchez
  6.   Version: 2.3
  7.   Author URI: www.cristiantala.cl
  8.   Plugin URI: https://bitbucket.org/ctala/woocommerce-webpay/wiki/Home
  9.   This program is free software: you can redistribute it and/or modify
  10.   it under the terms of the GNU General Public License as published by
  11.   the Free Software Foundation, either version 3 of the License or any later version.
  12.  
  13.   This program is distributed in the hope that it will be useful,
  14.   but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.   GNU General Public License for more details.
  17.  
  18.   You should have received a copy of the GNU General Public License
  19.   along with this program.  If not, see <http://www.gnu.org/licenses/>.
  20.  */
  21.   include_once 'admin/webpay_install.php';
  22.   include_once 'admin/webpay_debug.php';
  23.  
  24. /*
  25.  * Este activation Hook crea una tabla en la base de datos para mantener el registro
  26.  * de las transacciones.
  27.  */
  28. register_activation_hook(__FILE__, 'webpay_install');
  29. add_action('plugins_loaded', 'init_woocommerce_webpay');
  30. add_shortcode('webpay_thankyou', 'webpayThankYou');
  31.  
  32.  
  33.  
  34.  
  35.  
  36. /*
  37.  * La siguiente función  hace posible filtrar el acceso a la página de éxito de woocommerce.
  38.  */
  39.  
  40. function webpayThankYou() {
  41.   global $woocommerce;
  42.   $SUFIJO = "[WEBPAY-THANKYOU]";
  43.     /*
  44.      * Revisamos si los parametros necesarios para ver la página existen.
  45.      * El plugin en general pasa los parametros de id de la orden, la llave y el status.
  46.      */
  47.     log_me("Entrando al ThankYouPage", $SUFIJO);
  48.  
  49.     if (!(isset($_GET['order']) && isset($_GET['status']) && isset($_GET['key']))) {
  50.       ?>
  51.       <p><?= "No puedes acceder a esta página de manera directa"; ?></p>
  52.  
  53.       <?
  54.       break;
  55.     } else {
  56.         /*
  57.          * Si los parametros existen muestro la información si es que el status no es fallido.
  58.          * Además de la recepción, se que es fallido cuando NO es pagado.
  59.          * Para los siguientes status NO puedo mostrar esta página si es que el pago es con webpay.
  60.          *
  61.           - Pending – Order received (unpaid)
  62.           - Failed – Payment failed or was declined (unpaid)
  63.           - On-Hold – Awaiting payment – stock is reduced, but you need to confirm payment
  64.           - Cancelled – Cancelled by an admin or the customer – no further action required
  65.           - Refunded – Refunded by an admin - no further action required
  66.          *
  67.          * Por lo que solo se puede mostrar si la orden está completada o en proceso Si es que la orden es exitosa.
  68.          *
  69.          */
  70.           $order_id = explode('_', $_GET['order']);
  71.           $order_id = (int) $order_id[0];
  72.  
  73.           if (!is_numeric($order_id)) {
  74.             echo "<p>Acaba de ocurrir un error tratando de recuperar la información de la orden</p>";
  75.           }
  76.           $order = new WC_Order($order_id);
  77.           if ($order) {
  78.             log_me("ORDEN EXISTENTE", $SUFIJO);
  79.             if (in_array($order->status, array('failed'))) {
  80.               log_me("La orden está fallida, se carga la página de manera normal", $SUFIJO);
  81.               echo do_shortcode('[woocommerce_thankyou]');
  82.             } else {
  83.                 /*
  84.                  * Debo corroborar que la orden este en proceso o completada si el pago es con webpay.
  85.                  */
  86.                 log_me("La transacción no debería ser fallida, se verifica", $SUFIJO);
  87.                 $paymentMethod = $order->order_custom_fields[_payment_method][0];
  88.                 if ($paymentMethod == "webpay") {
  89.                   log_me("\t -> El pago de la orden fue con WebPay", $SUFIJO);
  90.                   if ($order->status == "completed" || $order->status == "processing") {
  91.                         /*
  92.                          * Se carga el template del plugin para la página de éxito solo si es una compra con webpay
  93.                          */
  94. //                        echo "WEBPAY PAYMENT";
  95.                         include_once plugin_dir_path(__FILE__) . '/php/templates/thankyou.php';
  96.                         /*
  97.                          * Se incluyen los detalles de la orden incluyendo el precio unitario según es requerido por transbank
  98.                          */
  99.                         include_once plugin_dir_path(__FILE__) . '/php/templates/order-details.php';
  100.                         echo "<br><p>Recuerda que tus productos serán enviados por correo a tu domicilio si es que seleccionaste este medio de despacho y deberían estar entre 2 y 3 días hábiles a tu hogar.</p>";
  101.                       } else {
  102.                         /*
  103.                          * Si este es el caso, se está intentando acceder a la página sin pasar por el ciclo regular.
  104.                          */
  105.                         echo "<h2>No te encuentras autorizado para acceder a esta página</h2>";
  106.                         return;
  107.                       }
  108.                     } else {
  109.                       log_me("\t -> El pago de la orden NO fue con WebPay o no se a realizado: $paymentMethod ", $SUFIJO);
  110.  
  111.                       if ($paymentMethod !== null) {
  112.                         echo do_shortcode('[woocommerce_thankyou]');
  113.                       } else {
  114.                         echo "Esta orden aún no ha sido pagada o procesada. Por favor vuleve cuando lo hayas hecho.";
  115.                         return;
  116.                       }
  117.                     }
  118.                   }
  119.                 } else {
  120.             //La orden no existía.
  121.                   log_me("ORDEN NO EXISTENTE", $SUFIJO);
  122.                   echo "<p>Lamentablemente la orden buscada no existe o no coincide con la información ingresada</p>";
  123.                   return;
  124.                 }
  125.               }
  126.               log_me("Saliendo al ThankYouPage", $SUFIJO);
  127.             }
  128.  
  129. /*
  130.  * Se agrega nuestro Gateway de pago al array que posee WooCommerce
  131.  */
  132.  
  133. function add_webpay_gateway_class($methods) {
  134.   $methods[] = 'WC_WebPay';
  135.   return $methods;
  136. }
  137.  
  138. add_filter('woocommerce_payment_gateways', 'add_webpay_gateway_class');
  139.  
  140. /*
  141.  * Se crea la clase de conexión
  142.  */
  143.  
  144. function init_woocommerce_webpay() {
  145.  
  146.     /*
  147.      * Si la clase de la cual quiero heredar no existe no hago nada.
  148.      */
  149.     if (!class_exists('WC_Payment_Gateway'))
  150.       return;
  151.  
  152.     class WC_Webpay extends WC_Payment_Gateway {
  153.  
  154.         /**
  155.          * Constructor for the gateway.
  156.          *
  157.          * @access public
  158.          * @return void
  159.          */
  160.         public function __construct() {
  161.  
  162.  
  163.           if (isset($_REQUEST['page_id'])):
  164.  
  165.             if ($_REQUEST['page_id'] == 'xt_compra') {
  166.               add_action('woocommerce_api_' . strtolower(get_class($this)), array($this, 'xt_compra'));
  167.             } else {
  168.  
  169.               $this->check_webpay_response();
  170.             }
  171.             endif;
  172.             $this->id = 'webpay';
  173.             $this->has_fields = false;
  174.             $this->icon = WP_PLUGIN_URL . "/" . plugin_basename(dirname(__FILE__)) . '/images/logo.png';
  175.             $this->method_title = __('WebPay GateWay', 'woocommerce');
  176.  
  177. // Load the settings.
  178.             $this->init_form_fields();
  179.             $this->init_settings();
  180.  
  181. // Define user set variables
  182.             $this->title = $this->get_option('title');
  183.             $this->description = $this->get_option('description');
  184.             $this->liveurl = $this->settings['cgiurl'];
  185.             $this->macpath = $this->settings['macpath'];
  186.  
  187.  
  188.             $this->redirect_page_id = $this->settings['redirect_page_id'];
  189.  
  190. // Actions
  191.             add_action('woocommerce_update_options_payment_gateways_' . $this->id, array(&$this, 'process_admin_options'));
  192.  
  193.             add_action('woocommerce_thankyou_webpay', array(&$this, 'thankyousuccess_page'));
  194.             add_action('woocommerce_receipt_webpay', array(&$this, 'receipt_page'));
  195.           }
  196.  
  197.         /**
  198.          * Initialise Gateway Settings Form Fields
  199.          *
  200.          * @access public
  201.          * @return void
  202.          */
  203.         function init_form_fields() {
  204.  
  205.           $this->form_fields = array(
  206.             'enabled' => array(
  207.               'title' => __('Enable/Disable', 'woocommerce'),
  208.               'type' => 'checkbox',
  209.               'label' => __('Habilita Woocommerce Webpay Plus', 'woocommerce'),
  210.               'default' => 'yes'
  211.               ),
  212.             'title' => array(
  213.               'title' => __('Title', 'woocommerce'),
  214.               'type' => 'text',
  215.               'description' => __('', 'woocommerce'),
  216.               'default' => __('Web Pay Plus', 'woocommerce')
  217.               ),
  218.             'description' => array(
  219.               'title' => __('Customer Message', 'woocommerce'),
  220.               'type' => 'textarea',
  221.               'description' => __('Give the customer instructions for paying via BACS, and let them know that their order won\'t be shipping until the money is received.', 'woocommerce'),
  222.                 //'default' => __('Make your payment directly into our bank account. Please use your Order ID as the payment reference. Your order wont be shipped until the funds have cleared in our account.', 'woocommerce')
  223.               ),
  224.             'account_details' => array(
  225.               'title' => __('Detalles de WebPay', 'woocommerce'),
  226.               'type' => 'title',
  227.               'description' => __('Optionally enter your bank details below for customers to pay into.', 'woocommerce'),
  228.               'default' => ''
  229.               ),
  230.             'cgiurl' => array(
  231.               'title' => __('CGI URL', 'woocommerce'),
  232.               'type' => 'text',
  233.               'description' => __('url like : http://empresasctm.cl/cgi-bin/tbk_bp_pago.cgi', 'woocommerce'),
  234.               'default' => __('http://empresasctm.cl/cgi-bin/tbk_bp_pago.cgi', 'woocommerce')
  235.               ),
  236.             'macpath' => array(
  237.               'title' => __('Check Mac Path', 'woocommerce'),
  238.               'type' => 'text',
  239.               'description' => __('url like : /usr/lib/cgi-bin/', 'woocommerce'),
  240.               'default' => __('/usr/lib/cgi-bin/', 'woocommerce')
  241.               ),
  242.             'redirect_page_id' => array(
  243.               'title' => __('Return Page'),
  244.               'type' => 'select',
  245.               'options' => $this->get_pages('Select Page'),
  246.               'description' => "URL of success page"
  247.               ),
  248.             'trade_name' => array(
  249.               'title' => __('Nombre del Comercio', 'woocommerce'),
  250.               'type' => 'text',
  251.               'description' => __('Trade Name like : EmpresasCTM', 'woocommerce')
  252.               ),
  253.             'url_commerce' => array(
  254.               'title' => __('URL Comercio', 'woocommerce'),
  255.               'type' => 'text',
  256.               'description' => __('Url Commerce like : http://www.empresasctm.cl', 'woocommerce')
  257.               ),
  258.             );
  259. }
  260.  
  261.         /**
  262.          * Admin Panel Options
  263.          * - Options for bits like 'title' and availability on a country-by-country basis
  264.          *
  265.          * @access public
  266.          * @return void
  267.          */
  268.         public function admin_options() {
  269.           ?>
  270.           <h3><?php _e('WebPay Plus', 'woocommerce'); ?></h3>
  271.           <p><?php _e('Permite el pago con Tarjetas Bancarias en Chile.', 'woocommerce'); ?></p>
  272.           <table class="form-table">
  273.             <?php
  274.                 // Generate the HTML For the settings form.
  275.             $this->generate_settings_html();
  276.             ?>
  277.           </table><!--/.form-table-->
  278.           <?php
  279.         }
  280.  
  281.         /**
  282.          * Output for the order received page.
  283.          *
  284.          * @access public
  285.          * @return void
  286.          */
  287.         function thankyousuccess_page() {
  288.           include_once plugin_dir_path(__FILE__) . '/php/thankYouPage.php';
  289.         }
  290.  
  291.         function receipt_page($order) {
  292.           echo '<p>' . __('Gracias por tu pedido, por favor haz click a continuación para pagar con webpay', 'woocommerce') . '</p>';
  293.           echo $this->generate_webpay_form($order);
  294.         }
  295.  
  296.         function process_payment($order_id) {
  297.           $sufijo = "[WEBPAY - PROCESS - PAYMENT]";
  298.           log_me("Iniciando el proceso de pago para $order_id", $sufijo);
  299.           $order = &new WC_Order($order_id);
  300.           return array('result' => 'success', 'redirect' => add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))))
  301.             );
  302.         }
  303.  
  304.         public function generate_webpay_form($order_id) {
  305.           global $woocommerce;
  306.           global $webpay_comun_folder;
  307.           $SUFIJO = "[WEBPAY - FORM]";
  308.  
  309.           $order = &new WC_Order($order_id);
  310.           $redirect_url = get_site_url() . "/?page_id=" . ($this->redirect_page_id);
  311.           $order_id = $order_id;
  312.  
  313.           log_me("REDIRECT_URL " . $redirect_url, $SUFIJO);
  314.           $order_key = $order->order_key;
  315.  
  316.  
  317.           $TBK_MONTO = round($order->order_total);
  318.           $TBK_ORDEN_COMPRA = $order_id;
  319.           $TBK_ID_SESION = date("Ymdhis");
  320.  
  321.           $filename = __FILE__;
  322.  
  323.           $myPath = $webpay_comun_folder . DIRECTORY_SEPARATOR . "dato$TBK_ID_SESION.log";
  324.  
  325.           log_me("Se utilizará $myPath para guardar los datos", $SUFIJO);
  326.           /*             * **************** FIN CONFIGURACION **************** */
  327.             //formato Moneda
  328.           $partesMonto = split(",", $TBK_MONTO);
  329.           $TBK_MONTO = $partesMonto[0] . "00";
  330.             //Grabado de datos en archivo de transaccion
  331.           $fic = fopen($myPath, "w+");
  332.           $linea = "$TBK_MONTO;$TBK_ORDEN_COMPRA";
  333.  
  334.           log_me("Preparando para escribir $linea en $myPath", $SUFIJO);
  335.           fwrite($fic, $linea);
  336.           fclose($fic);
  337.           log_me("ARCHIVO CERRADO", $SUFIJO);
  338.  
  339.           log_me("Argumentos", $SUFIJO);
  340.           $ccavenue_args = array(
  341.             'TBK_TIPO_TRANSACCION' => "TR_NORMAL",
  342.             'TBK_MONTO' => $TBK_MONTO,
  343.             'TBK_ORDEN_COMPRA' => $TBK_ORDEN_COMPRA,
  344.             'TBK_ID_SESION' => $TBK_ID_SESION,
  345.             'TBK_URL_EXITO' => $redirect_url . "&status=success&order=$order_id&key=$order_key",
  346.             'TBK_URL_FRACASO' => $redirect_url . "&status=failure&order=$order_id&key=$order_key",
  347.             );
  348.           log_me($ccavenue_args);
  349.  
  350.  
  351.           $woopayment = array();
  352.           foreach ($ccavenue_args as $key => $value) {
  353.             $woopayment[] = "<input type='hidden' name='$key' value='$value'/>";
  354.           }
  355.  
  356.           return '<form action="' . $this->liveurl . '" method="post" id="webpayplus">
  357.          ' . implode('', $woopayment) . '
  358.          <input type="submit" class="button" id="submit_webpayplus_payment_form" value="Pagar" /> <a class="button cancel" href="' . $order->get_cancel_order_url() . '">Cancel</a>
  359.          <script type="text/javascript">
  360.          jQuery(function() {
  361.            jQuery("body").block(
  362.            {
  363.              message: "<img src=\"' . $woocommerce->plugin_url() . '/assets/images/ajax-loader.gif\" alt=\"Redirecting�\" style=\"float:left; margin-right: 10px;\" />' . __('Thank you for your order. We are now redirecting you to Webpay to make payment.', 'mrova') . '",
  364.              overlayCSS:
  365.              {
  366.                background: "#fff",
  367.                opacity: 0.6
  368.              },
  369.              css: {
  370.                padding: 20,
  371.                textAlign: "center",
  372.                color: "#555",
  373.                border: "3px solid #aaa",
  374.                backgroundColor: "#fff",
  375.                cursor: "wait",
  376.                lineHeight: "32px"
  377.              }
  378.            });
  379. jQuery("#submit_webpayplus_payment_form").click();
  380.  
  381. });
  382. </script>
  383. </form>';
  384. }
  385.  
  386.         // get all pages
  387. function get_pages($title = false, $indent = true) {
  388.   $wp_pages = get_pages('sort_column=menu_order');
  389.   $page_list = array();
  390.   if ($title)
  391.     $page_list[] = $title;
  392.   foreach ($wp_pages as $page) {
  393.     $prefix = '';
  394.                 // show indented child pages?
  395.     if ($indent) {
  396.       $has_parent = $page->post_parent;
  397.       while ($has_parent) {
  398.         $prefix .= ' - ';
  399.         $next_page = get_page($has_parent);
  400.         $has_parent = $next_page->post_parent;
  401.       }
  402.     }
  403.                 // add to page list array array
  404.     $page_list[$page->ID] = $prefix . $page->post_title;
  405.   }
  406.   return $page_list;
  407. }
  408.  
  409.         /**
  410.          *      Check payment response from web pay plus
  411.          * */
  412.         function check_webpay_response() {
  413.           global $woocommerce;
  414.           global $webpay_comun_folder;
  415.           $SUFIJO = "[WEBPAY - RESPONSE]";
  416.  
  417.           log_me("Entrando al Webpay Response", $SUFIJO);
  418.  
  419.           if ($_REQUEST['TBK_ORDEN_COMPRA'] and $_REQUEST['TBK_ID_SESION']) {
  420.             $order_id_time = $_REQUEST['order'];
  421.             $order_id = explode('_', $_REQUEST['order']);
  422.             $order_id = (int) $order_id[0];
  423.  
  424.  
  425.             if ($order_id != '') {
  426.               try {
  427.                 $order = new WC_Order($order_id);
  428.  
  429.                 $status = $_REQUEST['status'];
  430.                 if ($order->status !== 'completed') {
  431.                   if ($status == 'success') {
  432.                     $woocommerce->cart->empty_cart();
  433.                                 // Mark as Processing, we already received the money.
  434.                     $order->update_status('processing');
  435.  
  436.                                 // Reduce stock levels
  437.                     $order->reduce_order_stock();
  438.  
  439.                                 // Remove cart
  440.                     $woocommerce->cart->empty_cart();
  441.  
  442.                                 // Empty awaiting payment session
  443.                     unset($_SESSION['order_awaiting_payment']);
  444.  
  445.                     log_me('START WEBPAY RESPONSE ARRAY REQUEST', $SUFIJO);
  446.                     log_me($_REQUEST);
  447.                     log_me('END WEBPAY RESPONSE ARRAY REQUEST', $SUFIJO);
  448.                                 //RESCATO EL ARCHIVO
  449.                     $TBK_ID_SESION
  450.                     = $_POST["TBK_ID_SESION"];
  451.                     $TBK_ORDEN_COMPRA
  452.                     = $_POST["TBK_ORDEN_COMPRA"];
  453.                     /*                                 * **************** CONFIGURAR AQUI ****************** */
  454.  
  455.  
  456.                                 //Archivo previamente generado para rescatar la información.
  457.                     $myPath = $webpay_comun_folder . DIRECTORY_SEPARATOR . "MAC01Normal$TBK_ID_SESION.txt";
  458.                     /*                                 * **************** FIN CONFIGURACION **************** */
  459.                                 //Rescate de los valores informados por transbank
  460.                     $fic = fopen($myPath, "r");
  461.                     $linea = fgets($fic);
  462.                     fclose($fic);
  463.                     $detalle = explode("&", $linea);
  464.  
  465.                     $TBK = array(
  466.                       'TBK_ORDEN_COMPRA' => explode("=", $detalle[0]),
  467.                       'TBK_TIPO_TRANSACCION' => explode("=", $detalle[1]),
  468.                       'TBK_RESPUESTA' => explode("=", $detalle[2]),
  469.                       'TBK_MONTO' => explode("=", $detalle[3]),
  470.                       'TBK_CODIGO_AUTORIZACION' => explode("=", $detalle[4]),
  471.                       'TBK_FINAL_NUMERO_TARJETA' => explode("=", $detalle[5]),
  472.                       'TBK_FECHA_CONTABLE' => explode("=", $detalle[6]),
  473.                       'TBK_FECHA_TRANSACCION' => explode("=", $detalle[7]),
  474.                       'TBK_HORA_TRANSACCION' => explode("=", $detalle[8]),
  475.                       'TBK_ID_TRANSACCION' => explode("=", $detalle[10]),
  476.                       'TBK_TIPO_PAGO' => explode("=", $detalle[11]),
  477.                       'TBK_NUMERO_CUOTAS' => explode("=", $detalle[12]),
  478.                                         //'TBK_MAC' => explode("=", $detalle[13]),
  479.                       );
  480.  
  481.  
  482.                     log_me("INSERTANDO EN LA BDD");
  483.                     woocommerce_payment_complete_add_data_webpay($order_id, $TBK);
  484.                     log_me("TERMINANDO INSERSIÓN");
  485.                   } elseif ($status == 'failure') {
  486.                     $order->update_status('failed');
  487.                     $order->add_order_note('Failed');
  488.  
  489.                                 //Si falla no limpio el carrito para poder pagar nuevamente
  490.                                 //$woocommerce->cart->empty_cart();
  491.                   }
  492.                 } else {
  493.                   $this->msg = 'Esta orden ya ha sido completada.';
  494.                   add_action('the_content', array(&$this, 'thankyouContent'));
  495.                 }
  496.               } catch (Exception $e) {
  497.  
  498.                 $this->msg = "Ha ocurrido un error procesando el pago.";
  499.                 add_action('the_content', array(&$this, 'thankyouContent'));
  500.               }
  501.             }
  502.           } else {
  503.             log_me("FALTAN PARAMETROS", $SUFIJO);
  504.           }
  505.           log_me("SALIENDO DEL RESPONSE", $SUFIJO);
  506.         }
  507.  
  508.         function thankyouContent($content) {
  509.           echo $this->msg;
  510.         }
  511.  
  512.         public function xt_compra() {
  513.           global $webpay_table_name;
  514.           global $wpdb;
  515.           global $woocommerce;
  516.           global $webpay_comun_folder;
  517.           $sufijo = "[XT_COMPRA]";
  518.           log_me("Iniciando xt_compra", $sufijo);
  519.  
  520.             //rescate de datos de POST.
  521.           $TBK_RESPUESTA = $_POST["TBK_RESPUESTA"];
  522.           $TBK_ORDEN_COMPRA = $_POST["TBK_ORDEN_COMPRA"];
  523.           $TBK_MONTO = $_POST["TBK_MONTO"];
  524.           $TBK_ID_SESION = $_POST["TBK_ID_SESION"];
  525.           $TBK_TIPO_TRANSACCION = $_POST['TBK_TIPO_TRANSACCION'];
  526.           $TBK_CODIGO_AUTORIZACION = $_POST['TBK_CODIGO_AUTORIZACION'];
  527.           $TBK_FINAL_NUMERO_TARJETA = $_POST['TBK_FINAL_NUMERO_TARJETA'];
  528.           $TBK_FECHA_CONTABLE = $_POST['TBK_FECHA_CONTABLE'];
  529.           $TBK_FECHA_TRANSACCION = $_POST['TBK_FECHA_TRANSACCION'];
  530.           $TBK_HORA_TRANSACCION = $_POST['TBK_HORA_TRANSACCION'];
  531.           $TBK_ID_TRANSACCION = $_POST['TBK_ID_TRANSACCION'];
  532.           $TBK_TIPO_PAGO = $_POST['TBK_TIPO_PAGO'];
  533.           $TBK_NUMERO_CUOTAS = $_POST['TBK_NUMERO_CUOTAS'];
  534.  
  535.  
  536.             //Validación de los datos del post.
  537.           if (!isset($TBK_RESPUESTA) || !is_numeric($TBK_RESPUESTA))
  538.             die('RECHAZADO');
  539.           if (!isset($TBK_ORDEN_COMPRA))
  540.             die('RECHAZADO');
  541.           if (!isset($TBK_MONTO) || !is_numeric($TBK_MONTO))
  542.             die('RECHAZADO');
  543.           if (!isset($TBK_ID_SESION) || !is_numeric($TBK_ID_SESION))
  544.             die('RECHAZADO');
  545.           if (!isset($TBK_TIPO_TRANSACCION))
  546.             die('RECHAZADO');
  547.           if (!isset($TBK_CODIGO_AUTORIZACION) || !is_numeric($TBK_CODIGO_AUTORIZACION))
  548.             die('RECHAZADO');
  549.           if (!isset($TBK_FINAL_NUMERO_TARJETA) || !is_numeric($TBK_FINAL_NUMERO_TARJETA))
  550.             die('RECHAZADO');
  551.           if (!isset($TBK_FECHA_CONTABLE) || !is_numeric($TBK_FECHA_CONTABLE))
  552.             die('RECHAZADO');
  553.           if (!isset($TBK_FECHA_TRANSACCION) || !is_numeric($TBK_FECHA_TRANSACCION))
  554.             die('RECHAZADO');
  555.           if (!isset($TBK_HORA_TRANSACCION) || !is_numeric($TBK_HORA_TRANSACCION))
  556.             die('RECHAZADO');
  557.           if (!isset($TBK_ID_TRANSACCION) || !is_numeric($TBK_ID_TRANSACCION))
  558.             die('RECHAZADO');
  559.           if (!isset($TBK_TIPO_PAGO))
  560.             die('RECHAZADO');
  561.           if (!isset($TBK_NUMERO_CUOTAS) || !is_numeric($TBK_NUMERO_CUOTAS))
  562.             die('RECHAZADO');
  563.  
  564.           $order_id = explode('_', $TBK_ORDEN_COMPRA);
  565.           $order_id = (int) $order_id[0];
  566.  
  567.           if (!is_numeric($order_id))
  568.             die('RECHAZADO');
  569.  
  570.           if ($TBK_RESPUESTA >=-8 && $TBK_RESPUESTA <=-1)
  571.             die("ACEPTADO");
  572.  
  573.             //Validar que la orden exista        
  574.           $order = new WC_Order($order_id);
  575.           log_me($order->status, $sufijo);
  576.  
  577.             //Si la orden de compra no tiene status es debido a que no existe
  578.  
  579.           if ($order->status == '') {
  580.             log_me("ORDEN NO EXISTENTE " . $order_id, $sufijo);
  581.             die('RECHAZADO');
  582.           } else {
  583.             log_me("ORDEN EXISTENTE " . $order_id, $sufijo);
  584.                 //CUANDO UNA ORDEN ES PAGADA SE VA A PROCESSING.
  585.  
  586.             if ($order->status == 'completed' || $order->status == 'processing' || $order->status == 'refunded' || $order->status == 'canceled') {
  587.               log_me("ORDEN YA PAGADA (" . $order->status . ") EXISTENTE " . $order_id, "\t" . $sufijo);
  588.               die('RECHAZADO');
  589.             } else {
  590.  
  591.               if ($order->status == 'pending' || $order->status == 'failed') {
  592.                 log_me("ORDEN DE COMPRA NO PAGADA (" . $order->status . "). Se procede con el pago de la orden " . $order_id, $sufijo);
  593.               } else {
  594.                 log_me("ORDEN YA PAGADA (" . $order->status . ") EXISTENTE " . $order_id, "\t" . $sufijo);
  595.                 die('RECHAZADO');
  596.               }
  597.             }
  598.           }
  599.  
  600.  
  601.           /*             * **************** CONFIGURAR AQUI ****************** */
  602.           $myPath = $webpay_comun_folder . DIRECTORY_SEPARATOR . "dato$TBK_ID_SESION.log";
  603.             //GENERA ARCHIVO PARA MAC
  604.           $filename_txt = $webpay_comun_folder . DIRECTORY_SEPARATOR . "MAC01Normal$TBK_ID_SESION.txt";
  605.             // Ruta Checkmac
  606.           $cmdline = $this->macpath . "/tbk_check_mac.cgi $filename_txt";
  607.           /*             * **************** FIN CONFIGURACION **************** */
  608.           $acepta = false;
  609.             //lectura archivo que guardo pago.php
  610.           if ($fic = fopen($myPath, "r")) {
  611.             $linea = fgets($fic);
  612.             fclose($fic);
  613.           }
  614.           $detalle = split(";", $linea);
  615.           if (count($detalle) >= 1) {
  616.             $monto = $detalle[0];
  617.             $ordenCompra = $detalle[1];
  618.           }
  619.             //guarda los datos del post uno a uno en archivo para la ejecuci�n del MAC
  620.           $fp = fopen($filename_txt, "wt");
  621.           while (list($key, $val) = each($_POST)) {
  622.             fwrite($fp, "$key=$val&");
  623.           }
  624.           fclose($fp);
  625.             //Validación de respuesta de Transbank, solo si es 0 continua con la pagina de cierre
  626.           if ($TBK_RESPUESTA == "0") {
  627.             $acepta = true;
  628.           } else {
  629.             $acepta = false;
  630.           }
  631.             //validación de monto y Orden de compra
  632.           if ($TBK_MONTO == $monto && $TBK_ORDEN_COMPRA == $ordenCompra && $acepta == true) {
  633.  
  634.             $res=$wpdb->get_row("SELECT count(*) as total FROM ".$webpay_table_name." WHERE idOrder = ".$TBK_ORDEN_COMPRA, ARRAY_A);
  635.  
  636.  
  637.             if($res['total']>0){
  638.  
  639.               $acepta=false;
  640.             }else{
  641.  
  642.               $acepta=true;
  643.             }
  644.           } else {
  645.             $acepta = false;
  646.           }
  647.  
  648.             //Validación MAC
  649.           if ($acepta == true) {
  650.             exec($cmdline, $result, $retint);
  651.             if ($result [0] == "CORRECTO")
  652.               $acepta = true;
  653.             else
  654.               $acepta = false;
  655.           }
  656.           ?>
  657.           <html>
  658.           <?php
  659.           if ($acepta == true) {
  660.             ?>
  661.             ACEPTADO
  662.             <?php } else { ?>
  663.             RECHAZADO
  664.             <?php } exit; ?>
  665.             </html>
  666.  
  667.             <?php
  668.             log_me("FINALIZANDO XT_COMPRA", $sufijo);
  669.           }
  670.  
  671.         }
  672.  
  673.     //End of the GateWay Class
  674.  
  675.         function woocommerce_payment_complete_add_data_webpay($order_id, $TBK) {
  676.           global $webpay_table_name;
  677.           global $wpdb;
  678.  
  679.           $order = new WC_Order($order_id);
  680.           $order->add_order_note("Pago Completado. Transacción : " . $TBK['TBK_CODIGO_AUTORIZACION'][1]);
  681.  
  682.           log_me("idOrden : ");
  683.           log_me($order_id);
  684.           log_me('TBK:');
  685.           log_me($TBK);
  686.           $rows_affected = $wpdb->insert($webpay_table_name, array(
  687.             'idOrder' => $order_id,
  688.             'TBK_ORDEN_COMPRA' => $TBK['TBK_ORDEN_COMPRA'][1],
  689.             'TBK_TIPO_TRANSACCION' => $TBK['TBK_TIPO_TRANSACCION'][1],
  690.             'TBK_RESPUESTA' => $TBK['TBK_RESPUESTA'][1],
  691.             'TBK_MONTO' => $TBK['TBK_MONTO'][1],
  692.             'TBK_CODIGO_AUTORIZACION' => $TBK['TBK_CODIGO_AUTORIZACION'][1],
  693.             'TBK_FINAL_NUMERO_TARJETA' => $TBK['TBK_FINAL_NUMERO_TARJETA'][1],
  694.             'TBK_FECHA_CONTABLE' => $TBK['TBK_FECHA_CONTABLE'][1],
  695.             'TBK_FECHA_TRANSACCION' => $TBK['TBK_FECHA_TRANSACCION'][1],
  696.             'TBK_HORA_TRANSACCION' => $TBK['TBK_HORA_TRANSACCION'][1],
  697.             'TBK_ID_TRANSACCION' => $TBK['TBK_ID_TRANSACCION'][1],
  698.             'TBK_TIPO_PAGO' => $TBK['TBK_TIPO_PAGO'][1],
  699.             'TBK_NUMERO_CUOTAS' => $TBK['TBK_NUMERO_CUOTAS'][1],
  700.             )
  701.           );
  702.         }
  703.  
  704.         add_action('woocommerce_payment_complete', 'woocommerce_payment_complete_add_data_webpay', 10, 1);
  705.       }
  706.       ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement