# Payment Gateway & Passkey Setup Guide

## What's Been Created

### 1. Payment Gateway System

**Files Created:**
- `database_payment_and_passkey_migration.sql` - Database tables
- `src/PaymentGateway/GatewayInterface.php` - Base interface
- `src/PaymentGateway/PayFastHandler.php` - PayFast implementation
- `src/PaymentGateway/OzowHandler.php` - OzOw implementation
- `src/PaymentManager.php` - Payment orchestration

**Features:**
- ✅ Multi-gateway support (PayFast, OzOw)
- ✅ Flexible gateway switching in admin
- ✅ Transaction logging
- ✅ Webhook processing
- ✅ Automatic credit assignment on payment completion

### 2. Passkey (WebAuthn) System

**Files Created:**
- `src/Security/WebAuthnHandler.php` - WebAuthn/FIDO2 handler

**Features:**
- ✅ Security key support (USB keys, Platform authenticators)
- ✅ Passkey enrollment flow
- ✅ Authentication challenge/response
- ✅ Signature verification
- ✅ Challenge expiration (10 minutes)

---

## Setup Instructions

### Step 1: Database Migration

Run the SQL migration to create all required tables:

```bash
mysql -u youruser -p yourdb < database_payment_and_passkey_migration.sql
```

**Tables Created:**
- `payment_gateways` - Gateway configuration
- `payment_transactions` - Transaction history
- `user_passkeys` - Enrolled passkeys
- `passkey_challenges` - Active challenges

### Step 2: Configure Payment Gateways

#### PayFast Setup:
1. Get your PayFast API credentials from `payfast.io`
2. In admin panel, configure:
   - Merchant ID
   - Merchant Key
   - Passphrase (for webhooks)

#### OzOw Setup:
1. Get your OzOw API credentials from `ozow.com`
2. In admin panel, configure:
   - API ID
   - API Key
   - Webhook Secret

### Step 3: Environment Configuration

Add to your `.env` or config:

```php
// PayFast (Testing)
PAYFAST_MERCHANT_ID=10000100
PAYFAST_MERCHANT_KEY=test_merchant_key
PAYFAST_PASSPHRASE=passphrase
PAYFAST_TEST_MODE=true

// OzOw (When ready)
// OZOW_API_ID=your_api_id
// OZOW_API_KEY=your_api_key
// OZOW_TEST_MODE=true

// WebAuthn
WEBAUTHN_RP_ID=localhost      // or yourdomain.com
WEBAUTHN_RP_ORIGIN=http://localhost:8000  // Change in production to https
```

---

## Next Steps (To Be Implemented)

### 1. Admin Payment Settings Page
Create page to:
- Configure payment gateways
- Set active gateway
- View transaction history
- Configure webhook URLs

### 2. Payment Checkout Page
Create page with:
- Plan selection
- Payment form (redirects to gateway)
- Webhook handler for payment completion

### 3. Passkey Enrollment Page
Create page for users to:
- Register new passkeys
- Manage existing passkeys
- Test passkey authentication

### 4. Login Flow Updates
Modify login to:
- Step 1: Username/password
- Step 2: SMS 2FA (if enabled)
- Step 3: Request passkey (if enrolled)

---

## Using the Payment System

### For Admin:

```php
use BankConverter\PaymentManager;

$pm = PaymentManager::getInstance();

// Set active gateway
$pm->setActiveGateway('payfast');

// Initiate payment
$result = $pm->initiatePayment(
    userId: 123,
    amount: 49.99,
    planId: 5,
    description: 'Premium Plan Subscription'
);

// Redirect user
header('Location: ' . $result['url']);
```

### For Webhook Handler:

```php
$pm = PaymentManager::getInstance();

$webhookData = $_POST; // or json_decode(file_get_contents('php://input'), true)

try {
    $result = $pm->processWebhook('payfast', $webhookData, $_SERVER['HTTP_X_PAYFAST_SIGNATURE'] ?? null);
    
    if ($result['status'] === 'completed') {
        $pm->completePayment($result['transaction_id']);
    }
} catch (\Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
```

### For Passkeys:

```php
use BankConverter\Security\WebAuthnHandler;

$webauthn = new WebAuthnHandler('localhost', 'http://localhost:8000');

// Enrollment:
$challenge = $webauthn->generateRegistrationChallenge($userId);
// ... send to frontend ...
$webauthn->verifyAndStorePasskey($userId, $registrationResponse);

// Authentication:
$challenge = $webauthn->generateAuthenticationChallenge();
// ... send to frontend ...
$isValid = $webauthn->verifyAuthenticationResponse($authResponse, $userId);
```

---

## Security Considerations

1. **Payment Webhooks:**
   - Always verify signatures
   - Validate transaction amounts
   - Prevent double-crediting

2. **Passpkeys:**
   - Store credential_id securely
   - Validate RP ID and origin
   - Check challenge expiration
   - Monitor sign count for cloned devices

3. **HTTPS:**
   - Payment gateways require HTTPS
   - WebAuthn requires HTTPS (except localhost)

---

## Troubleshooting

### PayFast Issues:
- Verify merchant credentials in database
- Check return_url and notify_url are correct
- Validate signature generation

### OzOw Issues:
- Verify API key has correct permissions
- Check webhook secret matches
- Validate amount format (should be in cents)

### Passkey Issues:
- Browser must support WebAuthn
- Ensure rpId matches your domain
- Check origin includes protocol (https://)
- Verify challenge under 10 minutes old

---

## Environment-Specific Notes

### Local Development:
- Use PayFast/OzOw test credentials
- WebAuthn works with `localhost`
- No HTTPS required for WebAuthn testing

### Production:
- Switch to production credentials
- WebAuthn requires HTTPS
- Update rpId to actual domain
- Implement proper CBOR decoder (current is simplified)
- Use proper crypto library for signature verification

---

## Files to Implement Next

1. `public/admin-payment-settings.php` - Admin configuration
2. `public/checkout.php` - Payment checkout page
3. `public/webhook-payment.php` - Payment webhook handler
4. `public/passkey-enroll.php` - Passkey enrollment
5. `public/passkey-authenticate.php` - Passkey login
6. Frontend JavaScript for WebAuthn APIs

---

## Testing PayFast (Sandbox)

Sandbox URL: https://sandbox.payfast.co.za

Test Card Numbers:
- Visa: 4110145110145112
- Mastercard: 2223003122003222

Use any future date and any CVC.
