Skip to content
← All articles
10 min read

YooKassa integration: how to build reliable payment gateway workflows

A resilient YooKassa integration connects your checkout flow to the payment gateway without exposing the system to duplicate charges, dropped orders, or spoofed webhooks. The backend creates a payment using the Idempotence-Key header, redirects the customer to a secure checkout page, acknowledges notifications with an immediate HTTP 200, and verifies the transaction status directly through the API. Below is the complete engineering architecture from checkout to refunds.

How does the YooKassa payment lifecycle work from cart to fulfillment?

A production payment gateway integration connects three decoupled boundaries: the customer's browser or mobile application, your merchant backend, and the YooKassa API servers. The core responsibility of your backend is maintaining strict transactional consistency. Money is authorized and captured inside banking infrastructure, but product delivery, entitlement provisioning, or physical warehouse reservation occurs inside your database. When network packets drop mid-flight, your system must deterministically recover without manual support intervention.

The standard payment flow relies on a secure redirect pattern. Your application never handles raw credit card credentials, avoiding stringent PCI DSS compliance scopes by delegating sensitive card inputs to YooKassa's certified payment pages. The end-to-end lifecycle follows seven discrete operational phases:

  • The customer submits their order at checkout. Your backend persists a new order record in PostgreSQL with status "pending" containing the items and computed total.
  • Your backend issues an authenticated POST request to the YooKassa v3 payments endpoint with a unique Idempotence-Key header, receiving a payment id and a confirmation URL.
  • The application redirects the customer's browser to the YooKassa payment URL, where the user enters card details, approves 3-D Secure challenges, or selects alternative methods.
  • Once the transaction completes, YooKassa redirects the customer back to your application return_url, displaying a confirmation holding screen.
  • Concurrently, the payment gateway dispatches an asynchronous webhook notification containing payment details to your configured webhook endpoint.
  • Your webhook handler immediately returns an HTTP 200 OK status, enqueues a background job, and initiates an authoritative verification call against the YooKassa API.
  • Upon verifying the succeeded status, an atomic database transaction promotes the order status to "paid", triggering fulfillment and notification workflows.

Creating a payment: Idempotence-Key header and request parameters

Initiating a transaction requires sending an authenticated POST request to the YooKassa v3 payments endpoint using HTTP Basic Auth with your shop identifier and secret API key. The most critical reliability guarantee in this call is the Idempotence-Key HTTP header. This header accepts a unique ASCII string up to 64 characters long, typically formatted as a UUID v4. It ensures that repeated submissions caused by network blips or connection timeouts never produce duplicate charges.

When your backend encounters a socket timeout or a 5xx response while creating a payment, your background worker can safely replay the identical request using the original Idempotence-Key. YooKassa detects the existing key within its 24-hour cache and returns the original response payload without allocating another payment entity. For an in-depth analysis of retry strategies, exponential backoff, and idempotency keys, see our guide on API idempotency and retries.

The request body defines the payment amount, currency, confirmation redirect settings, and the capture mode flag. Setting capture to true executes a single-stage transaction where funds are immediately settled. Setting capture to false enables two-stage authorization, placing the payment into the waiting_for_capture status; the merchant holds the customer's funds and submits a subsequent capture request once stock availability is confirmed. Custom key-value pairs stored in the metadata object allow you to link your internal order id directly to the gateway payload.

Handling webhooks: why you must verify status via API queries

Once a customer completes payment authorization, YooKassa transmits an HTTP POST notification to your registered webhook URL. A widespread vulnerability in novice payment integrations is blindly trusting the JSON payload delivered in this incoming request. Because public webhook endpoints are accessible to anyone on the internet, malicious actors can send forged payloads with a fake payment.succeeded event to trick an unverified service into shipping goods for free.

While firewall rules can restrict incoming connections to official YooKassa IP subnet ranges, network-level filtering alone is insufficient defense against internal routing compromises or proxy spoofing. The industry standard architecture treats incoming webhooks strictly as wake-up hints rather than trusted truth. When the webhook arrives, your endpoint parses the structure, responds with an immediate HTTP 200 OK to prevent gateway redeliveries, and enqueues the payment identifier into an asynchronous processing queue.

A decoupled worker picks up the payment id and issues an authoritative, authenticated GET request to the YooKassa API over TLS. Your application accepts the payment as valid only when the response received directly from the gateway matches your internal records in order id, exact currency, and total amount. Detailed techniques for webhook authentication, replay prevention, and signature checks are explored in our article on webhook security and signatures.

Order state machine and preventing database race conditions

A robust billing integration maintains a clean distinction between external gateway states and internal business domain statuses. In YooKassa, a transaction progresses through states such as pending, waiting_for_capture, succeeded, or canceled. Internally, your order state machine might encompass states like draft, pending_payment, authorized, paid, processing, refunded, or failed. Crucially, your state machine must reject invalid transitions, such as moving from paid back to pending.

Race conditions frequently emerge when customers return to the application. When a user completes payment, their browser hits your return_url almost simultaneously with the gateway firing the webhook. If both request handlers attempt to update the database concurrently, uncoordinated writes can cause double fulfillment, duplicate notification emails, or corrupted audit logs. In PostgreSQL, this is mitigated using explicit row-level locks via SELECT ... FOR UPDATE or conditional atomic queries like UPDATE orders SET status = 'paid' WHERE id = $1 AND status = 'pending'.

If an incoming webhook or verification task encounters an order that has already transitioned into a final paid status, the worker gracefully exits without re-executing business side effects. This guarantees safety when processing duplicate webhook retries dispatched by the gateway. If you are designing subscription models or digital platforms, review our architectural comparison on SaaS billing build or buy, and explore messenger checkout patterns in our guide to Telegram bot payments.

Fiscal receipt compliance and processing refunds

When accepting consumer payments in regulated markets such as the Russian Federation under federal law 54-FZ, businesses must issue digital fiscal receipts for every transaction. YooKassa provides integrated cloud cash register connectivity as well as bridges to external certified fiscal hardware. When creating payments or capturing funds, your payload can include customer contact coordinates and itemized cart entries. The gateway then coordinates fiscalization with the designated cash register service. Exact tax classification codes, fiscal attributes, and calculation formats must always be verified against official gateway and fiscal operator documentation.

Processing refunds requires identical defensive engineering. Refunds can be executed in full or as partial settlements when customers return individual items from a multi-line order. Issuing a refund involves sending an authenticated POST request to the YooKassa refunds endpoint with an independent Idempotence-Key header, the original payment id, and the refund amount. Important architectural considerations include:

  • Full refunds processed through integrated cloud cash registers typically generate the return fiscal receipt automatically using original payment data.
  • Partial refunds require explicit item arrays inside the receipt object so the fiscal cash register accurately calculates returned tax amounts and residual balances.
  • Every refund request must generate its own distinct UUID for the Idempotence-Key header to ensure network retries never trigger repeated balance deductions.
  • Refund status transitions should be tracked via asynchronous webhook events or scheduled polling, acknowledging that interbank settlement can require several business days.
  • Refund entries in your local database must maintain foreign keys to the original order, transitioning the order status to refunded or partially_refunded only after gateway verification.

Sandbox testing: validating edge cases before production launch

Before accepting live customer credit cards, the payment pipeline must undergo comprehensive end-to-end verification inside YooKassa's sandbox test environment. The merchant dashboard provides a dedicated test shop identifier and sandbox secret key. The sandbox payment UI replicates production checkout forms while accepting specialized test payment credentials provided in developer documentation to validate diverse real-world outcomes.

Engineering verification must look beyond the standard happy path to stress-test error handling, timeout recovery, and edge-case behavior. A rigorous pre-launch testing checklist includes:

  • Executing a successful transaction through the full 3-D Secure challenge flow and confirming automated webhook delivery.
  • Testing payment declines using test cards configured for insufficient funds and expired credentials to verify clean UI error messages.
  • Simulating network failures during the initial payment creation call to confirm safe retries with identical Idempotence-Key headers.
  • Triggering deliberate webhook delivery delays to ensure your asynchronous verification queue and database locks prevent race conditions.
  • Replaying duplicate webhook payloads against your endpoint to verify that state machine guards prevent double fulfillment.
  • Executing both full and partial refund scenarios to validate balance reversals and fiscal data consistency.

Pre-built CMS modules vs custom API integration: making the right choice

For standard online stores built on mainstream platforms like WooCommerce, 1C-Bitrix, or Tilda, YooKassa maintains ready-made plugins. If your project follows a conventional shopping cart model with static catalog items and single-step checkout, an off-the-shelf module can be configured in a few hours without writing backend software. However, off-the-shelf plugins quickly become bottlenecks as architectural complexity grows.

A custom API integration developed on a modern backend stack like Go or Node.js becomes indispensable when your product requires tailored transaction workflows. This includes recurring subscription billing, dynamic escrow or split payments for multi-vendor marketplaces, mobile backend endpoints, and custom CRM or ERP synchronizations. Bespoke integrations deliver full observability, sub-millisecond execution, and custom audit trails. Our engineering team builds custom payment integrations engineered for mission-critical reliability and high transaction volume.

  • Turnkey CMS modules: best for traditional e-commerce catalogs, fixed-price retail, standard checkout forms, and rapid initial proof-of-concept testing.
  • Custom API integration: necessary for SaaS architectures, multi-tenant platforms, custom checkout logic, and two-stage authorization workflows.
  • Decoupled queues and microservices: essential when high transaction volume demands that payment gateway latency never degrades user-facing web performance.
Questions

FAQ

Didn't find an answer — ask on the call or in Telegram.

How does YooKassa integration work for web applications?

A YooKassa integration connects your web application to the gateway API using authenticated REST calls. Your backend initiates payments using a unique Idempotence-Key and directs the user to a secure checkout page. When payment completes, YooKassa dispatches an asynchronous webhook, and your server verifies transaction authenticity via a direct API query before updating the order to paid.

Why is the Idempotence-Key header essential in YooKassa API requests?

The Idempotence-Key header prevents accidental duplicate charges when network timeouts or connection drops occur. If a request is interrupted mid-flight, your backend can safely retry sending the exact same payload with the identical key. YooKassa recognizes the key from its internal cache and returns the existing transaction response without creating an additional charge for the customer.

How should webhooks from YooKassa be verified securely?

Never rely blindly on the payload delivered to your webhook endpoint. The secure practice is to immediately return an HTTP 200 OK status to acknowledge delivery, then enqueue an asynchronous verification task. The worker makes an authenticated GET request directly to the YooKassa API over TLS, confirming the payment id, exact amount, currency, and status before fulfilling the order.

How do refunds and fiscal receipt generation work in YooKassa?

Fiscal receipts are generated through YooKassa's integrated cloud cash register service or connected fiscal printers when payment details are submitted. Refunds are initiated through a dedicated API endpoint with an independent Idempotence-Key. Full or partial amounts can be refunded, and fiscal return data should always be cross-referenced with official documentation for current statutory compliance.

How do you test YooKassa payment flows before going to production?

Configure a sandbox test store in your YooKassa dashboard using dedicated test credentials. Use official test card numbers to simulate successful payments, 3-D Secure challenges, insufficient funds, and expired cards. Test edge cases including dropped connections during redirects, delayed webhook deliveries, duplicate notifications, and partial refund processing before swapping credentials to live production keys.

When do you need custom payment gateway integration instead of a CMS plugin?

A pre-built CMS module works well for standard e-commerce with simple shopping carts. A custom API integration is required when building SaaS platforms with recurring billing, mobile applications, multi-vendor marketplaces with split payments, custom ERP workflows, or Telegram bots that demand bespoke state machines, queue resilience, and granular transaction auditing.

Related service

CRM, ERP and API integrations built for your workflows

When teams copy data between systems by hand, delays and mistakes become part of the process. We automate the exchange and make its status visible to the people running it.

Learn about the service
Other articles
Contact

Shall we discuss your task?

Thirty minutes on a call — and you understand the architecture, timeline and engagement format. No obligations.

Or message us on Telegram →Follow our Telegram channel →

Enter your Telegram or email so we can reply.

We reply within 15 minutes.