/** * заказ оплачен уже или нет */ 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; }
/** * Код будет выполнен, когда интернет-сайт получит уведомление от 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")); }
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; }
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; }