Third-party integration: choosing a provider, sync versus async, webhooks and an anti-corruption layer
A common playbook for integrating payment gateways, SMS, eKYC or shipping providers: the order to evaluate requirements in, provider selection criteria, picking an integration style, receiving webhooks safely, hiding the provider behind your own interface, logging and testing.
On this page
Every third-party integration (payment gateway, SMS OTP, eKYC, shipping) is a dependency you don't control: slow, cryptic errors, duplicate webhooks, API changes. This post extracts the general playbook. The concrete VNPay QR example lives in the payment gateway post and the late IPNs and reconciliation post; timeouts, retries, circuit breakers and bulkheads are in part 2.
1. The problem
A webhook controller takes @RequestBody WebhookEvent and computes the HMAC over re-serialized JSON. The signature is "sometimes wrong" because field order and whitespace differ from the original bytes. A week later someone disables signature checks to make it work: now anyone can call the public endpoint and change order status.
2. Key idea
The adapter is the only interpreter between you and the provider. Look first at what costs most when wrong: a security mistake loses real money, a performance mistake can be patched with caches and machines.
| Style | Use when | Don't use when |
|---|---|---|
| Synchronous, wait for the result | fast, under 1–2 s: exchange rates, address checks | long tasks: their latency becomes yours |
| Create synchronously, result via webhook | payments, eKYC | you can't expose a public endpoint |
| Queue + worker | no need to wait: email, SMS, pushing orders | the user needs the result now |
A webhook may never arrive (endpoint down when they call, wrong URL). Use both: webhooks as the main path; ask for status when overdue; a job scans stuck requests; daily reconciliation by file.
2.1 Receiving webhooks safely
| Step | What |
|---|---|
| 1. Signature on the raw body | take byte[]/String, verify the HMAC, then parse |
| 2. Replay protection | a signed timestamp, reject skew over 5 minutes; dedupe by event id |
| 3. Store, then 2xx | write to the DB or outbox; heavy work runs later |
| 4. Tolerate duplicates and reordering | refunded can arrive before succeeded: the state machine only moves forward |
3. In Java
@PostMapping("/webhooks/payments")
ResponseEntity<String> receive(@RequestBody byte[] raw,
@RequestHeader("X-Signature") String sig,
@RequestHeader("X-Timestamp") long ts) throws Exception {
if (Math.abs(clock.instant().getEpochSecond() - ts) > 300) return ResponseEntity.status(400).build();
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret, "HmacSHA256"));
byte[] expected = HexFormat.of().formatHex(mac.doFinal(concat(ts + ".", raw))).getBytes(US_ASCII);
if (!MessageDigest.isEqual(expected, sig.getBytes(US_ASCII))) // constant time
return ResponseEntity.status(401).build();
WebhookOutcome o = gateway.parseCallback(raw); // adapter: their codes -> our enum
payments.apply(o); // UPDATE ... WHERE status = 'PENDING'
return ResponseEntity.ok("received");
}Outside the adapter, business code sees only PaymentGateway with createCheckout, queryStatus, parseCallback and our own enums; no vnp_ResponseCode leaks out. Other languages: Node.js needs express.raw() to keep the raw body.
Choosing a provider
Compare across seven groups: security and compliance, fees, reliability (SLA, a status query API, callback retries), settlement (T+1 or T+n, reconciliation by file or API), integration (docs, sandbox), operations (support, incident channels), exit cost.
PCI DSS 3.2.1 retired on 31/03/2024; the current version is 4.0.1: ask for a valid Attestation of Compliance. Fee schedules change: record them in an ADR with the date you took them.
One provider is easy to integrate and reconcile, but their outage is your lost revenue; several give failover but double reconciliation and testing. SMS OTP nearly always needs several; payment gateways usually start with one, behind your own interface.
4. Working with AI
Give the AI: adapters from the provider's docs, fixed signature test vectors, a mock server (WireMock) for slow responses, 503s, unknown codes, duplicate webhooks.
Check in AI-written code:
- Signatures are verified on the raw body, compared with
MessageDigest.isEqual. - Timestamps are checked and event ids deduplicated.
- State transitions are conditional
UPDATEs that only move forward. - Provider codes never appear outside the adapter; unknown codes become
Unknownand alert.
5. Exercises
Exercise 1: Designing an eKYC integration
An eKYC service takes an ID card photo and a portrait, returns results 5–60 s later via webhook, and offers a per-request status API. Design the flow.
Solution to Exercise 1
- Table
kyc_request(id, user_id, provider_ref, status, ...), statesSUBMITTED → PROCESSING → APPROVED | REJECTED | NEEDS_REVIEW. - Submit: store the encrypted images, create the record, queue the call.
- Worker calls the provider with idempotency key =
kyc_request.id, a timeout, jittered retries. - Webhook: verify the raw-body signature and timestamp, store it verbatim, transition conditionally, return 2xx at once.
- Job every minute queries requests stuck in
PROCESSINGfor over 2 minutes, rate-limited.
Exercise 2: "Paid but the order is still pending"
A customer was charged but the order is still PENDING. Logs show an IPN at 10:02 and the handler returned 00, yet the DB didn't change. The gateway won't resend. Diagnose and fix.
Solution to Exercise 2
The handler returned 00 before the transaction committed (e.g. it replied in the controller while the update ran asynchronously and failed, or the commit failed after the response went out). The gateway saw 00 and stopped retrying.
Fix: return 00 only after a durable write (the callback record plus the status change in one transaction, or an outbox write first). Store the response code and handling time next to the callback record so this kind of bug is visible at once. A job querying overdue PENDING payments is the final safety net.
Summary
- Security first, complexity last.
- Long tasks: create synchronously, results via webhook, plus polling and a scanning job.
- Verify signatures on the raw body, check timestamps, dedupe, store then 2xx.
- The state machine only moves forward; duplicate and out-of-order webhooks are normal.
- Provider codes live only in the adapter.
Read more: Integrating the VNPay gateway.
Comments
Community rules