# IlmFun Official Platform & Partner API Documentation (v2.0)

**Official Documentation Portal**: `https://docs.ilmfun.com`  
**Partner Network Portal**: `https://partner.ilmfun.com`  
**Base M2M API URL**: `https://partner.ilmfun.com/api/v1` (Alias: `https://partner.ilmfun.com/api/v1/payment-provider`)  
**OpenAPI 3.0.3 Specification**: `https://docs.ilmfun.com/openapi.json`  
**ISO 4217 Currency Minor Units**: `https://docs.ilmfun.com/currencies`

---

## 1. Platform Overview & Ecosystem Architecture

IlmFun is an educational community and live-classroom ecosystem powered by a unified internal virtual currency called **Emeralds (Zumrad, 💎)**. Every stakeholder participates in a transparent, legally compliant, and mutually profitable economy:

1. **Learners & Students**:
   - Earn Emeralds by completing verified **Quests** (sponsored by educational partners, universities, and brands) or acquire Emeralds on the web account portal (`https://ilmfun.com/account`) via authorized regional Payment Service Providers (PSPs).
   - Spend Emeralds on **IlmFun MAX** (`100 💎 / 30 days`), **Paid Live Events & Classes**, **Academy Shop Items & Purchasable Roles**, and **Global & Partner Shop** items (courses, IELTS/SAT exam vouchers, textbooks, robotics/hardware kits).
2. **Teachers, Instructors & Academy Owners**:
   - Host paid live interactive classes and events with automatic **7-Day Student Protection** and **30-Day Rolling FIFO Escrow**.
   - Monetize their academies with **Purchasable Academy Roles** (`one_time` or `monthly`) and **Academy Shop** storefronts, configuring an academy commission percentage (`0%–50%`) on items sold by authorized academy sellers.
3. **Commercial Partners, Sponsors & Payment Providers (`partner.ilmfun.com`)**:
   - **Payment Service Providers (PSPs) & Authorized Merchants**: Process Emerald top-ups and cashout settlements backed 100% by segregated **Reserve Float**.
   - **Store Merchants & Course Providers**: List digital vouchers, courses, books, hardware kits, and webhook-provisioned services in the Global Shop, earning Emeralds on every sale.
   - **Quest Sponsors & Educational Brands**: Launch Emerald-backed **Quests** (`telegram_join`, `video_watch`, `web_visit`, `academy_join`) with 100% escrowed campaign budgets to engage verified learners.

---

## 2. Authentication, Scopes & Security

All machine-to-machine (M2M) API calls require HTTPS (TLS 1.3+) and a bearer secret key (`ifp_<64_hex_chars>`) generated in the Partner Portal (`https://partner.ilmfun.com`).

```http
Authorization: Bearer ifp_YOUR_SECRET_KEY
Content-Type: application/json
```

### API Key Scopes
| Scope | Capabilities |
|---|---|
| `read` | Read partner account status, reserve float, order lists, shop catalog, and quest stats (`GET /account`, `GET /orders`, `GET /shop/*`, `GET /quests`). |
| `lookup` | Verify customer existence, country eligibility, and optional balance sharing (`GET /users/{username}`). |
| `topup` | Create Emerald top-up invoices and complete/cancel top-up orders (`POST /topups`, `POST /orders/{id}`). |
| `withdrawal` | Claim, complete, or fail customer cashout/withdrawal orders (`POST /orders/{id}`). |
| `refund` | Process customer refund orders (`POST /orders/{id}`). |
| `shop` | Create, update, toggle, delete Partner Shop items and fulfill or refund customer shop orders (`/shop/*`). |
| `quests` | Create, update, toggle, delete Sponsored Quests and inspect completion logs (`/quests/*`). |

### Idempotency & Rate Limits
- Mutating payment endpoints (`POST /topups`) require an `Idempotency-Key` header (`8–128` ASCII characters `[A-Za-z0-9_-]`). Replaying the exact same payload with the same key returns the original order (`200 OK`); sending a different payload with an existing key returns `409 Conflict` (`idempotency_conflict`).
- All 64-bit Snowflake IDs (`user_id`, `academy_id`) are serialized as strings in JSON payloads. Never cast them to IEEE-754 `Number` in JavaScript.

---

## 3. Payment Provider & Reserve Float API

### 3.1 Currency & Integer Minor Units
- `amount` is always whole integer Emeralds (`💎`).
- `fiat_minor` is always whole integer minor units of the settlement currency (`fiat_minor = amount * rate`, displayed as `fiat_minor / 10^currency_decimals`).
- Three contract rates govern each provider (in minor units per `1 💎`):
  - `deposit_rate`: Reserve float funding and settlement rate.
  - `topup_rate`: Customer purchase price per Emerald.
  - `payout_rate`: Customer cashout payout per Emerald (`payout_rate <= deposit_rate <= topup_rate`).

### 3.2 Endpoints
1. **`GET /api/v1/account`**: Returns provider status, contract rates, limits, and segregated reserve float (`available`, `customer_liability`, `settled_total`).
2. **`GET /api/v1/users/{username}`**: Verifies customer account and `payment_ready` status before charging or paying out.
3. **`POST /api/v1/topups`**: Reserves `amount` from `available` float into `customer_liability` and creates an `authorized` order.
4. **`POST /api/v1/orders/{id}`**:
   - `{"action": "claim", "verification_reference": "..."}`: Atomically transitions `authorized -> processing`. Must be called before capturing funds or sending payouts. Returns `409 Conflict` if already claimed.
   - `{"action": "complete", "reference": "..."}`: Finalizes `processing -> completed` (or `reported_paid` for withdrawals), crediting Emeralds to the customer and consuming the held liability.
   - `{"action": "cancel", "reason": "..."}`: Releases held liability back to `available` float.

---

## 4. Partner Shop & Real-Time Purchase Webhooks API

Partners can sell vouchers, courses, books, hardware kits, and automated digital services in the IlmFun Shop.

### 4.1 Shop Endpoints
- `GET /api/v1/shop/items` — List your shop items and revenue statistics.
- `POST /api/v1/shop/items` — Publish a new item (`category`, `price_emeralds`, `delivery_type`: `instant` | `manual` | `service`, `service_type`: `none` | `webhook_custom`, `webhook_url`, `webhook_secret`, `stock`, `max_per_user`).
- `PUT /api/v1/shop/items/{id}` — Update item pricing, stock, delivery content, or webhook configuration.
- `POST /api/v1/shop/items/{id}/toggle` — Pause or resume a listing.
- `DELETE /api/v1/shop/items/{id}` — Remove a listing.
- `GET /api/v1/shop/orders` — List customer purchase orders.
- `POST /api/v1/shop/orders/{id}/fulfill` — Update order status (`processing`, `fulfilled`, `refunded`), attach `delivery_content` (voucher/license code), or add `fulfillment_note`.

### 4.2 Real-Time Webhook Verification (`X-IlmFun-Signature`)
When a learner purchases an item configured with `webhook_url`, IlmFun sends an HTTP `POST` request with:
- `X-IlmFun-Event: shop.order.created`
- `X-IlmFun-Order-ID: ord_shop_...`
- `X-IlmFun-Signature: sha256=<hex_hmac_sha256>` (computed over the raw JSON request body using your `webhook_secret`)

Your webhook endpoint can return HTTP `200 OK` with JSON to dynamically inject a generated license/voucher code directly into the buyer's receipt:
```json
{
  "status": "fulfilled",
  "delivery_content": "IELTS-MOCK-2026-99481",
  "fulfillment_note": "Activated for @student_ali"
}
```

---

## 5. Sponsored Quests & Emerald Escrow API

Partners can sponsor interactive learning quests (`telegram_join`, `video_watch`, `web_visit`, `academy_join`).

### 5.1 Budget Escrow Guarantee
- Every partner quest requires a finite `max_completions >= 1` and `reward_emeralds >= 1`.
- Total campaign budget (`reward_emeralds * max_completions`) is escrowed from your Partner Balance / Reserve Float when the quest is created.
- If a quest is deleted or its `max_completions` is reduced, all unspent escrowed Emeralds (`(max_completions - current_completions) * reward_emeralds`) are automatically refunded to your available balance.

### 5.2 Quest Endpoints
- `GET /api/v1/quests` — List your quests and completion metrics.
- `POST /api/v1/quests` — Create and fund a new quest campaign.
- `PUT /api/v1/quests/{id}` — Update quest details or adjust `max_completions` budget.
- `POST /api/v1/quests/{id}/toggle` — Pause or resume a quest.
- `DELETE /api/v1/quests/{id}` — Delete a quest and refund unspent escrowed Emeralds.
- `GET /api/v1/quests/{id}/completions` — Retrieve verified learner completions with timestamps.
