# 웹훅 생성 (POST)

외부 서비스에서 알림을 받을 새 웹훅을 생성합니다.

## 엔드포인트

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

## 인증

> **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 | ✅ | 웹훅 이름 (예: "Sentry", "GitHub") |
| `url` | string | ❌ | 수신 URL `https://p4a.me/wh/{url}`의 슬러그입니다. 생략하면 무작위 20자 슬러그가 생성됩니다. 고유해야 하며, 이미 사용 중인 슬러그면 `409`를 반환합니다 |
| `message` | string | ✅ | 메시지 템플릿 (원본 JSON을 그대로 쓰려면 `*` 사용) |
| `application_id` | string | ❌ | 메시지를 분류할 애플리케이션 TID |
| `device_id` | string | ❌ | 대상 기기 TID (생략하면 모든 기기) |
| `default_level` | string \| int | ❌ | 페이로드에 우선순위가 없을 때 이 웹훅의 메시지에 적용되는 기본 우선순위 레벨입니다. 이름(`silent`, `low`, `default`, `high`, `critical`) 또는 정수(`-2`..`2`)를 사용합니다. [메시지 우선순위 레벨](https://info.pocketalert.app/api/messages/create.md#priority-levels)을 참고하세요. |
| `actions` | string | ❌ | 액션 버튼 JSON 템플릿입니다. [메시지 액션](https://info.pocketalert.app/api/messages/create.md#action-buttons)과 같은 형식이지만, `label`/`value`에 수신 페이로드를 기준으로 치환되는 `%field.path%` 자리표시자를 포함할 수 있습니다. JSON 문자열로 저장됩니다. 유료 기능이며, 무료 플랜에서는 제거됩니다. |

### 액션 버튼 템플릿

`actions`를 사용하면 웹훅으로 생성된 알림에 최대 3개의 버튼을 넣을 수 있습니다. `%field.path%` 자리표시자는 수신 페이로드의 값으로 치환됩니다(메시지 템플릿과 같은 문법):

```json
[
  { "type": "view", "label": "Open issue", "value": "%issue.html_url%" },
  { "type": "http", "label": "Ack", "value": "{\"url\":\"https://ops.example.com/ack/%issue.id%\",\"method\":\"POST\"}" }
]
```

템플릿은 저장할 때 검사됩니다. 최대 3개 버튼으로 이루어진 JSON 배열이어야 하며, 각 버튼은 올바른 `type`을 가져야 합니다. 자리표시자가 없는 버튼은 완전히 유효해야 하고, 그렇지 않으면 요청이 `400`을 반환합니다.

치환 후 각 버튼은 [메시지 액션](https://info.pocketalert.app/api/messages/create.md#action-buttons)과 같은 방식으로 검증됩니다. 이 페이로드에서 잘못된 버튼이 되는 경우(예: URL 필드가 없는 `view` 버튼)는 해당 버튼만 제외되며, 나머지 버튼과 메시지는 그대로 전달됩니다.

액션 버튼은 유료 기능입니다. 무료 플랜에서는 서버에서 버튼이 제거되고, 버튼 없이 메시지가 전달됩니다.

### 메시지 템플릿 문법

`%field.path%`를 사용하면 수신 JSON에서 값을 추출할 수 있습니다:

| 템플릿 | 설명 |
|----------|-------------|
| `*` | 전체 JSON 페이로드 출력 |
| `%field%` | 최상위 필드 추출 |
| `%object.field%` | 중첩된 필드 추출 |
| `%array.0.field%` | 인덱스로 배열에서 추출 |
| `%%` | 리터럴 `%`입니다. `%`처럼 바로 뒤에 단어와 또 다른 `%cpu%%%`가 이어질 때만 필요합니다. `%`처럼 `90% on %host%` 뒤에 공백이 오면 그대로 둡니다 |

자세한 예시는 [웹훅 설정](https://info.pocketalert.app/api/webhooks/settings.md)을 참고하세요.

### 요청 예시

**cURL**

```bash
curl -X POST "https://api.pocketalert.app/v1/webhooks" \
  -H "Token: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "GitHub Push",
    "message": "Push to %repository.name%: %head_commit.message%",
    "application_id": "s9h1ekk5xb46jikthl"
  }'
```

**JavaScript**

```javascript
const response = await fetch('https://api.pocketalert.app/v1/webhooks', {
  method: 'POST',
  headers: {
    'Token': 'your-api-key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'GitHub Push',
    message: 'Push to %repository.name%: %head_commit.message%',
    application_id: 's9h1ekk5xb46jikthl'
  })
});

const webhook = await response.json();
console.log('Webhook URL:', `https://p4a.me/wh/${webhook.url}`);
```

**Python**

```python
import requests

response = requests.post(
    'https://api.pocketalert.app/v1/webhooks',
    headers={'Token': 'your-api-key'},
    json={
        'name': 'GitHub Push',
        'message': 'Push to %repository.name%: %head_commit.message%',
        'application_id': 's9h1ekk5xb46jikthl'
    }
)

webhook = response.json()
print(f"Webhook URL: https://p4a.me/wh/{webhook['url']}")
```

**PHP**

```php
$response = Http::withHeaders([
    'Token' => 'your-api-key',
])->post('https://api.pocketalert.app/v1/webhooks', [
    'name' => 'GitHub Push',
    'message' => 'Push to %repository.name%: %head_commit.message%',
    'application_id' => 's9h1ekk5xb46jikthl',
]);

$webhook = $response->json();
echo 'Webhook URL: https://p4a.me/wh/'.$webhook['url'];
```

## 응답

### 성공 응답

> **Tip: 201 Created**
>
> 웹훅이 성공적으로 생성되었습니다

| 필드 | 타입 | 설명 |
|-------|------|-------------|
| `tid` | string | 고유 웹훅 식별자 |
| `name` | string | 웹훅 이름 |
| `url` | string | 웹훅 URL 슬러그 — 외부 서비스에서 이 값을 사용하세요 |
| `message` | string | 메시지 템플릿 |
| `actions` | string | 액션 버튼 JSON 템플릿 (설정하지 않았다면 비어 있음) |
| `is_active` | boolean | 웹훅 활성화 여부 |

```json
{
  "tid": "kblf7mh9j8jjyeh4fx",
  "name": "GitHub Push",
  "url": "cs994rqfkk8ljngt",
  "message": "Push to %repository.name%: %head_commit.message%",
  "actions": "",
  "application_tid": "qm47b9pzxzx7applfd0",
  "device_tid": "",
  "is_active": true,
  "created_at": "01.09.2023 22:38:48"
}
```

> **Tip: 웹훅 사용하기**
>
> 외부 서비스가 다음 주소로 POST 요청을 보내도록 설정하세요:
> ```
> https://p4a.me/wh/{url}
> ```

### 오류 응답

| 상태 | 설명 |
|:------:|-------------|
| `400` | 잘못된 요청 — `name` 또는 `message`가 없거나, `default_level`이 잘못되었거나, `actions` 템플릿이 잘못되었습니다 |
| `401` | 인증 실패 — 토큰이 잘못되었거나 없습니다 |
| `403` | 금지됨 — 플랜의 웹훅 한도에 도달했습니다 |
| `404` | 찾을 수 없음 — `application_id` 또는 `device_id`가 존재하지 않습니다 |
| `409` | 충돌 — `url` 슬러그가 이미 사용 중입니다 |
