---
metadata:
  - name: generator
    content: Diplodoc Platform v5.52.0
alternate:
  - https://pay.yandex.ru/docs/en/custom/web-sdk/reset-session.md
  - https://pay.yandex.ru/docs/ru/custom/web-sdk/reset-session.md
  - href: ru/custom/web-sdk/reset-session.md
    type: text/markdown
    title: Markdown version
  - href: ../../llms.txt
    type: text/markdown
    title: llms.txt
title: "Сброс сессии Яндекс\_Пэй\_— обновление платежных кнопок | Документация"
description: "Пересоздавайте платежную сессию при изменении корзины. API для динамического обновления кнопок и виджетов Яндекс\_Пэй."
---
> **Documentation Index:** Fetch the complete configuration index at https://pay.yandex.ru/docs/ru/llms.txt


# Пересоздание платежной сессии и кнопок Яндекс Пэй

Иногда возникает необходимость пересоздания платежной сессии и платежных кнопок.
Например, кнопка может показываться в динамическом блоке, а сессия пересоздаваться при динамическом каталоге.

Процесс пересоздания предполагает удаление активных сессии и кнопок перед созданием новых.

## Удаление платежной сессии {#delete-payment-session}

При удалении сессии также удаляются все платежные кнопки, относящиеся к этой сессии.

```javascript
// Удаление платежной сессии и кнопок
paymentSession.destroy();
```

## Удаление платежной кнопки {#delete-payment-button}

```javascript
// Удаление платежной кнопки на определенном DOM-узле
paymentSession.unmountButton(
    document.querySelector('<selector>')
);
```

## Пример {#example}

<!-- TODO: w-sdk-snippets-1 -->

<!-- source: ru/custom/web-sdk/_snippets/reset-session--v4.mdx -->
<!-- markdownlint-disable -->

<div class="ypd-preview ypd-preview_with-source">
    <a href="https://yastatic.net/s3/pay-static/docs/v46.0.0/custom/reset-session--v4/index.html" target="_blank">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M18 19H6c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h5c.55 0 1-.45 1-1s-.45-1-1-1H5c-1.11 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-6c0-.55-.45-1-1-1s-1 .45-1 1v5c0 .55-.45 1-1 1zM14 4c0 .55.45 1 1 1h2.59l-9.13 9.13c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L19 6.41V9c0 .55.45 1 1 1s1-.45 1-1V3h-6c-.55 0-1 .45-1 1z"></path></svg>
    </a>
    <iframe src="https://yastatic.net/s3/pay-static/docs/v46.0.0/custom/reset-session--v4/index.html" style="height: 250px"></iframe>
</div>

```javascript
function onYaPayLoad() {
    const YaPay = window.YaPay;

    const buttonContainer = document.querySelector('#button_container');
    const resetPaySessionButton = document.querySelector('#reset_pay_session');
    const resetPayButtonButton = document.querySelector('#reset_pay_button');

    // Ссылка на активную сессию
    let activeSession = null;

    function createPaymentSession(amount) {
        // Данные платежа
        const paymentData = {
            env: YaPay.PaymentEnv.Sandbox,
            version: 4,
            currencyCode: YaPay.CurrencyCode.Rub,
            merchantId: '<YOUR_MERCHANT_ID>',
            totalAmount: `${amount}.00`,
            availablePaymentMethods: ['CARD', 'SPLIT'],
        };

        // Обработчик на клик по кнопке
        // Функция должна возвращать промис которые резолвит ссылку на оплату полученную от бэкенда Яндекс Пэй
        // Подробнее про создание заказа: https://pay.yandex.ru/ru/docs/custom/backend/yandex-pay-api/order/merchant_v1_orders-post
        async function onPayButtonClick() {
            /* Создание заказа... */
        }

        // Создаем платежную сессию
        YaPay.createSession(paymentData, {
            onPayButtonClick: onPayButtonClick,
        })
            .then(function (paymentSession) {
                activeSession = paymentSession;
                // Создаем кнопку для активной сессии
                createPaymentButton();
            })
            .catch(function (err) {
                // Не получилось создать платежную сессию.
            });
    }

    // Функция создания платежной кнопки
    function createPaymentButton() {
        if (activeSession) {
            activeSession.mountButton(buttonContainer, {
                type: YaPay.ButtonType.Pay,
                theme: YaPay.ButtonTheme.Black,
                width: YaPay.ButtonWidth.Auto,
            });
        }
    }

    // Функция пересоздания платежной сессии
    function resetPaymentSession() {
        // Удаляем активную сессию
        if (activeSession) {
            activeSession.destroy();
            activeSession = null;
        }

        // Создаем новую сессию
        createPaymentSession(getNewAmount());
    }

    // Функция пересоздания платежной кнопки
    function resetPaymentButton() {
        // Удаляем кнопку на активной сессии
        if (activeSession) {
            activeSession.unmountButton(buttonContainer);
        }

        // Создаем новую кнопку
        createPaymentButton();
    }

    resetPaySessionButton.addEventListener('click', resetPaymentSession);
    resetPayButtonButton.addEventListener('click', resetPaymentButton);

    createPaymentSession(7990);
}

/**
 * Сопроводительные функции для иллюстрации работы
 */

function getNewAmount() {
    const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

    const price = 7990;
    const count = randomInt(1, 20);

    return price * count;
}

```
<!-- endsource: ru/custom/web-sdk/_snippets/reset-session--v4.mdx -->
