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.
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.
┌──────────────────────┐
│ 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
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.
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
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.
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.
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.
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.
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.
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.
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.
RecoverX includes session-based authentication.
- HTTP-only session cookie
- HMAC-signed session payload
- Password hashing using
scrypt - Registration and login
- Session validation
- Logout
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.
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.
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.
- Recovery overview
- Recovery cases
- Case details
- AI analysis
- Policy checks
- Payment execution
- Razorpay verification
- Audit history
- Analytics
- Settings
- Authentication
- React
- Vite
- React Router
- Tailwind CSS
- Axios
- Node.js
- Express.js
- REST APIs
- Middleware-based architecture
- PostgreSQL
- Neon
- Prisma ORM
- Google Gemini API
- Structured AI output validation
- Razorpay Test Mode
- Razorpay Checkout
- Razorpay Webhooks
- HTTP-only sessions
- HMAC signing
- scrypt password hashing
- Role-based authorization
- Request validation
- Rate limiting
- Security headers
- 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
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
GET /api/healthReturns service, database, execution mode, and gateway configuration status.
POST /api/auth/register
POST /api/auth/login
POST /api/auth/logout
GET /api/auth/meGET /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/auditGET /api/evaluation/overview
GET /api/evaluation/policy
GET /api/evaluation/simulation
GET /api/evaluation/benchmarkPOST /api/webhooks/razorpay
GET /api/payments/razorpay/status/:idMake sure you have installed:
- Node.js
- npm
- PostgreSQL-compatible database
- Razorpay Test Mode account
- Gemini API key
git clone https://github.com/<your-username>/recoverx-ai-payment-recovery.git
cd recoverx-ai-payment-recoverycd server
npm installCreate:
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"Never commit .env.
Never expose:
GEMINI_API_KEY
RAZORPAY_KEY_SECRET
RAZORPAY_WEBHOOK_SECRET
AUTH_SECRET
DATABASE_URL
to the frontend or GitHub.
From:
server/
run:
npx prisma migrate devThen:
npx prisma generateVerify:
npx prisma migrate statusnpm startThe API runs on:
http://localhost:5000
Check:
http://localhost:5000/api/health
Open another terminal:
cd client
npm installCreate:
client/.env
VITE_API_URL=http://localhost:5000Start:
npm run devThe frontend runs on:
http://localhost:5173
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=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.jsOr use:
npm testdepending on the configured test script.
The test suite covers:
- Recovery scoring
- Recovery eligibility
- Determinism
- Existing recovery cases
- Tool boundaries
- Structured output
- Malformed output rejection
- Unsupported recommendation rejection
- Gemini failure handling
- Confidence threshold
- Customer risk
- Retry limits
- Payment state
- Amount limits
- Failure reasons
- Recoverability
- Razorpay credentials
- Gateway dispatch
- Policy-before-gateway enforcement
- Gateway failures
- Webhook signatures
- Duplicate events
- Unsupported events
- Checkout signature verification
- Secret leakage prevention
- Registration validation
- Password hashing
- Session signing
- Session tampering
- Authentication guards
- Role-based authorization
- Synthetic benchmark
- Audit mapping
- Simulation metrics
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
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.
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.
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
RecoverX supports:
EXECUTION_MODE=simulationNo external payment operation is performed.
Useful for:
- Development
- Automated tests
- Local demos
EXECUTION_MODE=razorpay_testCreates Razorpay sandbox orders and allows the complete checkout/webhook workflow to be demonstrated.
No real money is processed.
Live payment execution is intentionally not enabled by the current implementation.
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
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.
Anushka Singh
Computer Science Engineering
React · Node.js · Express · PostgreSQL · Prisma · Gemini · Razorpay · Vite · Tailwind CSS