How to Build·16 min read

How to Build a Custom Payment Gateway From Scratch in 2026

Off-the-shelf payment gateways cost you 2.9% plus $0.30 per transaction, and they own the customer relationship. Building your own gateway gives you full control over fees, data, and user experience.

Nate Laquis

Nate Laquis

Founder & CEO

Why Build a Custom Payment Gateway

Every time you process a transaction through Stripe, Adyen, or Braintree, you hand over 2.9% plus $0.30 to a company that sits between you and your customer's money. At $1M in monthly volume, that is $29,300 in fees every month. At $10M, it is $293,000. At some point, the math stops making sense.

But cost is only half the story. When you rely on a third-party gateway, you lose control over the checkout experience, the transaction data, the retry logic, and the relationship with the acquiring bank. You cannot customize decline recovery. You cannot negotiate interchange rates directly. You cannot build features that the gateway vendor has not prioritized on their roadmap.

Companies like Shopify (Shop Pay), Amazon, and Netflix all built proprietary payment infrastructure for exactly these reasons. Shopify saved an estimated $100M annually after moving off third-party processors for their own transactions. Netflix built custom payment orchestration to optimize authorization rates across 190 countries.

This guide walks you through every layer of building a custom payment gateway from scratch: the architecture, the compliance requirements, the processor integrations, the fraud systems, and the realistic costs. This is not a weekend project. But for the right business, it is the most profitable infrastructure investment you will ever make.

Digital payment checkout terminal processing a credit card transaction

Payment Gateway Architecture: The Core Components

A payment gateway is middleware. It sits between your application (the merchant) and the payment processor or acquiring bank. Its job is to securely collect card data, route it to the right processor, handle the response, and manage the lifecycle of each transaction. Here is what you need to build.

Transaction Engine

The transaction engine is the heart of your gateway. It handles authorization requests, captures, voids, refunds, and chargebacks. Each transaction moves through a state machine: created, authorized, captured, settled, or alternatively voided, declined, or disputed. Your engine must guarantee idempotency (processing the same request twice must not result in a double charge) and atomicity (partial failures must not leave transactions in an inconsistent state).

Build this on an event-sourced architecture. Every state change is an immutable event. This gives you a complete audit trail for compliance and makes debugging production issues straightforward. PostgreSQL with an event store pattern works well for gateways processing under 10,000 transactions per second. Above that, consider Apache Kafka for event streaming with Cassandra or ScyllaDB for storage.

Tokenization Vault

You must never store raw card numbers. Instead, you replace the PAN (Primary Account Number) with a token, a random string that maps back to the real card number inside a secure vault. The vault is an isolated service with its own database, its own encryption keys, and strict network access controls. No other service in your stack should ever touch raw card data.

Your tokenization service needs to support both single-use tokens (for one-time payments) and multi-use tokens (for saved cards and subscription billing). Use AES-256 encryption with envelope encryption: a data encryption key (DEK) encrypts the card data, and a key encryption key (KEK) encrypts the DEK. Rotate KEKs quarterly. Store KEKs in an HSM (Hardware Security Module) or a cloud KMS like AWS CloudHSM or Google Cloud HSM.

Payment Router

The router decides which processor handles each transaction. At minimum, it routes based on card network (Visa, Mastercard, Amex, Discover) and geography. A sophisticated router also considers processor uptime, historical authorization rates, transaction costs, and fallback logic. If Processor A declines a transaction, the router can automatically retry with Processor B. This "waterfall" routing alone can improve your overall authorization rate by 2 to 5%.

API Layer

Your gateway exposes a RESTful API (or gRPC for internal services) that merchants or your own application use to initiate transactions. Standard endpoints include: create payment intent, authorize, capture, void, refund, and query transaction status. Every request must be authenticated (API keys with HMAC signatures), rate-limited, and logged. Design your API to be idempotent from day one by requiring an idempotency key on every mutating request.

PCI DSS Compliance: The Non-Negotiable Foundation

PCI DSS (Payment Card Industry Data Security Standard) is not optional. If you touch, process, or store cardholder data, you must comply. There are four levels of PCI compliance based on transaction volume, and building your own gateway puts you at Level 1 (the most stringent) as soon as you process over 6 million transactions annually, or immediately if you are acting as a payment facilitator.

What PCI Level 1 Requires

Level 1 PCI compliance requires an annual on-site audit by a Qualified Security Assessor (QSA), quarterly network scans by an Approved Scanning Vendor (ASV), annual penetration testing, and a formal Report on Compliance (ROC). The audit alone costs $50,000 to $200,000 depending on the complexity of your cardholder data environment (CDE). Plan for 3 to 6 months of preparation before your first audit.

The 12 PCI DSS requirements cover everything from firewall configurations and encryption to access controls, monitoring, and security policies. The requirements that trip up most teams are: requirement 3 (protect stored cardholder data), requirement 6 (develop and maintain secure systems), and requirement 10 (track and monitor all access to network resources and cardholder data).

Reducing Your PCI Scope

The smartest move is to minimize your CDE (the systems that touch card data). Isolate your tokenization vault in a dedicated VPC with no internet access. Use point-to-point encryption (P2PE) so that card data is encrypted at the point of entry and only decrypted inside the vault. Every system outside the vault only handles tokens, never real card numbers. This approach can reduce your PCI audit scope by 80% and cut compliance costs dramatically.

Consider using a cloud-native approach. AWS, GCP, and Azure all offer PCI-compliant infrastructure. AWS has over 100 services covered under their PCI AOC (Attestation of Compliance). This means you inherit their physical security and infrastructure compliance, letting you focus on application-level controls. Host your CDE in a dedicated AWS account with separate billing, IAM, and network boundaries from the rest of your infrastructure.

Security compliance dashboard showing PCI DSS audit and encryption status

Ongoing Compliance Costs

First-year PCI compliance costs for a custom gateway typically run $150,000 to $400,000 including the QSA audit, penetration testing, ASV scans, security tooling, and staff training. Annual renewal costs drop to $80,000 to $200,000 once your processes are established. This is a fixed cost that does not scale with volume, which is exactly why high-volume businesses build their own gateways. At 10 million transactions per month, the PCI cost per transaction is fractions of a cent.

Integrating with Payment Processors and Card Networks

Your gateway does not communicate directly with Visa or Mastercard. Instead, it connects to acquiring banks and payment processors that have direct network connections. Understanding this chain is critical to your architecture.

The Transaction Flow

When a customer submits a card payment, here is what happens in roughly 2 seconds: your gateway sends an authorization request to your acquiring processor (e.g., Worldpay, First Data/Fiserv, or Adyen as a processor). The processor forwards the request to the card network (Visa, Mastercard). The card network routes it to the issuing bank (the customer's bank). The issuing bank approves or declines based on available funds, fraud checks, and account status. The response flows back through the same chain.

Choosing Your Acquiring Partners

You need at least two acquiring processors for redundancy. Here are the major players and what they offer for direct gateway integrations:

  • Worldpay (FIS): The largest acquirer globally. Processes over 40 billion transactions annually. Strong in the US and Europe. Direct API access for custom gateways requires a minimum volume commitment, typically $5M+ in annual processing.
  • Fiserv (First Data): The second-largest US processor. Offers the Rapid Connect API for direct integrations. Good interchange-plus pricing for high-volume merchants. Typical setup takes 4 to 8 weeks.
  • Adyen: Originally a gateway, now also a full-stack acquirer. Their API is the most developer-friendly of the major processors. Supports 250+ payment methods globally. A strong choice if you need international payment coverage.
  • Chase Paymentech: Best interchange rates for US domestic transactions due to Chase's issuing volume. Their Orbital API supports direct gateway connections.

The Integration Work

Each processor has its own API format, its own certification process, and its own quirks. Expect 4 to 8 weeks of development per processor integration, plus 2 to 4 weeks for certification testing. The certification process involves submitting test transactions across dozens of scenarios: approvals, declines, partial authorizations, reversals, and edge cases specific to each card network.

Build a processor abstraction layer in your gateway. Each processor integration implements a common interface (authorize, capture, void, refund). Your transaction engine interacts only with the abstraction layer, never with processor-specific code. This makes adding new processors a matter of writing a new adapter rather than modifying core logic.

Fraud Detection and Risk Management

A payment gateway without fraud detection is a liability. Card-not-present fraud costs merchants $48 billion annually as of 2025, and that number climbs every year. Your gateway needs multiple layers of fraud prevention, not just a single rules engine.

Layer 1: Real-Time Rules Engine

Start with velocity checks and basic rules. Block or flag transactions that match known fraud patterns: multiple transactions from the same IP in a short window, mismatched billing and shipping addresses, BIN (Bank Identification Number) from a high-risk country, transaction amounts that deviate significantly from the merchant's average. These rules catch the obvious stuff and can be implemented in week one.

Layer 2: Machine Learning Scoring

Rules catch known patterns. ML catches emerging patterns. Train a model on your transaction data (you need at least 50,000 transactions with labeled fraud outcomes to get meaningful results). Features to include: device fingerprint, behavioral biometrics (typing speed, mouse movement), historical transaction patterns, email age, shipping address history, and card BIN metadata.

If you do not have enough data for a custom model, use a third-party fraud scoring service as a bridge. Sift, Forter, and Riskified all offer API-based fraud scoring. Sift charges $0.01 to $0.05 per transaction depending on volume. Plug their score into your rules engine as an additional signal, and gradually transition to your own model as your data grows.

Layer 3: 3D Secure 2.0

3D Secure (3DS) shifts fraud liability from the merchant to the issuing bank. In the EU, Strong Customer Authentication (SCA) makes 3DS mandatory for most transactions. In the US, it is optional but increasingly adopted. Your gateway should support 3DS as a configurable option: always on, risk-based (trigger only for suspicious transactions), or merchant-configured.

Implementing 3DS requires integrating with a 3DS Server (also called an MPI, Merchant Plug-In). You can build your own or use a certified provider like Cardinal Commerce (Visa), Arcot (CA Technologies), or Netcetera. The integration adds 2 to 3 weeks of development and requires separate certification.

Chargeback Management

Your gateway must handle the entire chargeback lifecycle: receive the representment request from the processor, notify the merchant, collect evidence, format and submit the response, and track the outcome. Automate as much of this as possible. Merchants who respond to chargebacks within 24 hours win 45% of disputes compared to 20% for those who respond later. If you are also building a marketplace payment system, chargeback handling becomes even more complex because funds have already been split between multiple parties.

Settlement, Reconciliation, and Reporting

Processing payments is only half the job. The other half is making sure the money actually arrives in the right accounts and that every penny is accounted for. This is settlement and reconciliation, and it is where most custom gateway projects underestimate the complexity.

How Settlement Works

After a transaction is authorized and captured, it enters the settlement process. Your gateway batches captured transactions (typically daily) and submits them to the processor. The processor submits them to the card network. The card network debits the issuing bank and credits the acquiring bank. The acquiring bank deposits funds into your merchant's bank account. This process takes 1 to 3 business days for domestic transactions and 3 to 7 days for international ones.

Your gateway needs a settlement engine that tracks each transaction from capture through funding. It must reconcile three data sources: your internal transaction records, the processor's settlement files (usually delivered as CSV or ISO 8583 formatted files via SFTP), and the bank deposit records. Discrepancies happen regularly, roughly 0.1 to 0.5% of transactions will have mismatches due to timing differences, currency conversions, chargebacks processed after settlement, or processor errors.

Building the Reconciliation Pipeline

Automate reconciliation from day one. Build a nightly batch job that ingests processor settlement files, matches each record to your internal transactions by reference ID, and flags discrepancies. Common mismatch types include: amount differences (usually due to currency conversion or interchange fee adjustments), missing transactions (captured in your system but not in the processor's file), and extra transactions (in the processor's file but not in your system, often from retry logic).

Store all reconciliation data in a dedicated analytics database. Build dashboards that show daily settlement totals, reconciliation match rates, outstanding discrepancies, and aging of unresolved items. Your finance team will live in these dashboards.

Data center servers powering payment settlement and transaction processing infrastructure

Reporting Requirements

Your merchants need transaction reports (real-time and historical), settlement reports (daily funding summaries), dispute reports (chargebacks and their status), and fee reports (processing fees broken down by card type, network, and transaction type). Build a reporting API that supports CSV export, scheduled email delivery, and real-time webhook notifications for key events like settlements, chargebacks, and declines above a threshold.

Costs, Timeline, and Build vs. Buy Decision

Here is the honest breakdown of what building a custom payment gateway costs in 2026:

Development Costs

  • MVP gateway (6 to 9 months, $500K to $800K): Core transaction engine, single processor integration, basic tokenization vault, PCI Level 1 compliance, simple fraud rules, basic reporting. Suitable for a single product or merchant with straightforward payment flows.
  • Production-grade gateway (9 to 15 months, $800K to $1.5M): Everything above plus multi-processor routing, ML fraud scoring, 3D Secure, automated reconciliation, merchant portal, and comprehensive reporting. Handles multiple card networks, currencies, and payment methods.
  • Enterprise payment platform (15 to 24 months, $1.5M to $3M+): Full payment orchestration with dynamic routing, white-label merchant onboarding, real-time risk decisioning, multi-region deployment, and support for alternative payment methods (ACH, wire, digital wallets, BNPL).

Ongoing Operational Costs

Infrastructure runs $15,000 to $40,000 per month depending on volume and redundancy requirements. PCI compliance costs $80,000 to $200,000 annually. You need a dedicated team: at minimum, 2 senior backend engineers, 1 security/compliance specialist, and 1 DevOps engineer. Loaded cost for that team is $600,000 to $900,000 per year.

The Break-Even Calculation

On a third-party gateway like Stripe, you pay approximately 2.9% plus $0.30 per transaction. With your own gateway connecting directly to processors, your cost drops to interchange plus 0.1 to 0.3% (interchange averages 1.7 to 2.1% for credit cards). That savings of roughly 0.8 to 1.2% per transaction is your margin.

At $5M in monthly volume, the savings are $40,000 to $60,000 per month, or roughly $500K to $700K annually. Against total annual operating costs of $1M to $1.5M, you need $10M+ in monthly volume to break even in year one, or $5M+ if you amortize development costs over three years. Below that threshold, use Stripe or Adyen and focus your engineering resources elsewhere.

When to Build

Build your own gateway if you process $100M+ annually, you need custom routing logic that no off-the-shelf solution provides, payment processing is your core product (you are a fintech company), or regulatory requirements demand full control over the payment stack. For everyone else, integrate with an existing gateway and revisit the build decision when volume justifies the investment.

Whether you are building a custom gateway, integrating with existing processors, or figuring out the right payment architecture for your scale, we can help you make the right decision. Book a free strategy call to discuss your payment infrastructure needs.

Need help building this?

Our team has launched 50+ products for startups and ambitious brands. Let's talk about your project.

custom payment gatewaypayment gateway developmentPCI DSS compliancepayment processing architecturefintech infrastructure

Ready to build your product?

Book a free 15-minute strategy call. No pitch, just clarity on your next steps.

Get Started