Payment APIIntegrationMerchant Guide

How Payment APIs Work: A Technical Guide for Merchants

By PayEurasia Team · 4 August 2026 · 13 min read

Last updated 4 August 2026

Payment APIs explained: authentication, idempotency, payment lifecycle, webhooks, signatures, retries, reconciliation, sandbox testing and integration security.

A payment API is a contract about money. Unlike most integrations, a bug does not just produce a wrong screen — it produces a double charge, an uncredited order or an unreconciled balance. This guide explains how payment APIs work in practice and which behaviours determine whether your integration is safe.

It is written for merchants and engineering teams integrating a payment provider for the first time, or evaluating one before committing.

The building blocks

Authentication

Payment APIs authenticate server-to-server using API keys, HMAC-signed requests or OAuth client credentials. Three rules apply universally:

  • Secret keys live only on your server, never in browser or mobile code.
  • Keys are stored in a managed secret store, not in source control or environment files committed to a repository.
  • Keys are rotatable on a schedule and immediately on suspicion of exposure.

Providers that issue a single non-rotatable credential are telling you something about their security maturity.

Requests and responses

Most modern payment APIs are JSON over HTTPS with predictable resource semantics: create a payment, retrieve a payment, list payments, create a refund. Responses should carry a stable provider reference, a status, an amount and currency, timestamps and structured error information.

Error handling deserves specific attention. Distinguish between four classes: validation errors you should never retry, authentication errors that indicate configuration problems, transient errors that are safe to retry, and ambiguous errors — including timeouts — where you do not know whether the payment was created.

Idempotency

Idempotency is the single most important safety mechanism in a payment API. You send a unique key with each creation request; if the request is repeated with the same key, the provider returns the original result instead of creating a second payment.

Implement it properly:

  • Generate one key per logical payment attempt, not per HTTP call.
  • Store the key with your order before making the request.
  • Reuse the same key on every retry of that attempt, including after timeouts.
  • Never reuse a key across different amounts or orders.

Without idempotency, any network timeout can become a duplicate charge. With it, timeouts become harmless.

The payment lifecycle

A typical payment moves through defined states.

  1. Created — the provider has accepted your instruction and returned a reference.
  2. Pending or awaiting customer action — the customer must authenticate or approve, often in another app.
  3. Processing — the rail is executing the transfer.
  4. Succeeded — funds are confirmed, and this is the only state on which you should deliver value.
  5. Failed, cancelled or expired — terminal negative outcomes.
  6. Refunded or partially refunded — value returned to the customer.
  7. Disputed — the customer has challenged the transaction.

Two rules govern state handling. First, only terminal states drive business actions. Second, every non-terminal state needs a timeout and a resolution path, or it will eventually become an unreconciled record.

Webhooks: the backbone of reliable crediting

Why webhooks, not redirects

Customers close tabs, lose connectivity and switch apps mid-payment. If your system credits orders from a browser redirect, you will lose payments and generate support tickets. Webhooks are the authoritative channel.

Verifying signatures

Every webhook must be verified before it is trusted. Providers sign payloads with a shared secret, typically as an HMAC over the raw request body plus a timestamp. Verify against the raw body — parsing and re-serialising the JSON changes bytes and breaks signatures. Reject webhooks whose timestamp is outside a short tolerance window to prevent replay.

Idempotent handlers

Assume every webhook may arrive more than once, out of order, or late. Store processed event IDs and ignore duplicates. Make the handler's effect a state transition rather than an increment — "set order to paid" is safe to repeat, "add balance" is not.

Fast acknowledgement, async work

Return a 2xx quickly and do the heavy work asynchronously. Providers retry on non-2xx responses and on timeouts, and a slow handler creates a retry storm during exactly the moments you can least afford it.

Retries and dead letters

Providers retry failed deliveries with backoff for a limited window. Your side needs a dead-letter queue and an alert for events that never processed successfully, plus the ability to replay them.

Polling and reconciliation sweeps

Webhooks are the primary path; a status query is your safety net. Run a scheduled sweep that queries the provider for any payment not in a terminal state after your timeout window, and reconcile the result. This single job prevents the majority of stuck orders in real-world integrations.

Refunds, disputes and reversals

Refund APIs generally support full and partial amounts against an original payment. Handle these carefully:

  • Use idempotency keys on refunds too — duplicate refunds are real money lost.
  • Track refund state separately; refunds have their own lifecycle and can fail.
  • For cross-currency settlements, record the FX rate at both the original transaction and the refund, because the difference is a real cost.
  • Handle dispute webhooks by freezing related fulfilment and assembling evidence automatically where possible.

Reconciliation endpoints and settlement data

A production-grade provider offers a settlement report or reconciliation endpoint containing, per transaction: provider reference, your reference, gross amount, fees, taxes, net amount, settlement currency, FX rate and settlement batch identifier.

Your integration should ingest this daily and diff it against your ledger. If a provider cannot supply machine-readable reconciliation data, you will be doing manual month-end work forever.

The broader system design is covered in the merchant payment infrastructure guide.

Sandbox testing that actually prepares you

Most teams test only the happy path and are surprised in production. A useful test matrix covers:

  • Successful payment via each method you will offer
  • Customer cancellation and abandonment
  • Explicit decline and insufficient funds
  • Timeout during creation, then retry with the same idempotency key
  • Webhook delivered twice, and delivered out of order
  • Webhook delivered after your timeout sweep already resolved the payment
  • Full refund, partial refund and failed refund
  • Dispute notification handling
  • Rate limit response and backoff behaviour
  • Settlement report ingestion and deliberate mismatch handling

Ask providers whether their sandbox can simulate all of these. Many cannot, and that is useful information about how much you will be debugging in production.

Security practices for payment integrations

  • Enforce TLS and reject weak configurations.
  • Keep secrets in a managed store with rotation and audit logging.
  • Apply least privilege — separate keys for different environments and functions.
  • Restrict webhook endpoints to signature-verified traffic and log every received event.
  • Never log full sensitive payloads; redact and retain only what reconciliation and dispute evidence require.
  • Monitor for anomalous API usage patterns as a fraud and compromise signal.
  • Alert on authentication failures, which frequently indicate misconfiguration or key leakage.

Rate limits and performance

Providers impose rate limits per endpoint. Handle 429 responses with exponential backoff and jitter, never a tight retry loop. Before a peak sales or sporting event, confirm your limits in advance and request an increase — discovering the ceiling during peak is an avoidable outage.

Evaluating a provider's API before you sign

  1. Is idempotency supported on all creation endpoints?
  2. Are webhooks signed, timestamped and retried with backoff?
  3. Are terminal states clearly documented, and is there a status query endpoint?
  4. Is there machine-readable reconciliation and settlement data?
  5. Does the sandbox reproduce failures, timeouts and duplicates?
  6. Are errors structured and documented with retry guidance?
  7. Are rate limits documented and adjustable?
  8. Are there official SDKs or at least accurate, versioned API documentation?
  9. Is there a changelog and a deprecation policy?
  10. What are the support channels and response commitments for integration issues?

Providers that score well on these are cheaper to operate for years, which usually outweighs a small pricing difference.

Regional considerations in South Asia

Wallet and instant-rail integrations add specific behaviours: customer confirmation happens outside your page, pending states are common, and late confirmations occur. This makes webhook discipline, timeout policy and reconciliation sweeps more important here than in card-only markets. Method-specific behaviour is covered in the bKash merchant payment guide, UPI merchant payment guide, JazzCash merchant payment guide and eSewa merchant payment guide.

How PayEurasia's API is built

PayEurasia provides idempotent payment creation, signed webhooks with retries, explicit terminal states, status query endpoints and reconcilable settlement data across Bangladesh, India, Pakistan and Nepal — one integration for four markets.

See the API documentation or contact our team to discuss your integration.

Frequently asked questions

What is a payment API?

A payment API is a server-to-server interface that lets a merchant create payments, check their status, issue refunds and receive event notifications from a payment provider, returning structured data your systems use to credit orders and reconcile money.

What is idempotency and why does it matter in payments?

Idempotency means a repeated request with the same key returns the original result instead of creating a second payment. It is what makes network timeouts and retries safe, and without it any timeout can become a duplicate charge.

Should I use webhooks or polling to confirm payments?

Use webhooks as the authoritative crediting mechanism because customers frequently abandon the browser flow, and use scheduled status polling only as a reconciliation safety net for payments that remain non-terminal past your timeout window.

How do I verify a webhook is genuine?

Compute an HMAC over the raw request body and timestamp using your shared secret and compare it to the provider's signature header with a constant-time comparison, rejecting events whose timestamp falls outside a short tolerance window to prevent replay.

What should I test in a payment sandbox before going live?

Test successes and declines per method, cancellations, creation timeouts followed by idempotent retry, duplicate and out-of-order webhooks, late confirmations, full and partial refunds, failed refunds, dispute notifications, rate limiting and settlement report reconciliation including deliberate mismatches.

How do I keep payment API keys secure?

Store secrets server-side in a managed secret store with rotation and audit logging, use separate keys per environment and function, never expose keys in client code or version control, and alert on authentication failures and anomalous usage patterns.

Talk to PayEurasia

Working in a high-risk vertical across South Asia? We can probably help.

Request integration →

Related solutions

Related articles

Powering High-Risk Merchants With Local Payment Infrastructure Across South AsiaHow local payment infrastructure — bKash, Nagad, UPI, IMPS, JazzCash, Easypaisa, eSewa and Khalti — lets high-risk merchants collect, settle and scale across Bangladesh, India, Pakistan and Nepal.Payment Gateway Fees in Pakistan: Every Charge ExplainedEvery payment gateway fee type in Pakistan explained: transaction and fixed fees, payout and conversion charges, refund and dispute costs, tax treatment, benchmarking and contract clauses.Best Payment Gateway for Small Business in India (2026)A practical guide for small and mid-sized merchants in India: what to prioritise, a minimum viable payment setup, realistic costs, onboarding preparation and when to add complexity.Payment Gateway Charges in Bangladesh: Complete 2026 Cost GuideA complete breakdown of payment gateway charges in Bangladesh — method costs, fixed fees, payout and conversion charges, failure cost, and how to calculate and negotiate your blended effective rate.Payment Gateway Charges in Pakistan: Complete 2026 Cost GuideA complete breakdown of payment gateway charges in Pakistan — method costs, fixed fees, payout and conversion charges, failure cost, and how to calculate and negotiate your blended effective rate.Payment Gateway Fees in Nepal: Every Charge ExplainedEvery payment gateway fee type in Nepal explained: transaction and fixed fees, payout and conversion charges, refund and dispute costs, tax treatment, benchmarking and contract clauses.
View all articles →