
Choosing a payment gateway is usually treated as a commercial decision about fees. The integration pattern you choose matters just as much: it determines your PCI DSS burden, your fraud exposure, how your checkout behaves on a slow mobile connection, and how much of your finance team's week disappears into reconciliation. This guide explains the three main integration flows, the security mechanisms that sit underneath them, and a practical way to choose and implement a gateway for a business operating in Kenya and East Africa.
Key takeaways
- There are three broad integration patterns: redirect (hosted payment page), embedded (hosted fields or drop-in components) and direct API. Each step towards direct API increases control and compliance scope.
- Tokenisation and hosted fields keep raw card data off your servers, which keeps your PCI DSS scope small.
- 3-D Secure shifts fraud liability for authenticated card payments but adds friction; design for it rather than fight it.
- Webhooks, not browser redirects, are the source of truth for payment status. Verify their signatures and process them idempotently.
- Reconciliation is part of the integration, not an afterthought. Store gateway references and match settlements daily.
- In East Africa, a good gateway strategy usually combines cards with mobile money; check which methods and currencies each provider supports today.
What a payment gateway actually does
A gateway sits between your application and the financial networks. For a card payment, the simplified chain is:
Customer browser/app
-> Your checkout
-> Payment gateway (tokenises, routes, applies fraud rules)
-> Acquirer / processor (your merchant bank or its processor)
-> Card network (Visa, Mastercard, etc.)
-> Issuer (customer's bank: approves or declines)
For mobile money, the gateway (or aggregator) instead calls the wallet provider's API, which prompts the customer to approve on their phone. Many gateways operating in Kenya offer both, so a single integration can present card, M-Pesa and sometimes Airtel Money or bank options. Provider line-ups change; at the time of writing, businesses in the region commonly evaluate options such as Pesapal, Flutterwave, Paystack, DPO Pay, Cellulant's Tingg, iPay and bank-provided card acquiring. Verify each provider's current licensing, supported methods, settlement currency and fees directly before committing.
Key terms you will see:
- Authorisation: the issuer approves and reserves funds.
- Capture: you claim the authorised funds. Some flows authorise and capture together; others let you capture later, which suits bookings and pre-orders.
- Void / refund: cancelling before settlement versus returning funds after settlement.
- Settlement: the gateway or acquirer pays you, net of fees, on a schedule.
- Chargeback: the cardholder disputes a payment through their bank.
QR and mobile money payments are everyday checkout options in East Africa.
The three integration patterns
1. Redirect (hosted payment page)
Your site sends the customer to a page hosted by the gateway. They pay there and return to your "success" or "failure" URL. The gateway then notifies your server via webhook.
- Pros: fastest to implement, smallest PCI DSS scope, the gateway handles 3-D Secure and mobile money prompts.
- Cons: less control over look and feel, a visible domain change that can unsettle customers, and return URLs that are easily lost on unreliable mobile data.
2. Embedded (hosted fields, iframes, drop-in components)
The payment form appears inside your page, but the sensitive inputs are iframes or components served by the gateway. Your JavaScript receives a token, not the card number, and your server uses that token to create the charge.
- Pros: seamless branding, card data still never touches your servers, flexible flows.
- Cons: more front-end work, a dependency on the gateway's script loading correctly, and a somewhat larger compliance footprint than a full redirect because your page hosts the payment experience.
3. Direct API (server-to-server)
Your application collects payment details and sends them to the gateway's API. For cards, this means card data passes through your systems.
- Pros: total control, suitable for platforms, marketplaces and payment facilitators.
- Cons: the heaviest PCI DSS obligations, the need for hardened infrastructure and audits, and full responsibility for 3-D Secure orchestration.
For mobile money, "direct API" is far more common and less burdensome because you never handle card data: you send a phone number and amount, and the customer approves on their handset. Integrating directly with Safaricom's Daraja API is exactly this pattern; see how to integrate M-Pesa payments into a web application.
Pattern comparison
| Criterion | Redirect / hosted page | Embedded / hosted fields | Direct API (cards) |
|---|---|---|---|
| Time to integrate | Days | One to a few weeks | Weeks to months |
| Card data touches your servers | No | No (tokens only) | Yes |
| Typical PCI DSS self-assessment | Simplest (SAQ A type) | Small (SAQ A or A-EP type, depends on implementation) | Largest (SAQ D or full assessment) |
| Checkout branding control | Low to medium | High | Full |
| 3-D Secure handling | Gateway | Mostly gateway SDK | You orchestrate |
| Best for | SMEs, quick launches | Growing e-commerce, SaaS | Platforms, PSPs, large merchants |
Your exact Self-Assessment Questionnaire depends on implementation details and your acquirer's requirements; confirm with them. Standards and guidance are published by the PCI Security Standards Council.
Security mechanisms you must understand
Tokenisation
A token is a surrogate value that represents a card or payment method stored securely in the gateway's vault. You store the token and use it for refunds, recurring billing or one-click checkout. If your database leaks, tokens are useless outside your merchant account. Always prefer gateway tokens over storing anything card-related yourself. Never store the card verification code under any circumstances.
PCI DSS scope
PCI DSS applies to any system that stores, processes or transmits cardholder data, and to systems connected to them. The simplest way to reduce cost and risk is to shrink scope: redirect or hosted fields, no card data in logs, no card data in support tickets or WhatsApp messages, and a segmented network so that your checkout servers are not on the same flat network as staff laptops.
3-D Secure
3-D Secure (the current generation is EMV 3-D Secure, often called 3DS2) asks the issuer to authenticate the cardholder, sometimes silently using device and risk data, sometimes with a one-time password or banking app approval. For you, a successfully authenticated transaction generally shifts fraud chargeback liability to the issuer. In practice:
- Expect a redirect or modal challenge in the flow, and test it on low-end Android devices over mobile data.
- Handle the "authentication abandoned" outcome distinctly from "declined".
- Do not try to bypass it to "reduce friction"; you will usually absorb the fraud instead.
Webhooks
The browser returning to your success page proves nothing: the customer may close the tab, lose signal, or tamper with the URL. The gateway's webhook (server-to-server notification) is the authoritative event. A sound webhook handler:
- Accepts only HTTPS and verifies the signature or shared secret per the gateway's documentation.
- Stores the raw payload before doing anything else.
- Looks up the transaction by your reference and the gateway's reference.
- Applies state changes idempotently (processing the same event twice has no extra effect).
- Returns a 2xx response quickly and hands slow work to a background queue.
- Re-queries the gateway's API for status if the payload is ambiguous.
Here is an idempotent webhook handler skeleton in TypeScript using Express. The signature scheme shown is a generic HMAC-SHA256 over the raw body; adapt it to your gateway's documented method.
import express from "express";
import crypto from "node:crypto";
const app = express();
const WEBHOOK_SECRET = process.env.GATEWAY_WEBHOOK_SECRET ?? "";
// Keep the raw body: signatures are computed over exact bytes.
app.post(
"/webhooks/gateway",
express.raw({ type: "application/json" }),
async (req, res) => {
const signature = req.header("x-signature") ?? "";
const expected = crypto
.createHmac("sha256", WEBHOOK_SECRET)
.update(req.body as Buffer)
.digest("hex");
const valid =
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
if (!valid) return res.status(401).end();
const event = JSON.parse((req.body as Buffer).toString("utf8"));
// Unique constraint on event_id makes this insert the idempotency guard.
const isNew = await saveRawEventIfNew(event.id, event);
if (isNew) await enqueue("payment-event", { eventId: event.id });
return res.status(200).json({ received: true });
}
);
// Placeholders for your persistence and queue layers.
async function saveRawEventIfNew(id: string, payload: unknown): Promise<boolean> {
// INSERT ... ON CONFLICT (event_id) DO NOTHING; return rowCount === 1
return true;
}
async function enqueue(topic: string, message: object): Promise<void> {}
app.listen(3000);
Reconciliation: where integrations succeed or fail
Every payment exists in at least three places: your order system, the gateway's records and your bank statement. Reconciliation confirms they agree.
A practical daily process:
- Store references at creation: your order ID, the gateway's transaction or charge ID, and for mobile money the provider receipt number when it arrives.
- Ingest the gateway's settlement report via API or scheduled export.
- Match each settled line to an order using the gateway reference. Flag gateway lines with no order (orphan payments) and orders marked paid with no settlement line.
- Account for fees, refunds and chargebacks so that the net settlement equals the bank credit.
- Match the bank credit to the settlement batch.
- Route exceptions to a named person with a deadline, and track ageing.
Multi-currency adds complexity. If you sell in USD but settle in KES, record the exchange rate applied by the gateway per transaction or batch, otherwise your margins will be wrong and unexplained differences will accumulate.
Payments only feel simple when the integration and reconciliation behind them are solid.
Choosing a gateway: decision checklist
- Supports the methods your customers use: cards, M-Pesa, Airtel Money, bank transfer, and for regional sales MTN MoMo or Tanzanian wallets.
- Licensed or authorised appropriately in the markets you serve (in Kenya, check Central Bank of Kenya authorisation status).
- Settlement currency, frequency and bank options suit your cash flow.
- Clear fee schedule: percentage, fixed fees, currency conversion margins, chargeback fees. Check current pricing; it changes.
- Integration options that fit your team: hosted page, hosted fields, SDKs for your stack, plugins for your e-commerce platform.
- Sandbox environment with realistic test cases, including 3-D Secure challenges and mobile money timeouts.
- Signed webhooks, retry policies and an event log in the dashboard.
- Settlement and transaction reports accessible by API.
- Refunds and partial refunds by API.
- Data handling terms compatible with the Kenya Data Protection Act 2019, including where data is stored and processed.
- Responsive local support during business hours, with an escalation path for outages.
East African implementation realities
- Mobile-first, bandwidth-constrained users. Keep checkout pages light, avoid heavy third-party scripts, and make every step resumable. Many customers will pay on mid-range Android phones over 3G or 4G.
- Mixed payment preferences. In Kenya, many consumers prefer M-Pesa even when they hold cards. Present mobile money prominently and do not hide it behind a "more options" link.
- Card decline rates on international payments. Some locally issued cards are restricted for online or foreign-currency transactions by default. Surface clear guidance when a decline code suggests the card is not enabled for online use.
- Latency to processors. Some gateways process in Europe or South Africa. Expect higher API latency than local services and set timeouts accordingly; never block a request thread waiting indefinitely.
- Data protection. Payment records include personal data. Limit who can export transaction lists, and avoid copying them into spreadsheets shared by email.
Common mistakes
- Marking orders paid on the browser redirect. Always wait for the verified webhook or an API status check.
- Not verifying webhook signatures. An unauthenticated webhook endpoint is an open "mark as paid" button.
- Logging full request payloads in production that contain card data or secrets.
- No idempotency on order creation. A double-click or retry creates two charges. Use idempotency keys where the gateway supports them.
- Treating refunds as a manual process outside the system, which breaks reconciliation.
- Single gateway with no fallback for a business where checkout downtime is expensive. A second provider for at least one method reduces risk.
- Skipping the settlement report. Your order system says paid; your bank says otherwise; nobody notices for a month.
FAQ
Which integration pattern should an SME start with?
A hosted payment page or embedded hosted fields. Both keep card data off your servers, minimise PCI DSS effort and let you launch quickly. Move to more control only when there is a specific business reason.
Do I need PCI DSS compliance if I only use a hosted page?
Yes, but the obligation is much lighter. You typically complete a short self-assessment and maintain basic security controls. Your acquirer or gateway will tell you which questionnaire applies.
Can one gateway handle both cards and M-Pesa?
Many regional gateways offer both through a single integration. Compare that convenience with integrating M-Pesa directly via Daraja, which avoids the intermediary's fee on mobile money but requires more engineering.
Why do customers get charged but my system shows the order unpaid?
Usually a missed or failed webhook. Check your endpoint logs, the gateway's webhook delivery log, and implement a scheduled status query for pending transactions older than a few minutes.
What is the difference between a void and a refund?
A void cancels an authorisation before it settles, so no money moves. A refund returns money after settlement and may take several days to reach the customer.
How TechBytes can help
TechBytes EA integrates card and mobile money gateways into web and mobile applications, with signed webhook handling, idempotent order flows and automated settlement reconciliation. We also review existing checkouts for PCI DSS scope reduction and security gaps. Speak to our software development team about a new integration, or ask our cybersecurity specialists to assess the one you have.

