CommunityPay

Multi-Provider
Payment Infrastructure

Provider-agnostic architecture with cost-optimized routing, three-layer idempotency, and signal-driven accounting integration.

Abstract gateway interface · Cost-optimized provider selection · Automatic fallback chains.
Three-layer idempotency · Fraud scoring · Signal-driven GL integration.

N Provider Agnostic
3-Layer Idempotency
0-100 Fraud Scoring
5-Step Reconciliation
A unified interface abstracts multiple payment providers behind a single API. The factory pattern enables cost-optimized routing, automatic fallbacks, and seamless provider switching—no vendor lock-in, ever.
01

Provider-Agnostic Architecture

Every payment gateway implements a unified abstract interface. The factory calculates actual fees per-transaction and routes to the cheapest provider. If one fails health checks, the system falls back automatically to the next in chain.

Abstract Gateway Interface
739-line interface defines the contract: create_payment, verify_account, process_refund, etc. All providers implement identical methods. Swap providers without touching business logic.
Cost Optimization Routing
Factory calculates real fees per transaction amount. Percentage-based vs. flat-fee providers compared dynamically. System routes to cheapest option automatically.
Automatic Fallback Chains
Configurable fallback sequences. Primary→Secondary→Tertiary routing. Health checks verify provider availability before returning gateway. Gateway instances cached with continuous health verification.
ProviderCustomer Abstraction
Model decouples users from provider-specific IDs. Multi-tenant HOA context with unique constraint on [user, provider, hoa]. Verification status tracked per provider independently.
Connect Account Integration
Two-step vendor payment flow: debit HOA account, then transfer to vendor's connected account. Complete onboarding workflow with account status monitoring.
Mandate-Based Compliance
ACH mandate collection with validation. Mandate metadata storage. Automatic reuse when valid mandate exists. Status verification before every payment attempt.
No Vendor Lock-In: The abstract interface means you can add a new payment provider by implementing the gateway contract. Business logic never changes. Volume-based and HOA-specific routing rules supported.
02

Three-Layer Idempotency

Click twice, get charged once. This isn't UI protection—it's enforced at the API layer, webhook layer, and database layer. Every payment operation is protected against duplication through defense in depth.

Layer 1: Payment UUID Keys
Every Payment model has a unique UUID4 field (editable=False). Idempotency key format: payment_{id}_{uuid}. Sent with every payment creation request. Provider returns cached result on retry—no duplicate charge.
Layer 2: Webhook Deduplication
WebhookEvent model with unique_together constraint on [provider, event_id]. Database-level enforcement—same event cannot insert twice. Status tracking: received→processing→processed/failed/ignored.
Layer 3: Transaction ID Check
Each Payment stores provider_transaction_id. Query-before-retry pattern: if transaction ID already exists in database, reject the duplicate attempt. Belt and suspenders protection at the application layer.
Why Three Layers? Network failures cause retries at every level— user double-clicks, API timeouts, webhook redelivery. Each layer catches duplicates that slip past the others. Fiduciary protection requires defense in depth.
03

Fraud Detection & Velocity Controls

Multi-factor risk scoring with configurable velocity limits. Every payment evaluated against historical patterns, account signals, and timing anomalies.

Risk Scoring (0-100)

  • Payment amount anomalies vs. unit history
  • User account age factor
  • IP reputation signals
  • Time-based pattern analysis
  • Unit payment history context
  • Duplicate detection (5-minute window)

Velocity Limits

  • 2 payments per minute maximum
  • 10 payments per day maximum
  • $10,000 daily limit
  • $5,000 single transaction cap
  • Per-IP and per-user tracking
  • Exponential backoff on violations
04

Failure-Aware Retry Scheduling

Not all failures are equal. NSF requires days between retries. Network errors need rapid exponential backoff. The retry service parses failure codes and applies type-specific strategies.

NSF / Insufficient Funds
Schedule: [15min, 1d, 3d, 5d, 7d]. Final action: suspend_account. Immediate user notification. Prevents wasteful rapid retries that damage customer relationship.
Card Declined
Schedule: [15min, 1hr, 6hr, 1d, 3d]. Final action: request_new_payment_method. Faster cadence—card issues often resolve quickly with limit resets or fraud flags cleared.
Network / Processing Errors
Exponential backoff: [1min, 2min, 4min, 8min, 16min]. Final action: escalate_to_support. Technical issues need aggressive retry before human intervention.
Failure Code Parsing: The retry service detects failure type from provider error codes and response metadata. Strategy selection is automatic— no manual classification required.
05

Webhook Security

Unified webhook endpoint handles multiple providers with signature verification, rate limiting, and replay attack prevention.

Signature Verification

  • HMAC timing-safe comparison (hmac.compare_digest)
  • Provider-specific signature format support
  • Dual-secret support (platform + Connect webhooks)
  • Replay attack prevention (5-minute timestamp window)
  • Automatic webhook type detection from payload

Rate Limiting

  • Per-provider rate limits (50-100 req/min)
  • 512KB max payload size
  • Unified endpoint routes to correct handler
  • Fallback secret verification chain
  • Detailed logging for multi-account debugging
06

Signal-Driven Accounting Integration

When a payment succeeds, Django signals trigger automatic accounting entries. No manual posting. No end-of-day batch. The ledger updates in real-time with full audit trail.

Payment.status → SUCCEEDED (webhook confirms) ↓ Signal handler: create_accounting_payment_receipt ↓ Check for linked AR Invoice (ar_invoice FK) ↓ Create PaymentReceipt with payment_uuid reference ↓ GL entries posted: DR Cash (1000), CR Accounts Receivable (1100) ↓ ARService.receive_payment() applies to invoice ↓ Invoice balance updated automatically
Duplicate Prevention: PaymentReceipt creation checks for existing provider_payment_intent. If receipt already exists, signal handler exits early. Combined with webhook idempotency, duplicate GL entries are architecturally impossible.
07

5-Step Reconciliation Engine

Comprehensive reconciliation runs compare database records against provider data. Discrepancies surface immediately with detailed tracking of what differs and why.

Step 1: Payment Reconciliation
Compare provider PaymentIntents against Payment records. Detect: missing_in_provider, missing_in_db, amount_mismatch, status_mismatch, duplicate entries.
Step 2: Refund Reconciliation
Match provider refunds to Refund model records. Track partial vs. full refunds. Verify amounts, timing, and linked original payment.
Step 3: Transfer Reconciliation
Validate Connect transfers to vendor accounts. Ensure Disbursement records match transfer records. Detect fee discrepancies.
Step 4: Payout Reconciliation
Match bank payouts to expected settlements. Payout model tracks each settlement with status and timing metadata.
Step 5: Balance Check
Snapshot provider balances at reconciliation time. Compare to expected based on transaction activity. Detect unexplained variances.
Alert Generation
Automatic ReconciliationAlert for discrepancies. ReconciliationItem stores both DB and provider values. Email reports. Resolution status tracking.
08

Bank Account Verification

Instant Verification

  • Financial Connections API integration
  • Instant auth for immediate access
  • Real-time balance and ownership confirmation
  • Verification tokens stored securely

Micro-Deposit Fallback

  • Micro-deposit flow for unsupported institutions
  • Verification status tracking per provider
  • Account metadata storage (provider_metadata JSON)
  • Multi-provider verification history
09

API Security

Defense-in-depth API protection with exponential backoff rate limiting, dynamic windows, and cache-based efficiency.

Exponential Backoff
Rate limit violations trigger exponential backoff capped at 300 seconds. Prevents abuse while allowing legitimate burst traffic to recover.
Multi-Dimension Tracking
Per-IP, per-user, and per-API-key rate tracking. Each dimension has independent limits. Cache-based implementation for minimal latency.
Dynamic Windows
Rate limit windows adjust based on endpoint sensitivity. Payment endpoints stricter than read-only queries. Configurable per-route limits.

Payment Infrastructure
Built for Fiduciary Duty.

Provider-agnostic. Cost-optimized. Triple-idempotent. The payment architecture HOA accounting demands.

CommunityPay