Setting up product exchange on 1C-Bitrix

Our company is engaged in the development, support and maintenance of Bitrix and Bitrix24 solutions of any complexity. From simple one-page sites to complex online stores, CRM systems with 1C and telephony integration. The experience of developers is confirmed by certificates from the vendor.
Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1175
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    811
  • image_bitrix-bitrix-24-1c_development_of_an_online_appointment_booking_widget_for_a_medical_center_594_0.webp
    Development based on Bitrix, Bitrix24, 1C for the company Development of an Online Appointment Booking Widget for a Medical Center
    564
  • image_bitrix-bitrix-24-1c_mirsanbel_458_0.webp
    Development based on 1C Enterprise for MIRSANBEL
    747
  • image_crm_dolbimby_434_0.webp
    Website development on CRM Bitrix24 for DOLBIMBY
    655
  • image_crm_technotorgcomplex_453_0.webp
    Development based on Bitrix24 for the company TECHNOTORGKOMPLEKS
    976

Configuring Product Exchange in 1C-Bitrix

A product exchange is a scenario distinct from a return: the customer does not want their money back — they want a different product (different size, colour, or model). 1C-Bitrix has no dedicated "Exchange" module — it is a combination of returning the original item and creating a new order, typically with a credit adjustment. Setting this up requires custom logic on top of the sale module.

Exchange business logic

Two exchange schemes must be supported:

Scheme 1: 1-to-1 exchange — item of equal value. A return is created for the original item and a new order is created for the replacement. Surcharge/refund of difference = 0.

Scheme 2: Exchange with surcharge/refund of the difference — item of different value. If the new item is more expensive — the customer pays the difference. If cheaper — the difference is refunded.

Exchange data structure

To store the relationship "original return → new order", create a Highload block or table:

class ExchangeTable extends \Bitrix\Main\ORM\Data\DataManager
{
    public static function getTableName(): string { return 'local_sale_exchange'; }

    public static function getMap(): array
    {
        return [
            new \Bitrix\Main\ORM\Fields\IntegerField('ID', ['primary' => true, 'autocomplete' => true]),
            new \Bitrix\Main\ORM\Fields\IntegerField('ORIGINAL_ORDER_ID'),
            new \Bitrix\Main\ORM\Fields\IntegerField('RETURN_ID'),          // return request ID
            new \Bitrix\Main\ORM\Fields\IntegerField('NEW_ORDER_ID'),       // new order ID
            new \Bitrix\Main\ORM\Fields\IntegerField('ORIGINAL_BASKET_ID'), // line item in the original order
            new \Bitrix\Main\ORM\Fields\IntegerField('NEW_PRODUCT_ID'),     // new product
            new \Bitrix\Main\ORM\Fields\FloatField('ORIGINAL_PRICE'),
            new \Bitrix\Main\ORM\Fields\FloatField('NEW_PRICE'),
            new \Bitrix\Main\ORM\Fields\FloatField('DIFF_AMOUNT'),          // surcharge (+) or refund (-) amount
            new \Bitrix\Main\ORM\Fields\StringField('STATUS'),              // pending, paid, completed
            new \Bitrix\Main\ORM\Fields\DatetimeField('CREATED_AT'),
        ];
    }
}

Creating an exchange

namespace Local\Returns;

class ExchangeManager
{
    public function initiateExchange(array $params): array
    {
        // $params:
        // - original_order_id: int
        // - original_basket_id: int (line item being exchanged)
        // - new_product_id: int (replacement product)
        // - new_product_props: [] (size, colour, etc.)

        \Bitrix\Main\Loader::includeModule('sale');
        \Bitrix\Main\Loader::includeModule('catalog');

        $order = \Bitrix\Sale\Order::load($params['original_order_id']);
        if (!$order || $order->getUserId() !== $this->currentUserId) {
            throw new \RuntimeException('Order not found');
        }

        // Get the original line item
        $originalItem = null;
        foreach ($order->getBasket() as $item) {
            if ($item->getId() === (int)$params['original_basket_id']) {
                $originalItem = $item;
                break;
            }
        }

        if (!$originalItem) {
            throw new \RuntimeException('Basket item not found');
        }

        $originalPrice = $originalItem->getFinalPrice();

        // Price of the new product
        $newPrice = $this->getProductPrice($params['new_product_id']);
        $diffAmount = $newPrice - $originalPrice;

        // Create a return request for the original item
        $returnManager = new ReturnManager();
        $returnId = $returnManager->createReturn(
            $params['original_order_id'],
            [['basket_id' => $params['original_basket_id'], 'quantity' => 1, 'reason' => 'exchange']],
            'EXCHANGE'
        );

        // Create a new replacement order
        $newOrderId = $this->createExchangeOrder(
            $order->getUserId(),
            $params['new_product_id'],
            $params['new_product_props'] ?? [],
            $diffAmount,
            $order
        );

        // Save the relationship
        $exchangeId = ExchangeTable::add([
            'ORIGINAL_ORDER_ID' => $params['original_order_id'],
            'RETURN_ID'         => $returnId,
            'NEW_ORDER_ID'      => $newOrderId,
            'ORIGINAL_BASKET_ID'=> $params['original_basket_id'],
            'NEW_PRODUCT_ID'    => $params['new_product_id'],
            'ORIGINAL_PRICE'    => $originalPrice,
            'NEW_PRICE'         => $newPrice,
            'DIFF_AMOUNT'       => $diffAmount,
            'STATUS'            => $diffAmount > 0 ? 'pending_payment' : 'pending_ship',
            'CREATED_AT'        => new \Bitrix\Main\Type\DateTime(),
        ])->getId();

        return [
            'exchange_id'  => $exchangeId,
            'return_id'    => $returnId,
            'new_order_id' => $newOrderId,
            'diff_amount'  => $diffAmount,
            'needs_payment'=> $diffAmount > 0,
        ];
    }

    private function createExchangeOrder(
        int $userId,
        int $productId,
        array $props,
        float $diffAmount,
        \Bitrix\Sale\Order $originalOrder
    ): int {
        $order = \Bitrix\Sale\Order::create(SITE_ID, $userId);
        $order->setPersonTypeId($originalOrder->getPersonTypeId());

        // Copy delivery address from the original order
        $propertyCollection = $order->getPropertyCollection();
        foreach ($originalOrder->getPropertyCollection() as $prop) {
            $newProp = $propertyCollection->getItemByOrderPropertyId($prop->getPropertyId());
            if ($newProp) {
                $newProp->setValue($prop->getValue());
            }
        }

        $basket = \Bitrix\Sale\Basket::create(SITE_ID);
        $item   = $basket->createItem('catalog', $productId);
        $item->setField('QUANTITY', 1);

        if ($props) {
            $item->setField('PROPS', $props);
        }

        $order->setBasket($basket);

        // If a refund is due — apply a discount equal to (originalPrice - newPrice)
        if ($diffAmount < 0) {
            $order->getDiscount()->setData([
                'COUPON_DISCOUNT' => abs($diffAmount),
            ]);
        }

        // Copy delivery
        $shipmentCollection = $order->getShipmentCollection();
        $shipment = $shipmentCollection->createItem();
        $shipment->setField('DELIVERY_ID', $this->getDefaultDeliveryId());

        $result = $order->save();

        if (!$result->isSuccess()) {
            throw new \RuntimeException('Exchange order failed: ' . implode('; ', $result->getErrorMessages()));
        }

        return $order->getId();
    }
}

Exchange status synchronisation

When the return is complete (old item received) and the new order is paid — mark the exchange as completed:

\Bitrix\Main\EventManager::getInstance()->addEventHandler(
    'sale',
    'OnSaleOrderReturnStatusChange',
    function (\Bitrix\Main\Event $event) {
        if ($event->getParameter('NEW_STATUS_ID') !== 'RECEIVED') return;

        $returnId = $event->getParameter('RETURN_ID');

        $exchange = ExchangeTable::getList([
            'filter' => ['RETURN_ID' => $returnId],
            'limit'  => 1,
        ])->fetch();

        if (!$exchange) return;

        // Check whether the new order is paid
        $newOrder = \Bitrix\Sale\Order::load($exchange['NEW_ORDER_ID']);
        if ($newOrder && $newOrder->isPaid()) {
            ExchangeTable::update($exchange['ID'], ['STATUS' => 'completed']);
        } else {
            ExchangeTable::update($exchange['ID'], ['STATUS' => 'awaiting_payment']);
        }
    }
);

Customer notification about the exchange

class ExchangeNotifications
{
    public static function sendExchangeCreated(int $exchangeId): void
    {
        $exchange = ExchangeTable::getById($exchangeId)->fetch();

        $diffAmount = (float)$exchange['DIFF_AMOUNT'];

        if ($diffAmount > 0) {
            $message = "Exchange created. To complete it, please pay the difference of {$diffAmount}. "
                . "Payment link: https://example.com/order/{$exchange['NEW_ORDER_ID']}/pay/";
        } elseif ($diffAmount < 0) {
            $message = "Exchange approved. After we receive the item, we will refund "
                . abs($diffAmount) . " to your card.";
        } else {
            $message = "Exchange approved. New order #{$exchange['NEW_ORDER_ID']} will be shipped "
                . "once the returned item is received.";
        }

        \CEvent::Send('EXCHANGE_CREATED', SITE_ID, [
            'ORDER_ID'    => $exchange['ORIGINAL_ORDER_ID'],
            'NEW_ORDER_ID'=> $exchange['NEW_ORDER_ID'],
            'MESSAGE'     => $message,
        ]);
    }
}

Scope of work

  • Table local_sale_exchange to store the return ↔ new order relationship
  • ExchangeManager class: creating a return and a new order in a single transaction
  • Exchange form in the personal account: selecting the new product/size
  • Handling surcharges when exchanging for a more expensive item
  • Event handler: automatic exchange status update upon item receipt
  • Email notifications: exchange created, item received, exchange completed

Timeline: basic 1-to-1 exchange logic — 2–3 weeks. Exchange with surcharge and full automation — 4–6 weeks.