# M-Pesa Integration for HAVEN GRAZURI Advance

This document explains the automatic M-Pesa payment integration that has been added to your loan management system.

## Features

### 🚀 Automatic Payment Processing
- **Real-time Callbacks**: Receives M-Pesa payment notifications instantly
- **Smart Loan Matching**: Automatically matches payments to the correct loans
- **Multiple Loan Support**: Handles customers with multiple active loans intelligently
- **Phone Number Matching**: Links payments to borrowers using phone numbers

### 🧠 Smart Loan Allocation Logic

The system uses a sophisticated algorithm to determine which loan a payment should be applied to:

1. **Bill Reference Match**: If the customer enters a loan number as the account number, it matches exactly
2. **Single Loan**: If the customer has only one active loan, payment goes there automatically  
3. **Amount Matching**: Matches payments to loans with similar outstanding amounts
4. **Oldest First**: Falls back to applying payment to the oldest loan by due date

### 📊 Admin Dashboard
- **Real-time Statistics**: View payment volumes, success rates, and pending transactions
- **Transaction Management**: Monitor all M-Pesa transactions with detailed filtering
- **Failed Payment Recovery**: Manually reprocess failed transactions
- **Configuration Management**: Easy setup and URL registration

## Setup Instructions

### 1. Run Database Migrations
```bash
python manage.py makemigrations payments
python manage.py migrate
```

### 2. Configure M-Pesa Settings
```bash
python manage.py setup_mpesa \
    --environment sandbox \
    --consumer-key YOUR_CONSUMER_KEY \
    --consumer-secret YOUR_CONSUMER_SECRET \
    --business-short-code YOUR_PAYBILL_NUMBER \
    --base-url https://yourdomain.com
```

### 3. Register Callback URLs
The system will automatically register these URLs with M-Pesa:
- **Validation URL**: `https://yourdomain.com/payments/mpesa/validation/`
- **Confirmation URL**: `https://yourdomain.com/payments/mpesa/confirmation/`

### 4. Test the Integration
1. Go to `/payments/test-payment/` in your admin panel
2. Use sandbox test phone numbers (254708374149)
3. Simulate payments and verify they're processed correctly

## How It Works

### Payment Flow
1. **Customer Payment**: Customer sends money to your M-Pesa paybill
2. **M-Pesa Validation**: M-Pesa sends validation request to your system
3. **Smart Matching**: System matches phone number to borrower and loan
4. **Validation Response**: System approves or rejects the payment
5. **Payment Confirmation**: M-Pesa confirms successful payment
6. **Automatic Processing**: System creates repayment record and updates loan
7. **Notifications**: Borrower and loan officer receive notifications

### Phone Number Matching
The system tries multiple phone number formats:
- `0712345678` → `254712345678` → `+254712345678`
- Handles masked numbers from M-Pesa callbacks

### Loan Matching Strategies
1. **Exact Reference**: Customer enters `LOAN-000123` as account number
2. **Single Active Loan**: Only one loan exists, payment goes there
3. **Amount Match**: Payment amount matches outstanding balance (±10 KES tolerance)
4. **Oldest Loan**: Payment goes to loan with earliest due date

## Admin Interface

### Dashboard (`/payments/dashboard/`)
- View payment statistics and recent transactions
- Monitor failed payments needing attention
- Quick access to configuration and testing

### Transactions (`/payments/transactions/`)
- List all M-Pesa transactions with filtering
- Search by phone number, amount, date range
- View transaction details and processing notes

### Configuration (`/payments/configuration/`)
- Manage M-Pesa API credentials
- Set callback URLs
- Switch between sandbox and production

## Customer Experience

### For Customers with One Loan
1. Send money to your M-Pesa paybill
2. Enter any account number or leave blank
3. Payment automatically applies to their loan
4. Receive confirmation SMS and system notification

### For Customers with Multiple Loans
1. **Option 1**: Enter specific loan number (e.g., `LOAN-000123`) as account number
2. **Option 2**: Send exact outstanding amount to match specific loan
3. **Option 3**: Send any amount - system applies to oldest loan first

## Error Handling

### Failed Payments
- System logs all failures with detailed error messages
- Admin can manually reprocess failed transactions
- Automatic retry logic for temporary failures

### Unmatched Payments
- Payments from unregistered phone numbers are logged but not processed
- Admin receives notifications for manual review
- Can manually assign payments to correct borrowers

## Security Features

### Callback Validation
- Validates M-Pesa callback authenticity
- Logs all callback attempts with IP addresses
- Prevents duplicate transaction processing

### Data Protection
- Customer phone numbers are masked in logs
- Sensitive M-Pesa data is encrypted
- Audit trail for all payment processing

## Monitoring & Reporting

### Real-time Metrics
- Total transactions processed
- Success/failure rates
- Daily payment volumes
- Average processing time

### Notifications
- Instant notifications to borrowers on payment receipt
- Loan officer notifications for their portfolio clients
- Admin alerts for failed payments

## Troubleshooting

### Common Issues

**1. Payment not processed automatically**
- Check if phone number matches borrower's registered number
- Verify borrower has active loans
- Check transaction logs for error messages

**2. Wrong loan charged**
- Customer should use loan number as account number
- Or send exact outstanding amount
- Admin can manually reallocate payments

**3. Callback URLs not working**
- Ensure URLs are publicly accessible
- Use HTTPS in production
- Check firewall settings

### Support Commands
```bash
# View recent transactions
python manage.py shell -c "from payments.models import MpesaTransaction; print(MpesaTransaction.objects.all()[:5])"

# Reprocess failed transaction
python manage.py shell -c "from payments.models import MpesaTransaction; t=MpesaTransaction.objects.get(trans_id='XXXXX'); t.process_payment()"

# Check configuration
python manage.py shell -c "from payments.models import MpesaConfiguration; print(MpesaConfiguration.get_active_config())"
```

## Production Deployment

### 1. Switch to Production Environment
- Update configuration to use production credentials
- Change environment from 'sandbox' to 'production'
- Re-register callback URLs

### 2. SSL Certificate
- Ensure your domain has valid SSL certificate
- M-Pesa requires HTTPS for production callbacks

### 3. Monitoring
- Set up log monitoring for payment failures
- Configure alerts for high failure rates
- Monitor callback response times

## API Endpoints

### Public Endpoints (No Authentication)
- `POST /payments/mpesa/validation/` - M-Pesa validation callback
- `POST /payments/mpesa/confirmation/` - M-Pesa confirmation callback

### Admin Endpoints (Authentication Required)
- `GET /payments/dashboard/` - Payment dashboard
- `GET /payments/transactions/` - Transaction list
- `GET /payments/configuration/` - M-Pesa configuration
- `POST /payments/test-payment/` - Payment simulation (sandbox only)

## Support

For technical support or questions about the M-Pesa integration:

1. Check the admin dashboard for error messages
2. Review transaction logs in `/payments/transactions/`
3. Test with sandbox environment first
4. Contact your system administrator for configuration issues

---

**Note**: This integration follows M-Pesa C2B (Customer to Business) API specifications and handles all the complexity of payment matching and processing automatically.