Vinoteca: модуль, шаблон и компоненты интернет-магазина вина на 1С-Битрикс

This commit is contained in:
jimagie committed 2026-10-22 03:32:28 +05:00
commit f6ba0d2174
470 files changed
+26454

No files matched your search

@@ -0,0 +1,351 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Application;
use Bitrix\Main\Context;
use Bitrix\Main\Engine\CurrentUser;
use Bitrix\Main\HttpRequest;
use Bitrix\Main\Loader;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\Security\Sign\Signer;
use Bitrix\Main\Type\DateTime;
use Bitrix\Main\Web\HttpClient;
use Bitrix\Main\Web\Json;
use Bitrix\Sale\Basket\RefreshFactory;
use Bitrix\Sale\BasketBase;
use Bitrix\Sale\BusinessValue;
use Bitrix\Sale\Delivery\Services\Manager as DeliveryManager;
use Bitrix\Sale\Internals\PaymentTable;
use Bitrix\Sale\Internals\PersonTypeTable;
use Bitrix\Sale\Order;
use Bitrix\Sale\Payment;
use Bitrix\Sale\PaySystem\BaseServiceHandler;
use Bitrix\Sale\PaySystem\Logger;
use Bitrix\Sale\PaySystem\Manager as PaySystemManager;
use Bitrix\Sale\PaySystem\Service;
Loc::loadMessages(__FILE__);
final class Checkout
{
private const PERSON_CODE = "BUYER";
private const DELIVERY_CODE = "pickup";
private const PROPERTIES = ["NAME", "PHONE", "EMAIL"];
private const PAYPAL_ACTION = "jinove_paypal";
private const YOOKASSA_ACTION = "yandexcheckout";
private const HALYK_ACTION = "jinove_halyk";
private const UNPAID_HOURS = 24;
private const UNPAID_REASON = "Online payment was not completed within 24 hours";
private const YOOKASSA_API = "https://api.yookassa.ru/v3/payments/";
private const TOKEN_SALT = "vino-order";
private const LOCK_SECONDS = 10;
public static function methods(): array
{
$methods = [];
if (!Loader::includeModule("sale")) {
return $methods;
}
$rows = PaySystemManager::getList(["filter" => ["=ACTIVE" => "Y", "=ENTITY_REGISTRY_TYPE" => "ORDER"], "order" => ["SORT" => "ASC", "ID" => "ASC"]]);
while ($row = $rows->fetch()) {
$code = self::methodCode((string)$row["ACTION_FILE"]);
if ($code === "") {
continue;
}
$methods[] = [
"id" => (int)$row["ID"],
"code" => $code,
"name" => (string)Loc::getMessage("VINO_PAY_" . strtoupper($code)),
"hint" => (string)Loc::getMessage("VINO_PAY_" . strtoupper($code) . "_HINT"),
];
}
return $methods;
}
public static function create(BasketBase $basket, array $contacts, int $paySystemId, string $consentProof): array
{
$methods = array_column(self::methods(), null, "id");
if (!isset($methods[$paySystemId])) {
return ["error" => "pay"];
}
$person = PersonTypeTable::getRow(["filter" => ["=CODE" => self::PERSON_CODE, "=ACTIVE" => "Y"], "select" => ["ID"]]);
$delivery = \Bitrix\Sale\Delivery\Services\Table::getRow(["filter" => ["=CODE" => self::DELIVERY_CODE, "=ACTIVE" => "Y"], "select" => ["ID"]]);
if ($person === null || $delivery === null) {
return ["error" => "shop"];
}
$basket->refresh(RefreshFactory::create(RefreshFactory::TYPE_FULL));
$items = $basket->getOrderableItems();
if ($items->isEmpty()) {
return ["error" => "empty"];
}
$siteId = Config::basketSiteId();
$userId = (int)CurrentUser::get()->getId();
$order = Order::create($siteId, $userId > 0 ? $userId : (int)\CSaleUser::GetAnonymousUserID());
$order->setPersonTypeId((int)$person["ID"]);
$order->setBasket($items);
$shipments = $order->getShipmentCollection();
$shipment = $shipments->createItem(DeliveryManager::getObjectById((int)$delivery["ID"]));
$shipment->setField("CURRENCY", $order->getCurrency());
$shipmentItems = $shipment->getShipmentItemCollection();
foreach ($order->getBasket() as $basketItem) {
$shipmentItems->createItem($basketItem)->setQuantity($basketItem->getQuantity());
}
$shipments->calculateDelivery();
$properties = $order->getPropertyCollection();
$proof = $properties->getItemByOrderPropertyCode("CONSENT_PROOF");
if ($proof === null) {
return ["error" => "shop"];
}
$proof->setValue($consentProof);
foreach (self::PROPERTIES as $code) {
$property = $properties->getItemByOrderPropertyCode($code);
if ($property !== null) {
$property->setValue((string)($contacts[strtolower($code)] ?? ""));
}
}
$comment = (string)($contacts["comment"] ?? "");
if ($comment !== "") {
$order->setField("USER_DESCRIPTION", $comment);
}
$payment = $order->getPaymentCollection()->createItem(PaySystemManager::getObjectById($paySystemId));
$order->doFinalAction(true);
$payment->setField("SUM", $order->getPrice());
$payment->setField("CURRENCY", $order->getCurrency());
$result = $order->save();
if (!$result->isSuccess()) {
return ["error" => "save", "messages" => $result->getErrorMessages()];
}
return [
"order" => $order,
"payment" => $order->getPaymentCollection()->current(),
"method" => $methods[$paySystemId],
];
}
public static function token(Order $order): string
{
return (new Signer())->getSignature($order->getId() . ":" . $order->getField("ACCOUNT_NUMBER"), self::TOKEN_SALT);
}
public static function find(int $orderId, string $hash): ?Order
{
if ($orderId <= 0 || $hash === "" || !Loader::includeModule("sale")) {
return null;
}
$order = Order::load($orderId);
if ($order === null || !hash_equals(self::token($order), $hash)) {
return null;
}
return $order;
}
public static function doneUrl(Order $order, string $dir, array $extra = []): string
{
return Config::host() . $dir . "personal/order/done/?" . http_build_query(["id" => $order->getId(), "hash" => self::token($order)] + $extra);
}
public static function startPayment(Order $order, string $dir): array
{
$payment = $order->getPaymentCollection()->current();
if ($payment === null || $payment->isPaid()) {
return ["url" => ""];
}
$service = $payment->getPaySystem();
$code = $service !== null ? self::methodCode((string)$service->getField("ACTION_FILE")) : "";
if ($code === "" || $code === "cash") {
return ["url" => ""];
}
if ((string)$payment->getField("PS_INVOICE_ID") !== "" && self::finishPayment($order, [])) {
return ["url" => self::doneUrl($order, $dir)];
}
$order = Order::load($order->getId());
$payment = $order->getPaymentCollection()->current();
$service = $payment->getPaySystem();
$returnUrl = self::doneUrl($order, $dir, ["payment" => $payment->getId()]);
if ($code === "yookassa") {
$service->getContext()->setUrl($returnUrl);
}
$request = new HttpRequest(
Context::getCurrent()->getServer(),
["return_url" => $returnUrl, "cancel_url" => self::doneUrl($order, $dir, ["payment" => $payment->getId(), "cancel" => "Y"])],
[],
[],
[]
);
$result = $service->initiatePay($payment, $request, BaseServiceHandler::STRING);
$widget = $result->getData()["widget"] ?? null;
if (!$result->isSuccess() || ($result->getPaymentUrl() === "" && !is_array($widget))) {
return ["url" => ""];
}
if (!$order->save()->isSuccess()) {
return ["url" => ""];
}
return ["url" => $result->getPaymentUrl(), "widget" => is_array($widget) ? $widget : null];
}
public static function finishPayment(Order $order, array $query): bool
{
$connection = Application::getConnection();
$key = "vino_pay_" . $order->getId();
if (!$connection->lock($key, self::LOCK_SECONDS)) {
return false;
}
try {
$fresh = Order::load($order->getId());
return $fresh !== null && self::verify($fresh, $query);
} finally {
$connection->unlock($key);
}
}
public static function methodOf(Order $order): string
{
$payment = $order->getPaymentCollection()->current();
$service = $payment !== null ? $payment->getPaySystem() : null;
return $service !== null ? self::methodCode((string)$service->getField("ACTION_FILE")) : "";
}
public static function cancelUnpaid(): string
{
if (!Loader::includeModule("sale")) {
return __METHOD__ . "();";
}
$online = [];
foreach (self::methods() as $method) {
if ($method["code"] !== "cash") {
$online[] = $method["id"];
}
}
if (!$online) {
return __METHOD__ . "();";
}
$border = new DateTime();
$border->add("-" . self::UNPAID_HOURS . " hours");
$rows = PaymentTable::getList([
"filter" => ["=PAID" => "N", "@PAY_SYSTEM_ID" => $online, "=ORDER.CANCELED" => "N", "<ORDER.DATE_INSERT" => $border],
"select" => ["ORDER_ID"],
"order" => ["ID" => "ASC"],
"limit" => 200,
]);
while ($row = $rows->fetch()) {
$order = Order::load((int)$row["ORDER_ID"]);
if ($order === null || $order->isPaid() || $order->isCanceled()) {
continue;
}
$payment = $order->getPaymentCollection()->current();
if ($payment !== null && (string)$payment->getField("PS_INVOICE_ID") !== "" && self::finishPayment($order, [])) {
continue;
}
$order = Order::load($order->getId());
$order->setField("CANCELED", "Y");
$order->setField("REASON_CANCELED", self::UNPAID_REASON);
$order->save();
}
return __METHOD__ . "();";
}
public static function consentProof(string $page): string
{
return "consent=Y; version=" . Consent::VERSION . "; policy=" . Consent::POLICY_VERSION . "; page=" . $page . "; at=" . new DateTime();
}
public static function dir(string $requested): string
{
foreach (Config::languages() as $language) {
if ((string)($language["dir"] ?? "") === $requested) {
return $requested;
}
}
return "/";
}
private static function verify(Order $order, array $query): bool
{
$payment = $order->getPaymentCollection()->current();
if ($payment === null) {
return false;
}
if ($payment->isPaid()) {
return true;
}
$service = $payment->getPaySystem();
$code = $service !== null ? self::methodCode((string)$service->getField("ACTION_FILE")) : "";
if ($code === "yookassa") {
return self::finishYookassa($order, $payment, $service);
}
$token = (string)($query["token"] ?? "");
if ($code === "paypal" && $token === "") {
$token = (string)$payment->getField("PS_INVOICE_ID");
}
if ($code !== "halyk" && ($code !== "paypal" || $token === "")) {
return false;
}
$request = new HttpRequest(Context::getCurrent()->getServer(), ["payment" => $payment->getId(), "token" => $token], [], [], []);
$result = $service->processRequest($request);
return $result->isSuccess() && Order::load($order->getId())->getPaymentCollection()->current()->isPaid();
}
private static function finishYookassa(Order $order, Payment $payment, Service $service): bool
{
$invoice = (string)$payment->getField("PS_INVOICE_ID");
if ($invoice === "") {
return false;
}
$consumer = "PAYSYSTEM_" . (int)$service->getField("ID");
$client = new HttpClient(["socketTimeout" => 10, "streamTimeout" => 10]);
$client->setHeader("Authorization", "Basic " . base64_encode(trim((string)BusinessValue::get("YANDEX_CHECKOUT_SHOP_ID", $consumer)) . ":" . trim((string)BusinessValue::get("YANDEX_CHECKOUT_SECRET_KEY", $consumer))));
$body = $client->get(self::YOOKASSA_API . rawurlencode($invoice));
if ($body === false || $client->getStatus() !== 200) {
Logger::addError(__METHOD__ . ": status request failed, HTTP " . $client->getStatus());
return false;
}
try {
$data = Json::decode((string)$body);
} catch (\Throwable $exception) {
return false;
}
$amount = (float)($data["amount"]["value"] ?? 0);
$currency = (string)($data["amount"]["currency"] ?? "");
if (($data["status"] ?? "") !== "succeeded" || empty($data["paid"]) || $currency !== $payment->getCurrency() || abs($amount - (float)$payment->getSum()) > 0.01) {
return false;
}
$paid = $payment->setPaid("Y");
if (!$paid->isSuccess()) {
return false;
}
$payment->setFields(["PS_STATUS" => "Y", "PS_STATUS_CODE" => "succeeded", "PS_SUM" => $amount, "PS_CURRENCY" => $currency, "PS_RESPONSE_DATE" => new DateTime()]);
return $order->save()->isSuccess();
}
private static function methodCode(string $action): string
{
if ($action === self::PAYPAL_ACTION) {
return "paypal";
}
if ($action === self::YOOKASSA_ACTION) {
return "yookassa";
}
if ($action === self::HALYK_ACTION) {
return "halyk";
}
return $action === "cashondelivery" ? "cash" : "";
}
}