# AI 妆容虚拟试妆

# 概览
AI 造型虚拟试穿接口提供一套完整流程，把美妆专家设计的整组脸部造型套到用户照片上。每套造型都由美妆专家打造，通过接口即可即时套用。
## 接入指南
本指南将带您走完全流程：
* **接口地址：**

`/s2s/v2.0/task/look-vto`
* **鉴权：**
 所有请求都需要
`Authorization: Bearer <TOKEN>`
* **流程：**
  1. **准备自拍照：**
 上传图片，或提供一个有效的图片 URL
  2. **列出造型模板：**
 取得可用的 AI 造型模板清单
  3. **发起任务（`POST`）：**
 提交您的图片 id/URL 与造型
`template_id`
。
  4. **取得 Task ID：**
 从响应中取回
`task_id`
。
  5. **轮询状态（`GET`）：**
 用
`task_id`
 查看任务状态，持续轮询直到
`task_status`
 为
`"success"`
 或
`"error"`
。



---

* API 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 密钥：

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

API Key 可在 https://yce.makeupar.com/api-console/en/api-keys/ 获取。
*   1. 上传图片

您可以把文件直接上传到服务器，也可以在 VTO 任务参数中提供有效的图片 URL。
* 上传接口


```
POST /s2s/v2.0/file
```
如果您已有公开可访问的图片 URL，这一步可以跳过。


---

*   1. 列出可用造型风格

取得所有可用于虚拟试穿的 AI 妆效造型模板。
* 接口地址


```
GET /s2s/v2.0/task/template/look-vto
```
* 查询参数

| 参数 | 说明 |
|  --- | --- |
| `page_size` | 每页笔数 |
| `starting_token` | 分页用的 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": "thumbnail preview image URL",
        "title": "Berry Smooth",
        "category_name": "Daily"
      }
    ],
    "next_token": 73a3c9e69b89
  }
}
```
> **说明：** 创建造型 VTO 任务时，请使用 `id` 的值（即 `template_id`）。



---

*   1. 创建造型 VTO 任务并轮询结果

图片和模板 ID 都备齐后即可创建任务。接口异步处理请求，您需要轮询任务状态，直到状态变为 `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. 上传图片** | 直接上传，或提供图片 URL。 |
| **2. 列出造型模板** | 取得可用造型风格及其 ID。 |
| **3. 创建 VTO 任务** | 提交图片 URL + 模板 ID。 |
| **4. 轮询至完成** | 取回最终结果图片的 URL。 |

这套流程稳定可靠、对开发者友好，可支撑即时上线的虚拟妆效试穿体验。


---

## 文件规格与错误码
* 支持的格式与尺寸

| 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 (modern TLS/HTTP support)   - jq >= 1.6 (robust JSON parsing) |
| Node.js (JavaScript) | Node >= 18 (for global fetch) |
| JavaScript | - Chrome / Edge >= 80   - Firefox >= 74   - Safari >= 13.1 |
| PHP | PHP >= 7.4 (for modern TLS/compat), ext-curl (recommended) or allow_url_fopen=On + ext-openssl, ext-json |
| Python | Python >= 3.10 (for f-strings), requests >= 2.20.0 |
| Java | Java 11+ (for HttpClient), Jackson Databind >= 2.12.0 |



---

## 点数消耗
| AI 功能 | 消耗点数 |
|  --- | --- |
| AI 造型虚拟试穿 V1.0 | 2 |



---

License: Privacy policy

## Servers

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

## Security

### BearerAuthenticationV2

使用标准的 Bearer 鉴权。把您的 API 密钥放进请求头： `Authorization:Bearer YOUR_API_KEY`。请注意 'Bearer' 与 'YOUR_API_KEY' 之间有一个空格。

Type: http
Scheme: bearer

## Download OpenAPI description

 - [AI 妆容虚拟试妆](https://docs.perfectcorp.com/_bundle/@l10n/zh-CN/reference/ai_look_vto.yaml)

## V1.0

 - [GET /s2s/v2.0/task/template/look-vto](https://docs.perfectcorp.com/zh-cn/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-cn/reference/ai_look_vto/v1.0/paths/~1s2s~1v2.0~1task~1look-vto/post.md): 本接口用模板与源图片发起 AI 妆容虚拟试妆流程。任务会异步处理，您可以使用本响应返回的 task_id 查询其状态。
 - [GET /s2s/v2.0/task/look-vto/{task_id}](https://docs.perfectcorp.com/zh-cn/reference/ai_look_vto/v1.0/paths/~1s2s~1v2.0~1task~1look-vto~1%7Btask_id%7D/get.md)
