# 🔌 Reseller API Documentation — Automated Gmail Store (v1)

Tài liệu tích hợp **API v1** dành cho **Shop Đại Lý / Cộng Tác Viên (Reseller)** đấu kho Gmail tự động 24/7:
- Mua Gmail trừ ví đại lý tức thì, tự áp dụng **% chiết khấu riêng**.
- Hỗ trợ `client_order_id` **chống trừ trùng tiền** khi mạng lag / timeout retry.
- Dữ liệu trả về sạch chuẩn **6 cột** (tự bỏ `Profile ID` & `Note` nội bộ), có cả chuỗi raw (`items_raw`) và JSON object (`items`).
- Tự tạo mã **VietQR nạp ví đại lý** (`POST /api/v1/topup`), tiền tự cộng vào ví sau **2–10 giây**.

---

## 1. Base URL & Xác thực (Authentication)

- **Base URL:** `https://miragemail.vorte.me`
- **Web Docs (có giao diện Test trực tiếp):** `https://miragemail.vorte.me/docs` *(English: `https://miragemail.vorte.me/docs?lang=en`)*
- **Tải file Markdown mới nhất:** `https://miragemail.vorte.me/docs.md`

Mọi request tới `/api/v1/*` đều phải gửi kèm **API Key** (do Admin cấp) theo **1 trong 3 cách**:

| Cách truyền | Ví dụ | Khuyên dùng |
| :--- | :--- | :--- |
| Header `X-API-Key` | `X-API-Key: mgm_live_xxxxxxxx...` | ✅ Khuyên dùng |
| Header `Authorization` | `Authorization: Bearer mgm_live_xxxxxxxx...` | ✅ Khuyên dùng |
| Query parameter | `?api_key=mgm_live_xxxxxxxx...` | Tiện test nhanh |

> Tất cả response đều trả về JSON (`Content-Type: application/json; charset=utf-8`).

---

## 2. Chuẩn Format Dữ Liệu Gmail Trả Về (6 cột)

Mỗi tài khoản Gmail được trả về đồng thời dưới 2 dạng:
1. **`items_raw`** — chuỗi ngăn cách bởi dấu `|`:
   ```text
   Email|Password|2FA|Mail Khôi Phục|Họ Tên / Ngày Sinh|Thời Gian Tạo
   ```
2. **`items`** — mảng JSON object đã tách sẵn từng trường:

| Cột | Trường JSON | Ý nghĩa |
| :---: | :--- | :--- |
| 1 | `email` | Địa chỉ Gmail |
| 2 | `password` | Mật khẩu đăng nhập |
| 3 | `two_fa` | Mã Secret 2FA (TOTP) |
| 4 | `recovery_email` | Email khôi phục |
| 5 | `full_name_dob` | Họ tên & ngày sinh (VD: `Morris Eleanor (1998-08-29)`) |
| 6 | `created_at` | Thời gian tạo tài khoản |

---

## 3. Danh sách Endpoints

### 3.1. Kiểm tra thông tin ví & chiết khấu đại lý
- **Method & Path:** `GET /api/v1/me`

**Response `200 OK`:**
```json
{
  "ok": true,
  "data": {
    "id": 1,
    "name": "Shop Partner A",
    "balance": 2500000,
    "discount_percent": 10,
    "total_spent": 1200000,
    "total_orders": 18,
    "is_active": true
  }
}
```

---

### 3.2. Lấy danh sách sản phẩm & tồn kho thực tế
- **Method & Path:** `GET /api/v1/products`
- Trả về giá gốc (`base_price`), giá sau chiết khấu đại lý (`unit_price`) và tồn kho thực tế (`available_stock`).

**Response `200 OK`:**
```json
{
  "ok": true,
  "discount_percent": 10,
  "format": "Email|Password|2FA|Mail Khôi Phục|Họ Tên / Ngày Sinh|Thời Gian Tạo",
  "data": [
    {
      "id": 1,
      "category_id": 1,
      "category_name": "Gmail New 2FA",
      "name": "Gmail New Full 2FA + Recovery",
      "description": "Gmail sạch, bảo hành login đầu",
      "base_price": 5000,
      "unit_price": 4500,
      "available_stock": 340,
      "format": "Email|Password|2FA|Mail Khôi Phục|Họ Tên / Ngày Sinh|Thời Gian Tạo"
    }
  ]
}
```

---

### 3.3. Mua hàng tự động (Trừ ví & Trả Gmail ngay lập tức)
- **Method & Path:** `POST /api/v1/orders`
- **Giới hạn:** `quantity` từ `1` đến `500` mỗi request.
- **Chống trừ trùng (Idempotency):** Nên truyền `client_order_id` duy nhất cho mỗi đơn bên shop của bạn. Nếu request bị timeout và bạn gửi lại cùng `client_order_id`, hệ thống sẽ trả về lại đơn cũ (`"idempotent_replay": true`) mà **không trừ tiền lần 2**.

**Request Body (`application/json`):**
```json
{
  "product_id": 1,
  "quantity": 2,
  "client_order_id": "SHOPA_20261126_001"
}
```

**Response `200 OK`:**
```json
{
  "ok": true,
  "idempotent_replay": false,
  "data": {
    "order_code": "SHOPDH8K2M9A",
    "client_order_id": "SHOPA_20261126_001",
    "product_id": 1,
    "product_name": "Gmail New Full 2FA + Recovery",
    "quantity": 2,
    "unit_price": 4500,
    "total_amount": 9000,
    "balance_after": 2491000,
    "format": "Email|Password|2FA|Mail Khôi Phục|Họ Tên / Ngày Sinh|Thời Gian Tạo",
    "items_raw": [
      "mail1@gmail.com|Pass123|2FASECRET1|rec1@gmail.com|Morris Eleanor (1998-08-29)|2026-11-25 00:15:44",
      "mail2@gmail.com|Pass456|2FASECRET2|rec2@gmail.com|John Smith (1999-04-12)|2026-11-25 00:16:10"
    ],
    "items": [
      {
        "email": "mail1@gmail.com",
        "password": "Pass123",
        "two_fa": "2FASECRET1",
        "recovery_email": "rec1@gmail.com",
        "full_name_dob": "Morris Eleanor (1998-08-29)",
        "created_at": "2026-11-25 00:15:44"
      }
    ],
    "created_at": "2026-11-26T02:15:00Z"
  }
}
```

---

### 3.4. Lấy danh sách lịch sử đơn hàng
- **Method & Path:** `GET /api/v1/orders?limit=50`

**Response `200 OK`:**
```json
{
  "ok": true,
  "data": [
    {
      "order_code": "SHOPDH8K2M9A",
      "client_order_id": "SHOPA_20261126_001",
      "product_id": 1,
      "product_name": "Gmail New Full 2FA + Recovery",
      "quantity": 2,
      "unit_price": 4500,
      "total_amount": 9000,
      "status": "DELIVERED",
      "created_at": "2026-11-26T02:15:00Z"
    }
  ]
}
```

---

### 3.5. Tra cứu chi tiết & lấy lại dữ liệu 1 đơn hàng đã mua
- **Method & Path:** `GET /api/v1/orders/{order_code}`
- Dùng để tải lại toàn bộ `items_raw` và `items` của đơn hàng bất cứ lúc nào.

**Response `200 OK`:**
```json
{
  "ok": true,
  "data": {
    "order_code": "SHOPDH8K2M9A",
    "client_order_id": "SHOPA_20261126_001",
    "product_id": 1,
    "product_name": "Gmail New Full 2FA + Recovery",
    "quantity": 2,
    "unit_price": 4500,
    "total_amount": 9000,
    "status": "DELIVERED",
    "format": "Email|Password|2FA|Mail Khôi Phục|Họ Tên / Ngày Sinh|Thời Gian Tạo",
    "items_raw": [
      "mail1@gmail.com|Pass123|2FASECRET1|rec1@gmail.com|Morris Eleanor (1998-08-29)|2026-11-25 00:15:44"
    ],
    "items": [
      {
        "email": "mail1@gmail.com",
        "password": "Pass123",
        "two_fa": "2FASECRET1",
        "recovery_email": "rec1@gmail.com",
        "full_name_dob": "Morris Eleanor (1998-08-29)",
        "created_at": "2026-11-25 00:15:44"
      }
    ],
    "created_at": "2026-11-26T02:15:00Z"
  }
}
```

---

### 3.6. Tạo lệnh nạp ví đại lý tự động qua VietQR
- **Method & Path:** `POST /api/v1/topup`
- **Hạn mức:** Tối thiểu `50,000` VNĐ — tối đa `100,000,000` VNĐ mỗi lệnh.
- Chuyển đúng nội dung `transfer_content` (hoặc quét ảnh `qr_url`) → số dư ví đại lý **tự động cộng sau 2–10 giây**.

**Request Body:**
```json
{
  "amount": 500000
}
```

**Response `200 OK`:**
```json
{
  "ok": true,
  "data": {
    "topup_code": "SHOPRES7A9X2K",
    "amount": 500000,
    "bank_code": "TIMO",
    "bank_account_no": "9021189147066",
    "bank_account_name": "LUONG TRAN HUY PHUC",
    "transfer_content": "SHOPRES7A9X2K",
    "qr_url": "https://img.vietqr.io/image/TIMO-9021189147066-compact2.png?...",
    "expires_at": "2026-11-26T02:30:00Z"
  }
}
```

---

## 4. Bảng Mã Lỗi Chuẩn

Mọi lỗi đều có định dạng thống nhất:
```json
{
  "ok": false,
  "code": "OUT_OF_STOCK",
  "message": "Kho không đủ số lượng yêu cầu"
}
```

| HTTP | Code | Ý nghĩa |
| :---: | :--- | :--- |
| `400` | `INVALID_JSON` / `INVALID_PARAMS` / `TOPUP_FAILED` / `ORDER_FAILED` | Sai dữ liệu gửi lên hoặc vượt giới hạn số lượng / tiền nạp |
| `401` | `MISSING_API_KEY` / `INVALID_API_KEY` | Thiếu hoặc sai API Key |
| `402` | `INSUFFICIENT_BALANCE` | Số dư ví đại lý không đủ |
| `403` | `RESELLER_DISABLED` | Tài khoản đại lý đang bị tạm khóa |
| `404` | `PRODUCT_NOT_FOUND` / `ORDER_NOT_FOUND` | Không tìm thấy sản phẩm hoặc mã đơn hàng |
| `409` | `OUT_OF_STOCK` | Tồn kho không đủ số lượng yêu cầu |
| `500` | `INTERNAL_ERROR` | Lỗi hệ thống tạm thời |

---

## 5. Code Mẫu Tích Hợp Nhanh

### cURL
```bash
# 1. Kiểm tra số dư ví đại lý
curl -H "X-API-Key: YOUR_API_KEY" \
  https://miragemail.vorte.me/api/v1/me

# 2. Lấy danh sách sản phẩm & tồn kho
curl -H "X-API-Key: YOUR_API_KEY" \
  https://miragemail.vorte.me/api/v1/products

# 3. Mua 2 tài khoản sản phẩm ID = 1
curl -X POST https://miragemail.vorte.me/api/v1/orders \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"product_id": 1, "quantity": 2, "client_order_id": "ORD_001"}'
```

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

BASE_URL = "https://miragemail.vorte.me"
HEADERS = {"X-API-Key": "YOUR_API_KEY"}

# Lấy danh sách sản phẩm
products = requests.get(f"{BASE_URL}/api/v1/products", headers=HEADERS, timeout=15).json()
print(products)

# Mua hàng tự động
resp = requests.post(
    f"{BASE_URL}/api/v1/orders",
    headers=HEADERS,
    json={
        "product_id": 1,
        "quantity": 2,
        "client_order_id": f"ORD_{int(time.time())}",
    },
    timeout=15,
).json()

if resp.get("ok"):
    for line in resp["data"]["items_raw"]:
        print("RAW:", line)
    for acc in resp["data"]["items"]:
        print("PARSED:", acc["email"], acc["password"], acc["two_fa"], acc["recovery_email"])
else:
    print("ERROR:", resp.get("code"), resp.get("message"))
```

### Node.js (`fetch`)
```javascript
const BASE_URL = "https://miragemail.vorte.me";
const API_KEY = "YOUR_API_KEY";

const res = await fetch(`${BASE_URL}/api/v1/orders`, {
  method: "POST",
  headers: {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    product_id: 1,
    quantity: 2,
    client_order_id: "ORD_" + Date.now(),
  }),
});

const json = await res.json();
if (json.ok) {
  console.log("Order:", json.data.order_code);
  console.log("Raw lines:", json.data.items_raw);
  console.log("Objects:", json.data.items);
} else {
  console.error("Failed:", json.code, json.message);
}
```

### PHP (`cURL`)
```php
<?php
$baseUrl = "https://miragemail.vorte.me";
$apiKey  = "YOUR_API_KEY";

$ch = curl_init("$baseUrl/api/v1/orders");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_HTTPHEADER     => [
        "X-API-Key: $apiKey",
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "product_id"      => 1,
        "quantity"        => 2,
        "client_order_id" => "ORD_" . time(),
    ]),
]);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);

if (!empty($res["ok"])) {
    foreach ($res["data"]["items_raw"] as $line) {
        echo $line . PHP_EOL;
    }
} else {
    echo "Error: " . ($res["code"] ?? "UNKNOWN") . " - " . ($res["message"] ?? "") . PHP_EOL;
}
```
