public function getOrders($customerToken, $customerLanguage, $limit, $offset, $orderDateFrom, $sortOrder)
 {
     $shopgateCustomerModel = new ShopgateCustomerPrestashop();
     $this->_currentCustomer = $shopgateCustomerModel->getCustomerByToken($customerToken);
     if (!$this->_currentCustomer->validateFields(false)) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_CUSTOMER_TOKEN_INVALID);
     }
     $orders = $this->getCustomerOrders($this->_currentCustomer->id, $limit, $offset, $orderDateFrom, $sortOrder);
     foreach ($orders as $orderItem) {
         /** @var OrderCore $orderCore */
         $orderCore = new Order($orderItem['id_order']);
         $order = new ShopgateExternalOrder();
         $order->setOrderNumber($orderCore->id);
         $order->setExternalOrderNumber($orderCore->reference);
         $order->setExternalOrderId($orderCore->id);
         /** @var OrderStateCore $orderStatus */
         $orderStatus = new OrderState($orderCore->getCurrentState());
         $order->setStatusName($orderStatus->name[$this->getPlugin()->getLanguageId()]);
         $order->setStatusColor($orderStatus->color);
         $order->setCreatedTime($orderCore->date_add);
         $order->setMail($this->_currentCustomer->email);
         $order->setDeliveryAddress($this->_getAddress($orderCore->id_address_delivery, ShopgateCustomerPrestashop::DEFAULT_CUSTOMER_ADDRESS_IDENTIFIER_DELIVERY));
         $order->setInvoiceAddress($this->_getAddress($orderCore->id_address_invoice, ShopgateCustomerPrestashop::DEFAULT_CUSTOMER_ADDRESS_IDENTIFIER_DELIVERY));
         $order->setItems($this->_getOrderItems($orderCore));
         $order->setExternalCoupons($this->_getCartRules($orderCore));
         /** @var CurrencyCore $currency */
         $currency = Currency::getCurrency($orderCore->id_currency);
         $order->setCurrency($currency['iso_code']);
         $order->setAmountComplete(isset($orderCore->total_paid_tax_incl) ? $orderCore->total_paid_tax_incl : $orderCore->total_paid);
         $order->setIsPaid($orderCore->hasBeenPaid());
         $order->setPaymentMethod($orderCore->payment);
         $order->setIsShippingCompleted($orderCore->hasBeenShipped());
         $order->setShippingCompletedTime($orderCore->hasBeenShipped() ? $orderCore->delivery_date : null);
         $order->setDeliveryNotes($this->_getDeliveryNotes($orderCore));
         $order->setExtraCosts($this->_getExtraCost($orderCore));
         $order->setOrderTaxes($this->_getOrderTaxes());
         $this->_result[] = $order;
     }
     return $this->_result;
 }
 public function hookPaymentReturn($params)
 {
     global $smarty, $cookie;
     require_once "vendor/PagSeguroLibrary/PagSeguroLibrary.php";
     $transaction_code = Tools::getValue('transaction_id');
     $id_order = Tools::getValue("id_order");
     if ($transaction_code) {
         Db::getInstance()->Execute("INSERT INTO `" . _DB_PREFIX_ . "pagseguro_order` VALUES (NULL, {$id_order}, '{$transaction_code}');");
     }
     $objOrder = new Order($id_order);
     //$transaction_code = Db::getInstance()->getValue("SELECT id_transaction FROM " . _DB_PREFIX_ . "pagseguro_order WHERE id_order = {$id_order} ");
     try {
         $credentials = new PagSeguroAccountCredentials(Configuration::get("PAGSEGURO_BUSINESS"), Configuration::get("PAGSEGURO_TOKEN"));
         $transaction = PagSeguroTransactionSearchService::searchByCode($credentials, $transaction_code);
         $statusValue = $transaction->getStatus()->getValue();
         $order_state = Configuration::get("PAGSEGURO_STATUS_{$statusValue}");
         $orderState = new OrderState($order_state);
         $status = $orderState->name[$cookie->id_lang];
         if ($objOrder->getCurrentState() !== intval($order_state)) {
             $customer = new Customer(intval($params['objOrder']->id_customer));
             $mailVars = array('{email}' => Configuration::get('PS_SHOP_EMAIL'), '{firstname}' => stripslashes($customer->firstname), '{lastname}' => stripslashes($customer->lastname), '{terceiro}' => stripslashes($this->displayName), '{id_order}' => stripslashes($id_order), '{status}' => stripslashes($status));
             $objOrderHistory = new OrderHistory();
             $objOrderHistory->id_order = intval($id_order);
             $objOrderHistory->changeIdOrderState($order_state, $id_order);
             $objOrderHistory->addWithemail(true, $mailVars);
         }
     } catch (PagSeguroServiceException $e) {
         return false;
         die($e->getMessage());
     }
     $cart = new Cart($params['objOrder']->id_cart);
     $smarty->assign(array("id_order" => $id_order, "total" => $params['total_to_pay'], "codigo_pagseguro" => $transaction->getCode(), "status" => $status));
     return $this->display(__FILE__, 'payment_return.tpl');
 }
Exemple #3
0
 Context::getContext()->currency = new Currency((int) $cart->id_currency);
 PayplugLock::check($cart->id);
 $order = new Order();
 $order_id = $order->getOrderByCartId($cart->id);
 /**
  * If existing order
  */
 if ($order_id) {
     /**
      * If status paid
      */
     if ($status == Payplug::PAYMENT_STATUS_PAID) {
         $order = new Order($order_id);
         /** Get the right order status following module configuration (Sandbox or not) */
         $order_state = Payplug::getOsConfiguration('waiting');
         $current_state = $order->getCurrentState();
         if ($current_state == $order_state) {
             $order_history = new OrderHistory();
             /**
              * Change order state to payment paid by payplug
              */
             $order_history->id_order = $order_id;
             /** Get the right order status following module configuration (Sandbox or not) */
             $new_order_state = Payplug::getOsConfiguration('paid');
             $order_history->changeIdOrderState((int) $new_order_state, $order_id);
             $order_history->save();
             if (version_compare(_PS_VERSION_, '1.5', '>') && version_compare(_PS_VERSION_, '1.5.2', '<')) {
                 $order->current_state = $order_history->id_order_state;
                 $order->update();
             }
         }
        Context::getContext()->link = new Link();
    }
    Context::getContext()->language = new Language($cart->id_lang);
    Context::getContext()->currency = new Currency($cart->id_currency);
}
$sofortbanking = new Sofortbanking();
/* If valid hash, set order state as accepted */
if (is_object($cart) && Tools::getValue('hash') == sha1(implode('|', $request))) {
    $order_state = Configuration::get('SOFORTBANKING_OS_ACCEPTED');
}
$customer = new Customer($cart->id_customer);
/* Validate this card in store if needed */
if ($order_state == Configuration::get('SOFORTBANKING_OS_ACCEPTED') && Configuration::get('SOFORTBANKING_OS_ACCEPTED_IGNORE') != 'Y' || $order_state == Configuration::get('SOFORTBANKING_OS_ERROR') && Configuration::get('SOFORTBANKING_OS_ERROR_IGNORE') != 'Y') {
    if (!Order::getOrderByCartId($cart->id)) {
        $sofortbanking->validateOrder($cart->id, $order_state, (double) number_format($cart->getOrderTotal(true, 3), 2, '.', ''), $sofortbanking->displayName, $sofortbanking->l('Directebanking transaction id: ') . Tools::getValue('transaction'), null, null, false, $customer->secure_key, null);
    } else {
        $order = new Order(Order::getOrderByCartId($cart->id));
        if ($order->getCurrentState() != $order_state) {
            $history = new OrderHistory();
            $history->id_order = $order->id;
            $history->changeIdOrderState($order_state, $order->id);
            $history->addWithemail(true);
            /* Add private order message for seller */
            $message = new Message();
            $message->message = $sofortbanking->l('Change order state by SOFORT notification for transaction id: ') . Tools::getValue('transaction');
            $message->private = 1;
            $message->id_order = $order->id;
            $message->add();
        }
    }
}
function updateHistory($order_id = null, $newOrderStatusId = null)
{
    echo '-fnUH';
    checkStatus116();
    $updateorders = true;
    // Verifications to skip the update History is there is a need for it.
    // Case 1 : Paiement partielle
    // Status 117 and 118 creates a double entry. Only one entry is needed ( in case of 117 only )
    $order = new Order((int) $order_id);
    if ($_POST['status'] == '118') {
        // If current state is already partially captured
        if ($order->getCurrentState() == Configuration::get('HIPAY_PARTIALLY_CAPTURED')) {
            // And if the amount capture is still being partially captured
            if ($_POST['captured_amount'] < $_POST['authorized_amount']) {
                $updateorders = false;
            }
        }
    }
    if ($updateorders) {
        // Update orders
        $sql_update = "UPDATE `" . _DB_PREFIX_ . "orders`\r\n        SET `current_state` = '" . (int) $newOrderStatusId . "'\r\n        WHERE `id_order`='" . (int) $order_id . "'";
        Db::getInstance()->execute($sql_update);
        // Insert into order_history
        $sql_insert = "INSERT INTO `" . _DB_PREFIX_ . "order_history` (`id_employee`, `id_order`, `id_order_state`, `date_add`)\r\n        VALUES ('0', '" . (int) $order_id . "', '" . (int) $newOrderStatusId . "', now());";
        Db::getInstance()->execute($sql_insert);
    }
    // Update to minimize risk of simultaneous calls for status 116 and 117
    if ($_POST['status'] == '116') {
        // If order exists for cart
        $cart = new Cart((int) $_POST['order']->id);
        if ($cart->orderExists()) {
            $context = Context::getContext();
            // Retrieve Order ID
            $order_id = retrieveOrderId($cart->id);
            $order = new Order((int) $order_id);
            // If current state is paiement accepted or capture partielle
            // then skip the process
            if ((bool) $order->getHistory($context->language->id, _PS_OS_PAYMENT_)) {
                // Update orders
                $sql_update = "UPDATE `" . _DB_PREFIX_ . "orders`\r\n                    SET `current_state` = '" . _PS_OS_PAYMENT_ . "'\r\n                    WHERE `id_order`='" . (int) $order_id . "'";
                Db::getInstance()->execute($sql_update);
                // Insert into order_history
                $sql_insert = "INSERT INTO `" . _DB_PREFIX_ . "order_history` (`id_employee`, `id_order`, `id_order_state`, `date_add`)\r\n                    VALUES ('0', '" . (int) $order_id . "', '" . _PS_OS_PAYMENT_ . "', now());";
                Db::getInstance()->execute($sql_insert);
            }
            if ((bool) $order->getHistory($context->language->id, Configuration::get('HIPAY_PARTIALLY_CAPTURED'))) {
                // Update orders
                $sql_update = "UPDATE `" . _DB_PREFIX_ . "orders`\r\n                    SET `current_state` = '" . Configuration::get('HIPAY_PARTIALLY_CAPTURED') . "'\r\n                    WHERE `id_order`='" . (int) $order_id . "'";
                Db::getInstance()->execute($sql_update);
                // Insert into order_history
                $sql_insert = "INSERT INTO `" . _DB_PREFIX_ . "order_history` (`id_employee`, `id_order`, `id_order_state`, `date_add`)\r\n                    VALUES ('0', '" . (int) $order_id . "', '" . Configuration::get('HIPAY_PARTIALLY_CAPTURED') . "', now());";
                Db::getInstance()->execute($sql_insert);
            }
            HipayLogger::addLog($hipay->l('Callback process', 'hipay'), HipayLogger::ERROR, 'updateHistory status 116 order already exists - cid : ' . (int) $_POST['order']->id);
            die;
        }
    }
    return true;
}
 /**
  * @param array $hook
  * @return string
  */
 public function hookdisplayAdminOrder($hook)
 {
     $order = new Order(Tools::getValue('id_order'));
     $securionPayPayment = null;
     foreach ($order->getOrderPaymentCollection() as $payment) {
         if ($payment->payment_method == 'Card payment' && $order->module == 'securionpay' && $order->getCurrentState() != 7) {
             $securionPayPayment = $payment;
             break;
         }
     }
     if (!$securionPayPayment) {
         return '';
     }
     $this->context->smarty->assign(array('button_href' => 'index.php?controller=AdminSecurionPay' . '&id_order=' . Tools::getValue('id_order') . '&token=' . Tools::getAdminTokenLite('AdminSecurionPay'), 'version' => (double) _PS_VERSION_));
     return $this->display(__FILE__, 'displayAdminOrder.tpl');
 }
 /**
  * @brief The merchant can cancel the order or refund the customer
  */
 public function hookadminOrder($params)
 {
     if (!$this->active) {
         return false;
     }
     $order = new Order($params['id_order']);
     $cart = new Cart($order->id_cart);
     $tokenTransaction = new TokenTransaction($cart->id);
     $token = $tokenTransaction->getToken();
     if ($token == null) {
         return false;
     }
     if ($order->getCurrentState() == Configuration::get('PS_OS_CANCELED') && $tokenTransaction->getStatus() != 'CANCEL') {
         $call = new Call();
         try {
             $result = $call->voidTransaction($token);
         } catch (Exception $e) {
             $this->context->smarty->assign('error', Tools::safeOutput($e->getMessage()));
         }
         if (isset($result->VoidResult->ApprovalStatus) && strrpos($result->VoidResult->ApprovalStatus, 'APPROVED') !== false) {
             $tokenTransaction->setStatus('CANCEL');
             $this->context->smarty->assign('message', $this->l('Action succeded.'));
         } else {
             $this->context->smarty->assign('error', isset($result->VoidResult->ApprovalStatus) ? Tools::safeOutput($result->VoidResult->ApprovalStatus) : $this->l('ERROR, please contact MerchantWare for Support assistance.'));
         }
     }
     if ($order->getCurrentState() == Configuration::get('PS_OS_REFUND') && $tokenTransaction->getStatus() != 'REFUND') {
         $call = new Call();
         try {
             $result = $call->refundTransaction($token, $order->total_paid_real);
         } catch (Exception $e) {
             $this->context->smarty->assign('error', Tools::safeOutput($e->getMessage()));
         }
         if (isset($result->RefundResult->ApprovalStatus) && strrpos($result->RefundResult->ApprovalStatus, 'APPROVED') !== false) {
             $tokenTransaction->setStatus('REFUND');
             $this->context->smarty->assign('message', $this->l('Action succeded.'));
         } else {
             $this->context->smarty->assign('error', isset($result->RefundResult->ApprovalStatus) ? Tools::safeOutput($result->RefundResult->ApprovalStatus) : $this->l('ERROR, please contact Merchant Warehouse for Support assistance.'));
         }
     }
     return $this->display(__FILE__, 'tpl/adminOrder.tpl');
 }
Exemple #8
0
 public function validation()
 {
     # LOG
     $message = '######################################' . "\r\n";
     $message .= '# Date Début Validation - ' . date("d/m/Y H:i:s") . "\r\n";
     $message .= '#### Module actif - ' . ($this->active ? 'TRUE' : 'FALSE') . "\r\n";
     $message .= '#### Variable POST :' . "\r\n";
     $message .= print_r($_POST, true);
     $message .= "\r\n";
     # ---
     $this->HipayLog($message);
     if (!$this->active) {
         return;
     }
     if (!array_key_exists('xml', $_POST)) {
         return;
     }
     if (_PS_MAGIC_QUOTES_GPC_) {
         $_POST['xml'] = stripslashes($_POST['xml']);
     }
     require_once dirname(__FILE__) . '/mapi/mapi_package.php';
     # LOG
     $this->HipayLog('#### Début HIPAY_MAPI_COMM_XML::analyzeNotificationXML' . "\r\n");
     # ---
     if (HIPAY_MAPI_COMM_XML::analyzeNotificationXML($_POST['xml'], $operation, $status, $date, $time, $transid, $amount, $currency, $id_cart, $data) === false) {
         file_put_contents('logs' . Configuration::get('HIPAY_UNIQID') . '.txt', '[' . date('Y-m-d H:i:s') . '] Analysis error: ' . htmlentities($_POST['xml']) . "\n", FILE_APPEND);
         return false;
     }
     # LOG
     $message = '#### Fin HIPAY_MAPI_COMM_XML::analyzeNotificationXML' . "\r\n";
     $message .= '#### Version Prestashop : ' . _PS_VERSION_;
     # ---
     $this->HipayLog($message);
     if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
         # LOG
         $this->HipayLog('#### ID Panier : ' . (int) $id_cart . "\r\n");
         # ---
         Context::getContext()->cart = new Cart((int) $id_cart);
     }
     $cart = new Cart((int) $id_cart);
     # LOG
     $message = '#### TOKEN : ' . Tools::getValue('token') . "\r\n";
     $message .= '#### SECURE KEY : ' . $cart->secure_key . "\r\n";
     $message .= '#### HIPAY SALT : ' . Configuration::get('HIPAY_SALT') . "\r\n";
     $message .= '#### CLE ENCRYPTE : ' . Tools::encrypt($cart->id . $cart->secure_key . Configuration::get('HIPAY_SALT')) . "\r\n";
     # ---
     $this->HipayLog($message);
     if (Tools::encrypt($cart->id . $cart->secure_key . Configuration::get('HIPAY_SALT')) != Tools::getValue('token')) {
         # LOG
         $this->HipayLog('#### TOKEN = CLE : NOK' . "\r\n");
         # ---
         file_put_contents('logs' . Configuration::get('HIPAY_UNIQID') . '.txt', '[' . date('Y-m-d H:i:s') . '] Token error: ' . htmlentities($_POST['xml']) . "\n", FILE_APPEND);
     } else {
         # LOG
         $message = '#### Opération : ' . trim($operation) . "\r\n";
         $message .= '#### Status : ' . trim(strtolower($status)) . "\r\n";
         # ---
         $this->HipayLog($message);
         if (trim($operation) == 'authorization' && trim(strtolower($status)) == 'waiting') {
             // Authorization WAITING
             $orderMessage = $operation . ": " . $status . "\ndate: " . $date . " " . $time . "\ntransaction: " . $transid . "\namount: " . (double) $amount . " " . $currency . "\nid_cart: " . (int) $id_cart;
             //$this->_createAuthorizationOrderState();
             $this->validateOrder((int) $id_cart, Configuration::get('HIPAY_WAITINGPAYMENT_OS'), (double) $amount, $this->displayName, $orderMessage, array(), NULL, false, $cart->secure_key);
             # LOG
             $this->HipayLog('######## AW - création Commande / status : ' . (int) Configuration::get('HIPAY_WAITINGPAYMENT_OS') . "\r\n");
             # ---
         } else {
             if (trim($operation) == 'authorization' && trim(strtolower($status)) == 'ok') {
                 // vérification si commande existante
                 $id_order = Order::getOrderByCartId((int) $id_cart);
                 # LOG
                 $this->HipayLog('######## AOK - ID Commande : ' . ($id_order ? $id_order : 'Pas de commande') . "\r\n");
                 # ---
                 if ($id_order !== false) {
                     // change statut si commande en attente de paiement
                     $order = new Order((int) $id_order);
                     if ((int) $order->getCurrentState() == (int) Configuration::get('HIPAY_WAITINGPAYMENT_OS')) {
                         // on affecte à la commande au statut paiement autorisé par HiPay
                         $statut_id = Configuration::get('HIPAY_AUTHORIZATION_OS');
                         $order_history = new OrderHistory();
                         $order_history->id_order = $id_order;
                         $order_history->changeIdOrderState($statut_id, $id_order);
                         $order_history->addWithemail();
                         # LOG
                         $this->HipayLog('######## AOK - Historique Commande / Change status : ' . (int) Configuration::get('HIPAY_AUTHORIZATION_OS') . "\r\n");
                         # ---
                     }
                 } else {
                     // on revérifie si la commande n'existe pas au cas où la capture soit arrivée avant
                     // sinon on ne fait rien
                     $id_order = Order::getOrderByCartId((int) $id_cart);
                     if ($id_order === false) {
                         // Authorization OK
                         $orderMessage = $operation . ": " . $status . "\ndate: " . $date . " " . $time . "\ntransaction: " . $transid . "\namount: " . (double) $amount . " " . $currency . "\nid_cart: " . (int) $id_cart;
                         //$this->_createAuthorizationOrderState();
                         $this->validateOrder((int) $id_cart, Configuration::get('HIPAY_AUTHORIZATION_OS'), (double) $amount, $this->displayName, $orderMessage, array(), NULL, false, $cart->secure_key);
                         # LOG
                         $this->HipayLog('######## AOK - création Commande / status : ' . (int) Configuration::get('HIPAY_AUTHORIZATION_OS') . "\r\n");
                         # ---
                     }
                 }
             } else {
                 if (trim($operation) == 'capture' && trim(strtolower($status)) == 'ok') {
                     // Capture OK
                     $orderMessage = $operation . ": " . $status . "\ndate: " . $date . " " . $time . "\ntransaction: " . $transid . "\namount: " . (double) $amount . " " . $currency . "\nid_cart: " . (int) $id_cart;
                     $id_order = Order::getOrderByCartId((int) $id_cart);
                     # LOG
                     $this->HipayLog('######## C*K - ID Commande : ' . ($id_order ? $id_order : 'Pas de commande') . "\r\n");
                     # ---
                     if ($id_order !== false) {
                         # LOG
                         $this->HipayLog('######## C*K - id_order existant' . "\r\n");
                         # ---
                         $order = new Order((int) $id_order);
                         # LOG
                         $this->HipayLog('######## C*K - objet order loadé' . "\r\n");
                         # ---
                         // si la commande est au statut Autorisation ok ou en attente de paiement
                         // on change le statut en paiement accepté
                         if ((int) $order->getCurrentState() == (int) Configuration::get('HIPAY_AUTHORIZATION_OS') || (int) $order->getCurrentState() == (int) Configuration::get('HIPAY_WAITINGPAYMENT_OS')) {
                             $statut_id = Configuration::get('PS_OS_PAYMENT');
                             $order_history = new OrderHistory();
                             $order_history->id_order = $id_order;
                             $order_history->changeIdOrderState($statut_id, $id_order);
                             $order_history->addWithemail();
                             # LOG
                             $this->HipayLog('######## C*K - Historique Commande / Change status : ' . (int) Configuration::get('PS_OS_PAYMENT') . "\r\n");
                             # ---
                         }
                     } else {
                         $this->validateOrder((int) $id_cart, Configuration::get('PS_OS_PAYMENT'), (double) $amount, $this->displayName, $orderMessage, array(), NULL, false, $cart->secure_key);
                         # LOG
                         $this->HipayLog('######## C*K - création Commande / status : ' . (int) Configuration::get('PS_OS_PAYMENT') . "\r\n");
                         # ---
                     }
                     // Commande que prestashop lance mais n'a aucune incidence dans le module...
                     // Ajouté en commentaire
                     // Configuration::updateValue('HIPAY_CONFIGURATION_OK', true);
                 } else {
                     if (trim($operation) == 'capture' && trim(strtolower($status)) == 'nok') {
                         // Capture NOK
                         $id_order = Order::getOrderByCartId((int) $id_cart);
                         # LOG
                         $this->HipayLog('######## CNOK - ID Commande : ' . ($id_order ? $id_order : 'Pas de commande') . "\r\n");
                         # ---
                         if ($id_order !== false) {
                             $order = new Order((int) $id_order);
                             if ((int) $order->getCurrentState() == (int) Configuration::get('HIPAY_AUTHORIZATION_OS')) {
                                 $statut_id = Configuration::get('PS_OS_ERROR');
                                 $order_history = new OrderHistory();
                                 $order_history->id_order = $id_order;
                                 $order_history->changeIdOrderState($statut_id, $id_order);
                                 $order_history->addWithemail();
                                 # LOG
                                 $this->HipayLog('######## CNOK - Historique Commande / Change status : ' . (int) Configuration::get('PS_OS_ERROR') . "\r\n");
                                 # ---
                             }
                         }
                     } elseif (trim($operation) == 'refund' and trim(strtolower($status)) == 'ok') {
                         /* Paiement remboursé sur Hipay */
                         if (!($id_order = Order::getOrderByCartId((int) $id_cart))) {
                             die(Tools::displayError());
                         }
                         $order = new Order((int) $id_order);
                         if (!$order->valid or $order->getCurrentState() === Configuration::get('PS_OS_REFUND')) {
                             die(Tools::displayError());
                         }
                         $statut_id = Configuration::get('PS_OS_REFUND');
                         $order_history = new OrderHistory();
                         $order_history->id_order = $id_order;
                         $order_history->changeIdOrderState($statut_id, $id_order);
                         $order_history->addWithemail();
                         # LOG
                         ${$this}->HipayLog('######## ROK - Historique Commande / Change status : ' . (int) Configuration::get('PS_OS_REFUND') . "\r\n");
                         # ---
                     }
                 }
             }
         }
     }
     #
     # Patch LOG Pour les erreurs 500
     #
     $message = '# Date Fin Validation - ' . date("d/m/Y H:i:s") . "\r\n";
     $message .= '######################################' . "\r\n";
     $this->HipayLog($message);
     # ---------------------------------------------------------
     return true;
 }
 public function hookadminOrder($params)
 {
     if (!$this->active) {
         return false;
     }
     $order = new Order($params['id_order']);
     if ($order->module != $this->name) {
         return false;
     }
     $cart = new Cart((int) $order->id_cart);
     $interpay_order = Db::getInstance()->getRow('SELECT * FROM `' . _DB_PREFIX_ . 'gointerpay_order_id` WHERE `id_cart` = ' . (int) $order->id_cart);
     include_once _PS_MODULE_DIR_ . 'gointerpay/Rest.php';
     $rest = new Rest(Configuration::get('GOINTERPAY_STORE'), Configuration::get('GOINTERPAY_SECRET'));
     $result = $rest->orderDetail(Tools::safeOutput($interpay_order['orderId']));
     if ($order->getCurrentState() == Configuration::get('PS_OS_CANCELED') && $interpay_order['status'] != 'Cancel') {
         $result = $rest->updateOrderStatus($interpay_order['orderId'], 'VENDOR_CANCELLATION_REQUEST');
         Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'gointerpay_order_id` SET `status` = \'Cancel\' WHERE `id_cart` = ' . (int) $order->id_cart);
         $interpay_order['status'] = 'Cancel';
         $this->context->smarty->assign('interpay_validate', $this->l('Request sent to IGlobal to cancel the order'));
     } else {
         if ($order->getCurrentState() == Configuration::get('PS_OS_PAYMENT') && $interpay_order['status'] != 'Accepted') {
             $result = $rest->updateOrderStatus($interpay_order['orderId'], 'VENDOR_PREPARING_ORDER');
             Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'gointerpay_order_id` SET `status` = \'Accepted\' WHERE `id_cart` = ' . (int) $order->id_cart);
             $interpay_order['status'] = 'Accepted';
             $this->context->smarty->assign('interpay_validate', $this->l('Order accepted in Gointerpay'));
         } else {
             if ($order->getCurrentState() == Configuration::get('PS_OS_SHIPPING') && $interpay_order['status'] != 'Shipped') {
                 $result = $rest->updateOrderStatus($interpay_order['orderId'], '400', true);
                 Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'gointerpay_order_id` SET `status` = \'Shipped\' WHERE `id_cart` = ' . (int) $order->id_cart);
                 $interpay_order['status'] = 'Shipped';
                 $this->context->smarty->assign('interpay_validate', $this->l('Order updated in Gointerpay'));
             }
         }
     }
     $message = array();
     if ($interpay_order['status'] == 'Pending') {
         $message[] = $this->l('You can accept this order by updating the status to "Payment accepted" or cancel it by updating the status to "Canceled".');
         $interpay_status[] = (int) Configuration::get('PS_OS_PAYMENT');
         $interpay_status[] = (int) Configuration::get('PS_OS_CANCELED');
     } elseif ($interpay_order['status'] == 'Accepted') {
         $message[] = $this->l('Once this order has been shipped, please update the order status to "Shipped".');
         $message[] = $this->l('You can also cancel the order by updating the status to "Canceled".');
         $interpay_status[] = (int) Configuration::get('PS_OS_SHIPPING');
         $interpay_status[] = (int) Configuration::get('PS_OS_CANCELED');
     } elseif ($interpay_order['status'] == 'Cancel') {
         $message[] = $this->l('This order has been marked as cancelled.');
     } elseif ($interpay_order['status'] == 'Shipped') {
         $message[] = $this->l('This order has been marked as shipped.');
     }
     $interpay_status[] = Configuration::get('PS_OS_REFUND');
     $this->context->smarty->assign(array('interpay_message' => $message, 'interpay_order' => $interpay_order, 'interpay_link' => $rest->getOrderStatusLink(Tools::safeOutput($interpay_order['orderId'])), 'interpay_status' => Tools::jsonEncode(array('available' => $interpay_status))));
     return $this->display(__FILE__, 'tpl/order.tpl');
 }
         // payment KO
         $module->logger->logInfo("Payment failed for cart #{$cartId}.");
         if (Configuration::get('PAYZEN_FAILURE_MANAGEMENT') == Payzen::ON_FAILURE_SAVE || $module->isOney($payzenResponse)) {
             // save on failure option is selected or oney payment
             $newState = $payzenResponse->isCancelledPayment() ? Configuration::get('PS_OS_CANCELED') : Configuration::get('PS_OS_ERROR');
             $msg = $module->isOney($payzenResponse) ? 'FacilyPay Oney payment' : 'Save on failure option is selected';
             $module->logger->logInfo("{$msg} : save failed order for cart #{$cartId}. New order status is {$newState}.");
             $order = $module->saveOrder($cart, $newState, $payzenResponse);
         }
         die($payzenResponse->getOutputForGateway('payment_ko'));
     }
 } else {
     // order already registered
     $module->logger->logInfo("Order already registered for cart #{$cartId}.");
     $order = new Order((int) $orderId);
     $oldState = $order->getCurrentState();
     switch ($oldState) {
         case Configuration::get('PS_OS_ERROR'):
         case Configuration::get('PS_OS_CANCELED'):
             $module->logger->logInfo("Save on failure option is selected or FacilyPay Oney payment. Order for cart #{$cartId} is in a failed status.");
             if ($payzenResponse->isAcceptedPayment()) {
                 // order saved with failed status while payment is successful
                 $module->logger->logWarning("Payment success received from platform while order is in a failed status for cart #{$cartId}.");
                 $msg = 'payment_ko_on_order_ok';
             } else {
                 // just display a failure confirmation message
                 $module->logger->logInfo("Payment failure confirmed for cart #{$cartId}.");
                 $msg = 'payment_ko_already_done';
             }
             die($payzenResponse->getOutputForGateway($msg));
             break;
Exemple #11
0
}
if ($id_order = Order::getOrderByCartId(intval($cart->id))) {
    $order = new Order(intval($id_order));
}
switch (Tools::getValue('Tag')) {
    case 0:
        $orderHistory = new OrderHistory();
        $orderHistory->id_order = intval($id_order);
        $orderHistory->id_order_state = _PS_OS_CANCELED_;
        $orderHistory->save();
        //$orderHistory->changeIdOrderState(intval($orderHistory->id), intval($order->id));
        break;
    case 1:
    case 13:
    case 10:
        if ($order->getCurrentState() == intval(Configuration::get('RNP_ID_ORDERSTATE'))) {
            $orderHistory = new OrderHistory();
            $orderHistory->id_order = intval($id_order);
            $orderHistory->id_order_state = _PS_OS_PAYMENT_;
            $orderHistory->save();
            //$orderHistory->changeIdOrderState(intval($orderHistory->id), intval($order->id));
        }
        break;
    case 2:
        if ($order->getCurrentState() == intval(Configuration::get('RNP_ID_ORDERSTATE'))) {
            $orderHistory = new OrderHistory();
            $orderHistory->id_order = intval($id_order);
            $orderHistory->id_order_state = _PS_OS_CANCELED_;
            $orderHistory->save();
            //$orderHistory->changeIdOrderState(intval($orderHistory->id), intval($order->id));
        }
Exemple #12
0
 public function validation()
 {
     if (!$this->active) {
         return;
     }
     if (!array_key_exists('xml', $_POST)) {
         return;
     }
     if (_PS_MAGIC_QUOTES_GPC_) {
         $_POST['xml'] = stripslashes($_POST['xml']);
     }
     require_once dirname(__FILE__) . '/mapi/mapi_package.php';
     if (HIPAY_MAPI_COMM_XML::analyzeNotificationXML($_POST['xml'], $operation, $status, $date, $time, $transid, $amount, $currency, $id_cart, $data) === false) {
         file_put_contents('logs' . Configuration::get('HIPAY_UNIQID') . '.txt', '[' . date('Y-m-d H:i:s') . '] Analysis error: ' . htmlentities($_POST['xml']) . "\n", FILE_APPEND);
         return false;
     }
     if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
         Context::getContext()->cart = new Cart((int) $id_cart);
     }
     $cart = new Cart((int) $id_cart);
     if (Tools::encrypt($cart->id . $cart->secure_key . Configuration::get('HIPAY_SALT')) != Tools::getValue('token')) {
         file_put_contents('logs' . Configuration::get('HIPAY_UNIQID') . '.txt', '[' . date('Y-m-d H:i:s') . '] Token error: ' . htmlentities($_POST['xml']) . "\n", FILE_APPEND);
     } else {
         if (trim($operation) == 'authorization' && trim(strtolower($status)) == 'ok') {
             // Authorization OK
             $orderMessage = $operation . ": " . $status . "\ndate: " . $date . " " . $time . "\ntransaction: " . $transid . "\namount: " . (double) $amount . " " . $currency . "\nid_cart: " . (int) $id_cart;
             $this->_createAuthorizationOrderState();
             $this->validateOrder((int) $id_cart, Configuration::get('HIPAY_AUTHORIZATION_OS'), (double) $amount, $this->displayName, $orderMessage, array(), NULL, false, $cart->secure_key);
         } else {
             if (trim($operation) == 'capture' && trim(strtolower($status)) == 'ok') {
                 // Capture OK
                 $orderMessage = $operation . ": " . $status . "\ndate: " . $date . " " . $time . "\ntransaction: " . $transid . "\namount: " . (double) $amount . " " . $currency . "\nid_cart: " . (int) $id_cart;
                 $id_order = Order::getOrderByCartId((int) $id_cart);
                 if ($id_order !== false) {
                     $order = new Order((int) $id_order);
                     if ((int) $order->getCurrentState() == (int) Configuration::get('HIPAY_AUTHORIZATION_OS')) {
                         $orderHistory = new OrderHistory();
                         $orderHistory->id_order = (int) $order->id;
                         $orderHistory->changeIdOrderState((int) Configuration::get('PS_OS_PAYMENT'), (int) $id_order);
                         $orderHistory->addWithemail();
                     }
                 } else {
                     $this->validateOrder((int) $id_cart, Configuration::get('PS_OS_PAYMENT'), (double) $amount, $this->displayName, $orderMessage, array(), NULL, false, $cart->secure_key);
                 }
                 Configuration::updateValue('HIPAY_CONFIGURATION_OK', true);
             } else {
                 if (trim($operation) == 'capture' && trim(strtolower($status)) == 'nok') {
                     // Capture NOK
                     $id_order = Order::getOrderByCartId((int) $id_cart);
                     if ($id_order !== false) {
                         $order = new Order((int) $id_order);
                         if ((int) $order->getCurrentState() == (int) Configuration::get('HIPAY_AUTHORIZATION_OS')) {
                             $orderHistory = new OrderHistory();
                             $orderHistory->id_order = (int) $order->id;
                             $orderHistory->changeIdOrderState((int) Configuration::get('PS_OS_ERROR'), (int) $id_order);
                             $orderHistory->addWithemail();
                         }
                     }
                 } elseif (trim($operation) == 'refund' && trim(strtolower($status)) == 'ok') {
                     /* Paiement remboursé sur Hipay */
                     if (!($id_order = Order::getOrderByCartId((int) $id_cart))) {
                         die(Tools::displayError());
                     }
                     $order = new Order((int) $id_order);
                     if (!$order->valid or $order->getCurrentState() === Configuration::get('PS_OS_REFUND')) {
                         die(Tools::displayError());
                     }
                     $orderHistory = new OrderHistory();
                     $orderHistory->id_order = (int) $order->id;
                     $orderHistory->changeIdOrderState((int) Configuration::get('PS_OS_REFUND'), (int) $id_order);
                     $orderHistory->addWithemail();
                 }
             }
         }
     }
 }
 public function validationws()
 {
     require_once _PS_MODULE_DIR_ . 'payulatam/config.php';
     $conf = new ConfPayu();
     $keysPayu = $conf->keys();
     $currency_iso_code = '';
     if ($conf->isTest()) {
         $currency_iso_code = 'USD';
     } else {
         $currency_iso_code = $params[9]['currency'];
     }
     if (!isset($_POST['sign']) && !isset($_POST['signature'])) {
         Logger::AddLog('[Payulatam] the signature is missing.', 2, null, null, null, true);
     } else {
         $token = isset($_POST['sign']) ? $_POST['sign'] : $_POST['signature'];
     }
     if (!isset($_POST['reference_sale']) && !isset($_POST['referenceCode'])) {
         Logger::AddLog('[Payulatam] the reference is missing.', 2, null, null, null, true);
     } else {
         $ref = isset($_POST['reference_sale']) ? $_POST['reference_sale'] : $_POST['referenceCode'];
     }
     if (!isset($_POST['value']) && !isset($_POST['amount'])) {
         Logger::AddLog('[Payulatam] the amount is missing.', 2, null, null, null, true);
     } else {
         $amount = isset($_POST['value']) ? $_POST['value'] : $_POST['amount'];
     }
     if (!isset($_POST['merchant_id']) && !isset($_POST['merchantId'])) {
         Logger::AddLog('[Payulatam] the merchantId is missing.', 2, null, null, null, true);
     } else {
         $merchantId = isset($_POST['merchant_id']) ? $_POST['merchant_id'] : $_POST['merchantId'];
     }
     if (!isset($_POST['lap_state']) && !isset($_POST['state_pol'])) {
         Logger::AddLog('[Payulatam] the lap_state is missing.', 2, null, null, null, true);
     } else {
         $statePol = isset($_POST['lap_state']) ? $_POST['lap_state'] : $_POST['state_pol'];
     }
     $idCart = explode('_', $ref)[2];
     $this->context->cart = new Cart((int) $idCart);
     $total_order = $this->context->cart->getOrderTotal();
     if (!$this->context->cart->OrderExists()) {
         Logger::AddLog('[Payulatam] The shopping card ' . (int) $idCart . ' doesn\'t have any order created', 2, null, null, null, true);
         return false;
     }
     if (Validate::isLoadedObject($this->context->cart)) {
         $id_orders = Db::getInstance()->ExecuteS('SELECT `id_order` FROM `' . _DB_PREFIX_ . 'orders` WHERE `id_cart` = ' . (int) $this->context->cart->id . '');
         foreach ($id_orders as $val) {
             $order = new Order((int) $val['id_order']);
             if ($this->context->cart->getOrderTotal() != $amount) {
                 Logger::AddLog('[Payulatam] The shopping card ' . (int) $idCart . ' doesn\'t have the correct amount expected during payment validation.' . $keysPayu['apiKey'] . '~' . Tools::safeOutput($keysPayu['merchantId']) . '~payU_' . Configuration::get('PS_SHOP_NAME') . '_' . (int) $this->context->cart->id . '~' . number_format((double) $this->context->cart->getOrderTotal(), 2, '.', '') . '~' . $currency->iso_code . '~' . $statePol . "---" . $amount, 2, null, null, null, true);
             } else {
                 $currency = new Currency((int) $this->context->cart->id_currency);
                 if ($token == md5($keysPayu['apiKey'] . '~' . Tools::safeOutput($keysPayu['merchantId']) . '~payU_' . Configuration::get('PS_SHOP_NAME') . '_' . (int) $this->context->cart->id . '_' . $conf->get_intentos($this->context->cart->id) . '~' . number_format((double) $total_order, 2, '.', '') . '~' . $currency_iso_code . '~' . $statePol) || $token == md5($keysPayu['apiKey'] . '~' . Tools::safeOutput($keysPayu['merchantId']) . '~payU_' . Configuration::get('PS_SHOP_NAME') . '_' . (int) $this->context->cart->id . '_' . $conf->get_intentos($this->context->cart->id) . '~' . number_format((double) $total_order, 1, '.', '') . '~' . $currency_iso_code . '~' . $statePol) || $token == md5($keysPayu['apiKey'] . '~' . Tools::safeOutput($keysPayu['merchantId']) . '~payU_' . Configuration::get('PS_SHOP_NAME') . '_' . (int) $this->context->cart->id . '_' . $conf->get_intentos($this->context->cart->id) . '~' . number_format((double) $total_order, 0, '.', '') . '~' . $currency_iso_code . '~' . $statePol)) {
                     // CUANDO SE ENVIAN # ENTEROS EN EL PAGO A PAYU, ESTE RETORNA 1 DECIMAL, CUANDO SE ENVIAN DECIMALES, PAYU RETORNA 2 DECIMALES. SE VALIDA TAMBIEN SIN DECIMALES EVG GPB
                     if ($statePol == 7) {
                         if ($order->getCurrentState() != (int) Configuration::get('PAYU_WAITING_PAYMENT')) {
                             $order->setCurrentState((int) Configuration::get('PAYU_WAITING_PAYMENT'));
                         }
                     } else {
                         if ($statePol == 4) {
                             if ($order->getCurrentState() != (int) Configuration::get('PS_OS_PAYMENT')) {
                                 $order->setCurrentState((int) Configuration::get('PS_OS_PAYMENT'));
                             }
                         } else {
                             if ($order->getCurrentState() != (int) Configuration::get('PS_OS_ERROR')) {
                                 $order->setCurrentState((int) Configuration::get('PS_OS_ERROR'));
                             }
                             Logger::AddLog('[PayU] (payulatam) The shopping card ' . (int) $idCart . ' has been rejected by PayU state pol=' . (int) $statePol, 2, null, null, null, true);
                         }
                     }
                 } else {
                     Logger::AddLog('[PayU] The shopping card ' . (int) $idCart . ' has an incorrect token given from payU during payment validation.' . $keysPayu['apiKey'] . '~' . Tools::safeOutput($keysPayu['merchantId']) . '~payU_' . Configuration::get('PS_SHOP_NAME') . '_' . (int) $this->context->cart->id . '~' . number_format((double) $total_order, 2, '.', '') . '~' . $currency->iso_code . '~' . $statePol . "--" . number_format((double) $total_order, 1, '.', '') . "--" . $token, 2, null, null, null, true);
                 }
             }
             if (_PS_VERSION_ >= 1.5) {
                 $payment = $order->getOrderPaymentCollection();
                 if (isset($payment[0])) {
                     $payment[0]->transaction_id = pSQL("payU_" . md5(Configuration::get('PS_SHOP_NAME')) . "_" . $idCart);
                     $payment[0]->save();
                 }
             }
         }
     } else {
         Logger::AddLog('[PayU] The shopping card ' . (int) $idCart . ' was not found during the payment validation step', 2, null, null, null, true);
     }
 }
Exemple #14
0
/* We made internal security checks */
$max_time = 60 * 10;
$idEmployee = (int) Tools::getValue('idEmployee');
$timeGenerated = (int) Tools::getValue('timeGenerated');
$cryptToken = md5($idEmployee . _COOKIE_KEY_ . $timeGenerated);
if (Tools::getValue('cryptToken') == $cryptToken && time() - $timeGenerated < $max_time) {
    /* Retrive all orders up to 3 months */
    $sql = 'SELECT *
			FROM ' . _DB_PREFIX_ . 'orders
			WHERE date_add > "' . date('c', strtotime('-3 months')) . '"';
    $order_details = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    $final_products = array();
    if (is_array($order_details) && count($order_details) > 0) {
        foreach ($order_details as $ar_order) {
            $order = new Order($ar_order['id_order']);
            if ($order->getCurrentState() == Configuration::get('feedaty_status_request')) {
                /* For each order we get id, date, customer email, prestashop version and some product infos */
                $products = $order->getProducts();
                $tmp_order = array();
                $tmp_order['OrderId'] = $ar_order['id_order'];
                $tmp_order['OrderDate'] = $ar_order['date_add'];
                $customer = new Customer((int) $order->id_customer);
                $tmp_order['CustomerEmail'] = $customer->email;
                $tmp_order['CustomerId'] = $customer->email;
                $tmp_order['Platform'] = 'PrestaShop ' . _PS_VERSION_ . ' CSV';
                if (is_array($products) && count($products) > 0) {
                    foreach ($products as $product) {
                        /* For each product we collect image url, url, name, id */
                        $tmp = $tmp_order;
                        $id_image = Product::getCover($product['product_id']);
                        if (count($id_image) > 0) {
Exemple #15
0
 private function _processPaymentReturn()
 {
     /** @var PayzenResponse $payzenResponse */
     $payzenResponse = new PayzenResponse($_REQUEST, Configuration::get('PAYZEN_MODE'), Configuration::get('PAYZEN_KEY_TEST'), Configuration::get('PAYZEN_KEY_PROD'));
     $cartId = $this->currentCart->id;
     // Check the authenticity of the request
     if (!$payzenResponse->isAuthentified()) {
         $this->module->logger->logError("Cart #{$cartId} : authentication error ! Redirect to home page.");
         Tools::redirectLink('index.php');
     }
     // Search order in db
     $orderId = Order::getOrderByCartId($cartId);
     if ($orderId == false) {
         // order has not been processed yet
         if ($payzenResponse->isAcceptedPayment()) {
             $this->module->logger->logWarning("Payment for cart #{$cartId} has been processed by client return ! This means the check URL did not work.");
             $newState = $this->module->isOneyPendingPayment($payzenResponse) ? Configuration::get('PAYZEN_OS_ONEY_PENDING') : Configuration::get('PS_OS_PAYMENT');
             $this->module->logger->logInfo("Payment accepted for cart #{$cartId}. New order status is {$newState}.");
             $order = $this->module->saveOrder($this->currentCart, $newState, $payzenResponse);
             // redirect to success page
             $this->_redirectSuccess($order, $this->module->id, $payzenResponse, true);
         } else {
             // payment KO
             if (Configuration::get('PAYZEN_FAILURE_MANAGEMENT') == Payzen::ON_FAILURE_SAVE || $this->module->isOney($payzenResponse)) {
                 // save on failure option is selected or oney payment : save order and go to history page
                 $newState = $payzenResponse->isCancelledPayment() ? Configuration::get('PS_OS_CANCELED') : Configuration::get('PS_OS_ERROR');
                 $this->module->logger->logWarning("Payment for order #{$cartId} has been processed by client return ! This means the check URL did not work.");
                 $msg = $this->module->isOney($payzenResponse) ? 'FacilyPay Oney payment' : 'Save on failure option is selected';
                 $this->module->logger->logInfo("{$msg} : save failed order for cart #{$cartId}. New order status is {$newState}.");
                 $this->module->saveOrder($this->currentCart, $newState, $payzenResponse);
                 $this->module->logger->logInfo("Redirect to history page, cart ID : #{$cartId}.");
                 Tools::redirect('index.php?controller=history');
             } else {
                 // option 2 choosen : get back to checkout process and show message
                 $this->module->logger->logInfo("Payment failed, redirect to order checkout page, cart ID : #{$cartId}.");
                 $controller = Configuration::get('PS_ORDER_PROCESS_TYPE') ? 'order-opc' : 'order' . (Tools::version_compare(_PS_VERSION_, '1.5.1', '>=') ? '&step=3' : '');
                 Tools::redirect('index.php?controller=' . $controller . '&payzen_pay_error=yes');
             }
         }
     } else {
         // order already registered
         $this->module->logger->logInfo("Order already registered for cart #{$cartId}.");
         $order = new Order((int) $orderId);
         $oldState = $order->getCurrentState();
         switch ($oldState) {
             case Configuration::get('PS_OS_ERROR'):
             case Configuration::get('PS_OS_CANCELED'):
                 $this->module->logger->logInfo("Save on failure option is selected or FacilyPay Oney payment. Order for cart #{$cartId} is in a failed status.");
                 if ($payzenResponse->isAcceptedPayment()) {
                     // order saved with failed status while payment is successful
                     $this->module->logger->logError("Payment success received from platform while order is in a failed status for cart #{$cartId}.");
                 } else {
                     // just display a failure confirmation message
                     $this->module->logger->logInfo("Payment failure confirmed for cart #{$cartId}.");
                 }
                 $this->module->logger->logInfo("Redirect to history page. Cart ID : #{$cartId}.");
                 Tools::redirect('index.php?controller=history');
                 break;
             case Configuration::get('PAYZEN_OS_ONEY_PENDING'):
             case $oldState == Configuration::get('PS_OS_OUTOFSTOCK') && $this->module->isOney($payzenResponse):
                 $this->module->logger->logInfo("Order for cart #{$cartId} is saved but waiting FacilyPay Oney confirmation. Update order status according to payment result.");
                 if ($payzenResponse->isPendingPayment()) {
                     // redirect to success page
                     $this->module->logger->logInfo("FacilyPay Oney pending status confirmed for cart #{$cartId}. Just redirect to success page.");
                     $this->_redirectSuccess($order, $this->module->id, $payzenResponse);
                 } else {
                     // order is pending Oney confirmation, payment is not pending : error case
                     $this->module->logger->logError("Order saved with FacilyPay Oney pending status while payment not pending, cart ID : #{$cartId}.");
                     Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cartId . '&id_module=' . $this->module->id . '&id_order=' . $order->id . '&key=' . $order->secure_key . '&error=yes');
                 }
                 break;
             case Configuration::get('PS_OS_PAYMENT'):
             case Configuration::get('PAYZEN_OS_PAYMENT_OUTOFSTOCK'):
             case $oldState == Configuration::get('PS_OS_OUTOFSTOCK') && !$this->module->isOney($payzenResponse):
             default:
                 if ($payzenResponse->isAcceptedPayment()) {
                     // redirect to success page
                     $this->module->logger->logInfo("Payment success confirmed for cart #{$cartId}. Just redirect to success page.");
                     $this->_redirectSuccess($order, $this->module->id, $payzenResponse);
                 } else {
                     // order saved with success status while payment failed
                     $this->module->logger->logError("Order saved with success status while payment failed, cart ID : #{$cartId}.");
                     Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cartId . '&id_module=' . $this->module->id . '&id_order=' . $order->id . '&key=' . $order->secure_key . '&error=yes');
                 }
                 break;
             default:
                 // order saved with unmanaged status, redirect client according to payment result
                 $this->module->logger->logInfo("Order saved with unmanaged status for cart #{$cartId}, redirect client according to payment result.");
                 if ($payzenResponse->isAcceptedPayment()) {
                     // redirect to success page
                     $this->module->logger->logInfo("Payment success for cart #{$cartId}. Redirect to success page.");
                     $this->_redirectSuccess($order, $this->module->id, $payzenResponse);
                 } else {
                     $this->module->logger->logInfo("Payment failure for cart #{$cartId}. Redirect to history page.");
                     Tools::redirect('index.php?controller=history');
                 }
                 break;
         }
     }
 }
Exemple #16
0
 /**
  *
  * Get the last Kwixo tag for an order and return the correct payment status
  * 
  * @param TaglineResponse $tag
  * @param Order $order
  * @param string $tid
  * 
  */
 function manageKwixoTagline($tag, $order, $tid)
 {
     $id_order = $order->id;
     if ($tag->hasError()) {
         KwixoLogger::insertLogKwixo(__METHOD__ . " : " . __LINE__, "Appel Tagline sur commande kwixo {$id_order} échoué : " . $tag->getError());
     } else {
         //get kwixo tag and kwixo score
         $kwixo_tag = $tag->getTagValue();
         $kwixo_score = $tag->getScore();
         KwixoLogger::insertLogKwixo(__METHOD__ . ' : ' . __LINE__, 'Appel Tagline : id_order = ' . $id_order . ' | tag = ' . $kwixo_tag);
         //insert or update kwixo order for tagline action
         $this->manageKwixoOrder($id_order, $kwixo_tag, $tid, '', 'tagline');
         if (in_array($order->getCurrentState(), array((int) Configuration::get('KW_OS_WAITING'), (int) Configuration::get('KW_OS_CREDIT'), (int) Configuration::get('KW_OS_CONTROL')))) {
             switch ($kwixo_tag) {
                 //order under kwixo control
                 case 3:
                     $psosstatus = (int) Configuration::get('KW_OS_CONTROL');
                     break;
                 case 4:
                     //if current state is diffrent of kwixo under control
                     if (!in_array($order->getCurrentState(), array((int) Configuration::get('KW_OS_CONTROL')))) {
                         $psosstatus = (int) Configuration::get('KW_OS_WAITING');
                     } else {
                         return false;
                     }
                     break;
                     //order under credit waiting
                 //order under credit waiting
                 case 6:
                     $psosstatus = (int) Configuration::get('KW_OS_CREDIT');
                     break;
                     //order on valid status
                 //order on valid status
                 case 1:
                 case 13:
                 case 14:
                 case 10:
                     if ($kwixo_score == 'positif') {
                         $psosstatus = (int) Configuration::get('KW_OS_PAYMENT_GREEN');
                     } elseif ($kwixo_score == 'negatif') {
                         $psosstatus = (int) Configuration::get('KW_OS_PAYMENT_RED');
                     } else {
                         $psosstatus = (int) _PS_OS_PAYMENT_;
                     }
                     break;
                     //order on payment refused
                 //order on payment refused
                 case 0:
                 case 2:
                 case 11:
                 case 12:
                 case 101:
                     $psosstatus = (int) _PS_OS_CANCELED_;
                     break;
                     //order on delivery done
                 //order on delivery done
                 case 100:
                     $psosstatus = (int) _PS_OS_PAYMENT_;
                     break;
                 default:
                     break;
             }
             //return the correct payment status
             if ($order->getCurrentState() != $psosstatus) {
                 //update order history
                 $this->updateOrderHistory($id_order, $psosstatus);
             }
         }
     }
 }
Exemple #17
0
 public function validation()
 {
     if (!array_key_exists('xml', $_POST)) {
         return;
     }
     if (_PS_MAGIC_QUOTES_GPC_) {
         $_POST['xml'] = stripslashes($_POST['xml']);
     }
     require_once dirname(__FILE__) . '/mapi/mapi_package.php';
     if (HIPAY_MAPI_COMM_XML::analyzeNotificationXML($_POST['xml'], $operation, $status, $date, $time, $transid, $amount, $currency, $id_cart, $data) === false) {
         file_put_contents('logs' . Configuration::get('HIPAY_UNIQID') . '.txt', '[' . date('Y-m-d H:i:s') . '] ' . $_POST['xml'] . "\n", FILE_APPEND);
     }
     if (trim($operation) == 'capture' and trim(strtolower($status)) == 'ok') {
         /* Paiement capturé sur Hipay = Paiement accepté sur Prestashop */
         $orderMessage = $operation . ': ' . $status . "\n" . 'date: ' . $date . ' ' . $time . "\n" . 'transaction: ' . $transid . "\n" . 'amount: ' . (double) $amount . ' ' . $currency . "\n" . 'id_cart: ' . (int) $id_cart;
         $this->validateOrder((int) $id_cart, _PS_OS_PAYMENT_, (double) $amount, $this->displayName, $orderMessage);
     } elseif (trim($operation) == 'refund' and trim(strtolower($status)) == 'ok') {
         /* Paiement remboursé sur Hipay */
         if (!($id_order = Order::getOrderByCartId(intval($id_cart)))) {
             die(Tools::displayError());
         }
         $order = new Order(intval($id_order));
         if (!$order->valid or $order->getCurrentState() === _PS_OS_REFUND_) {
             die(Tools::displayError());
         }
         $orderHistory = new OrderHistory();
         $orderHistory->id_order = intval($order->id);
         $orderHistory->changeIdOrderState(intval(_PS_OS_REFUND_), intval($id_order));
         $orderHistory->addWithemail();
     }
 }
 public static function ManageUrlSys()
 {
     $payment = new Kwixo();
     if (!$payment->isInstalled('kwixo')) {
         KwixoLogger::insertLogKwixo(__METHOD__ . ' : ' . __LINE__, 'Module Kwixo non installé, retour UrlSys échoué');
         return false;
     }
     $transactionID = Tools::getValue('TransactionID');
     $refID = Tools::getValue('RefID');
     $tag = Tools::getValue('Tag');
     $id_cart = Tools::getValue('custom', false);
     $amount = Tools::getValue('amount', false);
     $cart = new Cart((int) $id_cart);
     //Multishop
     if (_PS_VERSION_ < '1.5') {
         $kwixo = new KwixoPayment();
     } else {
         $kwixo = new KwixoPayment($cart->id_shop);
     }
     if ($kwixo->getAuthKey() == '') {
         KwixoLogger::insertLogKwixo(__METHOD__ . ' : ' . __LINE__, 'Clé privée Kwixo vide, retour UrlSys échoué');
         return false;
     }
     $md5 = new KwixoMD5();
     $waitedhash = $md5->hash($kwixo->getAuthKey() . $refID . $transactionID);
     $receivedhash = Tools::getValue('HashControl', '0');
     //Hash control
     if ($waitedhash != $receivedhash) {
         KwixoLogger::insertLogKwixo(__METHOD__ . ' : ' . __LINE__, 'URLSys erreur : HashControl invalide (valeur attendue = "' . $waitedhash . '", valeur reçue = "' . $receivedhash . '"). IP expediteur : ' . Tools::getRemoteAddr());
     } else {
         //if cart if empty : error and exit
         if (!$cart->id) {
             KwixoLogger::insertLogKwixo(__METHOD__ . ' : ' . __LINE__, "Le panier pour la commande {$refid}/{$transactionid} n'existe pas.");
             exit;
         }
         global $cookie;
         //Give order_id
         $id_order = Order::getOrderByCartId($cart->id);
         if ($id_order !== false) {
             $order = new Order((int) $id_order);
             KwixoLogger::insertLogKwixo(__METHOD__ . ' : ' . __LINE__, 'URLSys : id_cart = ' . $id_cart . (!Order::getOrderByCartId($id_cart) ? '' : ' | id_order = ' . Order::getOrderByCartId($id_cart)) . ' | tag = ' . $tag);
         } else {
             KwixoLogger::insertLogKwixo(__METHOD__ . ' : ' . __LINE__, 'URLSys : order false');
         }
         switch ($tag) {
             //Give up payment, tag sent after 1 hour
             case 0:
                 KwixoLogger::insertLogKwixo(__METHOD__ . ' : ' . __LINE__, 'URLSys abandon après 1h : id_cart = ' . $id_cart . (!Order::getOrderByCartId($id_cart) ? '' : ' | id_order = ' . Order::getOrderByCartId($id_cart)) . ' | tag = ' . $tag);
                 break;
                 //Accepted payment
             //Accepted payment
             case 1:
             case 13:
             case 14:
             case 10:
                 //Retrieve score if present
                 $score = Tools::getValue('Score', false);
                 //if order current state in cancelled or waiting or under control or credit status, status updated
                 if ($id_order === false || in_array($order->getCurrentState(), array((int) _PS_OS_CANCELED_, (int) Configuration::get('KW_OS_WAITING'), (int) Configuration::get('KW_OS_CREDIT'), (int) Configuration::get('KW_OS_CONTROL')))) {
                     if ($score == 'positif') {
                         $psosstatus = (int) Configuration::get('KW_OS_PAYMENT_GREEN');
                     } elseif ($score == 'negatif') {
                         $psosstatus = (int) Configuration::get('KW_OS_PAYMENT_RED');
                     } else {
                         $psosstatus = (int) _PS_OS_PAYMENT_;
                     }
                 }
                 break;
                 //Payment refused
             //Payment refused
             case 2:
                 if (!in_array($order->getCurrentState(), array((int) Configuration::get('KW_OS_PAYMENT_GREEN'), (int) Configuration::get('KW_OS_PAYMENT_RED'), (int) Configuration::get('KW_OS_CONTROL'), (int) Configuration::get('KW_OS_CREDIT')))) {
                     $psosstatus = (int) _PS_OS_CANCELED_;
                 }
                 break;
                 //order under control
             //order under control
             case 3:
                 //if order current state in cancelled or waiting or credit status, status updated
                 if ($id_order === false || in_array($order->getCurrentState(), array((int) _PS_OS_CANCELED_, (int) Configuration::get('KW_OS_WAITING'), (int) Configuration::get('KW_OS_CREDIT')))) {
                     $psosstatus = (int) Configuration::get('KW_OS_CONTROL');
                 }
                 break;
                 //order on waiting status
             //order on waiting status
             case 4:
                 if ($id_order === false) {
                     $psosstatus = (int) Configuration::get('KW_OS_WAITING');
                 }
                 break;
                 //order under credit status
             //order under credit status
             case 6:
                 //if order current state in cancelled or waiting, status updated
                 if ($id_order === false || in_array($order->getCurrentState(), array((int) _PS_OS_CANCELED_, (int) Configuration::get('KW_OS_WAITING')))) {
                     $psosstatus = (int) Configuration::get('KW_OS_CREDIT');
                 }
                 break;
                 //payment refused
             //payment refused
             case 11:
             case 12:
                 //if order current state in cancelled or waiting, status updated
                 if ($id_order === false || in_array($order->getCurrentState(), array((int) _PS_OS_CANCELED_, (int) Configuration::get('KW_OS_WAITING'), (int) Configuration::get('KW_OS_CREDIT'), (int) Configuration::get('KW_OS_CONTROL')))) {
                     $psosstatus = (int) _PS_OS_CANCELED_;
                 }
                 break;
                 //payment cancelled
             //payment cancelled
             case 101:
                 $psosstatus = (int) _PS_OS_CANCELED_;
                 break;
                 //delivery done
             //delivery done
             case 100:
                 if ($id_order === false || !in_array($order->getCurrentState(), array((int) _PS_OS_DELIVERED_, (int) _PS_OS_PREPARATION_, (int) _PS_OS_SHIPPING_, (int) _PS_OS_PAYMENT_))) {
                     $psosstatus = (int) _PS_OS_PAYMENT_;
                 }
                 break;
             default:
                 break;
                 KwixoLogger::insertLogKwixo(__METHOD__ . ' : ' . __LINE__, 'Appel URLSys : id_cart = ' . $id_cart . (!Order::getOrderByCartId($id_cart) ? '' : ' | id_order = ' . Order::getOrderByCartId($id_cart)) . ' | tag = ' . $tag);
         }
     }
     //Validate order and update status
     if (isset($psosstatus)) {
         if ($id_order === false) {
             $feedback = 'Order Create';
             $payment->validateOrder((int) $cart->id, $psosstatus, $amount, $payment->displayName, $feedback, NULL, $cart->id_currency);
             $id_order = Order::getOrderByCartId($cart->id);
             $payment->manageKwixoOrder($id_order, $tag, $transactionID, $id_cart, 'urlsys');
             if ($cookie->id_cart == (int) $cookie->last_id_cart) {
                 unset($cookie->id_cart);
             }
         } else {
             //update order history
             $order->setCurrentState($psosstatus);
         }
     }
 }
if (!$success) {
    die;
}
$data = $_POST['data'];
$parsed_data = json_decode(base64_decode($data));
$received_signature = $_POST['signature'];
$received_public_key = $parsed_data['public_key'];
$order_id = $parsed_data['order_id'];
$status = $parsed_data['status'];
$order = new Order();
$OrderID = $order->getOrderByCartId(intval($order_id));
if (!$OrderID) {
    die;
}
$order = new Order($OrderID);
if ($order->getCurrentState() != Configuration::get('PS_OS_PREPARATION')) {
    die;
}
$private_key = Configuration::get('LIQPAY_PRIVATE_KEY');
$public_key = Configuration::get('LIQPAY_PUBLIC_KEY');
$generated_signature = base64_encode(sha1($private_key . $data . $private_key, 1));
if ($received_signature != $generated_signature || $public_key != $received_public_key) {
    die;
}
if ($status == 'success') {
    $history = new OrderHistory();
    $history->id_order = $OrderID;
    $history->id_order_state = Configuration::get('PS_OS_PAYMENT');
    $history->add();
} elseif ($status == 'failure') {
    $history = new OrderHistory();
 public function validation()
 {
     if (!$this->active) {
         return;
     }
     if (!array_key_exists('xml', $_POST)) {
         return;
     }
     if (_PS_MAGIC_QUOTES_GPC_) {
         $_POST['xml'] = stripslashes($_POST['xml']);
     }
     require_once dirname(__FILE__) . '/mapi/mapi_package.php';
     if (HIPAY_MAPI_COMM_XML::analyzeNotificationXML($_POST['xml'], $operation, $status, $date, $time, $transid, $amount, $currency, $id_cart, $data) === false) {
         file_put_contents('logs' . Configuration::get('HIPAY_UNIQID') . '.txt', '[' . date('Y-m-d H:i:s') . '] Analysis error: ' . htmlentities($_POST['xml']) . "\n", FILE_APPEND);
         return false;
     }
     if (_PS_VERSION_ >= 1.5) {
         Context::getContext()->cart = new Cart((int) $id_cart);
     }
     $cart = new Cart((int) $id_cart);
     if (Tools::encrypt($cart->id . $cart->secure_key . Configuration::get('HIPAY_SALT')) != Tools::getValue('token')) {
         file_put_contents('logs' . Configuration::get('HIPAY_UNIQID') . '.txt', '[' . date('Y-m-d H:i:s') . '] Token error: ' . htmlentities($_POST['xml']) . "\n", FILE_APPEND);
     } else {
         if (trim($operation) == 'capture' and trim(strtolower($status)) == 'ok') {
             /* Paiement capturé sur Hipay = Paiement accepté sur Prestashop */
             $orderMessage = $operation . ': ' . $status . '\\ndate: ' . $date . ' ' . $time . '\\ntransaction: ' . $transid . '\\namount: ' . (double) $amount . ' ' . $currency . '\\nid_cart: ' . (int) $id_cart;
             $this->validateOrder((int) $id_cart, Configuration::get('PS_OS_PAYMENT'), (double) $amount, $this->displayName, $orderMessage, array(), NULL, false, $cart->secure_key);
         } elseif (trim($operation) == 'refund' and trim(strtolower($status)) == 'ok') {
             /* Paiement remboursé sur Hipay */
             if (!($id_order = Order::getOrderByCartId((int) $id_cart))) {
                 die(Tools::displayError());
             }
             $order = new Order((int) $id_order);
             if (!$order->valid or $order->getCurrentState() === Configuration::get('PS_OS_REFUND')) {
                 die(Tools::displayError());
             }
             $orderHistory = new OrderHistory();
             $orderHistory->id_order = (int) $order->id;
             $orderHistory->changeIdOrderState((int) Configuration::get('PS_OS_REFUND'), (int) $id_order);
             $orderHistory->addWithemail();
         }
     }
 }
 public function updatePendyngOrdesConfirmation()
 {
     $orders_pendyng = $this->getPendyngOrdesConfirmation();
     foreach ($orders_pendyng as $key) {
         $order = new Order((int) $key['id_order']);
         $statePol = $this->getStatePolBymessagePol($key['message']);
         if ($statePol == 7) {
             if ($order->getCurrentState() != (int) Configuration::get('PAYU_OS_PENDING')) {
                 $order->setCurrentState((int) Configuration::get('PAYU_OS_PENDING'));
             }
         } else {
             if ($statePol == 4) {
                 if ($order->getCurrentState() != (int) Configuration::get('PS_OS_PAYMENT')) {
                     $order->setCurrentState((int) Configuration::get('PS_OS_PAYMENT'));
                 }
             } else {
                 if ($order->getCurrentState() != (int) Configuration::get('PS_OS_ERROR')) {
                     $order->setCurrentState((int) Configuration::get('PS_OS_ERROR'));
                 }
             }
         }
         if (_PS_VERSION_ >= 1.5) {
             $payment = $order->getOrderPaymentCollection();
             if (isset($payment[0])) {
                 $payment[0]->transaction_id = pSQL("payU_farmalisto_" . $key['id_cart']);
                 $payment[0]->save();
             }
         }
         echo '<br>Order: ' . $key['id_order'];
     }
 }