/**
  *
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     $hipay = new HiPay_Tpp();
     // Acceptable return status for iframe :
     // Accept, decline, cancel and exception
     // Default value = exception
     $return_status = Tools::getValue("return_status", "exception");
     switch ($return_status) {
         case 'accept':
             $redirect_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'index.php?fc=module&module=' . $hipay->name . '&controller=accept');
             break;
         case 'decline':
             $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':
             $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>
         ');
 }
    /**
     *
     * @see FrontController::postProcess()
     */
    public function postProcess()
    {
        // Disconnect User from cart
        HipayClass::unsetCart();
        // block 3s because
        sleep(3);
        // récupération des informations en GET ou POST venant de la page de paiement
        $cart_id = Tools::getValue('orderId');
        $transac = Tools::getValue('reference');
        $context = Context::getContext();
        // --------------------------------------------------------------------------
        // vérification si les informations ne sont pas = à FALSE
        if (!$cart_id) {
            // récupération du dernier panier via son compte client
            $sql = 'SELECT `id_cart`
					FROM `' . _DB_PREFIX_ . 'cart`
					WHERE `id_customer` = ' . $context->customer->id . '
					ORDER BY date_upd DESC';
            $result = Db::getInstance()->getRow($sql);
            $cart_id = isset($result['id_cart']) ? $result['id_cart'] : false;
            if ($cart_id) {
                $objCart = new Cart((int) $cart_id);
            }
        } else {
            // load cart
            $objCart = new Cart((int) $cart_id);
        }
        // load order for id_order
        $order_id = Order::getOrderByCartId($cart_id);
        if ($order_id && !empty($order_id) && $order_id > 0) {
            // load transaction by id_order
            $sql = 'SELECT DISTINCT(op.transaction_id)
					FROM `' . _DB_PREFIX_ . 'order_payment` op
					INNER JOIN `' . _DB_PREFIX_ . 'orders` o ON o.reference = op.order_reference
					WHERE o.id_order = ' . $order_id;
            $result = Db::getInstance()->getRow($sql);
        }
        $transaction = isset($result['transaction_id']) ? $result['transaction_id'] : 0;
        $context->smarty->assign(array('id_order' => $order_id, 'total' => $objCart->getOrderTotal(true), 'transaction' => $transaction, 'currency' => $context->currency->iso_code, 'email' => $context->customer->email));
        $this->setTemplate('payment_accept.tpl');
    }
 /**
  * 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;
     }
 }
 /**
  * Generates API data Note : This data structure is different from HipayToken::getApiData.
  *
  * @param $cart :
  *        	Contains cart information @param $data_type : Can be either 'null' or 'iframe'. 'null' = default dedicated page behaviour 'iframe' = Updates some values to match iframe behaviour @param $context : Optional parameter through which current context is passed. If not present, the context will get instantiated none the less. returns API response array()
  */
 public static function getApiData($cart = null, $data_type = null, $context = null, $local_card = null)
 {
     $hipay = new HiPay_Tpp();
     if (!$context) {
         $context = Context::getContext();
     }
     // Basic check for security
     // If no currency for the cart, redirect to first order step
     if (!$hipay->checkCurrency($cart)) {
         Tools::redirect('index.php?controller=order&xer=3');
     }
     $language = HipayClass::getLanguageCode($context->language->iso_code);
     // Retrieving Currency
     $currency_array = $hipay->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;
     }
     // Retrieve Total
     $amount = $cart->getOrderTotal(true, Cart::BOTH);
     // Order ID
     $orderid = $cart->id . "(" . time() . ")";
     // Cart other details
     $cart_summary = $cart->getSummaryDetails(null, true);
     $shipping = $cart_summary['total_shipping'];
     $tax = $cart_summary['total_tax'];
     $description = '';
     // Initialize to blank
     foreach ($cart_summary['products'] as $key => $value) {
         if ($value['reference']) {
             // Add reference of each product
             $description .= 'ref_' . $value['reference'] . ', ';
         }
     }
     // Trim trailing seperator
     $description = Tools::substr($description, 0, -2);
     if (Tools::strlen($description) == 0) {
         $description = 'cart_id_' . $orderid;
     }
     // If description exceeds 255 char, trim back to 255
     $max_length = 255;
     if (Tools::strlen($description) > $max_length) {
         $offset = $max_length - 3 - Tools::strlen($description);
         $description = Tools::substr($description, 0, strrpos($description, ' ', $offset)) . '...';
     }
     // Load customer and populate data array
     $customer = new Customer((int) $cart->id_customer);
     // Verify if customer is indeed a customer object
     if (!Validate::isLoadedObject($customer)) {
         Tools::redirect('index.php?controller=order&xer=5');
     }
     // Retrive Customer ID
     $cid = (int) $customer->id;
     // Retrieve first name and last name
     $firstname = $customer->firstname;
     $lastname = $customer->lastname;
     // Retrieve Gender
     $gender = HipayClass::getAPIGender($customer->id_gender);
     // Retrieve Email
     $email = $customer->email;
     // Retrieve Birthdate
     $birthdate = $customer->birthday;
     $birthdate = str_replace('-', '', $birthdate);
     // Load Addresses - Invoice addr and Delivery addr
     $invoice = new Address((int) $cart->id_address_invoice);
     $delivery = new Address((int) $cart->id_address_delivery);
     if (isset($invoice->phone) && $invoice->phone != '') {
         $phone = $invoice->phone;
     } elseif (isset($invoice->phone_mobile) && $invoice->phone_mobile != '') {
         $phone = $invoice->phone_mobile;
     } else {
         $phone = '';
     }
     $streetaddress = $invoice->address1;
     $streetaddress2 = $invoice->address2;
     $city = $invoice->city;
     $zipcode = $invoice->postcode;
     // Data 'state' = The USA state or the Canada state of the
     // customer making the purchase. Send this
     // information only if the address country of the
     // customer is US (USA) or CA (Canada
     $state = '';
     // Data 'country' = The country code of the customer.
     // This two-letter country code complies with ISO
     // 3166-1 (alpha 2).
     $country = HipayClass::getCountryCode($invoice->country);
     // Delivery info
     $shipto_firstname = $delivery->firstname;
     $shipto_lastname = $delivery->lastname;
     $shipto_streetaddress = $delivery->address1;
     $shipto_streetaddress2 = $delivery->address2;
     $shipto_city = $delivery->city;
     $shipto_zipcode = $delivery->postcode;
     // Data 'shipto_state' = The USA state or the Canada state of the
     // customer making the purchase. Send this
     // information only if the address country of the
     // customer is US (USA) or CA (Canada
     $shipto_state = '';
     // Data 'shipto_country' = The country code of the customer.
     // This two-letter country code complies with ISO
     // 3166-1 (alpha 2).
     $shipto_country = HipayClass::getCountryCode($delivery->country);
     // Data set => cdata1, cdata2, cdata3, cdata4
     // Custom data. You may use these parameters
     // to submit values you wish to receive back in
     // the API response messages or in the
     // notifications, e.g. you can use these
     // parameters to get back session data, order
     // content or user info.
     $cdata1 = 'c' . $orderid;
     // Cart ID
     $cdata2 = 'u' . $cid;
     // User ID
     $cdata3 = 'My+data+3';
     $cdata4 = 'My+data+4';
     // Set of return URLs
     if ($data_type == 'iframe') {
         // Template = iframe
         $accept_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14iframe.php' . '?return_status=accept&content_only=1');
         $decline_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14iframe.php' . '?return_status=decline&content_only=1');
         $cancel_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14iframe.php' . '?return_status=cancel&content_only=1');
         $pending_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14iframe.php' . '?return_status=pending&content_only=1');
         $exception_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14iframe.php' . '?return_status=exception&content_only=1');
         // Template = iframe
         $template = 'iframe';
         if (Configuration::get('HIPAY_TEMPLATE_MODE') == 'basic-js') {
             $template .= '-js';
         }
     } else {
         $accept_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14accept.php');
         $decline_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14decline.php');
         $cancel_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14cancel.php');
         $exception_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14exception.php');
         $pending_url = HipayClass::getRedirectionUrl(Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $hipay->name . '/14pending.php');
         // Template = basic
         $template = Configuration::get('HIPAY_TEMPLATE_MODE');
     }
     // Implementing challenge url
     // Redirecting to challenge url if url present
     if (Configuration::get('HIPAY_CHALLENGE_URL')) {
         $pending_url = Configuration::get('HIPAY_CHALLENGE_URL');
     }
     // Data 'eci'
     // Electronic Commerce Indicator (ECI).
     // The ECI indicates the security level at
     // which the payment information is
     // processed between the cardholder and
     // merchant.
     // Possible values:
     // 1 = MO/TO (Card Not Present)
     // 2 = MO/TO - Recurring
     // 3 = Installment Payment
     // 4 = Manually Keyed (Card Present)
     // 7 = Secure E-commerce with SSL/TLS
     // Encryption
     // 9 = Recurring E-commerce
     $eci = '7';
     // 3D Secure authentication
     // Data authentication_indicator
     // Indicates if the authentication should be
     // performed. Can be used to overrule the
     // merchant level configuration.
     // 0 = Bypass authentication
     // 1 = Continue if possible (Default)
     $authentication_indicator = (int) '0';
     if ((int) Configuration::get('HIPAY_THREEDSECURE')) {
         if ($amount >= (int) Configuration::get('HIPAY_THREEDSECURE_AMOUNT')) {
             $authentication_indicator = (int) Configuration::get('HIPAY_THREEDSECURE');
         } else {
             $authentication_indicator = (int) '0';
         }
     }
     // Get last payment methods list
     $payment_product_list_upd = Tools::getValue('payment_product_list_upd');
     if (Configuration::get('HIPAY_MANUALCAPTURE')) {
         $operation = 'Authorization';
     } else {
         $operation = 'Sale';
     }
     // Intergrating Local cards logic into the data construction
     $payment_product_list = Configuration::get('HIPAY_ALLOWED_CARDS');
     if ($local_card != null) {
         // Override payment_product_list with local card
         $payment_product_list_upd = $local_card;
         $operation = 'Sale';
         // Default value
         // Override operation - Force sale, not manual capture.
         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 (count($local_cards)) {
                 foreach ($local_cards as $key => $value) {
                     if ($local_card == (string) $value->code) {
                         if ((string) $value->manualcapture == '1') {
                             $operation = 'Authorization';
                         } else {
                             $operation = 'Sale';
                         }
                     }
                 }
             }
         }
     }
     // On module administration we change the values of display selector to get always by default the selector showed
     if (Configuration::get('HIPAY_SELECTOR_MODE') == '1') {
         $display_selector = 0;
     } else {
         $display_selector = 1;
     }
     $data = array('operation' => $operation, 'payment_product_list' => $payment_product_list_upd, 'description' => $description, 'long_description' => '', 'currency' => $currency, 'orderid' => $orderid, 'amount' => $amount, 'shipping' => $shipping, 'tax' => $tax, 'accept_url' => $accept_url, 'decline_url' => $decline_url, 'pending_url' => $pending_url, 'cancel_url' => $cancel_url, 'exception_url' => $exception_url, 'language' => $language, 'cdata1' => $cdata1, 'cdata2' => $cdata2, 'cdata3' => $cdata3, 'cdata4' => $cdata4, 'cid' => $cid, 'phone' => $phone, 'birthdate' => $birthdate, 'gender' => $gender, 'firstname' => $firstname, 'lastname' => $lastname, 'recipientinfo' => 'Client', 'streetaddress' => $streetaddress, 'streetaddress2' => $streetaddress2, 'city' => $city, 'state' => $state, 'zipcode' => $zipcode, 'country' => $country, 'shipto_firstname' => $shipto_firstname, 'shipto_lastname' => $shipto_lastname, 'shipto_recipientinfo' => 'Client', 'shipto_streetaddress' => $shipto_streetaddress, 'shipto_streetaddress2' => $shipto_streetaddress2, 'shipto_city' => $shipto_city, 'shipto_state' => $shipto_state, 'shipto_zipcode' => $shipto_zipcode, 'shipto_country' => $shipto_country, 'ipaddr' => $_SERVER['REMOTE_ADDR'], 'email' => $email, 'authentication_indicator' => strval($authentication_indicator), 'eci' => $eci, 'template' => $template, 'css' => Configuration::get('HIPAY_CSS_URL'), 'display_selector' => $display_selector);
     // TPPPRS-21
     if ($birthdate == 0) {
         unset($data['birthdate']);
     }
     // Merchant display name limited to 32 characters only
     if ($data_type == 'iframe') {
         // No merchant_display_name for mode iframe
     } else {
         $merchant_display_name = Tools::substr(Configuration::get('PS_SHOP_NAME'), 0, 32);
         $data['merchant_display_name'] = $merchant_display_name;
     }
     return $data;
 }
 /**
  *
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     // Disconnect User from cart
     HipayClass::unsetCart();
     $this->setTemplate('payment_exception.tpl');
 }
function hipayResetOrderStatus($cart = null)
{
    echo '-fnROS';
    if ($_POST['status'] == '117' || $_POST['status'] == '118') {
        $cart = new Cart((int) $_POST['order']->id);
        if ($cart->orderExists()) {
            $orderState = _PS_OS_PAYMENT_;
            if ($_POST['captured_amount'] < $_POST['authorized_amount']) {
                $orderState = Configuration::get('HIPAY_PARTIALLY_CAPTURED') ? Configuration::get('HIPAY_PARTIALLY_CAPTURED') : HipayClass::getConfiguration('HIPAY_PARTIALLY_CAPTURED');
            }
            // FORCE INVOICE CREATION IF OrderState = _PS_OS_PAYMENT_
            if ($orderState == _PS_OS_PAYMENT_) {
                $order_id = retrieveOrderId($cart->id);
                // Retrieve order id
                $order = new Order((int) $order_id);
                // Recreate order
                $newOS = new OrderState((int) $orderState, $order->id_lang);
                // Emulate the order state _PS_OS_PAYMENT_
                // Uf the order state allows invoice and there is no invoice number, then generate the invoice
                if ($newOS->invoice and !$order->invoice_number) {
                    $order->setInvoice();
                }
            }
        }
    }
    // New modification for status challenged
    // Second check for status 112 -> 117 -> 118
    if ($_POST['status'] == '117') {
        if ((bool) $order->getHistory($context->language->id, Configuration::get('HIPAY_CHALLENGED'))) {
            $cart = new Cart((int) $_POST['order']->id);
            if ($cart->orderExists()) {
                $orderState = _PS_OS_PAYMENT_;
            }
            if ($_POST['captured_amount'] < $_POST['authorized_amount']) {
                $orderState = Configuration::get('HIPAY_PARTIALLY_CAPTURED') ? Configuration::get('HIPAY_PARTIALLY_CAPTURED') : HipayClass::getConfiguration('HIPAY_PARTIALLY_CAPTURED');
            }
            // FORCE INVOICE CREATION IF OrderState = _PS_OS_PAYMENT_
            if ($orderState == _PS_OS_PAYMENT_) {
                $order_id = retrieveOrderId($cart->id);
                // Retrieve order id
                $order = new Order((int) $order_id);
                // Recreate order
                $newOS = new OrderState((int) $orderState, $order->id_lang);
                // Emulate the order state _PS_OS_PAYMENT_
                // Uf the order state allows invoice and there is no invoice number, then generate the invoice
                if ($newOS->invoice and !$order->invoice_number) {
                    $order->setInvoice();
                }
            }
        }
    }
    // Update to minimize risk of simultaneous calls for status 116 and 117
    if ($_POST['status'] == '116') {
        usleep(500000);
        // 0.5sec
        echo '/116';
        // If order exists for cart
        $cart = new Cart((int) $_POST['order']->id);
        if ($cart->orderExists()) {
            echo '/C_OK' . $GLOBALS['_HIPAY_CALLBACK_ORDER_ID_'];
            $context = Context::getContext();
            // Retrieve Order ID
            $order_id = retrieveOrderId($cart->id);
            $order = new Order((int) $order_id);
            echo '/' . (int) $order_id;
            // If current state is paiement accepted or capture partielle
            // then skip the process
            if ((bool) $order->getHistory($context->language->id, _PS_OS_PAYMENT_)) {
                echo '/' . (int) _PS_OS_PAYMENT_ . '_U';
                // Update orders
                $sql_update = "UPDATE `" . _DB_PREFIX_ . "orders`\r\n                    SET `current_state` = '" . _PS_OS_PAYMENT_ . "'\r\n                    WHERE `id_order`='" . (int) $order_id . "'";
                Db::getInstance()->execute($sql_update);
                // Insert into order_history
                $sql_insert = "INSERT INTO `" . _DB_PREFIX_ . "order_history` (`id_employee`, `id_order`, `id_order_state`, `date_add`)\r\n                    VALUES ('0', '" . (int) $order_id . "', '" . _PS_OS_PAYMENT_ . "', now());";
                Db::getInstance()->execute($sql_insert);
            }
            if ((bool) $order->getHistory($context->language->id, Configuration::get('HIPAY_PARTIALLY_CAPTURED'))) {
                echo '/' . (int) Configuration::get('HIPAY_PARTIALLY_CAPTURED') . '_U';
                // Update orders
                $sql_update = "UPDATE `" . _DB_PREFIX_ . "orders`\r\n                    SET `current_state` = '" . Configuration::get('HIPAY_PARTIALLY_CAPTURED') . "'\r\n                    WHERE `id_order`='" . (int) $order_id . "'";
                Db::getInstance()->execute($sql_update);
                // Insert into order_history
                $sql_insert = "INSERT INTO `" . _DB_PREFIX_ . "order_history` (`id_employee`, `id_order`, `id_order_state`, `date_add`)\r\n                    VALUES ('0', '" . (int) $order_id . "', '" . Configuration::get('HIPAY_PARTIALLY_CAPTURED') . "', now());";
                Db::getInstance()->execute($sql_insert);
            }
            HipayLogger::addLog($hipay->l('Callback process', 'hipay'), HipayLogger::NOTICE, 'hipayResetOrderStatus status 116 cart already ok - cid : ' . (int) $_POST['order']->id);
            die;
        } else {
            echo '/C_KO' . $GLOBALS['_HIPAY_CALLBACK_ORDER_ID_'];
        }
    }
    HipayLogger::addLog($hipay->l('Callback process', 'hipay'), HipayLogger::NOTICE, 'hipayResetOrderStatus ended - cid : ' . (int) $_POST['order']->id);
    die;
}
 /**
  *
  * @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 hookPayment($params)
 {
     global $smarty, $cookie;
     if (!$this->active) {
         return;
     }
     // Verify if customer has memorized tokens
     // $cart = $this->context->cart; // v1.5
     $cart = new Cart((int) $cookie->id_cart);
     $tokens = HipayToken::getTokens($cart->id_customer);
     // Retrieve list of tokens
     if (isset($tokens['0'])) {
         $token_display = 'true';
     } else {
         $token_display = 'false';
     }
     // Verify if systems should display memorized tokens
     $allow_memorize = HipayClass::getShowMemorization();
     // If both are true, activate additional info to allow payment via existing token
     if ($allow_memorize == 'true') {
         $currency_array = $this->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;
         }
         $smarty->assign(array('cart_id' => $cart->id, 'currency' => $currency, 'amount' => $cart->getOrderTotal(true, Cart::BOTH)));
     }
     // Create dynamic payment button
     $card_str = Configuration::get('HIPAY_ALLOWED_CARDS');
     $cart_arr = explode(',', $card_str);
     $card_currency = Configuration::get('HIPAY_CURRENCY_CARDS');
     if (Tools::strlen($card_currency) > 3) {
         $currency_array = $this->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'];
             }
         }
         $card_currency_arr = explode(',', Tools::substr($card_currency, 1, -1));
         foreach ($card_currency_arr as $key => $value) {
             foreach ($cart_arr as $cardkey => $cardvalue) {
                 if ($value == '"' . $actual_currency . '-' . $cardvalue . '"') {
                     $card_curr_val[$cardvalue] = true;
                 }
             }
         }
     } else {
         foreach ($cart_arr as $cardkey => $cardvalue) {
             $card_curr_val[$cardvalue] = true;
         }
     }
     $btn_image = '';
     $card_currency_ok = '0';
     $payment_product_list_upd = '';
     $count_ccards = 0;
     foreach ($cart_arr as $key => $value) {
         if ($value == 'visa' && $card_curr_val['visa']) {
             $btn_image .= '<img class= "hipay_method" src="' . _MODULE_DIR_ . $this->name . '/img/visa_small.png" alt="Visa" />';
             $card_currency_ok = '1';
             $payment_product_list_upd .= 'visa,';
             $count_ccards++;
         }
         if ($value == 'mastercard' && $card_curr_val['mastercard']) {
             $btn_image .= '<img class= "hipay_method" src="' . _MODULE_DIR_ . $this->name . '/img/mc_small.png" alt="MasterCard" />';
             $card_currency_ok = '1';
             $payment_product_list_upd .= 'mastercard,';
             $count_ccards++;
         }
         if ($value == 'american-express' && $card_curr_val['american-express']) {
             $btn_image .= '<img class= "hipay_method" src="' . _MODULE_DIR_ . $this->name . '/img/amex_small.png" alt="American Express" />';
             $card_currency_ok = '1';
             $payment_product_list_upd .= 'american-express,';
             $count_ccards++;
         }
         if ($value == 'bcmc' && $card_curr_val['bcmc']) {
             $btn_image .= '<img class= "hipay_method" src="' . _MODULE_DIR_ . $this->name . '/img/bcmc_small.png" alt="Bancontact / Mister Cash" />';
             $card_currency_ok = '1';
             $payment_product_list_upd .= 'bcmc,';
             $count_ccards++;
         }
         if ($value == 'cb' && $card_curr_val['cb']) {
             $btn_image .= '<img class= "hipay_method" src="' . _MODULE_DIR_ . $this->name . '/img/cb_small.png" alt="CB" />';
             $card_currency_ok = '1';
             $payment_product_list_upd .= 'cb,';
             $count_ccards++;
         }
         if ($value == 'maestro' && $card_curr_val['maestro']) {
             $btn_image .= '<img class= "hipay_method" src="' . _MODULE_DIR_ . $this->name . '/img/maestro_small.png" alt="Maestro" />';
             $card_currency_ok = '1';
             $payment_product_list_upd .= 'maestro,';
             $count_ccards++;
         }
     }
     // Assign smarty variables
     $smarty->assign(array('token_display' => $token_display, 'allow_memorize' => $allow_memorize, 'tokens' => $tokens, 'payment_mode' => Configuration::get('HIPAY_PAYMENT_MODE'), 'PS_VERSION' => _PS_VERSION_, 'btn_image' => $btn_image, 'card_currency_ok' => $card_currency_ok, 'payment_product_list_upd' => $payment_product_list_upd, 'count_ccards' => $count_ccards));
     // Assign paths
     $smarty->assign(array('this_path' => $this->_path, 'this_path_bw' => $this->_path, 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/'));
     // Local cards variables
     $localPayments = Tools::jsonDecode(Configuration::get('HIPAY_LOCAL_PAYMENTS'));
     $local_cards = $this->checkLocalCards();
     // Retrieving images and storing in any array associate to the card code.
     $local_cards_img = array();
     $local_cards_name = array();
     $show_cards = array();
     if (count($local_cards)) {
         $currency_array = $this->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'];
             }
         }
         foreach ($local_cards as $key => $value) {
             $local_cards_img[(string) $value->code] = (string) $value->image;
             $local_cards_name[(string) $value->code] = (string) $value->name;
             $show_cards[(string) $value->code] = 'false';
             // Initialize to false
             // Assigning temporary code to variable
             $card_code = (string) $value->code;
             foreach ($value->currencies as $key => $value) {
                 foreach ($value->iso_code as $key => $value) {
                     if (Tools::strtoupper($actual_currency) == Tools::strtoupper((string) $value)) {
                         $show_cards[$card_code] = 'true';
                         // Update to true
                     }
                 }
             }
         }
     }
     if (count($localPayments)) {
         $allow_local_cards = 'true';
     } else {
         $allow_local_cards = 'false';
     }
     $smarty->assign(array('allow_local_cards' => $allow_local_cards, 'local_cards_list' => $localPayments, 'local_cards_img' => $local_cards_img, 'local_cards_name' => $local_cards_name, 'show_cards' => $show_cards));
     // modif One Page Checkout
     // Check if cart is in OPC
     $is_opc = Configuration::get('PS_ORDER_PROCESS_TYPE') ? 'true' : 'false';
     $id_opc = '';
     // Set id_opc to empty by default
     if ($is_opc == 'true') {
         $id_opc = 'OPC';
         // This will update hidden field 'ioBB' to 'ioBBOPC' to prevent duplicate id
     }
     // Add generic smarty variables;
     $smarty->assign(array('id_opc' => $id_opc));
     return $this->display(__FILE__, '1.4/views/templates/hook/payment.tpl');
 }
 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();
     }
 }
 /**
  *
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     $hipay = new HiPay_Tpp();
     $this->display_column_left = false;
     $this->display_column_right = false;
     parent::initContent();
     #PROFILEO64 - Multishop issue when using $this->context->cart. Switching to Context::getContext()
     //$cart = $this->context->cart;
     $context = Context::getContext();
     $cart = $context->cart;
     if (!$this->module->checkCurrency($cart)) {
         Tools::redirect('index.php?controller=order&xer=1');
     }
     // Check if cart_id has already been stored in tbl cart_sent
     $override_payment_mode = false;
     $cart_id_count = Db::getInstance()->getValue("SELECT COUNT( cart_id ) FROM  `" . _DB_PREFIX_ . "hipay_cart_sent` WHERE cart_id = '" . (int) $cart->id . "'");
     if ($cart_id_count == 0) {
         // Not found. Add new entry
         $sql_add_cart_id = "INSERT INTO `" . _DB_PREFIX_ . "hipay_cart_sent` (`cart_id`, `timestamp`)\r\n            VALUES('" . (int) $cart->id . "', NOW() )";
         Db::getInstance()->execute($sql_add_cart_id);
     }
     /*
     		// TPPPRS-23
     		else{
     			// Found. Duplicate cart
     			$duplicate_status_msg = HipayClass::duplicateCart();
     			if($duplicate_status_msg)
     			{
     				$override_payment_mode = true;
     			}
     		}*/
     $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 . '/'));
     $context->controller->addCSS(_MODULE_DIR_ . $this->module->name . '/css/hipay.css');
     $context->controller->addJs(_MODULE_DIR_ . $this->module->name . '/js/15hipay.js');
     $hipay_payment_mode = Configuration::get('HIPAY_PAYMENT_MODE');
     if (Tools::getValue('cartMemorizeToken')) {
         $sql_insert = "INSERT INTO `" . _DB_PREFIX_ . "hipay_tokens_tmp` (`cart_id`) VALUES('" . $cart->id . "')";
         @Db::getInstance()->execute($sql_insert);
     }
     // Initializing the payment mode to the default configuration mode
     $payment_mode = Configuration::get('HIPAY_PAYMENT_MODE');
     // Check card used - if card used is a local card, force mode 'dedicated page'
     if (Tools::isSubmit('localcardToken') && tools::getValue('localcardToken')) {
         // Override to mode page dedicated
         $payment_mode = 3;
     }
     // Last check, if $override_payment_mode = true then override all payement modes and force error message display
     /*
     		// TPPPRS-23
     		if($override_payment_mode) {
     			// Override to mode page cart duplicated
     			$payment_mode = 4;
     			// Use $duplicate_status_msg to display msg err
     		}*/
     // Different calls depending on Payment mode
     switch ($payment_mode) {
         case 1:
             // Mode Iframe
             $data = HipayApi::getApiData($cart, 'iframe');
             $response = $this->restApi('hpayment', $data);
             // Update to display montant
             $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;
             }
             if (Tools::strlen(Configuration::get('HIPAY_IFRAME_WIDTH')) > 0) {
                 $iframe_width = Configuration::get('HIPAY_IFRAME_WIDTH');
             } else {
                 $iframe_width = '100%';
             }
             if (Tools::strlen(Configuration::get('HIPAY_IFRAME_HEIGHT')) > 0) {
                 $iframe_height = Configuration::get('HIPAY_IFRAME_HEIGHT');
             } else {
                 $iframe_height = '670';
             }
             if (_PS_VERSION_ >= '1.6') {
                 $show_breadcrumb = false;
             } else {
                 $show_breadcrumb = true;
             }
             $context->smarty->assign(array('iframe_url' => $response->forwardUrl, 'cart_id' => $cart->id, 'currency' => $currency, 'show_breadcrumb' => $show_breadcrumb, 'amount' => $cart->getOrderTotal(true, Cart::BOTH), 'iframe_width' => $iframe_width, 'iframe_height' => $iframe_height));
             $payment_tpl = 'payment_execution_iframe.tpl';
             break;
         case 2:
             // Mode API
             // Constructs data array and sends it as a parameter to the tpl
             $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' => '200', 'cart_id' => $cart->id, 'currency' => $currency, 'amount' => $cart->getOrderTotal(true, Cart::BOTH)));
             // Tpl will load a form that will store those infomations.
             $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 (isset($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';
             break;
         case 3:
             $local_card = tools::getValue('localcardToken');
             $data = HipayApi::getApiData($cart, null, null, $local_card);
             if ($local_card == 'sofort-uberweisung' || $local_card == 'sisal' || $local_card == 'przelewy24' || $local_card == 'webmoney' || $local_card == 'yandex' || $local_card == 'paypal') {
                 $data['payment_product'] = $local_card;
                 unset($data['payment_product_list']);
                 unset($data['merchant_display_name']);
                 unset($data['css']);
                 $response = $this->restApi('order', $data);
             } else {
                 $response = $this->restApi('hpayment', $data);
             }
             if ($response == false) {
                 // Wrong response, redirect to page order first step
                 Tools::redirect('index.php?controller=order&xer=2');
             }
             Tools::redirect($response->forwardUrl);
             break;
         case 4:
             // Use $duplicate_status_msg to display msg err
             if (_PS_VERSION_ >= '1.6') {
                 $show_breadcrumb = false;
             } else {
                 $show_breadcrumb = true;
             }
             $context->smarty->assign(array('duplicate_status_msg' => $duplicate_status_msg, 'show_breadcrumb' => $show_breadcrumb));
             $payment_tpl = 'payment_cart_duplicate.tpl';
             break;
         case 0:
         default:
             // Dedicated page
             // NO TPL NEEDED, will redirect to response forwardURL
             if (Tools::isSubmit('localcardToken') && tools::getValue('localcardToken')) {
                 $local_card = tools::getValue('localcardToken');
             } else {
                 $local_card = null;
             }
             $data = HipayApi::getApiData($cart, null, null, $local_card);
             $response = $this->restApi('hpayment', $data);
             if ($response == false) {
                 // Wrong response, redirect to page order first step
                 Tools::redirect('index.php?controller=order&xer=2');
             }
             Tools::redirect($response->forwardUrl);
             break;
     }
     $this->setTemplate($payment_tpl);
 }