# Fix M-Pesa Payment NOW - Simple Steps

## 🎯 The Problem (Found!)

Your callback shows:
- ✅ Callback received from M-Pesa
- ❌ **Transaction was NEVER created**
- ❌ **Callback was NEVER processed**
- ⚠️ **Phone number is HASHED** (encrypted)

**Callback ID:** `682dc145-3a65-40df-b93c-bb688dab289d`  
**Trans ID:** `TK1018ZAQC`  
**Amount:** KES 1.00  
**Phone:** `99193bd8110f876a9408aa0ddc2478b585b4019969af0dd1ec83b20845edae95` (hashed!)

---

## 🚀 The Fix (3 Commands)

### Step 1: Upload New Command
Upload this file:
- **`payments/management/commands/process_callback.py`** (NEW)

### Step 2: Restart Application
```bash
touch /home/acbptxvs/public_html/branchbusinessadvance.co.ke/passenger_wsgi.py
```

### Step 3: Process the Callback
```bash
cd /home/acbptxvs/public_html/branchbusinessadvance.co.ke
python manage.py process_callback 682dc145-3a65-40df-b93c-bb688dab289d
```

This will:
1. ✅ Create the missing transaction
2. ✅ Link callback to transaction
3. ✅ Match borrower by phone
4. ✅ Match loan
5. ✅ Create repayment
6. ✅ Update loan balance

---

## 📊 Expected Output

```
======================================================================
Process M-Pesa Callback
======================================================================

Callback ID: 682dc145-3a65-40df-b93c-bb688dab289d
Type: confirmation
Date: 2025-11-01 06:07:28

Transaction Data:
  Trans ID: TK1018ZAQC
  Amount: KES 1.00
  Phone: 99193bd8110f876a9408aa0ddc2478b585b4019969af0dd1ec83b20845edae95
  Bill Ref: ...
  First Name: ...
  Last Name: ...

----------------------------------------------------------------------
Creating transaction...
----------------------------------------------------------------------

✓ Transaction created: abc123...

----------------------------------------------------------------------
Processing payment...
----------------------------------------------------------------------

======================================================================
✓ Payment Processed Successfully!
======================================================================

Transaction Status: processed
Matched Borrower: Phin Client
Matched Loan: LOAN-000123
Repayment Created: Yes
Receipt Number: RCP-000456

✓ Payment successfully applied to loan!

You can now view it at:
  • /loans/repayments/ - Repayment record
  • /payments/transactions/ - Transaction details
  • /loans/ - Updated loan balance
```

---

## ⚠️ About the Hashed Phone Number

The phone number is showing as a hash because M-Pesa is encrypting it. This is unusual but might be:
1. A security feature from Safaricom
2. A configuration setting
3. A test environment behavior

**The good news:** The command will still work! It will:
- Create the transaction with the hashed phone
- Try to match by other fields (Bill Ref Number, Name)
- Or you can manually link it after

---

## 🔧 Alternative: Process All Unprocessed

If you have multiple unprocessed callbacks:

```bash
python manage.py process_callback --all-unprocessed
```

This will process ALL callbacks that failed to create transactions.

---

## 📋 Files to Upload (6 Total)

### Critical Commands:
1. **`loans/models.py`** - Fixed phone matching
2. **`payments/management/commands/process_callback.py`** - **NEW** - Process callbacks
3. **`payments/management/commands/check_callbacks.py`** - Check callback status
4. **`payments/management/commands/check_mpesa_status.py`** - Check transaction status
5. **`payments/management/commands/fix_mpesa_payments.py`** - Fix unprocessed
6. **`payments/management/commands/reprocess_mpesa_transaction.py`** - Reprocess

### Templates (if needed):
7-10. The 4 template files

---

## ✅ Verification Steps

After running the command:

### 1. Check Callback Status
```bash
python manage.py check_callbacks
```

Should now show:
```
✓ Linked to Transaction: abc123...
✓ Processed: Yes
```

### 2. Check Transaction Status
```bash
python manage.py check_mpesa_status
```

Should show:
```
✓ Borrower: Phin Client
✓ Loan: LOAN-000123
✓ Repayment: RCP-000456
```

### 3. Check Web Pages
- `/payments/callbacks/` - Should show "Processed"
- `/payments/transactions/` - Should show transaction with borrower/loan
- `/loans/repayments/` - Should show repayment with M-Pesa badge
- `/loans/` - Should show updated balance

---

## 🐛 If Phone Matching Fails

Because the phone is hashed, it might not match any borrower. In that case:

### Option 1: Match by Bill Ref Number
If the customer entered their ID number as Bill Ref, it will match automatically.

### Option 2: Match by Name
If First Name + Last Name match a borrower, it will work.

### Option 3: Manual Linking
```python
# Django shell
from loans.models import MpesaTransaction
from users.models import User

# Get the transaction
t = MpesaTransaction.objects.get(trans_id='TK1018ZAQC')

# Find the borrower (replace with actual phone)
borrower = User.objects.get(phone_number='+254114565176')

# Link them
t.borrower = borrower
t.save()

# Process payment
t.process_payment()

print(f"Repayment: {t.repayment.receipt_number if t.repayment else 'Failed'}")
```

---

## 🎯 Quick Fix Summary

```bash
# 1. Upload process_callback.py

# 2. Restart
touch /home/acbptxvs/public_html/branchbusinessadvance.co.ke/passenger_wsgi.py

# 3. Process the callback
cd /home/acbptxvs/public_html/branchbusinessadvance.co.ke
python manage.py process_callback 682dc145-3a65-40df-b93c-bb688dab289d

# 4. Verify
python manage.py check_callbacks
python manage.py check_mpesa_status
```

---

## 💡 Why This Happened

The callback processing code in `payments/services.py` should automatically:
1. Receive callback
2. Create transaction
3. Link callback to transaction
4. Mark as processed

But something failed silently. Possible reasons:
- Database error
- Exception in code
- Missing required field
- Validation error

The `process_callback` command bypasses the automatic flow and manually creates the transaction.

---

## 🆘 If Still Not Working

Check Django error logs for the exact error:
```bash
# In cPanel, check error logs around 2025-11-01 06:07:28
# Look for Python exceptions or tracebacks
```

Or run in Django shell to see the exact error:
```python
from payments.models import MpesaCallback
from payments.services import MpesaService

callback = MpesaCallback.objects.get(id='682dc145-3a65-40df-b93c-bb688dab289d')
data = callback.raw_data

# Try to process
try:
    result = MpesaService.process_confirmation_callback(data)
    print(f"Result: {result}")
except Exception as e:
    print(f"Error: {e}")
    import traceback
    traceback.print_exc()
```

---

**Upload `process_callback.py` → Run the command → Payment will be processed!** 🚀
