Build the Payment Ingestion API

Implementing the contract: a thin controller, validation, one adapter per provider into a canonical payment, consistent errors, honest responses and provider authentication.

  • Advanced
  • About 21 minutes
  • Includes an exercise and a knowledge check

From the contract POST /api/v1/payment-notifications

On the left, a photo of a post office clerk sorting letters into pigeonholes. On the right, five steps for one notification: authenticate (signature, recent timestamp, no replay), validate (fields, amount, currency, status, lengths), adapt (Provider A or B adapter to the canonical payment), store (one row per provider and transaction ID, source kept), answer (ACCEPTED with the ingestion ID). Rejections: 401 for a bad signature, stale timestamp or replayed request; 400 with errorCode INVALID_PAYMENT_REQUEST and a correlation ID, never a stack trace.
Check every letter before it is filed. The controller is the counter, not the sorting office.

javaThe controller: HTTP in, HTTP out (Spring Boot sketch)

@RestController
@RequestMapping("/api/v1/payment-notifications")
class PaymentNotificationController {

    private final PaymentIngestionService ingestion;

    PaymentNotificationController(PaymentIngestionService ingestion) {
        this.ingestion = ingestion;
    }

    @PostMapping("/{provider}")
    ResponseEntity<IngestionResponse> receive(@PathVariable String provider,
                                              @RequestHeader("X-Apex-Timestamp") String timestamp,
                                              @RequestHeader("X-Apex-Signature") String signature,
                                              @RequestBody byte[] rawBody) {   // the exact bytes, never a re-encoded String
        IngestionResult result = ingestion.receive(provider, timestamp, signature, rawBody);
        return switch (result.outcome()) {
            case CREATED   -> ResponseEntity.accepted().body(result.response());   // 202
            case DUPLICATE -> ResponseEntity.ok(result.response());               // 200, same ingestionId
            case CONFLICT  -> ResponseEntity.status(409).body(result.response()); // same ID, other content
        };   // signature, timestamp and validation failures are exceptions mapped to 401 and 400 centrally
    }
}

The controller only translates HTTP. It receives the raw body as bytes, because signature verification must run on the exact bytes the provider signed; reading it as a String first can change the encoding or line endings. The provider is part of the path, and the timestamp and signature travel in the X-Apex-Timestamp and X-Apex-Signature headers, exactly as frozen in the Module 06 contract (decision CD-01), so the right adapter and signing key are chosen before anything is parsed. The application service runs the workflow, and the response code tells the provider what happened: a new payment (202 Accepted), an exact repeat (200 with the same ingestion ID), or a conflict (409).

Two providers Validation and provider adapters

Do not trust a payload because it comes from an approved integration. Validate required identifiers, amount format, currency, supported status, timestamp and string lengths, plus provider-specific rules. Then let one adapter per provider build the canonical payment, so a provider’s format change touches only its adapter.

javaProviderAdapters.java: two formats, one canonical payment

import java.math.BigDecimal;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;

public class ProviderAdapters {

    record CanonicalPayment(String provider, String providerTransactionId, String loanAccountId,
                            long amountMinorUnits, String currency, Instant transactionTimestamp) {}

    /** Thrown for a payload the platform must reject; the message is safe to return to the caller. */
    static class InvalidPaymentException extends RuntimeException {
        InvalidPaymentException(String message) { super(message); }
    }

    interface ProviderAdapter {
        CanonicalPayment toCanonical(Map<String, String> payload);
    }

    static String required(Map<String, String> p, String field, int maxLength) {
        String v = p.get(field);
        if (v == null || v.isBlank()) throw new InvalidPaymentException("missing field " + field);
        if (v.length() > maxLength) throw new InvalidPaymentException(field + " is longer than " + maxLength);
        return v.trim();
    }

    /** Parsing errors (bad digits, too many digits, bad dates) become a safe 400, never a 500. */
    static <T> T parse(String field, java.util.function.Supplier<T> parser) {
        try {
            return parser.get();
        } catch (NumberFormatException | ArithmeticException | DateTimeParseException e) {
            throw new InvalidPaymentException("invalid " + field);
        }
    }

    static String usd(String currency) {
        if (!currency.equals("USD")) throw new InvalidPaymentException("unsupported currency " + currency);
        return currency;
    }

    /** Provider A: snake_case fields, amount as a decimal string, UTC timestamps. */
    static class ProviderAAdapter implements ProviderAdapter {
        public CanonicalPayment toCanonical(Map<String, String> p) {
            String raw = required(p, "paid_amount", 20);
            BigDecimal amount = parse("paid_amount", () -> new BigDecimal(raw));
            if (amount.scale() > 2 || amount.signum() <= 0) throw new InvalidPaymentException("invalid paid_amount");
            long cents = parse("paid_amount", () -> amount.movePointRight(2).longValueExact());   // overflow is an error
            String paidAt = required(p, "paid_at", 40);
            return new CanonicalPayment("PROVIDER_A", required(p, "payment_ref", 64), required(p, "loan", 32),
                    cents, usd(required(p, "currency", 3)), parse("paid_at", () -> Instant.parse(paidAt)));
        }
    }

    /** Provider B: camelCase fields, amount already in cents, local time with an offset. */
    static class ProviderBAdapter implements ProviderAdapter {
        public CanonicalPayment toCanonical(Map<String, String> p) {
            String raw = required(p, "amountInCents", 18);
            long cents = parse("amountInCents", () -> Long.parseLong(raw));
            if (cents <= 0) throw new InvalidPaymentException("invalid amountInCents");
            String ts = required(p, "timestamp", 40);
            return new CanonicalPayment("PROVIDER_B", required(p, "transactionId", 64), required(p, "loanAccount", 32),
                    cents, usd(required(p, "currency", 3)), parse("timestamp", () -> OffsetDateTime.parse(ts).toInstant()));
        }
    }

    public static void main(String[] args) {
        Map<String, ProviderAdapter> adapters = Map.of("PROVIDER_A", new ProviderAAdapter(), "PROVIDER_B", new ProviderBAdapter());
        List<Map.Entry<String, Map<String, String>>> inbox = List.of(
                Map.entry("PROVIDER_A", Map.of("payment_ref", "PAY-77821", "loan", "LN-10042", "paid_amount", "425.50",
                        "currency", "USD", "paid_at", "2026-11-18T14:30:00Z")),
                Map.entry("PROVIDER_B", Map.of("transactionId", "TXN-5531", "loanAccount", "LN-20981", "amountInCents", "18000",
                        "currency", "USD", "timestamp", "2026-11-18T08:30:00-06:00")),
                Map.entry("PROVIDER_A", Map.of("payment_ref", "PAY-77822", "paid_amount", "99.50", "currency", "USD",
                        "paid_at", "2026-11-18T14:31:00Z")),
                Map.entry("PROVIDER_A", Map.of("payment_ref", "PAY-77823", "loan", "LN-10077", "paid_amount", "99.999",
                        "currency", "USD", "paid_at", "2026-11-18T14:32:00Z")),
                Map.entry("PROVIDER_A", Map.of("payment_ref", "PAY-77824", "loan", "LN-10078", "paid_amount", "4x5.50",
                        "currency", "USD", "paid_at", "2026-11-18T14:33:00Z")),
                Map.entry("PROVIDER_A", Map.of("payment_ref", "PAY-77825", "loan", "LN-10079", "paid_amount", "99999999999999999.99",
                        "currency", "USD", "paid_at", "2026-11-18T14:34:00Z")),
                Map.entry("PROVIDER_B", Map.of("transactionId", "TXN-5532", "loanAccount", "LN-20982", "amountInCents", "18000",
                        "currency", "USD", "timestamp", "2026-11-18 08:30")));
        for (var item : inbox) {
            try {
                System.out.println("ACCEPTED " + adapters.get(item.getKey()).toCanonical(item.getValue()));
            } catch (InvalidPaymentException e) {
                System.out.println("REJECTED " + item.getKey() + ": " + e.getMessage());
            }
        }
    }
}

Output

ACCEPTED CanonicalPayment[provider=PROVIDER_A, providerTransactionId=PAY-77821, loanAccountId=LN-10042, amountMinorUnits=42550, currency=USD, transactionTimestamp=2026-11-18T14:30:00Z]
ACCEPTED CanonicalPayment[provider=PROVIDER_B, providerTransactionId=TXN-5531, loanAccountId=LN-20981, amountMinorUnits=18000, currency=USD, transactionTimestamp=2026-11-18T14:30:00Z]
REJECTED PROVIDER_A: missing field loan
REJECTED PROVIDER_A: invalid paid_amount
REJECTED PROVIDER_A: invalid paid_amount
REJECTED PROVIDER_A: invalid paid_amount
REJECTED PROVIDER_B: invalid timestamp

Real output from Java 17.0.18 running this program (fictional data), November 22, 2026.

Look at the timestamps. Provider B sent 08:30 in Dallas time (UTC minus 6); its adapter converted it to 14:30 UTC, the same instant as Provider A’s payment. Store every instant in UTC and convert only for display. The other five payloads were refused with a safe reason: a missing loan account; 99.999 dollars, which has more decimals than US dollars allow; 4x5.50, which is not a number; an amount too large for the amount column; and a timestamp in no recognized format. Every parsing error becomes a controlled 400, never a 500: the adapter catches number, overflow and date errors and turns them into the same InvalidPaymentException.

One format Consistent, safe errors

jsonEvery error looks the same

{
  "errorCode": "INVALID_PAYMENT_REQUEST",
  "message": "missing field loan",
  "correlationId": "CORR-20001"
}

Use one central exception handler (a Spring @RestControllerAdvice) that maps each exception type to a code and an HTTP status. Never return stack traces, SQL errors or class names to an external caller: they help attackers and confuse partners. The correlation ID lets support find the full details in the logs.

Who is calling? Provider authentication

  • Signature verification: an HMAC or public-key signature over the raw body, with per-provider keys from the secret store.
  • Timestamp validation: refuse requests older than an agreed tolerance, such as five minutes.
  • Replay protection: remember recently seen signatures or request IDs and refuse repeats.
  • Provider-specific credentials: one identity per provider, never shared.
  • IP restrictions where supported, as an extra layer only.

javaProviderSignature.java: signature, timestamp window and replay check

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.Set;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class ProviderSignature {

    static final byte[] PROVIDER_A_KEY = "fictional-key-for-provider-a".getBytes(StandardCharsets.UTF_8);
    static final Duration WINDOW = Duration.ofMinutes(5);
    // Stands in for a table with UNIQUE (provider_id, signature), rows kept a little longer than the window.
    static final Set<String> seenSignatures = new HashSet<>();

    /** HMAC-SHA256 over: timestamp, a dot, then the request body exactly as received. */
    static byte[] sign(byte[] key, String timestamp, byte[] rawBody) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
        mac.update(timestamp.getBytes(StandardCharsets.UTF_8));
        mac.update((byte) '.');
        return mac.doFinal(rawBody);
    }

    static String verify(String provider, String timestamp, String signatureHex, byte[] rawBody, Instant now) throws Exception {
        Instant sentAt;
        try {
            sentAt = Instant.parse(timestamp);
        } catch (DateTimeParseException e) {
            return "401 timestamp is not a valid instant";
        }
        if (Duration.between(sentAt, now).abs().compareTo(WINDOW) > 0) return "401 timestamp outside the 5-minute window";
        byte[] given;
        try {
            given = HexFormat.of().parseHex(signatureHex);
        } catch (IllegalArgumentException e) {
            return "401 signature is not valid hex";
        }
        // Constant-time comparison, so the response time does not leak how many bytes matched.
        if (!MessageDigest.isEqual(sign(PROVIDER_A_KEY, timestamp, rawBody), given)) return "401 signature does not match the raw body";
        if (!seenSignatures.add(provider + "|" + signatureHex)) return "401 replay: this signed request was already received";
        return "OK  signature valid; pass the raw body to the adapter";
    }

    public static void main(String[] args) throws Exception {
        Instant now = Instant.parse("2026-11-18T14:30:05Z");
        String ts = "2026-11-18T14:30:00Z";
        byte[] body = "{\"payment_ref\":\"PAY-77821\",\"paid_amount\":\"425.50\"}".getBytes(StandardCharsets.UTF_8);
        String sig = HexFormat.of().formatHex(sign(PROVIDER_A_KEY, ts, body));
        byte[] reformatted = "{\"payment_ref\": \"PAY-77821\",\"paid_amount\":\"425.50\"}".getBytes(StandardCharsets.UTF_8);
        String oldTs = "2026-11-18T14:10:00Z";
        String oldSig = HexFormat.of().formatHex(sign(PROVIDER_A_KEY, oldTs, body));

        System.out.println("1. The signed request as sent:        " + verify("PROVIDER_A", ts, sig, body, now));
        System.out.println("2. Same JSON with one extra space:    " + verify("PROVIDER_A", ts, sig, reformatted, now));
        System.out.println("3. The exact same request again:      " + verify("PROVIDER_A", ts, sig, body, now));
        System.out.println("4. Correctly signed, 20 minutes old:  " + verify("PROVIDER_A", oldTs, oldSig, body, now));
    }
}

Output

1. The signed request as sent:        OK  signature valid; pass the raw body to the adapter
2. Same JSON with one extra space:    401 signature does not match the raw body
3. The exact same request again:      401 replay: this signed request was already received
4. Correctly signed, 20 minutes old:  401 timestamp outside the 5-minute window

Real output from Java 17.0.18 running this program (fictional data), November 22, 2026.

Four requests, four lessons. The original passes. The same JSON with one extra space fails, because the signature covers the bytes, not the meaning. The exact same signed request a second time is refused as a replay. A correctly signed request that is 20 minutes old is refused by the timestamp window. Two contract rules make this work in production: the remembered signatures live in a table with a unique constraint, so a restart does not forget them, and every provider retry is signed again with a new timestamp, so an honest retry is never mistaken for a replay and goes on to the idempotency check instead.

Practice Implement payment ingestion

Practical exercise

Exercise 04: a working payment ingestion API

Build the first slice and test valid, invalid and unsupported payloads.

  1. Request handling and validation rules.
  2. Provider adapters and the canonical payment model.
  3. The ingestion application service and the REST controller.
  4. Centralized error handling.
  5. A provider authentication check on the raw body.
Show sample test cases
  • Valid Provider A payload: 202 with an ingestion ID; the row stores 42550 USD and the provider reference.
  • Provider B with a local-time timestamp: stored as the correct UTC instant.
  • Missing loan account: 400 INVALID_PAYMENT_REQUEST, nothing stored.
  • Bad signature: 401, nothing stored, a security log entry.
  • Unsupported currency: 400 with a specific message.

3 questions

Check your understanding

1. Why does each provider get its own adapter?
2. Why does the controller take the raw request body?
3. What should an external caller see when validation fails?
Answer every question to submit.

What you can do now

  • Implement an API from its contract with a thin controller.
  • Validate payloads and normalize them through provider adapters.
  • Return consistent, safe errors and honest status codes.
  • Authenticate providers properly.