# Paystack Integration Guide

This guide explains how to integrate and use Paystack payment gateway in your event management system.

## ✅ What's Already Implemented

The following components have been created:

1. **PaystackService** (`app/Services/PaystackService.php`) - Handles Paystack API calls
2. **PaymentController** (`app/Http/Controllers/PaymentController.php`) - Handles payment initialization, callbacks, and webhooks
3. **Payment Routes** - Added to `routes/web.php`
4. **Configuration** - Added to `config/services.php`

## Prerequisites

1. A Paystack account (sign up at https://paystack.com)
2. Paystack API keys (Public Key and Secret Key)

## Step 1: Get Your Paystack API Keys

1. Log in to your Paystack dashboard
2. Go to **Settings** > **API Keys & Webhooks**
3. Copy your **Public Key** and **Secret Key**
   - Use **Test Keys** for development
   - Use **Live Keys** for production

## Step 2: Configure Paystack (Two Options)

### Option A: Via Admin Panel (Recommended)

1. Go to **Admin** > **Settings** > **Payment Gateways**
2. Find **Paystack** section
3. Enable Paystack
4. Enter your **Public Key** and **Secret Key**
5. Click **Save**

The keys will be stored in the `platform_settings` table.

### Option B: Via Environment Variables

Add these to your `.env` file:

```env
PAYSTACK_PUBLIC_KEY=pk_test_your_public_key_here
PAYSTACK_SECRET_KEY=sk_test_your_secret_key_here
PAYSTACK_MERCHANT_EMAIL=your-email@example.com
```

For production, replace `pk_test_` with `pk_live_` and `sk_test_` with `sk_live_`.

## Step 3: Configure Webhook URL

In your Paystack dashboard:
1. Go to **Settings** > **API Keys & Webhooks**
2. Add a webhook URL: `https://yourdomain.com/payment/webhook`
3. Select events: **charge.success**
4. Save the webhook

## Step 4: How It Works

### Payment Flow

1. **Customer initiates payment:**
   - Customer selects Paystack as payment method
   - System creates an order
   - Payment record is created with status "pending"

2. **Payment initialization:**
   - System calls Paystack API to initialize transaction
   - Customer is redirected to Paystack payment page
   - Paystack handles the payment processing

3. **Payment callback:**
   - After payment, Paystack redirects to callback URL
   - System verifies the transaction
   - If successful:
     - Payment status updated to "successful"
     - Order status updated to "completed"
     - Tickets are generated (if applicable)

4. **Webhook (optional but recommended):**
   - Paystack sends webhook notification
   - System processes the webhook for additional verification
   - Ensures payment is recorded even if callback fails

## Step 5: Using Paystack in Your Code

### Initialize Payment

```php
// In your checkout/order controller
use App\Services\PaystackService;

$paystackService = new PaystackService();

// Initialize payment
$result = $paystackService->initializeTransaction([
    'email' => $order->customer_email,
    'amount' => $order->total,
    'reference' => $reference,
    'currency' => 'NGN',
    'callback_url' => route('payment.callback'),
    'metadata' => [
        'order_id' => $order->id,
    ],
]);

if ($result['success']) {
    // Redirect to Paystack payment page
    return redirect($result['data']['authorization_url']);
}
```

### Verify Payment

```php
// Verify transaction
$result = $paystackService->verifyTransaction($reference);

if ($result['success'] && $result['status']) {
    // Payment successful
    // Update order and generate tickets
}
```

## Step 6: Testing

### Test Cards (for development)

Paystack provides test cards for testing:

- **Successful payment:** `4084084084084081`
- **Declined payment:** `5060666666666666666`
- **Insufficient funds:** `5060666666666666667`

Use any future expiry date (e.g., 12/25) and any CVV (e.g., 123).

### Test Email

Use any email address for testing (e.g., `test@example.com`).

## Step 7: Admin Configuration

1. Go to **Admin** > **Settings** > **Payment Gateways**
2. Enter your Paystack credentials:
   - Public Key
   - Secret Key
3. Enable Paystack
4. Save settings

## Important Notes

1. **Amount Conversion:** Paystack requires amounts in the smallest currency unit (kobo for NGN). The service automatically converts NGN amounts by multiplying by 100.

2. **Webhook Security:** The webhook endpoint verifies the signature from Paystack to ensure requests are legitimate.

3. **Error Handling:** All payment operations are wrapped in try-catch blocks and logged for debugging.

4. **Transaction Reference:** Each payment gets a unique reference that's used for verification.

## Troubleshooting

### Payment not initializing
- Check that API keys are correctly set in `.env`
- Verify the keys are active in Paystack dashboard
- Check application logs for errors

### Callback not working
- Ensure callback URL is accessible
- Check that route is not protected by authentication middleware
- Verify Paystack can reach your server

### Webhook not received
- Check webhook URL in Paystack dashboard
- Ensure webhook URL is publicly accessible
- Check server logs for webhook requests

## Support

For Paystack-specific issues, contact Paystack support:
- Email: support@paystack.com
- Documentation: https://paystack.com/docs

