/**
  * 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;
     }
 }
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/../../header.php';
require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
//die('here');
$hipay = new HiPay_Tpp();
echo $hipay->execIframe($cart);
include_once dirname(__FILE__) . '/../../footer.php';
 /**
  *
  * @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();
     }
 }
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/../../header.php';
require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
//die('here');
$hipay = new HiPay_Tpp();
echo $hipay->execPending($cart);
include_once dirname(__FILE__) . '/../../footer.php';
 /**
  * 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;
 }
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade HiPay to newer
* versions in the future. If you wish to customize HiPay for your
* needs please refer to http://www.hipayfullservice.com/ for more information.
*
*  @author    Support HiPay <*****@*****.**>
*  @copyright © 2015 HIPAY
*  @license   http://opensource.org/licenses/afl-3.0.php
*  
*  Copyright © 2015 HIPAY
*/
/**
 * Initialisation API prestashop
 */
include dirname(__FILE__) . '/../../config/config.inc.php';
if (_PS_VERSION_ < '1.5') {
    // token
    $token = Tools::getValue('token');
    $token_module = Tools::getToken(false);
    if ($token == $token_module) {
        require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
        $hipay = new HiPay_Tpp();
        $hipay->validation_process();
    } else {
        echo "Vous n'avez pas la permission.";
    }
} else {
    echo 'Version Module Hipay is not compatible with your version.';
}
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/../../header.php';
require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
//die('here');
$hipay = new HiPay_Tpp();
echo $hipay->execRefund($cart);
include_once dirname(__FILE__) . '/../../footer.php';
 /**
  *
  * @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');
 }
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include_once dirname(__FILE__) . '/../../../config/config.inc.php';
include_once dirname(__FILE__) . '/../../../header.php';
require_once dirname(__FILE__) . '/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
$hipay = new HiPay_Tpp();
echo $hipay->execPayment($cart);
include_once dirname(__FILE__) . '/../../../footer.php';
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;
}
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/../../header.php';
require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
//die('here');
$hipay = new HiPay_Tpp();
echo $hipay->execCancel($cart);
include_once dirname(__FILE__) . '/../../footer.php';
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/../../header.php';
require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
//die('here');
$hipay = new HiPay_Tpp();
echo $hipay->execPaymentapi($cart);
include_once dirname(__FILE__) . '/../../footer.php';
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/../../header.php';
require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
//die('here');
$hipay = new HiPay_Tpp();
echo $hipay->execAccept($cart);
include_once dirname(__FILE__) . '/../../footer.php';
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;
}
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/../../header.php';
require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
//die('here');
$hipay = new HiPay_Tpp();
echo $hipay->execCapture($cart);
include_once dirname(__FILE__) . '/../../footer.php';
*  @copyright  2007-2013 Profileo
*  
*  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) {
 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;
 }
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/../../header.php';
require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
//die('here');
$hipay = new HiPay_Tpp();
echo $hipay->execException($cart);
include_once dirname(__FILE__) . '/../../footer.php';
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
/* SSL Management */
$useSSL = true;
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/../../header.php';
require_once dirname(__FILE__) . '/1.4/hipay_tpp.php';
if (!$cookie->isLogged(true)) {
    Tools::redirect('authentication.php?back=order.php');
} elseif (!Customer::getAddressesTotalById((int) $cookie->id_customer)) {
    Tools::redirect('address.php?back=order.php?step=1');
}
//die('here');
$hipay = new HiPay_Tpp();
echo $hipay->execDecline($cart);
include_once dirname(__FILE__) . '/../../footer.php';