AIVANA BRAYNOR
Advanced Fintech & PaymentsPayment Foundations & Core ArchitectureTopic 3

Building an API-First Payment Gateway from Scratch

Complete architectural blueprint for building a production-grade, API-first payment gateway with modern engineering practices

Quick Answer

Building an API-first payment gateway requires designing REST APIs with idempotency, webhooks, SDKs, and developer portals. The architecture includes API gateway, payment orchestration service, rail connectors, tokenization vault, double-entry ledger, and reconciliation engine. Key principles: API-first design (APIs before implementation), idempotency (safe retries), webhooks (async notifications), SDKs (client-side security), and developer experience.

Learning Objectives
1Design API-first payment gateway architecture from scratch
2Implement idempotent payment APIs with proper error handling
3Build webhook delivery system with retry and signature verification
4Design client SDKs for secure payment data collection
5Create developer portal with documentation and sandbox
Executive Summary

Building a payment gateway from scratch is a significant engineering undertaking requiring deep expertise in distributed systems, security, and financial processing.

API-first design means designing APIs before implementation. The API contract is defined first, ensuring consistency and developer experience.

Key components include API gateway, payment orchestration, rail connectors, tokenization, ledger, webhooks, reconciliation, and developer portal.

What Is Building an API-First Payment Gateway from Scratch?

An API-first payment gateway is a payment processing platform designed with APIs as the primary interface. The API contract is defined before implementation, ensuring consistency, developer experience, and integration simplicity.

Why This Topic Matters

API-first design is the modern standard for payment gateways. It enables rapid merchant integration, consistent developer experience, and platform extensibility.

Building from scratch provides full control over architecture, cost optimization at scale, and customization.

The API is the product. Developer experience determines adoption and retention.

Why It Matters in 2026+

In 2026, API-first is not optional. Merchants expect clean REST APIs, comprehensive SDKs, sandbox environments, and webhooks.

AI-assisted development tools can generate SDKs and documentation from API specs, reducing the cost of API-first development.

The rise of API gateways as managed services reduces infrastructure burden but does not replace API design expertise.

Architecture Overview

API-first payment gateway architecture:

Reference Architecture

API Spec (OpenAPI)
↓
API Gateway
↓
Payment Service
↓
Rail Connectors
↓
Ledger
↓
Webhooks
↓
Developer Portal

The API spec is the source of truth. SDKs, documentation, and sandbox are generated from the spec.

Core Components
ComponentResponsibilityTechnology
API SpecContract definition, SDK generationOpenAPI 3.0, Swagger
API GatewayAuth, rate limiting, routingKong, AWS API Gateway
Payment ServiceTransaction orchestrationGo, Java, Node.js
Rail ConnectorsBank/network communicationISO 8583, REST, gRPC
TokenizationCard data vaultingHSM, encrypted DB
LedgerDouble-entry accountingPostgreSQL, event sourcing
WebhooksAsync notificationsKafka, HTTP, retry queue
Developer PortalDocs, SDKs, sandboxBackstage, custom portal
APIs and Integration Patterns

API-first design principles:

OpenAPI Spec

Define API contract in OpenAPI 3.0. Generate SDKs, documentation, and mock servers from spec.

Idempotency

Every payment endpoint accepts idempotency-key header. Retries with same key return cached response.

Versioning

URI-based versioning (/v1/, /v2/). Backward-compatible changes within version.

Error Handling

Consistent error format with code, message, details. Retryable vs non-retryable classification.

Webhooks

Event-driven notifications with HMAC signature verification. Retry with exponential backoff.

POST/v1/payments

Create payment with idempotency

Request

{ "amount": 1000, "currency": "INR", "payment_method": { "type": "card", "card_token": "tok_xxx" }, "idempotency_key": "key_123" }

Response

{ "id": "pay_xxx", "status": "authorized", "amount": 1000 }
GET/v1/payments/{id}

Retrieve payment status

Response

{ "id": "pay_xxx", "status": "captured", "amount": 1000 }
POST/v1/webhooks

Register webhook endpoint

Request

{ "url": "https://merchant.com/webhooks", "events": ["payment.authorized", "payment.captured"] }

Response

{ "id": "wh_xxx", "url": "https://merchant.com/webhooks", "secret": "whsec_xxx" }
Security Architecture

Security for API-first gateway:

API Authentication

API key + secret for merchant auth. OAuth 2.0 for scoped access. mTLS for service-to-service.

Client SDK Security

Card data collected in SDK iframe. PAN never touches merchant server. Tokenization at SDK level.

Webhook Security

HMAC-SHA256 signature on every webhook. Timestamp validation to prevent replay.

Rate Limiting

Per-merchant rate limits. Burst allowance. 429 with Retry-After header.

Vendor Landscape
Stripe API

Industry-leading API design. Reference for API-first payment platforms.

REST APISDKsWebhooksSandbox
Razorpay API

India-focused API with UPI, cards, net banking support.

REST APIUPISDKs
Adyen API

Enterprise API with unified commerce support.

REST APIUnified commerce
Real Enterprise Case Studies

API-first gateway implementations:

StripeUSA · Fintech

Context: API-first payment platform serving millions of developers.

Problem: Design APIs that developers love while handling complex payment processing.

Architecture: API-first with OpenAPI spec. SDKs in 10+ languages. Comprehensive documentation and sandbox.

Technology: Ruby, Go, OpenAPI

Outcomes: Industry-leading developer experience. Millions of integrations.

Lessons: API design is the primary differentiator. Developer experience drives adoption.

Common Architecture Mistakes
Storing Raw Card Data

Storing PAN or CVV in databases creates massive PCI DSS scope and security risk. Always use tokenization.

No Idempotency on Payment APIs

Missing idempotency keys on payment endpoints causes duplicate charges on retries. Every payment API must support idempotency.

Synchronous Processing of Async Operations

Treating inherently asynchronous payment operations as synchronous causes timeouts and poor UX. Use webhooks and async patterns.

No Webhook Retry Logic

Failing to retry failed webhook deliveries causes merchants to miss critical payment status updates. Implement exponential backoff retry.

No Reconciliation Automation

Manual reconciliation at scale is error-prone and slow. Automate reconciliation from day one.

Single-Rail Dependency

Depending on a single payment rail creates a single point of failure. Implement multi-rail architecture with failover.

No Fraud Monitoring

Launching without fraud monitoring leads to chargebacks and losses. Implement real-time fraud detection from day one.

Payment Database as Financial Ledger

Using the transaction database as the financial ledger leads to accuracy and audit issues. Maintain a separate double-entry ledger.

KPIs
KPIDescriptionTarget
Authorization RatePercentage of payment attempts that receive authorization> 95%
Payment Success RatePercentage of initiated payments that complete successfully> 97%
API Latency (p99)99th percentile API response time< 500ms
TPS CapacityTransactions per second the system can handleBased on peak demand
Fraud RateFraudulent transactions as percentage of total< 0.1%
Chargeback RateChargebacks as percentage of transactions< 0.75%
UptimeSystem availability99.99%
Reconciliation AccuracyPercentage of transactions successfully reconciled> 99.5%
Practical Project

Build an API-First Payment Gateway

Objective: Design and implement an API-first payment gateway with OpenAPI spec, SDKs, and webhooks.

Scenario: Build a payment gateway for a SaaS platform that needs to offer payments to its customers via API.

Tasks:
  1. Write OpenAPI 3.0 spec for payment APIs
  2. Generate SDKs from spec
  3. Implement API gateway with auth and rate limiting
  4. Build payment service with idempotency
  5. Implement webhook delivery with signatures
  6. Create developer portal with docs and sandbox

Deliverables: OpenAPI spec, SDKs, API gateway, payment service, webhook system, developer portal.

Validation: Register a webhook. Create a payment via API. Verify webhook delivery with signature. Retry with same idempotency key.

Interview Questions

What is API-first design?

Designing the API contract before implementation. Ensures consistency, enables SDK generation from spec, and prioritizes developer experience.

How do you design idempotent payment APIs?

Accept idempotency-key header. Store key with transaction. On retry with same key, return cached response. Prevents duplicate charges.

Frequently Asked Questions (52)
Glossary
PSP

Payment Service Provider: entity that enables merchants to accept payments through multiple payment methods via a single integration.

PayFac

Payment Facilitator: entity that enables sub-merchants to accept payments under the PayFac master merchant account.

Acquirer

Bank or financial institution that processes card transactions on behalf of merchants.

Issuer

Bank or financial institution that issues payment cards to consumers.

Interchange

Fee paid between the acquiring bank and the issuing bank for card transactions, set by card networks.

MID

Merchant ID: unique identifier assigned to a merchant by the acquirer.

PAN

Primary Account Number: the 14-19 digit number on a payment card, considered sensitive cardholder data under PCI DSS.

Tokenization

Process of replacing sensitive card data with a non-sensitive token.

Authorization

Process of verifying that a payment account has sufficient funds and is valid for a transaction.

Capture

Process of finalizing a previously authorized transaction, triggering the transfer of funds.

Clearing

Process of exchanging transaction details between acquiring and issuing banks.

Settlement

Actual transfer of funds between banks to complete a payment transaction.

Chargeback

Transaction dispute initiated by a cardholder through their issuing bank.

MCC

Merchant Category Code: 4-digit code classifying the type of goods or services a merchant sells.

3DS

3-D Secure: authentication protocol for card-not-present transactions.

PCI DSS

Payment Card Industry Data Security Standard: security standard for organizations handling cardholder data.

HSM

Hardware Security Module: physical computing device that safeguards and manages digital keys.

Idempotency

Property of an API where making the same request multiple times produces the same result as making it once.

Webhook

HTTP callback triggered by an event, used in payments for asynchronous notifications.

UPI

Unified Payments Interface: India real-time payment system developed by NPCI.

NPCI

National Payments Corporation of India: umbrella organization for retail payment systems in India.

RBI

Reserve Bank of India: India central bank and regulatory authority for payment systems.

ISO 20022

International standard for electronic data interchange between financial institutions.

ACH

Automated Clearing House: US electronic payment network for batch-processed bank-to-bank transfers.

FedNow

US Federal Reserve instant payment service launched in 2023.

SEPA

Single Euro Payments Area: EU payment integration initiative.

RTP

Real-Time Payments: payment infrastructure enabling instant, irrevocable payments 24/7.

Ledger

Financial record-keeping system using double-entry accounting.

Reconciliation

Process of matching transaction records across different systems to ensure consistency.

Escrow

Financial arrangement where a third party holds funds until conditions are met.

BNPL

Buy Now Pay Later: short-term financing allowing consumers to pay in installments.

BaaS

Banking-as-a-Service: model where licensed banks provide banking infrastructure via APIs.

Open Banking

Practice of providing secure API access to bank account data and payment initiation.

Embedded Finance

Integration of financial services into non-financial platforms via APIs.

Stablecoin

Cryptocurrency designed to maintain stable value by pegging to a reference asset.

Implementation Checklist
  • Architecture designed and reviewed
  • API contracts defined with idempotency
  • Authentication and authorization implemented
  • PCI DSS scope assessed and minimized via tokenization
  • Error handling and retry logic designed
  • Webhook delivery and retry implemented
  • Security review completed (encryption, HSM, key management)
  • Regulatory requirements identified (RBI, PCI DSS, AML)
  • Data model defined (transactions, ledger, reconciliation)
  • Observability implemented (metrics, logs, traces, alerts)
  • Testing completed (unit, integration, load, chaos)
  • Disaster recovery designed and tested
  • Reconciliation process validated
  • Fraud detection deployed and tuned
  • Production readiness assessed and approved
Career & Enterprise Skills
Payment Architect

Designs end-to-end payment architecture including gateways, orchestration, rails, security, and compliance.

Fintech Architect

Designs comprehensive fintech platform architecture including payments, banking, ledgers, risk, and compliance.

API Architect

Designs API-first payment platforms including REST APIs, webhooks, SDKs, developer portals, and API governance.

Payment Engineer

Implements and operates payment infrastructure including gateway, routing, processing, reconciliation, and settlement.

Platform Engineer

Builds internal developer platforms for payment integration, providing self-service APIs, SDKs, and golden paths.

SRE Engineer

Applies software engineering to payment operations, managing SLI/SLO/error budgets and incident response.

Fraud Analyst

Monitors transaction patterns, investigates suspicious activity, tunes fraud rules, and manages chargeback disputes.

Fintech Product Manager

Defines payment product strategy, manages roadmap, balances user experience with compliance, and drives payment metrics.

Compliance Specialist

Ensures payment systems meet PCI DSS, RBI, AML, and other regulatory requirements.

Treasury Technology Specialist

Implements and operates treasury management systems including liquidity management, settlement, FX, and bank connectivity.

Future Outlook

2027: Building an API-First Payment Gateway will see increased AI integration with AI agents handling routine payment decisions, intelligent routing optimization, and predictive fraud prevention becoming standard capabilities.

2028: Autonomous payment systems will mature with self-healing infrastructure, AI-driven reconciliation, and cross-border real-time payments reducing settlement time from days to seconds.

2029: Programmable money and tokenized deposits will enable new payment models with conditional settlement, smart contract-based escrow, and machine-to-machine payments becoming practical.

2030: The convergence of AI, blockchain, and real-time payments will be complete. Building an API-First Payment Gateway will be managed through AI agents with humans governing policy, security, and business alignment. Payments will be invisible, instant, and intelligent.

Key Takeaways
  • API-first design is the modern standard for payment gateways, prioritizing developer experience.
  • OpenAPI spec is the source of truth for API contract, SDKs, and documentation.
  • Idempotency, webhooks, and SDKs are essential components of API-first payment platforms.
  • Developer experience is the primary differentiator for payment gateway adoption.