> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/ja/api-integration/webhook.md).

# Webhook

会話プラットフォームのWebhook：訪問者のメッセージとAI／有人担当者の返信をリアルタイムでシステムにプッシュし、MaiAgent標準形式、Genesys Cloud、カスタムJinja2テンプレートに対応します

Webhookは\*\*会話プラットフォーム（Inbox）\*\*で設定します。そのプラットフォームの会話に新しいメッセージが作成されるたびに、MaiAgentは指定されたエンドポイントへHTTPリクエストでメッセージをプッシュします。1つの会話プラットフォームに複数のWebhookを設定でき、それぞれでプッシュするメッセージの方向と形式を指定できます。

設定場所：<mark style="color:blue;">設定</mark> → <mark style="color:blue;">会話プラットフォーム</mark> → プラットフォームを選択 → <mark style="color:blue;">Webhooks</mark>タブ → <mark style="color:blue;">Webhookを追加</mark>。

{% hint style="info" %}
[会話とメッセージの作成](/tech/ja/api-integration/dui-hua-yu-xun-xi.md) APIでメッセージを送信した場合、レスポンスはメッセージが作成されたことのみを示します。**AIアシスタントの返信は非同期で生成され、Outgoing Webhookを通じて送信されます**。これはAPI連携で返信を取得する標準的な方法です。
{% endhint %}

## 動作の仕組み <a href="#how-it-works" id="how-it-works"></a>

```mermaid
sequenceDiagram
    participant C as お客様のシステム
    participant M as MaiAgent
    participant AI as AIアシスタント

    C->>M: POST /api/v1/messages/（訪問者メッセージ）
    M-->>C: 201 作成済み（返信を含みません）
    M-)C: Incoming Webhook（訪問者メッセージ）
    M->>AI: 返信を生成
    AI-->>M: 返信メッセージを作成
    M-)C: Outgoing Webhook（AI返信）
```

有人担当者が管理画面から返信した場合も、その返信はOutgoingメッセージとしてOutgoing Webhookへプッシュされます。payloadの`sender.type`でAIと有人担当者を区別できます。

## Webhookの種類 <a href="#directions" id="directions"></a>

| 種類           | トリガー                                                | 主な用途                                                                          |
| ------------ | --------------------------------------------------- | ----------------------------------------------------------------------------- |
| **Outgoing** | AIアシスタントまたは有人担当者の返信が作成されたとき                         | AIの返信を取得し、お客様のフロントエンドやメッセージングサービスへ転送します                                       |
| **Incoming** | 訪問者メッセージが作成されたとき（API、Web Chat、LINEなど、すべてのチャネルを含みます） | 会話履歴をカスタマーサービスシステム、データウェアハウス、監査システムへ同期します                                     |
| **Receive**  | 外部プラットフォームからMaiAgentが呼び出されたとき                       | 外部カスタマーサービスプラットフォームから返されたメッセージを受信します（現在はGenesys Cloud Open Messagingに対応しています） |

このページではOutgoingとIncomingについて説明します。

## 設定項目 <a href="#fields" id="fields"></a>

| 項目                                            | 説明                                                                   |
| --------------------------------------------- | -------------------------------------------------------------------- |
| <mark style="color:blue;">名前</mark>           | カスタム識別名                                                              |
| <mark style="color:blue;">種類</mark>           | Outgoing／Incoming／Receive                                            |
| <mark style="color:blue;">エンドポイントURL</mark>   | プッシュを受信するURL                                                         |
| <mark style="color:blue;">HTTP Method</mark>  | `POST`（デフォルト）／`PUT`／`PATCH`                                          |
| <mark style="color:blue;">Headers</mark>      | 各リクエストに追加するカスタムヘッダー（お客様のシステムのAPIキーなど）                                |
| <mark style="color:blue;">Payload形式</mark>    | **MaiAgent標準形式**／**Genesys Cloud**／**カスタムテンプレート**（Jinja2）            |
| <mark style="color:blue;">Secret Token</mark> | 設定すると、各リクエストに`X-Webhook-Secret: <token>`ヘッダーが付与され、エンドポイントで送信元を検証できます |
| <mark style="color:blue;">有効状態</mark>         | 無効にするとプッシュされませんが、設定は保持されます                                           |

## MaiAgent標準形式 <a href="#standard-payload" id="standard-payload"></a>

`Content-Type: application/json`で、内容は次のとおりです（OutgoingとIncomingは同じ構造で、`type`により方向を区別します）。

```json
{
  "id": "2491074a-6d23-4289-af45-caa12531420e",
  "type": "outgoing",
  "content": "こんにちは。どのようなご用件でしょうか？",
  "created_at": "2026-09-09T10:15:30.123456+00:00",
  "conversation": {
    "id": "8e44604a-8278-4c96-96b5-3e5a0548d738",
    "title": "返品手続きについての問い合わせ",
    "type": "individual",
    "status": "open",
    "progress_status": "ai_processing",
    "auto_reply_enabled": true,
    "assignee": null
  },
  "inbox": {
    "id": "1f9c1c1e-4d1a-4b1e-9d0e-7b2f4a5c6d7e",
    "name": "公式サイトカスタマーサービス",
    "channel_type": "web"
  },
  "contact": {
    "id": "c0ffee00-1111-2222-3333-444455556666",
    "name": "山田太郎",
    "email": null,
    "phone_number": null
  },
  "sender": {
    "id": "5c1d3e2a-0000-4b1e-9d0e-7b2f4a5c6d7e",
    "name": "AIカスタマーサービス",
    "type": "chatbot"
  },
  "attachments": [
    {
      "id": "a1b2c3d4-0000-4b1e-9d0e-7b2f4a5c6d7e",
      "type": "image",
      "filename": "photo.jpg",
      "source_url": "https://example.com/photo.jpg"
    }
  ],
  "metadata": {}
}
```

### 項目の説明 <a href="#standard-fields" id="standard-fields"></a>

| 項目                                | 型              | 説明                                                                                                                  |
| --------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------- |
| `id`                              | string         | メッセージID（UUID）                                                                                                       |
| `type`                            | string         | `incoming`（訪問者メッセージ）／`outgoing`（AIまたは有人担当者の返信）                                                                      |
| `content`                         | string         | メッセージテキスト                                                                                                           |
| `created_at`                      | string         | ISO 8601形式の時刻                                                                                                       |
| `conversation.id`                 | string         | 会話ID                                                                                                                |
| `conversation.title`              | string         | 会話タイトル                                                                                                              |
| `conversation.type`               | string         | `individual`／`group`                                                                                                |
| `conversation.status`             | string         | `open`／`queued`（有人担当者の対応待ち）／`resolved`                                                                              |
| `conversation.progress_status`    | string         | 現在の対応者：`ai_processing`／`waiting_for_human`／`human_serving`／`resolved`／`open`                                        |
| `conversation.auto_reply_enabled` | boolean        | `false`はAIが自動返信を停止していることを示します（有人対応へ切り替え中）                                                                           |
| `conversation.assignee`           | object \| null | 対応するカスタマーサービス担当者`{ id, name }`。未割り当ての場合は`null`です                                                                    |
| `inbox.id` / `inbox.name`         | string         | 会話プラットフォームのIDと名前                                                                                                    |
| `inbox.channel_type`              | string         | `web`／`line`／`messenger`／`instagram`／`telegram`／`teams`／`email`／`whatsapp`／`slack`／`team_plus`／`line_works`／`viber` |
| `contact`                         | object \| null | 訪問者（連絡先）`{ id, name, email, phone_number }`                                                                         |
| `sender.type`                     | string         | `chatbot`（AIアシスタント）／`user`（有人担当者）／`contact`（訪問者）                                                                    |
| `attachments[]`                   | array          | 添付ファイル`{ id, type, filename, source_url }`。`type`は`image`／`video`／`audio`／`sticker`／`other`です                       |
| `metadata`                        | object         | メッセージの追加データ                                                                                                         |

{% hint style="warning" %}
`attachments[].source_url`は添付ファイルの**ソースURL**（外部プラットフォームから渡された元のリンク）です。MaiAgentが保存したファイル（APIでアップロードしたファイルやAIが生成したファイルなど）では、この項目が空の場合があります。ダウンロード可能なURLが必要な場合は、カスタムテンプレートで`attachment.file.url`を取得する（以下の例を参照）か、メッセージIDを指定してメッセージAPIを呼び出し、添付ファイルを取得してください。
{% endhint %}

## カスタムテンプレート（Jinja2） <a href="#custom-template" id="custom-template"></a>

システムで特定のJSON構造が必要な場合は、<mark style="color:blue;">カスタムテンプレート</mark>を選択し、Jinja2構文でpayloadを記述します。テンプレートのレンダリング結果は有効なJSONである必要があります。保存時にテストデータを使用して一度検証されます。

### 使用可能な変数 <a href="#template-variables" id="template-variables"></a>

| 変数             | 内容                                                                                                                                       |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `message`      | `id`、`type`、`content`、`created_at`（datetime）、`metadata`                                                                                  |
| `conversation` | `id`、`title`、`type`、`status`、`progress_status`、`auto_reply_enabled`、`assignee`（`None`の場合があります。値がある場合は`assignee.id`、`assignee.user.name`） |
| `inbox`        | `id`、`name`、`channel_type`                                                                                                               |
| `contact`      | `id`、`name`、`email`、`phone_number`、`source_id`（ID同期APIで渡した`sourceId`）。`None`の場合があります                                                     |
| `sender`       | `id`、`name`。`sender_type`は`chatbot`／`user`／`contact`です                                                                                   |
| `attachments`  | 添付ファイルのリスト。各項目には`id`、`type`、`filename`、`source_url`、`file`（`file.url`はダウンロード可能なURL）があります                                                 |
| `now`          | レンダリング時の現在時刻（datetime）                                                                                                                   |

文字列は必ず`| tojson`フィルターを通して出力してください。これにより、引用符と改行が正しくエスケープされます。

### 例：システムのユーザーIDとダウンロード可能な添付ファイルURLを返す <a href="#template-example" id="template-example"></a>

```jinja
{
  "external_user_id": {{ (contact.source_id if contact else "") | tojson }},
  "conversation_id": "{{ conversation.id }}",
  "direction": "{{ message.type }}",
  "from_human_agent": {{ (sender_type == "user") | tojson }},
  "text": {{ message.content | tojson }},
  "attachments": [{% for a in attachments %}{
    "type": "{{ a.type }}",
    "url": {{ (a.file.url if a.file else a.source_url) | tojson }}
  }{% if not loop.last %},{% endif %}{% endfor %}],
  "sent_at": "{{ message.created_at.isoformat() }}"
}
```

## 送信動作 <a href="#delivery" id="delivery"></a>

* 各メッセージは、有効なWebhookごとに1回ずつプッシュされます。リクエストは**30秒**でタイムアウトします。
* **2xx**レスポンスは成功とみなされます。2xx以外のレスポンスまたはタイムアウトは失敗として記録され、**自動的には再試行されません**。確実な配信が必要な場合は、エンドポイントでリクエストを保存してから2xxレスポンスを返し、メッセージの`id`を使用して重複を排除してください。
* エンドポイントURLにはSSRF対策が適用されます。プライベートネットワークや内部アドレスの宛先は拒否されます。
* トラブルシューティングのため、各プッシュリクエストの内容、レスポンス、ステータスコードをAIアシスタントページの<mark style="color:blue;">Webhook</mark>タブで確認できます。

## APIでWebhookを管理する <a href="#manage-by-api" id="manage-by-api"></a>

管理画面に加えて、APIでWebhookを作成および管理できます（項目は管理画面の設定に対応します）。認証方法については[クイックスタート](/tech/ja/api-integration/quickstart.md)を参照してください。

```bash
# 一覧 / 追加
GET  https://api.maiagent.ai/api/v1/inboxes/{inboxId}/webhooks/
POST https://api.maiagent.ai/api/v1/inboxes/{inboxId}/webhooks/

# 更新 / 削除
PATCH  https://api.maiagent.ai/api/v1/inboxes/{inboxId}/webhooks/{webhookId}/
DELETE https://api.maiagent.ai/api/v1/inboxes/{inboxId}/webhooks/{webhookId}/
```

```json
{
  "name": "返信をカスタマーサービスシステムへ同期",
  "direction": "outgoing",
  "isEnabled": true,
  "url": "https://your-system.example.com/maiagent/reply",
  "method": "POST",
  "headers": { "X-Api-Key": "your-key" },
  "templatePreset": "maiagent_standard",
  "customTemplate": null,
  "secretToken": "shared-secret"
}
```

`inboxId`は[会話の作成](/tech/ja/api-integration/dui-hua-yu-xun-xi.md)のレスポンスに含まれる`inbox.id`から取得するか、管理画面の会話プラットフォーム設定ページで確認できます。

## 「有人切り替えWebhook」との違い <a href="#vs-handoff-webhook" id="vs-handoff-webhook"></a>

このページのWebhookは**メッセージ**単位でプッシュします。システムで会話が**いつ有人担当者へ切り替わり、いつAIへ戻ったか**を把握する必要がある場合（お客様のカスタマーサービスシステムが対応を引き継ぐ場合など）は、会話のライフサイクル単位で動作する別の有人切り替えWebhookを使用してください。[サードパーティのカスタマーサービスシステム連携（有人切り替えを含む）](/tech/ja/api-integration/customer-service-system-integration.md)を参照してください。

{% hint style="warning" %}
**リリース状況：正式リリース待ちです。** 上記リンクでは、ネストされた`id`／`occurred_at` payloadを含む新版の4イベント有人切り替え契約について説明していますが、現在は本番環境へリリースされていません。リンク先の新しい契約に基づいて本番連携を有効にしないでください。まず、お客様の環境が更新済みであることをMaiAgentチームに確認してください。このリリース状況はリンク先の新版有人切り替え契約にのみ適用されます。このページで説明しているメッセージWebhookは通常どおり使用できます。
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.maiagent.ai/tech/ja/api-integration/webhook.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
