Introduction to Payment Gateways
A crypto payment gateway is a service that enables merchants to accept cryptocurrency payments and optionally convert them to fiat currency. It handles invoice generation, payment detection, confirmation monitoring, and settlement.
Gateway vs. Processor
| Aspect | Payment Gateway | Payment Processor |
|---|---|---|
| Primary Role | Connects merchant to blockchain | Handles actual payment flow |
| Invoice Creation | Yes | No |
| Payment Detection | Via blockchain monitoring | Via gateway notification |
| Settlement | Converts and transfers funds | Manages fund flow |
| Examples | BTCPay Server, NOWPayments | BitPay, Coinbase Commerce |
Gateway Architecture
Merchant API Design
Core API Endpoints
POST /api/v1/invoices Create new payment invoice
GET /api/v1/invoices/:id Get invoice status
GET /api/v1/invoices List all invoices
POST /api/v1/refunds Process refund
GET /api/v1/rates Get exchange rates
GET /api/v1/wallets Get merchant wallets
POST /api/v1/webhooks Register webhook endpoint
GET /api/v1/transactions List transactions
Invoice Creation Request
{
"amount": "50.00",
"currency": "USD",
"accepted_currencies": ["BTC", "ETH", "USDC"],
"title": "Order #12345",
"description": "Product purchase",
"callback_url": "https://merchant.com/webhook",
"redirect_url": "https://merchant.com/success",
"expires_in": 900,
"metadata": {
"order_id": "12345",
"customer_id": "cust_abc"
}
}
Invoice Response
{
"id": "inv_x9k2m4p6",
"status": "pending",
"amount": "50.00",
"currency": "USD",
"addresses": {
"BTC": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
"ETH": "0x742d35Cc6634C0532925a3b844Bc9e7595f2bD3e",
"USDC": "0x742d35Cc6634C0532925a3b844Bc9e7595f2bD3e"
},
"amounts": {
"BTC": "0.001234",
"ETH": "0.020521",
"USDC": "50.00"
},
"qr_codes": {
"BTC": "data:image/png;base64,...",
"ETH": "data:image/png;base64,..."
},
"expires_at": "2024-01-15T12:15:00Z",
"created_at": "2024-01-15T12:00:00Z"
}
Webhook System
Webhooks notify merchants of payment status changes in real-time:
Webhook Payload Structure
{
"event": "invoice.confirmed",
"timestamp": "2024-01-15T12:05:30Z",
"invoice_id": "inv_x9k2m4p6",
"data": {
"status": "confirmed",
"amount_received": "0.001234",
"currency": "BTC",
"txid": "a1b2c3d4e5f6...",
"confirmations": 3,
"amount_usd": "50.00"
},
"signature": "hmac-sha256:abc123..."
}
Webhook Events
| Event | Trigger | Data |
|---|---|---|
invoice.created | Invoice generated | Invoice details |
invoice.paid | Payment detected (0-conf) | TXID, amount |
invoice.confirmed | Required confirmations reached | Final amount |
invoice.expired | Timeout exceeded | Final status |
invoice.refunded | Refund processed | Refund details |
payout.completed | Settlement sent | Payout TXID |
Webhook Security
Verification Process:
1. Extract signature from X-Webhook-Signature header
2. Compute HMAC-SHA256 of request body using API secret
3. Compare computed signature with received signature
4. Reject if signatures don't match
5. Reject if timestamp exceeds 5-minute window (replay protection)
Multi-Coin Support
Supported Blockchain Networks
| Network | Native Token | Confirmation Time | Avg Fee |
|---|---|---|---|
| Bitcoin | BTC | 10â60 min | 5.00 |
| Bitcoin (Lightning) | BTC | <1 second | < $0.01 |
| Ethereum | ETH | 12â15 sec | 50.00 |
| Polygon | MATIC | 2 seconds | < $0.01 |
| Solana | SOL | 400 ms | < $0.01 |
| USDC (Ethereum) | USDC | 12â15 sec | 50.00 |
| USDC (Solana) | USDC | 400 ms | < $0.01 |
| Stellar | XLM | 3â5 sec | < $0.001 |
Address Derivation
HD (Hierarchical Deterministic) wallet derivation for each coin:
BIP-44 Path Structure:
m / purpose' / coin_type' / account' / change / address_index
Examples:
BTC: m/84'/0'/0'/0/0 (Native SegWit)
ETH: m/44'/60'/0'/0/0 (Ethereum)
SOL: m/44'/501'/0'/0' (Solana)
Fiat On-Ramp Integration
Checkout Flow Integration
Hosted Checkout (Redirect)
Flow:
1. Customer clicks "Pay with Crypto"
2. Redirect to gateway hosted page
3. Select currency and complete payment
4. Redirect back to merchant success page
5. Webhook confirms payment to merchant
Inline Checkout (iframe)
Flow:
1. Customer clicks "Pay with Crypto"
2. iframe opens with payment UI
3. Customer completes payment in iframe
4. iframe closes, parent page receives event
5. Webhook confirms payment to merchant
Direct API Integration
Flow:
1. Customer clicks "Pay with Crypto"
2. Merchant calls API to create invoice
3. Display QR code / payment URI
4. Customer pays from wallet
5. Poll API or receive webhook
6. Update order status
Settlement Options
| Settlement Type | Timing | Fee | Best For |
|---|---|---|---|
| Instant Fiat | T+0 | 1â2% | Risk-averse merchants |
| Daily Batch | T+1 | 0.5â1% | Medium volume |
| Weekly Batch | T+7 | 0.25â0.5% | High volume |
| Hold Crypto | None | 0% | Crypto-forward businesses |
| Hybrid (50/50) | T+1 | 0.5â1% | Balanced approach |
Real-World Examples
BTCPay Server
Open-source, self-hosted payment processor. No fees, full control, supports Lightning Network and on-chain Bitcoin. Used by over 10,000 merchants including major open-source projects.
CoinGate
Lithuanian-based gateway supporting 70+ cryptocurrencies. Offers instant fiat conversion, batch settlements, and a merchant dashboard. Processing $50M+ monthly across 5,000+ merchants.
NOWPayments
Non-custodial payment gateway with 150+ supported cryptocurrencies. Features include point-of-sale apps, recurring payments, and API-first design. No KYC required for merchants.
Trade-Offs
| Advantage | Disadvantage |
|---|---|
| Lower fees than cards | Price volatility during settlement |
| Global reach | Regulatory complexity per jurisdiction |
| No chargebacks | Customer support for crypto issues |
| Faster settlements | Integration complexity |
| Access to crypto-native customers | Tax reporting requirements |
Interview Questions
-
Describe the complete architecture of a crypto payment gateway, including all major components and their interactions.
A crypto payment gateway consists of: (1) API Server handling merchant requests; (2) Invoice Manager creating and tracking payment requests; (3) Exchange Rate Service providing real-time pricing; (4) Blockchain Monitor scanning for incoming transactions; (5) Webhook Engine notifying merchants of status changes; (6) Settlement Engine handling payouts; (7) Database storing invoice and transaction data; (8) Security Layer managing authentication and rate limiting. The flow starts with the merchant creating an invoice via API, the gateway generating addresses and amounts, monitoring blockchain for payment, confirming via webhooks, and settling to the merchant's account.
-
How does a payment gateway handle the risk of double-spend attacks on zero-confirmation transactions?
Gateways employ several mitigation strategies: (1) RBF (Replace-By-Fee) detection â monitoring for conflicting transactions; (2) Chain analysis â checking the fee level and mempool position; (3) Lightning Network â for instant, secure payments; (4) Confirmation waiting â requiring 1-3 confirmations for higher-value transactions; (5) Merchant risk scoring â varying confirmation requirements based on transaction history. Most gateways require at least 1 confirmation for Bitcoin but may accept 0-conf for small amounts with Lightning.
-
Explain the webhook retry mechanism and why idempotency is critical for payment gateways.
Webhooks are retried with exponential backoff (e.g., 1min, 5min, 30min, 2hr, 24hr) because merchants' endpoints may be temporarily unavailable. Idempotency ensures duplicate webhooks don't cause duplicate processing (e.g., double-fulfilling an order). Each webhook includes a unique event ID and signature. Merchants must store processed event IDs and reject duplicates. The gateway must also ensure exactly-once delivery semantics despite at-least-once webhook delivery, which requires careful database design with unique constraints.
Quiz Questions
-
What is the primary purpose of HMAC-SHA256 signatures on webhook payloads?
- a) To compress the payload data
- b) To verify the payload hasn't been tampered with and came from the gateway
- c) To encrypt the payment data
- d) To speed up webhook delivery
-
Which settlement option provides the lowest risk for merchants who want to avoid cryptocurrency volatility?
- a) Holding Bitcoin for 90 days
- b) Converting to stablecoins weekly
- c) Instant fiat conversion at payment confirmation
- d) Receiving payments only in USDC
-
In the BIP-44 key derivation path
m/84'/0'/0'/0/0, what does the purpose84'indicate?- a) Ethereum address format
- b) Native SegWit Bitcoin address format
- c) Lightning Network address format
- d) Legacy Bitcoin address format