# 웹훅

Tomba는 세 가지 방법으로 서버에 데이터를 보낼 수 있습니다. `webhook_url`을 추가한 개별 API 요청에 대한 콜백, `webhook_url`과 함께 생성한 대량 작업이 끝날 때 보내는 서명된 이벤트, 계정에서 리드가 생성될 때마다 실행되는 리드 웹훅입니다.

## 요청별 콜백

지원되는 요청에 `webhook_url`을 추가합니다. API는 평소처럼 응답에 결과를 반환합니다. 결과가 조건을 충족하면 Tomba는 결과를 URL로도 보냅니다.

```bash
curl -G "https://api.tomba.io/v1/email-verifier" \
  --data-urlencode "email=jane.doe@stripe.com" \
  --data-urlencode "webhook_url=https://hooks.example.com/tomba/7f3c9a" \
  -H "X-Tomba-Key: $TOMBA_API_KEY" \
  -H "X-Tomba-Secret: $TOMBA_SECRET_KEY"
```

### 지원되는 엔드포인트

| 엔드포인트                                              | 콜백 전송 조건                                                     |
| ----------------------------------------------------- | ---------------------------------------------------------------------- |
| [`GET /domain-search`](/api/finder#domain-search)     | 이메일 주소가 하나 이상 반환됨                                 |
| [`GET /email-finder`](/api/finder#email-finder)       | 검증 상태가 `unknown`이 아닌 주소가 반환됨 |
| [`GET /author-finder`](/api/finder#author-finder)     | 주소가 반환됨                                                 |
| [`GET /enrich`](/api/finder#email-enrichment)         | 검증 상태가 `unknown`이 아닌 주소가 반환됨 |
| [`GET /linkedin`](/api/finder#linkedin-finder)        | 주소가 반환됨                                                 |
| [`GET /email-verifier`](/api/verifier#email-verifier) | 상태가 `disposable` 또는 `unknown`이 아님                            |
| [`GET /phone-finder`](/api/phone#phone-finder)        | 유효한 전화번호 하나가 반환됨. `full=true`에서는 전송되지 않습니다.    |
| [`GET /people/find`](/api/enrichment#person-api)      | 인물이 반환됨                                                   |
| [`GET /combined/find`](/api/enrichment#combined-api)  | 인물이 반환됨                                                   |

다른 엔드포인트는 `webhook_url`을 무시합니다.

### 전송

Tomba는 본문이 API 응답과 같은 JSON인 `POST` 요청을 보냅니다. 다음 헤더가 포함됩니다:

| 헤더              | 값                                          |
| ------------------- | ---------------------------------------------- |
| `Content-Type`      | `application/json`                             |
| `Accept`            | `application/json`                             |
| `User-Agent`        | `Tomba-Webhook/1.0`                            |
| `X-Tomba-Timestamp` | 전송 시도 시각의 Unix 시간(초) |

- 각 시도는 30초 후 타임아웃됩니다. 네트워크 오류나 2xx가 아닌 응답은 재시도되며, 시도는 2초 간격으로 최대 4회입니다. 페이로드를 저장하는 즉시 2xx 상태로 응답합니다.
- 콜백은 서명되지 않습니다. 위 예시처럼 추측하기 어려운 토큰을 URL에 넣고, 토큰이 없는 요청은 거부합니다.
- URL은 공개 도메인 이름을 사용해야 합니다. IP 주소와 `localhost`는 `422`로 실패합니다. 일반 `http://` URL도 허용되지만 `https://`를 사용합니다.
- 과금되지 않는 [중복 요청](/usage-and-quotas#duplicate-requests)에 대해서도 콜백이 전송됩니다. `webhook_url`을 바꾸면 중복 규칙상 새 요청이 됩니다.

## 대량 작업 이벤트

[대량 작업을 생성](/bulks#create-a-job)할 때 `webhook_url`을 설정하면, 작업이 끝날 때 Tomba가 해당 URL로 서명된 `POST` 요청을 보냅니다:

| `type`           | 전송 조건                                                                                |
| ---------------- | ---------------------------------------------------------------------------------------- |
| `bulk.completed` | 작업이 완료되었습니다. `data.metrics`에 결과가, `data.links.download`에 파일이 있습니다. |
| `bulk.failed`    | 작업이 실패했습니다. `data.error_message`에 이유가 나옵니다.                                           |
| `bulk.cancelled` | 실행 중인 작업이 취소되었습니다. `pending` 상태의 작업을 취소하면 이벤트가 전송되지 않습니다.          |

재시도한 작업은 끝날 때 `data.attempt`를 하나 증가시킨 새 이벤트를 보냅니다.

```json
{
    "type": "bulk.completed",
    "created_at": "2026-09-29T09:16:19Z",
    "data": {
        "bulk_id": 4521,
        "bulk_type": "search",
        "name": "Q3 target accounts",
        "status": "completed",
        "attempt": 1,
        "started_at": "2026-09-29T09:14:05Z",
        "completed_at": "2026-09-29T09:16:18Z",
        "metrics": {
            "v": 1,
            "rows": {
                "input": 3,
                "valid_input": 3,
                "invalid_input": 0,
                "duplicates": 0,
                "skipped": 0,
                "processed": 3,
                "errors": 0
            },
            "results": {
                "found": 3,
                "not_found": 0,
                "hit_rate": 100,
                "records": 24
            },
            "distribution": {},
            "emails": {
                "total": 24,
                "per_found_row": 8,
                "with_sources": 21,
                "webmail": 0,
                "deliverable_rate": 75
            },
            "errors": { "client": 0, "server": 0, "rate_limited": 0 },
            "credits": { "search": 3, "verify": 24, "phone": 0, "total": 27 },
            "timing": {
                "queued_ms": 1840,
                "duration_ms": 133520,
                "rows_per_minute": 1.3
            }
        },
        "billed_on_download": true,
        "links": {
            "api": "https://api.tomba.io/v1/bulk/search/4521",
            "download": "https://api.tomba.io/v1/bulk/search/4521/download",
            "app": "https://app.tomba.io/bulk/searches/4521"
        }
    }
}
```

| 필드                                                        | 설명                                                                                                                       |
| ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `type`, `created_at`                                         | 이벤트와 이벤트 생성 시각                                                                                                |
| `data.bulk_id`, `data.bulk_type`, `data.name`, `data.status` | 작업. Phone Finder 작업은 `phone`입니다.                                                                                           |
| `data.attempt`                                               | 첫 실행은 `1`, 이후 재시도할 때마다 하나씩 증가                                                                               |
| `data.error_message`                                         | 작업이 실패한 이유. `bulk.failed`에만 있습니다.                                                                                           |
| `data.started_at`, `data.completed_at`                       | 작업이 시작되고 완료된 시각                                                                                                |
| `data.metrics`                                               | [작업 필드](/bulks#job-fields)와 같은 작업 결과. `bulk.completed`에만 있습니다.                                                  |
| `data.billed_on_download`                                    | 항상 `true`: 작업 비용은 이벤트가 전송될 때가 아니라 결과를 처음 다운로드할 때 청구됩니다. [청구](/bulks#billing)를 참고합니다. |
| `data.links`                                                 | `api`: 작업. `download`: 결과 파일(`bulk.completed`에만 있음). `app`: 대시보드의 작업.                             |

### 헤더

이벤트는 [Standard Webhooks](https://www.standardwebhooks.com) 사양을 따릅니다:

| 헤더              | 값                                                                                                           |
| ------------------- | --------------------------------------------------------------------------------------------------------------- |
| `Content-Type`      | `application/json`                                                                                              |
| `User-Agent`        | `Tomba-Webhooks/1.0`                                                                                            |
| `webhook-id`        | `blk_4521_1_bulk.completed` 같은 이벤트 ID. 모든 시도에서 같으므로 중복을 건너뛰는 데 사용합니다. |
| `webhook-timestamp` | 시도 시각의 Unix 시간(초)                                                                           |
| `webhook-signature` | `v1,` 뒤에 base64로 인코딩된 HMAC-SHA256 서명                                                      |

### 서명 검증

`GET /v1/bulk/webhook-secret`에서 시크릿을 가져옵니다. 시크릿은 `webhook_url`이 있는 첫 대량 작업을 만들 때 또는 이 호출로 생성되며, 모든 작업의 이벤트에 서명합니다. 이벤트를 검증하려면 다음과 같이 합니다:

1. 시크릿에서 `whsec_` 접두사를 제거하고 나머지를 base64로 디코딩합니다. 그것이 키입니다.
2. 키로 `{webhook-id}.{webhook-timestamp}.{body}`의 HMAC-SHA256을 계산하고 base64로 인코딩합니다. 여기서 `body`는 원시 요청 본문입니다.
3. 결과를 `webhook-signature`에서 `v1,` 뒤의 부분과 비교합니다. 타임스탬프가 5분보다 오래된 이벤트는 거부합니다.

<CodeTabs syncKey="lang">

```js title="Node.js"
import crypto from "node:crypto";

// secret: from GET /v1/bulk/webhook-secret. body: the raw request body, as a string.
export function verifyTombaEvent(secret, headers, body) {
    const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
    const signed = `${headers["webhook-id"]}.${headers["webhook-timestamp"]}.${body}`;
    const expected = crypto
        .createHmac("sha256", key)
        .update(signed)
        .digest("base64");
    const received = headers["webhook-signature"].replace(/^v1,/, "");
    const age = Math.abs(
        Date.now() / 1000 - Number(headers["webhook-timestamp"]),
    );
    return (
        age < 300 &&
        expected.length === received.length &&
        crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received))
    );
}
```

```python title="Python"
import base64
import hashlib
import hmac
import time


# secret: from GET /v1/bulk/webhook-secret. body: the raw request body, as bytes.
def verify_tomba_event(secret: str, headers: dict, body: bytes) -> bool:
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{headers['webhook-id']}.{headers['webhook-timestamp']}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    received = headers["webhook-signature"].removeprefix("v1,")
    fresh = abs(time.time() - int(headers["webhook-timestamp"])) < 300
    return fresh and hmac.compare_digest(expected, received)
```

</CodeTabs>

`POST /v1/bulk/webhook-secret/rotate`는 시크릿을 교체합니다. 이전 시크릿은 이미 실행 중인 작업의 이벤트를 포함하여 즉시 작동을 멈춥니다.

### 전송 및 재시도

- 각 시도는 10초 후 타임아웃됩니다. 네트워크 오류나 2xx가 아닌 응답은 재시도되며, 시도는 최대 5회입니다. 첫 시도는 즉시, 이후 시도는 각각 이전 시도로부터 10초, 30초, 2분, 5분 후에 이루어집니다. `410 Gone` 응답은 재시도를 중단합니다.
- `webhook_url`은 사용자 이름이나 비밀번호가 없고, 호스트가 공개 IP 주소로 확인되는 최대 2,048자의 `https://` URL이어야 합니다. 그렇지 않으면 작업 생성이 `422`로 실패합니다. 전송은 공개 IP 주소로만 연결됩니다.
- 각 시도는 HTTP 상태와 함께 `webhook_delivered` 또는 `webhook_failed`로 작업 이력에 기록됩니다. [`GET /v1/bulk/{type}/{id}/history`](/api/bulks#get-bulk-job-history)를 참고합니다.

## 리드 이벤트

리드 웹훅은 계정에서 리드가 생성될 때마다 URL을 호출합니다. 리드가 업데이트되거나 삭제될 때는 전송되지 않으며, 유료 플랜이 필요합니다.

대시보드의 [Webhooks](https://app.tomba.io/settings/webhooks)에서 설정합니다. 계정에는 리드 웹훅이 하나 있습니다:

| 설정 | 설명                                                                                                          |
| ------- | -------------------------------------------------------------------------------------------------------------------- |
| Name    | 2~50자.                                                                                                  |
| URL     | Tomba가 리드를 보내는 곳. Tomba는 경로와 쿼리를 포함하여 URL을 소문자로 저장하므로 소문자 URL을 사용합니다. |
| Method  | `POST`, `PUT`, `PATCH`, `GET` 또는 `HEAD`. `POST`를 사용합니다.                                                                |
| Header  | `Authorization: Bearer <token>` 같은 사용자 지정 헤더 이름과 값 하나. Tomba의 요청을 인증하는 데 사용합니다.  |
| Status  | 웹훅 활성화 여부. 새 웹훅은 비활성 상태로 시작합니다.                                                         |

Tomba는 `Content-Type: application/json`, `User-Agent` `Mozilla/5.0 (compatible; TombaHooks/1.0; +https://tomba.io)`, 사용자 지정 헤더와 함께 리드를 보냅니다:

```json
{
    "data": {
        "email": "jane.doe@stripe.com",
        "company": "Stripe",
        "first_name": "Jane",
        "last_name": "Doe",
        "phone": null,
        "website": "stripe.com",
        "position": "Marketing Manager",
        "twitter": null,
        "linkedin": null,
        "notes": null,
        "score": 90
    }
}
```

| 필드                     | 유형           | 설명               |
| ------------------------- | -------------- | ------------------------- |
| `email`                   | string         | 리드의 이메일 주소      |
| `website`                 | string         | 회사 웹사이트           |
| `company`                 | string 또는 null | 회사 이름              |
| `first_name`, `last_name` | string 또는 null | 리드 이름               |
| `phone`                   | string 또는 null | 전화번호              |
| `position`                | string 또는 null | 직함                 |
| `twitter`, `linkedin`     | string 또는 null | 소셜 프로필           |
| `notes`                   | string 또는 null | 리드와 함께 저장된 메모 |
| `score`                   | integer        | 리드 점수                |

본문에는 이벤트 이름, ID, 타임스탬프가 없으며, Tomba는 전송 성공 여부를 기록하지 않습니다. 완전한 기록이 필요하면 [`GET /v1/leads`](/api/leads#retrieve-leads)와 대조합니다.
