# Complete UPI PSP API Documentation

## Overview
This document describes the complete UPI (Unified Payments Interface) PSP (Payment Service Provider) implementation that supports all 8 mandatory APIs as per NPCI specification for UPI International transactions.

## Architecture

### UPI International Flow
```
[Indian Customer] → [NPCI] → [Your PSP] → [International Partner] → [International Merchant]
      (INR)          (INR)       (INR→FX)        (Foreign Currency)        (Local Currency)
```

1. **Customer Scan**: Indian customer scans QR code at international merchant
2. **NPCI Debit**: NPCI debits INR from customer's bank account
3. **PSP Credit**: NPCI credits your PSP with INR amount
4. **FX Conversion**: Your PSP converts INR to merchant's local currency
5. **Partner Credit**: Your PSP credits international partner
6. **Merchant Credit**: Partner credits merchant in local currency

## API Endpoints

### Base URL
- **Production**: `https://your-psp-domain.com/api/v1`
- **UAT**: `https://uat-your-psp-domain.com/api/v1`

### Content Type
All APIs accept and return XML with `Content-Type: application/xml`

## Core UPI APIs (8 Mandatory APIs)

### 1. ReqValQR - QR Validation Request
**Direction**: NPCI → PSP  
**Endpoint**: `POST /upi/validate-qr`  
**Purpose**: Validate merchant QR code and return merchant details

#### Request XML
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ReqValQr>
    <Head ver="1.0" ts="2024-01-15T10:30:00+05:30" orgId="NPCI" msgId="MSG123456789"/>
    <QrData qrString="upi://pay?pa=merchant@paytm&pn=TestMerchant&tr=TXN123&am=100.00"/>
    <ExpireAfter>300</ExpireAfter>
    <Rules>INTL</Rules>
</ReqValQr>
```

#### Response XML (RespValQR)
```xml
<?xml version="1.0" encoding="UTF-8"?>
<RespValQr>
    <Head ver="1.0" ts="2024-01-15T10:30:05+05:30" orgId="MERCURY001" msgId="MSG987654321"/>
    <Resp reqMsgId="MSG123456789" result="SUCCESS" errCode="00"/>
    <Txn id="TXN123456789" note="QR Validation" refId="REF123" refUrl="https://merchant.com" ts="2024-01-15T10:30:05+05:30" type="COLLECT"/>
    <Payees>
        <Payee addr="merchant@paytm" name="Test Merchant" type="ENTITY" code="5411"/>
    </Payees>
    <Amount curr="INR" value="100.00"/>
    <MerchantTran>
        <Merchant>
            <genre>RETAIL</genre>
            <type>SMALL</type>
            <brand>TestBrand</brand>
            <logo>https://example.com/logo.png</logo>
            <id>MERCHANT_001</id>
            <name>Test Merchant</name>
        </Merchant>
    </MerchantTran>
</RespValQr>
```

### 2. ReqPay - Payment Request
**Direction**: NPCI → PSP  
**Endpoint**: `POST /upi/process-payment`  
**Purpose**: Process payment transaction (both CREDIT and REVERSAL)

#### Request XML (CREDIT)
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ReqPay>
    <Head ver="1.0" ts="2024-01-15T10:35:00+05:30" orgId="NPCI" msgId="MSG987654321"/>
    <Txn id="UPI123456789" orgTxnId="NPCI123456789" note="International Payment" refId="REF123" type="PAY" custRef="CUST123"/>
    <Amount curr="INR" value="1000.00"/>
    <Payer addr="customer@sbi" name="John Doe"/>
    <Payee addr="merchant@paytm" name="Test Merchant" type="ENTITY" code="5411"/>
</ReqPay>
```

#### Request XML (REVERSAL)
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ReqPay>
    <Head ver="1.0" ts="2024-01-15T10:50:00+05:30" orgId="NPCI" msgId="MSG111222333"/>
    <Txn id="UPI123456789" orgTxnId="NPCI123456789" note="Transaction Reversal" refId="REF123" type="REVERSAL" custRef="CUST123"/>
    <Amount curr="INR" value="1000.00"/>
    <Payer addr="customer@sbi" name="John Doe"/>
    <Payee addr="merchant@paytm" name="Test Merchant" type="ENTITY" code="5411"/>
</ReqPay>
```

#### Response XML (RespPay)
```xml
<?xml version="1.0" encoding="UTF-8"?>
<RespPay>
    <Head ver="1.0" ts="2024-01-15T10:35:05+05:30" orgId="MERCURY001" msgId="MSG555666777"/>
    <Resp reqMsgId="MSG987654321" result="SUCCESS" errCode="00"/>
    <Txn id="TXN987654321" custRef="CUST123" ts="2024-01-15T10:35:05+05:30" type="PAY"/>
    <AddInfo>Partner Ref: PTR123456, Rate: 0.012</AddInfo>
</RespPay>
```

### 3. ReqChkTxn - Check Transaction Request
**Direction**: NPCI → PSP  
**Endpoint**: `POST /upi/check-transaction`  
**Purpose**: Check transaction status

#### Request XML
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ReqChkTxn>
    <Head ver="1.0" ts="2024-01-15T10:40:00+05:30" orgId="NPCI" msgId="MSG555666777"/>
    <Txn orgTxnId="NPCI123456789"/>
</ReqChkTxn>
```

#### Response XML (RespChkTxn)
```xml
<?xml version="1.0" encoding="UTF-8"?>
<RespChkTxn>
    <Head ver="1.0" ts="2024-01-15T10:40:05+05:30" orgId="MERCURY001" msgId="MSG888999000"/>
    <Resp reqMsgId="MSG555666777" result="SUCCESS" errCode="00"/>
    <Txn id="TXN987654321" orgTxnId="NPCI123456789" status="SUCCESS" ts="2024-01-15T10:40:05+05:30"/>
    <Amount curr="INR" value="1000.00"/>
</RespChkTxn>
```

### 4. ReqHbt - Heartbeat Request
**Direction**: NPCI → PSP  
**Endpoint**: `POST /upi/heartbeat`  
**Purpose**: Health monitoring and connectivity check

#### Request XML
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ReqHbt>
    <Head ver="1.0" ts="2024-01-15T10:45:00+05:30" orgId="NPCI" msgId="HBT123456789"/>
</ReqHbt>
```

#### Response XML (RespHbt)
```xml
<?xml version="1.0" encoding="UTF-8"?>
<RespHbt>
    <Head ver="1.0" ts="2024-01-15T10:45:00+05:30" orgId="MERCURY001" msgId="HBT987654321"/>
    <Resp reqMsgId="HBT123456789" result="SUCCESS" errCode="00"/>
</RespHbt>
```

## Enhanced APIs

### 5. Batch Check Transactions
**Endpoint**: `POST /upi/batch-check`  
**Purpose**: Check multiple transaction statuses in one request

#### Request XML
```xml
<?xml version="1.0" encoding="UTF-8"?>
<BatchReqChkTxn>
    <Head ver="1.0" ts="2024-01-15T11:00:00+05:30" orgId="NPCI" msgId="BATCH123456"/>
    <Transactions>
        <orgTxnId>NPCI123456789</orgTxnId>
        <orgTxnId>NPCI987654321</orgTxnId>
        <orgTxnId>NPCI555666777</orgTxnId>
    </Transactions>
</BatchReqChkTxn>
```

### 6. Reconciliation
**Endpoint**: `POST /upi/reconciliation`  
**Purpose**: End-of-day settlement reconciliation

#### Request XML
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ReqReconciliation>
    <Head ver="1.0" ts="2024-01-15T11:05:00+05:30" orgId="NPCI" msgId="RECON123456"/>
    <fromDate>2024-01-15T00:00:00+05:30</fromDate>
    <toDate>2024-01-15T23:59:59+05:30</toDate>
</ReqReconciliation>
```

### 7. Mandate Management
**Endpoint**: `POST /upi/mandate`  
**Purpose**: Recurring payment mandate processing

#### Request XML
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ReqMandate>
    <Head ver="1.0" ts="2024-01-15T11:10:00+05:30" orgId="NPCI" msgId="MANDATE123456"/>
    <mandateId>MND123456789</mandateId>
    <amount>500.00</amount>
    <frequency>MONTHLY</frequency>
    <validUntil>2025-01-15T11:10:00+05:30</validUntil>
</ReqMandate>
```

## Error Codes

### Standard UPI Error Codes
| Code | Description |
|------|-------------|
| 00 | Transaction is successful |
| 01 | Transaction is pending |
| 02 | Transaction failed |
| 03 | Transaction timeout |
| 04 | Format Error in transaction |
| 05 | Invalid transaction |
| 06 | Amount limit exceeded |
| 07 | Permission denied |
| 08 | Invalid response |
| 09 | Collect request expired |
| 10 | Debit has been failed |
| 11 | Credit has been failed |
| 12 | UPI PIN has not been set by customer |
| 13 | Transaction not allowed to this account |
| 14 | External Error |
| 15 | Request declined by user |
| 16 | Risk threshold exceeded |
| 17 | Requester cannot perform this operation |
| 18 | Required field missing |
| 19 | Address resolution failed |
| 20 | Credit reversal timeout |
| 21 | Debit reversal timeout |
| 91 | Invalid Parameters |
| 92 | No such mobile/account |
| 93 | Validation Error |
| 94 | Beneficiary bank unavailable |
| 95 | Issuer or switch inoperative |
| 96 | System malfunction |
| 97 | Timeout at Acquirer end |
| 98 | Duplicate transaction |
| 99 | Request could not be delivered |
| ZH | Invalid XML |
| ZM | Checksum failed |
| ZP | PSP OrgId not found |
| ZQ | QR code not found |
| ZR | Merchant not found |

## Transaction States

### Internal States
- **initiated**: Transaction initiated by NPCI
- **validated**: QR/Merchant validated
- **processing**: Payment processing with partner
- **success**: Transaction completed successfully
- **failed**: Transaction failed
- **timeout**: Transaction timed out
- **reversed**: Transaction reversed
- **deemed_success**: Deemed success after timeout

### UPI Status Mapping
- **initiated/processing/timeout** → "PENDING"
- **success/deemed_success** → "SUCCESS"
- **failed/reversed** → "FAILED"

## Security

### Authentication
- PSP must authenticate with NPCI using digital certificates
- All XML messages must be digitally signed
- TLS 1.2+ encryption required for all communications

### Data Protection
- PII data must be masked in logs
- Transaction data retention as per RBI guidelines
- PCI DSS compliance for card-related data

## Rate Limits

### Production Limits
- QR Validation: 1000 requests/minute
- Payment Processing: 500 requests/minute
- Status Check: 2000 requests/minute
- Heartbeat: Unlimited

### Error Handling
- Retry logic with exponential backoff
- Circuit breaker pattern for partner APIs
- Graceful degradation for non-critical failures

## Monitoring

### Key Metrics
- Transaction success rate
- Average response time
- Partner API latency
- Error rate by type
- Daily/monthly volume

### Alerts
- Transaction failure rate > 5%
- Response time > 5 seconds
- Partner API errors
- System health issues

## Testing

### Test Environment
- UAT Base URL: `https://uat-your-psp-domain.com/api/v1`
- Test data provided by NPCI
- Sandbox partner integration

### Test Script
Use the provided test script: `./test_complete_upi_implementation.sh`

```bash
# Run all tests
./test_complete_upi_implementation.sh

# Run specific test phases
./test_complete_upi_implementation.sh --phase core
./test_complete_upi_implementation.sh --phase enhanced
./test_complete_upi_implementation.sh --phase compliance
```

## Deployment

### Environment Variables
```bash
# PSP Configuration
PSP_ORG_ID=MERCURY001
PSP_BASE_URL=https://your-psp-domain.com
PSP_CERT_PATH=/path/to/psp-cert.pem
PSP_PRIVATE_KEY_PATH=/path/to/psp-private-key.pem

# NPCI Configuration
NPCI_BASE_URL=https://npci-prod.upi.org.in
NPCI_CERT_PATH=/path/to/npci-cert.pem

# Database Configuration
DATABASE_URL=postgresql://user:pass@localhost/upi_psp_prod

# Partner Configuration
PARTNER_API_URL=https://international-partner.com/api
PARTNER_API_KEY=your-partner-api-key
PARTNER_TIMEOUT_MS=30000

# Security
JWT_SECRET=your-jwt-secret
ENCRYPTION_KEY=your-32-byte-encryption-key
```

### Production Checklist
- [ ] NPCI certification completed
- [ ] Production certificates installed
- [ ] Load testing completed
- [ ] Security audit passed
- [ ] Monitoring setup
- [ ] Alerting configured
- [ ] Backup strategy implemented
- [ ] Disaster recovery tested
- [ ] Documentation updated
- [ ] Team training completed

## Support

### Technical Support
- Email: tech-support@your-psp-domain.com
- Phone: +91-XXXX-XXXXXX
- Slack: #upi-psp-support

### Business Support  
- Email: business@your-psp-domain.com
- Phone: +91-XXXX-XXXXXX

### Emergency Contact
- 24/7 Hotline: +91-XXXX-XXXXXX
- Email: emergency@your-psp-domain.com

---

*This documentation covers the complete UPI PSP implementation as per NPCI specification v1.0. Last updated: January 2024*
