Exemplo n.º 1
0
 public function createTables()
 {
     $prefix = PayqrModuleDbConfig::$prefix;
     $sql = "CREATE TABLE IF NOT EXISTS `{$prefix}payqr_invoice` (\n                    `id` int(11) NOT NULL AUTO_INCREMENT,\n                    `invoice_id` varchar(100) NOT NULL,\n                    `invoice_type` varchar(100) NOT NULL,\n                    `order_id` varchar(100) DEFAULT NULL,\n                    INDEX `order_id_index` (`order_id`), \n                    INDEX `invoice_index` (`invoice_id`, `invoice_type`),\n                    PRIMARY KEY (`id`)\n                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n                \n                CREATE TABLE IF NOT EXISTS `{$prefix}payqr_log` (\n                `log_id` int(11) NOT NULL AUTO_INCREMENT,\n                  `data` text NOT NULL,\n                  `event_id` varchar(100) NOT NULL,\n                  `event_type` varchar(100) NOT NULL,\n                  `payqr_number` varchar(100) NOT NULL,\n                  `datetime` datetime NOT NULL, \n                  `order_id` int(11) DEFAULT NULL,\n                   INDEX `event_id_index` (`event_id`), \n                   PRIMARY KEY (`log_id`)\n                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n                CREATE TABLE IF NOT EXISTS `{$prefix}payqr_user` (\n                    `user_id` int(11) NOT NULL AUTO_INCREMENT,\n                    `username` varchar(100) NOT NULL,\n                    `password` varchar(100) NOT NULL,\n                    `merch_id` varchar(100) DEFAULT NULL,\n                    `settings` text DEFAULT NULL,\n                    PRIMARY KEY (`user_id`)\n                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
     $db = PayqrModuleDb::getInstance();
     $table = $db->query("show tables like '{$prefix}payqr_user'");
     if (!$table) {
         $db->multiQuery($sql);
     }
 }
Exemplo n.º 2
0
 private function setOptions()
 {
     $db = PayqrModuleDb::getInstance();
     $auth = new PayqrModuleAuth();
     $user = $auth->getUser();
     if ($user) {
         $query = "select settings from " . PayqrModuleDb::getUserTable() . " where user_id={$user->user_id}";
     } else {
         $query = "select settings from " . PayqrModuleDb::getUserTable() . " limit 1";
     }
     $result = $db->query($query);
     if ($settings = json_decode($result->settings)) {
         foreach ($settings as $item) {
             $this->options[$item->key] = $item->value;
         }
     }
 }
Exemplo n.º 3
0
 private function recoverUser()
 {
     if (isset($_COOKIE[$this->key])) {
         $db = PayqrModuleDb::getInstance();
         $user = $db->select("select user_id, username, merch_id from " . PayqrModuleDb::getUserTable() . " where md5(concat(user_id, username, '" . $this->salt . "')) = ?", array($_COOKIE[$this->key]), array("s"));
         if ($user) {
             $_SESSION[$this->key] = $user;
         }
     } else {
         $location = PayqrModule::getBaseUrl() . "/module/auth/";
         $auth_location = "http://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}";
         if ($location != $auth_location) {
             header("Location: {$location}");
         }
         $_SESSION[$this->key] = false;
     }
 }
Exemplo n.º 4
0
 public function save($post)
 {
     $db = PayqrModuleDb::getInstance();
     $settings = $this->getSettings();
     foreach ($settings as $item) {
         if (isset($post[$item->key])) {
             $item->value = $post[$item->key];
             if ($item->key == "logUrl") {
                 $key = "key=";
                 $url = explode($key, $post[$item->key]);
                 $item->value = $url[0] . $key . $post["logKey"];
             }
             if ($item->key == "merchantID") {
                 $db->update(PayqrModuleDb::getUserTable(), array("merch_id" => $post[$item->key]), array("%s"), array("user_id" => $this->user->user_id), array("%s"));
             }
         }
     }
     $settings = json_encode($settings);
     $db->update(PayqrModuleDb::getUserTable(), array("settings" => $settings), array("%s"), array("user_id" => $this->user->user_id), array("%s"));
 }
Exemplo n.º 5
0
 /**
  * заказ оплачен уже или нет
  */
 public function getOrderPaidStatus($invoice_id)
 {
     $db = PayqrModuleDb::getInstance();
     $invoice = $db->select("select * from " . PayqrModuleDb::getInvoiceTable() . " where invoice_id=?", array($invoice_id), array("s"));
     return $invoice;
 }
Exemplo n.º 6
0
 public function getForm()
 {
     $html = "";
     PayqrConfig::setConfig();
     $db = PayqrModuleDb::getInstance();
     $invoiceObj = $db->select("select * from " . PayqrModuleDb::getInvoiceTable() . " where order_id=?", array($this->id), array("s"));
     if ($invoiceObj) {
         $payqrInvoice = new PayqrInvoiceAction();
         $invoice = $payqrInvoice->invoice_get($invoiceObj->invoice_id);
         if ($invoice) {
             $html .= "<form method='post'>";
             $html .= "<div style='margin-bottom:20px'>";
             $html .= "<input type='hidden' name='invoice_id' value='{$invoice->id}'/>";
             $html .= "<input type='hidden' name='order_id' value='{$this->id}'/>";
             $html .= "<div class='row'><strong>Информация о заказе</strong>";
             $payqrFields = array("id" => "ID", "status" => "Статус", "confirmStatus" => "Cтатус подтверждения заказа", "payqrNumber" => "Номер инвойса", "orderId" => "ID заказа", "amount" => "Сумма", "revertAmount" => "Сумма возврата");
             $invoice->revertAmount = 0;
             foreach ($invoice->reverts as $item) {
                 if ($item->status == "succeedeed") {
                     $invoice->revertAmount += $item->revertedAmount;
                 }
             }
             $html .= "<table class='payqr'>";
             $k = 0;
             foreach ($payqrFields as $key => $field) {
                 $html .= "<tr class='" . ($k % 2 == 0 ? "odd" : "even") . "'><td>{$field}</td><td>{$invoice->{$key}}</td></tr>";
                 $k++;
             }
             $html .= "</table></div>";
             $html .= "<div class='row'><strong>Товары в заказе</strong>";
             $html .= "<table class='payqr'><tr><td>ID</td><td>кол-во</td><td>сумма</td></tr>";
             foreach ($invoice->cart as $k => $item) {
                 $html .= "<tr class='" . ($k % 2 == 0 ? "odd" : "even") . "'><td>{$item->article}</td><td>{$item->quantity}</td><td>{$item->amount}</td></tr>";
             }
             $html .= "</table></div>";
             if (count($invoice->reverts) > 0) {
                 $html .= "<div class='row'><strong>История возвратов</strong>";
                 $html .= "<table class='payqr'><tr><td>revertId</td><td>сумма</td><td>Статус</td></tr>";
                 foreach ($invoice->reverts as $k => $item) {
                     $html .= "<tr class='" . ($k % 2 == 0 ? "odd" : "even") . "'><td>{$item->id}</td><td>{$item->revertedAmount}</td><td>{$item->status}</td></tr>";
                 }
                 $html .= "</table></div>";
             }
             $html .= "<div class='row'><strong>Действия</strong></div>";
             //7 cases for payqr orders
             $html .= "<div class='row'><label>Ничего не выполнять: <input type='radio' name='invoice_action' value='invoice_no_action' checked/></label></div>";
             if ($invoice->status == "new") {
                 $html .= "<div class='row'><label>Аннулировать счет на заказ: <input type='radio' name='invoice_action' value='invoice_cancel'/></label></div>";
             } elseif ($invoice->status != "cancelled" && $invoice->status != "failed") {
                 if ($invoice->status == "paid" || $invoice->status == "revertedPartially") {
                     $html .= "<div class='row'><label>Отменить заказ после оплаты: <input class='invoice_check' text='PayQR.invoice_revert' type='radio' name='invoice_action' value='invoice_revert'/></label>";
                     $revert_amount_value = $invoice->amount - $invoice->revertAmount;
                     $html .= "<input type='hidden' name='invoice_amount' value='{$invoice->amount}'/>";
                     $html .= "<input type='hidden' name='invoice_revertAmount' value='{$invoice->revertAmount}'/>";
                     $html .= "<div><label>Сумма возврата: <input type='text' name='invoice_revert_amount' value='{$revert_amount_value}' class='form-text'/></label><div>";
                     $html .= "</div>";
                 }
                 if (($invoice->status == "paid" || $invoice->status == "revertedPartially" || $invoice->status == "reverted") && $invoice->confirmStatus == "waiting") {
                     $html .= "<div class='row'><label>Досрочно запустить расчеты: <input class='invoice_check' text='PayQR.invoice_confirm' type='radio' name='invoice_action' value='invoice_confirm'/></label></div>";
                 }
                 $time_since_created = round((time() - strtotime($invoice->created)) / 60);
                 if ($time_since_created < 259200 && ($invoice->status == "paid" || $invoice->status == "revertedPartially" || $invoice->status == "reverted")) {
                 }
                 $html .= "<div class='row'><label>Дослать/изменить сообщение: <input class='invoice_check' text='PayQR.invoice_message' text='PayQR.invoice_message' type='radio' name='invoice_action' value='invoice_message'/></label>";
                 $html .= "<div><label>Текст сообщения к покупке: <input type='text' name='invoice_message_text' value='' class='form-text'/></label></div>";
                 $html .= "<div><label>URL изображения для сообщения к покупке: <input type='text' name='invoice_message_image_url' value='' class='form-text'/></label></div>";
                 $html .= "<div><label>URL сайта для сообщения к покупке: <input type='text' name='invoice_message_click_url' value='' class='form-text'/></label></div></div>";
                 $html .= "<div class='row'><label>Синхронизировать статус с PayQR: <input class='invoice_check' text='PayQR.invoice_sync_data' type='radio' name='invoice_action' value='invoice_sync_data'/></label></div>";
             }
             $html .= "</div>";
             $html .= "<input type='submit' value='Выполнить' name='order_form'>";
             $html .= "</form>";
         } else {
             $html = "<strong>Нет данных в системе PayQR</strong>";
         }
     }
     return $html;
 }
Exemplo n.º 7
0
 /**
  * Код будет выполнен, когда интернет-сайт получит уведомление от PayQR об успешной оплате конкретного заказа.
  * Это означает, что PayQR успешно списал запрошенную интернет-сайтом сумму денежных средств с покупателя и перечислит ее интернет-сайту в ближайшее время, интернет-сайту нужно исполнять свои обязанности перед покупателем, т.е. доставлять товар или оказывать услугу. 
  *
  * $this->invoice содержит объект "Счет на оплату" (подробнее об объекте "Счет на оплату" на https://payqr.ru/api/ecommerce#invoice_object)
  *
  * Ниже можно вызвать функции своей учетной системы, чтобы особым образом отреагировать на уведомление от PayQR о событии invoice.paid.
  *
  * Получить orderId из объекта "Счет на оплату", по которому произошло событие, можно через $this->invoice->getOrderId();
  *
  * Важно: несмотря на то, что заказ создается на этапе получения уведомления о событии invoice.order.creating, крайне рекомендуется валидировать все содержание заказа и после получения уведомления о событии invoice.paid. А в случае, когда запрос адреса доставки у покупателя на уровне кнопки PayQR, настроен на рекомендательный режим (спрашивать после оплаты/спрашивать необязательно), то не просто рекомендуется, а обязательно, так как объект "Счет на оплату" на этапе invoice.paid будет содержать в себе расширенные окончательные данные, которых не было на invoice.order.creating. Если по результатам проверки данных из invoice.paid обнаружатся какие-то критичные расхождения (например, сумма заказа из объекта "Счет на оплату" не сходится с суммой из соответствующего заказа), можно сразу послать запрос в PayQR на отмену счету после его оплаты (возврат денег).
  */
 public function payOrder()
 {
     //отправка сообщений
     $module = new PayqrModule();
     if ($module->getOption("message-invoice-paid")) {
         $message = $this->invoice->getMessage();
         if ($message) {
             $message->article = $module->getOption("message-invoice-paid-article");
             $message->text = $module->getOption("message-invoice-paid-text");
             $message->imageUrl = $module->getOption("message-invoice-paid-imageUrl");
             $message->url = $module->getOption("message-invoice-paid-url");
             $this->invoice->setMessage($message);
         }
     }
     //сохраняем заказ
     $db = PayqrModuleDb::getInstance();
     $id = $db->update(PayqrModuleDb::getInvoiceTable(), array("invoice_type" => "invoice.paid"), array("%s"), array("invoice_id" => $this->invoice->getInvoiceId()), array("%s"));
 }
Exemplo n.º 8
0
 public function createOrder()
 {
     $order = new PayqrOrder($this->invoice, $this->diafan);
     $orderId = $order->createOrder();
     PayqrLog::log("Создали заказ:" . $orderId);
     $this->invoice->setOrderId($orderId);
     PayqrLog::log("Получаем invoice_id");
     $invoice_id = $this->invoice->getInvoiceId();
     PayqrLog::log("Получили invoice_id: " . $invoice_id);
     if ($order->getOrderPaidStatus($invoice_id)) {
     }
     /**
      * Устанавливаем общую стоимость заказа
      */
     PayqrLog::log("Устанавливаем сумму заказа");
     $total = $order->getTotalAmount();
     /**
      * Устанавливаем пользовательские данные
      */
     $order->setUserOrderData($orderId);
     /**
      * Получаем стоимость доставки
      */
     $delivery = 0;
     $deliverySelected = $this->invoice->getDeliveryCasesSelected();
     if (isset($deliverySelected, $deliverySelected->amountFrom) && !empty($deliverySelected->amountFrom)) {
         $delivery = round((double) $deliverySelected->amountFrom, 2);
         $order->updateDeliverySumm($orderId, $deliverySelected->article, $delivery);
     }
     $this->invoice->setAmount(round($total + $delivery));
     PayqrLog::log("Установили сумму заказа вместе с доставкой: " . $total . "+" . $delivery . " = " . ($total + $delivery));
     //отправка сообщений
     $module = new PayqrModule();
     if ($module->getOption("message-invoice-order-creating")) {
         $message = $this->invoice->getMessage();
         if ($message) {
             $message->article = $module->getOption("message-invoice-order-creating-article");
             $message->text = $module->getOption("message-invoice-order-creating-text");
             $message->imageUrl = $module->getOption("message-invoice-order-creating-imageUrl");
             $message->url = $module->getOption("message-invoice-order-creating-url");
             $this->invoice->setMessage($message);
         }
     }
     //сохраняем заказ
     $db = PayqrModuleDb::getInstance();
     $id = $db->insert(PayqrModuleDb::getInvoiceTable(), array("invoice_id" => $this->invoice->getInvoiceId(), "order_id" => $orderId, "invoice_type" => "invoice.order.creating"), array("%s", "%s", "%s"));
     //сохраняем логи
     $id = $db->insert(PayqrModuleDb::getLogTable(), array("event_id" => $this->invoice->getInvoiceId(), "order_id" => $orderId, "event_type" => "invoice.order.creating", "payqr_number" => $this->invoice->getPayqrNumber(), "datetime" => date("Y-m-d H:i:s"), "data" => file_get_contents("php://input")), array("%s", "%s", "%s", "%s", "%s", "%s"));
     return true;
 }