Design Patterns Tutorial 0/70 lessons ~6 min read Lesson 68

    Payment Gateway Integration

    Payment gateway integration is highest-stakes pattern composition: money involved, partial failures unacceptable, vendor SDKs inconsistent, regional providers need fallbacks.

    Course progress0%
    Focus
    21 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Payment gateway integration is highest-stakes pattern composition: money involved, partial failures unacceptable, vendor SDKs inconsistent, regional providers need fallbacks. Adapter + Strategy + Circuit Breaker + Saga + Outbox.

    The story

    Platform expanding to LATAM needed Brazilian provider with 1990s SOAP API. Built PaymentGatewayPort; Adapter per provider (Stripe, PayPal, Adyen, Brazilian SOAP). New providers ship in 2 days. Original Stripe-only integration took 6 weeks.

    The business problem

    Payment integration mistakes cost money and trust:

    • Vendor lock-in: Stripe types leak into checkout domain.
    • Regional gaps: LATAM provider with SOAP/XML mess.
    • Cascade failures: one provider down takes checkout down.
    • Double charge: retry without idempotency keys.

    The problem teams faced

    Payment gateway forces:

    • Normalize heterogeneous provider APIs to domain port.
    • Select provider by region, currency, failover rules.
    • Resilience: breaker, backup provider, idempotent charges.
    • Saga integration: charge/refund as compensatable steps.

    Understanding the topic

    Intent: Safe multi-provider payment architecture.

    • Adapter — Stripe SDK, SOAP XML → PaymentGatewayPort.
    • Strategy — provider selection by region/rules.
    • Circuit Breaker — fail fast; route to backup.
    • Saga — charge/refund in order workflow.
    • Idempotency — keys on every charge attempt.

    Internal architecture

    Payment integration architecture:

    ts
    interface PaymentGatewayPort {
    charge(req: ChargeRequest): Promise<Receipt> // idempotencyKey required
    refund(receiptId: string, amount: Money): Promise<void>
    }
    class PaymentRouter {
    charge(req: ChargeRequest) {
    const primary = this.strategy.select(req.region)
    if (!this.breaker.isOpen(primary.name))
    return this.breaker.exec(primary.name, () => primary.charge(req))
    return this.backup.charge(req)
    }
    }

    Visual explanation

    Three diagrams cover port/adapters, failover, LATAM SOAP:

    PaymentGatewayPort + Adapters
    Checkout domain
    Port only
    StripeAdapter
    REST
    SoapBrazilAdapter
    Legacy
    AdyenAdapter
    EU
    Domain never imports vendor SDK types.
    Provider failover
    Primary Stripe
    Region US
    Breaker open?
    5 failures
    Backup Adyen
    Route
    Idempotency key
    Same charge
    Strategy selects primary; breaker triggers fallback.
    2-day new provider
    New SOAP API
    LATAM
    Write Adapter
    Port impl
    Register Strategy
    Region BR
    Contract test
    Shared suite
    Port + Adapter — new provider without domain changes.

    Informative example

    SOAP Adapter sketch:

    ts
    class BrazilSoapPaymentAdapter implements PaymentGatewayPort {
    async charge(req: ChargeRequest): Promise<Receipt> {
    const xml = this.buildSoapEnvelope(req) // translate domain → SOAP
    const raw = await this.http.post(this.endpoint, xml)
    return this.parseReceipt(raw) // translate SOAP → Receipt domain type
    }
    }
    // Checkout only knows PaymentGatewayPort — never SOAP

    Execution workflow

    1Multi-provider payment rollout
    1 / 4

    Define port

    Charge, refund, idempotency in domain terms.

    No Stripe types.

    Real-world use

    Stripe Connect multi-party; Adyen unified commerce; regional LATAM processors; PCI scope reduction via tokenization at adapter boundary.

    Production case study

    LATAM expansion:

    • Challenge: Brazilian SOAP provider + existing Stripe.
    • Design: PaymentGatewayPort + 4 adapters + router.
    • Outcome: provider #2 in 2 days vs 6 weeks for first.

    Trade-offs

    • Pro: vendor swap; regional coverage; testable port.
    • Con: lowest-common-denominator port may miss provider features.

    Decision framework

    • 2+ providers or regions → port + adapters mandatory.
    • Always idempotency keys on charge.
    • Breaker + backup before production multi-provider.

    Best practices

    • Contract test suite run against every adapter.
    • PCI: tokenize at adapter; domain sees tokens only.
    • Saga refund as compensation step — idempotent.

    Anti-patterns to avoid

    • Stripe SDK types in Order entity.
    • Retry charge without idempotency key.
    • Single provider with no breaker in production checkout.

    Common mistakes

    • Adapter leaks provider error codes into domain — map to domain errors.
    • Fallback provider different fee structure — document in Strategy.

    Debugging tips

    • Log idempotency key + provider name on every charge attempt.

    Optimization strategies

    • Route by latency metrics — adaptive Strategy selection.

    Common misconceptions

    • Adapter ≠ anti-corruption only for legacy — all vendor SDKs are foreign.
    • Strategy here = provider selection — not pricing algorithm.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1AdvancedQuestionIntegrate 3 payment providers?+

    Answer

    PaymentGatewayPort domain interface. Adapter per vendor. Strategy/router by region. Circuit breaker + backup. Idempotency keys. Contract tests shared.

    Follow-up

    SOAP legacy?
    2AdvancedQuestionIdempotency in payments?+

    Answer

    Client-generated key per charge attempt. Provider dedupes — safe retries from saga or network blip.

    Follow-up

    Double charge scenario?
    3IntermediateQuestionPCI scope reduction?+

    Answer

    Tokenize card at adapter/gateway; domain stores tokens not PAN. Adapter boundary is PCI seam.

    Follow-up

    What domain sees?

    Summary

    You can integrate multi-provider payments safely. Tell the 6-week → 2-day provider story — you own Payment Gateway Integration.

    Ready to mark this lesson complete?Track your journey across the entire course.