# Mobile Money Payment Reference Fix

## Issue Identified

The Relworx API was returning the following error:
```json
{
    "success": false,
    "message": "Invalid reference. Should contain only alpnanumeric, underscore and hyphen characters.",
    "error_code": 400
}
```

## Root Cause

The `generateReference()` method in `MobileMoneyService.php` was using `uniqid('MM_', true)` which generates references with a **period (.)** character:

```php
// OLD CODE (BUGGY)
return uniqid('MM_', true) . '_' . time();
// Generated: MM_64a5e7b3c9f2.12345678_1234567890
//                          ^ Period not allowed by Relworx!
```

Relworx API only accepts: **alphanumeric, underscore (_), and hyphen (-)** characters.

## Fixes Applied

### 1. Fixed Reference Generation
Updated `generateReference()` to only use allowed characters:

```php
// NEW CODE (FIXED)
public function generateReference(): string
{
    // Generate a unique reference without special characters
    // Format: MM_TIMESTAMP_RANDOMHEX
    return 'MM_' . time() . '_' . bin2hex(random_bytes(8));
}
// Now generates: MM_1728576000_a1b2c3d4e5f67890 (valid!)
```

### 2. Added Reference Validation Method
Created a new validation method to check reference format:

```php
public function validateReference(string $reference): bool
{
    // Check if reference contains only alphanumeric, underscore and hyphen
    return preg_match('/^[a-zA-Z0-9_-]+$/', $reference) === 1;
}
```

### 3. Applied Validation to All Payment Methods
Added reference validation to:
- `requestPayment()` - Mobile money collection
- `sendPayment()` - Mobile money disbursement
- `requestPaymentSession()` - VISA/Mastercard payments
- `validateProduct()` - Product/service validation

Each method now validates references before sending to Relworx API.

## Payload Structure (Confirmed Correct)

The payload being sent to Relworx for `pay()` endpoint matches the expected structure:

```php
POST /api/mobile-money/request-payment
{
    "account_no": "REL4737AB23A9",
    "reference": "MM_1728576000_a1b2c3d4e5f67890",  // Now properly formatted
    "msisdn": "+256709713160",
    "currency": "UGX",
    "amount": 1000.00,
    "description": "Payment Request."
}
```

Headers:
```
Content-Type: application/json
Accept: application/vnd.relworx.v2
Authorization: Bearer {api_key}
```

## Testing

To test the fix, you can:

1. **Use auto-generated reference:**
```bash
curl -X POST http://localhost/api/mobile-money/pay \
  -H "Content-Type: application/json" \
  -d '{
    "msisdn": "+256709713160",
    "amount": 1000,
    "currency": "UGX",
    "description": "Payment Request."
  }'
```

2. **Use custom reference (must be valid):**
```bash
curl -X POST http://localhost/api/mobile-money/pay \
  -H "Content-Type: application/json" \
  -d '{
    "msisdn": "+256709713160",
    "amount": 1000,
    "currency": "UGX",
    "description": "Payment Request.",
    "reference": "MY_CUSTOM_REF_12345"
  }'
```

## Expected Behavior

✅ **Before Fix:** Reference with periods → API error 400
✅ **After Fix:** Reference without periods → Payment processed successfully

## Files Modified

- `app/Libraries/MobileMoneyService.php`
  - Fixed `generateReference()` method
  - Added `validateReference()` method
  - Added validation to `requestPayment()`
  - Added validation to `sendPayment()`
  - Added validation to `requestPaymentSession()`
  - Added validation to `validateProduct()`

## Notes

- User-provided references are now validated before being sent to Relworx
- Invalid references return a clear error message to the client
- All auto-generated references are guaranteed to be valid
- The fix is backward compatible (existing valid references will continue to work)

