# 🌐 LUSELLER API — TÀI LIỆU TÍCH HỢP HỆ THỐNG (API SPECIFICATION)

> **Phiên bản:** `v1.2.0`  
> **Giao thức:** `RESTful JSON API`  
> **Base URL:** `https://api.lucius.top`  
> **Xác thực:** API Key gắn kết 1:1 với tài khoản Telegram bot

---

## 📑 MỤC LỤC
1. [Tổng Quan & Kiến Trúc](#1-tổng-quan--kiến-trúc)
2. [Xác Thực & API Key](#2-xác-thực--api-key)
3. [Cơ Chế Mã Hóa id_product (Case-Sensitive String)](#3-cơ-chế-mã-hóa-id_product)
4. [Chính Sách Giá CTV & Làm Tròn](#4-chính-sách-giá-ctv--làm-tròn)
5. [Vòng Đời Đơn Hàng & Duyệt Thủ Công (NEEDS_REVIEW)](#5-vòng-đời-đơn-hàng--duyệt-thủ-công)
6. [Chi Tiết Các Endpoints](#6-chi-tiết-các-endpoints)
   - [GET /api/products — Danh sách sản phẩm](#61-get-apiproducts)
   - [GET /api/products/:id — Chi tiết sản phẩm](#62-get-apiproductsid)
   - [POST /api/orders/buy — Mua hàng qua API](#63-post-apiordersbuy)
   - [GET /api/orders — Lịch sử & Lọc đơn chờ duyệt](#64-get-apiorders)
   - [GET /api/orders/:order_id — Check trạng thái đơn hàng](#65-get-apiordersorder_id)
   - [GET /api/user/me — Thông tin tài khoản & Ví bot](#66-get-apiuserme)
   - [POST /api/wallet/topup — Tạo mã QR nạp tiền ví bot](#67-post-apiwallettopup)
   - [GET /api/health — Kiểm tra kết nối hệ thống](#68-get-apihealth)
7. [Bảng Mã Lỗi & HTTP Status Codes](#7-bảng-mã-lỗi--http-status-codes)
8. [Code Mẫu Tích Hợp (Node.js & Python)](#8-code-mẫu-tích-hợp)

---

## 1. TỔNG QUAN & KIẾN TRÚC

Luseller API là hệ thống API thương mại số chạy đồng bộ song song cùng bot Telegram `@luciustopadminbot`.
- **Thanh toán 1:1 từ ví bot:** Số dư trên bot Telegram chính là ngân sách thanh toán API. Không cần nạp tiền trung gian.
- **Xử lý đa luồng:** Hỗ trợ song song cả sản phẩm tự động xuất tài nguyên từ kho số và sản phẩm duyệt kích hoạt thủ công (như Youtube Premium, Canva Edu 2 năm).
- **Phân cấp đại lý CTV:** Tự động nhận diện API Key của CTV để trả về đơn giá ưu đãi đã làm tròn xuống đơn vị nghìn đồng.

---

## 2. XÁC THỰC & API KEY

Mỗi API Key tương ứng với duy nhất 1 tài khoản Telegram trên bot:
- **Lấy API Key:** Mở bot Telegram, gửi lệnh `/api` để lấy API Key cá nhân (định dạng `sk_bot_...`).
- **Gửi API Key trong Headers:**
  ```http
  X-API-Key: sk_bot_YOUR_API_KEY
  Content-Type: application/json
  ```
  *(Hỗ trợ thay thế bằng `Authorization: Bearer sk_bot_YOUR_API_KEY`)*

---

## 3. CƠ CHẾ MÃ HÓA ID_PRODUCT

Nhằm bảo mật ID nội bộ và phòng tránh duyệt ID tuần tự (enumeration attack), mã sản phẩm số nguyên (`1, 2, 103, 104...`) được hệ thống tự động mã hóa thành **chuỗi ký tự ngẫu nhiên phân biệt chữ hoa và chữ thường** (Case-Sensitive Base62 string):

| ID Gốc | Tên Sản Phẩm | `id_product` / `product_id` Mã Hóa |
| :---: | :--- | :---: |
| `1` | Gemini AI Pro 18 tháng | `7HZIVHq` |
| `2` | Gmails Accounts | `7HVU6U6` |
| `7` | Microsoft Office 365 Plus 1 năm | `7Hw4ENL` |
| `40` | Emails Outlook/Hotmail | `7HBuZ7p` |
| `45` | SCRIBD PREMIUM 1M FW | `7MRwAvW` |
| `54` | Gmail USA (global) | `7NTDK0C` |
| `56` | ElevenLabs API 131K Credit | `7NDUcpG` |
| `57` | Spotify premium account1M FW | `7NGzBqm` |
| `103` | **Youtube Premium 1 tháng** | `7ABo5OI` |
| `104` | **Canva Edu 2 năm (BHF)** | `7ARQMFn` |

> 💡 **Khả năng tương thích:**
> - Đầu ra API (`GET /api/products`, `GET /api/products/:id`) trả về `product_id` và `id_product` dưới dạng chuỗi mã hóa này.
> - Khi gửi yêu cầu (`GET /api/products/:id`, `POST /api/orders/buy`), hệ thống **chấp nhận cả 2 định dạng**: chuỗi mã hóa (ví dụ `"7ABo5OI"`) hoặc ID số nguyên (`103`).

---

## 4. CHÍNH SÁCH GIÁ CTV & LÀM TRÒN

Khi gửi yêu cầu có API Key của CTV, trường `user_price` sẽ được tự động áp dụng đơn giá CTV theo công thức:
$$\text{Giá CTV} = \lfloor \text{Giá công khai} \times (1 - \text{Discount}) \rfloor_{\text{nghìn đồng}}$$

### Bảng Phân Hạng CTV:
- **Hạng Đồng (Chi tiêu 0 - 5.000.000 VNĐ):** Áp dụng giá gốc CTV.
- **Hạng Bạc (Chi tiêu 5.000.000 - 10.000.000 VNĐ):** Giảm thêm **-5%** trên giá đơn hàng.
- **Hạng Vàng (Chi tiêu > 10.000.000 VNĐ):** Giảm thêm **-10%** trên giá đơn hàng.

### Sản Phẩm Cố Định Không Hết Hàng:
- **Youtube Premium 1 tháng (`7ABo5OI`):** Giá CTV cố định **10.000đ** (Giá công khai: 20.000đ).
- **Canva Edu 2 năm (BHF) (`7ARQMFn`):** Giá CTV cố định **5.000đ** (Giá công khai: 15.000đ).

---

## 5. VÒNG ĐỜI ĐƠN HÀNG & DUYỆT THỦ CÔNG

Đối với các sản phẩm kích hoạt qua email (như Youtube Premium hoặc Canva Edu):

```mermaid
sequenceDiagram
    autonumber
    actor Client as Đối Tác (Client API)
    participant Server as Luseller API Server
    participant DB as SQLite DB & Ví Bot
    actor Admin as Admin Telegram Bot

    Client->>Server: POST /api/orders/buy (product_id: "7ABo5OI", email: "...")
    Server->>DB: Trừ ví bot 1:1 & Lưu đơn status="NEEDS_REVIEW"
    Server->>Admin: Gửi thông báo kèm nút [Xác Nhận] & [Hủy]
    Server-->>Client: 200 OK (status: "NEEDS_REVIEW", order_id: "...")

    loop Polling (Mỗi 15-30s)
        Client->>Server: GET /api/orders/:order_id
        Server-->>Client: 200 OK (status: "NEEDS_REVIEW")
    end

    alt Admin bấm Xác Nhận Kích Hoạt
        Admin->>Server: Bấm [Xác Nhận Kích Hoạt Thành Công]
        Server->>DB: Đổi status="COMPLETED", lưu delivered_content
        Client->>Server: GET /api/orders/:order_id
        Server-->>Client: 200 OK (status: "COMPLETED", delivered_content: "...")
    else Admin bấm Hủy Đơn
        Admin->>Server: Bấm [Hủy & Hoàn Tiền]
        Server->>DB: Đổi status="CANCELLED" & Hoàn 100% ví
        Client->>Server: GET /api/orders/:order_id
        Server-->>Client: 200 OK (status: "CANCELLED", refund: true)
    end
```

---

## 6. CHI TIẾT CÁC ENDPOINTS

### 6.1. GET /api/products
Lấy danh sách tất cả các sản phẩm đang mở bán trên hệ thống.

- **URL:** `${BASE_URL}/api/products`
- **Method:** `GET`
- **Headers:** `X-API-Key` *(Tùy chọn - gửi để nhận giá CTV)*
- **cURL Mẫu:**
  ```bash
  curl -X GET "https://api.lucius.top/api/products" \
    -H "X-API-Key: sk_bot_YOUR_API_KEY"
  ```
- **Response 200 OK Mẫu:**
  ```json
  {
    "success": true,
    "count": 34,
    "is_authenticated": true,
    "caller_is_ctv": true,
    "data": [
      {
        "product_id": "7ABo5OI",
        "id_product": "7ABo5OI",
        "name": "Youtube Premium 1 tháng",
        "category_id": 1,
        "description": "- Sử dụng trong vòng 25-30 ngày...",
        "status": "active",
        "in_stock": true,
        "public_price": 20000,
        "ctv_price": 10000,
        "user_price": 10000,
        "is_ctv_applied": true,
        "requires_email": true,
        "manual_activation": true
      },
      {
        "product_id": "7ARQMFn",
        "id_product": "7ARQMFn",
        "name": "Canva Edu 2 năm (BHF)",
        "category_id": 1,
        "description": "- Kích hoạt Canva Edu 2 Năm trực tiếp...",
        "status": "active",
        "in_stock": true,
        "public_price": 15000,
        "ctv_price": 5000,
        "user_price": 5000,
        "is_ctv_applied": true,
        "requires_email": true,
        "manual_activation": true
      }
    ]
  }
  ```

---

### 6.2. GET /api/products/:id
Tra cứu chi tiết một sản phẩm theo ID mã hóa hoặc ID số.

- **URL:** `${BASE_URL}/api/products/:id` (ví dụ: `/api/products/7ABo5OI` hoặc `/api/products/103`)
- **Method:** `GET`
- **Headers:** `X-API-Key` *(Tùy chọn)*
- **cURL Mẫu:**
  ```bash
  curl -X GET "https://api.lucius.top/api/products/7ABo5OI" \
    -H "X-API-Key: sk_bot_YOUR_API_KEY"
  ```
- **Response 200 OK Mẫu:**
  ```json
  {
    "success": true,
    "data": {
      "product_id": "7ABo5OI",
      "id_product": "7ABo5OI",
      "name": "Youtube Premium 1 tháng",
      "category_id": 1,
      "description": "- Sử dụng trong vòng 25-30 ngày...",
      "status": "active",
      "in_stock": true,
      "public_price": 20000,
      "ctv_price": 10000,
      "user_price": 10000,
      "is_ctv_applied": true,
      "requires_email": true,
      "manual_activation": true
    }
  }
  ```

---

### 6.3. POST /api/orders/buy
Mua sản phẩm qua API bằng số dư ví bot Telegram.

- **URL:** `${BASE_URL}/api/orders/buy`
- **Method:** `POST`
- **Headers:** 
  - `X-API-Key: sk_bot_...` *(Bắt buộc)*
  - `Content-Type: application/json`
- **Request Body (JSON):**
  | Trường | Kiểu | Bắt buộc | Mô tả |
  | :--- | :---: | :---: | :--- |
  | `product_id` | String / Int | Có | ID mã hóa (`"7ABo5OI"`) hoặc ID số (`103`) |
  | `quantity` | Integer | Không | Số lượng mua (mặc định: `1`) |
  | `email` | String | Tùy SP | Bắt buộc với SP có `requires_email: true` |

- **cURL Mẫu (Mua Youtube Premium 10k):**
  ```bash
  curl -X POST "https://api.lucius.top/api/orders/buy" \
    -H "X-API-Key: sk_bot_YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "product_id": "7ABo5OI",
      "quantity": 1,
      "email": "khachhang@gmail.com"
    }'
  ```

- **Response 200 OK — Đơn Chờ Duyệt Thủ Công (NEEDS_REVIEW):**
  ```json
  {
    "success": true,
    "status": "NEEDS_REVIEW",
    "status_text": "Chờ duyệt thủ công (Admin đang kích hoạt)",
    "order_id": "101026606658",
    "product_id": "7ABo5OI",
    "id_product": "7ABo5OI",
    "product_name": "Youtube Premium 1 tháng",
    "quantity": 1,
    "unit_price": 10000,
    "total_price": 10000,
    "is_ctv": true,
    "email": "khachhang@gmail.com",
    "is_manual_review": true,
    "balance_remaining": 40000,
    "check_status_url": "/api/orders/101026606658",
    "message": "Đơn hàng đã được thanh toán từ số dư ví bot và đang chờ Admin kích hoạt thủ công cho email khachhang@gmail.com. Kiểm tra tiến độ qua GET /api/orders/101026606658"
  }
  ```

- **Response 200 OK — Đơn Kho Tự Động (COMPLETED):**
  ```json
  {
    "success": true,
    "status": "COMPLETED",
    "status_text": "Hoàn tất (Đã giao hàng thành công)",
    "order_id": "101026889922",
    "product_id": "7HZIVHq",
    "id_product": "7HZIVHq",
    "product_name": "Gemini AI Pro 18 tháng",
    "quantity": 1,
    "unit_price": 17000,
    "total_price": 17000,
    "is_ctv": true,
    "delivered_content": "https://families.google.com/join/...",
    "balance_remaining": 23000,
    "check_status_url": "/api/orders/101026889922",
    "message": "Đơn hàng đã hoàn tất thành công."
  }
  ```

---

### 6.4. GET /api/orders
Lấy danh sách toàn bộ lịch sử đơn hàng của tài khoản.

- **URL:** `${BASE_URL}/api/orders`
- **Method:** `GET`
- **Headers:** `X-API-Key` *(Bắt buộc)*
- **Query Params:**
  - `status`: Lọc trạng thái (`NEEDS_REVIEW`, `COMPLETED`, `CANCELLED`).
  - `limit`: Giới hạn số đơn trả về (ví dụ: `20`).
- **cURL Mẫu (Lọc danh sách các đơn đang chờ duyệt thủ công):**
  ```bash
  curl -X GET "https://api.lucius.top/api/orders?status=NEEDS_REVIEW" \
    -H "X-API-Key: sk_bot_YOUR_API_KEY"
  ```
- **Response 200 OK Mẫu:**
  ```json
  {
    "success": true,
    "count": 1,
    "filter_status": "NEEDS_REVIEW",
    "data": [
      {
        "order_id": "101026606658",
        "product_id": "7ABo5OI",
        "id_product": "7ABo5OI",
        "product_name": "Youtube Premium 1 tháng",
        "quantity": 1,
        "total_price": 10000,
        "payment_method": "BALANCE",
        "status": "NEEDS_REVIEW",
        "status_text": "Chờ duyệt thủ công (Admin đang kích hoạt)",
        "is_manual_review": true,
        "email": "khachhang@gmail.com",
        "delivered_content": null,
        "check_status_url": "/api/orders/101026606658",
        "created_at": "2026-10-10 10:45:00"
      }
    ]
  }
  ```

---

### 6.5. GET /api/orders/:order_id
Check trạng thái chi tiết của một đơn hàng cụ thể.

- **URL:** `${BASE_URL}/api/orders/:order_id` (ví dụ: `/api/orders/101026606658`)
- **Method:** `GET`
- **Headers:** `X-API-Key` *(Bắt buộc)*
- **cURL Mẫu:**
  ```bash
  curl -X GET "https://api.lucius.top/api/orders/101026606658" \
    -H "X-API-Key: sk_bot_YOUR_API_KEY"
  ```

#### Các trường hợp phản hồi:
1. **Đơn đang chờ Admin kích hoạt thủ công (`NEEDS_REVIEW`):**
   ```json
   {
     "success": true,
     "data": {
       "order_id": "101026606658",
       "product_id": "7ABo5OI",
       "id_product": "7ABo5OI",
       "product_name": "Youtube Premium 1 tháng",
       "quantity": 1,
       "total_price": 10000,
       "payment_method": "BALANCE",
       "status": "NEEDS_REVIEW",
       "status_text": "Chờ duyệt thủ công (Admin đang kích hoạt)",
       "is_manual_review": true,
       "email": "khachhang@gmail.com",
       "delivered_content": null,
       "check_status_url": "/api/orders/101026606658",
       "created_at": "2026-10-10 10:45:00"
     }
   }
   ```
2. **Đơn Admin đã bấm xác nhận hoàn tất (`COMPLETED`):**
   ```json
   {
     "success": true,
     "data": {
       "order_id": "101026606658",
       "status": "COMPLETED",
       "status_text": "Hoàn tất (Đã kích hoạt / Giao hàng thành công)",
       "email": "khachhang@gmail.com",
       "delivered_content": "Đã kích hoạt thành công trên email: khachhang@gmail.com",
       "check_status_url": "/api/orders/101026606658",
       "created_at": "2026-10-10 10:45:00"
     }
   }
   ```
3. **Đơn bị Admin hủy & đã hoàn tiền ví (`CANCELLED`):**
   ```json
   {
     "success": true,
     "data": {
       "order_id": "101026606658",
       "status": "CANCELLED",
       "status_text": "Đã hủy & hoàn tiền vào ví bot",
       "delivered_content": null,
       "created_at": "2026-10-10 10:45:00"
     }
   }
   ```

---

### 6.6. GET /api/user/me
Tra cứu số dư ví bot, cấp bậc CTV, tổng chi tiêu.

- **URL:** `${BASE_URL}/api/user/me`
- **Method:** `GET`
- **Headers:** `X-API-Key` *(Bắt buộc)*
- **Response 200 OK Mẫu:**
  ```json
  {
    "success": true,
    "data": {
      "user_id": 6372286539,
      "username": "Ngthlu24",
      "full_name": "Nope",
      "balance": 18624000,
      "total_spent": 1922000,
      "total_orders": 59,
      "points": 1663,
      "is_ctv": true,
      "ctv_spent": 1922000,
      "ctv_orders": 59,
      "ctv_rank": {
        "rank": 1,
        "shortName": "Hạng Đồng",
        "bonusPercent": 0,
        "needMore": 3078000
      }
    }
  }
  ```

---

### 6.7. POST /api/wallet/topup
Tạo mã QR chuẩn **VietQR** để nạp tiền vào ví bot Telegram. Hệ thống TPBank tự động quét biến động số dư và cộng tiền vào ví trong 1-3 phút khi nhận tiền chuyển đúng nội dung `NAP<telegram_id>NAP`.

- **URL:** `${BASE_URL}/api/wallet/topup` *(Hỗ trợ cả `POST` body JSON và `GET ?amount=...`)*
- **Method:** `POST` hoặc `GET`
- **Headers:** `X-API-Key` *(Bắt buộc)*
- **Request Body (JSON - áp dụng cho POST):**
  | Trường | Kiểu | Bắt buộc | Mô tả |
  | :--- | :---: | :---: | :--- |
  | `amount` | Integer | Không | Số tiền VNĐ muốn nạp (tối thiểu `1000`). Nếu không gửi, mã QR cho phép khách tự điền số tiền khi quét app ngân hàng. |

- **cURL Mẫu (Tạo QR nạp 50.000 VNĐ):**
  ```bash
  curl -X POST "https://api.lucius.top/api/wallet/topup" \
    -H "X-API-Key: sk_bot_YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{ "amount": 50000 }'
  ```
- **Response 200 OK Mẫu:**
  ```json
  {
    "success": true,
    "message": "Tạo mã QR nạp tiền ví bot thành công",
    "data": {
      "user_id": 6372286539,
      "username": "Ngthlu24",
      "transfer_code": "NAP6372286539NAP",
      "amount": 50000,
      "amount_formatted": "50.000 VNĐ",
      "bank_info": {
        "bank_name": "TPBank",
        "account_number": "10004923706",
        "account_holder": "NGUYEN THANH LUAN"
      },
      "qr_url": "https://img.vietqr.io/image/TPB-10004923706-qr_only.png?amount=50000&addInfo=NAP6372286539NAP",
      "qr_code_image": "https://img.vietqr.io/image/TPB-10004923706-qr_only.png?amount=50000&addInfo=NAP6372286539NAP",
      "current_balance": 18624000,
      "current_balance_formatted": "18.624.000 VNĐ",
      "instructions": "Quét mã QR hoặc chuyển khoản đến TPBank STK 10004923706 với NỘI DUNG CHUYỂN KHOẢN là NAP6372286539NAP. Tiền sẽ được cộng tự động vào ví bot trong 1-3 phút.",
      "check_balance_url": "/api/user/me"
    }
  }
  ```

---

### 6.8. GET /api/health
Kiểm tra sức khỏe dịch vụ và trạng thái Telegram Bot.

- **URL:** `${BASE_URL}/api/health`
- **Method:** `GET`
- **Headers:** Không yêu cầu (Public)
- **Response 200 OK Mẫu:**
  ```json
  {
    "success": true,
    "status": "ok",
    "service": "luseller-api",
    "timestamp": "2026-10-10T11:00:00.000Z",
    "bot_connected": true
  }
  ```

---

## 7. BẢNG MÃ LỖI & HTTP STATUS CODES

| HTTP Status | Mã Lỗi | Nguyên Nhân & Giải Pháp |
| :---: | :--- | :--- |
| `200` | `OK` | Yêu cầu xử lý thành công. |
| `400` | `Bad Request` | Thiếu trường bắt buộc, số dư không đủ, hoặc email sai cú pháp. |
| `401` | `Unauthorized` | Không có `X-API-Key` hoặc API Key không tồn tại trên hệ thống. |
| `403` | `Forbidden` | Tài khoản đã bị Admin khóa hoặc không có quyền truy cập tài nguyên. |
| `404` | `Not Found` | Không tìm thấy mã sản phẩm hoặc mã đơn hàng. |
| `500` | `Internal Server Error` | Lỗi máy chủ nội bộ. |

---

## 8. CODE MẪU TÍCH HỢP

### Node.js (Fetch / Async/Await)
```javascript
const API_URL = 'https://api.lucius.top';
const API_KEY = 'sk_bot_YOUR_API_KEY';

async function buyProduct(productId, email = null) {
  const res = await fetch(`${API_URL}/api/orders/buy`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': API_KEY,
    },
    body: JSON.stringify({ product_id: productId, quantity: 1, email }),
  });
  const data = await res.json();
  console.log('Kết quả mua hàng:', data);
  return data;
}

async function checkOrderStatus(orderId) {
  const res = await fetch(`${API_URL}/api/orders/${orderId}`, {
    headers: { 'X-API-Key': API_KEY },
  });
  return await res.json();
}

async function createTopupQr(amount = 50000) {
  const res = await fetch(`${API_URL}/api/wallet/topup`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': API_KEY,
    },
    body: JSON.stringify({ amount }),
  });
  const data = await res.json();
  console.log('Mã QR VietQR:', data.data.qr_url);
  return data;
}

// Ví dụ: Mua Youtube Premium (id_product: "7ABo5OI")
buyProduct('7ABo5OI', 'khachhang@gmail.com').then(order => {
  if (order.success && order.status === 'NEEDS_REVIEW') {
    console.log(`Đơn ${order.order_id} đang chờ Admin duyệt...`);
  }
});
```

### Python (Requests)
```python
import requests

API_URL = "https://api.lucius.top"
API_KEY = "sk_bot_YOUR_API_KEY"
HEADERS = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json"
}

def buy_product(product_id, email=None):
    payload = {"product_id": product_id, "quantity": 1}
    if email:
        payload["email"] = email
    response = requests.post(f"{API_URL}/api/orders/buy", json=payload, headers=HEADERS)
    return response.json()

def check_order(order_id):
    response = requests.get(f"{API_URL}/api/orders/{order_id}", headers=HEADERS)
    return response.json()

def create_topup_qr(amount=50000):
    response = requests.post(f"{API_URL}/api/wallet/topup", json={"amount": amount}, headers=HEADERS)
    return response.json()

# Tạo mã QR nạp 50k vào ví bot
topup = create_topup_qr(50000)
print("Link ảnh QR:", topup["data"]["qr_url"])
```

---
*© 2026 Luseller API Specification. Mọi thắc mắc hỗ trợ vui lòng liên hệ Admin qua Telegram bot.*
