# merchi.ai Webhooks

Webhooks allow you to receive real-time notifications when processing jobs complete, encounter errors, or finish with partial success. Instead of polling for status updates, your server receives automatic HTTP requests with job details.

> **Can't receive webhooks?** Use the [approved products endpoint](https://merchi.ai/api.md#get-approved-products) instead. It returns the same product data as the `product_approved` event and supports incremental polling.

> **Postman folder:** [Run in Postman](https://www.postman.com/ross-70770605-9019280/workspace/merchi-ai-api-public/folder/51963753-e33e5717-fd28-48b8-a070-9638527b4a2a?ctx=documentation)

---

## Configuring Webhooks

Navigate to **Settings → Webhooks** in the platform to manage your webhook endpoints. On a free trial, email [hello@merchi.ai](mailto:hello@merchi.ai) first and we'll enable webhook and API access for your account. You can create multiple webhooks, each with different configurations and notification types.

### Basic Configuration

| Field | Description |
|-------|-------------|
| **Name** | A friendly name to identify this webhook (e.g. "Production Server", "Zapier Integration") |
| **Webhook URL** | The HTTPS endpoint that will receive notifications |

### HTTP Settings

| Setting | Options | Default |
|---------|---------|---------|
| **HTTP Method** | POST, PUT, PATCH | POST |
| **Content Type** | JSON, Form URL Encoded | JSON |

### Notification Types

| Event | Description |
|-------|-------------|
| **Processing Complete** | All items in the job processed successfully |
| **Completed with Issues** | Job finished but some items failed or were skipped |
| **Processing Failed** | The entire job failed to process |
| **Product Approved** | A product's workflow status changed to "approved" |

The first three job-level events are enabled by default. **Product Approved** must be explicitly enabled — it fires once per product approval, not per job.

### Custom Headers

Add authentication or custom headers under the **Custom Headers** section. Up to 10 headers per webhook. Headers with "auth", "key", or "secret" in the name are automatically masked in the UI.

| Example header | Example value | Purpose |
|----------------|---------------|---------|
| `Authorization` | `Bearer your-token` | OAuth / JWT authentication |
| `X-API-Key` | `your-api-key` | API key authentication |
| `X-Webhook-Secret` | `shared-secret` | Request verification |

---

## Webhook Payloads

### Job Events

For `processing_complete`, `processing_partial`, and `processing_error` events:

```json
{
  "event": "processing_complete",
  "timestamp": "2026-01-31T12:00:00.000Z",
  "data": {
    "title": "Generation Complete",
    "message": "Successfully processed all 10 items.",
    "runId": "run_abc123xyz",
    "totalItems": 10,
    "successCount": 10,
    "errorCount": 0,
    "skippedCount": 0
  }
}
```

| Field | Type | Description |
|-------|------|-------------|
| `event` | string | `processing_complete`, `processing_partial`, or `processing_error` |
| `timestamp` | string | ISO 8601 timestamp when the event occurred |
| `data.title` | string | Human-readable event title |
| `data.message` | string | Detailed description of what happened |
| `data.runId` | string | Unique identifier for the processing job |
| `data.totalItems` | number | Total number of items in the batch |
| `data.successCount` | number | Number of successfully processed items |
| `data.errorCount` | number | Number of failed items |
| `data.skippedCount` | number | Number of skipped items |

**`processing_complete`:** `errorCount` is always 0; `successCount` equals `totalItems`.  
**`processing_partial`:** `errorCount` or `skippedCount` is greater than 0.  
**`processing_error`:** Critical job-level failure; details in `data.message`.

---

### Product Approved Event

When a product's workflow status changes to "approved", the `product_approved` event delivers the complete generated content, including a `schema` array describing the output fields:

```json
{
  "event": "product_approved",
  "timestamp": "2026-02-04T14:30:00.000Z",
  "data": {
    "productId": "SKU-001",
    "output": {
      "en": {
        "title": "Slim Fit Wool Jacket",
        "description": "AI-generated product description...",
        "taxonomy": ["Clothing", "Jackets"]
      }
    },
    "input": {
      "original_title": "Original Title",
      "category": "Menswear"
    },
    "image_paths": [
      {
        "path": "images/product-123.jpg",
        "url": "https://cdn.merchi.ai/storage/v1/object/public/processedImages/images/product-123.jpg"
      }
    ],
    "pdfs": [],
    "workflow_status": "approved",
    "approved_at": "2026-02-04T14:30:00.000Z",
    "schema": [
      { "label": "Product Title", "key": "title", "type": "string" },
      { "label": "Description",   "key": "description", "type": "string" },
      { "label": "Taxonomy",      "key": "taxonomy", "type": "array" }
    ]
  }
}
```

| Field | Type | Description |
|-------|------|-------------|
| `data.productId` | string | Your product identifier |
| `data.output` | object | AI-generated content keyed by locale. Field keys reflect your schema's Output Name configuration. |
| `data.input` | object | Original input data submitted during import |
| `data.image_paths` | array | Product images, each with `path` and `url` |
| `data.pdfs` | array | Product PDFs, each with `storage_path`, `asset_type`, `title`, and `url` |
| `data.workflow_status` | string | Always `approved` |
| `data.approved_at` | string | ISO 8601 timestamp of approval |
| `data.schema` | array | Ordered field descriptors: `label` (display name), `key` (key used in `output`), `type` |

**Use case:** automatically publish approved products to your e-commerce platform, CMS, or PIM system the moment they are approved.

---

## How Output Field Names are Determined

The keys inside `data.output` are controlled by your schema configuration in **Settings → Schema**. Each field has three identifiers:

| Identifier | Description | Used as JSON key? |
|------------|-------------|-------------------|
| **Field Name** | Display label shown in the merchi.ai UI (e.g. "Product Title") | Never |
| **Field Key** | Internal snake_case key used to store data (e.g. `product_title`) | Yes, unless Output Name is set |
| **Output Name** | Optional rename applied to outbound data only (e.g. `title`) | Yes, when set |

The `data.schema` array in every `product_approved` payload reflects this exactly: the `key` in each schema entry matches the key used in `data.output`. This lets your integration build dynamic field mappings without hardcoding names.

**Example:** A field with Field Key `product_title` and Output Name `title` appears as `title` in `output`. Its schema entry is `{ "label": "Product Title", "key": "title", "type": "string" }`.

See [Schema Configuration](https://merchi.ai/help/schema) for a full explanation.

---

## Webhook Status

| Status | Description |
|--------|-------------|
| **Active** | Enabled and last delivery succeeded |
| **Not tested** | Enabled but hasn't received any events yet |
| **Failing** | Recent deliveries failed |
| **Disabled** | Manually disabled |

A webhook is automatically disabled after **5 consecutive failures**. Re-enable it once you've fixed the issue.

---

## Reliability and Retries

- Respond with any `2xx` status to acknowledge receipt
- Each event is delivered **once**. merchi.ai does not currently retry failed deliveries, so a non-`2xx` response or a connection error means that event is not resent
- Respond quickly: acknowledge first, then do the work in a background queue
- Design your endpoint to be **idempotent**, so that replaying data (for example from a backfill) is safe
- To recover anything you missed, use [`GET /approved-products`](https://merchi.ai/api.md#get-approved-products) with `since` set to the time of your last successful delivery. Many integrations use the webhook for speed and a scheduled poll as a safety net

### When `product_approved` fires

The event fires when a product is approved in the platform, either individually or through a bulk action. It does not currently fire for products approved automatically (auto-approve). If your workspace uses auto-approve, collect results with `GET /approved-products` instead.

---

## Integration Examples

### Python (Flask)

```python
from flask import Flask, request

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def handle_webhook():
    data = request.json
    event = data.get('event')

    if event == 'processing_complete':
        run_id = data['data']['runId']
        success_count = data['data']['successCount']
        print(f"Job {run_id} completed: {success_count} items")

    elif event == 'processing_partial':
        error_count = data['data']['errorCount']
        print(f"Job completed with {error_count} errors")

    elif event == 'processing_error':
        print(f"Job failed: {data['data']['message']}")

    elif event == 'product_approved':
        product_id = data['data']['productId']
        output = data['data']['output']
        schema = data['data']['schema']
        print(f"Product {product_id} approved, publishing...")
        # publish_to_ecommerce(product_id, output, schema)

    return {'status': 'ok'}, 200
```

### Zapier

1. Create a Zap with "Webhooks by Zapier" as the trigger
2. Select "Catch Hook"
3. Copy the webhook URL provided by Zapier
4. Add it as a webhook in merchi.ai under Settings → Webhooks

### Slack

Slack expects a specific payload format. Use Zapier or a custom proxy endpoint to transform the merchi.ai payload into Slack's format before forwarding.

---

## Security Best Practices

- **Use HTTPS** — always use a secure HTTPS endpoint
- **Verify requests** — add a secret custom header and validate it in your endpoint
- **Validate payloads** — check the event type and structure before processing
- **Process asynchronously** — queue incoming data for background processing and respond straight away
- **Handle duplicates** — build idempotent handlers; use `runId` or `productId` as deduplication keys

---

## Troubleshooting

### Webhook not receiving events

1. Check the webhook is enabled (not showing "Disabled") in Settings → Webhooks
2. Confirm the URL is correct and publicly accessible
3. Check any firewall rules that might block external requests

### Frequent failures

1. Review the error message shown on the webhooks page
2. Verify any custom authentication headers are correct
3. Test manually with curl using the expected payload
4. Check server logs for incoming request details

### Common errors

| Error | Cause | Fix |
|-------|-------|-----|
| Connection refused | Server not accepting connections | Check server is running |
| Timeout | Endpoint too slow to respond | Acknowledge immediately and queue work asynchronously |
| SSL certificate error | Invalid or expired certificate | Renew SSL certificate |
| 401 / 403 response | Authentication failed | Check custom headers and credentials |
| 404 response | Endpoint path not found | Check the webhook URL |

---

## Webhooks vs Polling

| Aspect | Webhooks | Polling (approved-products endpoint) |
|--------|----------|--------------------------------------|
| **Timing** | Instant, event-driven | Delayed by polling interval |
| **Complexity** | Requires public HTTPS endpoint | Simpler — just call an endpoint |
| **Reliability** | No retries: events sent while your server is down are lost | Catches all data on next poll |
| **Best for** | Real-time publish pipelines | Scheduled batch sync, serverless, or restricted networks |

---

## Related Resources

- [API Reference](https://merchi.ai/api.md) — submit products and retrieve approved content
- [OpenAPI spec](https://merchi.ai/openapi.yaml) — machine-readable API definition
- [Schema documentation](https://merchi.ai/help/schema) — configure output fields and Output Names
- [In-app Webhooks settings](https://app.merchi.ai/settings/webhooks) — manage webhook endpoints
