← Back to Lego Blocks
Payment Gateway

Secure Payment Processing

Enterprise-grade payment gateway with tokenization, multiple payment methods, recurring billing, refunds, fraud detection, and PCI compliance for modern applications.

PCI-DSS Level 1
Sub-second Processing
99.99% Uptime

Overview

A production-ready payment gateway that handles the complete payment lifecycle from tokenization to settlement with security and compliance built-in.

Must-Have Features

  • Tokenization - Never store raw card numbers, use provider tokens (Stripe, PayPal)
  • Multiple payment methods - Credit/debit cards, ACH, digital wallets (Apple Pay, Google Pay)
  • One-time charges - Process immediate payments with automatic retry on failure
  • Refunds & voids - Full/partial refunds with automatic dispute handling
  • Transaction history - Complete audit trail with status tracking and reconciliation
  • Webhooks - Real-time event notifications for payment lifecycle events
  • Multi-currency - Support 135+ currencies with automatic conversion
  • Fraud detection - Built-in Radar rules, 3D Secure, address verification (AVS)

Nice-to-Have Features

  • Recurring billing - Subscription management with automatic renewals and proration
  • Payment links - Generate shareable links for invoice payments
  • Dispute management - Handle chargebacks with evidence submission and tracking
  • Saved payment methods - Securely store customer cards for future use
  • Payment intent tracking - Monitor payment lifecycle from created to succeeded
  • Compliance reporting - PCI-DSS audit logs and compliance certificates

Architecture

Four-tier architecture with React frontend, Node.js backend, PostgreSQL database, and multi-provider payment integration layer.

Frontend Layer

React with Stripe Elements SDK

  • Stripe Elements - Pre-built, PCI-compliant card input components
  • Payment method selection - Cards, ACH, wallets with dynamic forms
  • Client-side validation - Real-time validation before tokenization
  • Payment confirmation - Handle 3D Secure redirects and challenges
  • Saved cards UI - Display and manage tokenized payment methods

Backend Layer

Node.js/Express with Stripe SDK

  • Payment Intent API - Create, confirm, and capture payment intents
  • Customer management - CRUD operations for customers and payment methods
  • Subscription engine - Create/update/cancel subscriptions with proration
  • Refund processor - Process full/partial refunds with idempotency
  • Webhook handler - Verify signatures and process async events
  • Fraud detection - Integrate Stripe Radar rules and risk scoring

Data Layer

PostgreSQL with audit trail

  • Transaction records - Store metadata, amounts, statuses, timestamps
  • Customer profiles - Link internal users to Stripe customer IDs
  • Subscription tracking - Store plan details, billing cycles, status
  • Webhook events - Log all incoming events for debugging and replay
  • Audit log - Track all payment operations with user attribution

Integration Layer

Multi-provider support

  • Stripe connector - Primary payment processor with full feature set
  • PayPal connector - Alternative provider for PayPal wallet payments
  • Provider abstraction - Unified interface to swap providers without code changes
  • Webhook relay - Route provider webhooks to internal event handlers
  • Retry logic - Exponential backoff for failed payment attempts

Payment Methods

Support all major payment methods with intelligent fallbacks and conversion-optimized checkout flows.

Credit & Debit Cards

Visa, Mastercard, Amex, Discover

  • Tokenization with Stripe Elements
  • 3D Secure authentication (SCA compliance)
  • Address verification (AVS)
  • CVV validation
  • Saved cards with customer consent

ACH/Bank Transfers

Direct bank account debits

  • Plaid integration for instant verification
  • Microdeposit verification fallback
  • 2-5 day settlement window
  • Lower transaction fees (0.8% vs 2.9%)
  • Recurring billing support

Digital Wallets

Apple Pay, Google Pay, Link

  • One-tap checkout experience
  • Biometric authentication
  • Pre-filled shipping/billing info
  • Higher conversion rates (25%+)
  • Mobile-optimized flows

Alternative Methods

PayPal, Afterpay, Buy Now Pay Later

  • PayPal wallet integration
  • Installment payment plans
  • Regional payment methods (iDEAL, SEPA)
  • Crypto payments (optional)
  • Gift cards and credits

Database Schema

PostgreSQL schema with six core tables for customers, payment methods, transactions, subscriptions, refunds, and webhook events.

customers

Customer profiles linked to payment provider

id (UUID, PK)
user_id (FK to users table)
stripe_customer_id (unique)
email
default_payment_method_id
created_at, updated_at

payment_methods

Tokenized payment methods

id (UUID, PK)
customer_id (FK)
stripe_payment_method_id (unique)
type (card, ach, wallet)
last4
brand (visa, mastercard, etc.)
exp_month, exp_year
is_default (boolean)
created_at

transactions

Payment transaction records

id (UUID, PK)
customer_id (FK)
stripe_payment_intent_id (unique)
amount (integer, in cents)
currency
status (pending, succeeded, failed, refunded)
payment_method_id (FK)
description
metadata (JSONB)
failure_code, failure_message
created_at, updated_at

subscriptions

Recurring billing subscriptions

id (UUID, PK)
customer_id (FK)
stripe_subscription_id (unique)
plan_id (FK to subscription_plans)
status (active, canceled, past_due)
current_period_start, current_period_end
cancel_at_period_end (boolean)
trial_end
created_at, updated_at, canceled_at

refunds

Refund transactions

id (UUID, PK)
transaction_id (FK)
stripe_refund_id (unique)
amount (integer, in cents)
reason (duplicate, fraudulent, requested_by_customer)
status (pending, succeeded, failed)
created_at

webhook_events

Incoming webhook events from payment provider

id (UUID, PK)
stripe_event_id (unique)
type (payment_intent.succeeded, etc.)
payload (JSONB)
processed (boolean)
processed_at
created_at

⚠️Indexing Strategy

  • • Index on stripe_* IDs for fast lookup during webhook processing
  • • Index on customer_id for transaction/subscription queries
  • • Composite index on (customer_id, status) for filtering active subscriptions
  • • Index on created_at for time-range queries and reporting
  • • Partial index on webhook_events where processed = false

Payment Flow

Five-step payment processing flow from intent creation to fulfillment with secure tokenization and webhook confirmation.

1

Create Payment Intent

Backend creates payment intent with amount and currency

  • POST /api/payments/create-intent
  • Generate client_secret for frontend
  • Set metadata (order_id, user_id)
  • Configure automatic payment methods
2

Collect Payment Details

Frontend renders Stripe Elements and collects card info

  • Mount CardElement component
  • Client-side validation (card number, exp, CVV)
  • Never send raw card data to your server
  • Handle user input errors gracefully
3

Confirm Payment

Frontend confirms payment with Stripe using client secret

  • stripe.confirmCardPayment(clientSecret)
  • Handle 3D Secure authentication flow
  • Stripe tokenizes card and processes payment
  • Returns payment_intent with status
4

Handle Webhook

Stripe sends webhook event to your backend

  • payment_intent.succeeded event received
  • Verify webhook signature (HMAC)
  • Update transaction status in database
  • Fulfill order/grant access to product
5

Update UI

Frontend polls or receives confirmation of success

  • GET /api/payments/:id to check status
  • Display success message to user
  • Redirect to confirmation page
  • Send email receipt (optional)

Security & Compliance

Enterprise-grade security with PCI-DSS compliance, tokenization, fraud detection, and dispute management built-in.

PCI-DSS Compliance

Level 1 certification through Stripe

  • Never store raw card numbers - use tokens only
  • Stripe Elements are PCI-compliant by design
  • SAQ-A compliance questionnaire (lightest burden)
  • Automatic security updates from Stripe
  • Annual compliance audits handled by Stripe

Tokenization & Encryption

Secure handling of sensitive data

  • Client-side tokenization before data leaves browser
  • TLS 1.2+ for all API communication
  • Encrypted payment method storage
  • Tokenized references stored in your database
  • Automatic key rotation by provider

Fraud Detection

Built-in Stripe Radar protection

  • Machine learning-based risk scoring
  • 3D Secure (SCA) for European cards
  • Address verification system (AVS)
  • CVV validation on all card payments
  • Velocity checks for repeated attempts
  • Block high-risk countries/BINs

Dispute Management

Handle chargebacks automatically

  • Automatic dispute notification via webhook
  • Evidence submission portal for merchants
  • Chargeback liability shift with 3D Secure
  • Dispute analytics and win rate tracking
  • Integration with fraud detection to prevent future disputes

Recurring Billing & Subscriptions

Full-featured subscription management with automatic renewals, smart retry logic, proration, and lifecycle management.

Recurring Billing

  • Create subscriptions with monthly/yearly intervals
  • Automatic charge on renewal date
  • Prorated upgrades/downgrades
  • Trial periods with automatic conversion
  • Grace period for failed payments

Billing Cycles

  • Configurable billing intervals (day, week, month, year)
  • Anchor dates for consistent billing (e.g., 1st of month)
  • Proration logic for mid-cycle changes
  • Billing cycle notifications
  • Custom billing schedules

Payment Retry Logic

  • Smart retry for failed renewals (4 attempts over 3 weeks)
  • Update payment method during grace period
  • Dunning emails to recover failed payments
  • Automatic pause after max retries
  • Reactivate after payment update

Subscription Management

  • Cancel immediately or at period end
  • Pause/resume subscriptions
  • Change plan with proration
  • Add-ons and metered usage
  • Subscription lifecycle webhooks

Webhook Events

Real-time event notifications from Stripe for payment lifecycle events with signature verification and idempotent processing.

payment_intent.succeeded

Payment completed successfully

Fulfill order, grant access, send receipt
payment_intent.payment_failed

Payment attempt failed

Notify customer, update UI, log failure reason
customer.subscription.created

New subscription started

Activate subscription features, send welcome email
customer.subscription.updated

Subscription plan changed

Update subscription status, apply proration
customer.subscription.deleted

Subscription canceled

Revoke access, send cancellation email
invoice.payment_succeeded

Subscription renewal paid

Extend subscription period, send invoice
invoice.payment_failed

Subscription renewal failed

Trigger retry logic, send dunning email
charge.refunded

Payment refunded

Update transaction status, notify customer
charge.dispute.created

Chargeback initiated

Notify merchant, prepare evidence

⚠️Webhook Best Practices

  • • Verify webhook signature using Stripe signing secret (HMAC-SHA256)
  • • Use idempotency keys to prevent duplicate processing
  • • Return 200 immediately, process async to avoid timeouts
  • • Store webhook events in database for replay and debugging
  • • Set up webhook endpoint at /api/webhooks/stripe
  • • Monitor webhook delivery in Stripe Dashboard

API Endpoints

RESTful API with nine endpoints for payment intents, refunds, customer management, subscriptions, and webhook handling.

POST
/api/payments/create-intent

Create a payment intent with amount and metadata

Request
{ "amount": 1000, "currency": "usd", "metadata": { "order_id": "123" } }
Response
{ "client_secret": "pi_xxx_secret_yyy", "id": "pi_xxx" }
POST
/api/payments/confirm

Confirm payment intent after frontend tokenization

Request
{ "payment_intent_id": "pi_xxx", "payment_method": "pm_xxx" }
Response
{ "status": "succeeded", "transaction_id": "uuid" }
GET
/api/payments/:id

Get payment status and details

Request
GET /api/payments/uuid
Response
{ "status": "succeeded", "amount": 1000, "created_at": "2025-01-15T10:00:00Z" }
POST
/api/payments/:id/refund

Process full or partial refund

Request
{ "amount": 500, "reason": "requested_by_customer" }
Response
{ "refund_id": "re_xxx", "status": "succeeded" }
POST
/api/customers/:id/payment-methods

Attach payment method to customer for future use

Request
{ "payment_method_id": "pm_xxx", "set_as_default": true }
Response
{ "id": "pm_xxx", "last4": "4242", "brand": "visa" }
POST
/api/subscriptions

Create recurring subscription

Request
{ "customer_id": "cus_xxx", "plan_id": "plan_xxx", "trial_days": 14 }
Response
{ "id": "sub_xxx", "status": "trialing", "current_period_end": "2025-01-29" }
PATCH
/api/subscriptions/:id

Update subscription plan with proration

Request
{ "plan_id": "plan_yyy", "proration_behavior": "create_prorations" }
Response
{ "id": "sub_xxx", "status": "active", "plan_id": "plan_yyy" }
DELETE
/api/subscriptions/:id

Cancel subscription immediately or at period end

Request
{ "cancel_at_period_end": true }
Response
{ "id": "sub_xxx", "status": "active", "cancel_at_period_end": true }
POST
/api/webhooks/stripe

Webhook endpoint for Stripe events (signature verified)

Request
Stripe-Signature header + JSON payload
Response
{ "received": true }

React UI Components

Four key pages for checkout, payment method management, subscription dashboard, and admin transaction logging.

Checkout Page

Payment form with Stripe Elements

  • Embedded CardElement with real-time validation
  • Payment method selection (card, ACH, wallets)
  • Order summary with itemized breakdown
  • 3D Secure authentication flow
  • Success/error handling with retry option

Payment Methods

Manage saved cards and bank accounts

  • List all saved payment methods
  • Add new payment method with tokenization
  • Set default payment method
  • Remove payment method with confirmation
  • Display last4, brand, expiry for cards

Subscription Dashboard

Manage active subscriptions

  • Current plan details with billing cycle
  • Upgrade/downgrade options with pricing preview
  • Cancel subscription (immediate or at period end)
  • Pause/resume subscription
  • View upcoming invoice and payment history

Admin Transaction Log

View all payment transactions

  • Filterable table (status, date range, customer)
  • Transaction details with metadata
  • Refund action button with amount input
  • Export to CSV for accounting
  • Webhook event log for debugging

Production Benefits

Enterprise-grade payment infrastructure that increases conversion, reduces fraud, and ensures compliance from day one.

Key Benefits

  • PCI-DSS Level 1 compliant through Stripe - no SAQ-D burden on your team
  • Multiple payment methods increase conversion by 25%+ (cards, ACH, wallets)
  • Automatic retry logic for failed payments recovers 30-40% of revenue
  • 3D Secure reduces fraud disputes by 87% while meeting SCA requirements
  • Subscription management with smart dunning recovers 70% of failed renewals
  • Webhook-driven architecture ensures reliable order fulfillment
  • Multi-currency support enables global payments in 135+ currencies
  • Fraud detection with Stripe Radar blocks 99.9% of fraudulent attempts

Definition of Done

  • Payment intents successfully process cards, ACH, and digital wallets
  • Tokenization working - no raw card data touches your servers
  • 3D Secure authentication flow completes for European cards
  • Webhooks verified with signature checking and processed idempotently
  • Refunds processed (full/partial) with automatic dispute handling
  • Subscriptions create, renew, and cancel with proration logic
  • Failed payment retry logic triggers with dunning emails
  • Admin dashboard displays transaction log with filtering and refund actions
  • PCI-DSS SAQ-A questionnaire completed and stored
  • Multi-currency support tested with at least 3 currencies

Build Your Next Product With AI Expertise

Experience the future of software development. Let our GenAI platform accelerate your next project.

Schedule a Free AI Blueprint Session