/**
  * returns API response array()
  */
 public static function restApi($action = null, $data = null)
 {
     try {
         $hipay = new HiPay_Tpp();
         HipayLogger::addLog($hipay->l('API call initiated', 'hipay'), HipayLogger::APICALL, 'Action : ' . $action . ' - Data : ' . Tools::jsonEncode($data));
         if ($action == null) {
             Tools::redirect('index.php?controller=order&xer=6');
         }
         if ($data == null) {
             Tools::redirect('index.php?controller=order&xer=7');
         }
         define('API_ENDPOINT', HipayClass::getAPIURL());
         define('API_USERNAME', HipayClass::getAPIUsername());
         define('API_PASSWORD', HipayClass::getAPIPassword());
         $credentials = API_USERNAME . ':' . API_PASSWORD;
         $resource = API_ENDPOINT . $action;
         // create a new cURL resource
         $curl = curl_init();
         // set appropriate options
         $options = array(CURLOPT_URL => $resource, CURLOPT_USERPWD => $credentials, CURLOPT_HTTPHEADER => array('Accept: application/json'), CURLOPT_RETURNTRANSFER => true, CURLOPT_FAILONERROR => false, CURLOPT_HEADER => false, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $data, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false);
         foreach ($options as $option => $value) {
             curl_setopt($curl, $option, $value);
         }
         $result = curl_exec($curl);
         $status = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
         $response = Tools::jsonDecode($result);
         // execute the given cURL session
         if (false === $result) {
             $errorCurl = curl_error($curl);
             throw new Exception('Curl error: ' . $errorCurl);
         }
         if (floor($status / 100) != 2) {
             throw new Exception('Hipay message: ' . $response->message, $response->code);
         }
         curl_close($curl);
         HipayLogger::addLog($hipay->l('API call success', 'hipay'), HipayLogger::APICALL, 'Appel vers API avec success : ' . Tools::jsonEncode($response));
         return $response;
     } catch (Exception $e) {
         HipayLogger::addLog($hipay->l('API call error', 'hipay'), HipayLogger::ERROR, $e->getMessage());
         return $e;
     }
 }
 /**
  * returns API response array()
  */
 public static function restMaintenanceApi($transaction_reference = null, $data = null)
 {
     try {
         $hipay = new HiPay_Tpp();
         HipayLogger::addLog($hipay->l('API Refund call initiated', 'hipay'), HipayLogger::APICALL, 'Transaction_reference : ' . $transaction_reference . ' - Data : ' . Tools::jsonEncode($data));
         if ($transaction_reference == null) {
             return 'Error - No transaction reference';
         }
         if ($data == null) {
             return 'Error - No data';
         }
         define('API_ENDPOINT', HipayClass::getAPIURL());
         define('API_USERNAME', HipayClass::getAPIUsername());
         define('API_PASSWORD', HipayClass::getAPIPassword());
         $credentials = API_USERNAME . ':' . API_PASSWORD;
         $resource = API_ENDPOINT . 'maintenance/transaction/' . $transaction_reference;
         // create a new cURL resource
         $curl = curl_init();
         // set appropriate options
         $options = array(CURLOPT_URL => $resource, CURLOPT_USERPWD => $credentials, CURLOPT_HTTPHEADER => array('Accept: application/json'), CURLOPT_RETURNTRANSFER => true, CURLOPT_FAILONERROR => false, CURLOPT_HEADER => false, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $data, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false);
         foreach ($options as $option => $value) {
             curl_setopt($curl, $option, $value);
         }
         $result = curl_exec($curl);
         $status = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
         $response = Tools::jsonDecode($result);
         // execute the given cURL session
         if (false === $result) {
             throw new Exception(curl_error($curl));
         }
         if (floor($status / 100) != 2) {
             throw new Exception('Err Msg : ' . $response->message . ', Err Desc : ' . $response->description . ', Err Code : ' . $response->code);
         }
         curl_close($curl);
         HipayLogger::addLog($hipay->l('API call success', 'hipay'), HipayLogger::APICALL, 'Appel vers API avec success : ' . mysql_real_escape_string(Tools::jsonEncode($response)));
         return $response;
     } catch (Exception $e) {
         HipayLogger::addLog($hipay->l('API call error', 'hipay'), HipayLogger::ERROR, mysql_real_escape_string($e->getMessage()));
         return false;
     }
 }
*  International Registered Trademark & Property of Profileo
*/
require_once dirname(__FILE__) . '/../../../config/config.inc.php';
$str_ps_version = (int) str_replace('.', '', _PS_VERSION_);
if ($str_ps_version < 1600) {
    // version 1.5 or 1.4
    include_once dirname(__FILE__) . '/../../../init.php';
} else {
    // Version 1.6 or above
    include_once dirname(__FILE__) . '/../../../init.php';
}
include_once dirname(__FILE__) . '/hipay_tpp.php';
try {
    $hipay = new HiPay_Tpp();
    $content = Tools::jsonEncode($_POST);
    // Insert into order_history
    $log_state = $_POST['state'] ? $_POST['state'] : 'error';
    // Sets to error if nothing is found
    $log_status = $_POST['status'] ? $_POST['status'] : 'error';
    // Sets to error if nothing is found
    HipayLogger::addLog($hipay->l('Callback recieved', 'hipay'), HipayLogger::NOTICE, 'Callback recieved - cid : ' . (int) $_POST['order']['id'] . ' - state : ' . $log_state . ' - status : ' . $log_status . ' - content : ' . mysql_real_escape_string($content));
    $sql_insert = "INSERT INTO `" . _DB_PREFIX_ . "hipay_callbacks` (`callback`) VALUES ('" . mysql_real_escape_string(pSQL($content)) . "');";
    $insert = Db::getInstance()->execute($sql_insert);
    if ($insert) {
        echo 'Callback captured';
    } else {
        echo 'Callback failed to be captured';
    }
} catch (Exception $e) {
    echo 'Callback failed : ' . $e->getMessage();
}
function refundOrder($order = null)
{
    $hipay = new HiPay_Tpp();
    $amount = -1 * $_POST['refunded_amount'];
    // Set refund to negative
    $payment_method = 'HiPay - refund';
    $payment_transaction_id = '';
    $currency = new Currency($order->id_currency);
    $payment_date = date("Y-m-d H:i:s");
    $order_has_invoice = $order->invoice_number;
    //	if ($order_has_invoice)
    //		$order_invoice = new OrderInvoice( Tools::getValue ( 'payment_invoice' ) );
    //	else
    //		$order_invoice = null;
    if (!addOrderPayment($order->id, $amount)) {
        // Ajout commentaire status KO
        $msg = new Message();
        $message = $hipay->l('HiPay - Refund failed.');
        $message .= ' - ' . $hipay->l('Amount refunded failed =') . ' ' . $amount;
        $message = strip_tags($message, '<br>');
        if (Validate::isCleanHtml($message)) {
            $msg->message = $message;
            $msg->id_order = intval($order->id);
            $msg->private = 1;
            $msg->add();
        }
    } else {
        $cart = new Cart((int) $_POST['order']->id);
        $order_id = retrieveOrderId($cart->id);
        $tag = 'HIPAY_CAPTURE ';
        $amount = $_POST['captured_amount'] - $_POST['refunded_amount'];
        $msgs = Message::getMessagesByOrderId($order_id, true);
        //true for private messages (got example from AdminOrdersController)
        $create_new_msg = true;
        if (count($msgs)) {
            foreach ($msgs as $msg) {
                $line = $msg['message'];
                if (startsWith($line, $tag)) {
                    $create_new_msg = false;
                    $to_update_msg = new Message($msg['id_message']);
                    $to_update_msg->message = $tag . $amount;
                    $to_update_msg->save();
                    break;
                }
            }
        }
    }
    return true;
}
 /**
  *
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     $hipay = new HiPay_Tpp();
     //$cart = $this->context->cart;
     $context = Context::getContext();
     $cart = $context->cart;
     if (!$this->module->checkCurrency($cart)) {
         Tools::redirect('index.php?controller=order&xer=1');
     }
     $context->smarty->assign(array('nbProducts' => $cart->nbProducts(), 'cust_currency' => $cart->id_currency, 'currencies' => $this->module->getCurrency((int) $cart->id_currency), 'total' => $cart->getOrderTotal(true, Cart::BOTH), 'this_path' => $this->module->getPathUri(), 'this_path_bw' => $this->module->getPathUri(), 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->module->name . '/'));
     // Token is called when the user ENTERS the card details.
     $paymentproductswitcher = Tools::getValue('paymentproductswitcher');
     if ($paymentproductswitcher == 'american-express') {
         // American Express
         // No cardHolder, but firstname and lastname
         $cardNumber = Tools::getValue('cardNumber');
         $cardHolder = null;
         $cardFirstName = Tools::getValue('cardFirstName');
         $cardLastName = Tools::getValue('cardLastName');
         $cardExpiryMonth = Tools::getValue('cardExpiryMonth');
         $cardExpiryYear = Tools::getValue('cardExpiryYear');
         $cardSecurityCode = Tools::getValue('cardSecurityCode');
         $cardMemorizeCode = Tools::getValue('cardMemorizeCode');
         $cartUseExistingToken = Tools::getValue('cartUseExistingToken');
         $cardToken = Tools::getValue('cardToken');
     } else {
         if ($paymentproductswitcher == 'bcmc') {
             // BanckContact/MisterCash
             // No CRC check
             $cardNumber = Tools::getValue('cardNumber');
             $cardHolder = Tools::getValue('cardHolder');
             $cardFirstName = null;
             $cardLastName = null;
             $cardExpiryMonth = Tools::getValue('cardExpiryMonth');
             $cardExpiryYear = Tools::getValue('cardExpiryYear');
             $cardSecurityCode = null;
             $cardMemorizeCode = Tools::getValue('cardMemorizeCode');
             $cartUseExistingToken = Tools::getValue('cartUseExistingToken');
             $cardToken = Tools::getValue('cardToken');
         } else {
             $cardNumber = Tools::getValue('cardNumber');
             $cardHolder = Tools::getValue('cardHolder');
             $cardFirstName = null;
             $cardLastName = null;
             $cardExpiryMonth = Tools::getValue('cardExpiryMonth');
             $cardExpiryYear = Tools::getValue('cardExpiryYear');
             $cardSecurityCode = Tools::getValue('cardSecurityCode');
             $cardMemorizeCode = Tools::getValue('cardMemorizeCode');
             $cartUseExistingToken = Tools::getValue('cartUseExistingToken');
             $cardToken = Tools::getValue('cardToken');
         }
     }
     if ($cartUseExistingToken) {
         // $cartUseExistingToken = 1 -> Use memorized card token.
         // Pre-check
         $errors = true;
         // Initialize to true
         if ($cardToken != '' || $cardToken != null) {
             if ($cardToken) {
                 $token_to_use = $cardToken;
                 // This variable will be used to make the payment. Assign only when token is present.
                 $errors = false;
                 // proceed with the submit
             }
         }
         // If $cardToken is null or empty or false
         // Send error 999 to indicate that user should select the card
         if ($errors) {
             $cardtoken = '999';
         }
     } else {
         // $cartUseExistingToken = 0 -> Default processing of fetching card token.
         $cardtoken = HipayToken::createToken($cardNumber, $cardHolder, $cardExpiryMonth, $cardExpiryYear, $cardSecurityCode, $cardFirstName, $cardLastName, $paymentproductswitcher);
         // Pre-check
         $errors = true;
         // Initialize to true
         if (is_object($cardtoken)) {
             // Verify if token is not 0 or false
             if ($cardtoken->token) {
                 if ($cardMemorizeCode == 'memorize') {
                     HipayToken::saveToken($cardtoken, $cart);
                 }
                 $token_to_use = $cardtoken->token;
                 // This variable will be used to make the payment. Assign only when token is present.
                 $errors = false;
                 // proceed with the submit
             }
         }
     }
     if ($errors) {
         $cart = $context->cart;
         $context->smarty->assign(array('nbProducts' => $cart->nbProducts(), 'cust_currency' => $cart->id_currency, 'currencies' => $this->module->getCurrency((int) $cart->id_currency), 'total' => $cart->getOrderTotal(true, Cart::BOTH), 'this_path' => $this->module->getPathUri(), 'this_path_bw' => $this->module->getPathUri(), 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->module->name . '/'));
         $currency_array = $this->module->getCurrency((int) $cart->id_currency);
         $currency = $currency_array[0]['iso_code'];
         foreach ($currency_array as $key => $value) {
             if ($value['id_currency'] == $cart->id_currency) {
                 $actual_currency = $value['iso_code'];
             }
         }
         if ($currency != $actual_currency) {
             $currency = $actual_currency;
         }
         $context->smarty->assign(array('status_error' => (int) $cardtoken, 'cart_id' => $cart->id, 'currency' => $currency, 'amount' => $cart->getOrderTotal(true, Cart::BOTH)));
         // Tpl will load a form that will store those infomations.
         $context->controller->addCSS(_MODULE_DIR_ . $this->module->name . '/css/hipay.css');
         $context->controller->addJs(_MODULE_DIR_ . $this->module->name . '/js/15hipay.js');
         $card_str = Configuration::get('HIPAY_ALLOWED_CARDS');
         $selection_cards = array('american-express' => $hipay->l('American Express'), 'bcmc' => $hipay->l('Bancontact / Mister Cash'), 'cb' => $hipay->l('Carte Bancaire'), 'maestro' => $hipay->l('Maestro'), 'mastercard' => $hipay->l('MasterCard'), 'visa' => $hipay->l('Visa'));
         $cart_arr = explode(',', $card_str);
         $carte = array();
         foreach ($cart_arr as $key => $value) {
             foreach ($selection_cards as $key1 => $value1) {
                 if ($key1 && $value == $key1) {
                     $carte[$key1] = $value1;
                 }
             }
         }
         $context->smarty->assign(array('cartes' => $carte));
         $tokens = HipayToken::getTokens($cart->id_customer);
         //
         if ($tokens['0']) {
             $token_display = 'true';
         } else {
             $token_display = 'false';
         }
         $allow_memorize = HipayClass::getShowMemorization();
         if (_PS_VERSION_ >= '1.6') {
             $show_breadcrumb = false;
         } else {
             $show_breadcrumb = true;
         }
         $context->smarty->assign(array('token_display' => $token_display, 'allow_memorize' => $allow_memorize, 'show_breadcrumb' => $show_breadcrumb, 'tokens' => $tokens));
         $payment_tpl = 'payment_execution_api.tpl';
         return $this->setTemplate($payment_tpl);
         die;
     } else {
         // Mode API
         // Constructs data array and sends it as a parameter to the tpl
         $data = HipayToken::getApiData($cart, $token_to_use, null, $cartUseExistingToken);
         $response = HipayApi::restApi('order', $data);
         // Check if 3D secure is activated
         //if((int)$data['authentication_indicator'])
         //{
         // Check if forwardURL is true
         if ($response->forwardUrl) {
             // Redirect user
             Tools::redirect($response->forwardUrl);
         }
         //}
         if (get_class($response) != 'Exception') {
             switch ($response->state) {
                 case 'completed':
                     $response_state = 'completed';
                     break;
                 case 'forwarding':
                     $response_state = 'forwarding';
                     break;
                 case 'pending':
                     $response_state = 'pending';
                     break;
                 case 'declined':
                     $response_state = 'declined';
                     break;
                 case 'error':
                 default:
                     $response_state = 'error';
                     break;
             }
             $context->smarty->assign(array('error_code' => '', 'error_message' => '', 'error_response' => '', 'response_state' => $response_state));
         } else {
             $response_code = $response->getCode();
             $response_message = $response->getMessage();
             $context->smarty->assign(array('error_code' => $response_code, 'error_message' => $response_message, 'error_response' => 'exception_error', 'response_state' => 'error'));
         }
         switch ($response_state) {
             case 'completed':
                 $redirect_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'index.php?fc=module&module=' . $hipay->name . '&controller=accept');
                 break;
             case 'declined':
                 $redirect_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'index.php?fc=module&module=' . $hipay->name . '&controller=decline');
                 break;
             case 'cancel':
                 $redirect_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'index.php?fc=module&module=' . $hipay->name . '&controller=cancel');
                 break;
             case 'pending':
             case 'forwarding':
                 $redirect_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'index.php?fc=module&module=' . $hipay->name . '&controller=pending');
                 // Implementing challenge url
                 // Redirecting to challenge url if url present
                 if (Configuration::get('HIPAY_CHALLENGE_URL')) {
                     $redirect_url = Configuration::get('HIPAY_CHALLENGE_URL');
                 }
                 break;
             case 'exception':
             default:
                 $redirect_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'index.php?fc=module&module=' . $hipay->name . '&controller=exception');
                 break;
         }
         // Disconnect User from cart
         HipayClass::unsetCart();
         die('
             <script type="text/javascript">
                 try{
                     parent.window.location.replace("' . $redirect_url . '");
                 }catch(e){
                     alert(e);
                 }
             </script>
             <h1>' . Tools::displayError('Now loading..') . '</h1>
         ');
         $this->setTemplate('payment_api_response.tpl');
     }
 }
 public function execCapture()
 {
     $context = Context::getContext();
     $hipay = new HiPay_Tpp();
     $hipay_redirect_status = 'ok';
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             throw new PrestaShopException('Can\'t load Order object');
         }
         if (version_compare(_PS_VERSION_, '1.5.6', '>')) {
             ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
         }
         if (Tools::isSubmit('id_emp') && Tools::getValue('id_emp') > 0) {
             $id_employee = Tools::getValue('id_emp');
         } else {
             $id_employee = '1';
         }
     }
     if (Tools::isSubmit('hipay_capture_type')) {
         $refund_type = Tools::getValue('hipay_capture_type');
         $refund_amount = Tools::getValue('hipay_capture_amount');
         $refund_amount = str_replace(' ', '', $refund_amount);
         $refund_amount = floatval(str_replace(',', '.', $refund_amount));
     }
     // First check
     if (Tools::isSubmit('hipay_capture_submit') && $refund_type == 'partial') {
         $hipay_redirect_status = false;
         $hipay = new HiPay_Tpp();
         $orderLoaded = new OrderCore(Tools::getValue('id_order'));
         // v1.5 // $orderTotal = $orderLoaded->total_products_wt + $orderLoaded->total_shipping_tax_incl + $orderLoaded->total_wrapping_tax_incl;
         $orderTotal = $orderLoaded->total_products_wt + $orderLoaded->total_shipping + $orderLoaded->total_wrapping;
         $totalEncaissement = $hipay->getOrderTotalAmountCaptured($orderLoaded->id);
         $stillToCapture = floatval($orderTotal - $totalEncaissement);
         if (!$refund_amount) {
             $hipay_redirect_status = $hipay->l('Please enter an amount', 'capture');
             Tools::redirectAdmin('../../' . Tools::getValue('adminDir') . '/index.php?tab=AdminOrders' . '&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_err=' . $hipay_redirect_status . '#hipay');
             die('');
         }
         if ($refund_amount < 0) {
             $hipay_redirect_status = $hipay->l('Please enter an amount greater than zero', 'capture');
             Tools::redirectAdmin('../../' . Tools::getValue('adminDir') . '/index.php?tab=AdminOrders' . '&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_err=' . $hipay_redirect_status . '#hipay');
             die('');
         }
         if ($refund_amount > $stillToCapture) {
             $hipay_redirect_status = $hipay->l('Amount exceeding authorized amount', 'capture');
             Tools::redirectAdmin('../../' . Tools::getValue('adminDir') . '/index.php?tab=AdminOrders' . '&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_err=' . $hipay_redirect_status . '#hipay');
             die('');
         }
     }
     if (Tools::isSubmit('hipay_capture_submit') && isset($order)) {
         $sql = "SELECT * FROM `" . _DB_PREFIX_ . "hipay_transactions` WHERE `cart_id`='" . (int) $order->id_cart . "'";
         $result = Db::getInstance()->getRow($sql);
         $reference = $result['transaction_reference'];
         if ($refund_type == 'complete') {
             // Appel HiPay
             $data = HipayMaintenance::getMaintenanceData('capture', '0');
             $response = HipayMaintenance::restMaintenanceApi($reference, $data);
             // Ajout commentaire
             $msg = new Message();
             $message = 'HIPAY_CAPTURE_REQUESTED ' . $orderTotal;
             $message = strip_tags($message, '<br>');
             if (Validate::isCleanHtml($message)) {
                 $msg->message = $message;
                 $msg->id_order = intval($order->id);
                 $msg->private = 1;
                 $msg->add();
             }
         } else {
             // 'partial';
             // Appel HiPay
             /**
              * VERIFICATION
              */
             // v1.5 // $orderTotal = $order->total_products_wt + $order->total_shipping_tax_incl + $order->total_wrapping_tax_incl;
             $orderTotal = $order->total_products_wt + $order->total_shipping + $order->total_wrapping;
             $totalEncaissement = $this->getOrderTotalAmountCaptured($order->id);
             $stillToCapture = $orderTotal - $totalEncaissement;
             $orderLoaded = new OrderCore(Tools::getValue('id_order'));
             $currentState = $orderLoaded->getCurrentState();
             $stateLoaded = new OrderState($currentState);
             if (round($stillToCapture, 2) < round($refund_amount, 2)) {
                 $hipay_redirect_status = $hipay->l('Error, you are trying to capture more than the amount remaining', 'capture');
             } else {
                 $data = HipayMaintenance::getMaintenanceData('capture', $refund_amount);
                 $response = HipayMaintenance::restMaintenanceApi($reference, $data);
                 // Ajout commentaire
                 $msg = new Message();
                 $message = 'HIPAY_CAPTURE_REQUESTED ' . $refund_amount;
                 $message = strip_tags($message, '<br>');
                 if (Validate::isCleanHtml($message)) {
                     $msg->message = $message;
                     $msg->id_order = intval($order->id);
                     $msg->private = 1;
                     $msg->add();
                 }
                 $hipay_redirect_status = 'ok';
             }
         }
     } else {
         $hipay_redirect_status = $hipay->l('You do not have permission to do this.', 'capture');
     }
     Tools::redirectAdmin('../../' . Tools::getValue('adminDir') . '/index.php?tab=AdminOrders' . '&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_err=' . $hipay_redirect_status . '#hipay');
 }
 public static function createToken($cardNumber = null, $cardHolder = null, $cardExpiryMonth = null, $cardExpiryYear = null, $cardSecurityCode = null, $firstname = null, $lastname = null, $paymentproductswitcher = null)
 {
     try {
         $hipay = new HiPay_Tpp();
         HipayLogger::addLog($hipay->l('Token Create call initiated', 'hipay'), HipayLogger::APICALL, 'Action : Create Token');
         define('API_ENDPOINT_TOKEN', HipayClass::getAPITokenURL());
         define('API_USERNAME_TOKEN', HipayClass::getAPIUsername());
         define('API_PASSWORD_TOKEN', HipayClass::getAPIPassword());
         $credentials_token = API_USERNAME_TOKEN . ':' . API_PASSWORD_TOKEN;
         $resource_token = API_ENDPOINT_TOKEN . 'create';
         // Multi_use : only boolean
         // 0 = Generate a single-use token
         // 1 = Generate a multi-use token (default)
         $multi_use = 1;
         if ($paymentproductswitcher == 'american-express') {
             $data_token = array('card_number' => $cardNumber, 'card_expiry_month' => $cardExpiryMonth, 'card_expiry_year' => $cardExpiryYear, 'firstname' => $firstname, 'lastname' => $lastname, 'cvc' => $cardSecurityCode, 'multi_use' => $multi_use);
         } elseif ($paymentproductswitcher == 'bcmc') {
             $data_token = array('card_number' => $cardNumber, 'card_expiry_month' => $cardExpiryMonth, 'card_expiry_year' => $cardExpiryYear, 'card_holder' => $cardHolder, 'multi_use' => $multi_use);
         } else {
             $data_token = array('card_number' => $cardNumber, 'card_expiry_month' => $cardExpiryMonth, 'card_expiry_year' => $cardExpiryYear, 'card_holder' => $cardHolder, 'cvc' => $cardSecurityCode, 'multi_use' => $multi_use);
         }
         // create a new cURL resource
         $curl_token = curl_init();
         // set appropriate options
         $options_token = array(CURLOPT_URL => $resource_token, CURLOPT_USERPWD => $credentials_token, CURLOPT_HTTPHEADER => array('Accept: application/json'), CURLOPT_RETURNTRANSFER => true, CURLOPT_FAILONERROR => false, CURLOPT_HEADER => false, CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($data_token), CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false);
         foreach ($options_token as $option => $value) {
             curl_setopt($curl_token, $option, $value);
         }
         $result_token = curl_exec($curl_token);
         $status_token = (int) curl_getinfo($curl_token, CURLINFO_HTTP_CODE);
         $response_token = Tools::jsonDecode($result_token);
         // execute the given cURL session
         if (false === $result_token) {
             throw new Exception(curl_error($curl_token));
         }
         if (floor($status_token / 100) != 2) {
             throw new Exception($status_token);
         }
         curl_close($curl_token);
         HipayLogger::addLog($hipay->l('Token Create call success', 'hipay'), HipayLogger::APICALL, 'Creation token avec success');
         return $response_token;
     } catch (Exception $e) {
         HipayLogger::addLog($hipay->l('Token Create call status error', 'hipay'), HipayLogger::ERROR, Db::getInstance()->escape($e->getMessage()));
         return $e->getMessage();
     }
 }
 public static function duplicateCart()
 {
     $hipay = new HiPay_Tpp();
     // Taken from controllers\front\ParentOrderController.php , keyword "submitReorder"
     /* Disable some cache related bugs on the cart/order */
     header('Cache-Control: no-cache, must-revalidate');
     header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
     $errors = array();
     $context = Context::getContext();
     //$oldCart = new Cart(Order::getCartIdStatic($context->cookie->id_cart, $context->customer->id));
     $oldCart = new Cart($context->cookie->id_cart);
     $duplication = $oldCart->duplicate();
     if (!$duplication || !Validate::isLoadedObject($duplication['cart'])) {
         $errors[] = $hipay->l('Sorry. We cannot renew your order.', 'hipay');
     } else {
         if (!$duplication['success']) {
             $errors[] = $hipay->l('Some items are no longer available, and we are unable to renew your order.', 'hipay');
         } else {
             // FR. Le panier courant a déjà été utilisé sur la plateforme Hipay. Un nouveau panier viens d'être créé afin de procéder malgré tout au paiement. Attention, celui-ci va impliquer une nouvelle transaction sur la plateforme Hipay.
             // EN. The current cart has already been used on the Hipay platform. A new cart just been created to make the payment anyway. Warning, this will involve a new transaction on the Hipay platform.
             $errors[] = $hipay->l('The current cart has already been used on the Hipay platform. A new cart just been created to make the payment anyway. Warning, this will involve a new transaction on the Hipay platform.', 'hipay');
             $context->cookie->id_cart = $duplication['cart']->id;
             $context->cookie->write();
         }
     }
     if (count($errors)) {
         return $errors;
     }
     return false;
 }
 /**
  *
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     $this->HipayLog('####################################################');
     $this->HipayLog('# Début demande de remboursement partiel ou complète');
     $this->HipayLog('####################################################');
     $context = Context::getContext();
     $hipay = new HiPay_Tpp();
     $hipay_redirect_status = 'ok';
     $this->HipayLog('-- context et hipay sont init');
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $this->HipayLog('--------------------------------------------------');
         $this->HipayLog('-- init de la commande = ' . Tools::getValue('id_order'));
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             throw new PrestaShopException('Can\'t load Order object');
         }
         if (version_compare(_PS_VERSION_, '1.5.6', '>')) {
             $this->HipayLog('---- init du shop si version > à la 1.5.6 = ' . $order->id_shop);
             ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
         }
         if (Tools::isSubmit('id_emp') && Tools::getValue('id_emp') > 0) {
             $id_employee = Tools::getValue('id_emp');
         } else {
             $id_employee = '1';
         }
         $this->HipayLog('---- init id_emp = ' . $id_employee);
         $this->HipayLog('--------------------------------------------------');
     }
     if (Tools::isSubmit('hipay_refund_type')) {
         $this->HipayLog('--------------------------------------------------');
         $refund_type = Tools::getValue('hipay_refund_type');
         $refund_amount = Tools::getValue('hipay_refund_amount');
         $refund_amount = str_replace(' ', '', $refund_amount);
         $refund_amount = floatval(str_replace(',', '.', $refund_amount));
         $this->HipayLog('-- init refund_type = ' . $refund_type);
         $this->HipayLog('-- init refund_amount = ' . $refund_amount);
         $this->HipayLog('--------------------------------------------------');
     }
     // First check
     if (Tools::isSubmit('hipay_refund_submit') && $refund_type == 'partial') {
         $this->HipayLog('--------------------------------------------------');
         $this->HipayLog('-- Début Refund_submit & partiel');
         $hipay_redirect_status = false;
         $hipay = new HiPay_Tpp();
         $orderLoaded = new OrderCore(Tools::getValue('id_order'));
         $orderTotal = $orderLoaded->total_products_wt + $orderLoaded->total_shipping_tax_incl + $orderLoaded->total_wrapping_tax_incl;
         $this->HipayLog('---- Init id_order = ' . Tools::getValue('id_order'));
         $this->HipayLog('---- Init orderTotal => ' . $orderTotal . ' = ' . $orderLoaded->total_products_wt . ' + ' . $orderLoaded->total_shipping_tax_incl . ' + ' . $orderLoaded->total_wrapping_tax_incl);
         // patch de compatibilité
         if (_PS_VERSION_ < '1.5') {
             $id_or_reference = $orderLoaded->id;
         } else {
             $id_or_reference = $orderLoaded->reference;
         }
         $this->HipayLog('---- PS_VERSION = ' . _PS_VERSION_);
         $this->HipayLog('---- id_or_reference = ' . $id_or_reference);
         $totalEncaissement = $hipay->getOrderTotalAmountCaptured($id_or_reference);
         $this->HipayLog('---- totalEncaissement = ' . $totalEncaissement);
         // -----------------------
         if (!$refund_amount) {
             $hipay_redirect_status = $hipay->l('Please enter an amount', 'refund');
             $url = Tools::getValue('adminDir') . '/index.php?controller=AdminOrders' . '&id_order=' . (int) $orderLoaded->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_refund_err=' . $hipay_redirect_status . '#hipay';
             $this->HipayLog('---- Init URL pour redirectAdmin - refund_amount = ' . $url);
             $this->HipayLog('--------------------------------------------------');
             Tools::redirectAdmin($url);
             die('');
         }
         if ($refund_amount < 0) {
             $hipay_redirect_status = $hipay->l('Please enter an amount greater than zero', 'refund');
             $url = Tools::getValue('adminDir') . '/index.php?controller=AdminOrders' . '&id_order=' . (int) $orderLoaded->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_refund_err=' . $hipay_redirect_status . '#hipay';
             $this->HipayLog('---- Init URL pour redirectAdmin - refund_amount = ' . $url);
             $this->HipayLog('--------------------------------------------------');
             Tools::redirectAdmin($url);
             die('');
         }
         if ($refund_amount > $totalEncaissement) {
             $hipay_redirect_status = $hipay->l('Amount exceeding authorized amount', 'refund');
             $url = Tools::getValue('adminDir') . '/index.php?controller=AdminOrders' . '&id_order=' . (int) $orderLoaded->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_refund_err=' . $hipay_redirect_status . '#hipay';
             $this->HipayLog('---- Init URL pour redirectAdmin - refund_amount = ' . $url);
             $this->HipayLog('--------------------------------------------------');
             Tools::redirectAdmin($url);
             die('');
         }
         if (!is_numeric($refund_amount)) {
             $hipay_redirect_status = $hipay->l('Please enter an amount', 'refund');
             $url = Tools::getValue('adminDir') . '/index.php?controller=AdminOrders' . '&id_order=' . (int) $orderLoaded->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_refund_err=' . $hipay_redirect_status . '#hipay';
             $this->HipayLog('---- Init URL pour redirectAdmin - refund_amount = ' . $url);
             $this->HipayLog('--------------------------------------------------');
             Tools::redirectAdmin($url);
             die('');
         }
         $this->HipayLog('--------------------------------------------------');
     }
     if (Tools::isSubmit('hipay_refund_submit') && isset($order)) {
         $this->HipayLog('--------------------------------------------------');
         $sql = "SELECT * FROM `" . _DB_PREFIX_ . "hipay_transactions` WHERE `cart_id`='" . (int) $order->id_cart . "'";
         $this->HipayLog('-- SQL hipay refund submit & isset order = ' . $sql);
         $result = Db::getInstance()->getRow($sql);
         $reference = $result['transaction_reference'];
         $this->HipayLog('-- Transaction reference = ' . $reference);
         $this->HipayLog('---- type = ' . $refund_type);
         if ($refund_type == 'complete') {
             // Appel HiPay
             $data = HipayMaintenance::getMaintenanceData('refund', '0');
             $response = HipayMaintenance::restMaintenanceApi($reference, $data, (int) $order->id_shop);
             // Ajout commentaire
             $msg = new Message();
             $message = 'HiPay - Complete refund requested to HiPay.';
             $message = strip_tags($message, '<br>');
             $this->HipayLog('---- message = ' . $message);
             if (Validate::isCleanHtml($message)) {
                 $msg->message = $message;
                 $msg->id_order = intval($order->id);
                 $msg->private = 1;
                 $msg->add();
             }
         } else {
             // 'partial';
             // Appel HiPay
             $this->HipayLog('---- Partiel ');
             /**
              * VERIFICATION
              */
             $orderTotal = $order->total_products_wt + $order->total_shipping_tax_incl + $order->total_wrapping_tax_incl;
             $this->HipayLog('---- OrderTotal = ' . $order->total_products_wt . '+' . $order->total_shipping_tax_incl . '+' . $order->total_wrapping_tax_incl);
             // patch de compatibilité
             if (_PS_VERSION_ < '1.5') {
                 $id_or_reference = $order->id;
             } else {
                 $id_or_reference = $order->reference;
             }
             $this->HipayLog('---- PS_VERSION = ' . _PS_VERSION_);
             $this->HipayLog('---- id_or_reference = ' . $id_or_reference);
             $totalEncaissement = $this->module->getOrderTotalAmountCaptured($id_or_reference);
             // -----------------------
             $this->HipayLog('---- totalEncaissement = ' . $totalEncaissement);
             if ($totalEncaissement < $refund_amount) {
                 $hipay_redirect_status = $hipay->l('Error, you are trying to refund an amount that is more than the amount captured', 'refund');
                 $this->HipayLog('---- Error = ' . $hipay_redirect_status);
             } else {
                 $data = HipayMaintenance::getMaintenanceData('refund', $refund_amount);
                 $response = HipayMaintenance::restMaintenanceApi($reference, $data, (int) $order->id_shop);
                 // Ajout commentaire
                 $msg = new Message();
                 $message = 'HIPAY_REFUND_REQUESTED ' . $refund_amount;
                 $message = strip_tags($message, '<br>');
                 $this->HipayLog('---- Message = ' . $message);
                 if (Validate::isCleanHtml($message)) {
                     $msg->message = $message;
                     $msg->id_order = intval($order->id);
                     $msg->private = 1;
                     $msg->add();
                 }
                 $hipay_redirect_status = 'ok';
                 $this->HipayLog('---- Redirect status = ' . $hipay_redirect_status);
             }
         }
     } else {
         $hipay_redirect_status = $hipay->l('You do not have permission to do this.', 'refund');
         $this->HipayLog('---- Error = ' . $hipay_redirect_status);
     }
     $this->HipayLog('####################################################');
     $this->HipayLog('# Fin demande de remboursement partiel ou complète');
     $this->HipayLog('####################################################');
     Tools::redirectAdmin(Tools::getValue('adminDir') . '/index.php?controller=AdminOrders' . '&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_refund_err=' . $hipay_redirect_status . '#hipay');
 }
function captureOrder($callback_arr = null, $order = null)
{
    //LOG
    HipayLog('--------------- Début captureOrder');
    $hipay = new HiPay_Tpp();
    // Local Cards update
    $local_card_name = '';
    // Initialize to empty string
    if ($callback_arr['payment_product'] != '') {
        // Add the card name
        $local_card_name = ' via ' . (string) ucwords($callback_arr['payment_product']);
        // Retrieve xml list
        if (file_exists(_PS_ROOT_DIR_ . '/modules/' . $hipay->name . '/special_cards.xml')) {
            $local_cards = simplexml_load_file(_PS_ROOT_DIR_ . '/modules/' . $hipay->name . '/special_cards.xml');
            // If cards exists
            if (isset($local_cards)) {
                // If cards count > 0
                if (count($local_cards)) {
                    // Go through each card
                    foreach ($local_cards as $value) {
                        // If card code value = payment_product value
                        if ((string) $value->code == trim($callback_arr['payment_product'])) {
                            // Add the card name
                            $local_card_name = ' via ' . (string) $value->name;
                        }
                    }
                }
            }
        }
    }
    // On met à jour la ligne transaction / paiement de la commande
    // création de la transaction
    if (isset($callback_arr['payment_method']['token'])) {
        $sql = "\n\t\t\t\tUPDATE `" . _DB_PREFIX_ . "order_payment`\n                    SET `card_number` = '" . $callback_arr['payment_method']['pan'] . "',\n\t                    `amount` = '" . $callback_arr['captured_amount'] . "',\n\t                    `transaction_id` = '" . $callback_arr['transaction_reference'] . "',\n\t                    `card_brand` = '" . $callback_arr['payment_method']['brand'] . "',\n\t                    `card_expiration` = '" . $callback_arr['payment_method']['card_expiry_month'] . "/" . $callback_arr['payment_method']['card_expiry_year'] . "',\n\t                    `card_holder` = '" . $callback_arr['payment_method']['card_holder'] . "'\n                    WHERE \n                    \t`payment_method` = '" . 'HiPay Fullservice' . $local_card_name . "'\n                    AND `order_reference`= '" . $order->reference . "';";
        if (!Db::getInstance()->execute($sql)) {
            //LOG
            HipayLog('--------------- Update en erreur');
            return false;
        }
        // Check if there is a duplicated OrderPayment and remove duplicate from same order ref but with incomplete payment method name
        $sql_duplicate_order_payment = "\n\t\t\tDELETE FROM `" . _DB_PREFIX_ . "order_payment` \n\t\t\tWHERE \n\t\t\t\tpayment_method='HiPay Fullservice' \n\t\t\t\tAND transaction_id='' \n\t\t\t\tAND order_reference='" . $order->reference . "'\n\t\t\t;";
        Db::getInstance()->execute($sql_duplicate_order_payment);
        // set invoice order
        if ($callback_arr['status'] == HIPAY_STATUS_CAPTURE_REQUESTED || $callback_arr['status'] == HIPAY_STATUS_CAPTURED) {
            $sql = 'SELECT `id_order_payment`
				FROM `' . _DB_PREFIX_ . 'order_payment`
				WHERE order_reference="' . pSQL($order->reference) . ' LIMIT 1";';
            $result = Db::getInstance()->getRow($sql);
            $id_orderP = isset($result['id_order_payment']) ? $result['id_order_payment'] : false;
            if ($id_orderP) {
                $sql_update = "\n\t\t\t\t\tUPDATE `" . _DB_PREFIX_ . "order_invoice_payment`\n                    SET `id_order_payment` = " . (int) $id_orderP . "\n                    WHERE `id_order` = " . (int) $order->id;
                Db::getInstance()->execute($sql_update);
            }
        }
        //LOG
        HipayLog('--------------- delete transaction pas invoice = ' . $sql_duplicate_order_payment);
        // init message pour création de commande
        $message = $hipay->l('Transaction Reference:') . ' ' . $callback_arr['transaction_reference'] . '<br />
            ' . $hipay->l('State:') . ' ' . $callback_arr['state'] . '<br />
            ' . $hipay->l('Status:') . ' ' . $callback_arr['status'] . '<br />
            ' . $hipay->l('Message:') . ' ' . $callback_arr['message'] . '<br />
            ' . $hipay->l('Data:') . ' ' . $callback_arr['cdata1'] . '<br />
            ' . $hipay->l('Amount : ') . $callback_arr['authorized_amount'] . '<br />
            ' . $hipay->l('Payment mean:') . ' ' . $callback_arr['payment_product'] . '<br />
            ' . $hipay->l('Payment has began at:') . ' ' . $callback_arr['date_created'] . '<br />
            ' . $hipay->l('Payment received at:') . ' ' . $callback_arr['date_authorized'] . '<br />
            ' . $hipay->l('authorization Code:') . ' ' . $callback_arr['authorization_code'] . '<br />
            ' . $hipay->l('Currency:') . ' ' . $callback_arr['currency'] . '<br />
            ' . $hipay->l('Customer IP address:') . ' ' . $callback_arr['ip_address'];
        //LOG
        HipayLog('--------------- MESSAGE = ' . $message);
        $message = strip_tags($message, '<br>');
        if (Validate::isCleanHtml($message)) {
            $msg = new Message();
            $msg->message = $message;
            $msg->id_order = (int) $order->id;
            $msg->private = 1;
            $msg->add();
            //LOG
            HipayLog('--------------- addMessage on captureOrder - ' . $message);
        }
    }
    if ($callback_arr) {
        //LOG
        HipayLog('--------------- Fin captureOrder');
    }
    HipayLog('--------------- --------------- --------------- --------------- ');
    HipayLog('--------------- --------------- --------------- --------------- ');
    return true;
}