public function process()
    {
        if (empty($this->context->cart->id)) {
            Tools::redirect('/');
        }
        parent::process();
        $params = $this->initParams();
        // url para re intentos de pago
        $url_reintento = $_SERVER['HTTP_REFERER'];
        if (!strpos($_SERVER['HTTP_REFERER'], 'step=3')) {
            if (!strpos($_SERVER['HTTP_REFERER'], '?')) {
                $url_reintento .= '?step=3';
            } else {
                $url_reintento .= '&step=3';
            }
        }
        // vaciar errores en el intento de pago anterior
        if (isset($this->context->cookie->{'error_pay'})) {
            unset($this->context->cookie->{'error_pay'});
        }
        if (isset($_POST['pagar_baloto'])) {
            $conf = new ConfPayu();
            if ($conf->exist_cart_in_pagos($this->context->cart->id)) {
                if (isset($this->context->cookie->{'url_confirmation'})) {
                    Tools::redirectLink(json_decode($this->context->cookie->{'url_confirmation'}));
                }
                Tools::redirectLink('/');
                exit;
            }
            $id_cart = $this->context->cart->id;
            $id_address = $this->context->cart->id_address_delivery;
            $customer = new Customer((int) $this->context->cart->id_customer);
            $reference_code = $customer->id . '_' . $id_cart . '_0_' . $id_address;
            $address = $conf->get_address($this->context->cart->id_customer, $this->context->cart->id_address_delivery);
            $fecha = date('Y-m-j');
            $nuevafecha = strtotime('+3 day', strtotime($fecha));
            $fechaBaloto = date('Y-m-d', $nuevafecha) . 'T' . date('h:i:s', $nuevafecha);
            $keysPayu = $conf->keys();
            $intentos = $conf->count_pay_cart($id_cart);
            // Script Json payuLatam (Baloto)
            $data = '{
"language":"es",
"command":"SUBMIT_TRANSACTION",
"merchant":{
"apiLogin":"******",
"apiKey":"' . $keysPayu['apiKey'] . '"
},
"transaction":{
"order":{
"accountId":"' . $keysPayu['accountId'] . '",
"referenceCode":"' . $params[2]['referenceCode'] . '_' . $intentos . '",
"description":"' . $reference_code . '",
"language":"es",
"notifyUrl":"' . $conf->urlv() . '",
"signature":"' . $conf->sing($params[2]['referenceCode'] . '_' . $intentos . '~' . $params[4]['amount'] . '~' . $params[9]['currency']) . '",
"shippingAddress":{
"country":"' . $address['iso_code'] . '"
},
"buyer":{
"fullName":"' . $this->context->customer->firstname . ' ' . $this->context->customer->lastname . '",
"emailAddress":"' . $params[5]['buyerEmail'] . '",
"dniNumber":"' . $address['dni'] . '",
"shippingAddress":{
"street1":"' . $address['address1'] . '",
"city":"' . $address['city'] . '",
"state":"' . $address['state'] . '",
"country":"' . $address['iso_code'] . '",
"phone":"' . $address['phone_mobile'] . '"
}
},
"additionalValues":{
"TX_VALUE":{
"value":' . $params[4]['amount'] . ',
"currency":"' . $params[9]['currency'] . '"
}
}
},
"type":"AUTHORIZATION_AND_CAPTURE",
"paymentMethod":"BALOTO",
"expirationDate":"' . $fechaBaloto . '",
"paymentCountry": "' . $address['iso_code'] . '"     
},
"test":false
}
';
            $response = $conf->sendJson($data);
            // colector Errores Payu
            $error_pay = array();
            if ($response['code'] === 'ERROR') {
                $conf->error_payu(0, $customer->id, $data, $response, 'Baloto', $response['transactionResponse']['state'], $this->context->cart->id, $id_address);
                $error_pay[] = $response;
            } elseif ($response['code'] === 'SUCCESS' && $response['transactionResponse']['state'] === 'PENDING' && $response['transactionResponse']['responseMessage'] != 'ERROR_CONVERTING_TRANSACTION_AMOUNTS') {
                $extra_vars = array('method' => 'Baloto', 'cod_pago' => $response['transactionResponse']['extraParameters']['REFERENCE'], 'fechaex' => date('d/m/Y', substr($response['transactionResponse']['extraParameters']['EXPIRATION_DATE'], 0, -3)));
                $this->createPendingOrder($extra_vars, 'Baloto', utf8_encode($conf->getMessagePayu($response['transactionResponse']['responseCode'])), 'PAYU_OS_PENDING');
                $order = $conf->get_order($id_cart);
                $extras = $response['transactionResponse']['extraParameters']['REFERENCE'] . ';' . date('d/m/Y', substr($response['transactionResponse']['extraParameters']['EXPIRATION_DATE'], 0, -3));
                $conf->pago_payu($order['id_order'], $customer->id, $data, $response, 'Baloto', $extras, $id_cart, $id_address);
                $orden_select = $order['id_order'];
                $payulatam = new PayULatam();
                $url_base64 = strtr(base64_encode($response['transactionResponse']['extraParameters']['URL_PAYMENT_RECEIPT_HTML']), '+/=', '-_,');
                $url_confirmation = __PS_BASE_URI__ . 'order-confirmation.php?key=' . $customer->secure_key . '&id_cart=' . (int) $id_cart . '&id_module=' . (int) $payulatam->id . '&id_order=' . (int) $orden_select . '&URL_PAYMENT_RECEIPT_HTML=' . $url_base64;
                $this->context->cookie->{'url_confirmation'} = json_encode($url_confirmation);
                Tools::redirectLink($url_confirmation);
            } else {
                $conf->error_payu(0, $customer->id, $data, $response, 'Baloto', $response['transactionResponse']['state'], $this->context->cart->id, $id_address);
                $error_pay[] = array('ERROR' => utf8_encode($conf->getMessagePayu($response['transactionResponse']['responseCode'])));
            }
            $this->context->cookie->{'error_pay'} = json_encode($error_pay);
            Tools::redirectLink($url_reintento);
            exit;
        } else {
            $this->context->cookie->{'error_pay'} = json_encode(array('ERROR' => 'Valida tus datos he intenta de nuevo.'));
            Tools::redirectLink($url_reintento);
            exit;
        }
    }
 public function getByReference($reference)
 {
     $conf = new ConfPayu($this->url_reports);
     $keysPayu = $conf->keys();
     $data = '{
       "test":';
     if ($conf->isTest()) {
         $data .= 'true';
     } else {
         $data .= 'false';
     }
     $data .= ',
       "language":"es",
       "command":"ORDER_DETAIL_BY_REFERENCE_CODE",
       "merchant":{
                   "apiLogin":"******",
                   "apiKey":"' . $keysPayu['apiKey'] . '"
     },
       "details":{
       "referenceCode":"' . $reference . '"
       }
     }';
     $response = $conf->sendJson($data);
     return $response;
 }
    public function process()
    {
        if (empty($this->context->cart->id)) {
            Tools::redirect('/');
        }
        //exit(print_r($_POST,TRUE));
        if (isset($_POST['numerot']) && !empty($_POST['numerot']) && strlen($_POST['numerot']) > 13 && strlen((int) $_POST['numerot']) < 17 && isset($_POST['nombre']) && !empty($_POST['nombre']) && isset($_POST['codigot']) && !empty($_POST['codigot']) && isset($_POST['Month']) && !empty($_POST['Month']) && isset($_POST['year']) && !empty($_POST['year']) && isset($_POST['cuotas']) && !empty($_POST['cuotas']) || isset($_POST['token_id']) && !empty($_POST['token_id']) && isset($_POST['openpay_device_session_id']) && !empty($_POST['openpay_device_session_id'])) {
            parent::process();
            // url para re intentos de pago
            $url_reintento = $_SERVER['HTTP_REFERER'];
            if (!strpos($_SERVER['HTTP_REFERER'], 'step=3')) {
                if (!strpos($_SERVER['HTTP_REFERER'], '?')) {
                    $url_reintento .= '?step=3';
                } else {
                    $url_reintento .= '&step=3';
                }
            }
            // vaciar errores en el intento de pago anterior
            if (isset($this->context->cookie->{'error_pay'})) {
                unset($this->context->cookie->{'error_pay'});
            }
            $params = $this->initParams();
            // se optinen los datos del formulario de pago farmalisto
            $post = array('nombre' => Tools::getValue('nombre') ? Tools::getValue('nombre') : Tools::getValue('holder'), 'numerot' => Tools::getValue('numerot') ? Tools::getValue('numerot') : Tools::getValue('card'), 'codigot' => Tools::getValue('codigot') ? Tools::getValue('codigot') : Tools::getValue('cvv'), 'date' => Tools::getValue('year') . '/' . Tools::getValue('Month'), 'cuotas' => Tools::getValue('cuotas'), 'Month' => Tools::getValue('Month'), 'year' => Tools::getValue('Year'));
            $conf = new ConfPayu();
            if ($conf->exist_cart_in_pagos($this->context->cart->id)) {
                if (isset($this->context->cookie->{'url_confirmation'})) {
                    Tools::redirectLink(json_decode($this->context->cookie->{'url_confirmation'}));
                }
                Tools::redirectLink('/');
                exit;
            }
            $keysPayu = $conf->keys();
            $address = new Address($this->context->cart->id_address_delivery);
            $id_order = 0;
            $customer = new Customer((int) $this->context->cart->id_customer);
            $id_cart = $this->context->cart->id;
            $id_address = $this->context->cart->id_address_delivery;
            $dni = $conf->get_dni($this->context->cart->id_address_delivery);
            $reference_code = $customer->id . '_' . $id_cart . '_' . $id_order . '_' . $id_address;
            $_deviceSessionId = NULL;
            if (isset($this->context->cookie->deviceSessionId) && !empty($this->context->cookie->deviceSessionId) && strlen($this->context->cookie->deviceSessionId) === 32) {
                $_deviceSessionId = $this->context->cookie->deviceSessionId;
            } elseif (isset($_POST['deviceSessionId']) && !empty($_POST['deviceSessionId']) && strlen($_POST['deviceSessionId']) === 32) {
                $_deviceSessionId = $_POST['deviceSessionId'];
            } else {
                $_deviceSessionId = md5($this->context->cookie->timestamp);
            }
            $intentos = $conf->count_pay_cart($id_cart);
            $paymentMethod = $this->getFranquicia($post['numerot'], 'payulatam');
            $currency = '';
            if ($conf->isTest()) {
                $currency = 'USD';
            } else {
                $currency = $params[9]['currency'];
            }
            $data = '{
       "language":"es",
       "command":"SUBMIT_TRANSACTION",
       "merchant":{
          "apiKey":"' . $keysPayu['apiKey'] . '",
          "apiLogin":"******"
       },
       "transaction":{
         
          "order":{
             "accountId":"' . $keysPayu['accountId'] . '",
             "referenceCode":"' . $params[2]['referenceCode'] . '_' . $intentos . '",
             "description":"' . $reference_code . '",
             "language":"' . $params[10]['lng'] . '",
             "notifyUrl":"' . $conf->urlv() . '",
             "signature":"' . $conf->sing($params[2]['referenceCode'] . '_' . $intentos . '~' . $params[4]['amount'] . '~' . $currency) . '",
             "additionalValues":{
                "TX_VALUE":{
                   "value":' . $params[4]['amount'] . ',
                   "currency":"' . $currency . '"
                }
             },
             
           "buyer": {
                "fullName": "' . $customer->firstname . ' ' . $customer->lastname . '",
                "contactPhone": "' . $address->phone_mobile . '",
                 "emailAddress":"' . $params[5]['buyerEmail'] . '",
                 "dniNumber":"' . $dni . '",   
                 "shippingAddress": {
                 "street1": "' . $address->address1 . '",
                 "street2":"N/A",    
                 "city": "' . $address->city . '",
                 "state": "' . $conf->get_state($address->id_state) . '",
                 "country": "';
            if ($conf->isTest()) {
                $data .= 'PA';
            } else {
                $data .= $this->context->country->iso_code;
            }
            $data .= '",
                 "postalCode": "' . $address->postcode . '",
                 "phone": "' . $address->phone . '"
                }
             },      
            
        "shippingAddress":{
            "street1":"' . $address->address1 . '",
            "street2":"N/A",
            "city":"' . $address->city . '",
            "state":"' . $conf->get_state($address->id_state) . '",
            "country":"';
            if ($conf->isTest()) {
                $data .= 'PA';
            } else {
                $data .= $this->context->country->iso_code;
            }
            $data .= '",
            "postalCode":"' . $address->postcode . '",
            "phone":"' . $address->phone . '"
        }  
          },
          "payer":{

        "fullName":"' . $customer->firstname . ' ' . $customer->lastname . '",
        "emailAddress":"' . $params[5]['buyerEmail'] . '",
        "contactPhone":"' . $address->phone_mobile . '",
        "dniNumber":"' . $dni . '",
        "billingAddress":{
            "street1":"' . $address->address1 . '",
            "street2":"N/A",
            "city":"' . $address->city . '",
            "state":"' . $conf->get_state($address->id_state) . '",
            "country":"';
            if ($conf->isTest()) {
                $data .= 'PA';
            } else {
                $data .= $this->context->country->iso_code;
            }
            $data .= '",
            "postalCode":"' . $address->postcode . '",
            "phone":"' . $address->phone . '"
          }      
        },
          "creditCard":{
             "number":"' . $post['numerot'] . '",
             "securityCode":"' . $post['codigot'] . '",
             "expirationDate":"' . $post['date'] . '",
             "name":"';
            if ($conf->isTest()) {
                $data .= 'APPROVED';
            } else {
                $data .= $post['nombre'];
            }
            $data .= '"
          },
          
            "extraParameters":{
              "INSTALLMENTS_NUMBER":' . $post['cuotas'] . '
            },
            "type":"AUTHORIZATION_AND_CAPTURE",
            "paymentMethod":"' . $paymentMethod . '",
            "paymentCountry":"';
            if ($conf->isTest()) {
                $data .= 'PA';
            } else {
                $data .= $this->context->country->iso_code;
            }
            $data .= '",
            "deviceSessionId": "' . $_deviceSessionId . '",
            "ipAddress": "' . $_SERVER['REMOTE_ADDR'] . '",
            "userAgent": "' . $_SERVER['HTTP_USER_AGENT'] . '",
            "cookie": "' . md5($this->context->cookie->timestamp) . '"  
       },
       "test":';
            if ($conf->isTest()) {
                $data .= 'true';
            } else {
                $data .= 'false';
            }
            $data .= '          
    }
    ';
            $response = $conf->sendJson($data);
            $subs = substr($post['numerot'], 0, strlen($post['numerot']) - 4);
            $nueva = '';
            for ($i = 0; $i <= strlen($subs); $i++) {
                $nueva = $nueva . '*';
            }
            $data = str_replace('"number":"' . $subs, '"number":"' . $nueva, $data);
            $data = str_replace('"securityCode":"' . $post['codigot'], '"securityCode":"' . '****', $data);
            // colector Errores Payu
            $error_pay = array();
            if ($response['code'] === 'ERROR') {
                $conf->error_payu($id_order, $customer->id, $data, $response, 'Tarjeta_credito', $response['transactionResponse']['state'], $this->context->cart->id, $id_address);
                $error_pay[] = $response;
            } elseif ($response['code'] === 'SUCCESS' && ($response['transactionResponse']['state'] === 'PENDING' || $response['transactionResponse']['state'] === 'APPROVED') && $response['transactionResponse']['responseMessage'] != 'ERROR_CONVERTING_TRANSACTION_AMOUNTS') {
                $conf->pago_payu($id_order, $customer->id, $data, $response, 'Tarjeta_credito', $response['transactionResponse']['state'], $this->context->cart->id, $id_address);
                if ($response['transactionResponse']['state'] === 'APPROVED') {
                    //
                    $this->createPendingOrder(array(), 'Tarjeta_credito', utf8_encode($conf->getMessagePayu($response['transactionResponse']['responseCode'])), 'PS_OS_PAYMENT');
                } else {
                    $this->createPendingOrder(array(), 'Tarjeta_credito', utf8_encode($conf->getMessagePayu($response['transactionResponse']['responseCode'])), 'PAYU_OS_PENDING');
                }
                $order = $conf->get_order($id_cart);
                $id_order = $order['id_order'];
                $payulatam = new PayULatam();
                $url_confirmation = __PS_BASE_URI__ . 'order-confirmation.php?key=' . $customer->secure_key . '&id_cart=' . (int) $this->context->cart->id . '&id_module=' . (int) $payulatam->id . '&id_order=' . (int) $order['id_order'];
                $this->context->cookie->{'url_confirmation'} = json_encode($url_confirmation);
                Tools::redirectLink($url_confirmation);
                exit;
            } else {
                $conf->error_payu($id_order, $customer->id, $data, $response, 'Tarjeta_credito', $response['transactionResponse']['state'], $this->context->cart->id, $id_address);
                $error_pay[] = array('ERROR' => utf8_encode($conf->getMessagePayu($response['transactionResponse']['responseCode'])));
            }
            $this->context->cookie->{'error_pay'} = json_encode($error_pay);
            Tools::redirectLink($url_reintento);
            exit;
            //$conf->getMessagePayu($response['transactionResponse']['responseCode'])
        } else {
            $this->context->cookie->{'error_pay'} = json_encode(array('ERROR' => 'Valida tus datos he intenta de nuevo.'));
            Tools::redirectLink($url_reintento);
            exit;
        }
    }
    public function process()
    {
        if (empty($this->context->cart->id)) {
            Tools::redirect('/');
        }
        parent::process();
        // url para re intentos de pago
        $url_reintento = $_SERVER['HTTP_REFERER'];
        if (!strpos($_SERVER['HTTP_REFERER'], 'step=3')) {
            if (!strpos($_SERVER['HTTP_REFERER'], '?')) {
                $url_reintento .= '?step=3';
            } else {
                $url_reintento .= '&step=3';
            }
        }
        // vaciar errores en el intento de pago anterior
        if (isset($this->context->cookie->{'error_pay'})) {
            unset($this->context->cookie->{'error_pay'});
        }
        if (isset($_POST['pse_bank']) && isset($_POST['name_bank']) && !empty($_POST['pse_bank'])) {
            // reglas de carrito para bines
            $payulatam = new PayULatam();
            $params = $this->initParams();
            $conf = new ConfPayu();
            $keysPayu = $conf->keys();
            $customer = new Customer((int) $this->context->cart->id_customer);
            $id_cart = $this->context->cart->id;
            $id_address = $this->context->cart->id_address_delivery;
            //$this->createPendingOrder();
            //$order = $conf->get_order($id_cart);
            $id_order = 0;
            //$order['id_order'];
            $description = $customer->id . '_' . $id_cart . '_' . $id_order . '_' . $id_address;
            $varRandn = $conf->randString();
            $varRandc = $conf->randString();
            setcookie($varRandn, $varRandc, time() + 900);
            $browser = array('ipAddress' => $_SERVER['SERVER_ADDR'], 'userAgent' => $_SERVER['HTTP_USER_AGENT']);
            $address = new Address($this->context->cart->id_address_delivery);
            $dni = $conf->get_dni($this->context->cart->id_address_delivery);
            $intentos = $conf->count_pay_cart($id_cart);
            $currency = '';
            if ($conf->isTest()) {
                $currency = 'USD';
            } else {
                $currency = $params[9]['currency'];
            }
            $url = '';
            if (Configuration::get('PS_SSL_ENABLED') || !empty($_SERVER['HTTPS']) && Tools::strtolower($_SERVER['HTTPS']) != 'off') {
                if (method_exists('Tools', 'getShopDomainSsl')) {
                    $url = 'https://' . Tools::getShopDomainSsl() . __PS_BASE_URI__ . 'modules/' . $payulatam->name . '/';
                } else {
                    $url = 'https://' . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . 'modules/' . $payulatam->name . '/';
                }
            } else {
                $url = 'http://' . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . 'modules/' . $payulatam->name . '/';
            }
            $reference_code = $params[2]['referenceCode'] . '_' . $intentos;
            $token_orden = md5($reference_code);
            $data = '{
"test":false,
"language":"es",
"command":"SUBMIT_TRANSACTION",
"merchant":{
"apiLogin":"******",
"apiKey":"' . $keysPayu['apiKey'] . '"
},
"transaction":{
"order":{
"accountId":"' . $keysPayu['pse-CO'] . '",
"referenceCode":"' . $reference_code . '",
"description":"' . $description . '",
"language":"es",
"notifyUrl":"' . $conf->urlv() . '",
"signature":"' . $conf->sing($params[2]['referenceCode'] . '_' . $intentos . '~' . $params[4]['amount'] . '~' . $currency) . '",
"buyer":{
"fullName":"' . $this->context->customer->firstname . ' ' . $this->context->customer->lastname . '",
"emailAddress":"' . $params[5]['buyerEmail'] . '",
"dniNumber":"' . $dni . '",
"shippingAddress":{
"street1":"' . $address->address1 . '",
"city":"' . $address->city . '",
"state":"' . $conf->get_state($address->id_state) . '",
"country":"' . $this->context->country->iso_code . '",
"phone":"' . $address->phone . '"
}
},
"additionalValues":{
"TX_VALUE":{
"value":' . $params[4]['amount'] . ',
"currency":"' . $currency . '"
}
}
},
"payer":{
"fullName":"' . $this->context->customer->firstname . ' ' . $this->context->customer->lastname . '",
"emailAddress":"' . $params[5]['buyerEmail'] . '",
"dniNumber":"' . $dni . '",
"contactPhone":"' . $address->phone . '"
},
"ipAddress":"' . $browser['ipAddress'] . '",
"cookie":"' . $varRandn . '",
"userAgent":"' . $browser['userAgent'] . '",
"type":"AUTHORIZATION_AND_CAPTURE",
"paymentMethod":"PSE",
"extraParameters":{
"PSE_REFERENCE1":"' . $browser['ipAddress'] . '",
"FINANCIAL_INSTITUTION_CODE":"' . $_POST['pse_bank'] . '",
"FINANCIAL_INSTITUTION_NAME":"' . $_POST['name_bank'] . '",
"USER_TYPE":"' . $_POST['pse_tipoCliente'] . '",
"PSE_REFERENCE2":"' . $_POST['pse_docType'] . '",
"PSE_REFERENCE3":"' . $_POST['pse_docNumber'] . '",
"RESPONSE_URL": "' . $url . 'url_confirm.php?token=' . $token_orden . '"
}
}
}
';
            $response = $conf->sendJson($data);
            if ($response['code'] === 'ERROR') {
                $conf->error_payu($id_order, $customer->id, $data, $response, 'PSE', $response['transactionResponse']['state'], $this->context->cart->id, $id_address);
                $error_pay[] = $response;
            } elseif ($response['code'] === 'SUCCESS' && $response['transactionResponse']['state'] === 'PENDING' && $response['transactionResponse']['responseMessage'] != 'ERROR_CONVERTING_TRANSACTION_AMOUNTS') {
                $this->createPendingOrder(array(), 'PSE', utf8_encode($conf->getMessagePayu($response['transactionResponse']['responseCode'])), 'PAYU_OS_PENDING');
                $order = $conf->get_order($id_cart);
                $id_order = $order['id_order'];
                $conf->pago_payu($id_order, $customer->id, $data, $response, 'Pse', $response['code'], $id_cart, $id_address);
                $url_base64 = strtr(base64_encode($response['transactionResponse']['extraParameters']['BANK_URL']), '+/=', '-_,');
                $string_send = __PS_BASE_URI__ . 'order-confirmation.php?key=' . $customer->secure_key . '&id_cart=' . (int) $id_cart . '&id_module=' . (int) $payulatam->id . '&id_order=' . (int) $order['id_order'] . '&bankdest2=' . $url_base64;
                $conf->url_confirm_payu($token_orden, __PS_BASE_URI__ . 'order-confirmation.php?key=' . $customer->secure_key . '&id_cart=' . (int) $id_cart . '&id_module=' . (int) $payulatam->id . '&id_order=' . (int) $order['id_order']);
                Tools::redirectLink($string_send);
                exit;
            } else {
                $conf->error_payu($id_order, $customer->id, $data, $response, 'PSE', $response['transactionResponse']['state'], $this->context->cart->id, $id_address);
                $error_pay[] = array('ERROR' => utf8_encode($conf->getMessagePayu($response['transactionResponse']['responseCode'])));
            }
            $this->context->cookie->{'error_pay'} = json_encode($error_pay);
            Tools::redirectLink($url_reintento);
            exit;
        } else {
            $this->context->cookie->{'error_pay'} = json_encode(array('ERROR' => 'Valida tus datos he intenta de nuevo.'));
            Tools::redirectLink($url_reintento);
            exit;
        }
    }