# Pi Network API Key Setup Guide

## Complete Step-by-Step Instructions for Getting Your Pi API Key

This guide walks you through creating a Pi Developer account and obtaining your API key for the Nexera Africa payment system.

---

## 📋 Table of Contents

1. [Prerequisites](#prerequisites)
2. [Step 1: Create Pi Account](#step-1-create-pi-account)
3. [Step 2: Access Developer Portal](#step-2-access-developer-portal)
4. [Step 3: Register Your Application](#step-3-register-your-application)
5. [Step 4: Configure App Settings](#step-4-configure-app-settings)
6. [Step 5: Get Your API Key](#step-5-get-your-api-key)
7. [Step 6: Configure in Nexera Africa](#step-6-configure-in-nexera-africa)
8. [Step 7: Test Configuration](#step-7-test-configuration)
9. [Troubleshooting](#troubleshooting)

---

## Prerequisites

✅ Email address (Gmail, Outlook, Yahoo, etc.)  
✅ Access to your email for verification  
✅ Web browser (Chrome, Firefox, Safari, Edge)  
✅ Your domain name: `nexeraafrica.com`  
✅ Access to VPS server configuration  

---

## Step 1: Create Pi Account

### 1.1 Go to Pi Network Website

1. Open your browser
2. Navigate to: **https://www.pi.network**
3. You should see the Pi Network homepage

### 1.2 Sign Up

1. Click the **"Sign Up"** button (top right or in hero section)
   - Or go directly to: https://www.pi.network/register

2. Choose one of these options:
   - ✓ **Phone Number** (Recommended)
   - ✓ **Email Address**
   - ✓ **Facebook Account**
   - ✓ **Google Account**

### 1.3a Sign Up with Email

1. Click **"Email"** option
2. Enter your email address
3. Click **"Next"**
4. Create a strong password:
   - At least 8 characters
   - Mix of uppercase, lowercase, numbers, symbols
   - Example: `Nexera@2026!`
5. Click **"Create Account"**
6. **Check your email** for verification link
7. Click the verification link in your email
8. Your account is now active ✅

### 1.3b Sign Up with Phone

1. Click **"Phone"** option
2. Select your country
3. Enter your phone number
4. Click **"Send Code"**
5. Enter the 6-digit code sent to your phone
6. Create a password
7. Complete sign up
8. Your account is now active ✅

---

## Step 2: Access Developer Portal

### 2.1 Navigate to Developer Portal

1. Login to your Pi account at: https://www.pi.network
2. Click on your **profile icon** (top right)
3. Select **"Developer Portal"** from dropdown menu
   - Or go directly to: https://develop.pi

4. You'll see the Developer Dashboard

### 2.2 Verify Your Email (If Not Done)

If you see a banner asking to verify email:

1. Click **"Resend Verification Email"**
2. Check your email inbox
3. Click the verification link
4. Return to developer portal
5. Refresh the page

---

## Step 3: Register Your Application

### 3.1 Start App Registration

1. In Developer Portal, click **"Create New App"** button
   - Or look for **"My Apps"** section → **"Add App"**

2. You'll see the application form

### 3.2 Fill in Basic Information

**App Name:**
```
Nexera Africa
```

**App Type** (Select one):
- ✓ **Web App** ← SELECT THIS for our payment system
- Web Browser Integration
- Desktop App
- Mobile App
- Other

**Short Description:**
```
Pan-African digital marketplace on Pi Network with payment integration
```

### 3.3 Add App Icon (Optional)

1. Click **"Upload Icon"** or **"Choose Image"**
2. Select a logo or image (PNG/JPG, < 5MB)
3. Click **"Upload"** or **"Select"**
4. Image should be square (512x512 recommended)

### 3.4 Add Detailed Description

In the **"Description"** field, enter:

```
Nexera Africa is a pan-African digital infrastructure platform built on Pi Network.
Our marketplace enables users to buy and sell goods with Pi cryptocurrency.
This app integrates Pi payment processing for seamless transactions.

Features:
- Pi Wallet integration
- Secure payment processing
- Multi-category marketplace
- Real-time transaction tracking
```

---

## Step 4: Configure App Settings

### 4.1 Set Development/Production Modes

#### For Testing (Sandbox Mode):

**Sandbox Configuration:**
- Status: **ENABLED** (Default ✓)
- This allows testing without real Pi transactions
- Perfect for development and testing

**Sandbox URL:**
```
https://nexeraafrica.com/checkout.html
```

#### For Production (Live Mode):

Once testing is complete, you'll enable production:

**Production Configuration:**
- Status: **ENABLED**
- Real Pi transactions occur
- Only enable after thorough testing

**Production URL:**
```
https://nexeraafrica.com/checkout.html
```

### 4.2 Set Callback URLs

These are URLs that Pi network calls when payment events happen.

**For Sandbox Testing:**

In the **Callback URL** field, enter:
```
https://nexeraafrica.com/api/pi_payment.php
```

**For Production:**

Same URL works for both:
```
https://nexeraafrica.com/api/pi_payment.php
```

### 4.3 Set Redirect URIs

These are pages users return to after authentication.

**Add Redirect URI:**
```
https://nexeraafrica.com/checkout.html
```

**Also Add:**
```
https://nexeraafrica.com/payment.php
```

### 4.4 App Permissions

Select the permissions your app needs:

- ✓ **username** - Read user's Pi username
- ✓ **payments** - Process payments
- ✓ **wallet_address** - Access wallet address (optional)

Make sure these match what you requested in code.

### 4.5 Terms & Conditions

1. Check box: **"I agree to Pi Network Developer Terms"**
2. Check box: **"App follows Pi Network policies"**

---

## Step 5: Get Your API Key

### 5.1 Save/Create App

1. Click **"Save App"** or **"Create App"** button
2. Wait for processing (usually instant)
3. You'll see success message: **"App created successfully"**

### 5.2 View API Credentials

Your app dashboard will show:

**App ID:**
```
This is a unique identifier for your app
Example: 123456789abcdef
```

**API Key (Important!):**
```
This is your SECRET KEY - KEEP IT SAFE!
Example: sk_live_1a2b3c4d5e6f7g8h9i0j
```

**API Secret:**
```
Additional secret for server-to-server authentication
Example: secret_1a2b3c4d5e6f7g8h9i0j
```

### 5.3 Copy Your API Key

1. Click the **copy icon** next to API Key
2. Or manually select and copy the full key
3. **Store it safely** (password manager, secure note, etc.)

**⚠️ Security Note:** 
- Never share your API Key publicly
- Never commit it to GitHub
- Never post it in forums or chats
- Store it in environment variables only

---

## Step 6: Configure in Nexera Africa

### 6.1 Configure Backend

**Method 1: Direct Configuration (Testing Only)**

Edit `api/pi_payment.php`:

```php
<?php
// Find this line (around line 10):
define('PI_API_KEY', 'YOUR_PI_API_KEY_HERE');

// Replace with your actual key:
define('PI_API_KEY', 'sk_live_1a2b3c4d5e6f7g8h9i0j');
?>
```

**Method 2: Environment Variable (Recommended for Production)**

1. SSH into your VPS:
   ```bash
   ssh root@nexeraafrica.com
   ```

2. Edit your shell profile:
   ```bash
   nano ~/.bashrc
   ```

3. Add this line at the bottom:
   ```bash
   export PI_API_KEY="sk_live_1a2b3c4d5e6f7g8h9i0j"
   ```

4. Save (Ctrl+X, Y, Enter)

5. Reload the profile:
   ```bash
   source ~/.bashrc
   ```

6. Verify it's set:
   ```bash
   echo $PI_API_KEY
   ```

### 6.2 Update php.ini (If Using Environment Variables)

1. Check if environment variables are passed to PHP:
   ```bash
   php -i | grep variables_order
   ```

2. Should show: `variables_order => EGPCS`

3. If not, edit `php.ini`:
   ```bash
   sudo nano /etc/php/7.4/fpm/php.ini
   ```

4. Find and ensure this line:
   ```
   variables_order = "EGPCS"
   ```

5. Save and restart PHP:
   ```bash
   sudo systemctl restart php7.4-fpm
   ```

### 6.3 Update Api/pi_payment.php to Use Environment Variable

**Better approach for production:**

In `api/pi_payment.php`, change:

```php
// Old way (testing):
define('PI_API_KEY', 'sk_live_xxx');

// New way (production):
define('PI_API_KEY', getenv('PI_API_KEY') ?: 'sk_live_xxx');
```

This reads from environment variable, falls back to hardcoded value if needed.

### 6.4 Create .env File (Alternative Method)

Create file: `config/.env`

```
PI_API_KEY=sk_live_1a2b3c4d5e6f7g8h9i0j
DB_HOST=localhost
DB_USER=root
DB_PASS=your_password
DB_NAME=nexora_db
```

Then load it in `config/db.php`:

```php
<?php
// At the top of config/db.php
if (file_exists(__DIR__ . '/.env')) {
    $env = parse_ini_file(__DIR__ . '/.env');
    foreach ($env as $key => $value) {
        putenv("$key=$value");
    }
}

// Now use it:
$api_key = getenv('PI_API_KEY');
?>
```

---

## Step 7: Test Configuration

### 7.1 Quick Test in Terminal

SSH into your VPS:

```bash
ssh root@nexeraafrica.com
cd /var/www/html/nexera_africa
```

Test the API key:

```bash
php -r "
include 'api/pi_payment.php';
echo 'API Key set: ' . (defined('PI_API_KEY') ? 'YES' : 'NO') . '\n';
echo 'API Key length: ' . strlen(PI_API_KEY) . '\n';
"
```

Expected output:
```
API Key set: YES
API Key length: 55
```

### 7.2 Test Create Order Endpoint

```bash
curl -X POST https://nexeraafrica.com/api/pi_payment.php?action=create \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 0.00314,
    "memo": "Test Order",
    "metadata": {"test": true}
  }'
```

Expected response:
```json
{
  "status": "success",
  "orderId": "NEXERA-5f7g8h9i",
  "amount": 0.00314,
  "memo": "Test Order"
}
```

### 7.3 Test in Pi Browser

1. Download Pi Browser from: https://www.pi.network/browser

2. Install and open Pi Browser

3. Navigate to:
   ```
   https://nexeraafrica.com/checkout.html
   ```

4. You should see the checkout page load

5. Click "Connect Pi Wallet"

6. Authenticate with your Pi account

7. You should see your username displayed

8. Click "Complete Payment with Pi"

9. Payment process should start

10. Check database for created order:
    ```bash
    mysql -u root -p -e "SELECT * FROM nexora_db.pi_payments ORDER BY created_at DESC LIMIT 1;"
    ```

---

## Step 8: Switch from Sandbox to Production

### 8.1 When You're Ready

After thorough testing:

1. Go back to Developer Portal: https://develop.pi
2. Click on your app: **Nexera Africa**
3. Find **Sandbox** toggle
4. Switch to **Production** mode

### 8.2 Update Your Code

In `checkout.html` and `payment.php`:

**Change from:**
```javascript
Pi.init({ version: "2.0", sandbox: true });
```

**To:**
```javascript
Pi.init({ version: "2.0", sandbox: false });
```

### 8.3 Get Production API Key

1. In Developer Portal, switch to **Production** tab
2. Copy your **Production API Key**
3. Update your `.env` or `config`:
   ```
   PI_API_KEY=sk_prod_xxxxxxx
   ```

### 8.4 Update Callback URLs (Production)

In Developer Portal:

1. Go to App Settings
2. Update **Production Callback URL**:
   ```
   https://nexeraafrica.com/api/pi_payment.php
   ```

3. Click **Save**

---

## 🔍 Troubleshooting

### Problem: API Key Not Working

**Solution 1: Check the Key**
```bash
# Display just the first and last 10 chars (for security)
echo ${PI_API_KEY:0:10}...${PI_API_KEY: -10}
```

Verify format: Should start with `sk_live_` or `sk_prod_`

**Solution 2: Reload Environment**
```bash
source ~/.bashrc
php-fpm reload
```

**Solution 3: Check API Response**
```bash
curl -v https://api.minepi.com/v2/payments/test \
  -H "Authorization: Key YOUR_API_KEY"
```

Should return: `401 Unauthorized` or `404 Not Found` (both are OK - means API key is reaching)

---

### Problem: "Invalid API Key" Error

1. ✓ Verify key is correct (no extra spaces)
2. ✓ Check you're in correct mode (sandbox vs production)
3. ✓ Regenerate the key in Developer Portal if needed

---

### Problem: App Not Appearing in Developer Portal

1. Wait 5-10 minutes for system to process
2. Refresh page (Ctrl+R)
3. Log out and log back in
4. Try different browser

---

### Problem: Callback URL Not Working

1. Verify domain has SSL certificate:
   ```bash
   curl -I https://nexeraafrica.com/
   ```
   Should show `HTTP/2 200` or `HTTPS Connection`

2. Check firewall allows inbound connections:
   ```bash
   sudo ufw allow 443
   sudo ufw allow 80
   ```

3. Test endpoint directly:
   ```bash
   curl -X POST https://nexeraafrica.com/api/pi_payment.php?action=create \
     -H "Content-Type: application/json" \
     -d '{"amount": 0.00314, "memo": "test"}'
   ```

---

### Problem: "Unauthorized" When Testing Payment

1. Make sure you're using **Sandbox API Key** with `sandbox: true`
2. Make sure you're using **Production API Key** with `sandbox: false`
3. Don't mix sandbox and production

---

## 📱 Quick Reference

### Sandbox Testing
- **Mode:** `Pi.init({ version: "2.0", sandbox: true })`
- **API Key:** Starts with `sk_test_` or `sk_live_` from Sandbox section
- **Purpose:** Development and testing
- **Cost:** Free (no real Pi spent)

### Production Live
- **Mode:** `Pi.init({ version: "2.0", sandbox: false })`
- **API Key:** Starts with `sk_prod_` from Production section
- **Purpose:** Real transactions
- **Cost:** Real Pi spent

### Key Locations in Code
- **checkout.html:** Line ~150 (Pi.init)
- **payment.php:** Line ~200 (Pi.init)
- **api/pi_payment.php:** Line ~10-15 (API_KEY definition)

---

## ✅ Verification Checklist

- [ ] Pi account created and verified
- [ ] Developer Portal accessed
- [ ] App registered (Nexera Africa)
- [ ] Sandbox enabled
- [ ] Callback URLs configured
- [ ] API Key copied and stored safely
- [ ] API Key configured in code
- [ ] Tested with `curl` command
- [ ] Tested in Pi Browser
- [ ] Database table created
- [ ] Order created successfully
- [ ] Ready for production

---

## 🆘 Support Resources

| Resource | Link |
|----------|------|
| Pi Network Docs | https://docs.pi.network |
| Developer Portal | https://develop.pi |
| Pi Browser | https://www.pi.network/browser |
| API Reference | https://docs.pi.network/developer/reference/http_api |
| Community Forum | https://pinetwork.slack.com |
| GitHub Issues | https://github.com/pi-apps/pi-sdk |

---

## 📞 Need Help?

### Common Questions

**Q: Where do I find my API Key?**
A: Developer Portal → Your App → Credentials section

**Q: Can I use the same key for sandbox and production?**
A: No, they're separate keys. You get one for each.

**Q: What if I lose my API Key?**
A: You can regenerate it in Developer Portal. Old key becomes invalid.

**Q: Is it safe to commit API Key to GitHub?**
A: **NO!** Use environment variables or .gitignore

**Q: How often should I rotate my API Key?**
A: Every 90 days is recommended for security

---

**Last Updated:** June 13, 2026  
**Status:** Complete and Tested  
**Version:** 1.0
