# M-Pesa C2B URL Registration Guide

This guide will help you complete the M-Pesa integration by registering your callback URLs with Safaricom.

## 📋 Prerequisites

Before you begin, make sure you have:

1. ✅ M-Pesa Consumer Key (from Safaricom Developer Portal)
2. ✅ M-Pesa Consumer Secret (from Safaricom Developer Portal)
3. ✅ Business Short Code (Paybill number)
4. ✅ Publicly accessible HTTPS URLs for callbacks
5. ✅ Internet connectivity

## 🎯 What You Need to Register

According to Safaricom's email, you need to register these URLs:

- **Validation URL**: `https://branchbusinessadvance.co.ke/payments/callback/validation/`
- **Confirmation URL**: `https://branchbusinessadvance.co.ke/payments/callback/confirmation/`

## 🚀 Method 1: Using Django Management Command (Recommended)

This is the easiest method if you have Django set up.

### Step 1: Update M-Pesa Configuration in Database

First, make sure your M-Pesa configuration is in the database:

```bash
python manage.py shell
```

Then run:

```python
from payments.models import MpesaConfiguration

# Create or update configuration
config, created = MpesaConfiguration.objects.get_or_create(
    business_short_code="YOUR_SHORTCODE",
    defaults={
        'environment': 'production',
        'consumer_key': 'YOUR_CONSUMER_KEY',
        'consumer_secret': 'YOUR_CONSUMER_SECRET',
        'validation_url': 'https://branchbusinessadvance.co.ke/payments/callback/validation/',
        'confirmation_url': 'https://branchbusinessadvance.co.ke/payments/callback/confirmation/',
        'response_type': 'Completed',
        'is_active': True
    }
)

# If it already exists, update it
if not created:
    config.environment = 'production'
    config.consumer_key = 'YOUR_CONSUMER_KEY'
    config.consumer_secret = 'YOUR_CONSUMER_SECRET'
    config.validation_url = 'https://branchbusinessadvance.co.ke/payments/callback/validation/'
    config.confirmation_url = 'https://branchbusinessadvance.co.ke/payments/callback/confirmation/'
    config.response_type = 'Completed'
    config.is_active = True
    config.save()

print("Configuration saved!")
exit()
```

### Step 2: Run the Registration Command

```bash
python manage.py register_mpesa_urls --use-config --production
```

The command will:
1. Load credentials from your database
2. Generate an access token
3. Register the URLs with M-Pesa
4. Display the result

**Example Output:**
```
======================================================================
M-Pesa C2B URL Registration
======================================================================

Configuration:
  Environment: PRODUCTION
  Short Code: 4159523
  Consumer Key: 9mD1A3H1qw...
  Validation URL: https://branchbusinessadvance.co.ke/payments/callback/validation/
  Confirmation URL: https://branchbusinessadvance.co.ke/payments/callback/confirmation/
  Response Type: Completed

⚠️  WARNING: You are about to register URLs in PRODUCTION!
Type "yes" to continue: yes

Step 1: Generating access token...
✓ Access token generated: eyJ0eXAiOiJKV1QiLCJ...

Step 2: Registering callback URLs...

======================================================================
✓ URL Registration Successful!
======================================================================

Response from M-Pesa:
  OriginatorCoversationID: 29115-34620561-1
  ResponseCode: 0
  ResponseDescription: Success

✓ Configuration updated in database

Next Steps:
1. Test the integration by making a payment to your shortcode
2. Monitor the callback logs at /payments/callbacks/
3. Check transaction processing at /payments/transactions/
```

### Alternative: Register with Custom URLs

If you want to specify URLs directly:

```bash
python manage.py register_mpesa_urls \
    --shortcode YOUR_SHORTCODE \
    --consumer-key YOUR_CONSUMER_KEY \
    --consumer-secret YOUR_CONSUMER_SECRET \
    --validation-url https://branchbusinessadvance.co.ke/payments/callback/validation/ \
    --confirmation-url https://branchbusinessadvance.co.ke/payments/callback/confirmation/ \
    --production
```

---

## 🔧 Method 2: Using Standalone Python Script

If you prefer not to use Django, use the standalone script.

### Step 1: Edit the Script

Open `register_mpesa_urls_standalone.py` and update these values:

```python
# M-Pesa Credentials
CONSUMER_KEY = "YOUR_CONSUMER_KEY_HERE"
CONSUMER_SECRET = "YOUR_CONSUMER_SECRET_HERE"

# Business Short Code
SHORT_CODE = "YOUR_SHORTCODE_HERE"

# Callback URLs
VALIDATION_URL = "https://branchbusinessadvance.co.ke/payments/callback/validation/"
CONFIRMATION_URL = "https://branchbusinessadvance.co.ke/payments/callback/confirmation/"

# Environment
IS_PRODUCTION = True
```

### Step 2: Run the Script

```bash
python register_mpesa_urls_standalone.py
```

---

## 📮 Method 3: Using Postman

Since you have Postman installed, you can use it to register the URLs manually.

### Step 1: Generate Access Token

**Request:**
- **Method**: `GET`
- **URL**: `https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials`

**Headers:**
```
Authorization: Basic <base64_encoded_credentials>
Content-Type: application/json
```

**How to create the Authorization header:**

1. Open a terminal or Python:
```python
import base64
credentials = "YOUR_CONSUMER_KEY:YOUR_CONSUMER_SECRET"
encoded = base64.b64encode(credentials.encode()).decode()
print(f"Basic {encoded}")
```

2. Copy the output and use it as the Authorization header value

**Expected Response:**
```json
{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
    "expires_in": "3599"
}
```

### Step 2: Register URLs

**Request:**
- **Method**: `POST`
- **URL**: `https://api.safaricom.co.ke/mpesa/c2b/v2/registerurl`

**Headers:**
```
Authorization: Bearer <access_token_from_step_1>
Content-Type: application/json
```

**Body (raw JSON):**
```json
{
    "ShortCode": "YOUR_SHORTCODE",
    "ResponseType": "Completed",
    "ConfirmationURL": "https://branchbusinessadvance.co.ke/payments/callback/confirmation/",
    "ValidationURL": "https://branchbusinessadvance.co.ke/payments/callback/validation/"
}
```

**Expected Response:**
```json
{
    "OriginatorCoversationID": "29115-34620561-1",
    "ResponseCode": "0",
    "ResponseDescription": "Success"
}
```

---

## ✅ Verification

After registering the URLs, verify the integration:

### 1. Check Django Admin

Go to: `https://branchbusinessadvance.co.ke/admin/payments/mpesaconfiguration/`

Verify that:
- Environment is set to "production"
- Validation and Confirmation URLs are correct
- Configuration is marked as active

### 2. Test with a Real Payment

1. Send a small amount (e.g., 10 KES) to your shortcode
2. Check the callbacks: `/payments/callbacks/`
3. Check transactions: `/payments/transactions/`
4. Verify the payment was processed correctly

### 3. Monitor Logs

Check your application logs for any errors:
- Validation callback logs
- Confirmation callback logs
- Payment processing logs

---

## 🔍 Troubleshooting

### Error: "Invalid Access Token"

**Cause**: Access token expired or incorrect credentials

**Solution**:
1. Verify your consumer key and secret are correct
2. Generate a new access token
3. Access tokens expire after 1 hour

### Error: "Invalid ShortCode"

**Cause**: The shortcode doesn't match your credentials

**Solution**:
1. Verify the shortcode matches your M-Pesa account
2. Ensure you're using the production shortcode, not sandbox

### Error: "Invalid URL"

**Cause**: Callback URLs are not accessible or not HTTPS

**Solution**:
1. Ensure URLs are publicly accessible
2. Verify SSL certificate is valid
3. Test URLs in a browser: they should return a valid response

### Error: "Validation Failed"

**Cause**: M-Pesa cannot reach your validation URL

**Solution**:
1. Check firewall settings
2. Ensure your server is running
3. Verify the URL is correct and accessible from the internet

---

## 📝 Important Notes

### Production vs Sandbox

- **Production**: Uses `https://api.safaricom.co.ke` and API version `v2`
- **Sandbox**: Uses `https://sandbox.safaricom.co.ke` and API version `v1`

### Response Type

- **Completed**: Accept payment even if validation fails (recommended)
- **Cancelled**: Reject payment if validation fails

### URL Requirements

- Must use HTTPS (not HTTP)
- Must be publicly accessible
- Must return valid JSON responses
- Response time should be < 30 seconds

### Security

- Never commit credentials to version control
- Use environment variables for sensitive data
- Rotate credentials regularly
- Monitor callback logs for suspicious activity

---

## 🎉 Success Indicators

You'll know the integration is working when:

1. ✅ URL registration returns `ResponseCode: 0`
2. ✅ Test payments appear in `/payments/transactions/`
3. ✅ Callbacks are logged in `/payments/callbacks/`
4. ✅ Payments are automatically matched to loans
5. ✅ Borrowers receive payment confirmations

---

## 📞 Support

If you encounter issues:

1. Check the Django admin dashboard: `/payments/dashboard/`
2. Review callback logs: `/payments/callbacks/`
3. Check transaction details: `/payments/transactions/`
4. Review application logs for errors
5. Contact Safaricom support if API issues persist

---

## 🔗 Useful Links

- [M-Pesa Developer Portal](https://developer.safaricom.co.ke/)
- [C2B API Documentation](https://developer.safaricom.co.ke/APIs/CustomerToBusinessC2B)
- [API Reference](https://developer.safaricom.co.ke/Documentation)

---

**Last Updated**: November 2025
