# PhonePe Payment Gateway Integration

Complete guide to integrate PhonePe payments in LuckyChit app.

## 🚀 Features

- ✅ **Direct UPI Payments** - Members pay installments via PhonePe
- ✅ **Secure Transactions** - SHA256 checksum verification
- ✅ **Real-time Status** - Instant payment confirmation
- ✅ **Auto-recording** - Payments automatically recorded in system
- ✅ **Refund Support** - Managers can initiate refunds
- ✅ **Transaction History** - Complete payment audit trail

## 📋 Prerequisites

### 1. PhonePe Merchant Account

1. Sign up at [PhonePe Business Portal](https://business.phonepe.com/)
2. Complete KYC verification
3. Get your merchant credentials:
   - **Merchant ID** (e.g., `M1234567890`)
   - **Salt Key** (secret key for checksum)
   - **Salt Index** (usually `1`)

### 2. Backend Setup

#### Install Dependencies

```bash
cd backend
npm install axios crypto
```

#### Environment Variables

Add to `backend/.env`:

```env
# PhonePe Configuration
PHONEPE_MERCHANT_ID=your_merchant_id_here
PHONEPE_SALT_KEY=your_salt_key_here
PHONEPE_SALT_INDEX=1
PHONEPE_ENV=sandbox  # Change to 'production' for live

# PhonePe URLs
PHONEPE_REDIRECT_URL=https://chitfund.deepteklabs.com/payment/callback
PHONEPE_CALLBACK_URL=https://chitfund.deepteklabs.com/api/payments/phonepe/callback
```

#### API Endpoints Created

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/payments/phonepe/initiate` | POST | Start payment |
| `/api/payments/phonepe/callback` | POST | PhonePe webhook |
| `/api/payments/phonepe/verify` | POST | Verify payment |
| `/api/payments/phonepe/status/:id` | GET | Check status |
| `/api/payments/phonepe/refund` | POST | Refund payment |

### 3. Flutter App Setup

#### Install Dependencies

Add to `luckychit/pubspec.yaml`:

```yaml
dependencies:
  url_launcher: ^6.2.1  # For opening PhonePe app
```

#### Initialize Service

In `luckychit/lib/app.dart`:

```dart
import 'core/services/phonepe_service.dart';

// In initServices()
Get.put(PhonePeService());
```

#### Usage in UI

```dart
import 'package:luckychit/interfaces/member/member_payment_dialog.dart';

// Show payment dialog
showDialog(
  context: context,
  builder: (context) => MemberPaymentDialog(
    group: chitGroup,
    member: currentMember,
    month: DateTime.now().month,
    year: DateTime.now().year,
  ),
);
```

## 🔄 Payment Flow

### Step 1: Member Initiates Payment

```
Member Dashboard → Pay Installment → Select Month/Year → Pay with PhonePe
```

### Step 2: Backend Creates Payment Request

1. Validates member and group
2. Creates pending payment record
3. Generates PhonePe payload with checksum
4. Returns payment URL to app

### Step 3: PhonePe Payment

1. App opens PhonePe app/web
2. Member completes payment
3. PhonePe redirects back to app

### Step 4: Verification

1. PhonePe sends webhook to callback URL
2. Backend verifies checksum
3. Checks payment status with PhonePe API
4. Updates payment record to 'success'

### Step 5: Confirmation

1. App shows success message
2. Member sees updated payment status
3. Manager gets notification

## 🛠 Testing

### Sandbox Mode

PhonePe provides test credentials for sandbox:

```env
PHONEPE_ENV=sandbox
PHONEPE_MERCHANT_ID=PGTESTPAYUAT
PHONEPE_SALT_KEY=099eb0cd-02cf-4e2a-8aca-3e6c6aff0399
PHONEPE_SALT_INDEX=1
```

### Test Cards

| Card Number | Behavior |
|-------------|----------|
| `4111 1111 1111 1111` | Success |
| `4000 0000 0000 0002` | Declined |
| `5555 5555 5555 4444` | Timeout |

### Test UPI IDs

- `success@upi` - Successful payment
- `failure@upi` - Failed payment

## 🔐 Security

### Checksum Generation

```javascript
// Payload + Endpoint + Salt Key → SHA256
const string = base64Payload + endpoint + saltKey;
const checksum = sha256(string) + '###' + saltIndex;
```

### Checksum Verification

```javascript
// Verify callback from PhonePe
const [checksum, saltIndex] = header.split('###');
const string = base64Response + saltKey;
const calculatedChecksum = sha256(string);
return checksum === calculatedChecksum;
```

## 📊 Payment States

| Status | Description |
|--------|-------------|
| `pending` | Payment initiated |
| `success` | Payment completed |
| `failed` | Payment declined/error |
| `cancelled` | Refunded |

## 🔄 Refund Process

### Manager Initiates Refund

```dart
// From manager dashboard
final success = await phonePeService.initiateRefund(
  transactionId: 'TXN_123',
  amount: 10000.00,
  reason: 'Duplicate payment',
);
```

### Backend Processes

1. Validates manager permissions
2. Checks payment is 'success' status
3. Creates refund request with PhonePe
4. Updates payment status to 'cancelled'

## 📱 Deep Links (Optional)

### Android

Add to `AndroidManifest.xml`:

```xml
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data
        android:scheme="luckychit"
        android:host="payment" />
</intent-filter>
```

### iOS

Add to `Info.plist`:

```xml
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>luckychit</string>
        </array>
    </dict>
</array>
```

## 🐛 Troubleshooting

### Issue: Payment status stuck on "pending"

**Solution:**
- Check PhonePe callback URL is publicly accessible
- Verify webhook is reaching your server
- Check server logs for callback errors

### Issue: Checksum mismatch

**Solution:**
- Verify salt key and index are correct
- Ensure no extra spaces in environment variables
- Check endpoint path matches exactly

### Issue: Payment succeeds but not recorded

**Solution:**
- Check database connection
- Verify Payment model update logic
- Check for transaction conflicts

## 📞 PhonePe Support

- **Docs**: https://developer.phonepe.com/
- **Support**: https://business.phonepe.com/support
- **Status**: https://status.phonepe.com/

## 🚀 Going Live

### Checklist

- [ ] Get production merchant credentials
- [ ] Set `PHONEPE_ENV=production`
- [ ] Update callback URLs to production domain
- [ ] Test with small real payments
- [ ] Monitor first few transactions closely
- [ ] Set up error alerting
- [ ] Document transaction IDs

### Production Environment

```env
PHONEPE_ENV=production
PHONEPE_MERCHANT_ID=your_production_merchant_id
PHONEPE_SALT_KEY=your_production_salt_key
PHONEPE_REDIRECT_URL=https://chitfund.deepteklabs.com/payment/callback
PHONEPE_CALLBACK_URL=https://chitfund.deepteklabs.com/api/payments/phonepe/callback
```

## 💡 Best Practices

1. **Always verify payments** - Never trust client-side status
2. **Log all transactions** - Keep audit trail
3. **Handle timeouts** - Payment might succeed even if timeout
4. **Retry verification** - Network issues can cause false negatives
5. **Notify users** - Send confirmations via SMS/email
6. **Monitor refunds** - Track refund reasons and patterns

## 📈 Analytics

Track these metrics:
- Payment success rate
- Average payment time
- Failed payment reasons
- Refund frequency
- Member payment patterns

---

**Need Help?** Contact PhonePe support or check the [developer documentation](https://developer.phonepe.com/).

