# Payment Integration Setup Guide

## Paystack Integration

### Important URLs

#### 1. Webhook URL
Configure this URL in your Paystack Dashboard:
```
https://yourdomain.com/webhooks/paystack.php
```

**Steps to configure:**
1. Log in to your Paystack Dashboard
2. Go to Settings → Webhooks
3. Add the webhook URL above
4. Save the configuration

#### 2. Callback URL
This is automatically configured in the payment initialization. The callback URL is:
```
https://yourdomain.com/payment/callback.php
```

**What happens after payment:**
- User completes payment on Paystack
- Paystack redirects to callback URL with transaction reference
- Callback verifies payment and updates booking status
- User is redirected to: `https://yourdomain.com/index.php?page=my_bookings`

### Payment Flow

#### Security Deposit Payment Flow:
1. **User initiates booking** → Booking created with status `pending_payment`
2. **User clicks "Pay Deposit"** → Redirected to Paystack payment page
3. **User completes payment** → Two things happen simultaneously:
   - **Webhook** (Real-time): Paystack sends webhook to update transaction
   - **Callback** (User redirect): User redirected back to your site
4. **Payment verified** → Booking status updated to `deposit_paid`
5. **User redirected** → Sent to My Bookings page with success message

#### Full Payment Flow:
1. **User schedules inspection** → Inspection completed and approved
2. **User clicks "Pay Full Amount"** → Redirected to Paystack payment page
3. **User completes payment** → Webhook and callback process payment
4. **Payment verified** → Booking status updated to `confirmed`
5. **User redirected** → Sent to My Bookings page with success message

### Webhook Events Handled

The webhook handles the following Paystack events:

1. **charge.success** - Payment successful
   - Updates transaction status to `completed`
   - Updates booking status based on payment type
   - Sends notification to user

2. **charge.failed** - Payment failed
   - Updates transaction status to `failed`
   - Logs failure reason

3. **refund.processed** - Refund completed
   - Updates refund status to `completed`
   - Updates booking refund status

4. **refund.failed** - Refund failed
   - Updates refund status to `failed`
   - Logs failure reason

### Webhook Logging

All webhook events are logged to:
```
logs/paystack_webhooks.log
```

**Log includes:**
- Timestamp
- Event type
- Transaction reference
- Payment status
- Success/failure messages
- Error details (if any)

**To view logs:**
```bash
tail -f logs/paystack_webhooks.log
```

### Testing Webhooks Locally

Since Paystack cannot reach localhost, you have two options:

#### Option 1: Use ngrok (Recommended for testing)
```bash
# Install ngrok from https://ngrok.com/
# Run ngrok to expose your local server
ngrok http 80

# Use the ngrok URL in Paystack webhook settings
# Example: https://abc123.ngrok.io/webhooks/paystack.php
```

#### Option 2: Deploy to staging server
Deploy your code to a staging server with a public URL and configure the webhook there.

### Webhook Security

The webhook verifies Paystack signatures to ensure requests are authentic:

1. **Signature verification** - Validates `x-paystack-signature` header
2. **Secret key validation** - Uses your Paystack secret key
3. **Idempotency** - Handles duplicate webhook calls gracefully

**Note:** During development, signature verification can be temporarily disabled by uncommenting lines 59-60 in `webhooks/paystack.php`. **DO NOT disable in production!**

### Troubleshooting

#### Webhook not triggering:
1. Check webhook URL is correctly configured in Paystack dashboard
2. Verify webhook URL is publicly accessible (not localhost)
3. Check `logs/paystack_webhooks.log` for incoming requests
4. Verify Paystack secret key is correctly configured

#### Payment verified but booking not updating:
1. Check webhook logs for errors
2. Verify transaction reference matches
3. Check database `payment_transactions` table for transaction status
4. Verify `bookings` table is being updated

#### Callback not redirecting properly:
1. Check for PHP errors in callback.php
2. Verify session is started
3. Check APP_URL is correctly configured in config.php

### Database Tables

#### payment_transactions
Stores all payment transactions:
- `transaction_ref` - Unique transaction reference
- `booking_id` - Associated booking
- `status` - pending, completed, failed
- `amount` - Payment amount
- `metadata` - Payment metadata (JSON)

#### bookings
Stores booking information:
- `status` - pending_payment, deposit_paid, confirmed, etc.
- `amount_paid` - Total amount paid
- `balance` - Remaining balance
- `deposit_paid` - Boolean flag
- `deposit_payment_date` - When deposit was paid

### Configuration Checklist

- [ ] Paystack public key configured in payment gateway settings
- [ ] Paystack secret key configured in payment gateway settings
- [ ] Webhook URL added to Paystack dashboard
- [ ] Webhook URL is publicly accessible
- [ ] APP_URL correctly set in config.php
- [ ] Database tables created
- [ ] Logs directory exists and is writable
- [ ] Test payment completed successfully
- [ ] Webhook logs show successful processing

### Support

If you encounter issues:
1. Check the webhook logs first
2. Verify all configuration settings
3. Test with Paystack test mode first
4. Check Paystack dashboard for webhook delivery status

### Production Deployment

Before going live:
1. Switch from test keys to live keys
2. Enable signature verification (remove development bypass)
3. Test with small amounts first
4. Monitor webhook logs closely
5. Set up error alerting for failed webhooks