Building a real integration

Design a payments module, initiate payments correctly, handle and verify webhooks, map errors, process refunds and reconcile every shilling, naira or euro.

Level
Intermediate
Modules
6
Lessons
14
Price
Free

What you will learn

  • Structure a payments module with a clear status model and provider adapter
  • Initiate synchronous and asynchronous (redirect, STK push) payments safely
  • Verify webhook signatures and process events idempotently
  • Classify provider errors and apply safe retry rules
  • Implement refunds and dispute handling
  • Run a daily reconciliation between your ledger, provider reports and bank statements

Module 1: Designing the integration

A clean payments module and the hosted-vs-direct decision.

A payments module that survives change

Keep provider details behind one internal module. A minimal shape:
- A Payment record with your own id, order reference, amount in minor units, currency, method, provider, provider reference and a status (pending → processing → succeeded | failed | canceled, later refunded / disputed).
- A provider adapter exposing createPayment, getStatus, refund, parseWebhook.
- An append-only event log of every provider message you receive.

Status transitions should be explicit and one-directional: a succeeded payment never goes back to pending because a late webhook arrived. Store provider ids with a unique index so duplicates are impossible.

Hosted checkout vs direct API

Hosted checkout (redirect or provider iframe) is fastest to build, handles 3DS/SCA and local methods, and keeps you in PCI SAQ A scope. Direct API integrations give full UX control but add work: 3DS handling, more error cases and, if card data touches your pages, SAQ A-EP or SAQ D.

Mobile money is usually direct by nature (you call STK Push from your server), but it carries no card data, so PCI does not apply to it — operator security requirements do.

Start hosted; move to embedded components when you have a measured reason.

Exercise: Status machine

Write the status enum and an `applyTransition(payment, event)` function for your payments module. It must reject invalid transitions and be safe to call twice with the same event.

Module 2: Initiating payments

Create payments safely, including asynchronous methods.

Creating a payment the right way

Before calling the provider, persist a pending payment with your own id. Then call the provider with:
- The amount computed server-side from the order, in minor units.
- Your reference (order or payment id) so the provider echoes it back.
- An idempotency key derived from your payment id, so retries do not double-charge.
- Callback/return URLs from configuration.

Save the provider's reference on your record as soon as you get it. If the call times out, you do not know the outcome — retry with the same idempotency key or query status; never create a fresh payment blindly.

Asynchronous methods: STK Push, request-to-pay and redirects

With STK Push (M-Pesa Express) or MTN MoMo *request to pay*, the API call only means 'request accepted'. The customer still has to enter their PIN, and the result arrives later on your callback URL.

Design for this:
- Show a 'Check your phone' screen and poll your own backend, not the provider.
- Expire the attempt after a sensible timeout and let the customer retry.
- If no callback arrives, call the provider's status query before deciding.
- Rate-limit STK requests per phone number to prevent prompt spam.

Redirect flows have the same rule: a customer landing on your return_url is not proof of payment. Confirm via webhook or status API.

Recurring payments, SCA and dunning

Recurring billing starts with a customer-initiated payment that saves a reusable credential with consent: a card token, a direct-debit mandate, or a UPI/Pix recurring authorisation where the rail supports it. Later charges are merchant-initiated transactions (MITs) and must be flagged as such.

In the EEA and UK, the first payment needs Strong Customer Authentication (usually 3-D Secure). Correctly flagged MITs are normally out of SCA scope, but an issuer can still ask for authentication, so build a 'please confirm your payment' email flow.

When renewals fail, dunning takes over: retry soft declines on a schedule, never hammer hard declines, prompt the customer to update their method, and use network tokens/account updaters to cut failures from expired cards. Mobile money rarely supports pull-recurring, so re-prompt the customer each cycle and give a grace period.

Exercise: STK Push flow

Implement (in sandbox) an endpoint that starts an M-Pesa STK Push or MTN MoMo request-to-pay, stores the attempt, and a status endpoint the frontend polls. Include a 2-minute expiry.

Module 3: Webhooks and verification

Receive, verify and process provider events reliably.

Receiving webhooks

Webhooks are delivered at least once, possibly out of order, and retried when you don't respond with 2xx. A robust handler:
- Reads the raw body (needed for signature checks).
- Verifies authenticity, then stores the event with a unique event id.
- Responds 200 quickly and processes asynchronously (queue/worker).
- Applies status transitions idempotently.

Log every event, including ones you ignore — they are your audit trail when reconciling.

Verifying and trusting events

Most card PSPs sign webhooks with an HMAC of the raw body. Recompute it with your secret and compare using a constant-time function. Check timestamps where provided to block replays.

Some APIs (notably several mobile-money callbacks) do not sign payloads. Then layer defences:
- A hard-to-guess secret token in the callback path.
- Allowlist the provider's published IP ranges if they publish them.
- Always re-query the transaction status server-to-server before fulfilling.
- Check amount, currency and reference match what you expected.

Never trust amounts from the callback alone — compare against your stored payment.

Status checks as a safety net

Webhooks fail: your server was down, a firewall blocked them, or the provider had an incident. Run a sweeper job that finds payments stuck in pending/processing longer than expected and queries the provider's status endpoint.

Combine both: webhooks for speed, status queries for completeness. Pesapal's API 3.0, for example, expects you to call GetTransactionStatus after receiving an IPN notification.

Exercise: Hardened webhook endpoint

Build a webhook endpoint for one provider that verifies the signature (or re-queries status if unsigned), deduplicates by event id, and updates the payment via your status machine. Replay the same payload three times and prove the order is updated once.

Module 4: Errors, timeouts and retries

Classify failures and retry only what is safe.

Classifying errors

Sort every provider error into one of four buckets and handle each differently:
- Validation (400) — your bug or bad input. Do not retry; fix and show a clear message.
- Authentication/permission (401/403) — expired token or wrong keys. Refresh token once, then alert.
- Declines — the issuer or customer said no (insufficient funds, wrong PIN, cancelled prompt). Show a friendly message; let the customer try another method.
- Transient (429, 5xx, network timeouts) — retry with exponential backoff and jitter, using the same idempotency key.

Map provider-specific codes to your own small set so the UI and analytics stay provider-agnostic.

The unknown outcome

The most dangerous case is a timeout after the provider received your request. The payment may or may not exist. Never treat a timeout as a failure:
- Mark the payment unknown/processing.
- Retry with the same idempotency key (if supported) or query by your reference.
- Only show 'failed' after the provider confirms it.

For card authorizations some gateways automatically send a reversal after a timeout, so the customer isn't left with a hold for a payment you don't know about.

Exercise: Error map

For one provider, collect at least ten error/decline codes from its docs and map them to your four buckets with a user-facing message and a retry rule.

Module 5: Refunds and disputes

Give money back correctly and defend against chargebacks.

Refunds, voids and partial refunds

Choose the cheapest correct operation: void if not yet captured, otherwise refund. Model refunds as their own records linked to the payment, because one payment can have several partial refunds and each is asynchronous.

Guard rails:
- Sum of refunds ≤ captured amount.
- Use idempotency keys per refund request.
- Require staff permission and audit who refunded.

Mobile money: some providers offer a refund/reversal API; others require a B2C disbursement back to the customer, which needs a funded payout account (float) and its own reconciliation.

Handling disputes

Subscribe to dispute webhooks. When one opens:
- Freeze related fulfilment or account access if appropriate.
- Gather evidence automatically: order details, delivery proof, IP/device, customer communications, 3DS results.
- Respond before the deadline in the provider's dashboard or API.

Prevention beats defence: clear billing descriptors, easy refunds, 3DS where it shifts liability, and fraud scoring on risky orders.

Exercise: Refund service

Implement `refund(paymentId, amount, reason, staffUserId)` with partial refund support, idempotency, permission check and an audit entry. Update the payment status when the provider confirms.

Module 6: Reconciliation and ledgers

Prove that every payment in your system matches real money.

Daily reconciliation

Reconcile three sources every day:
- Your records (orders, payments, refunds).
- Provider reports (transactions, fees, payouts/settlements).
- Bank statements (actual deposits).

Match by provider reference and your reference, then by amount and date. Typical exceptions: paid in provider but pending in your DB (missed webhook), paid in your DB but missing at provider (bug or fraud), unexplained fee or FX differences, chargebacks netted from payouts.

Each exception should become a ticket with an owner — not a spreadsheet nobody reads.

Ledgers and money in minor units

Store money as integers in minor units with an explicit currency ({ amount: 150000, currency: "KES" }). Some currencies have zero or three decimal places, so look up the exponent rather than assuming 2.

A simple double-entry ledger (every movement is a debit and an equal credit) makes balances auditable: customer payment, provider fee, payout, refund and chargeback each become entries. You can always recompute a balance from entries — and you should never edit them; post a correcting entry instead.

Exercise: Reconcile a day

Export one day of sandbox transactions from a provider (or generate a CSV of 20 sample rows) and write a script that matches them to your payments table, listing matched, missing-in-DB, missing-at-provider and amount mismatches.

Other learning paths

Payments glossary · Integration guides