Choosing an online payment gateway leaves you with another decision: how should it fit into your checkout? You need to weigh the build effort, the shopper’s experience and the security work your team will own.
There are three routes: redirect shoppers to a hosted payment page, embed the provider’s payment form, or collect card details yourself and send them through a direct API. Each gives you a different level of control and responsibility.
This guide is for developers choosing an integration for UK checkouts that take cards and Pay by Bank.
Compare Your Online Payment Gateway Options
Start by checking a gateway’s SDKs, plugins and REST API against your checkout requirements. Having an API doesn’t necessarily mean a provider accepts raw card details from your server.
For cards, PCI DSS means the Payment Card Industry Data Security Standard: rules for protecting card data. A Self-Assessment Questionnaire, or SAQ, records how your business meets the applicable requirements.
Strong customer authentication, or SCA, checks that the person making a payment is authorised to do so. For online cards, 3-D Secure is the authentication technology that can run a challenge, such as a passcode or biometric check.
| Route | Card security scope | Authentication | Checkout control | Build effort |
|---|---|---|---|---|
| Hosted redirect | May qualify for SAQ A when eligibility conditions are met | Provider handles the payment-page flow | Your checkout leads into a separate page | Lowest of these routes |
| Embedded form | May qualify for SAQ A, with additional attention to scripts on your page | Provider’s form or SDK handles the flow | Payment stays within your page | SDK integration and page security work |
| Direct card API | Card data enters your systems; plan for SAQ D | Your integration must arrange 3-D Secure | Greatest control over the form | Greatest security and implementation responsibility |
Redirect: Keep the Payment Page Outside Your Application
Your server creates a payment request, then sends the shopper to the returned paymentUrl. The provider collects the payment details, and the shopper returns to your redirectUrl.
Choose this route when you want less payment-interface code to maintain. Test the outward journey, authentication and return journey together, including cancellation and an expired request.
Embedded: Keep the Dialog Inside Your Page
The documented web SDK opens a payment dialog inside your page. Your backend creates the request first; the browser receives only its paymentRequestId. Your domain must be whitelisted in the provider’s dashboard.
Embedding also creates work around your surrounding page. The SAQ A script-attack criterion applies to pages embedding a provider’s payment form, while redirect-only arrangements are outside that particular criterion. Review the scripts running beside your payment form before choosing this route. (PCI Security Standards Council, 2025)
Direct API: Check What “Direct” Actually Includes
A direct card integration means your form collects card details and your server sends them to the gateway. That brings card data into your systems and makes authentication part of your integration work.
The provider discussed here does not document an endpoint accepting raw card numbers from your server. Its payment-creation API supports hosted and embedded journeys; don’t build a card form around an endpoint that isn’t documented.
Pay by Bank has no card data: the shopper approves the payment in their bank’s app. The card-specific PCI rows above therefore don’t describe that payment method.
Create the Request and Prepare Confirmation
All routes need a trusted server-side outcome. Start by registering a webhook endpoint, so payment confirmation is ready before shoppers reach checkout.
A webhook is a message the provider sends to your server about a payment. It lets your backend receive updates independently of the shopper’s browser.
Use POST /api/webhook/v2/endpoints with an HTTPS url and events: ["PAYMENTS_STATUS"]. The URL cannot be changed later, so choose an address you can maintain.
Then build the payment-creation flow:
- Save the pending order before calling the payment API. Store your
orderIdand leave space for the returnedpaymentRequestId. - Call
POST /api/payments/process-paymentfrom your server with bearer authentication. - Send
customerId, your own customer reference;orderId; andamount, expressed as a number in pounds. - Set
paymentMethodto["CARD"],["PAY_BY_BANK"]or both. Supply yourredirectUrland an appropriateexpiresIn, measured in milliseconds. - Save the returned
paymentRequestId. Handle an immediateFAILEDreply because no webhook follows that outcome.
The API reference doesn't document an idempotency header. Before retrying creation, look up the existing payment for that orderId; a lost response doesn’t establish that creation failed.
For redirects, send the shopper to paymentUrl. On return, display “Checking your payment” until your server confirms completion.
The returned URLs never expire, but the payment request expires according to expiresIn. Check the request’s status before reusing a stored link; a page that still opens doesn’t establish that the request remains payable.
For embedded checkout, pass paymentRequestId to your provider’s web SDK and launch showPaymentDialog(). Treat onPaymentStatusChange, cancellation and close callbacks as interface signals. They must not authorise fulfilment.
Confirm Payment on the Server
The following Node 18+ service uses Express and better-sqlite3. Install those dependencies and configure the environment variables before starting it.
The checkout backend must use the same orders database: insert the pending order before creation, then attach the returned request ID. Keep fulfilment behind the stored COMPLETED status.
This example saves verified webhook bodies before acknowledging them. It then checks outstanding requests through the documented status endpoint, avoiding assumptions about the webhook’s JSON envelope.
const express = require("express");
const Database = require("better-sqlite3");
const crypto = require("node:crypto");
const { setTimeout: sleep } = require("node:timers/promises");
const app = express();
const db = new Database("payments.sqlite");
db.pragma("journal_mode = WAL");
db.pragma("synchronous = FULL");
db.exec(`
CREATE TABLE IF NOT EXISTS orders (
orderId TEXT PRIMARY KEY,
paymentRequestId TEXT UNIQUE,
status TEXT NOT NULL DEFAULT 'PENDING'
);
CREATE TABLE IF NOT EXISTS inbox (
id INTEGER PRIMARY KEY,
body BLOB NOT NULL
);
CREATE TABLE IF NOT EXISTS seen (
paymentRequestId TEXT,
status TEXT,
PRIMARY KEY (paymentRequestId, status)
);
`);
const base = process.env.PAYMENTS_API_BASE;
const apiKey = process.env.PAYMENTS_API_KEY;
const signatureHeader = process.env.PAYMENTS_SIGNATURE_HEADER;
const secret = process.env.PAYMENTS_WEBHOOK_SECRET || "";
if (!secret.startsWith("whsec_")) {
throw new Error("Configure a V2 signing secret");
}
if (!base || !apiKey || !signatureHeader) {
throw new Error("Missing payment configuration");
}
const key = Buffer.from(secret.slice(6), "base64");
const rank = { PENDING: 0, FAILED: 1, COMPLETED: 2 };
const applyStatus = db.transaction((id, status) => {
if (!Object.hasOwn(rank, status)) return;
const order = db.prepare(
"SELECT status FROM orders WHERE paymentRequestId = ?"
).get(id);
if (!order) return;
const inserted = db.prepare(
"INSERT OR IGNORE INTO seen VALUES (?, ?)"
).run(id, status);
if (!inserted.changes) return;
if (rank[status] <= rank[order.status]) return;
db.prepare(
"UPDATE orders SET status = ? WHERE paymentRequestId = ?"
).run(status, id);
});
let running = false;
async function sweep() {
if (running) return;
running = true;
try {
const orders = db.prepare(
"SELECT paymentRequestId FROM orders " +
"WHERE paymentRequestId IS NOT NULL " +
"AND status != 'COMPLETED'"
).all();
for (const order of orders) {
try {
const id = order.paymentRequestId;
const response = await fetch(
base + "/api/payments/v1/payment-status/" +
encodeURIComponent(id),
{
headers: { Authorization: "Bearer " + apiKey },
signal: AbortSignal.timeout(10000)
}
);
if (!response.ok) throw new Error("Status check failed");
const result = await response.json();
applyStatus(id, result.status);
} catch (error) {
console.error(error.message);
}
}
} finally {
running = false;
}
}
app.post(
"/webhooks/payments",
express.raw({ type: "application/json" }),
(req, res) => {
const signature = req.get(signatureHeader) || "";
if (!/^v1=[0-9a-f]{64}$/i.test(signature)) {
return res.sendStatus(401);
}
const received = Buffer.from(signature.slice(3), "hex");
const expected = crypto.createHmac("sha256", key)
.update(req.body).digest();
if (!crypto.timingSafeEqual(received, expected)) {
return res.sendStatus(401);
}
db.prepare("INSERT INTO inbox (body) VALUES (?)")
.run(req.body);
res.sendStatus(204);
setImmediate(() => sweep().catch(console.error));
}
);
async function poll() {
let delay = Number(process.env.POLL_INITIAL_MS);
const maximum = Number(process.env.POLL_MAX_MS);
if (!(delay > 0) || !(maximum >= delay)) {
throw new Error("Configure polling back-off");
}
for (;;) {
await sweep().catch(console.error);
await sleep(delay);
delay = Math.min(delay * 2, maximum);
}
}
app.listen(process.env.PORT || 3000);
poll().catch(console.error);
Set PAYMENTS_SIGNATURE_HEADER to the provider’s documented header name. Create the signing secret in the dashboard first: the V2 header is only sent after that step.
V2 verification uses HMAC-SHA256 over the raw body. The code strips whsec_, base64-decodes the secret and compares signatures with a timing-safe operation. Don’t put a JSON parser ahead of this route.
The inbox write happens before the successful response. Unused events also receive success after saving; processing errors should request a retry only when another delivery could help.
Payment webhooks have no event ID or webhook ID. The seen table instead deduplicates on paymentRequestId plus status, and the rank prevents a completed payment moving backwards.
Polling provides a backstop because webhook retries are limited. Configure its back-off for your application, monitor failures and use a separate fulfilment record to prevent duplicate dispatches. This example subscribes to payment-status events; add explicit expiry handling if you also subscribe to EXPIRED_STATUS.
Mistakes to Avoid
Don’t trust the return journey. A browser reaching your confirmation page proves only that it reached that page.
Keep the API key server-side. Embedded checkout needs a request ID, not your bearer token.
Test authentication challenges. Low-risk card payments may be frictionless; higher-risk payments can require a challenge. Test both journeys before selecting the integration. (EMVCo, 2026)
Review embedded-page scripts. A provider-owned form doesn’t remove the work around the page containing it.
Check before retrying creation. Don’t send an undocumented idempotency header or assume a timeout means no payment request exists.
Checklist
- Choose a route the provider documents.
- Confirm the applicable card-security assessment.
- Keep API credentials on the server.
- Save the order before payment creation.
- Handle an immediate
FAILEDresponse. - Verify signatures against the raw body.
- Acknowledge saved and unused events.
- Deduplicate by request ID and status.
- Keep completion final and fulfilment repeat-safe.
- Poll with back-off when confirmation is missing.
Conclusion
Choose redirect or embedded checkout according to the interface control and security work your team can maintain. Start by testing one complete journey, including authentication, cancellation and server-confirmed payment, before connecting fulfilment.
Top comments (0)