Skip to main content

Welcome to Payment Gateway

A complete payment processing platform built for scale, security, and learning Payment Gateway is a production-ready microservices ecosystem that handles the full payment lifecycle—from card tokenization to settlement. Built with Go, PostgreSQL, Redis, and Kubernetes, it demonstrates real-world distributed systems architecture while serving as a powerful learning resource.
Live Web Server
https://paymentgateway.redahaloubi.com

What is Payment Gateway?

Payment Gateway is both a functional payment platform and an educational resource showcasing:

Microservices Architecture

7 specialized services communicating via REST and gRPC

PCI-DSS Compliance

Card tokenization, AES-256 encryption, and secure key management

Financial Operations

Multi-currency processing, settlements, and chargeback management

Production Practices

Rate limiting, idempotency, audit logging, and monitoring

Key Features

Payment Operations

  • Authorize: Hold funds without charging (7-day expiry)
  • Capture: Charge previously authorized funds (full or partial)
  • Void: Cancel authorization before capture
  • Refund: Return funds to customer (full or partial)
  • Hosted checkout flow with browser-friendly authentication
  • Client secret-based security (no API keys in browser)
  • Automatic expiration after 1 hour
  • Payment attempt tracking and limits
  • Supported: USD, EUR, MAD (Moroccan Dirham)
  • Automatic currency conversion
  • Real-time exchange rates
  • Processing fees calculated per currency

Security & Compliance

  • PCI-compliant token-based system
  • AES-256-GCM encryption per merchant
  • Card fingerprinting for duplicate detection
  • Single-use tokens for sensitive operations
  • Role-based access control (RBAC)
  • Granular permissions (resource:action format)
  • Multi-tenant support (different roles per merchant)
  • API key management with usage tracking
  • Complete transaction history
  • Event logging for all state changes
  • PCI-compliant activity logs
  • Webhook delivery with retry logic

Developer Experience

  • REST APIs for public merchant access
  • gRPC for high-performance internal communication
  • Hosted checkout page (no PCI scope for merchants)
  • CLI tool for quick testing
  • Idempotency support (24-hour cache)
  • Rate limiting per merchant
  • Comprehensive test cards
  • Webhook notifications with HMAC signatures

System Architecture

High-Level Overview

Payment Gateway consists of 7 core microservices organized into layers based on access level and responsibility.

Service Architecture Layers

External Layer

API Gateway - Single entry point for all requests with CORS, rate limiting, and routing

Public Layer

Auth, Merchant, Payment - REST APIs accessible by merchants with authentication

Internal Layer

Tokenization, Transaction - gRPC-only services with no external access

Service Overview

1. API Gateway (Port 8080)

Entry point for all client requests
  • CORS handling and security headers
  • Request/response logging
  • Rate limiting per merchant (configurable per endpoint)
  • Request routing to backend services
  • Circuit breaking for failing services
  • Per-route rate limits (20 payments/sec, 5 login attempts/min)
  • Request ID generation for tracing
  • Health check aggregation
  • Graceful shutdown with connection draining

2. Auth Service (Port 8001, gRPC: 50051)

Authentication, authorization, and access control
  • User registration and login (JWT tokens)
  • Role-based access control (RBAC)
  • Permission management (resource:action format)
  • API key generation and validation
  • Session management with Redis
  • bcrypt password hashing (cost 10)
  • Account lockout after 5 failed attempts (30-minute lock)
  • Multi-tenant role assignments
  • Redis-cached permissions for fast validation
  • JWT with 24-hour access tokens, 7-day refresh tokens

3. Merchant Service (Port 8002)

Merchant account and team management
  • Merchant onboarding and verification
  • Business profile management
  • Team member invitations and role assignment
  • Payment settings configuration (currencies, webhooks)
  • Multi-merchant support per user
  • Invitation system with email tokens
  • Role-based team permissions (Owner, Admin, Manager, Staff)
  • Webhook configuration per merchant
  • Payment method and currency preferences

4. Payment API Service (Port 8004)

Public payment processing gateway
  • Payment orchestration (authorize, capture, void, refund)
  • Payment Intents for hosted checkout
  • Idempotency handling (24-hour cache)
  • Webhook delivery with retry logic
  • Transaction status tracking
  • Single-step (sale) and multi-step (auth → capture) payments
  • Payment attempt tracking with limits
  • Automatic expiration (1 hour for intents)
  • Test card support for development
  • Rate limiting: 20 payments/sec, 10,000/hour per merchant

5. Tokenization Service (Port 50052 - gRPC Only)

PCI-compliant card tokenization
  • Card data encryption (AES-256-GCM)
  • Token generation and validation
  • Card fingerprinting (SHA-256) for duplicate detection
  • Encryption key rotation (90 days or 1M operations)
  • BIN database lookups
  • Per-merchant encryption keys
  • Single-use tokens for sensitive operations
  • Luhn validation, expiry checks, CVV validation
  • Never logs full PAN or CVV
  • Token lifecycle management (active, expired, revoked, used)

6. Transaction Service (Port 50053 - gRPC Only)

Core payment transaction engine
  • Transaction lifecycle management (state machine)
  • Card simulator for testing (no real card processing)
  • Multi-currency conversion (USD, EUR, MAD)
  • Settlement batch processing (daily at midnight, T+2)
  • Chargeback handling
  • Auto-void expired authorizations (7 days)
  • Processing fee calculation (2.9% + $0.30 in MAD)
  • Daily settlement reports
  • Currency conversion with hourly rate updates
  • Complete transaction event history

7. Payment Checkout (Port 3000)

Hosted checkout application for customers
  • Browser-friendly payment flow
  • Client secret authentication (no API keys exposed)
  • Payment Intent confirmation
  • Redirect to success/cancel URLs
  • Card input validation
  • Built with Next.js 15 and React 19
  • Real-time card validation (Luhn, expiry, CVV)
  • Responsive mobile-first design
  • Automatic expiration handling
  • Success animation with redirect

Complete Payment Flow

Here’s how a payment flows through the entire system:

Flow Breakdown

1

Merchant Creates Payment Intent

Merchant server calls /payment-intents with amount, currency, and redirect URLs. Receives client_secret for browser authentication.
2

Customer Redirected to Checkout

Merchant redirects customer to hosted checkout page with client_secret in URL.
3

Customer Enters Card & Confirms

  • Checkout validates card details client-side (Luhn, expiry, CVV)
  • Sends card data to Payment API (secured by client_secret)
  • Payment API calls Tokenization Service to encrypt card
  • Tokenization returns token (never stores plain card data)
4

Transaction Processing

  • Payment API calls Transaction Service with token
  • Transaction Service simulates card processing
  • Returns authorization code or decline reason
  • Payment API updates intent status
5

Customer Redirected Back

Customer redirected to merchant’s success_url or cancel_url based on result.
6

Webhook Notification

Payment API asynchronously sends webhook to merchant’s configured URL with payment details.

Technology Stack

Backend Services

Language

Go 1.23+ - High-performance, concurrent

HTTP Framework

Gin - Fast HTTP router with middleware

gRPC

Protocol Buffers - Efficient inter-service communication

ORM

GORM - Type-safe database operations

Data Layer

Database

PostgreSQL 15+ - Separate DB per service

Cache

Redis 7+ - Sessions, rate limiting, idempotency

Security

Authentication

JWT (golang-jwt/jwt) - Token-based auth

Encryption

AES-256-GCM - Card data encryption

Hashing

bcrypt (passwords), SHA-256 (fingerprints)

Secrets

HashiCorp Vault (K8s) - Centralized secret management

Infrastructure

Orchestration

Kubernetes (k3d) - Container orchestration

Ingress

NGINX Ingress Controller - Traffic routing

Monitoring

Prometheus + Grafana - Metrics and dashboards

Cloud

AWS EC2 - Production deployment

Frontend

Framework

Next.js 15 - React 19, App Router

Styling

Tailwind CSS - Utility-first CSS

Database Architecture

Each microservice has its own dedicated PostgreSQL database, following microservices best practices:
PostgreSQL Instance
├── auth_db              (Auth Service)
├── merchant_db          (Merchant Service)
├── payment_api_db       (Payment API Service)
├── tokenization_db      (Tokenization Service)
└── transaction_db       (Transaction Service)
Database Isolation Benefits:
  • Independent scaling per service
  • Schema changes don’t cascade
  • Service failures isolated
  • Enhanced security (each service has credentials only to its DB)

Redis Usage

Single Redis instance shared across services for:
  • Session storage (Auth JWT sessions)
  • Rate limiting (API Gateway)
  • Caching (Merchant/Payment data)
  • Idempotency (24-hour request cache)

Security & Compliance

PCI-DSS Compliance

Card Data Protection:
  • Card numbers never logged or stored in plaintext
  • Tokenization reduces PCI scope for merchants
  • AES-256-GCM encryption at rest
  • TLS 1.3 for data in transit

Encryption Strategy

1

Per-Merchant Encryption Keys

Each merchant has unique AES-256 keys stored in HashiCorp Vault (production) or encrypted at rest.
2

Field-Level Encryption

Card number, CVV, and cardholder name encrypted separately with GCM authentication tags.
3

Automatic Key Rotation

Keys rotated every 90 days or after 1 million encryptions (whichever comes first).
4

Card Fingerprinting

SHA-256 hash of card_number + exp_month + exp_year for duplicate detection (never stores PAN).

Authentication Methods

Use Case: Dashboard, merchant portals
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
  • Access Token: 24-hour expiry
  • Refresh Token: 7-day expiry
  • Algorithm: HS256 (HMAC-SHA256)

Deployment Architecture

Production Environment

Live Platform

Hosted on AWS EC2 with Kubernetes orchestration
Infrastructure:
  • Cloud Provider: AWS
  • Instance Type: EC2 (Auto-scaling enabled)
  • Orchestration: Kubernetes (k3d cluster)
  • Ingress: NGINX Ingress Controller with Cloudflare Tunnel
  • TLS: Cloudflare SSL termination
  • Monitoring: Prometheus + Grafana (NodePort access)

Network Architecture

Internet → Cloudflare Tunnel → NGINX Ingress (NodePort 30080)

API Gateway (ClusterIP :8080)

Public Services (Auth, Merchant, Payment)

Internal Services (Tokenization, Transaction)

Databases (PostgreSQL, Redis)
Zero-Trust Networking: All pod-to-pod communication is secured by Kubernetes NetworkPolicies with deny-all-by-default rules.

What’s Next?


Support & Resources


Version: 1.0.0
Last Updated: January 2026
Status: Production Ready