Skip to content
anushka8singhPublic

About

RecoverX is an AI revenue-recovery agent that investigates failed payments, decides the safest recovery strategy, executes bounded actions, and measures how much revenue it actually recovers.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RecoverX — AI-Powered Payment Recovery & Decisioning Platform

An AI-assisted payment recovery platform that identifies recoverable failed payments, generates structured recovery recommendations, validates them through deterministic policy rules, executes approved actions through Razorpay Test Mode, and verifies the final payment state through signed webhooks.

RecoverX is designed around a simple principle:

AI can recommend. Policy decides. The payment gateway executes. Webhooks verify.

The system combines AI reasoning, deterministic business rules, payment infrastructure, auditability, authentication, and evaluation into a single end-to-end recovery workflow.


Why RecoverX?

Failed payments are not all the same.

A transient bank timeout on a customer's first payment attempt may be worth retrying, while a suspicious customer, repeated failed attempts, captured payment, or high-value transaction may require the system to stop and avoid automated recovery.

RecoverX addresses this decision-making problem by separating:

  • Detection — Which failed payments are worth investigating?
  • Scoring — How likely is recovery?
  • AI Analysis — What recovery action should be considered?
  • Policy Enforcement — Is that recommendation actually allowed?
  • Execution — Can the approved action be safely performed?
  • Verification — Did the payment actually succeed?
  • Auditability — What did the AI recommend, what did policy decide, and what happened afterward?

This prevents an LLM from directly controlling payment operations.


Core Architecture

                    ┌──────────────────────┐
                    │      Frontend        │
                    │   React + Vite       │
                    └──────────┬───────────┘
                               │
                               ▼
                    ┌──────────────────────┐
                    │      REST API        │
                    │ Node.js + Express     │
                    └──────────┬───────────┘
                               │
              ┌────────────────┼────────────────┐
              │                │                │
              ▼                ▼                ▼
      ┌─────────────┐   ┌─────────────┐  ┌─────────────┐
      │  Detection  │   │ AI Analyst  │  │  Evaluation │
      │   Engine    │   │   Gemini    │  │   & Audit   │
      └──────┬──────┘   └──────┬──────┘  └──────┬──────┘
             │                 │                │
             └─────────────────┼────────────────┘
                               ▼
                    ┌──────────────────────┐
                    │    Policy Guard      │
                    │ Deterministic Rules  │
                    └──────────┬───────────┘
                               │
                         APPROVED?
                         /       \
                       NO         YES
                       │           │
                       ▼           ▼
                   BLOCK       Gateway Layer
                                   │
                         ┌─────────┴─────────┐
                         │                   │
                         ▼                   ▼
                    Simulation       Razorpay Test
                                          Mode
                                             │
                                             ▼
                                      Razorpay Checkout
                                             │
                                             ▼
                                      Signed Webhook
                                             │
                                             ▼
                                      Gateway Events
                                             │
                                             ▼
                                     Verified Recovery

Key Design Principle

RecoverX deliberately does not allow the AI model to directly execute payment operations.

The control flow is:

Payment Failure
      ↓
Recovery Detection
      ↓
Recovery Score
      ↓
AI Recommendation
      ↓
Deterministic Policy Validation
      ↓
 ┌───────────────┐
 │ APPROVED      │──────► Gateway
 │ REJECTED      │──────► Block
 └───────────────┘
                         ↓
                  Razorpay Test Mode
                         ↓
                  Checkout / Payment
                         ↓
                 Signed Razorpay Webhook
                         ↓
                 Persisted Gateway Event
                         ↓
                 Verified Recovery State

This separation provides a much safer architecture than allowing an LLM to directly call payment APIs.


Features

1. Intelligent Recovery Detection

RecoverX analyzes failed payments using recovery-oriented signals such as:

  • Payment attempt number
  • Failure reason
  • Customer payment history
  • Historical success rate
  • Customer lifetime value
  • Customer risk signals
  • Payment state
  • Recovery eligibility

Each recovery case receives:

  • Recovery score
  • Priority
  • Detection reason
  • Associated customer
  • Associated payment
  • Amount at risk

2. AI Recovery Analyst

The AI layer uses Gemini to generate a structured recovery recommendation.

Supported actions:

RETRY_PAYMENT
SEND_PAYMENT_LINK
NO_ACTION
ESCALATE

The AI output is treated as untrusted input.

It must pass validation before reaching the policy engine.

The system rejects:

  • Malformed AI output
  • Missing actions
  • Unsupported actions
  • Invalid confidence values
  • Free-form instructions attempting to bypass the system

AI output is intentionally limited to structured decision fields rather than storing or exposing chain-of-thought.


3. Deterministic Policy Guard

The policy engine is the main safety boundary between AI and payment execution.

It checks conditions including:

VALID_ACTION
CONFIDENCE_THRESHOLD
IGNORE_PRIORITY
RETRY_LIMIT
CUSTOMER_RISK
PAYMENT_STATE
FAILURE_REASON
INSUFFICIENT_FUNDS
RECOVERY_SCORE
AMOUNT_LIMIT
RECOVERABLE_PAYMENT

Example:

AI:
    Action      → RETRY_PAYMENT
    Confidence → 0.91

Policy:
    ✓ Valid action
    ✓ Confidence threshold
    ✓ Customer risk acceptable
    ✓ Payment recoverable
    ✓ Retry limit not exceeded
    ✓ Amount within automated limit

Decision:
    APPROVED

The important distinction is:

High AI confidence does not automatically mean execution is allowed.


4. Payment Safety Boundaries

RecoverX intentionally rejects automated recovery when safety conditions are violated.

Examples include:

  • Unsupported REFUND
  • Low-confidence retry
  • Suspicious customer
  • Third automated retry
  • Captured payment
  • Customer-abandoned checkout
  • Expired card
  • Amount above ₹10,000
  • Non-recoverable payment

This creates a deterministic safety layer that does not depend on the LLM behaving correctly.


5. Razorpay Test Mode Integration

RecoverX integrates with Razorpay Test Mode to demonstrate a realistic payment execution flow without processing real money.

The gateway layer is isolated behind an adapter:

RecoverX
   ↓
Gateway Service
   ↓
Razorpay Adapter
   ↓
Razorpay Test Mode

The system supports:

  • Razorpay Test Mode order creation
  • Test Checkout
  • Checkout signature verification
  • Razorpay webhook verification
  • Payment/order correlation
  • Duplicate webhook handling
  • Persisted gateway events
  • Verified recovery state

No real money is charged in the demo environment.


6. Webhook-Based Payment Verification

A successful checkout response alone is not treated as the final source of truth.

RecoverX uses Razorpay's signed webhook events to establish payment state.

Example:

Razorpay
    │
    │ order.paid
    ▼
/api/webhooks/razorpay
    │
    ├── Verify signature
    ├── Validate payload
    ├── Detect duplicate event
    ├── Match order/payment
    └── Persist GatewayEvent
            │
            ▼
       Recovery Case
            │
            ▼
      WEBHOOK CONFIRMED

This prevents the UI from simply assuming that opening or completing checkout means the payment was recovered.


7. Audit Trail

Every evaluated recovery decision can be audited.

The audit records structured information such as:

AI Recommendation
    ↓
Action
Confidence
Reason
    ↓
Policy Decision
    ↓
Policy Reasons
    ↓
Simulation / Gateway Outcome
    ↓
Recovery Result

The audit intentionally avoids storing model chain-of-thought.

This makes the system easier to inspect and explain.


8. Evaluation & Benchmarking

RecoverX includes an evaluation layer using Prisma aggregations to measure:

  • Policy evaluations
  • Approved recommendations
  • Rejected recommendations
  • Approval/rejection rate
  • Rejection reasons
  • AI action distribution
  • Simulations executed
  • Simulation success rate
  • Simulated recovery value
  • Average recovery probability
  • Recovery outcomes by action

It also includes a deterministic benchmark containing 10 synthetic scenarios.

Important: The benchmark is synthetic and is not presented as production model accuracy.


9. Authentication & Authorization

RecoverX includes session-based authentication.

Authentication

  • HTTP-only session cookie
  • HMAC-signed session payload
  • Password hashing using scrypt
  • Registration and login
  • Session validation
  • Logout

Roles

ADMIN
  │
  ├── Full access
  │
OPERATOR
  │
  ├── Recovery operations
  │
VIEWER
  │
  └── Read-only access

Sensitive recovery actions are protected by role-based authorization.

A viewer cannot execute payment recovery actions.


10. Security & Hardening

The backend includes:

  • Environment validation
  • Secret protection
  • Centralized error handling
  • Safe production error responses
  • Request logging
  • JSON body size limit
  • Security headers
  • Input validation
  • Rate limiting on analysis
  • AI output validation
  • Razorpay webhook signature verification
  • Checkout signature verification
  • Role-based authorization

Production errors do not expose internal stack traces.


Frontend

The frontend is built as an operational dashboard rather than a simple form-based demo.

The Case Detail workflow follows a single primary action at a time:

Analyze
   ↓
Evaluate
   ↓
Continue to Test Checkout
   ↓
Open Test Checkout
   ↓
Payment Verification
   ↓
Webhook Confirmed
   ↓
Recovery Confirmed

The interface exposes the important reasoning and system state without overwhelming the user with repeated actions.

Dashboard Areas

  • Recovery overview
  • Recovery cases
  • Case details
  • AI analysis
  • Policy checks
  • Payment execution
  • Razorpay verification
  • Audit history
  • Analytics
  • Settings
  • Authentication

Tech Stack

Frontend

  • React
  • Vite
  • React Router
  • Tailwind CSS
  • Axios

Backend

  • Node.js
  • Express.js
  • REST APIs
  • Middleware-based architecture

Database

  • PostgreSQL
  • Neon
  • Prisma ORM

AI

  • Google Gemini API
  • Structured AI output validation

Payments

  • Razorpay Test Mode
  • Razorpay Checkout
  • Razorpay Webhooks

Security

  • HTTP-only sessions
  • HMAC signing
  • scrypt password hashing
  • Role-based authorization
  • Request validation
  • Rate limiting
  • Security headers

Testing

  • Node.js native test runner
  • Frontend Vite production build
  • Deterministic policy tests
  • AI safety tests
  • Gateway adapter tests
  • Webhook signature tests
  • Authentication tests
  • Evaluation tests

Project Structure

recoverx/
│
├── client/
│   ├── src/
│   │   ├── api/
│   │   ├── auth/
│   │   ├── components/
│   │   ├── pages/
│   │   └── ...
│   └── ...
│
├── server/
│   ├── prisma/
│   │   ├── migrations/
│   │   └── schema.prisma
│   │
│   └── src/
│       ├── config/
│       ├── controllers/
│       ├── middleware/
│       ├── routes/
│       │
│       └── services/
│           ├── actions/
│           ├── ai/
│           ├── auth/
│           ├── evaluation/
│           ├── paymentGateway/
│           ├── policy/
│           └── ...
│
├── docs/
│   ├── phase-7.md
│   ├── phase-8.md
│   └── phase-9.2.md
│
├── .gitignore
└── README.md

API Overview

Health

GET /api/health

Returns service, database, execution mode, and gateway configuration status.


Authentication

POST /api/auth/register
POST /api/auth/login
POST /api/auth/logout
GET  /api/auth/me

Recovery

GET  /api/recovery/cases
GET  /api/recovery/cases/:id
POST /api/recovery/cases/:id/analyze
POST /api/recovery/cases/:id/evaluate
POST /api/recovery/cases/:id/execute
GET  /api/recovery/cases/:id/audit

Evaluation

GET /api/evaluation/overview
GET /api/evaluation/policy
GET /api/evaluation/simulation
GET /api/evaluation/benchmark

Razorpay

POST /api/webhooks/razorpay
GET  /api/payments/razorpay/status/:id

Getting Started

Prerequisites

Make sure you have installed:

  • Node.js
  • npm
  • PostgreSQL-compatible database
  • Razorpay Test Mode account
  • Gemini API key

1. Clone the repository

git clone https://github.com/<your-username>/recoverx-ai-payment-recovery.git

cd recoverx-ai-payment-recovery

2. Backend Setup

cd server
npm install

Create:

server/.env

Example:

DATABASE_URL="your_database_url"

GEMINI_API_KEY="your_gemini_api_key"
GEMINI_MODEL="your_gemini_model"

AUTH_SECRET="your_long_random_secret"

EXECUTION_MODE="simulation"

RAZORPAY_KEY_ID="your_razorpay_test_key_id"
RAZORPAY_KEY_SECRET="your_razorpay_test_key_secret"
RAZORPAY_WEBHOOK_SECRET="your_webhook_secret"

CORS_ORIGIN="http://localhost:5173"

Important

Never commit .env.

Never expose:

GEMINI_API_KEY
RAZORPAY_KEY_SECRET
RAZORPAY_WEBHOOK_SECRET
AUTH_SECRET
DATABASE_URL

to the frontend or GitHub.


3. Database Setup

From:

server/

run:

npx prisma migrate dev

Then:

npx prisma generate

Verify:

npx prisma migrate status

4. Start Backend

npm start

The API runs on:

http://localhost:5000

Check:

http://localhost:5000/api/health

5. Frontend Setup

Open another terminal:

cd client
npm install

Create:

client/.env
VITE_API_URL=http://localhost:5000

Start:

npm run dev

The frontend runs on:

http://localhost:5173

Razorpay Test Mode Setup

RecoverX uses Razorpay Test Mode for development and demonstrations.

The intended flow is:

RecoverX
   ↓
Create Razorpay Test Order
   ↓
Open Test Checkout
   ↓
Complete Test Payment
   ↓
Razorpay Webhook
   ↓
RecoverX
   ↓
Verify & Persist Event

For local webhook development, a tunneling service such as ngrok can expose:

http://localhost:5000

through a public HTTPS endpoint.

Configure the Razorpay webhook as:

https://<your-public-domain>/api/webhooks/razorpay

and use the same webhook secret in:

RAZORPAY_WEBHOOK_SECRET=

Running Tests

Run the complete backend suite:

node --test `
src/middleware/hardening.test.js `
src/services/recoveryDetection.test.js `
src/services/actions/actionEngine.test.js `
src/services/ai/recoveryAgent.test.js `
src/services/evaluation/evaluation.test.js `
src/services/paymentGateway/razorpayGateway.test.js `
src/services/policy/policyEngine.test.js `
src/services/auth/auth.test.js

Or use:

npm test

depending on the configured test script.


Test Coverage

The test suite covers:

Recovery Engine

  • Recovery scoring
  • Recovery eligibility
  • Determinism
  • Existing recovery cases

AI Layer

  • Tool boundaries
  • Structured output
  • Malformed output rejection
  • Unsupported recommendation rejection
  • Gemini failure handling

Policy Layer

  • Confidence threshold
  • Customer risk
  • Retry limits
  • Payment state
  • Amount limits
  • Failure reasons
  • Recoverability

Gateway Layer

  • Razorpay credentials
  • Gateway dispatch
  • Policy-before-gateway enforcement
  • Gateway failures
  • Webhook signatures
  • Duplicate events
  • Unsupported events
  • Checkout signature verification
  • Secret leakage prevention

Authentication

  • Registration validation
  • Password hashing
  • Session signing
  • Session tampering
  • Authentication guards
  • Role-based authorization

Evaluation

  • Synthetic benchmark
  • Audit mapping
  • Simulation metrics

Verification

The current implementation has been validated with:

Backend tests:       91 / 91 passing
Frontend build:      Vite production build successful
Database migrations: Up to date
Razorpay Test Mode: End-to-end payment verified
Webhook:             Signed webhook successfully processed
Authentication:      Session + RBAC tests passing

The Razorpay Test Mode flow has been manually verified through:

AI recommendation
        ↓
Policy approval
        ↓
Razorpay Test Order
        ↓
Test Checkout
        ↓
order.paid webhook
        ↓
GatewayEvent
        ↓
Recovery confirmation

Example Recovery Flow

Consider a failed payment:

Payment
──────────────
Amount: ₹7,999
Attempt: 1
Failure: BANK_TIMEOUT

Customer history:

Previous successful payments
High lifetime value
Acceptable risk

Recovery engine:

Recovery Score: HIGH
Priority: HIGH

AI:

Action: RETRY_PAYMENT
Confidence: 0.91

Policy:

11/11 checks passed
Decision: APPROVED

Gateway:

Razorpay Test Order Created

Customer completes checkout.

Razorpay sends:

order.paid

RecoverX verifies the webhook and records:

Payment: CAPTURED
Webhook: CONFIRMED
Recovery: CONFIRMED

The complete decision chain is available through the audit trail.


Safety Model

RecoverX follows a layered defense model:

                 AI
                  │
                  ▼
        ┌───────────────────┐
        │ Structured Output │
        └─────────┬─────────┘
                  │
                  ▼
        ┌───────────────────┐
        │ Input Validation  │
        └─────────┬─────────┘
                  │
                  ▼
        ┌───────────────────┐
        │ Policy Guard      │
        │ Deterministic     │
        └─────────┬─────────┘
                  │
             APPROVED?
              /       \
            NO         YES
            │           │
            ▼           ▼
          BLOCK       Gateway
                         │
                         ▼
                     Webhook
                         │
                         ▼
                  Verify State

This means the AI is not the final authority over payment execution.


Engineering Highlights

RecoverX demonstrates several production-oriented engineering concepts:

  • Separation of AI reasoning from deterministic business logic
  • Adapter-based payment gateway integration
  • Signed webhook verification
  • Idempotent webhook processing
  • Role-based authorization
  • HTTP-only authentication cookies
  • Password hashing with scrypt
  • Environment-based configuration
  • Centralized error handling
  • Database migrations with Prisma
  • Structured audit records
  • Deterministic policy enforcement
  • Synthetic evaluation benchmarks
  • Test-driven safety boundaries
  • Simulation-first development
  • External payment gateway integration

Current Execution Modes

RecoverX supports:

Simulation

EXECUTION_MODE=simulation

No external payment operation is performed.

Useful for:

  • Development
  • Automated tests
  • Local demos

Razorpay Test Mode

EXECUTION_MODE=razorpay_test

Creates Razorpay sandbox orders and allows the complete checkout/webhook workflow to be demonstrated.

No real money is processed.

Production / Live Payments

Live payment execution is intentionally not enabled by the current implementation.


Important Limitations

RecoverX is a portfolio/research-oriented system and is not intended to be used as a production payment recovery platform without additional infrastructure and compliance work.

Current limitations include:

  • Razorpay integration is Test Mode only
  • No real-money payment execution
  • In-memory rate limiting
  • No distributed job queue
  • No production observability stack
  • Synthetic benchmark data
  • No claim of production AI accuracy
  • Deployment-specific infrastructure still required
  • Additional compliance/security review would be required for real financial workloads

Project Philosophy

RecoverX is built around a simple distinction:

Probabilistic intelligence should not directly control deterministic financial actions.

The AI layer is useful for interpreting recovery context and proposing an action.

The policy layer determines whether that action is permitted.

The payment gateway performs the external operation.

The webhook provides independent confirmation of what actually happened.

That separation makes the system more explainable, testable, and safer to evolve.


Author

Anushka Singh

Computer Science Engineering


Built With

React · Node.js · Express · PostgreSQL · Prisma · Gemini · Razorpay · Vite · Tailwind CSS



About

RecoverX is an AI revenue-recovery agent that investigates failed payments, decides the safest recovery strategy, executes bounded actions, and measures how much revenue it actually recovers.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages