> ## Documentation Index
> Fetch the complete documentation index at: https://docs-paymentgateway.redahaloubi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Introduction

> A modern, microservices-based payment gateway demonstrating production-ready architecture and PCI compliance

# 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.

<Tab title="Live Web Server" icon="globe">
  ```
  https://paymentgateway.redahaloubi.com
  ```
</Tab>

***

## What is Payment Gateway?

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

<CardGroup cols={2}>
  <Card title="Microservices Architecture" icon="diagram-project">
    7 specialized services communicating via REST and gRPC
  </Card>

  <Card title="PCI-DSS Compliance" icon="shield-check">
    Card tokenization, AES-256 encryption, and secure key management
  </Card>

  <Card title="Financial Operations" icon="money-bill-transfer">
    Multi-currency processing, settlements, and chargeback management
  </Card>

  <Card title="Production Practices" icon="gear">
    Rate limiting, idempotency, audit logging, and monitoring
  </Card>
</CardGroup>

***

## Key Features

### Payment Operations

<AccordionGroup>
  <Accordion title="Authorization & Capture" icon="credit-card">
    * **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)
  </Accordion>

  <Accordion title="Payment Intents" icon="browser">
    * 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
  </Accordion>

  <Accordion title="Multi-Currency Support" icon="globe">
    * **Supported**: USD, EUR, MAD (Moroccan Dirham)
    * Automatic currency conversion
    * Real-time exchange rates
    * Processing fees calculated per currency
  </Accordion>
</AccordionGroup>

### Security & Compliance

<AccordionGroup>
  <Accordion title="Card Tokenization" icon="lock">
    * PCI-compliant token-based system
    * AES-256-GCM encryption per merchant
    * Card fingerprinting for duplicate detection
    * Single-use tokens for sensitive operations
  </Accordion>

  <Accordion title="Access Control" icon="users-gear">
    * Role-based access control (RBAC)
    * Granular permissions (resource:action format)
    * Multi-tenant support (different roles per merchant)
    * API key management with usage tracking
  </Accordion>

  <Accordion title="Audit & Compliance" icon="file-shield">
    * Complete transaction history
    * Event logging for all state changes
    * PCI-compliant activity logs
    * Webhook delivery with retry logic
  </Accordion>
</AccordionGroup>

### Developer Experience

<AccordionGroup>
  <Accordion title="Multiple Integration Options" icon="code">
    * 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
  </Accordion>

  <Accordion title="Developer-Friendly Features" icon="toolbox">
    * Idempotency support (24-hour cache)
    * Rate limiting per merchant
    * Comprehensive test cards
    * Webhook notifications with HMAC signatures
  </Accordion>
</AccordionGroup>

***

## System Architecture

### High-Level Overview

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

```mermaid theme={null}
graph TB
    Client[Client Applications<br/>Dashboard, Mobile, CLI]
    
    subgraph External["🌐 External Layer"]
        Gateway[API Gateway<br/>Port 8080<br/>REST]
    end
    
    subgraph Public["📡 Public Services Layer"]
        Auth[Auth Service<br/>Port 8001<br/>REST + gRPC]
        Merchant[Merchant Service<br/>Port 8002<br/>REST]
        Payment[Payment API<br/>Port 8004<br/>REST]
    end
    
    subgraph Internal["🔒 Internal Services Layer"]
        Token[Tokenization Service<br/>Port 50052<br/>gRPC Only]
        Transaction[Transaction Service<br/>Port 50053<br/>gRPC Only]
    end
    
    subgraph Data["💾 Data Layer"]
        Postgres[(PostgreSQL<br/>Separate DBs per Service)]
        Redis[(Redis<br/>Cache & Sessions)]
    end
    
    Client -->|HTTPS| Gateway
    Gateway -->|HTTP| Auth
    Gateway -->|HTTP| Merchant
    Gateway -->|HTTP| Payment
    
    Auth -->|gRPC| Token
    Merchant -->|gRPC| Auth
    Payment -->|gRPC| Token
    Payment -->|gRPC| Transaction
    Transaction -->|gRPC| Token
    
    Auth -->|SQL| Postgres
    Merchant -->|SQL| Postgres
    Payment -->|SQL| Postgres
    Token -->|SQL| Postgres
    Transaction -->|SQL| Postgres
    
    Auth -->|Cache| Redis
    Merchant -->|Cache| Redis
    Payment -->|Cache| Redis
    Token -->|Cache| Redis
    Transaction -->|Cache| Redis
    
    style Gateway fill:#4CAF50
    style Auth fill:#2196F3
    style Merchant fill:#2196F3
    style Payment fill:#2196F3
    style Token fill:#FF9800
    style Transaction fill:#FF9800
    style Postgres fill:#9C27B0
    style Redis fill:#F44336
```

### Service Architecture Layers

<CardGroup cols={3}>
  <Card title="External Layer" icon="globe">
    **API Gateway** - Single entry point for all requests with CORS, rate limiting, and routing
  </Card>

  <Card title="Public Layer" icon="wifi">
    **Auth, Merchant, Payment** - REST APIs accessible by merchants with authentication
  </Card>

  <Card title="Internal Layer" icon="lock">
    **Tokenization, Transaction** - gRPC-only services with no external access
  </Card>
</CardGroup>

***

## Service Overview

### 1. API Gateway (Port 8080)

**Entry point for all client requests**

<Accordion title="Responsibilities">
  * 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
</Accordion>

<Accordion title="Key Features">
  * Per-route rate limits (20 payments/sec, 5 login attempts/min)
  * Request ID generation for tracing
  * Health check aggregation
  * Graceful shutdown with connection draining
</Accordion>

***

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

**Authentication, authorization, and access control**

<Accordion title="Responsibilities">
  * 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
</Accordion>

<Accordion title="Key Features">
  * 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
</Accordion>

***

### 3. Merchant Service (Port 8002)

**Merchant account and team management**

<Accordion title="Responsibilities">
  * Merchant onboarding and verification
  * Business profile management
  * Team member invitations and role assignment
  * Payment settings configuration (currencies, webhooks)
  * Multi-merchant support per user
</Accordion>

<Accordion title="Key Features">
  * Invitation system with email tokens
  * Role-based team permissions (Owner, Admin, Manager, Staff)
  * Webhook configuration per merchant
  * Payment method and currency preferences
</Accordion>

***

### 4. Payment API Service (Port 8004)

**Public payment processing gateway**

<Accordion title="Responsibilities">
  * Payment orchestration (authorize, capture, void, refund)
  * Payment Intents for hosted checkout
  * Idempotency handling (24-hour cache)
  * Webhook delivery with retry logic
  * Transaction status tracking
</Accordion>

<Accordion title="Key Features">
  * 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
</Accordion>

***

### 5. Tokenization Service (Port 50052 - gRPC Only)

**PCI-compliant card tokenization**

<Accordion title="Responsibilities">
  * 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
</Accordion>

<Accordion title="Key Features">
  * 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)
</Accordion>

***

### 6. Transaction Service (Port 50053 - gRPC Only)

**Core payment transaction engine**

<Accordion title="Responsibilities">
  * 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
</Accordion>

<Accordion title="Key Features">
  * 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
</Accordion>

***

### 7. Payment Checkout (Port 3000)

**Hosted checkout application for customers**

<Accordion title="Responsibilities">
  * Browser-friendly payment flow
  * Client secret authentication (no API keys exposed)
  * Payment Intent confirmation
  * Redirect to success/cancel URLs
  * Card input validation
</Accordion>

<Accordion title="Key Features">
  * 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
</Accordion>

***

## Complete Payment Flow

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

```mermaid theme={null}
sequenceDiagram
    participant M as Merchant
    participant API as API Gateway
    participant Auth as Auth Service
    participant Pay as Payment API
    participant Token as Tokenization
    participant Txn as Transaction
    participant DB as Database
    
    Note over M,DB: 1. Merchant Creates Payment Intent
    M->>API: POST /payment-intents<br/>(API Key auth)
    API->>Auth: Validate API Key
    Auth-->>API: ✓ Valid
    API->>Pay: Create Intent
    Pay->>DB: Store Intent
    Pay-->>M: {client_secret, checkout_url}
    
    Note over M,DB: 2. Customer Redirected to Checkout
    M->>M: Redirect to checkout_url
    
    Note over M,DB: 3. Customer Confirms Payment
    M->>API: POST /payment-intents/:id/confirm<br/>(client_secret auth)
    API->>Pay: Validate client_secret
    Pay->>Token: Tokenize Card (gRPC)
    Token->>Token: Encrypt (AES-256-GCM)
    Token->>DB: Store Token
    Token-->>Pay: {token}
    
    Pay->>Txn: Authorize Transaction (gRPC)
    Txn->>Txn: Simulate Card Processing
    Txn->>DB: Store Transaction
    Txn-->>Pay: {auth_code, status}
    
    Pay->>DB: Update Intent (authorized)
    Pay-->>M: {redirect_url: success_url}
    
    Note over M,DB: 4. Webhook Notification (Async)
    Pay->>M: POST merchant_webhook_url<br/>{event: payment.authorized}
```

### Flow Breakdown

<Steps>
  <Step title="Merchant Creates Payment Intent">
    Merchant server calls `/payment-intents` with amount, currency, and redirect URLs. Receives `client_secret` for browser authentication.
  </Step>

  <Step title="Customer Redirected to Checkout">
    Merchant redirects customer to hosted checkout page with `client_secret` in URL.
  </Step>

  <Step title="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)
  </Step>

  <Step title="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
  </Step>

  <Step title="Customer Redirected Back">
    Customer redirected to merchant's `success_url` or `cancel_url` based on result.
  </Step>

  <Step title="Webhook Notification">
    Payment API asynchronously sends webhook to merchant's configured URL with payment details.
  </Step>
</Steps>

***

## Technology Stack

### Backend Services

<CardGroup cols={2}>
  <Card title="Language" icon="golang">
    **Go 1.23+** - High-performance, concurrent
  </Card>

  <Card title="HTTP Framework" icon="server">
    **Gin** - Fast HTTP router with middleware
  </Card>

  <Card title="gRPC" icon="bolt">
    **Protocol Buffers** - Efficient inter-service communication
  </Card>

  <Card title="ORM" icon="database">
    **GORM** - Type-safe database operations
  </Card>
</CardGroup>

### Data Layer

<CardGroup cols={2}>
  <Card title="Database" icon="database">
    **PostgreSQL 15+** - Separate DB per service
  </Card>

  <Card title="Cache" icon="memory">
    **Redis 7+** - Sessions, rate limiting, idempotency
  </Card>
</CardGroup>

### Security

<CardGroup cols={2}>
  <Card title="Authentication" icon="key">
    **JWT** (golang-jwt/jwt) - Token-based auth
  </Card>

  <Card title="Encryption" icon="shield">
    **AES-256-GCM** - Card data encryption
  </Card>

  <Card title="Hashing" icon="lock">
    **bcrypt** (passwords), **SHA-256** (fingerprints)
  </Card>

  <Card title="Secrets" icon="vault">
    **HashiCorp Vault** (K8s) - Centralized secret management
  </Card>
</CardGroup>

### Infrastructure

<CardGroup cols={2}>
  <Card title="Orchestration" icon="dharmachakra">
    **Kubernetes (k3d)** - Container orchestration
  </Card>

  <Card title="Ingress" icon="globe">
    **NGINX Ingress Controller** - Traffic routing
  </Card>

  <Card title="Monitoring" icon="chart-line">
    **Prometheus + Grafana** - Metrics and dashboards
  </Card>

  <Card title="Cloud" icon="cloud">
    **AWS EC2** - Production deployment
  </Card>
</CardGroup>

### Frontend

<CardGroup cols={2}>
  <Card title="Framework" icon="react">
    **Next.js 15** - React 19, App Router
  </Card>

  <Card title="Styling" icon="paintbrush">
    **Tailwind CSS** - Utility-first CSS
  </Card>
</CardGroup>

***

## 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)
```

<Info>
  **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)
</Info>

### 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

<Warning>
  **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
</Warning>

### Encryption Strategy

<Steps>
  <Step title="Per-Merchant Encryption Keys">
    Each merchant has unique AES-256 keys stored in HashiCorp Vault (production) or encrypted at rest.
  </Step>

  <Step title="Field-Level Encryption">
    Card number, CVV, and cardholder name encrypted separately with GCM authentication tags.
  </Step>

  <Step title="Automatic Key Rotation">
    Keys rotated every 90 days or after 1 million encryptions (whichever comes first).
  </Step>

  <Step title="Card Fingerprinting">
    SHA-256 hash of `card_number + exp_month + exp_year` for duplicate detection (never stores PAN).
  </Step>
</Steps>

### Authentication Methods

<Tabs>
  <Tab title="JWT Tokens">
    **Use Case:** Dashboard, merchant portals

    ```http theme={null}
    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
    ```

    * **Access Token:** 24-hour expiry
    * **Refresh Token:** 7-day expiry
    * **Algorithm:** HS256 (HMAC-SHA256)
  </Tab>

  <Tab title="API Keys">
    **Use Case:** Server-to-server integration

    ```http theme={null}
    X-API-Key: pk_live_abc123def456...
    ```

    * **Production:** `pk_live_...` (64 random chars)
    * **Test:** `pk_test_...` (64 random chars)
    * **Storage:** SHA-256 hashed in database
  </Tab>

  <Tab title="Client Secrets">
    **Use Case:** Browser checkout (Payment Intents)

    ```http theme={null}
    X-Client-Secret: pi_abc123_secret_def456...
    ```

    * **Format:** `pi_{intent_id}_secret_{random}`
    * **Expiry:** 1 hour
    * **Purpose:** Authenticate customers without exposing API keys
  </Tab>
</Tabs>

***

## Deployment Architecture

### Production Environment

<Card title="Live Platform" icon="aws" href="https://paymentgateway.redahaloubi.com">
  Hosted on AWS EC2 with Kubernetes orchestration
</Card>

**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)
```

<Info>
  **Zero-Trust Networking:** All pod-to-pod communication is secured by Kubernetes NetworkPolicies with deny-all-by-default rules.
</Info>

***

## What's Next?

<CardGroup cols={2}>
  <Card title="Quick Start" icon="rocket" href="/get-started/quick-start">
    Create your first payment intent in 5 minutes
  </Card>

  <Card title="Auth API" icon="key" href="/api/auth">
    User registration, login, and API key management
  </Card>

  <Card title="Merchant API" icon="store" href="/api/merchant-api">
    Manage merchant accounts and team members
  </Card>

  <Card title="Payment API" icon="credit-card" href="/api/payment-api">
    Process payments, refunds, and manage transactions
  </Card>
</CardGroup>

***

## Support & Resources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/rhaloubi/Payment-Gateway">
    View source code and report issues
  </Card>

  <Card title="Email Support" icon="envelope" href="mailto:redahaloubi8@gmail.com">
    Contact for technical support
  </Card>

  <Card title="Kubernetes Guide" icon="dharmachakra" href="/deployment/kubernetes">
    Deploy to production with K8s
  </Card>

  <Card title="CLI Tool" icon="terminal" href="/tools/cli">
    Command-line interface for testing
  </Card>
</CardGroup>

***

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