# UPI Payment Integration Guide

## Overview
This document explains how to set up real-time UPI payment integration with your fitness website.

## Current Implementation

### What's Implemented:
✅ UPI payment method in checkout
✅ Dynamic QR code generation with purchase amount
✅ Real-time payment status checking (polling every 2 seconds)
✅ UPI string generation (upi://pay format)
✅ Payment status display with icons
✅ Real-time feedback to user

## How It Works

### 1. **Payment Method Selection**
When user selects UPI:
- A QR code is generated showing the amount
- Instructions are displayed for scanning
- Real-time status check starts

### 2. **QR Code Generation**
```
Format: upi://pay?pa=UPI_ID&pn=NAME&tr=REFERENCE&am=AMOUNT&tn=PURPOSE
Example: upi://pay?pa=powerzone@upi&pn=PowerZone%20Fitness&tr=PZ123456&am=100&tn=Purchase%20Order
```

### 3. **Real-time Status Check**
Every 2 seconds, the system checks `check-upi-payment.php` for payment status:
- Returns: `{status: 'pending' or 'completed', transaction_id: 'XXX'}`
- Updates UI when payment is confirmed

## Integration with Payment Gateways

### Option 1: Razorpay (Recommended for UPI)

**Step 1: Install Razorpay SDK**
```bash
composer require razorpay/razorpay
```

**Step 2: Create `process-upi-payment.php`**
```php
<?php
require 'vendor/autoload.php';
use Razorpay\Api\Api;

$api = new Api('YOUR_KEY_ID', 'YOUR_KEY_SECRET');

$order = $api->order->create([
    'amount' => $_POST['amount'] * 100,
    'currency' => 'INR',
    'receipt' => 'receipt#' . time(),
    'payment_capture' => 1
]);

echo json_encode($order);
?>
```

**Step 3: Add JavaScript for Razorpay**
```javascript
// In checkout.php, add this in the UPI payment handler:
fetch('process-upi-payment.php', {
    method: 'POST',
    body: JSON.stringify({amount: cartTotal})
})
.then(res => res.json())
.then(order => {
    var options = {
        key: 'YOUR_KEY_ID',
        amount: order.amount,
        currency: 'INR',
        order_id: order.id,
        handler: function(response) {
            // Payment successful
            updatePaymentStatus('completed', response.razorpay_payment_id);
        }
    };
    var rzp = new Razorpay(options);
    rzp.open();
});
```

### Option 2: PayU

**Setup Steps:**
1. Get Merchant ID and Key from PayU
2. Integrate PayU plugin
3. Handle payment redirects
4. Update webhook for status

### Option 3: Google Pay for Business

**Setup Steps:**
1. Register for Google Pay API
2. Implement API calls for UPI transactions
3. Handle payment responses
4. Store transaction data

## Real-time Webhook Integration

### Setup Payment Gateway Webhook

**Create `upi-webhook.php`:**
```php
<?php
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Verify webhook authenticity (HMAC)
// Update payment status in database
// Set session/file flag for payment completion

if ($data['status'] === 'captured' || $data['status'] === 'completed') {
    // Store payment in database
    $statusFile = sys_get_temp_dir() . '/upi_payment_' . $data['session_id'] . '.json';
    file_put_contents($statusFile, json_encode([
        'status' => 'completed',
        'transaction_id' => $data['transaction_id'],
        'amount' => $data['amount']
    ]));
    
    // Update database
    include 'includes/db.php';
    $conn->query("UPDATE orders SET payment_status='completed', upi_transaction_id='{$data['transaction_id']}' WHERE order_id='{$data['order_id']}'");
}
?>
```

**Add to Payment Gateway Dashboard:**
- Webhook URL: `https://yoursite.com/fitness/upi-webhook.php`
- Events: Payment Completed, Payment Failed
- Auth Method: HMAC (or as per gateway)

## Database Setup

Add these columns to orders table:
```sql
ALTER TABLE orders ADD COLUMN payment_method VARCHAR(50);
ALTER TABLE orders ADD COLUMN payment_status VARCHAR(50) DEFAULT 'pending';
ALTER TABLE orders ADD COLUMN upi_transaction_id VARCHAR(100);
ALTER TABLE orders ADD COLUMN upi_timestamp TIMESTAMP;
```

## Configuration

### Update checkout.php:

Change the UPI ID:
```javascript
const upiId = 'your.business@upi'; // Update this with your actual UPI ID
```

### Payment Methods to Update:

1. **For Razorpay:**
   - Get Key ID and Secret from Razorpay Dashboard
   - Update in checkout.php

2. **For PayU:**
   - Get Merchant ID and Key
   - Configure in checkout.php

3. **For Google Pay:**
   - Register for API access
   - Update credentials

## Testing

### Test Cases:

1. **Payment Success:**
   - Select UPI → Scan QR → Enter OTP → Confirm
   - Status should show "Payment received!"

2. **Payment Failure:**
   - Select UPI → Scan QR → Decline
   - Status should show "Payment failed"

3. **Payment Timeout:**
   - Select UPI → Wait without scanning
   - Should timeout after configurable duration

4. **Multiple Payments:**
   - Try selecting different payment methods
   - QR should update with correct amount

## Security Considerations

✅ Always verify webhook signatures
✅ Use HTTPS only
✅ Don't expose API keys in frontend
✅ Validate amounts on backend
✅ Store transactions securely
✅ Log all payment attempts

## Troubleshooting

### QR Code Not Displaying
- Check if qrcode.min.js is loading
- Verify container element exists
- Check browser console for errors

### Payment Status Not Updating
- Verify webhook is configured
- Check webhook logs in payment gateway
- Ensure session IDs match
- Review payment status check interval

### UPI Link Not Working
- Verify UPI ID is correct
- Check amount formatting
- Test with UPI app installed
- Ensure transaction reference is unique

## Next Steps

1. Choose a payment gateway (Razorpay recommended)
2. Get API credentials
3. Update `check-upi-payment.php` with gateway API calls
4. Add webhook handling
5. Test in sandbox environment
6. Move to production
7. Monitor payment transactions

## Support & Resources

- **Razorpay Docs:** https://razorpay.com/docs/
- **PayU Documentation:** https://www.payumoney.com/integration/
- **Google Pay API:** https://developers.google.com/pay
- **UPI Specification:** https://www.npci.org.in/

---

**Version:** 1.0
**Last Updated:** January 2026
**Status:** Ready for Integration
