# Nexera Africa - Pi Payment System Integration Guide

## 🚀 Quick Overview

This guide walks you through integrating Pi Network payments into the Nexera Africa platform hosted on Kamatera VPS.

**Key Files:**
- `api/pi_payment.php` - Pi Network API handler (backend)
- `checkout.html` - Standalone checkout page
- `payment.php` - Listing purchase page

---

## 📋 Pre-Requisites

1. **Pi Developer Account**
   - Create account at https://pi.network
   - Register app at https://develop.pi

2. **Kamatera VPS**
   - Domain: `nexeraafrica.com`
   - SSL certificate installed
   - PHP 7.4+ with cURL enabled
   - MySQL/MariaDB database

3. **Credentials**
   - Pi API Key (from Pi Developer Portal)
   - MySQL root password
   - Domain access (SSH)

---

## 🔧 Step 1: Setup Database

Run this SQL command on your MySQL server:

```sql
CREATE TABLE IF NOT EXISTS `pi_payments` (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_id VARCHAR(128) NOT NULL UNIQUE,
    payment_id VARCHAR(255),
    txid VARCHAR(255),
    status ENUM('initialized', 'approved', 'completed', 'failed', 'cancelled') NOT NULL DEFAULT 'initialized',
    metadata JSON,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_order_id (order_id),
    INDEX idx_payment_id (payment_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

---

## 🔑 Step 2: Get Pi API Key

1. Go to https://develop.pi
2. Sign in with your Pi account
3. Click "Create App"
4. Fill in app details:
   - **App Name:** Nexera Africa
   - **App Type:** Web App
   - **Redirect URI:** https://nexeraafrica.com/checkout.html
   - **Server URL:** https://nexeraafrica.com/api/pi_payment.php

5. Copy the **API Key**

---

## 🌐 Step 3: Configure Backend

**SSH into your Kamatera VPS:**

```bash
ssh root@nexeraafrica.com
cd /var/www/html/nexera_africa/api
```

**Edit `pi_payment.php`:**

Replace `YOUR_PI_API_KEY_HERE` with your actual Pi API Key:

```php
define('PI_API_KEY', 'YOUR_ACTUAL_PI_API_KEY');
```

You can also use environment variable (recommended):

```bash
export PI_API_KEY="your_api_key_here"
```

Then in `pi_payment.php`:

```php
define('PI_API_KEY', getenv('PI_API_KEY') ?: 'YOUR_PI_API_KEY_HERE');
```

---

## 🔐 Step 4: Configure Database Connection

**Verify `config/db.php`:**

```php
$host     = "localhost";
$user     = "root";
$password = "your_mysql_password";
$database = "nexora_db";
```

Test the connection:

```bash
php -r "
include 'config/db.php';
echo 'Database connection: ' . ($db ? 'OK' : 'FAILED');
"
```

---

## 📱 Step 5: Deploy Payment Pages

Upload these files to your VPS:

```
/var/www/html/nexera_africa/
├── api/
│   └── pi_payment.php       ✓ New unified handler
├── checkout.html            ✓ Standalone checkout
├── payment.php              ✓ Listing checkout
└── config/
    └── db.php               ✓ Database config
```

Set proper permissions:

```bash
chmod 755 /var/www/html/nexera_africa/api/pi_payment.php
chmod 644 /var/www/html/nexera_africa/checkout.html
chmod 644 /var/www/html/nexera_africa/payment.php
```

---

## ✅ Step 6: Verify HTTPS

Pi Network requires HTTPS. Verify your certificate:

```bash
curl -I https://nexeraafrica.com/checkout.html
```

Look for:
```
HTTP/2 200
Strict-Transport-Security: max-age=31536000
```

If HTTPS is not working, install SSL certificate:

```bash
apt-get update
apt-get install certbot python3-certbot-apache
certbot certonly -d nexeraafrica.com
```

---

## 🧪 Step 7: Test Payment Flow

### Option 1: Standalone Checkout (Recommended for Testing)

1. Open in **Pi Browser ONLY**:
   ```
   https://nexeraafrica.com/checkout.html
   ```

2. Click "Connect Pi Wallet"

3. Authenticate with your Pi Wallet

4. Click "Complete Payment with Pi"

5. Complete payment in the Pi Wallet overlay

6. Check status messages

### Option 2: Listing Checkout

1. Open listing page:
   ```
   https://nexeraafrica.com/payment.php?id=1
   ```

2. Click "Pay with Pi Wallet"

3. Follow the same flow

---

## 🐛 Step 8: Debugging

### Check API Response

```bash
curl -X POST https://nexeraafrica.com/api/pi_payment.php?action=create \
  -H "Content-Type: application/json" \
  -d '{"amount": 0.00314, "memo": "Test"}'
```

Expected response:
```json
{
  "status": "success",
  "orderId": "NEXERA-...",
  "amount": 0.00314,
  "memo": "Test"
}
```

### Check Browser Console

Open browser DevTools (F12) and check:
- **Console** tab: JavaScript errors
- **Network** tab: API requests and responses
- **Application** tab: Local storage

### View Payment Log

```bash
tail -f /var/www/html/nexera_africa/logs/payment_debug.log
```

---

## 🔄 API Endpoints Reference

All endpoints are at: `https://nexeraafrica.com/api/pi_payment.php`

### Create Order
```
POST ?action=create
Body: { "amount": 0.00314, "memo": "string", "metadata": {} }
Response: { "orderId": "NEXERA-...", "amount": 0.00314, "memo": "..." }
```

### Approve Payment
```
POST ?action=approve
Body: { "paymentId": "string", "orderId": "string" }
Response: { "status": "success", "paymentId": "..." }
```

### Complete Payment
```
POST ?action=complete
Body: { "paymentId": "string", "txid": "string", "orderId": "string" }
Response: { "status": "success", "txid": "..." }
```

### Verify Payment
```
POST ?action=verify
Body: { "paymentId": "string" }
Response: { "status": "success", "payment": {...} }
```

---

## 🚨 Troubleshooting

### Problem: "Nothing happens when clicking Pay"
- ✓ Ensure you're in **Pi Browser**
- ✓ Check browser console for errors (F12)
- ✓ Verify Pi SDK is loaded: `window.Pi`
- ✓ Check network requests in DevTools

### Problem: "Authentication failed"
- ✓ Make sure page is served over HTTPS
- ✓ Clear browser cache and reload
- ✓ Try on different device/browser
- ✓ Check Pi Browser version

### Problem: "Payment approved but not completing"
- ✓ Check Pi API Key is correct
- ✓ Verify database table exists
- ✓ Check MySQL error logs
- ✓ Review API responses in Network tab

### Problem: "CORS errors"
- ✓ CORS headers are set in `pi_payment.php`
- ✓ Verify no `.htaccess` rules blocking requests
- ✓ Check server firewall

---

## 📊 Production Checklist

- [ ] Pi API Key configured
- [ ] Database table created
- [ ] HTTPS certificate installed and valid
- [ ] `pi_payment.php` tested and responding
- [ ] `checkout.html` loads without console errors
- [ ] Pi Wallet authentication working
- [ ] Payment flow completes successfully
- [ ] Order recorded in `pi_payments` table
- [ ] `config/db.php` has correct credentials
- [ ] All file permissions set correctly (755 for PHP, 644 for HTML)
- [ ] Error logging configured
- [ ] Backup strategy in place

---

## 🎯 Production Mode (Switch from Sandbox)

When ready to go live:

**In `checkout.html` and `payment.php`:**
```javascript
// Change from:
Pi.init({ version: "2.0", sandbox: true });

// To:
Pi.init({ version: "2.0", sandbox: false });
```

**Also:**
1. Update Pi Developer Portal app settings to production
2. Update callback URLs to live domain
3. Thoroughly test complete payment flow
4. Monitor logs for any errors
5. Have rollback plan ready

---

## 📞 Support

- **Pi Network Docs:** https://docs.pi.network
- **Pi Developer Portal:** https://develop.pi
- **Pi Browser:** https://www.pi.network/browser
- **Error Logs:** Check `/logs/` directory on VPS

---

**Last Updated:** June 13, 2026
**Version:** 1.0
**Status:** Production Ready
