示例#1
0
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $id_cart = Tools::GetValue('id_cart');
     $cart = new Cart((int) $id_cart);
     $liqpay = new Liqpay();
     $total = $cart->getOrderTotal(true, 3);
     $liqpay->validateOrder(intval($cart->id), Configuration::get('PS_OS_PREPARATION'), $total, $liqpay->displayName);
     $currency = new Currency((int) $cart->id_currency);
     $private_key = Configuration::get('LIQPAY_PRIVATE_KEY');
     $public_key = Configuration::get('LIQPAY_PUBLIC_KEY');
     $amount = number_format($cart->getOrderTotal(true, Cart::BOTH), 1, '.', '');
     $currency = $currency->iso_code == 'RUR' ? 'RUB' : $currency->iso_code;
     $order_id = '000' . $id_cart;
     $description = 'Order #' . $order_id;
     $result_url = 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . __PS_BASE_URI__ . 'index.php?controller=history';
     $server_url = 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . $liqpay->getPath() . 'validation.php';
     $type = 'buy';
     $version = '3';
     $language = Configuration::get('PS_LOCALE_LANGUAGE') == 'en' ? 'en' : 'ru';
     $data = base64_encode(json_encode(array('version' => $version, 'public_key' => $public_key, 'amount' => $amount, 'currency' => $currency, 'description' => $description, 'order_id' => $order_id, 'type' => $type, 'language' => $language)));
     $signature = base64_encode(sha1($private_key . $data . $private_key, 1));
     $this->context->smarty->assign(compact('data', 'signature'));
     $this->setTemplate('redirect.tpl');
 }
 public function postProcess()
 {
     $sid = Configuration::get('TWOCHECKOUTPP_SID');
     $secret_word = Configuration::get('TWOCHECKOUTPP_SECRET');
     $credit_card_processed = $_REQUEST['credit_card_processed'];
     $order_number = $_REQUEST['order_number'];
     $cart_id = $_REQUEST['merchant_order_id'];
     $cart = new Cart($cart_id);
     $checkout = new twocheckoutpp();
     if (Configuration::get('TWOCHECKOUTPP_CURRENCY') > 0) {
         $amount = number_format($cart->getOrderTotal(true, 3), 2, '.', '');
         $currency_from = Currency::getCurrency($cart->id_currency);
         $currency_to = Currency::getCurrency(Configuration::get('TWOCHECKOUTPP_CURRENCY'));
         $amount = Tools::ps_round($amount / $currency_from['conversion_rate'], 2);
         $total = number_format(Tools::ps_round($amount *= $currency_to['conversion_rate'], 2), 2, '.', '');
     } else {
         $total = number_format($cart->getOrderTotal(true, 3), 2, '.', '');
     }
     //Check the hash
     $compare_string = $secret_word . $sid . $order_number . $total;
     $compare_hash1 = strtoupper(md5($compare_string));
     $compare_hash2 = $_REQUEST['key'];
     if ($compare_hash1 == $compare_hash2) {
         $customer = new Customer($cart->id_customer);
         $total = (double) $cart->getOrderTotal(true, Cart::BOTH);
         $checkout->validateOrder($cart_id, _PS_OS_PAYMENT_, $total, $checkout->displayName, '', array(), NULL, false, $customer->secure_key);
         $order = new Order($checkout->currentOrder);
         Tools::redirect('index.php?controller=order-confirmation&id_cart=' . (int) $cart->id . '&id_module=' . (int) $this->module->id . '&id_order=' . $checkout->currentOrder);
     } else {
         echo 'Hash Mismatch! Please contact the seller directly for assistance.</br>';
         echo 'Total: ' . $total . '</br>';
         echo '2CO Total: ' . $_REQUEST['total'];
     }
 }
 /**
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     parse_str($_POST['optData'], $optData);
     $id_cart = (int) $optData['cartId'];
     $cart = new Cart($id_cart);
     if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
         die('Cannot create order for this cart.');
     }
     $customer = new Customer($cart->id_customer);
     if (!Validate::isLoadedObject($customer)) {
         die('No customer for this order.');
     }
     $currency = new Currency((int) $cart->id_currency);
     $paid_amount = $_POST['amount'];
     $order_amount = $cart->getOrderTotal(true, Cart::BOTH);
     $apiHash = $_SERVER['HTTP_API_HASH'];
     $query = http_build_query($_POST);
     $hash = hash_hmac("sha512", $query, $this->module->secret_key);
     if ($apiHash == $hash && $paid_amount == $order_amount) {
         //success
         $this->module->validateOrder($cart->id, Configuration::get('PS_OS_PAYMENT'), $paid_amount, $this->module->displayName, 'Invoice Code: ' . $_POST['invoiceCode'], array(), (int) $currency->id, false, $customer->secure_key);
     } else {
         //failed transaction
     }
 }
示例#4
0
 public function initContent()
 {
     $payu = new PayU();
     $id_cart = Tools::getValue('id_cart');
     $id_payu_session = $this->context->cookie->__get('payu_order_id');
     if (Tools::getValue('error')) {
         Tools::redirect('order.php?error=' . Tools::getValue('error'), __PS_BASE_URI__, null, 'HTTP/1.1 301 Moved Permanently');
     }
     $payu->id_cart = $id_cart;
     $payu->payu_order_id = $id_payu_session;
     $order_payment = $payu->getOrderPaymentBySessionId($payu->payu_order_id);
     $id_order = (int) $order_payment['id_order'];
     $payu->id_cart = (int) $order_payment['id_cart'];
     // if order not validated yet
     $cart_id = $payu->id_cart;
     if ($id_order == 0 && $order_payment['status'] == PayU::PAYMENT_STATUS_NEW) {
         $cart = new Cart($payu->id_cart);
         $cart_id = $cart->id;
         $payu->validateOrder($cart->id, (int) Configuration::get('PAYU_PAYMENT_STATUS_PENDING'), $cart->getOrderTotal(true, Cart::BOTH), $payu->displayName, 'PayU cart ID: ' . $cart_id . ', sessionId: ' . $payu->payu_order_id, null, (int) $cart->id_currency, false, $cart->secure_key, Context::getContext()->shop->id ? new Shop((int) Context::getContext()->shop->id) : null);
         $payu->id_order = $payu->current_order = $payu->{'currentOrder'};
         $payu->updateOrderPaymentStatusBySessionId(PayU::PAYMENT_STATUS_INIT);
     }
     $id_order = $payu->getOrderIdBySessionId($id_payu_session);
     if (!empty($id_order)) {
         $payu->id_order = $id_order;
         $payu->updateOrderData();
     }
     Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cart_id, __PS_BASE_URI__, null, 'HTTP/1.1 301 Moved Permanently');
 }
 private function checkTotalToPaid($amountPaid, $currency)
 {
     if (!$currency instanceof Currency) {
         if (Validate::isInt($currency)) {
             $currency = new Currency((int) $currency);
         } else {
             $currencyCode = $currency;
             if (!($currency = PowaTagPayment::getCurrencyByIsoCode($currency))) {
                 $currency = $currencyCode;
             }
         }
     }
     if (!PowaTagValidate::currencyEnable($currency)) {
         $this->addError(sprintf($this->module->l('Currency is not enable : %s'), isset($currency->iso_code) ? $currency->iso_code : $currency), PowaTagErrorType::$CURRENCY_NOT_SUPPORTED);
         return false;
     }
     //We change context currency to be sure that calculs are made with correct currency
     $context = Context::getContext();
     $context->currency = $currency;
     $context->country = $this->getCountry($this->datas->customer->shippingAddress->country->alpha2Code);
     $price_cart = $this->cart->getOrderTotal(true, Cart::BOTH, null, Configuration::get('POWATAG_SHIPPING'));
     if (abs($price_cart - $amountPaid) >= 0.01) {
         $msg = "Cart: " . $price_cart . " != Payment: " . $amountPaid;
         $this->addError($this->module->l('Amount paid is not same as the cart: ' . $msg), PowaTagErrorType::$INTERNAL_ERROR);
         if (PowaTagAPI::apiLog()) {
             PowaTagLogs::initAPILog('Amount paid is not same as the cart', PowaTagLogs::ERROR, $msg);
         }
         return false;
     }
     return true;
 }
 /**
  * @param $order_payment
  * @param $payu
  * @param $response
  * @return mixed
  */
 private function createOrder($order_payment, Payu $payu, $response)
 {
     $cart = new Cart($order_payment['id_cart']);
     $payu->validateOrder($cart->id, (int) Configuration::get('PAYU_PAYMENT_STATUS_PENDING'), $cart->getOrderTotal(true, Cart::BOTH), $payu->displayName, 'PayU cart ID: ' . $cart->id . ', orderId: ' . $payu->payu_order_id, null, (int) $cart->id_currency, false, $cart->secure_key, Context::getContext()->shop->id ? new Shop((int) Context::getContext()->shop->id) : null);
     $id_order = $payu->current_order = $payu->currentOrder;
     SimplePayuLogger::addLog('notification', __FUNCTION__, 'Status zamówienia PayU: ' . PayU::PAYMENT_STATUS_NEW, $response->order->orderId);
     $payu->updateOrderPaymentStatusBySessionId(PayU::PAYMENT_STATUS_INIT);
     return $id_order;
 }
示例#7
0
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $id_cart = Tools::GetValue('id_cart');
     // получаем get id_cart
     $cart = new Cart((int) $id_cart);
     // Объект корзины
     $onpay = new onpay();
     //Объект onpay
     $total = $cart->getOrderTotal(true, 3);
     //Цена заказа расчёт
     $onpay->validateOrder(intval($cart->id), _PS_OS_PREPARATION_, $total, $onpay->displayName);
     //Создание заказа с статусом ожидаем оплату
     $currency = new Currency((int) $cart->id_currency);
     //получение данные о валюте
     $this->context->smarty->assign(array('login' => Configuration::get('ONPAY_LOGIN'), 'f' => Configuration::get('ONPAY_FORM'), 'id' => (int) $id_cart, 'price' => number_format($cart->getOrderTotal(true, Cart::BOTH), 1, '.', ''), 'currency' => $currency->iso_code == 'RUB' ? 'RUR' : $currency->iso_code, 'md5' => md5('fix;' . number_format($cart->getOrderTotal(true, Cart::BOTH), 1, '.', '') . ';' . ($currency->iso_code == 'RUB' ? 'RUR' : $currency->iso_code) . ';' . (int) $id_cart . ';yes;' . Configuration::get('ONPAY_API_IN_KEY')), 'url_success' => 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . __PS_BASE_URI__ . 'index.php?controller=history', 'this_path' => $this->_path));
     $this->setTemplate('redirect.tpl');
     // Подключение шаблона смарти
 }
 public function initContent()
 {
     parent::initContent();
     if (Tools::getValue('id_cart')) {
         $cart = new Cart((int) Tools::getValue('id_cart'));
         $this->context->smarty->assign(array('total' => Tools::displayPrice($cart->getOrderTotal())));
         return $this->setTemplate('confirmation.tpl');
     } else {
         return $this->setTemplate('error.tpl');
     }
 }
示例#9
0
 public function postProcess()
 {
     $cartId = Tools::getValue('id_cart', false);
     if (!$cartId) {
         Tools::redirect('index.php?controller=order-confirmation');
     }
     $cart = new Cart((int) $cartId);
     if (!$cart->orderExists()) {
         $this->module->validateOrder($cart->id, Configuration::get('PS_OS_CANCELED'), $cart->getOrderTotal(), $this->module->displayName, 'Order cancelled by Aplazame cancel_url', null, null, false, Tools::getValue('key', false));
     }
     $orderId = Order::getOrderByCartId($cart->id);
     Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cart->id . '&id_module=' . $this->module->id . '&id_order=' . $orderId . '&key=' . $cart->secure_key);
 }
示例#10
0
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $code = Tools::getValue('paymentcode');
     $cart = (int) Tools::substr($code, 0, 8);
     $this->nimblepayment_client_secret = Configuration::get('NIMBLEPAYMENT_CLIENT_SECRET');
     $cart = new Cart($cart);
     $order_num = Tools::substr($code, 0, 8);
     $total_url = $cart->getOrderTotal(true, Cart::BOTH) * 100;
     $paramurl = $order_num . md5($order_num . $this->nimblepayment_client_secret . $total_url);
     if ($paramurl == $code) {
         $total = $cart->getOrderTotal(true, Cart::BOTH);
         $extra_vars = array();
         $extra_vars['transaction_id'] = $this->context->cookie->nimble_transaction_id;
         //transaction_id in session
         $this->context->cookie->__set('nimble_transaction_id', '');
         //reset cookie
         $nimble = new nimblepayment();
         $nimble->validateOrder($cart->id, _PS_OS_PAYMENT_, $total, $nimble->displayName, null, $extra_vars, null, false, $cart->secure_key);
         $customer = new Customer($cart->id_customer);
         Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cart->id . '&id_module=' . $nimble->module->id . '&id_order=' . $nimble->module->currentOrder . '&key=' . $customer->secure_key);
     }
 }
示例#11
0
 function verif_champ($post)
 {
     $return = false;
     $conf = Configuration::getMultiple(array('ATOS_MERCHAND_ID'));
     $cookie = new Cookie('ps');
     $id_cart = $cookie->id_cart;
     $cart = new Cart($id_cart);
     $id_currency = intval($cart->id_currency);
     $currency = new Currency(intval($id_currency));
     $montant = number_format(Tools::convertPrice($cart->getOrderTotal(true, 3), $currency), 2, '.', '');
     if (strpos($montant, '.')) {
         $montant = $montant * 100;
     }
     $montant = str_replace('.', '', $montant);
     if ($post['amount'] == $montant && $post['id_cart'] == $id_cart) {
         $return = true;
     }
     //return $return;
     return true;
 }
示例#12
0
 public function postProcess()
 {
     if (Tools::isSubmit('cart_id') == false || Tools::isSubmit('secure_key') == false) {
         return false;
     }
     $cart_id = Tools::getValue('cart_id');
     $secure_key = Tools::getValue('secure_key');
     $cart = new Cart((int) $cart_id);
     $customer = new Customer((int) $cart->id_customer);
     /**
      * Since it's an example we are validating the order right here,
      * You should not do it this way in your own module.
      */
     $payment_status = Configuration::get('PS_OS_PAYMENT');
     // Default value for a payment that succeed.
     $message = null;
     // You can add a comment directly into the order so the merchant will see it in the BO.
     /**
      * Converting cart into a valid order
      */
     $module_name = $this->module->displayName;
     $currency_id = (int) Context::getContext()->currency->id;
     $this->module->validateOrder($cart_id, $payment_status, $cart->getOrderTotal(), $module_name, $message, array(), $currency_id, false, $secure_key);
     /**
      * If the order has been validated we try to retrieve it
      */
     $order_id = Order::getOrderByCartId((int) $cart->id);
     if ($order_id && $secure_key == $customer->secure_key) {
         /**
          * The order has been placed so we redirect the customer on the confirmation page.
          */
         $module_id = $this->module->id;
         Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cart_id . '&id_module=' . $module_id . '&id_order=' . $order_id . '&key=' . $secure_key);
     } else {
         /**
          * An error occured and is shown on a new page.
          */
         $this->errors[] = $this->module->l('An error occured. Please contact the merchant to have more informations');
         return $this->setTemplate('error.tpl');
     }
 }
    /**
     *
     * @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');
    }
 public function initContent()
 {
     if (!Tools::getValue('redirect')) {
         $module_name = $this->module->displayName;
         $currency_id = (int) Context::getContext()->currency->id;
         $json = file_get_contents('php://input');
         $data = json_decode($json, true);
         /*$json = Tools::file_get_contents('php://input');
           $data = Tools::json_decode($json, true);*/
         $order_id = $data["data"]["order_id"];
         $cart_id = $order_id;
         if ($data["event"] == 'charge.created') {
             $cart = new Cart((int) $cart_id);
             $customer = new Customer((int) $cart->id_customer);
             $secure_key = $customer->secure_key;
             $payment_status = Configuration::get('PS_OS_PAYMENT');
             $message = null;
             $this->module->validateOrder($cart_id, $payment_status, $cart->getOrderTotal(), $module_name, $message, array(), $currency_id, false, $secure_key);
             Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cart->id . '&id_module=' . $this->module->id . '&id_order=' . $this->module->currentOrder . '&key=' . $secure_key);
         }
     }
 }
示例#15
0
/*
Tester le header de la requette HTTP
*/
include dirname(__FILE__) . '/../../config/config.inc.php';
include dirname(__FILE__) . '/smtsps.php';
$errors = '';
$result = false;
$smt = new SmtSps();
$ref = $_GET['Reference'];
$act = $_GET['Action'];
$par = $_GET['Param'];
$temp = explode("TN-", $ref);
$id = str_replace("CMD", "", $temp[0]);
$id = intval($id) - 22002;
$cart = new Cart($id);
$Value = floatval($cart->getOrderTotal(true, 3));
$decimals = log10(abs($Value));
$decimals = -(intval(min($decimals, 0)) - 3);
$format = "%." . $decimals . "f";
$montant = sprintf($format, $Value);
switch ($act) {
    case "DETAIL":
        $tampon = "Reference=" . $ref . "&Action=" . $act . "&Reponse=" . $montant;
        break;
    case "ERREUR":
        //	$smt->validateOrder($id, _PS_OS_ERROR_, 0, $smt->displayName, $smt->l('erreur ').$act);
        $tampon = "Reference=" . $ref . "&Action=" . $act . "&Reponse=OK";
        break;
    case "ACCORD":
        $tampon = "Reference=" . $ref . "&Action=" . $act . "&Reponse=OK";
        $extra['transaction_id'] = $par;
示例#16
0
 protected function _deleteProduct($orderDetail, $quantity)
 {
     $price = $orderDetail->product_price * (1 + $orderDetail->tax_rate * 0.01);
     if ($orderDetail->reduction_percent != 0.0) {
         $reduction_amount = $price * $orderDetail->reduction_percent / 100;
     } elseif ($orderDetail->reduction_amount != '0.000000') {
         $reduction_amount = Tools::ps_round($orderDetail->reduction_amount, 2);
     }
     if (isset($reduction_amount) && $reduction_amount) {
         $price = Tools::ps_round($price - $reduction_amount, 2);
     }
     $productPriceWithoutTax = number_format($price / (1 + $orderDetail->tax_rate * 0.01), 2, '.', '');
     $price += Tools::ps_round($orderDetail->ecotax * (1 + $orderDetail->ecotax_tax_rate / 100), 2);
     $productPrice = number_format($quantity * $price, 2, '.', '');
     /* Update cart */
     $cart = new Cart($this->id_cart);
     $cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 'down');
     // customization are deleted in deleteCustomization
     $cart->update();
     /* Update order */
     $shippingDiff = $this->total_shipping - $cart->getOrderShippingCost();
     $this->total_products -= $productPriceWithoutTax;
     // After upgrading from old version
     // total_products_wt is null
     // removing a product made order total negative
     // and don't recalculating totals (on getTotalProductsWithTaxes)
     if ($this->total_products_wt != 0) {
         $this->total_products_wt -= $productPrice;
     }
     $this->total_shipping = $cart->getOrderShippingCost();
     /* It's temporary fix for 1.3 version... */
     if ($orderDetail->product_quantity_discount != '0.000000') {
         $this->total_paid -= $productPrice + $shippingDiff;
     } else {
         $this->total_paid = $cart->getOrderTotal();
     }
     $this->total_paid_real -= $productPrice + $shippingDiff;
     /* Prevent from floating precision issues (total_products has only 2 decimals) */
     if ($this->total_products < 0) {
         $this->total_products = 0;
     }
     if ($this->total_paid < 0) {
         $this->total_paid = 0;
     }
     if ($this->total_paid_real < 0) {
         $this->total_paid_real = 0;
     }
     /* Prevent from floating precision issues */
     $this->total_paid = number_format($this->total_paid, 2, '.', '');
     $this->total_paid_real = number_format($this->total_paid_real, 2, '.', '');
     $this->total_products = number_format($this->total_products, 2, '.', '');
     $this->total_products_wt = number_format($this->total_products_wt, 2, '.', '');
     /* Update order detail */
     $orderDetail->product_quantity -= (int) $quantity;
     if (!$orderDetail->product_quantity) {
         if (!$orderDetail->delete()) {
             return false;
         }
         if (count($this->getProductsDetail()) == 0) {
             $history = new OrderHistory();
             $history->id_order = (int) $this->id;
             $history->changeIdOrderState(Configuration::get('PS_OS_CANCELED'), (int) $this->id);
             if (!$history->addWithemail()) {
                 return false;
             }
         }
         return $this->update();
     }
     return $orderDetail->update() && $this->update();
 }
示例#17
0
$paypal = new Paypal();
$cart = new Cart((int) $cookie->id_cart);
$address = new Address((int) $cart->id_address_delivery);
$country = new Country((int) $address->id_country);
$state = NULL;
if ($address->id_state) {
    $state = new State((int) $address->id_state);
}
$customer = new Customer((int) $cart->id_customer);
$business = Configuration::get('PAYPAL_BUSINESS');
$header = Configuration::get('PAYPAL_HEADER');
$currency_order = new Currency((int) $cart->id_currency);
$currency_module = $paypal->getCurrency((int) $cart->id_currency);
if (empty($business) or !Validate::isEmail($business)) {
    die($paypal->getL('Paypal error: (invalid or undefined business account email)'));
}
if (!Validate::isLoadedObject($address) or !Validate::isLoadedObject($customer) or !Validate::isLoadedObject($currency_module)) {
    die($paypal->getL('Paypal error: (invalid address or customer)'));
}
// check currency of payment
if ($currency_order->id != $currency_module->id) {
    $cookie->id_currency = $currency_module->id;
    $cart->id_currency = $currency_module->id;
    $cart->update();
}
$smarty->assign(array('redirect_text' => $paypal->getL('Please wait, redirecting to Paypal... Thanks.'), 'cancel_text' => $paypal->getL('Cancel'), 'cart_text' => $paypal->getL('My cart'), 'return_text' => $paypal->getL('Return to shop'), 'paypal_url' => $paypal->getPaypalStandardUrl(), 'address' => $address, 'country' => $country, 'state' => $state, 'amount' => (double) $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), 'customer' => $customer, 'total' => (double) $cart->getOrderTotal(true, Cart::BOTH), 'shipping' => Tools::ps_round((double) $cart->getOrderShippingCost() + (double) $cart->getOrderTotal(true, Cart::ONLY_WRAPPING), 2), 'discount' => $cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS), 'business' => $business, 'currency_module' => $currency_module, 'cart_id' => (int) $cart->id . '_' . pSQL($cart->secure_key), 'products' => $cart->getProducts(), 'paypal_id' => (int) $paypal->id, 'header' => $header, 'url' => Tools::getShopDomain(true, true) . __PS_BASE_URI__));
if (is_file(_PS_THEME_DIR_ . 'modules/paypal/standard/redirect.tpl')) {
    $smarty->display(_PS_THEME_DIR_ . 'modules/' . $paypal->name . '/standard/redirect.tpl');
} else {
    $smarty->display(_PS_MODULE_DIR_ . $paypal->name . '/standard/redirect.tpl');
}
示例#18
0
 /**
  * get the total price of the shopping cart as Danish Kroner
  * @param Cart|Order $cart
  * @return floate
  */
 public function __getPriceDkk($cart, $t = 1)
 {
     /* t==1 use prestashop to convert in Cart Class */
     $_shop_currency = Currency::getDefaultCurrency();
     $_cart_currency = new Currency($cart->id_currency);
     if ($t == 1) {
         $oldc = $cart->id_currency;
         $cart->id_currency = (int) Currency::getIdByIsoCode('DKK');
         $price = $cart->getOrderTotal(true, Cart::BOTH);
         $cart->id_currency = $oldc;
         return $price;
         //            $price = $cart->getOrderTotal(true, Cart::BOTH);
         //            if ($cart->id_currency != $_shop_currency->id) {
         //                $_shop_price = ($price / $_cart_currency->conversion_rate);
         //            } else
         //                $_shop_price = $price;
         //            return Tools::convertPrice($_shop_price, Currency::getCurrencyInstance((int) (Currency::getIdByIsoCode('DKK'))));
     } else {
         /* t!=1 convert manualy */
         $_cart_price = $cart->total_paid;
         $_dkk_currency = new Currency(Currency::getIdByIsoCode('DKK'));
         if ($_cart_currency->id != $_shop_currency->id) {
             /* convert price to shop default */
             $_shop_price = $_cart_price / $_cart_currency->conversion_rate;
         } else {
             $_shop_price = $_cart_price;
         }
         if (strtoupper($_shop_currency->iso_code) != "DKK") {
             /* convert price to DKK */
             return $_shop_price * $_dkk_currency->conversion_rate;
         } else {
             return $_shop_price;
         }
     }
 }
示例#19
0
 public function hookPayment($params)
 {
     if (!$this->active) {
         return;
     }
     global $smarty, $cart;
     $currency = new Currency($params['cart']->id_currency);
     if ($currency->iso_code != 'EUR') {
         return;
     }
     if (!$this->verifAccount()) {
         return;
     }
     $cart = new Cart($params['cart']->id);
     $total = $cart->getOrderTotal();
     if ((int) $total < 1 && (int) $total > 1800) {
         return;
     }
     $times = Configuration::get('BUYSTER_PAYMENT_TIME_PAYMENT');
     $initAccount = Configuration::get('BUYSTER_PAYMENT_INITIAL_AMOUNT');
     if ($total > $initAccount) {
         $paymentN = Configuration::get('BUYSTER_PAYMENT_SEVERAL_PAYMENT');
     } else {
         $payment = 0;
     }
     $var = array('path' => $this->_path, 'this_path_ssl' => (_PS_VERSION_ >= 1.4 ? Tools::getShopDomainSsl(true, true) : '') . __PS_BASE_URI__ . 'modules/' . $this->_moduleName . '/', 'paymentN' => $paymentN, 'times' => $times, 'period' => Configuration::get('BUYSTER_PAYMENT_PERIOD_PAYMENT'), 'initAccount' => $initAccount, 'restAmount' => ($total - Configuration::get('BUYSTER_PAYMENT_INITIAL_AMOUNT')) / ((int) $times - 1));
     $smarty->assign('var', $var);
     return $this->display(__FILE__, 'tpl/payment.tpl');
 }
 public function postProcess()
 {
     parent::postProcess();
     $dd = serialize($_REQUEST);
     $this->log_on = Configuration::get('YA_ORG_LOGGING_ON');
     if ($this->log_on) {
         $this->module->log_save('payment_kassa ' . $dd);
     }
     Tools::getValue('label') ? $data = explode('_', Tools::getValue('label')) : ($data = explode('_', Tools::getValue('customerNumber')));
     if (!empty($data) && $data[0] == 'KASSA') {
         $cart = new Cart($data[1]);
         if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
             Tools::redirect('index.php?controller=order&step=1');
         }
         $customer = new Customer($cart->id_customer);
         if (!Validate::isLoadedObject($customer)) {
             Tools::redirect('index.php?controller=order&step=1');
         }
         $total_to_pay = $cart->getOrderTotal(true);
         $rub_currency_id = Currency::getIdByIsoCode('RUB');
         if ($cart->id_currency != $rub_currency_id) {
             $from_currency = new Currency($cart->id_currency);
             $to_currency = new Currency($rub_currency_id);
             $total_to_pay = Tools::convertPriceFull($total_to_pay, $from_currency, $to_currency);
         }
         $total_to_pay = number_format($total_to_pay, 2, '.', '');
         $amount = Tools::getValue('orderSumAmount');
         $action = Tools::getValue('action');
         $shopId = Tools::getValue('shopId');
         $invoiceId = Tools::getValue('invoiceId');
         $signature = md5($action . ';' . $amount . ';' . Tools::getValue('orderSumCurrencyPaycash') . ';' . Tools::getValue('orderSumBankPaycash') . ';' . $shopId . ';' . $invoiceId . ';' . Tools::getValue('customerNumber') . ';' . trim(Configuration::get('YA_ORG_MD5_PASSWORD')));
         $ord = $cart->orderExists() ? new Order((int) Order::getOrderByCartId($cart->id)) : $this->module->validateOrder($cart->id, _PS_OS_PREPARATION_, $cart->getOrderTotal(true, Cart::BOTH), $this->module->displayName, NULL, array(), NULL, false, $cart->secure_key);
         if (!$ord) {
             $this->module->validateResponse($this->module->l('Invalid order number'), 1, $action, $shopId, $invoiceId, true);
         }
         if (Tools::strtoupper($signature) != Tools::strtoupper(Tools::getValue('md5'))) {
             $this->module->validateResponse($this->module->l('Invalid signature'), 1, $action, $shopId, $invoiceId, true);
         }
         if ($amount != $total_to_pay) {
             $this->module->validateResponse($this->module->l('Incorrect payment amount'), $action == 'checkOrder' ? 100 : 200, $action, $shopId, $invoiceId, true);
         }
         if ($action == 'checkOrder') {
             if ($this->log_on) {
                 $this->module->log_save('payment_kassa: checkOrder invoiceId="' . $invoiceId . '" shopId="' . $shopId . '" ' . $this->module->l('check order'));
             }
             $this->module->validateResponse('', 0, $action, $shopId, $invoiceId, true);
         }
         if ($action == 'paymentAviso') {
             $history = new OrderHistory();
             $history->id_order = $ord->id;
             $history->changeIdOrderState(Configuration::get('PS_OS_PAYMENT'), $ord->id);
             $history->addWithemail(true);
             if ($this->log_on) {
                 $this->module->log_save('payment_kassa: paymentAviso invoiceId="' . $invoiceId . '" shopId="' . $shopId . '" #' . $ord->id . ' ' . $this->module->l('Order success'));
             }
             $this->module->validateResponse('', 0, $action, $shopId, $invoiceId, true);
         }
     } else {
         Tools::redirect('index.php?controller=order&step=3');
     }
 }
 public function postProcess()
 {
     // 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)) {
             $this->errors[] = Tools::displayError('The order cannot be found within your database.');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     /* Update shipping number */
     if (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) && ($module_name = Tools::getValue('payment_module_name')) && ($id_order_state = Tools::getValue('id_order_state')) && Validate::isModuleName($module_name)) {
         if ($this->tabAccess['edit'] === '1') {
             if (!Configuration::get('PS_CATALOG_MODE')) {
                 $payment_module = Module::getInstanceByName($module_name);
             } else {
                 $payment_module = new BoOrder();
             }
             $cart = new Cart((int) $id_cart);
             Context::getContext()->currency = new Currency((int) $cart->id_currency);
             Context::getContext()->customer = new Customer((int) $cart->id_customer);
             $bad_delivery = false;
             if (($bad_delivery = (bool) (!Address::isCountryActiveById((int) $cart->id_address_delivery))) || !Address::isCountryActiveById((int) $cart->id_address_invoice)) {
                 if ($bad_delivery) {
                     $this->errors[] = Tools::displayError('This delivery address country is not active.');
                 } else {
                     $this->errors[] = Tools::displayError('This invoice address country is not active.');
                 }
             } else {
                 $employee = new Employee((int) Context::getContext()->cookie->id_employee);
                 $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(true, Cart::BOTH), $payment_module->displayName, $this->l('Manual order -- Employee:') . ' ' . substr($employee->firstname, 0, 1) . '. ' . $employee->lastname, array(), null, false, $cart->secure_key);
                 if ($payment_module->currentOrder) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } else {
         parent::postProcess();
     }
 }
示例#22
0
 public function makePayPalAPIValidation($cookie, $cart, $id_currency, $payerID, $type)
 {
     global $cookie;
     if (!$this->active) {
         return;
     }
     if (!$this->_isPayPalAPIAvailable()) {
         return;
     }
     // Filling-in vars
     $id_cart = (int) $cart->id;
     $currency = new Currency((int) $id_currency);
     $iso_currency = $currency->iso_code;
     $token = $cookie->paypal_token;
     $total = (double) $cart->getOrderTotal(true, PayPal::BOTH);
     $paymentType = Configuration::get('PAYPAL_CAPTURE') == 1 ? 'Authorization' : 'Sale';
     $serverName = urlencode($_SERVER['SERVER_NAME']);
     $bn = $type == 'express' ? 'ECS' : 'ECM';
     $notifyURL = urlencode(PayPal::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/paypal/ipn.php');
     // Getting address
     if (isset($cookie->id_cart) and $cookie->id_cart) {
         $cart = new Cart((int) $cookie->id_cart);
     }
     if (isset($cart->id_address_delivery) and $cart->id_address_delivery) {
         $address = new Address((int) $cart->id_address_delivery);
     }
     $requestAddress = '';
     if (Validate::isLoadedObject($address)) {
         $country = new Country((int) $address->id_country);
         $state = new State((int) $address->id_state);
         $requestAddress = '&SHIPTONAME=' . urlencode($address->company . ' ' . $address->firstname . ' ' . $address->lastname) . '&SHIPTOSTREET=' . urlencode($address->address1 . ' ' . $address->address2) . '&SHIPTOCITY=' . urlencode($address->city) . '&SHIPTOSTATE=' . urlencode($address->id_state ? $state->iso_code : $country->iso_code) . '&SHIPTOCOUNTRYCODE=' . urlencode($country->iso_code) . '&SHIPTOZIP=' . urlencode($address->postcode);
     }
     // Making request
     $request = '&TOKEN=' . urlencode($token) . '&PAYERID=' . urlencode($payerID) . '&PAYMENTACTION=' . $paymentType . '&AMT=' . $total . '&CURRENCYCODE=' . $iso_currency . '&IPADDRESS=' . $serverName . '&NOTIFYURL=' . $notifyURL . '&BUTTONSOURCE=PRESTASHOP_' . $bn . $requestAddress;
     $discounts = (double) $cart->getOrderTotal(true, PayPal::ONLY_DISCOUNTS);
     if ($discounts == 0) {
         $products = $cart->getProducts();
         $amt = 0;
         for ($i = 0; $i < sizeof($products); $i++) {
             $request .= '&L_NAME' . $i . '=' . substr(urlencode($products[$i]['name'] . (isset($products[$i]['attributes']) ? ' - ' . $products[$i]['attributes'] : '') . (isset($products[$i]['instructions']) ? ' - ' . $products[$i]['instructions'] : '')), 0, 127);
             $request .= '&L_AMT' . $i . '=' . urlencode($this->PayPalRound($products[$i]['price']));
             $request .= '&L_QTY' . $i . '=' . urlencode($products[$i]['cart_quantity']);
             $amt += $this->PayPalRound($products[$i]['price']) * $products[$i]['cart_quantity'];
         }
         $shipping = $this->PayPalRound($cart->getOrderShippingCost($cart->id_carrier, false));
         $request .= '&ITEMAMT=' . urlencode($amt);
         $request .= '&SHIPPINGAMT=' . urlencode($shipping);
         $request .= '&TAXAMT=' . urlencode((double) max($this->PayPalRound($total - $amt - $shipping), 0));
     } else {
         $products = $cart->getProducts();
         $description = 0;
         for ($i = 0; $i < sizeof($products); $i++) {
             $description .= ($description == '' ? '' : ', ') . $products[$i]['cart_quantity'] . " x " . $products[$i]['name'] . (isset($products[$i]['attributes']) ? ' - ' . $products[$i]['attributes'] : '') . (isset($products[$i]['instructions']) ? ' - ' . $products[$i]['instructions'] : '');
         }
         $request .= '&ORDERDESCRIPTION=' . urlencode(substr($description, 0, 120));
     }
     // Calling PayPal API
     include_once _PS_MODULE_DIR_ . 'paypal/api/paypallib.php';
     $ppAPI = new PaypalLib();
     $result = $ppAPI->makeCall($this->getAPIURL(), $this->getAPIScript(), 'DoExpressCheckoutPayment', $request);
     $this->_logs = array_merge($this->_logs, $ppAPI->getLogs());
     // Checking PayPal result
     if (!is_array($result) or !sizeof($result)) {
         $this->displayPayPalAPIError($this->l('Authorization to PayPal failed.'), $this->_logs);
     } elseif (!isset($result['ACK']) or strtoupper($result['ACK']) != 'SUCCESS') {
         $this->displayPayPalAPIError($this->l('PayPal return error.'), $this->_logs);
     } elseif (!isset($result['TOKEN']) or $result['TOKEN'] != $cookie->paypal_token) {
         $logs[] = '<b>' . $ppExpress->l('Token given by PayPal is not the same as the cookie token', 'submit') . '</b>';
         $ppExpress->displayPayPalAPIError($ppExpress->l('PayPal return error.', 'submit'), $logs);
     }
     // Making log
     $id_transaction = $result['TRANSACTIONID'];
     if (Configuration::get('PAYPAL_CAPTURE')) {
         $this->_logs[] = $this->l('Authorization for deferred payment granted by PayPal.');
     } else {
         $this->_logs[] = $this->l('Order finished with PayPal!');
     }
     $message = Tools::htmlentitiesUTF8(strip_tags(implode("\n", $this->_logs)));
     // Order status
     switch ($result['PAYMENTSTATUS']) {
         case 'Completed':
             $id_order_state = Configuration::get('PS_OS_PAYMENT');
             break;
         case 'Pending':
             if ($result['PENDINGREASON'] != 'authorization') {
                 $id_order_state = Configuration::get('PS_OS_PAYPAL');
             } else {
                 $id_order_state = (int) Configuration::get('PAYPAL_OS_AUTHORIZATION');
             }
             break;
         default:
             $id_order_state = Configuration::get('PS_OS_ERROR');
     }
     // Call payment validation method
     $this->validateOrder($id_cart, $id_order_state, (double) $cart->getOrderTotal(true, PayPal::BOTH), $this->displayName, $message, array('transaction_id' => $id_transaction, 'payment_status' => $result['PAYMENTSTATUS'], 'pending_reason' => $result['PENDINGREASON']), $id_currency, false, $cart->secure_key);
     // Clean cookie
     unset($cookie->paypal_token);
     // Displaying output
     $order = new Order((int) $this->currentOrder);
     Tools::redirectLink(__PS_BASE_URI__ . 'order-confirmation.php?id_cart=' . (int) $id_cart . '&id_module=' . (int) $this->id . '&id_order=' . (int) $this->currentOrder . '&key=' . $order->secure_key);
 }
示例#23
0
 /**
  * Parse IPN Request
  *
  * @param array $post   Post data
  * @return integer      Status code
  */
 public function parseIpn($post)
 {
     $apiKey = Configuration::get('MTGOX_API_KEY');
     $apiSecretKey = Configuration::get('MTGOX_API_SECRET_KEY');
     $postData = file_get_contents("php://input");
     $goodSign = hash_hmac('sha512', $postData, base64_decode($apiSecretKey), TRUE);
     $sign = base64_decode($_SERVER['HTTP_REST_SIGN']);
     if ($sign == $goodSign) {
         $status = $post['status'];
         $data = explode(',', trim(stripslashes($post['data'])));
         $cartId = $data[0];
         $secureKey = $data[1];
         $cart = new Cart($cartId);
         switch ($status) {
             case 'paid':
                 if ($this->validateOrder($cartId, 2, $cart->getOrderTotal(), 'MtGox', 'Transaction Id: ' . $post['payment_id'] . ' ', array(), null, false, $secureKey) == true) {
                     echo '[OK]';
                 }
                 break;
             case 'partial':
                 echo '[OK]';
                 break;
             case 'cancelled':
                 echo '[OK]';
                 break;
             default:
                 break;
         }
     }
 }
示例#24
0
 case "request-received":
     break;
 case "error":
     break;
 case "diagnosis":
     break;
 case "checkout-redirect":
     break;
 case "merchant-calculation-callback":
     break;
 case "new-order-notification":
     $gcheckout = new GCheckout();
     $id_cart = intval($data[$root]['shopping-cart']['merchant-private-data']['VALUE']);
     $cart = new Cart($id_cart);
     $orderTotal = floatval($data[$root]['order-total']['VALUE']);
     $gcheckout->validateOrder($id_cart, _PS_OS_PAYMENT_, $cart->getOrderTotal(), $gcheckout->displayName);
     $Gresponse->SendAck();
     break;
 case "order-state-change-notification":
     $Gresponse->SendAck();
     break;
 case "charge-amount-notification":
     $Gresponse->SendAck();
     break;
 case "chargeback-amount-notification":
     $Gresponse->SendAck();
     break;
 case "refund-amount-notification":
     $Gresponse->SendAck();
     break;
 case "risk-information-notification":
示例#25
0
 /**
  * @deprecated 1.5.0
  */
 public static function paymentReturn($id_order, $id_module)
 {
     Tools::displayAsDeprecated();
     if (Validate::isUnsignedId($id_order) && Validate::isUnsignedId($id_module)) {
         $params = array();
         $order = new Order((int) $id_order);
         $currency = new Currency((int) $order->id_currency);
         if (Validate::isLoadedObject($order)) {
             $cart = new Cart((int) $order->id_cart);
             $params['total_to_pay'] = $cart->getOrderTotal();
             $params['currency'] = $currency->sign;
             $params['objOrder'] = $order;
             $params['currencyObj'] = $currency;
             return Hook::exec('paymentReturn', $params, (int) $id_module);
         }
     }
     return false;
 }
 /**
  * Find an open token with the submitted id. If found it means
  *  it can be used.
  *
  * @param int $token
  * @return a token row or false if not found
  */
 private function _canUseToken($token)
 {
     global $cart;
     $params = array('id' => $token, 'status' => self::OPEN, 'id_cart' => (int) $cart->id, 'id_order' => NULL, _DB_PREFIX_ . 'everypay_tokens.id_customer' => (int) $cart->id_customer);
     $result = $this->_getCardToken($params);
     if (!$result) {
         return false;
     }
     if ($result[0]['secsDiff'] > $this->configuration['EVERYPAY_EXPIRATION_SECONDS']) {
         $closeParams = array_merge(array('tokenRow' => $result[0]), array('status' => self::ERRORNEOUS, 'message' => 'Expired'));
         $cart2 = new Cart((int) $result[0]['id_cart']);
         $closeParams['cart'] = $cart2;
         $closeParams['amountInteger'] = (int) $cart2->getOrderTotal() * 100;
         return false;
     }
     return $result[0];
 }
示例#27
0
 public function getTotlePrice(){
      $cart=new Cart((int)($cookie->id_cart));
      $total = $cart->getOrderTotal(true, Cart::BOTH);
      return $total; 
 }
示例#28
0
 public function ajaxProcessAddProductOnOrder()
 {
     // Load object
     $order = new Order((int) Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The order object cannot be loaded.'))));
     }
     if ($order->hasBeenShipped()) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('You cannot add products to delivered orders. '))));
     }
     $product_informations = $_POST['add_product'];
     if (isset($_POST['add_invoice'])) {
         $invoice_informations = $_POST['add_invoice'];
     } else {
         $invoice_informations = array();
     }
     $product = new Product($product_informations['product_id'], false, $order->id_lang);
     if (!Validate::isLoadedObject($product)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The product object cannot be loaded.'))));
     }
     if (isset($product_informations['product_attribute_id']) && $product_informations['product_attribute_id']) {
         $combination = new Combination($product_informations['product_attribute_id']);
         if (!Validate::isLoadedObject($combination)) {
             die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The combination object cannot be loaded.'))));
         }
     }
     // Total method
     $total_method = Cart::BOTH_WITHOUT_SHIPPING;
     // Create new cart
     $cart = new Cart();
     $cart->id_shop_group = $order->id_shop_group;
     $cart->id_shop = $order->id_shop;
     $cart->id_customer = $order->id_customer;
     $cart->id_carrier = $order->id_carrier;
     $cart->id_address_delivery = $order->id_address_delivery;
     $cart->id_address_invoice = $order->id_address_invoice;
     $cart->id_currency = $order->id_currency;
     $cart->id_lang = $order->id_lang;
     $cart->secure_key = $order->secure_key;
     // Save new cart
     $cart->add();
     // Save context (in order to apply cart rule)
     $this->context->cart = $cart;
     $this->context->customer = new Customer($order->id_customer);
     // always add taxes even if there are not displayed to the customer
     $use_taxes = true;
     $initial_product_price_tax_incl = Product::getPriceStatic($product->id, $use_taxes, isset($combination) ? $combination->id : null, 2, null, false, true, 1, false, $order->id_customer, $cart->id, $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
     // Creating specific price if needed
     if ($product_informations['product_price_tax_incl'] != $initial_product_price_tax_incl) {
         $specific_price = new SpecificPrice();
         $specific_price->id_shop = 0;
         $specific_price->id_shop_group = 0;
         $specific_price->id_currency = 0;
         $specific_price->id_country = 0;
         $specific_price->id_group = 0;
         $specific_price->id_customer = $order->id_customer;
         $specific_price->id_product = $product->id;
         if (isset($combination)) {
             $specific_price->id_product_attribute = $combination->id;
         } else {
             $specific_price->id_product_attribute = 0;
         }
         $specific_price->price = $product_informations['product_price_tax_excl'];
         $specific_price->from_quantity = 1;
         $specific_price->reduction = 0;
         $specific_price->reduction_type = 'amount';
         $specific_price->from = '0000-00-00 00:00:00';
         $specific_price->to = '0000-00-00 00:00:00';
         $specific_price->add();
     }
     // Add product to cart
     $update_quantity = $cart->updateQty($product_informations['product_quantity'], $product->id, isset($product_informations['product_attribute_id']) ? $product_informations['product_attribute_id'] : null, isset($combination) ? $combination->id : null, 'up', 0, new Shop($cart->id_shop));
     if ($update_quantity < 0) {
         // If product has attribute, minimal quantity is set with minimal quantity of attribute
         $minimal_quantity = $product_informations['product_attribute_id'] ? Attribute::getAttributeMinimalQty($product_informations['product_attribute_id']) : $product->minimal_quantity;
         die(Tools::jsonEncode(array('error' => sprintf(Tools::displayError('You must add %d minimum quantity', false), $minimal_quantity))));
     } elseif (!$update_quantity) {
         die(Tools::jsonEncode(array('error' => Tools::displayError('You already have the maximum quantity available for this product.', false))));
     }
     // If order is valid, we can create a new invoice or edit an existing invoice
     if ($order->hasInvoice()) {
         $order_invoice = new OrderInvoice($product_informations['invoice']);
         // Create new invoice
         if ($order_invoice->id == 0) {
             // If we create a new invoice, we calculate shipping cost
             $total_method = Cart::BOTH;
             // Create Cart rule in order to make free shipping
             if (isset($invoice_informations['free_shipping']) && $invoice_informations['free_shipping']) {
                 $cart_rule = new CartRule();
                 $cart_rule->id_customer = $order->id_customer;
                 $cart_rule->name = array(Configuration::get('PS_LANG_DEFAULT') => $this->l('[Generated] CartRule for Free Shipping'));
                 $cart_rule->date_from = date('Y-m-d H:i:s', time());
                 $cart_rule->date_to = date('Y-m-d H:i:s', time() + 24 * 3600);
                 $cart_rule->quantity = 1;
                 $cart_rule->quantity_per_user = 1;
                 $cart_rule->minimum_amount_currency = $order->id_currency;
                 $cart_rule->reduction_currency = $order->id_currency;
                 $cart_rule->free_shipping = true;
                 $cart_rule->active = 1;
                 $cart_rule->add();
                 // Add cart rule to cart and in order
                 $cart->addCartRule($cart_rule->id);
                 $values = array('tax_incl' => $cart_rule->getContextualValue(true), 'tax_excl' => $cart_rule->getContextualValue(false));
                 $order->addCartRule($cart_rule->id, $cart_rule->name[Configuration::get('PS_LANG_DEFAULT')], $values);
             }
             $order_invoice->id_order = $order->id;
             if ($order_invoice->number) {
                 Configuration::updateValue('PS_INVOICE_START_NUMBER', false, false, null, $order->id_shop);
             } else {
                 $order_invoice->number = Order::getLastInvoiceNumber() + 1;
             }
             $invoice_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
             $carrier = new Carrier((int) $order->id_carrier);
             $tax_calculator = $carrier->getTaxCalculator($invoice_address);
             $order_invoice->total_paid_tax_excl = Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl = Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt = (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->total_shipping_tax_excl = (double) $cart->getTotalShippingCost(null, false);
             $order_invoice->total_shipping_tax_incl = (double) $cart->getTotalShippingCost();
             $order_invoice->total_wrapping_tax_excl = abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order_invoice->total_wrapping_tax_incl = abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->shipping_tax_computation_method = (int) $tax_calculator->computation_method;
             // Update current order field, only shipping because other field is updated later
             $order->total_shipping += $order_invoice->total_shipping_tax_incl;
             $order->total_shipping_tax_excl += $order_invoice->total_shipping_tax_excl;
             $order->total_shipping_tax_incl += $use_taxes ? $order_invoice->total_shipping_tax_incl : $order_invoice->total_shipping_tax_excl;
             $order->total_wrapping += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_excl += abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_incl += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->add();
             $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl));
             $order_carrier = new OrderCarrier();
             $order_carrier->id_order = (int) $order->id;
             $order_carrier->id_carrier = (int) $order->id_carrier;
             $order_carrier->id_order_invoice = (int) $order_invoice->id;
             $order_carrier->weight = (double) $cart->getTotalWeight();
             $order_carrier->shipping_cost_tax_excl = (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->shipping_cost_tax_incl = $use_taxes ? (double) $order_invoice->total_shipping_tax_incl : (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->add();
         } else {
             $order_invoice->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->update();
         }
     }
     // Create Order detail information
     $order_detail = new OrderDetail();
     $order_detail->createList($order, $cart, $order->getCurrentOrderState(), $cart->getProducts(), isset($order_invoice) ? $order_invoice->id : 0, $use_taxes, (int) Tools::getValue('add_product_warehouse'));
     // update totals amount of order
     $order->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
     $order->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
     $order->total_paid += Tools::ps_round((double) $cart->getOrderTotal(true, $total_method), 2);
     $order->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
     $order->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
     if (isset($order_invoice) && Validate::isLoadedObject($order_invoice)) {
         $order->total_shipping = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_incl = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_excl = $order_invoice->total_shipping_tax_excl;
     }
     // discount
     $order->total_discounts += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_excl += (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_incl += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     // Save changes of order
     $order->update();
     // Update weight SUM
     $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
     if (Validate::isLoadedObject($order_carrier)) {
         $order_carrier->weight = (double) $order->getTotalWeight();
         if ($order_carrier->update()) {
             $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
         }
     }
     // Update Tax lines
     $order_detail->updateTaxAmount($order);
     // Delete specific price if exists
     if (isset($specific_price)) {
         $specific_price->delete();
     }
     $products = $this->getProducts($order);
     // Get the last product
     $product = end($products);
     $resume = OrderSlip::getProductSlipResume((int) $product['id_order_detail']);
     $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
     $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
     $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']);
     $product['return_history'] = OrderReturn::getProductReturnDetail((int) $product['id_order_detail']);
     $product['refund_history'] = OrderSlip::getProductSlipDetail((int) $product['id_order_detail']);
     if ($product['id_warehouse'] != 0) {
         $warehouse = new Warehouse((int) $product['id_warehouse']);
         $product['warehouse_name'] = $warehouse->name;
     } else {
         $product['warehouse_name'] = '--';
     }
     // Get invoices collection
     $invoice_collection = $order->getInvoicesCollection();
     $invoice_array = array();
     foreach ($invoice_collection as $invoice) {
         $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop);
         $invoice_array[] = $invoice;
     }
     // Assign to smarty informations in order to show the new product line
     $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')));
     $this->sendChangedNotification($order);
     die(Tools::jsonEncode(array('result' => true, 'view' => $this->createTemplate('_product_line.tpl')->fetch(), 'can_edit' => $this->tabAccess['add'], 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'discount_form_html' => $this->createTemplate('_discount_form.tpl')->fetch())));
 }
示例#29
0
    public function displayMain()
    {
        global $cookie;
        /*
        when user add or change address,from addressView or joinView
        */
        if (isset($_GET['ajaxStates']) and isset($_GET['id_country'])) {
            $states = Db::getInstance()->getAll('
			SELECT s.id_state, s.name
			FROM ' . DB_PREFIX . 'state s
			LEFT JOIN ' . DB_PREFIX . 'country c ON (s.`id_country` = c.`id_country`)
			WHERE s.id_country = ' . (int) Tools::G('id_country') . ' AND s.active = 1 AND c.`need_state` = 1
			ORDER BY s.`name` ASC');
            if (is_array($states) and !empty($states)) {
                $list = '';
                if (Tools::G('no_empty') != true) {
                    $list = '<option value="0">-----------</option>' . "\n";
                }
                foreach ($states as $state) {
                    $list .= '<option value="' . (int) $state['id_state'] . '"' . (Tools::G('id_state') == $state['id_state'] ? ' selected="selected"' : '') . '>' . $state['name'] . '</option>' . "\n";
                }
            } else {
                $list = 'false';
            }
            die($list);
        }
        //end get states
        /*
        from cartView get total
        */
        if (isset($_GET['getTotal']) and isset($_GET['id_cart']) and isset($_GET['id_carrier'])) {
            $carrier = new Carrier((int) $_GET['id_carrier']);
            $cart = new Cart((int) $_GET['id_cart']);
            $shipping = $carrier->shipping;
            $p_total = $cart->getProductTotal();
            $total = $shipping + $p_total - $cart->discount;
            $arr = array('name' => $carrier->name, 'shipping' => Tools::displayPrice($shipping), 'total' => Tools::displayPrice($total));
            echo json_encode($arr);
            exit;
        }
        //end use gettotal
        /*
        start use promo code,from CartView
        */
        if (isset($_GET['validatedPromocode']) && isset($_GET['code'])) {
            if (!isset($cookie->id_cart)) {
                $arr = array('status' => "NO", 'msg' => "cart is not init!");
                echo json_encode($arr);
                exit;
            }
            $row = Db::getInstance()->getRow('SELECT * FROM ' . _DB_PREFIX_ . 'coupon WHERE code="' . pSQL($_GET['code']) . '" AND active=1');
            if ($row) {
                if ($row['id_user'] == 0 || $row['id_user'] == @$cookie->id_user) {
                    $cart = new Cart($cookie->id_cart);
                    $total = $cart->getProductTotal();
                    $quantity = $cart->getProductQantity();
                    $discount = 0;
                    if ($total > $row['total_over'] || $row['quantity_over'] > 0 && $quantity > $row['quantity_over']) {
                        if ($row['off'] > 0) {
                            $discount = (double) $total * $row['off'] / 100;
                        } else {
                            $discount = (double) $row['amount'];
                        }
                        $cart->discount = $discount;
                        if ($cart->update()) {
                            $arr = array('status' => "YES", 'discount' => "-" . Tools::displayPrice($discount), 'total' => Tools::displayPrice($cart->getOrderTotal()));
                            echo json_encode($arr);
                            exit;
                        }
                    }
                }
            }
            $arr = array('status' => "NO", 'msg' => "the code don't found!");
            echo json_encode($arr);
            exit;
        }
        //end use promo code
        /**
         * 购物车
         */
        if (Tools::G('c') == 'Cart') {
            global $cart;
            switch (Tools::G('m')) {
                case 'removeItem':
                    if ($cart->deleteProduct(Tools::G('id'))) {
                        $cart_info = $cart->getCartInfo();
                        $result = array('status' => 'yes', 'cart_total' => Tools::displayPrice($cart_info['cart_total']), 'cart_quantity' => $cart_info['cart_quantity']);
                        die(json_encode($result));
                    }
                    die(json_encode(array("status" => "no")));
                    break;
                case 'plusItem':
                    if ($row = $cart->plusProduct(Tools::G('id'))) {
                        $cart_info = $cart->getCartInfo();
                        $result = array('status' => 'yes', 'cart_total' => Tools::displayPrice($cart_info['cart_total']), 'cart_quantity' => $cart_info['cart_quantity'], 'item' => array('quantity' => $row['quantity'], 'total' => Tools::displayPrice($row['total'])));
                        die(json_encode($result));
                    }
                    die(json_encode(array("status" => "no")));
                    break;
                case 'minusItem':
                    if ($row = $cart->minusProduct(Tools::G('id'))) {
                        $cart_info = $cart->getCartInfo();
                        $result = array('status' => 'yes', 'cart_total' => Tools::displayPrice($cart_info['cart_total']), 'cart_quantity' => $cart_info['cart_quantity'], 'item' => array('quantity' => $row['quantity'], 'total' => Tools::displayPrice($row['total'])));
                        die(json_encode($result));
                    }
                    die(json_encode(array("status" => "no")));
                    break;
                case 'deleteMultiItem':
                    if ($cart->deleteMultiProduct(explode(',', Tools::G('id')))) {
                        $cart_info = $cart->getCartInfo();
                        $result = array('status' => 'yes', 'cart_total' => Tools::displayPrice($cart_info['cart_total']), 'cart_quantity' => $cart_info['cart_quantity']);
                        die(json_encode($result));
                    }
                    die(json_encode(array("status" => "no")));
                    break;
                default:
                    break;
            }
        }
        /**
         * 商品收藏
         */
        if (Tools::G('c') == 'Wish') {
            if (!isset($cookie->id_user)) {
                die(json_encode(array("status" => "no", "msg" => "d'not login!")));
            }
            $user = new User((int) $cookie->id_user);
            if (!Validate::isLoadedObject($user)) {
                die(json_encode(array("status" => "no", "msg" => "user load fail!")));
            }
            switch (Tools::G('m')) {
                case 'addItem':
                    if ($status = $user->addToWish(Tools::G('id'))) {
                        if ($status === 1) {
                            $result = array("m" => "add", 'status' => 'yes');
                        } else {
                            if ($status === -1) {
                                $result = array("m" => "delete", 'status' => 'yes');
                            }
                        }
                        die(json_encode($result));
                    }
                    die(json_encode(array("status" => "no")));
                    break;
                default:
                    break;
            }
        }
        /*
        start use add wish,from ProductView or CategoryView
        */
        if (isset($_GET['action']) && $_GET['action'] == 'add_wish' && isset($_GET['id_product'])) {
            if ($action = Wish::userAddWishProduct($_GET['id_product'])) {
                $wishs = Wish::getWishSumByUser();
                $count_html = "";
                if ($wishs['count'] > 0) {
                    $count_html = "<i>{$wishs['count']}</i>";
                }
                $arr = array('action' => $action, 'count' => $count_html, 'status' => "YES");
                echo json_encode($arr);
            } else {
                $arr = array('status' => "NO");
                echo json_encode($arr);
            }
            exit;
        }
        //end use add wish
        /**
         * 邮箱是否已被注册
         */
        if (Tools::P('existsEmail')) {
            $valid = true;
            if (User::userExists(Tools::P('existsEmail'))) {
                $valid = false;
            }
            echo json_encode(array('valid' => $valid));
        }
    }
    /**
     * Manage and finalize the order on prestashop side
     * @param xml $xm from RealexRedirectValidationModuleFrontController::postProcess()
     * @param boolean $viarealvault (optional)
     * Case 1 : Redirection to payment confirmation if $viarealvault
     * Case 2 : Display html if !$viarealvault
     */
    public function manageOrder($xm, $viarealvault = true, $failed = false)
    {
        $link = $this->context->link;
        $result = $xm->result;
        $pasref = (string) $xm->pasref;
        $tss = (int) $xm->tss->result;
        $orderid = (string) $xm->orderid;
        $merchantid = (string) $this->merchant_id;
        $message = (string) $xm->message;
        $authcode = (string) $xm->authcode;
        $sha1 = (string) $xm->sha1hash;
        $timestamp = (string) $xm->attributes()->timestamp;
        $account = (string) $xm->account;
        $currency = (string) $xm->currency;
        $amount = (string) $xm->amount;
        $cvn = (string) $xm->cvn;
        $autosettle = (string) $xm->autosettle;
        $rv = (string) $xm->RV;
        $rv_saved_payer_ref = (string) $xm->RVSavedPayerRef;
        $rv_saved_payment_ref = (string) $xm->RVSavedPaymentRef;
        $rv_saved_payment_type = (string) $xm->RVSavedPaymentType;
        $rv_pmt_response = (string) $xm->RVPmtResponse;
        $rv_pmt_digits = (string) $xm->RVPmtDigits;
        $rv_pmt_exp_format = (string) $xm->RVPmtExpFormat;
        $tss = (string) $xm->tss->result;
        $eci = (string) $xm->eci;
        $avs_post_code_response = (string) $xm->avspostcoderesponse;
        $avs_address_response = (string) $xm->avsaddressresponse;
        $dcc = (string) $xm->dcc;
        $dcc_choice = (string) $xm->dcc_choice;
        $dcc_rate = (string) $xm->dcc_rate;
        $dcc_cardholder_currency = (string) $xm->dcc_cardholder_currency;
        $dcc_cardholder_amount = (string) $xm->dcc_cardholder_amount;
        $dcc_merchant_currency = (string) $xm->dcc_merchant_currency;
        $dcc_merchant_amount = (string) $xm->dcc_merchant_amount;
        $rv_pmt_digits = preg_replace("/[0-9]/", 'x', $rv_pmt_digits, 6);
        // ---------------- CREATION PANIER
        $id_cart = explode('-', $orderid);
        $cart = new Cart($id_cart[0]);
        if (!$viarealvault) {
            $total = (double) $amount / 100;
        } else {
            $total = (double) $cart->getOrderTotal(true, Cart::BOTH);
        }
        // ---------------- CREATION CLIENT
        $customer = new Customer((int) $cart->id_customer);
        // ---------------- CREATION MSG BACKEND
        if ($failed) {
            $retour_msg = 'Status: ' . $this->getMsg('fail_liability') . " \r\n";
        } else {
            $retour_msg = 'Status: ' . $this->getMsg($result) . " \r\n";
        }
        $retour_msg .= $message . " \r\n";
        if ($viarealvault) {
            $retour_msg .= "Via RealVault \r\n";
        }
        if (isset($pasref) && $pasref) {
            $retour_msg .= 'Transaction reference: ' . $pasref . "\r\n";
        }
        if (isset($tss) && !empty($tss)) {
            $retour_msg .= 'TSS: ' . $tss . "\r\n";
        }
        if (isset($eci) && !empty($eci)) {
            $retour_msg .= 'ECI: ' . $eci . "\r\n";
        }
        // ---------------- DCC Choice
        if (isset($dcc) && !empty($dcc) && isset($dcc_rate) && !empty($dcc_rate) && isset($dcc_choice) && !empty($dcc_choice)) {
            $retour_msg .= 'DCC type: ' . $dcc . "\r\n";
            $retour_msg .= 'DCC choice: ' . $dcc_choice . "\r\n";
            $retour_msg .= 'DCC rate: ' . $dcc_rate . "\r\n";
            $retour_msg .= 'Card holder amount: ' . (double) ($dcc_cardholder_amount / 100) . ' ' . $dcc_cardholder_currency . "\r\n";
            $retour_msg .= 'Merchant amount: ' . (double) ($dcc_merchant_amount / 100) . ' ' . $dcc_merchant_currency . "\r\n";
        }
        // ---------------- AVS RETURN
        if (!empty($avs_post_code_response) && !empty($avs_address_response)) {
            $retour_msg .= 'AVS PostCode Response: ' . $this->getAVSresponse($avs_post_code_response) . "\r\n";
            $retour_msg .= 'AVS Address Response: ' . $this->getAVSresponse($avs_address_response) . "\r\n";
        }
        // ---------------- CONTROLES
        if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->active) {
            die($this->l('This payment method is not available.', 'validation'));
        }
        if (!Validate::isLoadedObject($customer)) {
            die($this->l('An error occured.', 'validation'));
        }
        // ---------------- PAYMENT OK
        if ($result == '00' && !$failed) {
            // ---------------- CONTROLE SHA1
            $tmp = $timestamp . '.' . $merchantid . '.' . $orderid . '.' . $result . '.' . $message . '.' . $pasref . '.' . $authcode;
            $sha1hash = sha1($tmp);
            $tmp = $sha1hash . '.' . $this->shared_secret;
            $sha1hash = sha1($tmp);
            //Check to see if hashes match or not
            if ($sha1hash != $sha1) {
                die($this->l("hashes don't match - response not authenticated!", 'validation'));
            }
            // ----- REAL VAULT ACTIVE
            if ($this->realvault && !$viarealvault) {
                if ($rv && $rv_pmt_response == '00') {
                    $date = new DateTime();
                    $sql = 'SELECT `refuser_realex`,`id_realex_payerref` FROM `' . _DB_PREFIX_ . 'realex_payerref` WHERE `id_user_realex` = ' . $cart->id_customer;
                    $payer_ref = Db::getInstance()->getRow($sql);
                    if (empty($payer_ref)) {
                        Db::getInstance()->insert('realex_payerref', array('id_user_realex' => (int) $cart->id_customer, 'refuser_realex' => (int) $rv_saved_payer_ref, 'date_add' => $date->format('Y-m-d h:i:s')));
                        $id_realex_payerref = Db::getInstance()->Insert_ID();
                    } else {
                        $id_realex_payerref = $payer_ref['id_realex_payerref'];
                    }
                    Db::getInstance()->insert('realex_paymentref', array('id_realex_payerref' => (int) $id_realex_payerref, 'refpayment_realex' => (int) $rv_saved_payment_ref, 'paymentname_realex' => pSQL($rv_pmt_digits . ' - ' . $rv_pmt_exp_format), 'type_card_realex' => pSQL($rv_saved_payment_type), 'date_add' => $date->format('Y-m-d h:i:s')));
                    $retour_msg .= "RealVault: Succesfull \r\n";
                } elseif ($rv) {
                    $retour_msg .= "RealVault: Problem \r\n";
                } else {
                    $retour_msg .= "RealVault: No \r\n";
                }
            }
            Configuration::updateValue('REALEXREDIRECT_CONFIGURATION_OK', true);
            $this->validateOrder($cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $this->displayName, $retour_msg, null, (int) $cart->id_currency, false, $customer->secure_key);
        } elseif ($result != '00' || $failed) {
            $this->validateOrder($cart->id, Configuration::get('PS_OS_ERROR'), $total, $this->displayName, $retour_msg, null, (int) $cart->id_currency, false, $customer->secure_key);
        }
        if ($viarealvault) {
            Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cart->id . '&id_module=' . $this->id . '&id_order=' . $this->currentOrder . '&key=' . $customer->secure_key);
        } else {
            // ---------------- BACK TO THE SHOP
            $shop_domain = Tools::getShopDomainSsl(true, true);
            $msg = str_replace('?', '&rsquo;', utf8_decode($this->getMsg($result)));
            $controller_link = $link->getPageLink('order-confirmation', true, null, 'id_cart=' . $cart->id . '&id_module=' . $this->id . '&id_order=' . $this->currentOrder . '&key=' . $customer->secure_key);
            echo '
			<html xmlns="http://www.w3.org/1999/xhtml">
				<head>
					<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
				   <title>' . $this->l('Realex Confirmation Payment') . '</title>
				</head>
				<body>
					<center>
						<table border="0" width="100%" style="margin:auto; border: 1px solid #FFA51F" cellpadding="10" cellspacing="10">
							<tr style="border: 1px solid #FFA51F">
								<td align="center">
									<strong>' . $msg . '</strong>
								</td>
							</tr>
							<tr>
                        ';
            if ($result != '00' || $failed) {
                echo '<td align="center">
									' . $this->l('Please click') . ' <a href="' . $controller_link . '">' . $this->l('here') . '</a> ' . htmlentities($this->l('to return to the checkout and try again.')) . '
								</td>';
            } else {
                echo '<td align="center">
									' . $this->l('Please click') . ' <a href="' . $controller_link . '">' . $this->l('here') . '</a> ' . htmlentities($this->l('to complete your order.')) . '
								</td>';
            }
            echo '					
                            </tr>
                            </table>
                            </center>
                            </body>
                            </html>';
            exit;
        }
    }