Skip to content

idlefor/PaymentRouter

Repository files navigation

Payment Router - Resilient API Consumption & Orchestration Platform

A comprehensive Spring Boot 3.3.0 application designed for Java 21, implementing enterprise-grade API orchestration with resilience patterns, secure authentication, and webhook management.

Architecture Overview

Core Components

1. API Integration Layer (ApiIntegrationService)

  • Purpose: Manages all external API communications
  • Features:
    • RESTful API invocation to external partners
    • Automatic retry on transient failures
    • Circuit breaker pattern for fault isolation
    • Rate limiting for API consumption
    • Time limiting for request execution
    • Request/Response logging and tracking
    • Multiple authentication mechanisms

2. Authentication & Security (AuthenticationService)

  • Supported Auth Methods:

    • JWT: Token-based authentication with configurable expiration
    • OAuth2: Client credentials flow integration
    • HMAC: Request signature verification (SHA256/SHA512)
    • RSA: Digital signature verification
    • Basic Auth: Username/password authentication
    • API Key: Custom header-based API keys
  • Security Features:

    • Constant-time signature comparison (prevents timing attacks)
    • PEM key format support for RSA operations
    • Secure credential storage with bcrypt hashing
    • CORS configuration for cross-origin requests

3. Webhook Handling (WebhookHandlerService)

  • Capabilities:
    • Receive and parse webhook events from external partners
    • Verify webhook signatures (HMAC and RSA)
    • Route events to appropriate handlers
    • Support for multiple event types:
      • Payment success/failure
      • Payment pending status
      • Reconciliation events
    • Callback processing
    • Event tracking and correlation

4. Resilience Patterns (Resilience4j)

  • Circuit Breaker:

    • Configurable failure rate threshold (50% default)
    • Automatic recovery with half-open state
    • 30-second open duration with automatic transition
  • Retry Logic:

    • Up to 3 retry attempts
    • Exponential backoff strategy (500ms initial, 2x multiplier)
    • Selective retry based on exception type
  • Rate Limiting:

    • 100 requests per second
    • Configurable per-partner limits
    • 5-second timeout for rate limit enforcement
  • Time Limiting:

    • 10-second request execution timeout
    • Cancels running futures on timeout
    • Prevents resource exhaustion

5. Monitoring & Observability (MonitoringService)

  • Metrics Collected:

    • Total API requests (counter)
    • Successful vs failed requests (counters)
    • API request duration (timer with percentiles)
    • Active requests (gauge)
    • Webhook processing metrics
    • Circuit breaker and rate limiter status
  • Integration:

    • Micrometer for metrics collection
    • Prometheus for scraping and storage
    • Spring Boot Actuator endpoints
    • Custom dashboard via API

6. API Gateway (Spring Cloud Gateway)

  • Features:
    • Request routing and filtering
    • Authentication enforcement
    • Traffic management
    • Request/Response logging
    • Access control policies

API Endpoints

Integration Endpoints

POST   /api/v1/integration/execute           # Synchronous API execution
POST   /api/v1/integration/execute-async     # Asynchronous API execution
GET    /api/v1/integration/health            # Integration health check

Webhook Endpoints

POST   /api/v1/webhooks/receive              # Generic webhook receiver
POST   /api/v1/webhooks/payment-provider     # Payment provider webhooks
POST   /api/v1/webhooks/compliance           # Compliance/KYC webhooks
POST   /api/v1/webhooks/operations           # Operations/Settlement webhooks
GET    /api/v1/webhooks/health               # Webhook service health

Monitoring Endpoints

GET    /api/v1/monitoring/metrics            # Current metrics
GET    /api/v1/monitoring/health             # Health status
GET    /api/v1/monitoring/gateway/status     # Gateway status
GET    /api/v1/monitoring/dashboard          # Operational dashboard
GET    /actuator/prometheus                  # Prometheus metrics

Data Models

ApiRequestDto

{
  "requestId": "uuid",
  "apiEndpoint": "https://api.partner.com/endpoint",
  "method": "POST",
  "headers": { "Custom-Header": "value" },
  "pathParameters": { "id": "12345" },
  "requestBody": { "field": "value" },
  "authType": "JWT",
  "partnerId": "partner-001",
  "metadata": { "key": "value" }
}

ApiResponseDto

{
  "requestId": "uuid",
  "responseId": "uuid",
  "statusCode": 200,
  "statusMessage": "OK",
  "responseBody": { "result": "data" },
  "headers": { "Header": "value" },
  "responseTime": "2026-06-20T10:30:00",
  "executionTimeMs": 150,
  "source": "https://api.partner.com/endpoint",
  "apiProvider": "partner-001",
  "success": true
}

WebhookEventDto

{
  "eventId": "uuid",
  "eventType": "payment.success",
  "source": "payment-provider",
  "payload": { "event_data": "..." },
  "headers": { "X-Signature": "..." },
  "signature": "base64-signature",
  "receivedAt": "2026-06-20T10:30:00",
  "verified": true,
  "verificationMethod": "HMAC"
}

Configuration

Key Properties (application.properties)

# Resilience4j
resilience4j.circuitbreaker.configs.default.failureRateThreshold=50
resilience4j.circuitbreaker.configs.default.waitDurationInOpenState=30s
resilience4j.retry.configs.default.maxAttempts=3
resilience4j.ratelimiter.configs.default.limitForPeriod=100

# JWT
jwt.secret=your-secret-key
jwt.expiration=86400000
jwt.algorithm=HS512

# OAuth2
oauth2.client-id=your-client-id
oauth2.client-secret=your-client-secret

# Security
security.cors.allowed-origins=http://localhost:3000

# Webhook
webhook.signature-verification.enabled=true
webhook.retry.max-attempts=3

Getting Started

Prerequisites

  • Java 21 JDK
  • Maven 3.8+
  • Spring Boot 3.3.0

Build & Run

# Build
mvn clean package

# Run
java -jar target/PaymentRouter-1.0-SNAPSHOT.jar

# Server starts on http://localhost:8080

Example Usage

Execute External API Call

curl -X POST http://localhost:8080/api/v1/integration/execute \
  -H "Content-Type: application/json" \
  -d '{
    "apiEndpoint": "https://api.partner.com/payments",
    "method": "POST",
    "authType": "JWT",
    "partnerId": "partner-001",
    "requestBody": {
      "amount": 100.00,
      "currency": "USD"
    }
  }'

Receive Webhook from Partner

curl -X POST http://localhost:8080/api/v1/webhooks/receive \
  -H "X-Partner-Id: payment-provider" \
  -H "X-Signature: base64-encoded-signature" \
  -H "X-Signature-Method: HMAC" \
  -H "Content-Type: application/json" \
  -d '{
    "eventType": "payment.success",
    "transactionId": "txn-12345",
    "amount": 100.00,
    "status": "completed"
  }'

Get Metrics

curl http://localhost:8080/api/v1/monitoring/metrics
curl http://localhost:8080/actuator/prometheus

Security Best Practices

  1. Credential Management:

    • Store credentials in secure vaults (AWS Secrets Manager, HashiCorp Vault)
    • Rotate credentials regularly
    • Never commit secrets to version control
  2. API Communication:

    • Always use HTTPS for external API calls
    • Validate SSL certificates
    • Implement request signing for sensitive operations
  3. Webhook Verification:

    • Always verify webhook signatures
    • Implement webhook replay protection
    • Log all webhook events for audit trails
  4. Authentication:

    • Use JWT with short expiration times
    • Implement refresh token mechanism
    • Protect endpoints with Spring Security

Scaling & Performance

Horizontal Scaling

  • Stateless design allows easy horizontal scaling
  • Cache credentials with appropriate TTL
  • Use distributed rate limiter for multi-instance deployments

Performance Optimization

  • Connection pooling for HTTP clients
  • Request/response buffering
  • Async API execution support
  • Metrics collection with minimal overhead

Monitoring & Alerts

Key Metrics to Monitor

  • API request latency (p50, p95, p99)
  • Circuit breaker state (open/half-open/closed)
  • Webhook verification success rate
  • Active connections and pending requests

Prometheus Integration

Metrics are automatically exposed at /actuator/prometheus for Prometheus scraping

Troubleshooting

Circuit Breaker Open

  • Check external API health
  • Review recent API failure logs
  • Verify network connectivity
  • Monitor error rate trends

High Webhook Verification Failures

  • Verify webhook signature algorithm matches partner
  • Check for secret key rotation on partner side
  • Review webhook payload format
  • Check timestamp validity

Rate Limiting Active

  • Consider increasing limits in configuration
  • Implement partner-specific rate limits
  • Use backoff strategy for retries

Dependencies

Key Spring Boot and Third-Party Libraries:

  • Spring Security & OAuth2 Client
  • Spring Cloud Gateway
  • Resilience4j (Circuit Breaker, Retry, Rate Limiter)
  • Micrometer & Prometheus
  • JWT (JJWT)
  • Apache Commons & Bouncy Castle (Cryptography)
  • Lombok
  • H2 Database (for development)

Future Enhancements

  • Distributed tracing with Spring Cloud Sleuth
  • AsyncAPI support for event-driven architecture
  • GraphQL endpoint for flexible queries
  • Multi-tenancy support
  • Advanced request/response caching
  • Machine learning-based anomaly detection
  • Real-time notifications with WebSocket
  • Partner onboarding portal

Contributing

Follow standard Spring Boot conventions:

  • Use meaningful commit messages
  • Add unit tests for new features
  • Follow code style guidelines
  • Document API changes

License

Proprietary - Internal Use Only

Support

For technical issues, contact the Integration team or Infrastructure team.

About

Payment Router - Resilient API Consumption & Orchestration Platform A comprehensive Spring Boot 3.2.0 application designed for Java 21, implementing enterprise-grade API orchestration with resilience patterns, secure authentication, and webhook management.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages