> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://developers.omicx.one/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://developers.omicx.one/_mcp/server.

# Tạo Webhook

POST https://api.omicx.one/webhooks/
Content-Type: application/json

Đăng ký một endpoint HTTP để nhận payload sự kiện (xem danh mục sự kiện). Các giá trị xác thực bí mật (`config.apiKey`, giá trị custom header) chỉ ghi (write-only) — response chỉ trả về `hasApiKey` hoặc giá trị đã che (masked). URL đích phải là endpoint http(s) công khai (có chống SSRF). **Scope yêu cầu:** `webhook:write`.

Reference: https://developers.omicx.one/integrations/webhooks/create-webhook

## Request

### Headers

- `X-Api-Key` (string, required)

### Body (application/json)

This endpoint expects a WebhookUpsertRequest.

- `events` (list of string, required) — Sự kiện đăng ký — dạng `"{TYPE}:{ACTION}"` (ví dụ `"AI_TTS:COMPLETED"`) hoặc chỉ `"{TYPE}"` ở những nơi hỗ trợ. Xem đầy đủ tại API Danh mục sự kiện.
- `config` (WebhookConfig, required)
- `name` (string, optional) — Tên hiển thị.

## Response

### 201

Webhook đã tạo (giá trị bí mật đã che).

- `id` (string, optional)
- `tenantId` (string, optional)
- `name` (string, optional)
- `events` (list of string, optional)
- `config` (WebhookConfig, optional)
- `status` (enum, optional)
  - Allowed values: `ENABLED`, `DISABLED`, `DELETED`
- `createdAt` (long, optional)
- `updatedAt` (long, optional)
- `lastExecutedAt` (long, optional, nullable)
- `blocked` (boolean, optional) — Lượt gửi tới webhook này có đang bị tạm giữ do chặn lỗi hay không.
- `blockedUntil` (long, optional, nullable) — Epoch millis khi trạng thái chặn hết hạn (chỉ có khi đang bị chặn).
- `errorCount` (long, optional) — Số lần lỗi trong cửa sổ trượt hiện tại.

## Errors

### 400 Bad Request Error

Lỗi dữ liệu đầu vào (relay từ webhook-service).

- `error` (ErrorResponseError, optional)

### 401 Unauthorized Error

Thiếu hoặc sai API key.

- `error` (ErrorResponseError, optional)

### 403 Forbidden Error

`INSUFFICIENT_SCOPE` — key hợp lệ nhưng thiếu scope `webhook:write`.

- `error` (ErrorResponseError, optional)

### 502 Bad Gateway Error

webhook-service tạm thời không khả dụng.

- `error` (ErrorResponseError, optional)

## Types

### WebhookConfig

- `url` (string, required) — Endpoint http(s) công khai của bạn (có chống SSRF).
- `method` (enum, optional, default: POST)
  - Allowed values: `POST`, `PUT`
- `authType` (enum, optional, default: NONE) — `NONE` — không kèm xác thực. `API_KEY` — gửi kèm `apiKey` trong header `X-API-KEY` của mỗi lượt gửi. `CUSTOM_HEADER` — gửi kèm một hoặc nhiều header tuỳ chỉnh khai báo trong `headers`.
  - Allowed values: `NONE`, `API_KEY`, `CUSTOM_HEADER`
- `apiKey` (string, optional) — Chỉ ghi (write-only) — dùng khi `authType` là `API_KEY`, được gửi dưới dạng header `X-API-KEY` khi giao payload.
- `hasApiKey` (boolean, optional) — (Chỉ có trong response) Webhook này đã cấu hình `apiKey` hay chưa.
- `headers` (list of WebhookKeyValue, optional) — Dùng khi `authType` là `CUSTOM_HEADER` — giá trị (`value`) chỉ ghi, response chỉ trả về tên header kèm giá trị đã che (`********`).
- `params` (list of WebhookKeyValue, optional) — Query param bổ sung, được gắn thêm vào URL khi giao payload.
- `retryEnabled` (boolean, optional) — Tự động gửi lại khi thất bại (mặc định `true`).
- `blockIfError` (boolean, optional) — Tự động chặn (block) sau nhiều lần thất bại liên tiếp (mặc định `true`).
- `blockAfterTimes` (integer, optional) — Số lần lỗi trong cửa sổ trượt trước khi bị chặn (`0` = dùng mặc định hệ thống).
- `alertOnFailure` (boolean, optional) — Gửi email khi một đợt lỗi (outage) mới bắt đầu (mặc định `true`).
- `alertOnRecovery` (boolean, optional) — Gửi email khi endpoint hồi phục (mặc định `true`).

### ErrorResponseError

- `code` (string, optional) — Nhóm lỗi (dạng máy đọc được), ổn định theo từng HTTP status.
- `subCode` (string, optional) — Mã cụ thể, ổn định — dùng để phân nhánh xử lý / dịch i18n. Hãy xử lý logic dựa trên `subCode`, không dựa vào chuỗi `message`.
- `message` (string, optional) — Mô tả cho con người đọc (dùng để debug), không nên dịch trực tiếp.
- `timestamp` (datetime, optional)
- `path` (string, optional) — Đường dẫn request đầy đủ.
- `details` (list of ErrorResponseErrorDetailsItems, optional) — Chỉ xuất hiện khi `code` là `VALIDATION_ERROR` — danh sách lỗi theo từng trường.

### WebhookKeyValue

- `key` (string, optional)
- `value` (string, optional)

### ErrorResponseErrorDetailsItems

## Examples

**Request**

```json
{
  "events": [
    "AI_TTS:COMPLETED",
    "AI_TTS:FAILED"
  ],
  "config": {
    "url": "https://yourdomain.com/webhooks",
    "method": "POST",
    "authType": "API_KEY",
    "apiKey": "my-secret-value",
    "retryEnabled": true,
    "blockIfError": true,
    "alertOnFailure": true,
    "alertOnRecovery": true
  },
  "name": "Webhook xử lý AI"
}
```

**Response**

```json
{
  "id": "your-webhook-id",
  "tenantId": "string",
  "name": "Webhook xử lý AI",
  "events": [
    "AI_TTS:COMPLETED",
    "AI_TTS:FAILED"
  ],
  "config": {
    "url": "https://yourdomain.com/webhooks",
    "method": "POST",
    "authType": "API_KEY",
    "apiKey": "my-secret-value",
    "hasApiKey": true,
    "headers": [
      {
        "key": "string",
        "value": "string"
      }
    ],
    "params": [
      {
        "key": "string",
        "value": "string"
      }
    ],
    "retryEnabled": true,
    "blockIfError": true,
    "blockAfterTimes": 0,
    "alertOnFailure": true,
    "alertOnRecovery": true
  },
  "status": "ENABLED",
  "createdAt": 1767225600000,
  "updatedAt": 1767225600000,
  "lastExecutedAt": 1767225600000,
  "blocked": false,
  "blockedUntil": 1,
  "errorCount": 0
}
```

**SDK Code**

```python Đăng ký webhook cho sự kiện TTS
import requests

url = "https://api.omicx.one/webhooks/"

payload = {
    "events": ["AI_TTS:COMPLETED", "AI_TTS:FAILED"],
    "config": {
        "url": "https://yourdomain.com/webhooks",
        "method": "POST",
        "authType": "API_KEY",
        "apiKey": "my-secret-value",
        "retryEnabled": True,
        "blockIfError": True,
        "alertOnFailure": True,
        "alertOnRecovery": True
    },
    "name": "Webhook xử lý AI"
}
headers = {
    "X-Api-Key": "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript Đăng ký webhook cho sự kiện TTS
const url = 'https://api.omicx.one/webhooks/';
const options = {
  method: 'POST',
  headers: {
    'X-Api-Key': 'omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'Content-Type': 'application/json'
  },
  body: '{"events":["AI_TTS:COMPLETED","AI_TTS:FAILED"],"config":{"url":"https://yourdomain.com/webhooks","method":"POST","authType":"API_KEY","apiKey":"my-secret-value","retryEnabled":true,"blockIfError":true,"alertOnFailure":true,"alertOnRecovery":true},"name":"Webhook xử lý AI"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Đăng ký webhook cho sự kiện TTS
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.omicx.one/webhooks/"

	payload := strings.NewReader("{\n  \"events\": [\n    \"AI_TTS:COMPLETED\",\n    \"AI_TTS:FAILED\"\n  ],\n  \"config\": {\n    \"url\": \"https://yourdomain.com/webhooks\",\n    \"method\": \"POST\",\n    \"authType\": \"API_KEY\",\n    \"apiKey\": \"my-secret-value\",\n    \"retryEnabled\": true,\n    \"blockIfError\": true,\n    \"alertOnFailure\": true,\n    \"alertOnRecovery\": true\n  },\n  \"name\": \"Webhook xử lý AI\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("X-Api-Key", "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Đăng ký webhook cho sự kiện TTS
require 'uri'
require 'net/http'

url = URI("https://api.omicx.one/webhooks/")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["X-Api-Key"] = 'omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"events\": [\n    \"AI_TTS:COMPLETED\",\n    \"AI_TTS:FAILED\"\n  ],\n  \"config\": {\n    \"url\": \"https://yourdomain.com/webhooks\",\n    \"method\": \"POST\",\n    \"authType\": \"API_KEY\",\n    \"apiKey\": \"my-secret-value\",\n    \"retryEnabled\": true,\n    \"blockIfError\": true,\n    \"alertOnFailure\": true,\n    \"alertOnRecovery\": true\n  },\n  \"name\": \"Webhook xử lý AI\"\n}"

response = http.request(request)
puts response.read_body
```

```java Đăng ký webhook cho sự kiện TTS
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.omicx.one/webhooks/")
  .header("X-Api-Key", "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
  .header("Content-Type", "application/json")
  .body("{\n  \"events\": [\n    \"AI_TTS:COMPLETED\",\n    \"AI_TTS:FAILED\"\n  ],\n  \"config\": {\n    \"url\": \"https://yourdomain.com/webhooks\",\n    \"method\": \"POST\",\n    \"authType\": \"API_KEY\",\n    \"apiKey\": \"my-secret-value\",\n    \"retryEnabled\": true,\n    \"blockIfError\": true,\n    \"alertOnFailure\": true,\n    \"alertOnRecovery\": true\n  },\n  \"name\": \"Webhook xử lý AI\"\n}")
  .asString();
```

```php Đăng ký webhook cho sự kiện TTS
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.omicx.one/webhooks/', [
  'body' => '{
  "events": [
    "AI_TTS:COMPLETED",
    "AI_TTS:FAILED"
  ],
  "config": {
    "url": "https://yourdomain.com/webhooks",
    "method": "POST",
    "authType": "API_KEY",
    "apiKey": "my-secret-value",
    "retryEnabled": true,
    "blockIfError": true,
    "alertOnFailure": true,
    "alertOnRecovery": true
  },
  "name": "Webhook xử lý AI"
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-Api-Key' => 'omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  ],
]);

echo $response->getBody();
```

```csharp Đăng ký webhook cho sự kiện TTS
using RestSharp;

var client = new RestClient("https://api.omicx.one/webhooks/");
var request = new RestRequest(Method.POST);
request.AddHeader("X-Api-Key", "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"events\": [\n    \"AI_TTS:COMPLETED\",\n    \"AI_TTS:FAILED\"\n  ],\n  \"config\": {\n    \"url\": \"https://yourdomain.com/webhooks\",\n    \"method\": \"POST\",\n    \"authType\": \"API_KEY\",\n    \"apiKey\": \"my-secret-value\",\n    \"retryEnabled\": true,\n    \"blockIfError\": true,\n    \"alertOnFailure\": true,\n    \"alertOnRecovery\": true\n  },\n  \"name\": \"Webhook xử lý AI\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Đăng ký webhook cho sự kiện TTS
import Foundation

let headers = [
  "X-Api-Key": "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "Content-Type": "application/json"
]
let parameters = [
  "events": ["AI_TTS:COMPLETED", "AI_TTS:FAILED"],
  "config": [
    "url": "https://yourdomain.com/webhooks",
    "method": "POST",
    "authType": "API_KEY",
    "apiKey": "my-secret-value",
    "retryEnabled": true,
    "blockIfError": true,
    "alertOnFailure": true,
    "alertOnRecovery": true
  ],
  "name": "Webhook xử lý AI"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.omicx.one/webhooks/")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```