# AI 完整妝容虛擬試妝

# 概述
AI 完整妝容虛擬試妝 API 提供完整的工作流程，將專業設計的臉部造型套用到使用者照片。每個造型都由美妝專家打造，可透過 API 即刻套用。
## 整合指南
本指南將引導您完成：
* **端點：**

`/s2s/v2.0/task/look-vto`
* **認證：**
 所有請求都需要
`Authorization: Bearer <TOKEN>`
* **工作流程：**
  1. **準備自拍：**
 上傳圖片，或提供有效的圖片網址
  2. **列出造型範本：**
 列出可用的 AI 完整妝容範本
  3. **啟動任務（`POST`）：**
 提交您的圖片 id/網址與造型
`template_id`
。
  4. **取得任務 ID：**
 從回應中取得
`task_id`
。
  5. **輪詢狀態（`GET`）：**
 使用
`task_id`
 查詢任務狀態。持續輪詢，直到
`task_status`
 為
`"success"`
 或
`"error"`
。



---

* API Playground

使用我們的官方 playground 進行互動式探索與測試：
**API Playground：**
[http://yce.makeupar.com/api-console/en/api-playground/ai-look-virtual-try-on/](http://yce.makeupar.com/api-console/en/api-playground/ai-look-virtual-try-on/)


---

* 認證

- 使用
**Bearer Token**
 將您的 API key 納入請求標頭：

```
Authorization: Bearer <API Key>
```

您可以在 https://yce.makeupar.com/api-console/en/api-keys/ 找到您的 API Key。
*   1. 上傳圖片

您可以直接上傳檔案到伺服器，或在 VTO 任務內容中提供有效的圖片網址。
* 上傳端點


```
POST /s2s/v2.0/file
```
或者，若您已有公開的圖片網址，可跳過此步驟。


---

*   1. 列出可用的造型風格

取得所有可用於虛擬試妝的 AI 彩妝造型範本。
* 端點


```
GET /s2s/v2.0/task/template/look-vto
```
* 查詢參數

| 參數 | 說明 |
|  --- | --- |
| `page_size` | 每頁的項目數量 |
| `starting_token` | 用於分頁的令牌（選填） |

* JavaScript 請求範例


```javascript
const data = null;

const xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener('readystatechange', function () {
    if (this.readyState === this.DONE) {
        console.log(this.responseText);
    }
});

xhr.open('GET', 'https://yce-api-01.makeupar.com/s2s/v2.0/task/template/look-vto?page_size=20&starting_token=73a3c9e69b89');
xhr.setRequestHeader('Authorization', 'Bearer <access_token for v1, API Key for v2>');

xhr.send(data);
```
* 成功回應範例


```json
{
  "status": 200,
  "data": {
    "templates": [
      {
        "id": "good_template_001",
        "thumb": "縮略圖預覽圖片網址",
        "title": "Berry Smooth",
        "category_name": "Daily"
      }
    ],
    "next_token": 73a3c9e69b89
  }
}
```
> **注意：** 在建立造型 VTO 任務時，使用 `id` 值（`template_id`）。



---

*   1. 建立造型 VTO 任務並輪詢結果

當您取得圖片與範本 ID 後，即可建立任務。API 以非同步方式處理請求。您必須輪詢任務狀態，直到達到 `success` 或 `error`。
* 建立任務端點


```
POST /s2s/v2.0/task/look-vto
```
* 輪詢端點


```
GET /s2s/v2.0/task/look-vto/{task_id}
```


---

* JavaScript 實作範例


```javascript
const BASE_URL = 'https://yce-api-01.makeupar.com/s2s/v2.0/task/look-vto';
const START_METHOD = 'POST';
const HEADERS = {
  "Content-Type": "application/json",
  "Authorization": "Bearer YOUR_API_KEY"
};

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function startTask() {
  const init = {
    method: START_METHOD,
    headers: HEADERS,
    body: JSON.stringify({
      "src_file_url": "https://plugins-media.makeupar.com/strapi/assets/sample_Image_7_fa28b2618a.jpg",
      "template_id": "all_rosy_chic"
    })
  };

  const res = await fetch(BASE_URL, init);
  if (!res.ok) throw new Error(`Start request failed: ${res.status} ${res.statusText}`);

  const payload = await res.json().catch(() => ({}));
  const taskId = payload?.data?.task_id;
  if (!taskId) throw new Error('task_id missing: ' + JSON.stringify(payload));

  console.log('[startTask] Task started, id =', taskId);
  return taskId;
}

async function pollTask(taskId, { intervalMs = 2000, maxAttempts = 300 } = {}) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const pollUrl = `${BASE_URL}/${taskId}`;
    const res = await fetch(pollUrl, { method: 'GET', headers: HEADERS });

    if (!res.ok) throw new Error(`Polling failed: ${res.status} ${res.statusText}`);

    const payload = await res.json().catch(() => ({}));
    const status = payload?.data?.task_status;
    console.log(`[pollTask] Attempt ${attempt} status = ${status}`);

    if (status === 'success') {
      console.log('[pollTask] Success results:', payload?.data?.results);
      return payload;
    }

    if (status === 'error') {
      throw new Error('Task failed: ' + JSON.stringify(payload));
    }

    await sleep(intervalMs);
  }

  throw new Error('Polling timeout: Max attempts exceeded');
}

(async () => {
  try {
    const taskId = await startTask();
    const final = await pollTask(taskId);
    console.log('[main] Final response:', final);
  } catch (e) {
    console.error('[main] Flow error:', e);
  }
})();
```


---

* 成功回應範例


```json
{
  "status": 200,
  "data": {
    "results": {
      "url": "https://yce-us.s3-accelerate.amazonaws.com/demo/.../result.jpg?..."
    },
    "task_status": "success"
  }
}
```
`results.url` 欄位包含最終渲染的虛擬彩妝影像。


---

* 摘要

| 步驟 | 說明 |
|  --- | --- |
| **1. 上傳圖片** | 直接上傳，或提供圖片網址。 |
| **2. 列出造型範本** | 取得可用的造型風格及其 ID。 |
| **3. 建立 VTO 任務** | 提交圖片網址 + 範本 ID。 |
| **4. 輪詢至完成** | 取得最終結果圖片網址。 |

這個工作流程確保可靠、開發者友善的整合，用於即時虛擬彩妝試色體驗。


---

## 檔案規格與錯誤
* 支援的格式與尺寸

| AI 功能 | 支援的尺寸 | 支援的檔案大小 | 支援的格式 |
|  --- | --- | --- | --- |
| AI 完整妝容虛擬試妝 | 長邊 < 1920，臉寬 >= 100 | < 10MB | jpg/jpeg/png |

* 錯誤代碼

| 錯誤代碼 | 說明 |
|  --- | --- |
| error_below_min_image_size | 來源圖片尺寸小於最小值（期望：寬 >= 100px，高 >= 100px） |
| error_exceed_max_image_size | 來源圖片尺寸大於最大值（期望：寬 < 1920px，高 < 1080px） |
| error_face_position_invalid | 請確保您的整張臉在圖片中完全可見 |
| error_face_position_too_small | 偵測到的臉部過小。請靠近鏡頭 |
| error_face_position_out_of_boundary | 臉部過大或部分在畫面之外。請調整您的位置 |
| error_face_angle_invalid | 臉部角度不正確。正面照片請將頭部保持在 10° 內。側面照片請確保超過 15°。 |

* 環境與相依性

| 範例程式語言 / 工具 | 建議的執行環境版本 |
|  --- | --- |
| cURL | - bash >= 3.2   - curl >= 7.58（現代 TLS/HTTP 支援）   - jq >= 1.6（穩健的 JSON 解析） |
| Node.js（JavaScript） | Node >= 18（支援全域 fetch） |
| JavaScript | - Chrome / Edge >= 80   - Firefox >= 74   - Safari >= 13.1 |
| PHP | PHP >= 7.4（現代 TLS/相容性），ext-curl（建議）或 allow_url_fopen=On + ext-openssl、ext-json |
| Python | Python >= 3.10（支援 f-strings），requests >= 2.20.0 |
| Java | Java 11+（支援 HttpClient），Jackson Databind >= 2.12.0 |



---

## 點數消耗
| AI 功能 | 消耗的點數 |
|  --- | --- |
| AI 完整妝容虛擬試妝 V1.0 | 2 |



---

License: Privacy policy

## Servers

```
https://yce-api-01.makeupar.com
```

## Security

### BearerAuthenticationV2

使用標準的 'Bearer authentication'。請在標頭中放入您的 'API Key'：`Authorization:Bearer YOUR_API_KEY`。請注意 'Bearer' 與 'YOUR_API_KEY' 之間有一個空格。

Type: http
Scheme: bearer

## Download OpenAPI description

 - [AI 完整妝容虛擬試妝](https://docs.perfectcorp.com/_bundle/@l10n/zh-TW/reference/ai_look_vto.yaml)

## V1.0

 - [GET /s2s/v2.0/task/template/look-vto](https://docs.perfectcorp.com/zh-tw/reference/ai_look_vto/v1.0/paths/~1s2s~1v2.0~1task~1template~1look-vto/get.md)
 - [POST /s2s/v2.0/task/look-vto](https://docs.perfectcorp.com/zh-tw/reference/ai_look_vto/v1.0/paths/~1s2s~1v2.0~1task~1look-vto/post.md): 這個端點使用範本與來源照片啟動完整妝容虛擬試妝流程。任務會以非同步方式處理，您可以使用這個回應回傳的 task_id 查詢其狀態。
 - [GET /s2s/v2.0/task/look-vto/{task_id}](https://docs.perfectcorp.com/zh-tw/reference/ai_look_vto/v1.0/paths/~1s2s~1v2.0~1task~1look-vto~1%7Btask_id%7D/get.md)
