Project 6: Full Payment Processing Simulator (Capstone)
Goal: Build practical expertise in payment security by implementing core controls (validation, tokenization, encryption), understanding PCI scope, and producing auditable, compliant artifacts.
Payment Data Boundaries
Payment systems live or die by data boundaries: where PANs can exist, how they move, and who can touch them. You need to draw a clear boundary between the Cardholder Data Environment (CDE) and everything else to reduce scope and risk.
Cryptographic Controls and Key Management
Payments rely on strong symmetric encryption, deterministic tokenization, and strict key lifecycle controls. Key custody, rotation, and HSM-backed operations are as important as the algorithms themselves.
Transaction Flow and Compliance Guarantees
Authorization, capture, and settlement have different security requirements. Compliance (PCI DSS, PCI PIN, 3DS) enforces minimal guarantees that must be reflected in system design.
Concept Summary Table
| Concept Cluster | What You Need to Internalize |
|---|---|
| Data classification | PAN vs token, CDE boundaries, data minimization. |
| Cryptography | AES, KDFs, tokenization, key hierarchy. |
| Transaction security | Auth vs settlement, 3DS, P2PE. |
| Compliance | PCI DSS scope, audit controls, evidence. |
| Risk controls | Rate limits, fraud signals, logging. |
Deep Dive Reading by Concept
| Concept | Book & Chapter |
|---|---|
| PCI DSS | PCI DSS v4.0 — Requirements overview |
| Tokenization | PCI Tokenization Guidelines — Implementation sections |
| Crypto in payments | Cryptography Engineering — Ch. 6-9 |
| Payment flows | Payment Systems in the U.S. — transaction chapters |
| Fraud controls | The Anatomy of the Payment Card Industry — risk sections |
Project Overview
| Attribute | Value |
|---|---|
| Difficulty | Level 5: Expert |
| Time Estimate | 2-3 months |
| Programming Language | Multi-language (system components) |
| Knowledge Area | Full Payment Ecosystem |
| Key Technologies | All previous projects + Settlement, Fraud Detection |
| Coolness Level | Level 5: Industry Expert |
| Business Potential | 5. Deep Domain Expertise |
Learning Objectives
By completing this capstone project, you will:
- Build a complete payment ecosystem - All parties from merchant to issuer
- Understand multi-party cryptographic trust - Each party’s keys and certificates
- Implement authorization AND settlement - Dual-message transaction flow
- Handle chargebacks and disputes - What happens when security fails
- Integrate fraud detection - Risk scoring and decision rules
- Master the four-party model - Merchant, Acquirer, Network, Issuer
The Core Question You’re Answering
“How does money actually move when you swipe a credit card?”
Most developers understand authorization (“card approved”), but that’s only half the story. This project teaches the complete flow from card swipe to money in the merchant’s bank account.
┌─────────────────────────────────────────────────────────────────────────┐
│ THE COMPLETE PAYMENT LIFECYCLE │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ PHASE 1: AUTHORIZATION (milliseconds) │
│ ══════════════════════════════════════ │
│ "Can this card pay $100?" │
│ │
│ Customer → Merchant → Acquirer → Network → Issuer │
│ └──────────────────────────────────────────┘ │
│ "APPROVED" or "DECLINED" │
│ │
│ NO MONEY MOVES YET! Just a promise from the issuer. │
│ │
│ ───────────────────────────────────────────────────────────────────── │
│ │
│ PHASE 2: CAPTURE (hours later) │
│ ══════════════════════════════ │
│ "I'm ready to collect that $100" │
│ │
│ Merchant → Acquirer: "Here's my authorized transaction" │
│ (Batch of all day's transactions) │
│ │
│ STILL NO MONEY MOVES! Just confirmation to collect. │
│ │
│ ───────────────────────────────────────────────────────────────────── │
│ │
│ PHASE 3: CLEARING (that night) │
│ ═════════════════════════════ │
│ "Everyone reconcile your transactions" │
│ │
│ Acquirer → Network: "I have $1M in Visa transactions" │
│ Network: "Let me match these with issuers..." │
│ Network → Issuer: "Your cardholders spent $500K" │
│ │
│ NUMBERS ARE AGREED, but still no money. │
│ │
│ ───────────────────────────────────────────────────────────────────── │
│ │
│ PHASE 4: SETTLEMENT (next business day) │
│ ═══════════════════════════════════════ │
│ "Move the money!" │
│ │
│ Issuer Bank → Fed Wire → Acquiring Bank │
│ │
│ FINALLY: Money moves from cardholder's bank to merchant's bank │
│ │
│ Total time: 1-3 business days │
│ │
└─────────────────────────────────────────────────────────────────────────┘
Deep Theoretical Foundation
1. The Four-Party Model
┌─────────────────────────────────────────────────────────────────────────┐
│ FOUR-PARTY MODEL │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ CARDHOLDER │ │ MERCHANT │ │
│ │ │ │ │ │
│ │ Has card │◄─────PURCHASE──────────►│ Sells goods │ │
│ │ from issuer │ │ │ │
│ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │
│ │ Account │ Account │
│ │ relationship │ relationship │
│ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ ISSUER │ │ ACQUIRER │ │
│ │ │ │ │ │
│ │ Cardholder's│◄────SETTLEMENT──────────►│ Merchant's │ │
│ │ bank │ │ bank │ │
│ │ │ │ │ │
│ │ • Issues │ │ • Processes │ │
│ │ cards │ │ payments │ │
│ │ • Authorizes│ │ • Settles │ │
│ │ purchases │ │ funds │ │
│ │ • Bears │ │ │ │
│ │ credit │ │ │ │
│ │ risk │ │ │ │
│ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │
│ │ │ │
│ └─────────────────┬───────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ CARD NETWORK │ │
│ │ (Visa, MC) │ │
│ │ │ │
│ │ • Routes auth │ │
│ │ • Clears txns │ │
│ │ • Sets rules │ │
│ │ • Manages │ │
│ │ disputes │ │
│ └──────────────────┘ │
│ │
│ MONEY FLOW: │
│ Cardholder ──► Issuer ──► Network ──► Acquirer ──► Merchant │
│ (credit) (settlement) (settlement) (deposit) │
│ │
│ FEE FLOW: │
│ Merchant pays: Interchange (to Issuer) + Network Fee + Acquirer Fee │
│ │
└─────────────────────────────────────────────────────────────────────────┘
2. ISO 8583 Message Format
ISO 8583 is THE standard for authorization messages:
┌─────────────────────────────────────────────────────────────────────────┐
│ ISO 8583 MESSAGE STRUCTURE │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ MTI (4 bytes): Message Type Indicator │ │
│ │ ══════════════════════════════════════ │ │
│ │ │ │
│ │ Format: XYZW where: │ │
│ │ X = Version (0=1987, 1=1993, 2=2003) │ │
│ │ Y = Class (1=Auth, 2=Financial, 4=Reversal, 8=Network) │ │
│ │ Z = Function (0=Request, 1=Response, 2=Advice) │ │
│ │ W = Origin (0=Acquirer, 1=Repeat, 2=Issuer) │ │
│ │ │ │
│ │ Examples: │ │
│ │ 0100 = Authorization Request (acquirer to network) │ │
│ │ 0110 = Authorization Response (network to acquirer) │ │
│ │ 0200 = Financial Request (purchase) │ │
│ │ 0400 = Reversal Request │ │
│ │ 0800 = Network Management Request (echo, key exchange) │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ BITMAP (8-16 bytes): Which data elements are present │ │
│ │ ════════════════════════════════════════════════════ │ │
│ │ │ │
│ │ Primary bitmap: 64 bits for data elements 1-64 │ │
│ │ Secondary bitmap: 64 bits for data elements 65-128 │ │
│ │ │ │
│ │ Example: 7234054020C00000 │ │
│ │ Binary: 0111 0010 0011 0100... │ │
│ │ │││ │ │ │
│ │ ││└─ DE3 └─ DE7 │ │
│ │ │└── DE2 │ │
│ │ └─── Secondary bitmap present │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ DATA ELEMENTS: The actual transaction data │ │
│ │ ═════════════════════════════════════════ │ │
│ │ │ │
│ │ DE2: Primary Account Number (PAN) │ │
│ │ DE3: Processing Code (what kind of transaction) │ │
│ │ DE4: Transaction Amount │ │
│ │ DE7: Transmission Date/Time │ │
│ │ DE11: System Trace Audit Number (STAN) │ │
│ │ DE12: Local Transaction Time │ │
│ │ DE13: Local Transaction Date │ │
│ │ DE14: Expiration Date │ │
│ │ DE22: Point of Service Entry Mode │ │
│ │ DE23: Card Sequence Number │ │
│ │ DE35: Track 2 Data │ │
│ │ DE37: Retrieval Reference Number │ │
│ │ DE38: Authorization Identification Response │ │
│ │ DE39: Response Code │ │
│ │ DE41: Card Acceptor Terminal ID │ │
│ │ DE42: Card Acceptor Merchant ID │ │
│ │ DE43: Card Acceptor Name/Location │ │
│ │ DE55: ICC System Related Data (EMV chip data) │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
3. Settlement and Clearing
┌─────────────────────────────────────────────────────────────────────────┐
│ SETTLEMENT PROCESS │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ END OF BUSINESS DAY │
│ ═══════════════════ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ MERCHANT BATCH CLOSE │ │
│ │ │ │
│ │ Terminal batches all day's transactions: │ │
│ │ - TXN001: $50.00 (Visa, captured) │ │
│ │ - TXN002: $125.00 (MC, captured) │ │
│ │ - TXN003: $30.00 (Visa, void) │ │
│ │ - TXN004: $200.00 (Visa, captured) │ │
│ │ │ │
│ │ Batch total: $375.00 (2 Visa, 1 MC) │ │
│ │ │ │
│ │ Sent to Acquirer │ │
│ └────────────────────────────────────┬────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ ACQUIRER AGGREGATION │ │
│ │ │ │
│ │ Combines batches from all merchants: │ │
│ │ │ │
│ │ Visa transactions: $5,234,567.00 (12,456 txns) │ │
│ │ Mastercard: $3,456,789.00 (8,234 txns) │ │
│ │ Amex: $1,234,567.00 (2,345 txns) │ │
│ │ │ │
│ │ Creates clearing files for each network │ │
│ └────────────────────────────────────┬────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ NETWORK CLEARING (VisaNet, Mastercard Network) │ │
│ │ │ │
│ │ 1. Receives clearing files from all acquirers │ │
│ │ 2. Matches transactions with original authorizations │ │
│ │ 3. Routes to issuing banks │ │
│ │ 4. Calculates interchange fees │ │
│ │ │ │
│ │ ┌─────────────────────────────────────────────────────────┐ │ │
│ │ │ INTERCHANGE CALCULATION │ │ │
│ │ │ │ │ │
│ │ │ Transaction: $100.00 │ │ │
│ │ │ Interchange: 1.80% + $0.10 = $1.90 │ │ │
│ │ │ │ │ │
│ │ │ Merchant receives: $100 - $1.90 - fees │ │ │
│ │ │ Issuer receives: $1.90 (for card benefits, fraud) │ │ │
│ │ │ │ │ │
│ │ └─────────────────────────────────────────────────────────┘ │ │
│ └────────────────────────────────────┬────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ SETTLEMENT (Money Movement) │ │
│ │ │ │
│ │ Network calculates net positions: │ │
│ │ │ │
│ │ Issuer A owes: $1,234,567 │ │
│ │ Issuer B owes: $2,345,678 │ │
│ │ Acquirer X receives: $2,567,890 │ │
│ │ Acquirer Y receives: $1,012,355 │ │
│ │ │ │
│ │ Wire transfers via Federal Reserve or correspondent banks │ │
│ │ │ │
│ │ COMPLETE: Merchant's bank account credited │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
4. Chargeback Flow
┌─────────────────────────────────────────────────────────────────────────┐
│ CHARGEBACK PROCESS │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ REASON CODES (Examples): │
│ ═══════════════════════ │
│ • 10.4: Fraud - Card-Absent Environment │
│ • 13.1: Merchandise/Services Not Received │
│ • 13.3: Not as Described │
│ • 12.6: Duplicate Processing │
│ │
│ TIMELINE (Visa): │
│ ═════════════════ │
│ │
│ Day 0 │ Day 75 │ Day 90 │ Day 120 │
│ ─────────┼─────────────────┼─────────────────┼──────────────────── │
│ Purchase │ Cardholder │ Issuer files │ Representment │
│ │ disputes │ chargeback │ deadline │
│ │ │ │ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ STEP 1: CARDHOLDER DISPUTE │ │
│ │ │ │
│ │ Cardholder: "I don't recognize this $200 charge" │ │
│ │ Contacts: Issuing bank │ │
│ │ Bank investigates, may issue provisional credit │ │
│ └────────────────────────────────────────┬────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ STEP 2: CHARGEBACK FILED │ │
│ │ │ │
│ │ Issuer → Network → Acquirer → Merchant │ │
│ │ │ │
│ │ Chargeback message includes: │ │
│ │ - Original transaction details │ │
│ │ - Reason code │ │
│ │ - Documentation required from merchant │ │
│ │ │ │
│ │ Merchant's account DEBITED for transaction amount │ │
│ └────────────────────────────────────────┬────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ STEP 3: MERCHANT REPRESENTMENT (optional) │ │
│ │ │ │
│ │ Merchant can fight the chargeback with evidence: │ │
│ │ - Signed receipt │ │
│ │ - Delivery confirmation │ │
│ │ - AVS/CVV match confirmation │ │
│ │ - 3D Secure authentication proof │ │
│ │ │ │
│ │ If successful: Merchant re-credited, cardholder debited │ │
│ └────────────────────────────────────────┬────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ STEP 4: ARBITRATION (if still disputed) │ │
│ │ │ │
│ │ Network makes final decision │ │
│ │ Losing party pays arbitration fee ($500+) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ LIABILITY SHIFT WITH 3D SECURE: │
│ ═══════════════════════════════ │
│ If merchant used 3D Secure and cardholder authenticated: │
│ - Fraud liability shifts to ISSUER │
│ - Chargeback reason 10.4 not available to cardholder │
│ │
└─────────────────────────────────────────────────────────────────────────┘
5. Fraud Detection
┌─────────────────────────────────────────────────────────────────────────┐
│ FRAUD DETECTION SIGNALS │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ VELOCITY CHECKS: │
│ ═══════════════ │
│ • Same card, multiple transactions in short time │
│ • Same card, multiple merchants in different locations │
│ • Same IP, multiple different cards │
│ • Same device fingerprint, multiple cards │
│ │
│ BEHAVIORAL ANOMALIES: │
│ ════════════════════ │
│ • Purchase amount unusually high for cardholder │
│ • Purchase category unusual (e.g., electronics for groceries card) │
│ • Geographic anomaly (card used 1000 miles from home) │
│ • Time anomaly (3AM purchase, normally 9-5 usage) │
│ │
│ DEVICE/NETWORK SIGNALS: │
│ ═══════════════════════ │
│ • Known fraud proxy/VPN │
│ • TOR exit node │
│ • Device previously used in fraud │
│ • Browser fingerprint mismatch │
│ │
│ RISK SCORING MODEL: │
│ ════════════════════ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Signal │ Points │ Threshold Action │ │
│ │ ═══════════════════════════│════════│══════════════════════ │ │
│ │ New card, first purchase │ +20 │ │ │
│ │ High-risk merchant category │ +15 │ │ │
│ │ Amount > 3x average │ +25 │ │ │
│ │ IP in different country │ +30 │ │ │
│ │ Known good device │ -40 │ │ │
│ │ Previous 3DS success │ -20 │ │ │
│ │ ─────────────────────────────────────│ │ │
│ │ Score < 30 │ │ Approve │ │
│ │ Score 30-60 │ │ 3DS Challenge │ │
│ │ Score 60-80 │ │ Manual Review │ │
│ │ Score > 80 │ │ Auto-Decline │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
Project Specification
What You’ll Build
A complete payment ecosystem simulator including:
- Merchant Checkout System - Web interface for purchases
- Payment Gateway - Merchant’s processor (from Project 5)
- Card Network Switch - Routes between acquirers and issuers
- Issuer Authorization System - Approves/declines transactions
- Settlement System - Batch clearing and money movement
- Chargeback System - Dispute handling workflow
- Fraud Detection Engine - Real-time risk scoring
- Admin Dashboard - Visualize money flow and security events
System Overview
┌─────────────────────────────────────────────────────────────────────────┐
│ FULL ECOSYSTEM COMPONENTS │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────────────────────────────────────────────────┐ │
│ │ WEB INTERFACE │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ Merchant │ │ Admin │ │ Cardholder │ │ │
│ │ │ Checkout │ │ Dashboard │ │ Portal │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ └───────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────────▼─────────────────────────────────┐ │
│ │ ACQUIRER DOMAIN │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │
│ │ │ Payment Gateway │ │ 3DS Server │ │ Settlement │ │ │
│ │ │ (Project 5) │ │ (Project 4) │ │ Engine │ │ │
│ │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │
│ │ │ │ │ │ │
│ │ └────────────────────┼────────────────────┘ │ │
│ │ │ │ │
│ │ ┌─────────────────────────────▼─────────────────────────────┐ │ │
│ │ │ Token Vault (Project 2) │ │ │
│ │ └───────────────────────────────────────────────────────────┘ │ │
│ └───────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────────▼─────────────────────────────────┐ │
│ │ NETWORK DOMAIN │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │
│ │ │ Switch (Router) │ │ Clearing House │ │ Dispute Manager │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • BIN routing │ │ • Match txns │ │ • Chargeback │ │ │
│ │ │ • Load balance │ │ • Calc fees │ │ • Represent │ │ │
│ │ │ • Fallback │ │ • Net settle │ │ • Arbitration │ │ │
│ │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │
│ │ │ │ │ │ │
│ └───────────┼────────────────────┼────────────────────┼─────────────┘ │
│ │ │ │ │
│ ┌───────────▼────────────────────▼────────────────────▼─────────────┐ │
│ │ ISSUER DOMAIN │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │
│ │ │ Authorization │ │ Fraud Engine │ │ ACS (3DS) │ │ │
│ │ │ System │ │ │ │ │ │ │
│ │ │ │ │ • Velocity │ │ • Risk decide │ │ │
│ │ │ • Check funds │ │ • Behavior │ │ • Challenge │ │ │
│ │ │ • Apply rules │ │ • ML scoring │ │ • Authenticate │ │ │
│ │ │ • Respond │ │ │ │ │ │ │
│ │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │
│ │ │ │ │ │ │
│ │ ┌────────▼────────────────────▼────────────────────▼─────────┐ │ │
│ │ │ Cardholder Accounts │ │ │
│ │ │ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ │ │ │
│ │ │ │Card A │ │Card B │ │Card C │ │Card D │ │ │ │
│ │ │ │$5000 │ │$2500 │ │$10000 │ │$1500 │ │ │ │
│ │ │ └───────┘ └───────┘ └───────┘ └───────┘ │ │ │
│ │ └────────────────────────────────────────────────────────────┘ │ │
│ └───────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
Expected Demo Output
╔═══════════════════════════════════════════════════════════════════════╗
║ PAYMENT ECOSYSTEM SIMULATOR ║
║ Live Transaction Dashboard ║
╠═══════════════════════════════════════════════════════════════════════╣
║ ║
║ REAL-TIME TRANSACTION FLOW ║
║ ────────────────────────── ║
║ ║
║ TXN: 7f3a9b2c │ Amount: $149.99 │ Card: Visa ****4242 ║
║ ║
║ ┌─────────────────────────────────────────────────────────────────┐ ║
║ │ │ ║
║ │ [14:32:17.001] MERCHANT → Checkout initiated │ ║
║ │ [14:32:17.023] GATEWAY → Card tokenized: tok_xyz │ ║
║ │ [14:32:17.045] GATEWAY → Auth request to network │ ║
║ │ [14:32:17.067] NETWORK → Routing to Visa (BIN: 424242) │ ║
║ │ [14:32:17.089] ISSUER → Fraud check: Score 23 (LOW) │ ║
║ │ [14:32:17.112] ISSUER → Balance check: $5000 available │ ║
║ │ [14:32:17.134] ISSUER → ✓ APPROVED (Auth: A12345) │ ║
║ │ [14:32:17.156] NETWORK → Response routed to acquirer │ ║
║ │ [14:32:17.178] GATEWAY → Response to merchant │ ║
║ │ [14:32:17.200] MERCHANT → Order confirmed │ ║
║ │ │ ║
║ │ Total latency: 199ms │ ║
║ │ │ ║
║ └─────────────────────────────────────────────────────────────────┘ ║
║ ║
║ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ║
║ ║
║ DAILY STATISTICS ║
║ ──────────────── ║
║ ║
║ Authorizations: 15,234 │ Approved: 14,123 (92.7%) ║
║ Captures: 13,891 │ Refunds: 342 (2.5%) ║
║ Chargebacks: 23 │ Fraud: 12 (0.08%) ║
║ ║
║ Settlement Status: PENDING (closes at 23:00 UTC) ║
║ Pending Amount: $1,234,567.89 ║
║ ║
║ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ║
║ ║
║ FRAUD ALERTS ║
║ ──────────── ║
║ ║
║ 🚨 [14:31:45] High-risk transaction declined ║
║ Card: ****9876 │ Amount: $2,500 │ Score: 87 │ Reason: Velocity ║
║ ║
║ ⚠️ [14:28:12] Transaction sent to manual review ║
║ Card: ****5555 │ Amount: $800 │ Score: 65 │ Reason: New device ║
║ ║
╚═══════════════════════════════════════════════════════════════════════╝
Project Structure
payment_ecosystem/
├── services/
│ ├── merchant/ # Merchant checkout system
│ │ ├── checkout-web/ # Web frontend
│ │ └── checkout-api/ # Backend
│ │
│ ├── acquirer/ # Acquirer domain
│ │ ├── gateway/ # Payment gateway (Project 5)
│ │ ├── threeds-server/ # 3DS Server (Project 4)
│ │ ├── token-vault/ # Token vault (Project 2)
│ │ └── settlement/ # Settlement engine
│ │
│ ├── network/ # Card network
│ │ ├── switch/ # Message router
│ │ ├── clearing/ # Clearing house
│ │ └── disputes/ # Chargeback management
│ │
│ └── issuer/ # Issuing bank
│ ├── authorization/ # Auth engine
│ ├── fraud-engine/ # Fraud detection
│ ├── acs/ # 3DS ACS (Project 4)
│ └── accounts/ # Cardholder accounts
│
├── shared/
│ ├── iso8583/ # Message format library
│ ├── crypto/ # Cryptography utilities
│ └── audit/ # Logging framework
│
├── infrastructure/
│ ├── docker-compose.yml # Full system orchestration
│ ├── k8s/ # Kubernetes configs (optional)
│ └── scripts/
│ ├── generate-keys.sh # Key generation
│ ├── simulate-day.sh # Day of transactions
│ └── run-settlement.sh # Settlement batch
│
├── admin-dashboard/ # Visualization UI
│ ├── src/
│ └── public/
│
├── tests/
│ ├── integration/ # End-to-end tests
│ ├── performance/ # Load tests
│ └── security/ # Penetration tests
│
└── docs/
├── architecture.md
├── message-flows.md
└── security-controls.md
Implementation Guide
Phase 1: ISO 8583 Message Library
Goal: Build the messaging foundation.
# iso8583/message.py
from dataclasses import dataclass
from typing import Dict, Optional
import struct
@dataclass
class ISO8583Message:
mti: str # Message Type Indicator
bitmap: bytes # Which fields present
data_elements: Dict[int, bytes] # Field number -> value
def encode(self) -> bytes:
"""Encode message to bytes for transmission"""
result = self.mti.encode('ascii')
result += self.bitmap
for de_num in sorted(self.data_elements.keys()):
result += self._encode_field(de_num, self.data_elements[de_num])
return result
@classmethod
def decode(cls, data: bytes) -> 'ISO8583Message':
"""Decode bytes to message"""
mti = data[0:4].decode('ascii')
bitmap = data[4:12] # Primary bitmap
# Parse data elements based on bitmap...
@dataclass
class AuthorizationRequest(ISO8583Message):
"""0100 - Authorization Request"""
pan: str # DE2
processing_code: str # DE3
amount: int # DE4 (in cents)
transmission_datetime: str # DE7
stan: str # DE11
expiry: str # DE14
pos_entry_mode: str # DE22
terminal_id: str # DE41
merchant_id: str # DE42
def __post_init__(self):
self.mti = "0100"
self.data_elements = {
2: self.pan.encode(),
3: self.processing_code.encode(),
4: str(self.amount).zfill(12).encode(),
7: self.transmission_datetime.encode(),
11: self.stan.encode(),
14: self.expiry.encode(),
22: self.pos_entry_mode.encode(),
41: self.terminal_id.encode(),
42: self.merchant_id.encode(),
}
self.bitmap = self._calculate_bitmap()
Phase 2: Network Switch
Goal: Route authorization requests to correct issuer.
# network/switch.py
class CardNetworkSwitch:
def __init__(self):
self.issuer_connections: Dict[str, IssuerConnection] = {}
self.routing_table = BINRoutingTable()
async def process_authorization(self, request: AuthorizationRequest) -> AuthorizationResponse:
# 1. Validate message format
self._validate_message(request)
# 2. Determine issuer from BIN
bin_prefix = request.pan[:6]
issuer_id = self.routing_table.lookup(bin_prefix)
if not issuer_id:
return AuthorizationResponse(
response_code="14", # Invalid card number
message="Unknown issuer"
)
# 3. Route to issuer
issuer = self.issuer_connections.get(issuer_id)
if not issuer or not issuer.is_connected:
# Try fallback
issuer = self._get_fallback_issuer(issuer_id)
# 4. Forward and await response
response = await issuer.send_authorization(request)
# 5. Log for clearing
await self.clearing_queue.enqueue(ClearingRecord(
request=request,
response=response,
timestamp=datetime.utcnow()
))
return response
Phase 3: Issuer Authorization
Goal: Implement cardholder account management and authorization logic.
# issuer/authorization.py
class IssuerAuthorizationEngine:
def __init__(self, fraud_engine: FraudEngine, account_db: AccountDatabase):
self.fraud_engine = fraud_engine
self.account_db = account_db
async def authorize(self, request: AuthorizationRequest) -> AuthorizationResponse:
# 1. Look up cardholder account
account = await self.account_db.get_by_pan(request.pan)
if not account:
return self._decline("14", "Invalid card")
# 2. Check card status
if account.card_status != CardStatus.ACTIVE:
return self._decline("05", f"Card {account.card_status}")
# 3. Check expiry
if self._is_expired(request.expiry):
return self._decline("54", "Expired card")
# 4. Fraud check
fraud_result = await self.fraud_engine.evaluate(request, account)
if fraud_result.action == FraudAction.DECLINE:
return self._decline("59", "Fraud suspected")
if fraud_result.action == FraudAction.CHALLENGE:
return self._request_3ds(request)
# 5. Check available funds
if account.available_credit < request.amount:
return self._decline("51", "Insufficient funds")
# 6. Place hold on funds
hold = await self.account_db.place_hold(
account_id=account.id,
amount=request.amount,
merchant=request.merchant_id,
expiry=datetime.utcnow() + timedelta(days=7)
)
# 7. Return approval
return AuthorizationResponse(
response_code="00",
auth_code=self._generate_auth_code(),
available_balance=account.available_credit - request.amount
)
Phase 4: Fraud Detection Engine
Goal: Real-time risk scoring.
# issuer/fraud_engine.py
class FraudEngine:
def __init__(self):
self.velocity_checker = VelocityChecker()
self.behavior_analyzer = BehaviorAnalyzer()
self.device_intelligence = DeviceIntelligence()
async def evaluate(self, request: AuthorizationRequest,
account: CardholderAccount) -> FraudResult:
score = 0
signals = []
# Velocity checks
velocity_result = await self.velocity_checker.check(request.pan)
if velocity_result.txn_count_1h > 5:
score += 30
signals.append("HIGH_VELOCITY")
# Behavior analysis
behavior = await self.behavior_analyzer.analyze(request, account)
if behavior.amount_unusual:
score += 25
signals.append("UNUSUAL_AMOUNT")
if behavior.merchant_category_unusual:
score += 15
signals.append("UNUSUAL_MCC")
if behavior.time_unusual:
score += 10
signals.append("UNUSUAL_TIME")
# Device/location checks
device_result = await self.device_intelligence.check(
ip=request.source_ip,
device_fingerprint=request.device_id
)
if device_result.is_known_fraud_proxy:
score += 40
signals.append("FRAUD_PROXY")
if device_result.geo_distance_from_home > 1000: # km
score += 20
signals.append("GEO_ANOMALY")
# Known good signals (reduce score)
if await self._is_trusted_device(request.device_id, account):
score -= 30
if await self._recent_3ds_success(account):
score -= 20
# Make decision
if score >= 80:
action = FraudAction.DECLINE
elif score >= 50:
action = FraudAction.CHALLENGE
elif score >= 30:
action = FraudAction.STEP_UP
else:
action = FraudAction.APPROVE
return FraudResult(
score=max(0, score),
action=action,
signals=signals
)
Phase 5: Settlement Engine
Goal: Batch processing and money movement.
# acquirer/settlement.py
class SettlementEngine:
def __init__(self):
self.transaction_store = TransactionStore()
self.network_client = NetworkSettlementClient()
async def run_settlement(self, settlement_date: date):
"""Run end-of-day settlement"""
# 1. Collect all captured transactions for the day
transactions = await self.transaction_store.get_captured_for_date(settlement_date)
# 2. Group by card network
by_network = self._group_by_network(transactions)
settlement_results = []
for network, txns in by_network.items():
# 3. Calculate totals
gross_amount = sum(t.amount for t in txns)
interchange_fees = sum(self._calc_interchange(t) for t in txns)
net_amount = gross_amount - interchange_fees
# 4. Create clearing file
clearing_file = self._create_clearing_file(network, txns)
# 5. Submit to network
result = await self.network_client.submit_clearing(network, clearing_file)
settlement_results.append(SettlementResult(
network=network,
transaction_count=len(txns),
gross_amount=gross_amount,
interchange=interchange_fees,
net_amount=net_amount,
clearing_reference=result.reference
))
# 6. Update transaction statuses
for txn in txns:
txn.status = TransactionStatus.SETTLED
txn.settlement_date = settlement_date
txn.clearing_reference = result.reference
await self.transaction_store.update(txn)
return settlement_results
def _calc_interchange(self, txn: Transaction) -> Decimal:
"""Calculate interchange fee based on card type and MCC"""
# Simplified - real interchange tables are complex
base_rate = Decimal("0.0180") # 1.80%
fixed_fee = Decimal("0.10") # $0.10
return (txn.amount * base_rate) + fixed_fee
Phase 6: Chargeback System
Goal: Handle disputes and representment.
# network/disputes.py
class DisputeManager:
def __init__(self):
self.dispute_store = DisputeStore()
self.acquirer_client = AcquirerNotificationClient()
async def file_chargeback(self, chargeback: Chargeback):
"""Process a chargeback from issuer"""
# 1. Validate chargeback
if not self._is_valid_reason_code(chargeback.reason_code):
raise InvalidChargebackError("Unknown reason code")
# 2. Check timeframes
original_txn = await self._get_original_transaction(chargeback.original_txn_id)
if not self._within_chargeback_window(original_txn):
raise ChargebackWindowExpired()
# 3. Check if 3DS protected
if original_txn.eci in ["05", "02"]: # Fully authenticated
if chargeback.reason_code.startswith("10."): # Fraud
# Liability shift - reject chargeback
return ChargebackResult(
status="REJECTED",
reason="Liability shift applies - 3DS authenticated"
)
# 4. Store chargeback
dispute = Dispute(
id=generate_dispute_id(),
original_transaction=original_txn,
chargeback=chargeback,
status=DisputeStatus.PENDING,
created_at=datetime.utcnow(),
representment_deadline=datetime.utcnow() + timedelta(days=30)
)
await self.dispute_store.create(dispute)
# 5. Notify acquirer/merchant
await self.acquirer_client.notify_chargeback(dispute)
# 6. Debit merchant account (provisional)
await self._debit_merchant(original_txn.merchant_id, original_txn.amount)
return ChargebackResult(
status="ACCEPTED",
dispute_id=dispute.id
)
async def representment(self, dispute_id: str, evidence: RepresentmentEvidence):
"""Merchant disputes the chargeback"""
dispute = await self.dispute_store.get(dispute_id)
if datetime.utcnow() > dispute.representment_deadline:
raise RepresentmentWindowExpired()
# Update dispute with evidence
dispute.representment = evidence
dispute.status = DisputeStatus.REPRESENTMENT_FILED
await self.dispute_store.update(dispute)
# Route to issuer for review
await self.issuer_client.send_representment(dispute)
Phase 7: Admin Dashboard
Goal: Visualization of the entire system.
Build a web dashboard showing:
- Real-time transaction flow (WebSocket updates)
- Authorization statistics
- Fraud alerts
- Settlement status
- Chargeback queue
- Money flow visualization
Testing Strategy
End-to-End Tests
# tests/integration/test_full_flow.py
async def test_complete_purchase_to_settlement():
"""Test entire lifecycle: auth → capture → settle"""
# 1. Create test cardholder with balance
account = await create_test_account(credit_limit=1000)
# 2. Initiate purchase
response = await merchant_checkout(
pan=account.pan,
amount=Decimal("100.00")
)
assert response.status == "APPROVED"
# 3. Capture
capture_response = await gateway_capture(response.transaction_id)
assert capture_response.status == "CAPTURED"
# 4. Run settlement
settlement_result = await run_settlement(date.today())
# 5. Verify
assert settlement_result.net_amount == Decimal("98.10") # After fees
assert account.balance == Decimal("100.00") # Cardholder charged
async def test_fraud_decline():
"""Test high-risk transaction gets declined"""
account = await create_test_account()
# Simulate suspicious activity
await inject_fraud_signals(
pan=account.pan,
ip="185.x.x.x", # Known fraud proxy
velocity=10 # 10 transactions in 1 hour
)
response = await merchant_checkout(
pan=account.pan,
amount=Decimal("2500.00") # High amount
)
assert response.status == "DECLINED"
assert response.reason == "Fraud suspected"
async def test_chargeback_with_3ds():
"""Test that 3DS blocks fraud chargebacks"""
# Purchase with 3DS authentication
response = await merchant_checkout_with_3ds(
pan="4111111111111111",
amount=Decimal("500.00")
)
assert response.eci == "05" # Fully authenticated
# Attempt fraud chargeback
chargeback_result = await issuer_file_chargeback(
transaction_id=response.transaction_id,
reason_code="10.4", # Fraud
amount=Decimal("500.00")
)
assert chargeback_result.status == "REJECTED"
assert "Liability shift" in chargeback_result.reason
Load Testing
# tests/performance/load_test.py
async def test_authorization_throughput():
"""Verify system handles target TPS"""
target_tps = 100 # Transactions per second
duration_seconds = 60
results = await run_load_test(
endpoint="/authorize",
tps=target_tps,
duration=duration_seconds
)
assert results.successful_rate > 0.999 # 99.9% success
assert results.p99_latency_ms < 500 # Under 500ms
assert results.p50_latency_ms < 100 # Median under 100ms
Self-Assessment Checklist
Core Functionality
- Authorization requests flow through entire system
- Responses route back correctly
- Settlement batches process nightly
- Money totals match at each stage
Security
- All components use proper encryption
- Keys managed with split knowledge
- Audit logs capture all transactions
- No PAN leakage anywhere
Fraud Detection
- Velocity checks block rapid-fire fraud
- Behavior analysis flags anomalies
- Risk scores drive decisions
- 3DS integration works correctly
Compliance
- Can map each component to PCI requirement
- Data retention policies enforced
- Chargeback handling follows network rules
Understanding
- Can explain four-party model to anyone
- Understand authorization vs. settlement
- Know how interchange fees work
- Understand liability shift
Resources
Specifications
- ISO 8583 (1987, 1993, 2003 versions)
- Visa BASE I and II
- Mastercard Network Rules
- EMVCo specifications
Books
| Topic | Book | |——-|——| | Distributed Systems | “Designing Data-Intensive Applications” by Kleppmann | | Fraud Detection | “Data Science for Business” by Provost & Fawcett | | Payment Systems | Industry white papers from Visa/Mastercard |
Conclusion
By completing this capstone project, you will have built the most comprehensive payment system simulation possible outside of an actual financial institution. You’ll understand:
- Every party in a credit card transaction
- How money actually moves through the system
- Why each security control exists
- What happens when things go wrong (chargebacks, fraud)
- The economics of payment processing
This knowledge is rare and valuable. Most developers never get this deep into payment infrastructure.
You’re not just building software—you’re learning how global commerce works.