Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 37.87 KB | None | 0 0
  1. <?php
  2. //error_reporting(E_ALL);
  3. //ini_set('display_errors', TRUE);
  4. //ini_set('display_startup_errors', TRUE);
  5.  
  6. /**
  7.  * Plugin Name: Simple VisaNet Payment Gateway
  8.  * Description: Procesador de pago para el API de VisaNet
  9.  * Version: 1.0
  10.  * Author: Archangel Systems
  11.  * Author URI: http://archangelsystems.com
  12.  * Copyright: © 2017  Archangelsystems.
  13.  */
  14. require_once 'lib/CybsSoapClient.php';
  15. require_once $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/elfotobus-reserva/public/class-elfotobus-reserva-public.php';
  16.  
  17. require_once 'settings_page.php';
  18.  
  19. add_action('wp_enqueue_scripts', 'ajax_test_enqueue_scripts');
  20. function ajax_test_enqueue_scripts()
  21. {
  22.     wp_enqueue_style('bootstrap.form', plugins_url('/css/bootstrap.css', __FILE__));
  23.     wp_enqueue_style('fontawesome', 'https://use.fontawesome.com/releases/v5.2.0/css/all.css');
  24.     wp_enqueue_style('checkout', plugins_url('/css/checkout.css', __FILE__));
  25.  
  26.     wp_enqueue_script('checkout', plugins_url('/js/checkout.js', __FILE__), array('jquery'), '1.1', true);
  27.     wp_enqueue_script('md5', plugins_url('/js/md5.js', __FILE__), array('jquery'), '1.0', true);
  28.     wp_enqueue_script('jquery.mask', plugins_url('/js/jquery.mask.min.js', __FILE__), array('jquery'), '1.0', true);
  29.  
  30.     wp_localize_script('checkout', 'checkout', array(
  31.         'ajax_url' => admin_url('admin-ajax.php'),
  32.         'home_url' => home_url(),
  33.     ));
  34. }
  35.  
  36. function my_error_notice()
  37. {
  38.     ?>
  39.     <div class="error notice">
  40.         <p><?php _e('Se creara una opcion nueva', 'my_plugin_textdomain'); ?></p>
  41.     </div>
  42.     <?php
  43. }
  44.  
  45. function check_some_other_plugin()
  46. {
  47.     if (!is_plugin_active('woocommerce/woocommerce.php')) {
  48.         //add_action( 'admin_notices', 'my_error_notice' );
  49.     } else {
  50.         add_action('plugins_loaded', 'init_visanet_cybersource_gateway_class_simple');
  51.  
  52.         function init_visanet_cybersource_gateway_class_simple()
  53.         {
  54.             class WC_Gateway_Visanet_CyberSource_Simple_Gateway extends WC_Payment_Gateway
  55.             {
  56.                 public function __construct()
  57.                 {
  58.                     //$this->supports[] = 'default_credit_card_form';
  59.                     $this->id = 'visanet';
  60.                     $this->has_fields = true;
  61.                     $this->method_title = 'VisaNet';
  62.                     $this->title = 'VisaNet';
  63.                     $this->method_description = 'Metodo de pago usando el puente de Visanet y CyberSource';
  64.  
  65.                     //$this->supports( 'default_credit_card_form' );
  66.  
  67.                     $this->init_form_fields();
  68.                     $this->init_settings();
  69.  
  70.                     $this->title = $this->get_option('title');
  71.                     add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this, 'process_admin_options'));
  72.  
  73.                     $this->supports = array('default_credit_card_form');
  74.  
  75.                     // load time variable setting
  76.                     $this->init_settings();
  77.  
  78.                     // Turn these settings into variables we can use
  79.                     foreach ($this->settings as $setting_key => $value) {
  80.                         $this->$setting_key = $value;
  81.                     }
  82.                 }
  83.  
  84.                 public function init_form_fields()
  85.                 {
  86.                     $this->form_fields = array(
  87.                         'enabled' => array(
  88.                             'title' => __('Enable/Disable', 'woocommerce'),
  89.                             'type' => 'checkbox',
  90.                             'label' => __('Enable VisaNet CyberSource', 'woocommerce'),
  91.                             'default' => 'yes',
  92.                         ),
  93.                         'title' => array(
  94.                             'title' => __('Title', 'woocommerce'),
  95.                             'type' => 'text',
  96.                             'description' => __('This controls the title which the user sees during checkout.', 'woocommerce'),
  97.                             'desc_tip' => true,
  98.                         ),
  99.                         'description' => array(
  100.                             'title' => __('Customer Message', 'woocommerce'),
  101.                             'type' => 'textarea',
  102.                             'default' => '',
  103.                         ),
  104.  
  105.                         'merchantId' => array(
  106.                             'title' => __('Merchant ID', 'woocommerce'),
  107.                             'type' => 'text',
  108.                             'description' => __('VisaNet Merchant ID'),
  109.                             'desc_tip' => true,
  110.                         ),
  111.  
  112.                         'currency' => array(
  113.                             'title' => __('Payment Currency', 'woocommerce'),
  114.                             'type' => 'text',
  115.                             'description' => __('Moneda de pago en la que se procesaran las compras'),
  116.                             'desc_tip' => true,
  117.                         ),
  118.  
  119.                         'orgId' => array(
  120.                             'title' => __('Org ID', 'woocommerce'),
  121.                             'type' => 'text',
  122.                             'description' => __('Visanet Org ID .', 'woocommerce'),
  123.                             'desc_tip' => true,
  124.                         ),
  125.  
  126.                         'trxId' => array(
  127.                             'title' => __('Transaction Key', 'woocommerce'),
  128.                             'type' => 'textarea',
  129.                             'description' => __('Visanet CyberSource Transaction Key.', 'woocommerce'),
  130.                             'desc_tip' => true,
  131.                             'default' => '',
  132.                         ),
  133.  
  134.                         'endpointUrl' => array(
  135.                             'title' => __('VisaNet SOAP WSDL URL', 'woocommerce'),
  136.                             'type' => 'textarea',
  137.                             'description' => __(' VisaNet SOAP WSDL to use on payment process.', 'woocommerce'),
  138.                             'desc_tip' => true,
  139.                             'default' => '',
  140.                         ),
  141.  
  142.                         'fingerprintUrl' => array(
  143.                             'title' => __('fingerprint scripts URL', 'woocommerce'),
  144.                             'type' => 'textarea',
  145.                             'description' => __('URL to request fingerprint scripts.', 'woocommerce'),
  146.                             'desc_tip' => true,
  147.                             'default' => '',
  148.                         ),
  149.                     );
  150.                 }
  151.  
  152.                 public function process_payment($order_id)
  153.                 {
  154.                     global $woocommerce;
  155.                     if (session_id() == '') {
  156.                         session_start();
  157.                     }
  158.                     require_once 'lib/CybsSoapClient.php';
  159.                     $order = new WC_Order($order_id);
  160.                     try {
  161.                         $order->update_status('on-hold', __('Procesando pago', 'woocommerce'));
  162.                         $items = $order->get_items();
  163.                         $products = array();
  164.                         if (is_array($items)) {
  165.                             foreach ($items as $item) {
  166.                                 $products[] = new WC_Product($item['product_id']);
  167.                             }
  168.                         }
  169.  
  170.                         $merchantId = get_option('merchantId');
  171.                         $trxId = get_option('trxId');
  172.                         $endpointUrl = get_option('endpointUrl');
  173.                         $currency = get_option('currency');
  174.  
  175.                         $properties = array(
  176.                             'merchant_id' => $merchantId,
  177.                             'transaction_key' => $trxId,
  178.                             'wsdl' => $endpointUrl,
  179.                             'nvp_wsdl' => $endpointUrl,
  180.                         );
  181.  
  182.                         $client = new CybsSoapClient($properties);
  183.                         $request = $client->createRequest($order_id);
  184.  
  185.                         $ccAuthService = new stdClass();
  186.                         $ccAuthService->run = 'true';
  187.                         $request->ccAuthService = $ccAuthService;
  188.  
  189.                         $ccCaptureService = new stdClass();
  190.                         $ccCaptureService->run = 'true';
  191.                         $request->ccCaptureService = $ccCaptureService;
  192.  
  193.                         $billTo = new stdClass();
  194.                         $billTo->firstName = $order->billing_first_name;
  195.                         $billTo->lastName = $order->billing_last_name;
  196.                         $billTo->street1 = $order->billing_address_1.' '.$order->billing_address_2;
  197.                         $billTo->city = $order->billing_city;
  198.                         $billTo->state = $order->billing_state;
  199.                         $billTo->postalCode = $order->billing_postcode;
  200.                         $billTo->country = $order->billing_country;
  201.                         $billTo->email = $order->billing_email;
  202.                         $billTo->phoneNumber = $order->billing_phone;
  203.                         $billTo->ipAddress = $_SERVER['REMOTE_ADDR'];
  204.                         $request->billTo = $billTo;
  205.  
  206.                         $parts = explode('/', $_POST['visanet-card-expiry']);
  207.                         $year = date('Y');
  208.                         $year = substr($year, 0, 2).trim($parts[1]);
  209.  
  210.                         $cardnumber = preg_replace('/\s+/', '', $_POST['visanet-card-number']);
  211.  
  212.                         $card = new stdClass();
  213.                         $card->accountNumber = strip_tags($cardnumber);
  214.                         $card->expirationMonth = trim($parts[0]);
  215.                         $card->expirationYear = $year;
  216.                         $card->cvNumber = strip_tags($_POST['visanet-card-cvc']);
  217.  
  218.                         $request->card = $card;
  219.  
  220.                         $purchaseTotals = new stdClass();
  221.                         $purchaseTotals->currency = $currency;
  222.                         $purchaseTotals->grandTotalAmount = $order->get_total();
  223.                         $request->purchaseTotals = $purchaseTotals;
  224.  
  225.                         $request->deviceFingerprintID = $_SESSION['requestSessionId'];
  226.  
  227.                         if (is_array($items)) {
  228.                             $cartItems = array();
  229.                             foreach ($items as $item) {
  230.                                 $currentProduct = new WC_Product($item['product_id']);
  231.                                 $currentItem = new stdClass();
  232.                                 $currentItem->unitPrice = $item['line_total'] / $item['qty'];
  233.                                 $currentItem->quantity = $item['qty'];
  234.                                 $currentItem->productCode = $item['product_id'];
  235.                                 $currentItem->productName = $item['name'];
  236.                                 $currentItem->productSKU = $item['product_id'];
  237.                                 $cartItems[] = $currentItem;
  238.                             }
  239.                         }
  240.  
  241.                         $request->item = $cartItems;
  242.  
  243.                         header('Content-Type: application/json');
  244.                         //echo json_encode($_POST);
  245.                         //echo json_encode($parts);
  246.  
  247.                         $reply = $client->runTransaction($request);
  248.                         $error_message = $reply->decision;
  249.  
  250.                         if ($reply->decision == 'REVIEW') {
  251.                             $error_message = __('Pago procesado, pero necesita revision en la plataforma de visanet', 'woocommerce');
  252.                             wc_add_notice($error_message, 'notice');
  253.  
  254.                             $order->update_status('on-hold', $error_message);
  255.                             $order->reduce_order_stock();
  256.                             $woocommerce->cart->empty_cart();
  257.  
  258.                             return array(
  259.                                 'result' => 'success',
  260.                                 'redirect' => $this->get_return_url($order),
  261.                             );
  262.                         } elseif ($reply->decision == 'REJECT') {
  263.                             $msg = 'El pago fue rechazado ';
  264.                             if (isset($reply->invalidField)) {
  265.                                 $msg = $reply->invalidField.' ';
  266.                             }
  267.  
  268.                             $order->update_status('failed', $msg);
  269.                             wc_add_notice($msg, 'error');
  270.  
  271.                             return;
  272.                         } elseif ($reply->decision == 'ACCEPT') {
  273.                             $msg = 'El pago fue procesado, queda pendiente de completar la orden<br/>Autorizaci&oacute;n No.: ';
  274.                             $msg .= $reply->ccAuthReply->authorizationCode;
  275.                             wc_add_notice($msg, 'success');
  276.  
  277.                             $order->payment_complete();
  278.                             $order->reduce_order_stock();
  279.  
  280.                             return array(
  281.                                 'result' => 'success',
  282.                                 'redirect' => $this->get_return_url($order),
  283.                             );
  284.                         }
  285.                     } catch (Exception $e) {
  286.                         wc_add_notice($e->getMessage(), 'error');
  287.  
  288.                         return;
  289.                     }
  290.                 }
  291.             }
  292.  
  293.             function getSimpleCCMonthExpDate($expDate)
  294.             {
  295.                 //$parts = explode('/',$expDate);
  296.                 return $expDate;
  297.                 /*$part = trim($parts[0]);
  298.                 if($part<10){
  299.                    $part = '0'. $part;
  300.                 }
  301.                 return $part; */
  302.             }
  303.  
  304.             function getSimpleYearExpDate($expDate)
  305.             {
  306.                 $parts = explode('/', $expDate);
  307.                 $part = trim($parts[1]);
  308.                 $year = date('Y');
  309.                 $part = substr($year, 0, 2).$part;
  310.  
  311.                 return $part;
  312.             }
  313.         }
  314.  
  315.         function add_visanet_cybersource_gateway_class_simple($methods)
  316.         {
  317.             $methods[] = 'WC_Gateway_Visanet_CyberSource_Simple_Gateway';
  318.  
  319.             return $methods;
  320.         }
  321.  
  322.         add_filter('woocommerce_payment_gateways', 'add_visanet_cybersource_gateway_class_simple');
  323.  
  324.         //WC_Gateway_Visanet_CyberSource_Simple_Gateway
  325.     }
  326. }
  327. add_action('admin_init', 'check_some_other_plugin');
  328.  
  329. function setCyberSourceRequestSimpleSessionID()
  330. {
  331.     if (session_id() == '') {
  332.         session_start();
  333.     }
  334.     $_SESSION['requestSessionId'] = md5(rand(99, 9999).time().rand(99, 9999));
  335.     //$_SESSION['requestSessionId'] = md5('25252525');
  336. }
  337.  
  338. function simple_fingerprint_shortcode()
  339. {
  340.     $options = get_option('simple_visanet_settings');
  341.  
  342.     if (session_id() == '') {
  343.         session_start();
  344.     }
  345.     ob_start();
  346.     setCyberSourceRequestSimpleSessionID();
  347.     $pluginUrl = plugins_url('/visanet_lib/call/requests.php?', __FILE__);
  348.  
  349.     //$CSGW = new WC_Gateway_Visanet_CyberSource_Simple_Gateway();
  350.  
  351.     $merchantId = get_option('merchantId');
  352.     $trxId = get_option('trxId');
  353.     $endpointUrl = get_option('endpointUrl');
  354.     $currency = get_option('currency');
  355.     $orgId = get_option('orgId');
  356.  
  357.     $_SESSION['SID'] = $_SESSION['requestSessionId'];
  358.     $_SESSION['MID'] = $merchantId;
  359.     $_SESSION['OID'] = $orgId;
  360.     //$query = '?S=' . $SID . '&M='. $MID . '&O=' . $OID;
  361.     //$pluginUrl .= $query;?>
  362.        
  363.         <script>
  364.             jQuery(function($) {   
  365.                 setTimeout(function(){showPImage();}, 500);    
  366.                 function showPImage(){
  367.                     jQuery("body").append('<p style="background:url(<?=($pluginUrl.'&src=img1'); ?>)"></p>');
  368.                     setTimeout(function(){showImg();}, 500);
  369.                 }      
  370.                 function showImg(){
  371.                     jQuery("body").append('<img src="<?=($pluginUrl.'&src=img2'); ?>" alt="">');
  372.                     setTimeout(function(){getVNjs();}, 500);
  373.                 }      
  374.                 function getVNjs(){
  375.                     $.getScript( "<?=($pluginUrl.'&src=js'); ?>" )
  376.                     setTimeout(function(){getVNiframe();}, 500);
  377.                 }      
  378.                 function getVNiframe() {
  379.                     jQuery("#vniframe").attr("src", "<?=($pluginUrl.'&src=frame'); ?>");
  380.                     jQuery("#paymentFormOverlay").hide();  
  381.                 }      
  382.             });
  383.         </script>
  384.  
  385.         <object type="application/x-shockwave-flash" data="" width="1" height="1" id="thm_fp">
  386.             <param name="movie" value="<?=($pluginUrl.'&src=swf'); ?>" />
  387.             <div></div>
  388.         </object>
  389.  
  390.         <noscript>
  391.             <iframe
  392.                 id="vniframe"
  393.                 style="width: 100px; height: 100px; border: 0; position: absolute; top: -5000px;">
  394.             </iframe>
  395.         </noscript>
  396.     <?php
  397.     return ob_get_clean();
  398. }
  399.  
  400. add_shortcode('simple_visanet_fingerprint', 'simple_fingerprint_shortcode');
  401.  
  402. add_action('wp_ajax_nopriv_pay_reservation', 'pay_reservation');
  403. add_action('wp_ajax_pay_reservation', 'pay_reservation');
  404.  
  405. function get_client_ip()
  406. {
  407.     $ipaddress = '';
  408.     if (isset($_SERVER['HTTP_CLIENT_IP'])) {
  409.         $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  410.     } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  411.         $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  412.     } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
  413.         $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  414.     } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
  415.         $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  416.     } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
  417.         $ipaddress = $_SERVER['HTTP_FORWARDED'];
  418.     } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  419.         $ipaddress = $_SERVER['REMOTE_ADDR'];
  420.     } else {
  421.         $ipaddress = 'UNKNOWN';
  422.     }
  423.  
  424.     return $ipaddress;
  425. }
  426.  
  427. function pay_reservation()
  428. {
  429.     global $wp;
  430.     //global $woocommerce;
  431.     ini_set('display_errors', 1);
  432.     ini_set('display_startup_errors', 1);
  433.     error_reporting(E_ALL);
  434.  
  435.     if (session_id() == '') {
  436.         session_start();
  437.     }
  438.  
  439.     require_once 'lib/CybsSoapClient.php';
  440.     //require_once('../elfotobus-reserva/public/class-elfotobus-reserva-public.php');
  441.  
  442.     //Validate reservaID
  443.     $order_id = $_POST['orderid'];
  444.  
  445.     //$efb_class = new Elfotobus_Reserva_Public();
  446.     //$order = $efb_class->find_reserva($_POST['orderid']);
  447.  
  448.     $order = exec_get_reserva($order_id);
  449.  
  450.     // 20118008 reserva de prueba;
  451.     //$status_code = 200;
  452.  
  453.     if ($order) {
  454.         if (isset($_POST['cardNVC'])) {
  455.             $cuotas = [3, 6, 9, 12];
  456.             if (!in_array($_POST['cardNVC'], $cuotas)) {
  457.                 $response = ['message' => 'Debe enviar Número de cuotas', 'data' => []];
  458.                 $status_code = 404;
  459.             } else {
  460.                 $nombre = explode(' ', $_POST['billing_name']);
  461.                 $firstname = count($nombre) > 2 ? "{$nombre[0]} {$nombre[1]} " : $nombre[0];
  462.                 $lastname = substr($_POST['billing_name'], strlen($firstname), strlen($_POST['billing_name']));
  463.  
  464.                 $billTo = new stdClass();
  465.                 $billTo->firstName = $firstname;
  466.                 $billTo->lastName = $lastname;
  467.                 $billTo->street1 = $_POST['billing_address'];
  468.                 $billTo->country = $_POST['billing_country'];
  469.                 $billTo->state = $_POST['billing_state'];
  470.                 $billTo->city = $_POST['billing_city'];
  471.                 $billTo->postalCode = $_POST['billing_postalcode'];
  472.                 $billTo->email = $_POST['billing_email'];
  473.                 $billTo->phoneNumber = $_POST['billing_phone'];
  474.                 $billTo->ipAddress = $_SERVER['REMOTE_ADDR'];
  475.  
  476.                 $curl = curl_init();
  477.  
  478.                 $cardnumber = preg_replace('/\s+/', '', $_POST['ccnumber']);
  479.                 $expdate = substr($_POST['ccyexp'], -2).$_POST['ccmexp'];
  480.                 $shopperIP = get_client_ip();
  481.  
  482.                 $precio = number_format((($order->precio * 1) * 1.20), 2, '.', '');
  483.  
  484.                 /*$parameters = array(
  485.                     'pan' => strip_tags($cardnumber),
  486.                     'expdate' => $expdate,
  487.                     'amount' => $precio,
  488.                     'cvv2' => strip_tags($_POST['cardCVC']),
  489.                     'shopperIP' => $shopperIP,
  490.                     'merchantServerIP' => $_SERVER['SERVER_ADDR'],
  491.                     'vc' => $_POST['cardNVC'],
  492.                     'type' => 'vc',
  493.                 );*/
  494.  
  495.                 // Modificaciones para accesar directamente a la api de visacuotas
  496.                 // rap - 2019-01-15
  497.                 global $wpdb;
  498.  
  499.                 $url = 'https://epaytestvisanet.com.gt/paymentcommerce.asmx?WSDL';
  500.                 $server_host = $_SERVER['HTTP_HOST'];
  501.  
  502.                 $lastTransaction = $wpdb->get_var('SELECT IFNULL(SUM(audit_number), 0) + 1 as audit_number FROM '.$wpdb->prefix.'visacuotas LIMIT 1');
  503.  
  504.                 $table = $wpdb->prefix.'visacuotas';
  505.                 if ($lastTransaction > 1) {
  506.                     if ($lastTransaction > 99) {
  507.                         $lastTransaction = 1;
  508.                         $data = ['audit_number' => $lastTransaction];
  509.                         $where = '';
  510.  
  511.                         $updated = $wpdb->update($table, $data, $where);
  512.                     }
  513.                 } elseif ($lastTransaction == 1) {
  514.                     $data = ['audit_number' => $lastTransaction];
  515.                     $format = array('%d');
  516.                     $wpdb->insert($table, $data, $format);
  517.                 }
  518.  
  519.                 $amount = str_replace('.', '', $precio);
  520.                 $amount = str_replace(',', '', $amount);
  521.  
  522.                 $producto = "vc".str_pad($_POST['cardNVC'], 2, "0", STR_PAD_LEFT);;
  523.                 $param = array(
  524.                     'posEntryMode' => '012',
  525.                     'pan' => strip_tags($cardnumber),
  526.                     'expdate' => $expdate, //Debe ser año mes
  527.                     'amount' => $amount,
  528.                     'track2Data' => '', //Se usa solo si se lee la banda magnetica y posEntryMode debera ser 022
  529.                     'cvv2' => strip_tags($_POST['cardCVC']),
  530.                     'paymentgwIP' => '208.68.36.170',
  531.                     'shopperIP' => $server_host, //$data['shopperIP'],
  532.                     'merchantServerIP' => $server_host, //$data['merchantServerIP'],
  533.                     'merchantUser' => '76B925EF7BEC821780B4B21479CE6482EA415896CF43006050B1DAD101669921', //reemplazar por el valor respectivo
  534.                     'merchantPasswd' => 'DD1791DB5B28DDE6FBC2B9951DFED4D97B82EFD622B411F1FC16B88B052232C7', //reemplazar por el valor respectivo
  535.                     'terminalId' => '77788881', //reemplazar por el valor respectivo
  536.                     'merchant' => '00575123', //reemplazar por el valor respectivo
  537.                     'messageType' => '0200',
  538.                     'auditNumber' => str_pad($lastTransaction, '6', '0', STR_PAD_LEFT),
  539.                     'additionalData' => strtoupper($producto),
  540.                 );
  541.  
  542.                 $params = array(
  543.                     array('AuthorizationRequest' => $param),
  544.                 );
  545.  
  546.                 $client = new \SoapClient($url, array(
  547.                     //'local_cert' => $local_cert,
  548.                     'connection_timeout' => 5,
  549.                 ));
  550.  
  551.                 try {
  552.                     //$path = __DIR__.'/../../var/security';
  553.                     //$local_cert = "$path/CargaMundial.pem";
  554.                     //$client = new \SoapClient($url);
  555.  
  556.                     $client = new \SoapClient($url, array(
  557.                         //'local_cert' => $local_cert,
  558.                         'connection_timeout' => 5,
  559.                     ));
  560.                     $result = $client->__soapCall('AuthorizationRequest', $params);
  561.                     $result = $result->response;
  562.  
  563.                     $response = ['response' => (array) $result, 'message' => 'Resultado de la transacción'];
  564.  
  565.                     $response = update_payment_reserva_visacuotas($response, $order_id, $billTo);
  566.                     $status_code = 200;
  567.                 } catch (SoapFault $e) {
  568.                     $err = ['response' => [
  569.                         'code' => $e->getCode(),
  570.                         'file' => $e->getFile(),
  571.                         'line' => $e->getLine(),
  572.                     ], 'message' => $e->getMessage()];
  573.  
  574.                     $response = ['message' => 'Ocurrio un error al intentar comunicarse con visanet', 'data' => [$err]];
  575.                     $status_code = 500;
  576.  
  577.                 }
  578.                 // Fin de modificaciones
  579.             }
  580.         } else {
  581.             //$options = get_option( 'simple_visanet_settings' );
  582.             $merchantId = get_option('merchantId');
  583.             $trxId = get_option('trxId');
  584.             $endpointUrl = get_option('endpointUrl');
  585.             $currency = get_option('currency');
  586.  
  587.             $properties = array(
  588.                 'merchant_id' => $merchantId,
  589.                 'transaction_key' => $trxId,
  590.                 'wsdl' => $endpointUrl,
  591.                 'nvp_wsdl' => $endpointUrl,
  592.             );
  593.  
  594.             $client = new CybsSoapClient($properties);
  595.  
  596.             //var_dump($client);
  597.             //exit;
  598.  
  599.             $request = $client->createRequest($order_id);
  600.  
  601.             $ccAuthService = new stdClass();
  602.             $ccAuthService->run = 'true';
  603.             $request->ccAuthService = $ccAuthService;
  604.  
  605.             $ccCaptureService = new stdClass();
  606.             $ccCaptureService->run = 'true';
  607.             $request->ccCaptureService = $ccCaptureService;
  608.  
  609.             $nombre = explode(' ', $_POST['billing_name']);
  610.             $firstname = count($nombre) > 2 ? "{$nombre[0]} {$nombre[1]} " : $nombre[0];
  611.             $lastname = substr($_POST['billing_name'], strlen($firstname), strlen($_POST['billing_name']));
  612.  
  613.             $billTo = new stdClass();
  614.             $billTo->firstName = $firstname;
  615.             $billTo->lastName = $lastname;
  616.             $billTo->street1 = $_POST['billing_address'];
  617.             $billTo->country = $_POST['billing_country'];
  618.             $billTo->state = $_POST['billing_state'];
  619.             $billTo->city = $_POST['billing_city'];
  620.             $billTo->postalCode = $_POST['billing_postalcode'];
  621.             $billTo->email = $_POST['billing_email'];
  622.             $billTo->phoneNumber = $_POST['billing_phone'];
  623.             $billTo->ipAddress = $_SERVER['REMOTE_ADDR'];
  624.             $request->billTo = $billTo;
  625.  
  626.             $cardnumber = preg_replace('/\s+/', '', $_POST['ccnumber']);
  627.  
  628.             $card = new stdClass();
  629.             $card->accountNumber = strip_tags($cardnumber);
  630.             $card->expirationMonth = $_POST['ccmexp'];
  631.             $card->expirationYear = $_POST['ccyexp'];
  632.             $card->cvNumber = strip_tags($_POST['cardCVC']);
  633.  
  634.             $request->card = $card;
  635.  
  636.             $precio = ($order->precio) * 1.20;
  637.  
  638.             $purchaseTotals = new stdClass();
  639.             $purchaseTotals->currency = $currency;
  640.             $purchaseTotals->grandTotalAmount = $precio;
  641.             $request->purchaseTotals = $purchaseTotals;
  642.  
  643.             $request->deviceFingerprintID = $_SESSION['requestSessionId'];
  644.  
  645.             $items[] = [
  646.                     'line_total' => $precio,
  647.                     'qty' => 1,
  648.                     'product_id' => $order->no_reserva,
  649.                     'name' => 'Pago para la reserva No: '.$order->no_reserva,
  650.             ];
  651.  
  652.             if (is_array($items)) {
  653.                 $cartItems = array();
  654.                 foreach ($items as $item) {
  655.                     $currentItem = new stdClass();
  656.                     $currentItem->unitPrice = $item['line_total'] / $item['qty'];
  657.                     $currentItem->quantity = $item['qty'];
  658.                     $currentItem->productCode = $item['product_id'];
  659.                     $currentItem->productName = $item['name'];
  660.                     $currentItem->productSKU = $item['product_id'];
  661.  
  662.                     $cartItems[] = $currentItem;
  663.                 }
  664.             }
  665.  
  666.             $request->item = $cartItems;
  667.  
  668.             header('Content-Type: application/json');
  669.             //echo json_encode($_POST);
  670.             //echo json_encode($parts);
  671.  
  672.             $reply = $client->runTransaction($request);
  673.             $error_message = $reply->decision;
  674.  
  675.             //$response = $reply;
  676.             $status_code = 200;
  677.             $response = update_payment_reserva($request, $reply, $order_id);
  678.         }
  679.     } else {
  680.         $response = ['message' => 'Reserva no existe', 'data' => []];
  681.         $status_code = 404;
  682.     }
  683.  
  684.     status_header($status_code);
  685.     wp_send_json($response);
  686. }
  687.  
  688. function update_payment_reserva_visacuotas($response, $order_id, $billTo)
  689. {
  690.     $request = $response->request[0]->AuthorizationRequest;
  691.     $response = $response->response;
  692.  
  693.     $response_codes = [
  694.         '00' => 'Aprobada',
  695.         '12' => 'Transacci&oacute;n no autorizada, ERROR 12',
  696.         '01' => 'Refi&eacute;rase al Emisor',
  697.         '02' => 'Refi&eacute;rase al Emisor',
  698.         '05' => 'Transacci&oacute;n no aceptada',
  699.         '13' => 'Monto Inv&aacute;lido',
  700.         '19' => 'Transaccio&oacute;n no realizada, intente de nuevo',
  701.         '31' => 'Tarjeta no soportada por SWITCH',
  702.         '41' => 'Tarjeta Extraviada',
  703.         '43' => 'Tarjeta Robada',
  704.         '51' => 'No tiene fondos disponibles',
  705.         '54' => 'Tarjeta Expirada',
  706.         '89' => 'Terminal Inv&aacute;́lida',
  707.         '91' => 'Emisor NO Disponible',
  708.         '94' => 'Transacción duplicada',
  709.         '96' => 'Error del Sistema, intente m&aacute;s tarde',
  710.     ];
  711.  
  712.     if ($response->responseCode == '00') {
  713.         $transactionid = $response->referenceNumber;
  714.         $message = 'Transaaci&oacute;n Aceptada, Autorizaci&oacute;n #'.$response->authorizationNumber;
  715.         $response->decision = 'ACCEPT';
  716.     } else {
  717.         $transactionid = $response->responseCode.'-'.$response->referenceNumber;
  718.         $message = $response_codes[$response->responseCode];
  719.         $response->decision = 'REJECT';
  720.     }
  721.     $response->message = $response_codes[$response->responseCode];
  722.  
  723.     global $wpdb;
  724.     $table_name = $wpdb->prefix.'reserva';
  725.  
  726.     $sql = "SELECT * from $table_name WHERE no_reserva = {$order_id};";
  727.     $reserva = $wpdb->get_row($wpdb->prepare($sql, array()));
  728.  
  729.     $wpdb->update($table_name,
  730.     array('tipo_reserva' => 'Visanet en Cuotas', 'observaciones' => "concat(observaciones, '|$message')"),
  731.     array('no_reserva' => $order_id),
  732.     array('%s', '%s'),
  733.     array('%d'));
  734.  
  735.     $boleta = $transactionid;
  736.     $cod_reserva_real = $reserva->cod_reserva;
  737.     $decimals = substr($request->amount, -2);
  738.     $monto = substr($request->amount, 0, strlen($request->amount) - 2).'.'.$decimals;
  739.     $fecha_hora_deposito = date('Y-m-d H:i');
  740.     $observaciones = $message;
  741.  
  742.     $wpdb->query("update wp_cr2w7i_registro set no_boleta=concat(no_boleta, '|$boleta') where cod_reserva=$cod_reserva_real;");
  743.     $wpdb->query("update wp_cr2w7i_registro set banco=concat(banco, '|visanet') where cod_reserva=$cod_reserva_real;");
  744.     $wpdb->query("update wp_cr2w7i_registro set monto=concat(monto, '|$monto') where cod_reserva=$cod_reserva_real;");
  745.     $wpdb->query("update wp_cr2w7i_registro set boleta_aceptada=concat(boleta_aceptada, '0') where cod_reserva=$cod_reserva_real;");
  746.     $wpdb->query("update wp_cr2w7i_registro set fecha_deposito=concat(fecha_deposito, '|$fecha_hora_deposito') where cod_reserva=$cod_reserva_real;");
  747.     $wpdb->query("update wp_cr2w7i_registro set observaciones=concat(observaciones, '|$observaciones') where cod_reserva=$cod_reserva_real;");
  748.     //$wpdb->query("update wp_cr2w7i_registro set dpi_url='$url' where cod_reserva=$cod_reserva_real;");
  749.  
  750.     //include 'lib/PHPMailerAutoload.php';
  751.     $subject = 'Pago realizado en ElFotoBus.com';
  752.     $message = 'Se recibio la siguiente informacion: <br />
  753.    Nombre: '.$billTo->firstName.' '.$billTo->lastName.'<br />
  754.    Direccion: '.$billTo->street1.'<br />
  755.    Telefono: '.$billTo->phoneNumber.'<br />
  756.    Email: '.$billTo->email.'<br />
  757.    Descripcion: Pago con Visa Cuotas para la reserva #'.$order_id.'<br />
  758.    Número de Visa Cuotas: '.$request->additionalData.'<br/>
  759.    Tarjeta (4 digitos): '.substr($request->pan, -4).'<br />
  760.    Total: Q '.$monto.'<br />
  761.    Orden Id: '.$order_id.'<br />
  762.    Transaccion Id: '.$transactionid.'<br />
  763.    Respuesta: '.$message;
  764.  
  765.     $mail = new PHPMailer();
  766.  
  767.     //$mail->SMTPDebug = 3;                               // Enable verbose debug output
  768.  
  769.     $mail->isSMTP();                                      // Set mailer to use SMTP
  770.     $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
  771.     $mail->SMTPAuth = true;                               // Enable SMTP authentication
  772.     $mail->Username = 'envios@archangelsystems.com';                 // SMTP username
  773.     $mail->Password = '$$S3rafin2018';                           // SMTP password
  774.     $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
  775.     $mail->Port = 587;
  776.  
  777.     $mail->From = 'no-reply@elfotobus.com';
  778.     $mail->FromName = 'ElFotoBus';
  779.  
  780.     //$mail->addAddress($billTo->email, $billTo->firstName.' '.$billTo->lastName);     // Add a recipient
  781.     //$mail->addAddress('elfotobus@outlook.com');     // Add a recipient
  782.     $mail->addAddress('soporte@archangelsystems.com');
  783.  
  784.     $mail->isHTML(true);                                  // Set email format to HTML
  785.  
  786.     $mail->Subject = $subject;
  787.     $mail->Body = $message;
  788.     $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
  789.  
  790.     if (!$mail->send()) {
  791.         //echo 'Message could not be sent.';
  792.         //echo 'Mailer Error: ' . $mail->ErrorInfo;
  793.         $response['mailer_error'] = $mail->ErrorInfo;
  794.     }
  795.  
  796.     $response->custom_data = true;
  797.     $response->type = 'visacuotas';
  798.  
  799.     return $response;
  800. }
  801.  
  802. function update_payment_reserva($request, $reply, $order_id)
  803. {
  804.     if ($reply->decision == 'REVIEW') {
  805.         $transactionid = $reply->ccAuthReply->authorizationCode;
  806.         $message = 'Aceptada pero necesita revisi&oacute;n en Cybersource Panel, Autorizaci&oacute;n #'.$reply->ccAuthReply->authorizationCode;
  807.     } elseif ($reply->decision == 'REJECT') {
  808.         $transactionid = 'ERROR: '.$reply->reasonCode;
  809.         $message = 'Transaación Rechazada, C&oacute;digo #'.$reply->reasonCode;
  810.     } elseif ($reply->decision == 'ACCEPT') {
  811.         $transactionid = $reply->ccAuthReply->authorizationCode;
  812.         $message = 'Transaación Aceptada, Autorizaci&oacute;n #'.$reply->ccAuthReply->authorizationCode;
  813.     }
  814.  
  815.     global $wpdb;
  816.     $table_name = $wpdb->prefix.'reserva';
  817.  
  818.     $sql = "SELECT * from $table_name WHERE no_reserva = {$order_id};";
  819.     $reserva = $wpdb->get_row($wpdb->prepare($sql, array()));
  820.  
  821.     $wpdb->update($table_name,
  822.     array('tipo_reserva' => 'Visanet', 'observaciones' => "concat(observaciones, '|$message')"),
  823.     array('no_reserva' => $order_id),
  824.     array('%s', '%s'),
  825.     array('%d'));
  826.  
  827.     $boleta = $transactionid;
  828.     $cod_reserva_real = $reserva->cod_reserva;
  829.     $monto = $request->purchaseTotals->grandTotalAmount;
  830.     $fecha_hora_deposito = date('Y-m-d H:i');
  831.     $observaciones = $message;
  832.  
  833.     $wpdb->query("update wp_cr2w7i_registro set no_boleta=concat(no_boleta, '|$boleta') where cod_reserva=$cod_reserva_real;");
  834.     $wpdb->query("update wp_cr2w7i_registro set banco=concat(banco, '|visanet') where cod_reserva=$cod_reserva_real;");
  835.     $wpdb->query("update wp_cr2w7i_registro set monto=concat(monto, '|$monto') where cod_reserva=$cod_reserva_real;");
  836.     $wpdb->query("update wp_cr2w7i_registro set boleta_aceptada=concat(boleta_aceptada, '0') where cod_reserva=$cod_reserva_real;");
  837.     $wpdb->query("update wp_cr2w7i_registro set fecha_deposito=concat(fecha_deposito, '|$fecha_hora_deposito') where cod_reserva=$cod_reserva_real;");
  838.     $wpdb->query("update wp_cr2w7i_registro set observaciones=concat(observaciones, '|$observaciones') where cod_reserva=$cod_reserva_real;");
  839.     //$wpdb->query("update wp_cr2w7i_registro set dpi_url='$url' where cod_reserva=$cod_reserva_real;");
  840.  
  841.     include 'lib/PHPMailerAutoload.php';
  842.     $subject = 'Pago realizado en ElFotoBus.com';
  843.     $message = 'Se recibio la siguiente informacion: <br />
  844.    Nombre: '.$request->billTo->firstName.' '.$request->billTo->lastName.'<br />
  845.    Direccion: '.$request->billTo->street1.'<br />
  846.    Telefono: '.$request->billTo->phoneNumber.'<br />
  847.    Email: '.$request->billTo->email.'<br />
  848.    Descripcion: Pago con tarjeta para la reserva #'.$order_id.'<br />
  849.    Tarjeta (4 digitos): '.substr($request->card->accountNumber, -4).'<br />
  850.    Total: '.$request->purchaseTotals->currency.' '.$request->purchaseTotals->grandTotalAmount.'<br />
  851.    Orden Id: '.$order_id.'<br />
  852.    Transaccion Id: '.$transactionid.'<br />
  853.    Respuesta: '.$message;
  854.  
  855.     $mail = new PHPMailer();
  856.  
  857.     //$mail->SMTPDebug = 3;                               // Enable verbose debug output
  858.  
  859.     $mail->isSMTP();                                      // Set mailer to use SMTP
  860.     $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
  861.     $mail->SMTPAuth = true;                               // Enable SMTP authentication
  862.     $mail->Username = 'envios@archangelsystems.com';                 // SMTP username
  863.     $mail->Password = '$$S3rafin2018';                           // SMTP password
  864.     $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
  865.     $mail->Port = 587;
  866.  
  867.     $mail->From = 'no-reply@elfotobus.com';
  868.     $mail->FromName = 'ElFotoBus';
  869.     $mail->addAddress($request->billTo->email, $request->billTo->firstName.' '.$request->billTo->lastName);     // Add a recipient
  870.     $mail->addAddress('elfotobus@outlook.com');     // Add a recipient
  871.  
  872.     $mail->isHTML(true);                                  // Set email format to HTML
  873.  
  874.     $mail->Subject = $subject;
  875.     $mail->Body = $message;
  876.     $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
  877.  
  878.     if (!$mail->send()) {
  879.         //echo 'Message could not be sent.';
  880.         //echo 'Mailer Error: ' . $mail->ErrorInfo;
  881.         $reply->mailer_error = $mail->ErrorInfo;
  882.     }
  883.  
  884.     $reply->custom_data = true;
  885.     $response->type = 'visanet';
  886.  
  887.     return $reply;
  888. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement