Building an API-First Payment Gateway from Scratch
Complete architectural blueprint for building a production-grade, API-first payment gateway with modern engineering practices
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.
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.
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.
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.
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.
API-first payment gateway architecture:
Reference Architecture
The API spec is the source of truth. SDKs, documentation, and sandbox are generated from the spec.
| Component | Responsibility | Technology |
|---|---|---|
| API Spec | Contract definition, SDK generation | OpenAPI 3.0, Swagger |
| API Gateway | Auth, rate limiting, routing | Kong, AWS API Gateway |
| Payment Service | Transaction orchestration | Go, Java, Node.js |
| Rail Connectors | Bank/network communication | ISO 8583, REST, gRPC |
| Tokenization | Card data vaulting | HSM, encrypted DB |
| Ledger | Double-entry accounting | PostgreSQL, event sourcing |
| Webhooks | Async notifications | Kafka, HTTP, retry queue |
| Developer Portal | Docs, SDKs, sandbox | Backstage, custom portal |
API-first design principles:
Define API contract in OpenAPI 3.0. Generate SDKs, documentation, and mock servers from spec.
Every payment endpoint accepts idempotency-key header. Retries with same key return cached response.
URI-based versioning (/v1/, /v2/). Backward-compatible changes within version.
Consistent error format with code, message, details. Retryable vs non-retryable classification.
Event-driven notifications with HMAC signature verification. Retry with exponential backoff.
/v1/paymentsCreate 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 }/v1/payments/{id}Retrieve payment status
Response
{ "id": "pay_xxx", "status": "captured", "amount": 1000 }/v1/webhooksRegister 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 for API-first gateway:
API key + secret for merchant auth. OAuth 2.0 for scoped access. mTLS for service-to-service.
Card data collected in SDK iframe. PAN never touches merchant server. Tokenization at SDK level.
HMAC-SHA256 signature on every webhook. Timestamp validation to prevent replay.
Per-merchant rate limits. Burst allowance. 429 with Retry-After header.
Industry-leading API design. Reference for API-first payment platforms.
India-focused API with UPI, cards, net banking support.
Enterprise API with unified commerce support.
API-first gateway implementations:
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.
Storing PAN or CVV in databases creates massive PCI DSS scope and security risk. Always use tokenization.
Missing idempotency keys on payment endpoints causes duplicate charges on retries. Every payment API must support idempotency.
Treating inherently asynchronous payment operations as synchronous causes timeouts and poor UX. Use webhooks and async patterns.
Failing to retry failed webhook deliveries causes merchants to miss critical payment status updates. Implement exponential backoff retry.
Manual reconciliation at scale is error-prone and slow. Automate reconciliation from day one.
Depending on a single payment rail creates a single point of failure. Implement multi-rail architecture with failover.
Launching without fraud monitoring leads to chargebacks and losses. Implement real-time fraud detection from day one.
Using the transaction database as the financial ledger leads to accuracy and audit issues. Maintain a separate double-entry ledger.
| KPI | Description | Target |
|---|---|---|
| Authorization Rate | Percentage of payment attempts that receive authorization | > 95% |
| Payment Success Rate | Percentage of initiated payments that complete successfully | > 97% |
| API Latency (p99) | 99th percentile API response time | < 500ms |
| TPS Capacity | Transactions per second the system can handle | Based on peak demand |
| Fraud Rate | Fraudulent transactions as percentage of total | < 0.1% |
| Chargeback Rate | Chargebacks as percentage of transactions | < 0.75% |
| Uptime | System availability | 99.99% |
| Reconciliation Accuracy | Percentage of transactions successfully reconciled | > 99.5% |
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.
- Write OpenAPI 3.0 spec for payment APIs
- Generate SDKs from spec
- Implement API gateway with auth and rate limiting
- Build payment service with idempotency
- Implement webhook delivery with signatures
- 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.
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.
Payment Service Provider: entity that enables merchants to accept payments through multiple payment methods via a single integration.
Payment Facilitator: entity that enables sub-merchants to accept payments under the PayFac master merchant account.
Bank or financial institution that processes card transactions on behalf of merchants.
Bank or financial institution that issues payment cards to consumers.
Fee paid between the acquiring bank and the issuing bank for card transactions, set by card networks.
Merchant ID: unique identifier assigned to a merchant by the acquirer.
Primary Account Number: the 14-19 digit number on a payment card, considered sensitive cardholder data under PCI DSS.
Process of replacing sensitive card data with a non-sensitive token.
Process of verifying that a payment account has sufficient funds and is valid for a transaction.
Process of finalizing a previously authorized transaction, triggering the transfer of funds.
Process of exchanging transaction details between acquiring and issuing banks.
Actual transfer of funds between banks to complete a payment transaction.
Transaction dispute initiated by a cardholder through their issuing bank.
Merchant Category Code: 4-digit code classifying the type of goods or services a merchant sells.
3-D Secure: authentication protocol for card-not-present transactions.
Payment Card Industry Data Security Standard: security standard for organizations handling cardholder data.
Hardware Security Module: physical computing device that safeguards and manages digital keys.
Property of an API where making the same request multiple times produces the same result as making it once.
HTTP callback triggered by an event, used in payments for asynchronous notifications.
Unified Payments Interface: India real-time payment system developed by NPCI.
National Payments Corporation of India: umbrella organization for retail payment systems in India.
Reserve Bank of India: India central bank and regulatory authority for payment systems.
International standard for electronic data interchange between financial institutions.
Automated Clearing House: US electronic payment network for batch-processed bank-to-bank transfers.
US Federal Reserve instant payment service launched in 2023.
Single Euro Payments Area: EU payment integration initiative.
Real-Time Payments: payment infrastructure enabling instant, irrevocable payments 24/7.
Financial record-keeping system using double-entry accounting.
Process of matching transaction records across different systems to ensure consistency.
Financial arrangement where a third party holds funds until conditions are met.
Buy Now Pay Later: short-term financing allowing consumers to pay in installments.
Banking-as-a-Service: model where licensed banks provide banking infrastructure via APIs.
Practice of providing secure API access to bank account data and payment initiation.
Integration of financial services into non-financial platforms via APIs.
Cryptocurrency designed to maintain stable value by pegging to a reference asset.
- 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
Designs end-to-end payment architecture including gateways, orchestration, rails, security, and compliance.
Designs comprehensive fintech platform architecture including payments, banking, ledgers, risk, and compliance.
Designs API-first payment platforms including REST APIs, webhooks, SDKs, developer portals, and API governance.
Implements and operates payment infrastructure including gateway, routing, processing, reconciliation, and settlement.
Builds internal developer platforms for payment integration, providing self-service APIs, SDKs, and golden paths.
Applies software engineering to payment operations, managing SLI/SLO/error budgets and incident response.
Monitors transaction patterns, investigates suspicious activity, tunes fraud rules, and manages chargeback disputes.
Defines payment product strategy, manages roadmap, balances user experience with compliance, and drives payment metrics.
Ensures payment systems meet PCI DSS, RBI, AML, and other regulatory requirements.
Implements and operates treasury management systems including liquidity management, settlement, FX, and bank connectivity.
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.
- 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.
Navigate through Advanced Fintech & Payments topics
