# 创建表单 (POST)

创建一个托管表单。它会立即发布到 `https://frms.click/{tid}`，每次提交都会在你的账户中生成一条消息。参见 [表单](https://info.pocketalert.app/features/forms.md)。

## 端点

```
POST https://api.pocketalert.app/v1/forms
```

## 身份验证

> **Info: 必需**
>
> 在请求中包含以下请求头之一：
> - `Token: <your-api-key>` — 从 [API 密钥](https://pocketalert.app/account/apikeys) 获取
> - `Authorization: Bearer <jwt-token>` — 来自 [登录](https://info.pocketalert.app/api/user/login.md)

## 请求

### 请求头

| 请求头 | 必填 | 说明 |
|--------|:--------:|-------------|
| `Token` | ✅ | 你的 API 密钥 |
| `Authorization` | ✅ | `Bearer <jwt-token>` |

### 请求体参数

| 参数 | 类型 | 必填 | 说明 |
|-----------|------|:--------:|-------------|
| `name` | string | ✅ | 内部名称，最多 191 个字符。同时也是默认的推送标题 |
| `fields` | array | ✅ | 表单字段，最多 30 个。至少需要一个由访问者填写的字段 |
| `settings` | object | ❌ | 标题、文本和外观设计。每个键都有默认值 |
| `application_tid` | string | ❌ | 提交内容所属的应用 |
| `device_tid` | string | ❌ | 目标设备 TID，或 `all`。省略则发送到所有设备 |
| `default_level` | int | ❌ | 提交内容的优先级（`-2`..`2`）。参见 [消息优先级](https://info.pocketalert.app/api/messages/create.md#priority-levels) |
| `push_title` | string | ❌ | 推送标题模板，使用 `{Field label}` 占位符，最多 191 个字符 |
| `allowed_origins` | array | ❌ | 允许嵌入和提交表单的域名，最多 10 个。留空表示不限制 |
| `max_responses` | int | ❌ | 达到此提交数量后关闭表单。`0`（默认）表示不限 |
| `closes_at` | string | ❌ | 关闭时间，RFC 3339 格式。以 UTC 存储 |
| `is_active` | boolean | ❌ | 设为 `false` 则立即关闭表单。默认为 `true` |

### 字段

`fields` 中的每一项：

| 参数 | 类型 | 必填 | 说明 |
|-----------|------|:--------:|-------------|
| `id` | string | ✅ | 在表单内唯一：字母、数字、`_` 和 `-`，最多 40 个字符 |
| `type` | string | ✅ | 以下类型之一 |
| `label` | string | ✅ | 显示在输入框上方，最多 200 个字符（`paragraph` 为 2000 个） |
| `placeholder` | string | ❌ | 仅适用于 text、textarea、email、phone、number、url 和 dropdown |
| `required` | boolean | ❌ | 布局字段会忽略此项 |
| `options` | array | ✅ 用于选择类字段 | `dropdown`、`radio` 和 `checkboxes` 最多 50 个选项 |
| `param` | string | ✅ 用于 `hidden` | 读取值的 URL 参数，例如 `utm_source` |

| 分组 | 类型 | 提交的值 |
|-------|-------|-----------------|
| 文本 | `text`、`textarea`、`email`、`phone`、`number`、`url`、`date` | 字符串。`text` 上限 1000 个字符，`textarea` 上限 5000 个字符 |
| 选择 | `dropdown`、`radio` | `options` 中的一个 |
| 选择 | `checkboxes` | `options` 组成的数组 |
| 选择 | `checkbox` | 布尔值，显示为 `Yes` / `No` |
| 评分 | `rating`（1–5）、`nps`（0–10） | 数字 |
| 布局 | `heading`、`paragraph`、`divider` | 从不提交 |
| 追踪 | `hidden` | 取自页面 URL，而非访问者输入 |

邮箱、手机号、数字、URL 和日期的值会在服务器端校验；浏览器端的检查仅为便利功能，并非安全保障。

### 设置

所有键均为可选，未填写的项保持默认值。

| 参数 | 类型 | 默认值 | 说明 |
|-----------|------|---------|-------------|
| `title` | string | `""` | 表单上方的标题，最多 200 个字符 |
| `top_text` | string | `""` | 引导文本，最多 2000 个字符。纯文本；链接会变为可点击 |
| `bottom_text` | string | `""` | 按钮下方的文本，最多 2000 个字符 |
| `success_message` | string | `Thanks! Your response has been sent.` | 提交后显示，最多 500 个字符 |
| `closed_message` | string | `This form is no longer accepting responses.` | 表单关闭时显示 |
| `background_color` | string | `#f5f5f4` | 页面背景，`#rrggbb` |
| `card_color` | string | `#ffffff` | 表单背景 |
| `text_color` | string | `#1c1917` | 文字颜色 |
| `primary_color` | string | `#3f5cad` | 强调色，未单独设置时也用于按钮 |
| `font_family` | string | `Inter` | 按名称指定的 Google 字体 |
| `font_size` | int | `16` | 12–24 |
| `font_weight` | int | `400` | 300、400、500、600 或 700 |
| `border_radius` | int | `10` | 0–48 |
| `hide_branding` | boolean | `false` | 隐藏“Powered by Pocket Alert”链接。仅限付费套餐，免费套餐下 API 会将其重置为 `false` |
| `submit` | object | — | `{ "text": "Submit", "color": "", "size": "md" }`。`size` 可为 `sm`、`md` 或 `lg`；`color` 为空时跟随 `primary_color` |

### 推送标题模板

`push_title` 会根据回答生成通知标题：

```
New lead: {Name} ({Email})
```

占位符通过**字段标签**引用字段，不区分大小写，另外 `{form}` 表示表单名称。没有回答的占位符会被移除；如果没有剩余内容，标题将回退为 `Form: {name}`。该模板永远不会在公开页面中显示。

### 允许的来源

表单 ID 包含在公开链接中，因此默认情况下任何持有该链接的人都可以嵌入表单。`allowed_origins` 可以限制这一点：只有列出的域名可以嵌入表单，`Origin`（或 `Referer`）不在列表中的提交将被以 `403` 拒绝。

填写域名，而不是 URL：`example.com`、`app.example.com`、`*.example.com`（匹配所有子域名）、开发时可用 `localhost:3000`。`www.` 会被忽略。

### 请求示例

**cURL**

```bash
curl -X POST "https://api.pocketalert.app/v1/forms" \
  -H "Token: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Contact form",
    "push_title": "New lead: {Name}",
    "fields": [
      { "id": "name", "type": "text", "label": "Name", "required": true },
      { "id": "email", "type": "email", "label": "Email", "required": true },
      { "id": "message", "type": "textarea", "label": "Message" },
      { "id": "src", "type": "hidden", "label": "Source", "param": "utm_source" }
    ],
    "settings": {
      "title": "Get in touch",
      "top_text": "We reply within one business day.",
      "primary_color": "#3f5cad"
    }
  }'
```

**JavaScript**

```javascript
const response = await fetch('https://api.pocketalert.app/v1/forms', {
  method: 'POST',
  headers: {
    'Token': 'your-api-key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Contact form',
    push_title: 'New lead: {Name}',
    fields: [
      { id: 'name', type: 'text', label: 'Name', required: true },
      { id: 'email', type: 'email', label: 'Email', required: true },
      { id: 'message', type: 'textarea', label: 'Message' }
    ],
    settings: { title: 'Get in touch' }
  })
});

const form = await response.json();
console.log('Form link:', `https://frms.click/${form.tid}`);
```

**Python**

```python
import requests

response = requests.post(
    'https://api.pocketalert.app/v1/forms',
    headers={'Token': 'your-api-key'},
    json={
        'name': 'Contact form',
        'push_title': 'New lead: {Name}',
        'fields': [
            {'id': 'name', 'type': 'text', 'label': 'Name', 'required': True},
            {'id': 'email', 'type': 'email', 'label': 'Email', 'required': True},
            {'id': 'message', 'type': 'textarea', 'label': 'Message'},
        ],
        'settings': {'title': 'Get in touch'},
    }
)

form = response.json()
print(f"Form link: https://frms.click/{form['tid']}")
```

**PHP**

```php
$form = Http::withHeaders([
    'Token' => 'your-api-key',
])->post('https://api.pocketalert.app/v1/forms', [
    'name' => 'Contact form',
    'push_title' => 'New lead: {Name}',
    'fields' => [
        ['id' => 'name', 'type' => 'text', 'label' => 'Name', 'required' => true],
        ['id' => 'email', 'type' => 'email', 'label' => 'Email', 'required' => true],
        ['id' => 'message', 'type' => 'textarea', 'label' => 'Message'],
    ],
    'settings' => ['title' => 'Get in touch'],
])->json();

echo 'Form link: https://frms.click/'.$form['tid'];
```

## 响应

### 成功响应

> **Tip: 201 Created**
>
> 表单已上线。分享 `https://frms.click/{tid}`，或将其嵌入页面。参见 [表单](https://info.pocketalert.app/features/forms.md#embedding)。

响应体与 [获取所有表单](https://info.pocketalert.app/api/forms/get-forms.md#response) 中单条记录的结构相同。

```json
{
  "tid": "vml19aihrga216gt8apc5e3m9",
  "name": "Contact form",
  "fields": [
    { "id": "name", "type": "text", "label": "Name", "required": true },
    { "id": "email", "type": "email", "label": "Email", "required": true },
    { "id": "message", "type": "textarea", "label": "Message" },
    { "id": "src", "type": "hidden", "label": "Source", "param": "utm_source" }
  ],
  "settings": {
    "title": "Get in touch",
    "top_text": "We reply within one business day.",
    "success_message": "Thanks! Your response has been sent.",
    "closed_message": "This form is no longer accepting responses.",
    "background_color": "#f5f5f4",
    "card_color": "#ffffff",
    "text_color": "#1c1917",
    "primary_color": "#3f5cad",
    "font_family": "Inter",
    "font_size": 16,
    "font_weight": 400,
    "border_radius": 10,
    "hide_branding": false,
    "submit": { "text": "Submit", "color": "", "size": "md" }
  },
  "application_tid": "",
  "device_tid": "",
  "default_level": null,
  "push_title": "New lead: {Name}",
  "allowed_origins": [],
  "max_responses": 0,
  "closes_at": null,
  "closed": false,
  "is_active": true,
  "submissions_count": 0,
  "last_submission_at": "",
  "created_at": "23.09.2026 11:40:02"
}
```

### 错误响应

| 状态码 | 说明 |
|:------:|-------------|
| `400` | 校验错误：`error` 字段会指出哪个字段或设置有误 |
| `401` | 未授权：令牌无效或缺失 |
| `403` | 已达到你的套餐允许的表单数量上限 |
| `500` | 创建表单失败 |
