# 🚀 Crypto Payment System — Progress Document
> **Purpose:** This document tracks every decision, file, and status so any AI (or developer) can continue the project from exactly where it left off.
> **Last Updated:** Phase 1 COMPLETE ✅

---

## 📋 Project Overview

**Goal:** A crypto payment system embeddable in any plain HTML website, backed by a PHP/MySQL server.

**Supported Coins:**
| Coin | Network | Blockchain API |
|------|---------|---------------|
| BTC  | Bitcoin | BlockCypher (free, 300 req/hr) |
| USDT | ERC-20 (Ethereum) | Alchemy (free tier) |
| USDC | ERC-20 (Ethereum) | Alchemy (free tier) |
| BNB  | BSC (Binance Smart Chain) | BSCScan (free) |
| USDT | BEP-20 (BSC) | BSCScan (free) |

**Tech Stack:**
- Frontend: Plain HTML, CSS, Vanilla JavaScript
- Backend: PHP 8+, MySQL
- Payment monitoring: Cron job (every 60 seconds)
- QR Codes: api.qrserver.com (free, no key)

---

## 🗂️ File Structure (All Files)

```
crypto-payment/
├── config.php                    ✅ DONE — All settings, API keys, wallet addresses
├── db_setup.sql                  ✅ DONE — All MySQL table definitions
├── install.php                   ✅ DONE — One-click web installer (delete after use)
│
├── includes/
│   ├── db.php                    ✅ DONE — PDO database singleton
│   ├── auth.php                  ✅ DONE — Register, login, sessions, balance credit
│   ├── payment.php               ✅ DONE — Create payments, confirm, unique amounts
│   └── blockchain.php            ✅ DONE — BlockCypher + Alchemy + BSCScan API calls
│
├── api/
│   ├── auth.php                  ✅ DONE — POST /api/auth.php?action=register|login|logout|me
│   ├── create_payment.php        ✅ DONE — POST — create a payment request
│   ├── check_payment.php         ✅ DONE — GET  — poll payment status
│   ├── get_balance.php           ✅ DONE — GET  — fetch user balances
│   └── transactions.php          ✅ DONE — GET  — fetch transaction history
│
├── cron/
│   └── monitor_payments.php      ✅ DONE — Cron job to check blockchain & confirm payments
│
├── widget/
│   ├── payment-widget.css        ✅ DONE — Full dark-mode widget styles
│   └── payment-widget.js         ✅ DONE — Full widget JS (modal, QR, polling, login, balance)
│
├── demo/
│   └── index.html                ✅ DONE — Example integration page
│
└── docs/
    └── PROGRESS.md               ✅ THIS FILE
```

**Still TODO (Phase 2):**
```
├── demo/dashboard.html           ✅ COMPLETE — Full user dashboard page with balance & transactions
├── widget/payment-widget.html    ✅ COMPLETE — Standalone widget test sandbox with embed code generator
├── api/withdraw.php              ✅ COMPLETE — Withdrawal API with atomic balance deduction
├── admin/
│   ├── index.php                 ✅ COMPLETE — Unified Admin dashboard with user manager, deposit/withdrawal handlers
│   └── payments.php              ✅ COMPLETE — Embedded inside index.php
```

---

## 🏗️ Architecture & Key Design Decisions

### 1. Payment Identification (Unique Amount Method)
**Problem:** Multiple users share the same wallet address. How do we know which payment belongs to which user?

**Solution:** When a payment request is created, we add a tiny random "tag" to the last decimal places:
- User wants to pay 100 USDT → system assigns 100.000047 USDT
- The unique tag (47) lets us match the incoming transaction to the payment request
- Tolerance: ±0.01 for stablecoins, ±0.00001 for BTC

**Code:** `includes/payment.php` → `makeUniqueAmount()`

### 2. Balance Storage
Balances are stored as DECIMAL in the database per coin per user:
```sql
bal_btc       DECIMAL(18,8)   -- Bitcoin
bal_usdt_erc  DECIMAL(18,6)   -- USDT ERC-20
bal_usdc_erc  DECIMAL(18,6)   -- USDC ERC-20
bal_bnb       DECIMAL(18,8)   -- BNB
bal_usdt_bep  DECIMAL(18,6)   -- USDT BEP-20
```

### 3. Payment Monitoring Flow
```
[Cron: every 60s]
  → Fetch all 'pending'/'detecting' payments
  → For each payment:
      → Call appropriate blockchain API
      → Look for transaction to merchant address with matching amount
      → If found with ≥1 confirmation:
          → Mark payment 'confirmed'
          → Insert into transactions table
          → Add amount to user's balance (UPDATE users SET bal_xxx = bal_xxx + amount)
```

### 4. Frontend Polling
The widget also polls the status API every 10 seconds so the UI updates in real-time when payment is detected.

### 5. Session Auth
Simple Bearer token system:
- Token stored in localStorage on the frontend
- Sent as `Authorization: Bearer {token}` header
- Sessions table in DB with 7-day expiry

---

## 🔑 API Keys Needed

The user needs to get these free API keys and put them in `config.php`:

| Service | Purpose | Free Signup |
|---------|---------|------------|
| Alchemy | ETH/USDT ERC-20/USDC detection | https://alchemy.com |
| BSCScan | BNB/USDT BEP-20 detection | https://bscscan.com/apis |
| BlockCypher | BTC detection (optional, works without) | https://www.blockcypher.com |

---

## 🚀 Deployment Steps (for user)

1. **Upload** all files to your server (e.g., `/var/www/html/crypto-payment/`)
2. **Create DB**: `mysql -u root -p -e "CREATE DATABASE crypto_payments;"`
3. **Run installer**: Visit `https://yourdomain.com/crypto-payment/install.php?run=1`
4. **Delete installer**: Remove `install.php` from server
5. **Edit config.php**:
   - Set your wallet addresses (`WALLET_BTC`, `WALLET_ETH`, `WALLET_BSC`)
   - Set API keys (Alchemy, BSCScan)
   - Set `APP_URL` to your domain
   - Set a strong `APP_SECRET`
6. **Set up cron job**:
   ```
   * * * * * /usr/bin/php /var/www/html/crypto-payment/cron/monitor_payments.php >> /tmp/crypto_cron.log 2>&1
   ```
7. **Embed widget** in your HTML:
   ```html
   <link rel="stylesheet" href="/crypto-payment/widget/payment-widget.css">
   <script src="/crypto-payment/widget/payment-widget.js"></script>
   <script>
     CryptoPayment.init({ apiBase: 'https://yourdomain.com/crypto-payment' });
   </script>
   <button onclick="CryptoPayment.open()">Deposit Crypto</button>
   ```

---

## 📊 Database Tables Summary

| Table | Purpose |
|-------|---------|
| `users` | Stores accounts + balances per coin |
| `payment_requests` | One row per payment attempt; tracks status |
| `transactions` | Confirmed payment ledger |
| `sessions` | Auth tokens |
| `monitor_log` | Cron job debug log |

---

## 🔄 Payment Status Flow

```
[created] → pending → detecting → confirmed ✅
                    ↓
                  expired ⏰ (after 30 mins)
                    ↓
                  failed ❌
```

---

## 📡 API Endpoints Reference

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| POST | `/api/auth.php?action=register` | None | Register user |
| POST | `/api/auth.php?action=login` | None | Login, get token |
| POST | `/api/auth.php?action=logout` | Bearer | Logout |
| GET  | `/api/auth.php?action=me` | Bearer | Get current user |
| POST | `/api/create_payment.php` | Bearer | Create payment request |
| GET  | `/api/check_payment.php?payment_id=X` | Bearer | Poll payment status |
| GET  | `/api/get_balance.php` | Bearer | Get balances |
| GET  | `/api/transactions.php` | Bearer | Get transaction history |

---

## ⏳ Phase 2 COMPLETE & What's Next (Phase 3)

All Phase 2 core deliverables are successfully implemented:
- **Priority 1: Dashboard page (`demo/dashboard.html`)** — ✅ COMPLETE
- **Priority 2: Admin Panel (`admin/index.php`)** — ✅ COMPLETE (Unified)
- **Priority 4: Withdrawal System (`api/withdraw.php`)** — ✅ COMPLETE (Atomic balance ledger)

### Next steps for Phase 3:
1. **Live Blockchain Testing**: Plug real API keys into `config.php` (Alchemy, BSCScan) and verify transaction detections.
2. **Production Deployment**: Deploy files to hosting (Namecheap, etc.), run database setup, configure cron, and remove installer.
3. **Webhook Notifications (Optional)**: Move from client-side polling to BlockCypher hooks for real-time BTC triggers.
4. **Standalone Widget Test Page (`widget/payment-widget.html`)**: ✅ COMPLETE (Interactive Sandbox & Embed Code Generator)

---

## 🐛 Known Limitations / To Watch

1. **Rate limits**: BlockCypher free = 300 req/hr. With many pending payments, could hit limit. Solution: add exponential backoff in cron.
2. **Amount collision**: Very rare but two users could get same unique amount. Add collision check in `makeUniqueAmount()` (query DB to ensure uniqueness).
3. **Token confirmations**: Currently requires 1 confirmation. For large amounts, increase `MIN_CONFIRMATIONS` in config.php.
4. **HTTPS required**: Browser localStorage and `fetch` API work best on HTTPS. Always use SSL.
5. **PHP bcmath**: `blockchain.php` uses `bcmul/bcdiv` for big integers. Ensure `bcmath` PHP extension is enabled.

---

## 💬 Prompt to Continue This Project

When sending this to another AI, use this prompt:

> "I'm building a crypto payment system. Here is the full progress document: [paste this file]. We have completed Phase 1. Please continue with Phase 2, starting with the dashboard page (`demo/dashboard.html`). The tech stack is plain HTML/CSS/JS frontend + PHP 8 backend + MySQL. All backend files are in place."

---
*Document auto-generated | Phase 1 Complete | All core files built*
