### Get Order Details Source: https://pay.yandex.ru/docs/ru/payments/payment-details Retrieves detailed information about a specific order, which includes payment details. ```APIDOC ## GET /orders/{order_id} ### Description Retrieves detailed information about a specific order, which includes payment details. ### Method GET ### Endpoint /orders/{order_id} ### Parameters #### Path Parameters - **order_id** (string) - Required - The unique identifier of the order. ### Response #### Success Response (200) - **order_id** (string) - The unique identifier of the order. - **status** (string) - The current status of the order. - **amount** (object) - The amount of the order. - **value** (string) - The monetary value. - **currency** (string) - The currency code (e.g., RUB). - **created_at** (string) - The timestamp when the order was created. - **updated_at** (string) - The timestamp when the order was last updated. ### Response Example ```json { "order_id": "12345abcde", "status": "PAID", "amount": { "value": "1000.00", "currency": "RUB" }, "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:05:00Z" } ``` ``` -------------------------------- ### Authenticate Seller Request Source: https://pay.yandex.ru/docs/ru/custom/backend/yandex-pay-api Pass your API key in the Authorization header for every request. Ensure the key is valid to avoid a 401 Unauthorized response. ```bash --header 'Authorization: Api-Key <значение ключа>' ``` -------------------------------- ### Include Yandex Pay Web SDK Source: https://pay.yandex.ru/docs/ru/custom/web-sdk Add this script tag to your HTML pages before the closing tag to load the Yandex Pay Web SDK. The `onload` attribute specifies the function to call after the SDK is loaded. ```html ``` -------------------------------- ### Initialize Yandex Pay Payment Session Source: https://pay.yandex.ru/docs/ru/custom/web-sdk This JavaScript code initializes the Yandex Pay session with payment details and configures event handlers for button clicks and form opening errors. It then mounts the Yandex Pay button to a specified DOM element. ```javascript function onYaPayLoad() { const YaPay = window.YaPay; // Данные платежа const paymentData = { // Для отладки нужно явно указать `SANDBOX` окружение, // для продакшена параметр можно убрать или указать `PRODUCTION` env: YaPay.PaymentEnv.Sandbox, // Версия 4 указывает на тип оплаты сервисом Яндекс Пэй // Пользователь производит оплату на форме Яндекс Пэй, // и мерчанту возвращается только результат проведения оплаты version: 4, // Код валюты в которой будете принимать платежи currencyCode: YaPay.CurrencyCode.Rub, // Идентификатор продавца, который получают при регистрации в Яндекс Пэй merchantId: '', // Сумма к оплате // Сумма которая будет отображена на форме зависит от суммы переданной от бэкенда // Эта сумма влияет на отображение доступности Сплита totalAmount: '15980.00', // Доступные для использования методы оплаты // Доступные на форме способы оплаты также зависят от информации переданной от бэкенда // Данные передаваемые тут влияют на внешний вид кнопки или виджета availablePaymentMethods: ['CARD', 'SPLIT'], }; // Обработчик на клик по кнопке // Функция должна возвращать промис которые резолвит ссылку на оплату полученную от бэкенда Яндекс Пэй // Подробнее про создание заказа: https://pay.yandex.ru/ru/docs/custom/backend/yandex-pay-api/order/merchant_v1_orders-post async function onPayButtonClick() { // Создание заказа... // и возврат URL на оплату вида 'https://pay.ya.ru/l/XXXXXX' } // Обработчик на ошибки при открытии формы оплаты function onFormOpenError(reason) { // Выводим информацию о недоступности оплаты в данный момент // и предлагаем пользователю другой способ оплаты. console.error(`Payment error — ${reason}`); } // Создаем платежную сессию YaPay.createSession(paymentData, { onPayButtonClick: onPayButtonClick, onFormOpenError: onFormOpenError, }) .then(function (paymentSession) { // Показываем кнопку Яндекс Пэй на странице. paymentSession.mountButton(document.querySelector('#button_container'), { type: YaPay.ButtonType.Pay, theme: YaPay.ButtonTheme.Black, width: YaPay.ButtonWidth.Auto, }); }) .catch(function (err) { // Не получилось создать платежную сессию. }); } ``` -------------------------------- ### Testing Cash Register API Sandbox Environment Source: https://pay.yandex.ru/docs/ru/testing Use the sandbox environment for Cash Register API testing. It mimics the production environment with test keys and an automatic payment flow. Ensure to configure test keys and Callback URL in your Yandex Pay personal account. ```bash https://sandbox.pay.yandex.ru/api/merchant/cash-register ``` -------------------------------- ### Service Headers Source: https://pay.yandex.ru/docs/ru/custom/backend/yandex-pay-api To enhance reliability and simplify debugging, include the following HTTP headers in your requests: `X-Request-Id` for unique request identification and idempotency, `X-Request-Timeout` for specifying the request timeout in milliseconds, and `X-Request-Attempt` for tracking retry attempts. ```APIDOC ## Служебные заголовки Чтобы повысить надежность и упростить отладку процессов, передавайте следующие HTTP-заголовки в ваших запросах: Заголовок | Значение | Описание ---|---|--- `X-Request-Id` | Уникальный идентификатор запроса | Нужен для: * отладки запросов; * обеспечения _идемпотентности_. Сохраняйте одно и то же значение `X-Request-Id` во всех перезапросах при получении ошибок с HTTP‑статусами `5xx` или `429`. `X-Request-Timeout` | Таймаут в миллисекундах | Нужен для _deadline propagation_ при обработке запроса. Правила: * не используйте значения меньше 1 секунды (1000 мс); * максимальное значение — 10 секунд (10 000 мс). `X-Request-Attempt` | Номер попытки | Полезен для общей диагностики. Например, 0 — первая попытка, 1, 2 и т. д. — перезапросы. ``` -------------------------------- ### Request Authentication Source: https://pay.yandex.ru/docs/ru/custom/backend/yandex-pay-api To use the Yandex Pay API, you need to obtain a Merchant API key. This key should be passed in the `Authorization` HTTP header for every request. If the key is missing or invalid, the server will respond with a `401 Unauthorized` status. ```APIDOC ## Аутентификация запроса продавца Для использования API необходимо получить ключ Merchant API (API-ключ). Выпустите его в личном кабинете Яндекс Пэй по инструкции. Передавайте API-ключ в HTTP-заголовке `Authorization` каждого запроса: ``` --header 'Authorization: Api-Key <значение ключа>' ``` Если в запросе отсутствует или передан недействительный API-ключ, сервер возвращает HTTP-статус `401 Unauthorized`. ``` -------------------------------- ### Refund Payment Operation Source: https://pay.yandex.ru/docs/ru/custom/refund-payments Initiates a full or partial refund for a given order. Ensure no other refund operation is in progress for the same order. ```APIDOC ## POST /orders/{order_id}/refund ### Description Initiates a refund for a specific order. Can be a full or partial refund. ### Method POST ### Endpoint /orders/{order_id}/refund ### Parameters #### Path Parameters - **order_id** (string) - Required - The unique identifier of the order to refund. #### Request Body - **refundAmount** (number) - Required - The amount to refund. For a full refund, this should be the total order amount. For a partial refund, specify the amount to be refunded. - **targetCart** (object) - Optional - The final state of the cart after the refund. Required for partial refunds if `refundCart` is not provided. - **refundCart** (object) - Optional - The items being refunded. Required for partial refunds if `targetCart` is not provided. ### Request Example For a full refund: ```json { "refundAmount": 1000 } ``` For a partial refund: ```json { "refundAmount": 500, "refundCart": { "items": [ { "quantity": 1, "price": { "amount": 500, "currency": "RUB" }, "offerId": "item_123" } ] } } ``` ### Response #### Success Response (200 OK) Indicates that the refund request has been accepted and is being processed. #### Response Example ```json { "operationId": "some_operation_id", "status": "PENDING" } ``` #### Error Response (409 Conflict) Returned if another refund operation is already in progress for the same order. ```json { "code": "ANOTHER_OPERATION_IN_PROGRESS", "description": "Another operation is in progress." } ``` ``` -------------------------------- ### Encrypt S3 Secret Key with OpenSSL Source: https://pay.yandex.ru/docs/ru/reports Encrypts an S3 Secret Key using OpenSSL with RSA PKCS#1 OAEP padding and encodes it in Base64. This is required for secure transmission of credentials to Yandex Pay support. ```bash echo -n 'S3_SECRET_KEY' | openssl rsautl -oaep -encrypt -pubin -inkey PUBLIC.pem | base64 ```