# 🚀 TinoVPS.com - Tài Liệu Tích Hợp API Dịch Vụ Cloud VPS (API Agency & API Thường)

> **Hệ thống API Agency & Reseller chuẩn dành cho Đại lý & Đối tác kết nối tự động hóa dịch vụ Cloud VPS tốc độ cao**  
> **Phiên bản:** API Protocol v2.0  
> **Base Domain:** `https://tinovps.com`  
> **Định dạng dữ liệu:** `JSON (UTF-8)`  
> **Trang tài liệu trên Web:** [https://tinovps.com/docs/api/vps-gold](https://tinovps.com/docs/api/vps-gold)

---

## 📑 MỤC LỤC

- [1. Hướng Dẫn Xác Thực & Quy Tắc Chung (API Agency)](#-1-hướng-dẫn-xác-thực--quy-tắc-chung-api-agency)
  - [1.1. Giới thiệu mô hình API Agency](#11-giới-thiệu-mô-hình-api-agency)
  - [1.2. Bộ thông tin xác thực](#12-bộ-thông-tin-xác-thực)
  - [1.3. Quy trình xác thực 2 bước (Two-Step Agency Flow)](#13-quy-trình-xác-thực-2-bước-two-step-agency-flow)
  - [1.4. Quy chuẩn HTTP Headers bắt buộc](#14-quy-chuẩn-http-headers-bắt-buộc)
  - [1.5. Cấu trúc Response quy chuẩn](#15-cấu-trúc-response-quy-chuẩn)
- [2. Chi Tiết Các Endpoints API Agency (`/api/agency/*`)](#-2-chi-tiết-các-endpoints-api-agency-apiagency)
  - [2.1. Lấy Auth Token (`POST /api/agency/get-token`)](#-21-lấy-auth-token-post-apiagencyget-token)
  - [2.2. Thông tin tài khoản đại lý & Số dư (`GET /api/agency/get-info`)](#-22-thông-tin-tài-khoản-đại-lý--số-dư-get-apiagencyget-info)
  - [2.3. Danh sách gói Cloud VPS & Bảng giá (`GET /api/agency/get-product`)](#-23-danh-sách-gói-cloud-vps--bảng-giá-get-apiagencyget-product)
  - [2.4. Danh sách Hệ điều hành (`GET /api/agency/get-list-os`)](#-24-danh-sách-hệ-điều-hành-get-apiagencyget-list-os)
  - [2.5. Danh sách Chu kỳ thanh toán (`GET /api/agency/get-list-billing-cycle`)](#-25-danh-sách-chu-kỳ-thanh-toán-get-apiagencyget-list-billing-cycle)
  - [2.6. Tạo đơn hàng đặt mua Cloud VPS (`POST /api/agency/order/create-order`)](#-26-tạo-đơn-hàng-đặt-mua-cloud-vps-post-apiagencyordercreate-order)
  - [2.7. Thao tác & Điều khiển VPS (`POST /api/agency/vps/action-vps`)](#-27-thao-tác--điều-khiển-vps-post-apiagencyvpsaction-vps)
    - [2.7.1. Bật nguồn VPS (`action: on`)](#271-bật-nguồn-vps-action-on)
    - [2.7.2. Tắt nguồn VPS (`action: off`)](#272-tắt-nguồn-vps-action-off)
    - [2.7.3. Khởi động lại VPS (`action: restart`)](#273-khởi-động-lại-vps-action-restart)
    - [2.7.4. Cài lại Hệ điều hành (`action: rebuild` hoặc `reinstall`)](#274-cài-lại-hệ-điều-hành-action-rebuild-hoặc-reinstall)
    - [2.7.5. Gia hạn Cloud VPS (`action: renew-vps`)](#275-gia-hạn-cloud-vps-action-renew-vps)
    - [2.7.6. Nâng cấp cấu hình CPU / RAM / Disk (`action: addon-vps`)](#276-nâng-cấp-cấu-hình-cpu--ram--disk-action-addon-vps)
    - [2.7.7. Hủy & Hoàn tiền VPS 80% (`action: cancel`)](#277-hủy--hoàn-tiền-vps-80-action-cancel)
    - [2.7.8. Đổi Chip Intel Platinum (`action: platinum`)](#278-đổi-chip-intel-platinum-action-platinum)
    - [2.7.9. Bật / Tắt Ảo hóa VT (`action: enable-vt` / `disable-vt`)](#279-bật--tắt-ảo-hóa-vt-action-enable-vt--disable-vt)
    - [2.7.10. Đồng bộ ổ cứng (`action: extend-disk`)](#2710-đồng-bộ-ổ-cứng-action-extend-disk)
    - [2.7.11. Đổi địa chỉ IP VPS (`action: change-ip`)](#2711-đổi-địa-chỉ-ip-vps-action-change-ip)
    - [2.7.12. Đổi mật khẩu quản trị VPS (`action: change-password`)](#2712-đổi-mật-khẩu-quản-trị-vps-action-change-password)
  - [2.8. Danh sách Cloud VPS đang sở hữu (`GET /api/agency/vps/get-list-vps`)](#-28-danh-sách-cloud-vps-đang-sở-hữu-get-apiagencyvpsget-list-vps)
  - [2.9. Chi tiết cấu hình & Trạng thái VPS (`GET /api/agency/vps/get-info-vps`)](#-29-chi-tiết-cấu-hình--trạng-thái-vps-get-apiagencyvpsget-info-vps)
  - [2.10. Xem lịch sử thao tác trên VPS (`GET /api/agency/vps/history-action-vps`)](#-210-xem-lịch-sử-thao-tác-trên-vps-get-apiagencyvpshistory-action-vps)
- [3. Tài Liệu API Thường (`/api/vps-gold/*` - Xác thực `key_app` & `token`)](#-3-tài-liệu-api-thường-apivps-gold---xác-thực-key_app--token)
- [4. Bảng Mã Lỗi & Hướng Dẫn Xử Lý](#-4-bảng-mã-lỗi--hướng-dẫn-xử-lý)
- [5. Code Mẫu Tích Hợp Hoàn Chỉnh (PHP, Python, Node.js)](#-5-code-mẫu-tích-hợp-hoàn-chỉnh-php-python-nodejs)
  - [5.1. PHP (Class SDK `TinoVpsAgency.php`)](#51-php-class-sdk-tinovpsagencyphp)
  - [5.2. Python 3 (Requests)](#52-python-3-requests)
  - [5.3. Node.js (Axios)](#53-nodejs-axios)
- [6. Prompt AI Thiết Kế Giao Diện Frontend & Tích Hợp Full API Cloud VPS](#-6-prompt-ai-thiết-kế-giao-diện-frontend--tích-hợp-full-api-cloud-vps)

---

## 🔐 1. Hướng Dẫn Xác Thực & Quy Tắc Chung (API Agency)

### 1.1. Giới thiệu mô hình API Agency
Hệ thống **API Agency** tại [tinovps.com](https://tinovps.com) cho phép các đối tác, đại lý bán lại (Reseller) và lập trình viên kết nối trực tiếp hệ thống của mình tới cụm máy chủ Cloud VPS NVMe để:
* Tự động đặt mua VPS ngay lập tức khi khách hàng của bạn thanh toán.
* Tự động quản lý toàn bộ vòng đời VPS: Khởi động, Tắt, Khởi động lại, Cài lại OS, Đổi mật khẩu, Đổi IP, Đồng bộ Disk, Bật/Tắt VT, Đổi chip Platinum, Hủy hoàn tiền 80% trong 24h đầu.
* Nâng cấp cấu hình (vCPU, RAM, SSD NVMe) tự động khấu trừ theo đúng số ngày sử dụng còn lại và gia hạn gói tự động.
* Đồng bộ số dư tài khoản đại lý theo thời gian thực.

### 1.2. Bộ thông tin xác thực
Để sử dụng API, bạn đăng nhập vào tài khoản trên website [https://tinovps.com](https://tinovps.com), mở menu **Đại lý -> Tài liệu API** (`/docs/api/vps-gold`) và nhấn **Tạo API Key** để nhận bộ thông tin bảo mật:

| Thông tin | Mô tả | Định dạng ví dụ |
| :--- | :--- | :--- |
| `api-username` | Tên tài khoản định danh API Agency của bạn | `user_e5be8e_7b89f2a1c4d2` |
| `api-app` (`key_app`) | Khóa ứng dụng (Key App dùng chung cho cả API Agency & API Thường) | `vps_9d28e71c03af84b2...` |
| `api-secret` | Mã khóa bí mật dành cho API Agency | `sec_4f910a28b6...` |
| `token` (`auth-token`) | Token xác thực (dùng cho cả API Thường và header `auth-token` của API Agency) | `8a19c20f3b7d...` |

> [!CAUTION]
> Tuyệt đối không để lộ `api-secret` hoặc `token` ra phía giao diện người dùng (Frontend JavaScript/HTML). Mọi yêu cầu gọi API phải được thực hiện từ phía máy chủ của bạn (Backend Server-to-Server).

---

### 1.3. Quy trình xác thực 2 bước (Two-Step Agency Flow)
Chuẩn Agency hoạt động theo mô hình bắt tay 2 bước (tương thích 100% chuẩn API Agency TinoVPS):

```mermaid
sequenceDiagram
    participant Client as Hệ thống Đại lý (Của bạn)
    participant API as TinoVPS.com API

    Note over Client,API: Bước 1: Lấy Auth Token
    Client->>API: POST /api/agency/get-token (api-username, api-app, api-secret)
    API-->>Client: Trả về {"error": 0, "auth-token": "..."}

    Note over Client,API: Bước 2: Gọi các API Dịch vụ
    Client->>API: GET/POST /api/agency/... (Kèm 4 HTTP Headers xác thực)
    API-->>Client: Trả về dữ liệu JSON (Gói cước, Mua VPS, Điều khiển...)
```

1. **Bước 1:** Gửi `api-username`, `api-app`, `api-secret` vào endpoint `POST /api/agency/get-token` để lấy chuỗi khóa `auth-token`.
2. **Bước 2:** Đính kèm đầy đủ **4 HTTP Headers** (`api-username`, `api-app`, `api-secret`, và `auth-token`) vào mọi request tiếp theo.

> [!TIP]
> Mã `auth-token` nhận được từ `/api/agency/get-token` chỉ thay đổi khi bạn bấm nút **Reset Token** trên web. Vì vậy bạn có thể lưu cache `auth-token` này ở Backend để tăng tốc độ phản hồi mà không cần gọi `get-token` trước mỗi request!

---

### 1.4. Quy chuẩn HTTP Headers bắt buộc
Tất cả các Endpoint trong nhóm `/api/agency/*` (ngoại trừ `/get-token`) đều **BẮT BUỘC** truyền các HTTP Headers sau:

```http
Content-Type: application/json
api-username: {api_username_cua_ban}
api-app: {key_app_cua_ban}
api-secret: {api_secret_cua_ban}
auth-token: {auth_token_nhan_duoc_tu_get_token}
```
*(Hệ thống chấp nhận cả header `auth-token` và alias `token`).*

---

### 1.5. Cấu trúc Response quy chuẩn
Mọi phản hồi từ API Agency đều trả về định dạng JSON (`application/json; charset=utf-8`):

* **Khi thành công (`error = 0`):**
```json
{
  "error": 0,
  "message": "Mô tả trạng thái thành công",
  "data": { ... }
}
```

* **Khi thất bại (`error = 1`):**
```json
{
  "error": 1,
  "message": "Chi tiết nguyên nhân lỗi"
}
```

---

## 📡 2. Chi Tiết Các Endpoints API Agency (`/api/agency/*`)

---

### 🔑 2.1. Lấy Auth Token (`POST /api/agency/get-token`)
Dùng bộ 3 thông tin API Key để lấy `auth-token` phục vụ cho các request tiếp theo.

- **URL:** `https://tinovps.com/api/agency/get-token`
- **Method:** `POST`
- **Content-Type:** `application/json` hoặc `application/x-www-form-urlencoded`

#### Tham số Body:
| Tên tham số | Kiểu | Bắt buộc | Mô tả |
| :--- | :--- | :---: | :--- |
| `api-username` | `string` | Có | API Username của bạn |
| `api-app` | `string` | Có | Key App của bạn |
| `api-secret` | `string` | Có | API Secret của bạn |

#### Ví dụ cURL:
```bash
curl -X POST "https://tinovps.com/api/agency/get-token" \
  -H "Content-Type: application/json" \
  -d '{
    "api-username": "YOUR_API_USERNAME",
    "api-app": "YOUR_KEY_APP",
    "api-secret": "YOUR_API_SECRET"
  }'
```

#### Response thành công:
```json
{
  "error": 0,
  "auth-token": "620b0cd9a18e4f7b230198cfe71a2d904b817c3ef1902a45",
  "token": "620b0cd9a18e4f7b230198cfe71a2d904b817c3ef1902a45"
}
```

---

### 👤 2.2. Thông tin tài khoản đại lý & Số dư (`GET /api/agency/get-info`)
Kiểm tra thông tin tài khoản đại lý, tổng dịch vụ, tổng chi tiêu và số dư khả dụng hiện tại (`credit` tính bằng VNĐ).

- **URL:** `https://tinovps.com/api/agency/get-info`
- **Method:** `GET`
- **Headers:** Đầy đủ 4 Headers xác thực

#### Ví dụ cURL:
```bash
curl -X GET "https://tinovps.com/api/agency/get-info" \
  -H "api-username: YOUR_API_USERNAME" \
  -H "api-app: YOUR_KEY_APP" \
  -H "api-secret: YOUR_API_SECRET" \
  -H "auth-token: YOUR_AUTH_TOKEN"
```

#### Response mẫu:
```json
{
  "error": 0,
  "message": "Lấy thông tin chi tiết đại lý thành công",
  "data": {
    "agency_name": "khanhbt7196",
    "email": "khanhbt7196@gmail.com",
    "total_service": 3,
    "credit": 1000000,
    "total_expenses": 450000,
    "total_credit": 1450000,
    "service": {
      "vps": {
        "on": 2,
        "expire": 0,
        "total": 3
      }
    }
  }
}
```

---

### 📦 2.3. Danh sách gói Cloud VPS & Bảng giá (`GET /api/agency/get-product`)
Trả về toàn bộ danh sách các gói Cloud VPS đang mở bán kèm cấu hình phần cứng (CPU, RAM, SSD, Băng thông), danh sách OS hỗ trợ và bảng giá nâng cấp lẻ Addon (`addon_vps`).

- **URL:** `https://tinovps.com/api/agency/get-product`
- **Method:** `GET`
- **Headers:** Đầy đủ 4 Headers xác thực

#### Ví dụ cURL:
```bash
curl -X GET "https://tinovps.com/api/agency/get-product" \
  -H "api-username: YOUR_API_USERNAME" \
  -H "api-app: YOUR_KEY_APP" \
  -H "api-secret: YOUR_API_SECRET" \
  -H "auth-token: YOUR_AUTH_TOKEN"
```

#### Response mẫu:
```json
{
  "error": 0,
  "products": {
    "vps": [
      {
        "group_product_name": "Cloud Server",
        "product": [
          {
            "product_id": 36,
            "name": "CS 1-1-20",
            "cpu": 1,
            "ram": 1,
            "disk": 20,
            "ip": 1,
            "bandwidth": "Unlimited",
            "pricing": {
              "monthly": { "billing_cycle": "1 Tháng", "amount": 90000 },
              "quarterly": { "billing_cycle": "3 Tháng", "amount": 270000 },
              "semi_annually": { "billing_cycle": "6 Tháng", "amount": 540000 },
              "annually": { "billing_cycle": "12 Tháng", "amount": 1080000 }
            }
          }
        ],
        "limit-os": [
          { "os-id": 1, "os-name": "Windows Server 2022" },
          { "os-id": 5, "os-name": "Ubuntu 22.04 LTS" }
        ]
      }
    ],
    "addon_vps": [
      {
        "group_product_name": "Addon Cloud Server",
        "product": [
          { "product_id": 1, "name": "Addon CPU", "type_addon": "addon_cpu", "pricing": { "monthly": { "billing_cycle": "1 Tháng", "amount": 20000 } } },
          { "product_id": 2, "name": "Addon Ram", "type_addon": "addon_ram", "pricing": { "monthly": { "billing_cycle": "1 Tháng", "amount": 20000 } } },
          { "product_id": 5, "name": "Addon DISK", "type_addon": "addon_disk", "pricing": { "monthly": { "billing_cycle": "1 Tháng", "amount": 10000 } } }
        ]
      }
    ]
  }
}
```

---

### 💿 2.4. Danh sách Hệ điều hành (`GET /api/agency/get-list-os`)
Lấy danh sách các Hệ điều hành kèm mã `os-id` để truyền vào khi tạo đơn mua hoặc cài lại VPS.

- **URL:** `https://tinovps.com/api/agency/get-list-os`
- **Method:** `GET`
- **Headers:** Đầy đủ 4 Headers xác thực

#### Response mẫu:
```json
{
  "error": 0,
  "os-vps": [
    { "os-id": 1, "os-name": "Windows Server 2022" },
    { "os-id": 2, "os-name": "Windows Server 2019" },
    { "os-id": 5, "os-name": "Ubuntu 22.04 LTS" },
    { "os-id": 7, "os-name": "AlmaLinux 9" }
  ]
}
```

---

### 🗓️ 2.5. Danh sách Chu kỳ thanh toán (`GET /api/agency/get-list-billing-cycle`)
Lấy danh sách mã chu kỳ thanh toán hợp lệ của hệ thống.

- **URL:** `https://tinovps.com/api/agency/get-list-billing-cycle`
- **Method:** `GET`
- **Headers:** Đầy đủ 4 Headers xác thực

#### Response mẫu:
```json
{
  "error": 0,
  "data": [
    { "cycle": "monthly", "name": "1 Tháng" },
    { "cycle": "twomonthly", "name": "2 Tháng" },
    { "cycle": "quarterly", "name": "3 Tháng" },
    { "cycle": "semi_annually", "name": "6 Tháng" },
    { "cycle": "annually", "name": "12 Tháng" }
  ]
}
```

---

### 🛒 2.6. Tạo đơn hàng đặt mua Cloud VPS (`POST /api/agency/order/create-order`)
Khởi tạo máy chủ Cloud VPS mới tự động. Hệ thống tự động kiểm tra số dư ví, trừ tiền và hoàn tiền tự động nếu quá trình cấp phát gặp sự cố.

- **URL:** `https://tinovps.com/api/agency/order/create-order`
- **Method:** `POST`
- **Headers:** Đầy đủ 4 Headers xác thực + `Content-Type: application/json`

#### Tham số Body:
| Tên tham số | Kiểu | Bắt buộc | Mặc định | Mô tả |
| :--- | :--- | :---: | :---: | :--- |
| `product-id` | `int / string` | **Có** | - | Mã `product_id` (ví dụ `36`) lấy từ `/get-product` |
| `billing-cycle` | `string` | **Có** | `monthly` | Chu kỳ thuê (`monthly`, `twomonthly`, `quarterly`, `semi_annually`, `annually`) |
| `os` | `int` | Không | OS đầu tiên | Mã `os-id` lấy từ `/get-list-os` |
| `addon-cpu` | `int` | Không | `0` | Số core CPU mua thêm |
| `addon-ram` | `int` | Không | `0` | Số GB RAM mua thêm |
| `addon-disk` | `int` | Không | `0` | Dung lượng SSD mua thêm (bội số `10`, ví dụ `10`, `20` GB) |

#### Ví dụ cURL:
```bash
curl -X POST "https://tinovps.com/api/agency/order/create-order" \
  -H "Content-Type: application/json" \
  -H "api-username: YOUR_API_USERNAME" \
  -H "api-app: YOUR_KEY_APP" \
  -H "api-secret: YOUR_API_SECRET" \
  -H "auth-token: YOUR_AUTH_TOKEN" \
  -d '{
    "product-id": 36,
    "billing-cycle": "monthly",
    "os": 1,
    "addon-cpu": 0,
    "addon-ram": 0,
    "addon-disk": 0
  }'
```

#### Response thành công:
```json
{
  "error": 0,
  "message": "Đặt hàng thành công",
  "credit": 910000,
  "total": 90000,
  "data": [
    {
      "vps-id": 7501,
      "ip": "103.x.x.x",
      "username": "Administrator",
      "password": "StrongPassword123",
      "vps-status": "progressing"
    }
  ],
  "local_order_id": "8e1920c4-45a1-4b92-8810-12a34b56c789",
  "order_code": "VPS-261116-AB12CD"
}
```

---

### ⚙️ 2.7. Thao tác & Điều khiển VPS (`POST /api/agency/vps/action-vps`)
Endpoint trung tâm xử lý toàn bộ 12 hành động điều khiển vòng đời, nâng cấp, gia hạn và bảo trì VPS.

- **URL:** `https://tinovps.com/api/agency/vps/action-vps`
- **Method:** `POST`
- **Headers:** Đầy đủ 4 Headers xác thực + `Content-Type: application/json`
- **Tham số định danh VPS:** Truyền `vps-id` (chấp nhận cả mã số nguyên `vps-id`, `order_code` hoặc `local_order_id`).

#### 2.7.1. Bật nguồn VPS (`action: on` / `start`)
```json
{ "vps-id": 7501, "action": "on" }
```

#### 2.7.2. Tắt nguồn VPS (`action: off` / `stop`)
```json
{ "vps-id": 7501, "action": "off" }
```

#### 2.7.3. Khởi động lại VPS (`action: restart`)
```json
{ "vps-id": 7501, "action": "restart" }
```

#### 2.7.4. Cài lại Hệ điều hành (`action: rebuild` hoặc `reinstall`)
```json
{ "vps-id": 7501, "action": "rebuild", "os": 5 }
```

#### 2.7.5. Gia hạn Cloud VPS (`action: renew-vps`)
```json
{ "vps-id": 7501, "action": "renew-vps" }
```

#### 2.7.6. Nâng cấp cấu hình CPU / RAM / Disk (`action: addon-vps`)
Tiền nâng cấp được tự động tính theo đúng số ngày sử dụng còn lại của VPS.
```json
{
  "vps-id": 7501,
  "action": "addon-vps",
  "addon-cpu": 1,
  "addon-ram": 2,
  "addon-disk": 1
}
```

#### 2.7.7. Hủy & Hoàn tiền VPS 80% (`action: cancel`)
Áp dụng cho VPS đăng ký trong vòng **24 giờ đầu tiên**, tự động thu hồi VM và hoàn 80% giá trị vào ví đại lý.
```json
{ "vps-id": 7501, "action": "cancel" }
```

#### 2.7.8. Đổi Chip Intel Platinum (`action: platinum`)
```json
{ "vps-id": 7501, "action": "platinum" }
```

#### 2.7.9. Bật / Tắt Ảo hóa VT (`action: enable-vt` / `disable-vt`)
```json
{ "vps-id": 7501, "action": "enable-vt" }
```

#### 2.7.10. Đồng bộ ổ cứng sau nâng cấp (`action: extend-disk`)
```json
{ "vps-id": 7501, "action": "extend-disk", "password": "YourPassword123" }
```

#### 2.7.11. Đổi địa chỉ IP VPS (`action: change-ip`)
```json
{ "vps-id": 7501, "action": "change-ip", "password": "YourPassword123" }
```

#### 2.7.12. Đổi mật khẩu quản trị VPS (`action: change-password`)
```json
{ "vps-id": 7501, "action": "change-password", "password": "NewStrongPassword@2026" }
```

---

### 📋 2.8. Danh sách Cloud VPS đang sở hữu (`GET /api/agency/vps/get-list-vps`)
Lấy danh sách tất cả các máy chủ VPS thuộc sở hữu của đại lý.

- **URL:** `https://tinovps.com/api/agency/vps/get-list-vps`
- **Method:** `GET`
- **Query Params (tuỳ chọn):** `type` (`all` | `dang-su-dung` | `het-han`)

#### Response mẫu:
```json
{
  "error": 0,
  "message": "Lấy danh sách VPS thành công",
  "list-service": [
    {
      "vps-id": 7501,
      "order_id": "8e1920c4-45a1-4b92-8810-12a34b56c789",
      "ip": "103.x.x.x",
      "cpu": 2,
      "ram": 2,
      "disk": 30,
      "text-config": "2 CPU - 2 RAM - 30 Disk",
      "date_create": "2026-11-16",
      "next_due_date": "2026-12-16",
      "billing-cycle": "1 Tháng",
      "day-left": "Còn hạn 30 ngày",
      "vps-status": "on",
      "amount": 90000,
      "username": "Administrator",
      "password": "StrongPassword123",
      "auto-renew": 0,
      "type-vps": "VPS"
    }
  ]
}
```

---

### 🔍 2.9. Chi tiết cấu hình & Trạng thái VPS (`GET /api/agency/vps/get-info-vps`)
Đồng bộ trực tiếp trạng thái thực tế từ cụm Hypervisor và trả về chi tiết cấu hình, IP, tài khoản, mật khẩu, hạn dùng của VPS.

- **URL:** `https://tinovps.com/api/agency/vps/get-info-vps?vps-id=7501`
- **Method:** `GET`
- **Tham số:** `vps-id` (Query hoặc JSON body)

#### Response mẫu:
```json
{
  "error": 0,
  "message": "Yêu cầu đến VPS thành công",
  "data": [
    {
      "vps-id": 7501,
      "order_id": "8e1920c4-45a1-4b92-8810-12a34b56c789",
      "ip": "103.x.x.x",
      "cpu": 2,
      "ram": 2,
      "disk": 30,
      "text-config": "2 CPU - 2 RAM - 30 Disk",
      "day-left": "Còn hạn 30 ngày",
      "vps-status": "on",
      "username": "Administrator",
      "password": "StrongPassword123",
      "next_due_date": "2026-12-16",
      "billing-cycle": "1 Tháng"
    }
  ]
}
```

---

### 📜 2.10. Xem lịch sử thao tác trên VPS (`GET /api/agency/vps/history-action-vps`)
Lấy danh sách 50 nhật ký thao tác gần nhất trên một VPS cụ thể.

- **URL:** `https://tinovps.com/api/agency/vps/history-action-vps?vps-id=7501`
- **Method:** `GET`

#### Response mẫu:
```json
{
  "error": 0,
  "message": "Lấy lịch sử thao tác VPS thành công",
  "data": [
    {
      "id": "b1920c4a-1122-4334-9988-776655443322",
      "action": "RESTART: Đã gửi lệnh khởi động lại VPS",
      "created_at": "2026-11-16T03:45:00.000Z"
    }
  ]
}
```

---

## ⚡ 3. Tài Liệu API Thường (`/api/vps-gold/*` - Xác thực `key_app` & `token`)

Ngoài chuẩn API Agency 2 bước, hệ thống hỗ trợ song song bộ **API Thường (`/api/vps-gold/*`)** chỉ với 2 tham số `key_app` và `token` truyền qua Query String (`GET`) hoặc Form/JSON Body (`POST`). Phản hồi dùng chuẩn `{"status": "success" | "error", "msg": "...", "data": ...}`.

| STT | Method | Endpoint | Chức năng & Tham số chính |
| :---: | :---: | :--- | :--- |
| 1 | `GET` | `/api/vps-gold/services` | Lấy danh sách gói Cloud VPS & giá chu kỳ (`key_app`, `token`) |
| 2 | `GET` | `/api/vps-gold/os` | Lấy danh sách Hệ điều hành (`key_app`, `token`) |
| 3 | `GET` | `/api/vps-gold/addon` | Lấy bảng giá nâng cấp lẻ Addon CPU / RAM / Disk (`key_app`, `token`) |
| 4 | `GET` | `/api/vps-gold/history` | Lấy danh sách VPS đã mua, thêm `id` để xem chi tiết 1 VPS (`key_app`, `token`, `id`) |
| 5 | `POST` | `/api/vps-gold/buy` | Mua Cloud VPS mới (`key_app`, `token`, `vpsId`, `os`, `billingcycle`, `cpu`, `ram`, `disk`) |
| 6 | `POST` | `/api/vps-gold/action` | Action Controller tổng hợp (`key_app`, `token`, `param`, `action`: `1..13` hoặc alias `start`, `stop`, `restart`, `rebuild`, `renew`, `cancel`, `platinum`, `vt_on`, `vt_off`, `upgrade`, `extend_disk`, `change_ip`, `change_password`) |
| 7 | `POST` | `/api/vps-gold/cancel` | Hủy VPS & hoàn tiền 80% trong 24h đầu (`key_app`, `token`, `param`) |
| 8 | `POST` | `/api/vps-gold/platinum` | Đổi chip CPU sang Intel Platinum (`key_app`, `token`, `param`) |
| 9 | `POST` | `/api/vps-gold/vt` | Bật / Tắt ảo hóa phần cứng VT (`key_app`, `token`, `param`, `action`: `on` \| `off`) |
| 10 | `POST` | `/api/vps-gold/extend-disk` | Đồng bộ ổ cứng sau nâng cấp (`key_app`, `token`, `param`, `password`) |
| 11 | `POST` | `/api/vps-gold/change-ip` | Đổi địa chỉ IPv4 mới cho VPS (`key_app`, `token`, `param`, `password`) |

#### Ví dụ nhanh API Thường:
```bash
# 1. Lấy danh sách gói VPS
curl -X GET "https://tinovps.com/api/vps-gold/services?key_app=YOUR_KEY_APP&token=YOUR_TOKEN"

# 2. Mua VPS mới
curl -X POST "https://tinovps.com/api/vps-gold/buy" \
  -d "key_app=YOUR_KEY_APP" \
  -d "token=YOUR_TOKEN" \
  -d "vpsId=36" \
  -d "os=1" \
  -d "billingcycle=monthly"

# 3. Khởi động lại VPS
curl -X POST "https://tinovps.com/api/vps-gold/action" \
  -d "key_app=YOUR_KEY_APP" \
  -d "token=YOUR_TOKEN" \
  -d "param=7501" \
  -d "action=restart"
```

---

## ⚠️ 4. Bảng Mã Lỗi & Hướng Dẫn Xử Lý

| Thông báo lỗi (`message` / `msg`) | HTTP Code | Nguyên nhân & Cách khắc phục |
| :--- | :---: | :--- |
| `Missing required headers: api-username, api-app, api-secret, auth-token` | `401` | Bạn chưa đính kèm đủ 4 headers bắt buộc khi gọi `/api/agency/*`. |
| `Invalid credentials` | `401` | Sai `api-username`, `api-app`, `api-secret` hoặc `auth-token` (có thể do vừa bấm Reset Token). Gọi lại `/api/agency/get-token`. |
| `Sản phẩm không tồn tại` | `200` | `product-id` không tồn tại hoặc gói đã tạm ngưng. Lấy lại danh sách mới từ `/api/agency/get-product`. |
| `Số dư không đủ...` | `200` | Số dư ví đại lý không đủ thanh toán đơn hàng hoặc gia hạn. Vui lòng nạp thêm tiền tại `/funds`. |
| `Không tìm thấy thông tin VPS hoặc VPS không thuộc quyền sở hữu` | `200` | Sai `vps-id` hoặc máy chủ không thuộc tài khoản API hiện tại. |
| `Chỉ hỗ trợ hủy và hoàn tiền tự động trong vòng 24 giờ...` | `200` | Lệnh `cancel` chỉ áp dụng cho VPS mới tạo dưới 24 giờ. |

---

## 💻 5. Code Mẫu Tích Hợp Hoàn Chỉnh (PHP, Python, Node.js)

### 5.1. PHP (Class SDK `TinoVpsAgency.php`)

```php
<?php
/**
 * TinoVPS.com Agency API Client
 * Tích hợp kết nối API Cloud VPS chuẩn Agency
 */
class TinoVpsAgency {
    private string $baseUrl = 'https://tinovps.com';
    private string $apiUsername;
    private string $apiApp;
    private string $apiSecret;
    private ?string $authToken = null;

    public function __construct(string $username, string $appKey, string $secretKey, ?string $baseUrl = null) {
        $this->apiUsername = $username;
        $this->apiApp      = $appKey;
        $this->apiSecret   = $secretKey;
        if ($baseUrl) {
            $this->baseUrl = rtrim($baseUrl, '/');
        }
    }

    public function authenticate(): bool {
        $res = $this->request('POST', $this->baseUrl . '/api/agency/get-token', [
            'api-username' => $this->apiUsername,
            'api-app'      => $this->apiApp,
            'api-secret'   => $this->apiSecret,
        ], false);

        if (isset($res['error']) && $res['error'] === 0 && !empty($res['auth-token'])) {
            $this->authToken = $res['auth-token'];
            return true;
        }
        return false;
    }

    public function getAccountInfo(): array {
        return $this->request('GET', $this->baseUrl . '/api/agency/get-info');
    }

    public function getProducts(): array {
        return $this->request('GET', $this->baseUrl . '/api/agency/get-product');
    }

    public function getListOS(): array {
        return $this->request('GET', $this->baseUrl . '/api/agency/get-list-os');
    }

    public function createOrder(int|string $productId, string $cycle, int|string $osId, int $cpu = 0, int $ram = 0, int $disk = 0): array {
        return $this->request('POST', $this->baseUrl . '/api/agency/order/create-order', [
            'product-id'    => $productId,
            'billing-cycle' => $cycle,
            'os'            => $osId,
            'addon-cpu'     => $cpu,
            'addon-ram'     => $ram,
            'addon-disk'    => $disk,
        ]);
    }

    public function actionVps(int|string $vpsId, string $action, array $extraParams = []): array {
        return $this->request('POST', $this->baseUrl . '/api/agency/vps/action-vps', array_merge([
            'vps-id' => $vpsId,
            'action' => $action,
        ], $extraParams));
    }

    public function getListVps(string $type = 'all'): array {
        return $this->request('GET', $this->baseUrl . '/api/agency/vps/get-list-vps?' . http_build_query(['type' => $type]));
    }

    public function getInfoVps(int|string $vpsId): array {
        return $this->request('GET', $this->baseUrl . '/api/agency/vps/get-info-vps?vps-id=' . urlencode((string)$vpsId));
    }

    private function request(string $method, string $url, array $data = [], bool $withHeaders = true): array {
        if ($withHeaders && empty($this->authToken)) {
            if (!$this->authenticate()) {
                return ['error' => 1, 'message' => 'Xác thực tài khoản API thất bại'];
            }
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 45);

        $headers = ['Content-Type: application/json'];
        if ($withHeaders) {
            $headers[] = 'api-username: ' . $this->apiUsername;
            $headers[] = 'api-app: ' . $this->apiApp;
            $headers[] = 'api-secret: ' . $this->apiSecret;
            $headers[] = 'auth-token: ' . $this->authToken;
        }

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $result = json_decode((string)$response, true);
        return is_array($result) ? $result : ['error' => 1, 'message' => 'Lỗi kết nối HTTP ' . $httpCode];
    }
}

// Ví dụ sử dụng:
$api = new TinoVpsAgency('YOUR_API_USERNAME', 'YOUR_KEY_APP', 'YOUR_API_SECRET');
print_r($api->getAccountInfo());
```

---

### 5.2. Python 3 (Requests)

```python
import requests

class TinoVpsAgency:
    def __init__(self, username: str, app_key: str, secret_key: str, base_url: str = "https://tinovps.com"):
        self.base_url = base_url.rstrip("/")
        self.username = username
        self.app_key = app_key
        self.secret_key = secret_key
        self.auth_token = None

    def get_token(self) -> bool:
        res = requests.post(f"{self.base_url}/api/agency/get-token", json={
            "api-username": self.username,
            "api-app": self.app_key,
            "api-secret": self.secret_key,
        }, timeout=30).json()
        if res.get("error") == 0 and res.get("auth-token"):
            self.auth_token = res["auth-token"]
            return True
        return False

    def _headers(self) -> dict:
        if not self.auth_token:
            self.get_token()
        return {
            "api-username": self.username,
            "api-app": self.app_key,
            "api-secret": self.secret_key,
            "auth-token": self.auth_token,
            "Content-Type": "application/json",
        }

    def get_account_info(self) -> dict:
        return requests.get(f"{self.base_url}/api/agency/get-info", headers=self._headers(), timeout=30).json()

    def get_products(self) -> dict:
        return requests.get(f"{self.base_url}/api/agency/get-product", headers=self._headers(), timeout=30).json()

    def create_order(self, product_id, cycle: str = "monthly", os_id=1) -> dict:
        return requests.post(
            f"{self.base_url}/api/agency/order/create-order",
            json={"product-id": product_id, "billing-cycle": cycle, "os": os_id},
            headers=self._headers(),
            timeout=45,
        ).json()

    def action_vps(self, vps_id, action: str, extra: dict | None = None) -> dict:
        payload = {"vps-id": vps_id, "action": action}
        if extra:
            payload.update(extra)
        return requests.post(
            f"{self.base_url}/api/agency/vps/action-vps",
            json=payload,
            headers=self._headers(),
            timeout=45,
        ).json()
```

---

### 5.3. Node.js (Axios)

```javascript
const axios = require("axios");

class TinoVpsAgency {
  constructor(username, appKey, secretKey, baseUrl = "https://tinovps.com") {
    this.baseUrl = baseUrl.replace(/\/+$/, "");
    this.username = username;
    this.appKey = appKey;
    this.secretKey = secretKey;
    this.authToken = null;
  }

  async authenticate() {
    const { data } = await axios.post(`${this.baseUrl}/api/agency/get-token`, {
      "api-username": this.username,
      "api-app": this.appKey,
      "api-secret": this.secretKey,
    });
    if (data?.error === 0 && data?.["auth-token"]) {
      this.authToken = data["auth-token"];
      return true;
    }
    return false;
  }

  async getHeaders() {
    if (!this.authToken) await this.authenticate();
    return {
      "api-username": this.username,
      "api-app": this.appKey,
      "api-secret": this.secretKey,
      "auth-token": this.authToken,
      "Content-Type": "application/json",
    };
  }

  async getAccountInfo() {
    const headers = await this.getHeaders();
    const { data } = await axios.get(`${this.baseUrl}/api/agency/get-info`, { headers });
    return data;
  }

  async getProducts() {
    const headers = await this.getHeaders();
    const { data } = await axios.get(`${this.baseUrl}/api/agency/get-product`, { headers });
    return data;
  }

  async createOrder(productId, cycle = "monthly", osId = 1) {
    const headers = await this.getHeaders();
    const { data } = await axios.post(
      `${this.baseUrl}/api/agency/order/create-order`,
      { "product-id": productId, "billing-cycle": cycle, os: osId },
      { headers }
    );
    return data;
  }

  async actionVps(vpsId, action, extra = {}) {
    const headers = await this.getHeaders();
    const { data } = await axios.post(
      `${this.baseUrl}/api/agency/vps/action-vps`,
      { "vps-id": vpsId, action, ...extra },
      { headers }
    );
    return data;
  }
}

module.exports = TinoVpsAgency;
```

---

## 🤖 6. Prompt AI Thiết Kế Giao Diện Frontend & Tích Hợp Full API Cloud VPS

> **Dành cho Đại lý, Reseller & Lập trình viên sử dụng AI (Cursor, Claude, ChatGPT, Antigravity, v0, Bolt, Lovable...):**  
> Đính kèm file `tinovps.com.md` này vào khung chat AI và sao chép nguyên văn khối **Master Prompt** bên dưới để AI dựng tự động trọn bộ 4 trang giao diện Cloud VPS và đấu nối toàn bộ API.

```markdown
Bạn là Senior Full-Stack & UI/UX Engineer. Dựa trên tài liệu tích hợp API trong file `tinovps.com.md` (Base URL: `https://tinovps.com`), hãy xây dựng trọn bộ 4 trang giao diện Frontend dịch vụ Cloud VPS kèm Backend proxy bảo mật đấu nối đầy đủ API Agency (`/api/agency/*`):

1. TRANG 1 - BẢNG GIÁ CLOUD VPS (`/cloudvps` hoặc `/services/vps`):
   - Lấy danh sách gói và giá chu kỳ từ `GET /api/agency/get-product`.
   - Hiển thị lưới gói cước hiện đại hỗ trợ Light/Dark mode: Tên gói, giá chu kỳ tháng, thông số CPU Core, RAM GB, SSD NVMe GB, 1 IPv4 riêng, Băng thông Unlimited, OS Windows/Linux và nút "Đăng ký ngay".

2. TRANG 2 - CẤU HÌNH & ĐẶT HÀNG VPS (`/cloudvps/{id}`):
   - Layout 2 cột (Cột trái cấu hình + Cột phải Sticky Tóm tắt hóa đơn).
   - Chọn Chu kỳ thanh toán (`/api/agency/get-list-billing-cycle`), Hệ điều hành (`/api/agency/get-list-os` kèm icon OS trực quan), và bộ đếm +/- mua thêm Addon CPU, RAM, SSD NVMe.
   - Tính tổng tiền realtime và gửi lệnh đặt mua qua `POST /api/agency/order/create-order`.

3. TRANG 3 - QUẢN LÝ DANH SÁCH CLOUD VPS (`/services/vps`):
   - Đồng bộ danh sách từ `GET /api/agency/vps/get-list-vps` (hỗ trợ tìm kiếm theo IP, lọc trạng thái Running/Stopped/Expired/Installing, chuyển chế độ Bảng & Lưới).
   - Hiển thị: Mã gói, IP (nút copy 1 chạm), OS, Cấu hình, Chu kỳ, Ngày hết hạn, Huy hiệu trạng thái và nút vào Bảng điều khiển.

4. TRANG 4 - BẢNG ĐIỀU KHIỂN CHI TIẾT VPS (`/services/vps/{id}`):
   - Đồng bộ chi tiết từ `GET /api/agency/vps/get-info-vps` và nhật ký từ `GET /api/agency/vps/history-action-vps`.
   - Cột trái: Thẻ Thông tin đăng nhập VPS (IP + copy + refresh, Port SSH 22 / RDP 3389, User, Root Password ẩn/hiện + copy) và Thẻ Đơn hàng & Chu kỳ.
   - Cột phải: Bảng điều khiển đầy đủ các thao tác gửi qua `POST /api/agency/vps/action-vps` (`on`, `off`, `restart`, `rebuild`, `change-password`, `change-ip`, `addon-vps` tính tiền theo ngày còn lại, `extend-disk`, `renew-vps`, `enable-vt`/`disable-vt`, `platinum`, `cancel` hoàn 80% trong 24h đầu) kèm hộp thoại xác nhận rõ ràng.

Yêu cầu bảo mật bắt buộc: Tuyệt đối giữ `api-username`, `api-app`, `api-secret` ở biến môi trường phía Server Backend (`.env`), không bao giờ lộ khóa bí mật ra trình duyệt.
```

---

## 🛡️ 7. Tài Liệu Tích Hợp API Proxy (`/api/proxy/*`)

> **Hỗ trợ mua tự động Proxy Tĩnh Dân Cư (Viettel, FPT, VNPT), Proxy Xoay, Key Xoay API & Proxy Datacenter VN/US.**  
> **Trang tài liệu trên Web:** [https://tinovps.com/docs/api/proxy](https://tinovps.com/docs/api/proxy)  
> **Xác thực:** Truyền `X-Api-Token: YOUR_TOKEN` hoặc `Authorization: Bearer YOUR_TOKEN` (dùng chung Token lấy tại `/docs/api/vps-gold` hoặc `/docs/api/proxy`).

| STT | Method | Endpoint | Chức năng & Tham số |
| :---: | :---: | :--- | :--- |
| 1 | `GET` | `/api/proxy/profile` | Xem thông tin tài khoản đại lý & số dư ví |
| 2 | `GET` | `/api/proxy/packages` | Lấy danh sách toàn bộ gói Proxy & danh sách khu vực (`HCM`, `HNI`, `BDG`) |
| 3 | `POST` | `/api/proxy/buy` | Đặt mua Proxy mới (`package_id`, `days`, `quantity`, `protocol`: `HTTP` \| `SOCKS`, `location`: `RANDOM` \| `HCM` \| `HNI` \| `BDG`, `username`, `password` >= 9 ký tự, `rotate_interval`) |
| 4 | `GET` | `/api/proxy/orders` | Danh sách Proxy & Key Xoay đã mua (`?kind=...`, `?status=...`, `?search=...`) |
| 5 | `POST` | `/api/proxy/rotate` | Xoay IP tức thì cho Proxy Xoay / Key Xoay (`id`, `checkOnly`: `true` \| `false`) |
| 6 | `POST` | `/api/proxy/change-info` | Đổi mật khẩu (>= 9 ký tự), username hoặc chuyển đổi HTTP/SOCKS (`ids`, `username`, `password`, `protocol`, `rotate_interval`) |
| 7 | `POST` | `/api/proxy/renew` | Gia hạn Proxy tự động (`ids`, `days`) |
| 8 | `POST` | `/api/proxy/check` | Kiểm tra Proxy Live / Die & đo độ trễ Ping ms (`proxy`: `ip:port:user:pass`) |

---

## 📞 Hỗ Trợ Kỹ Thuật
- **Website:** [https://tinovps.com](https://tinovps.com)
- **Tài liệu API Cloud VPS:** [https://tinovps.com/docs/api/vps-gold](https://tinovps.com/docs/api/vps-gold)
- **Tài liệu API Proxy:** [https://tinovps.com/docs/api/proxy](https://tinovps.com/docs/api/proxy)
