> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cabrapi.com.br/llms.txt
> Use this file to discover all available pages before exploring further.

# Agregar Webhook a la Tienda

> Agrega un nuevo webhook a la tienda, respetando el límite del plan.

## ➕ Agregar Webhook a la Tienda

Este endpoint permite agregar una nueva URL de webhook a la tienda, respetando el límite máximo permitido por el plan.

### 🔐 Autenticación

Esta ruta requiere autenticación mediante API Key, enviada en el header de la solicitud:

```http theme={null}
Authorization: TU_API_KEY_AQUI
```

### 📥 Parámetros de Ruta

| Parámetro | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| `storeId` | `string (UUID)` | Sí | ID de la tienda |

### 📥 Body de la Solicitud

| Campo | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| `url` | `string` | Sí | URL del endpoint de webhook (URI válida, mínimo 9 y máximo 200 caracteres) |
| `events` | `string[]` | No | Lista de eventos suscritos por el webhook. Si se omite o está vacía, se suscribe a todos los eventos disponibles. |

### 📋 Ejemplo de Solicitud

```bash theme={null}
curl --location --request POST "https://api.cabrapi.com.br/v1/stores/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/webhooks" \
--header "Authorization: TU_API_KEY_AQUI" \
--header "Content-Type: application/json" \
--data '{
  "url": "https://meusistema.com/callback",
  "events": [
    "payment.created",
    "payment.status.changed"
  ]
}'
```

### 📊 Ejemplo de Respuesta (200)

```json theme={null}
{
  "code": "WEBHOOK_ADDED",
  "webhook": "https://meusistema.com/callback",
  "events": [
    "payment.created",
    "payment.status.changed"
  ]
}
```

> **Actualizar eventos (`PUT` / `PATCH`):** También puedes enviar `PUT` o `PATCH /v1/stores/{storeId}/webhooks` con `{ "url": "...", "events": [...] }` (al menos 1 evento válido obligatorio) para actualizar los eventos de un webhook existente; en caso de éxito, retorna `200` con `code: "WEBHOOK_UPDATED"`, `"webhook"` y `"events"` (o `404 WEBHOOK_NOT_FOUND` si la URL no está registrada).

### ❌ Posibles Errores

| Status | Code | Cuándo ocurre |
| - | - | - |
| `400` | `STORE_ID_REQUIRED` | Código muerto: la ruta exige `storeId`; nunca se dispara en la práctica. |
| `400` | `INVALID_URL` | Body inválido o URL ausente/fuera del patrón. |
| `400` | `INVALID_DATA` | Algún evento informado en `events` es inválido. |
| `400` | `OWNER_API_KEY_MISSING` | Dueño de la tienda sin API Key registrada para la criptografía de la prueba. |
| `400` | `WEBHOOK_INVALID` | La URL respondió con status HTTP de error en la prueba de webhook (si la URL está inaccesible/inválida por red, retorna `500 WEBHOOK_ERROR`). |
| `400` | `WEBHOOK_ALREADY_EXISTS` | URL de webhook ya registrada para la tienda. |
| `400` | `WEBHOOK_LIMIT_REACHED` | Límite de webhooks alcanzado para el plan de la tienda (incluye el campo `"max"` en el JSON de respuesta). |
| `401` | `API_KEY_NOT_PROVIDED` | Header `Authorization` no enviado. |
| `401` | `INVALID_API_KEY` | API Key inválida o no encontrada. |
| `403` | `USER_DISABLED` | Cuenta de usuario desactivada o eliminada. |
| `403` | `NO_ACTIVE_SUBSCRIPTION` | Cuenta sin plan activo. |
| `404` | `STORE_NOT_FOUND` | La tienda no existe o no pertenece a su cuenta. |
| `429` | `RATE_LIMIT_EXCEEDED` | Límite de solicitudes por minuto del plan excedido. |
| `500` | `WEBHOOK_ERROR` | Fallo interno al procesar la solicitud. |
| `503` | `SERVICE_UNAVAILABLE` | Servicio temporalmente no disponible. |


## OpenAPI

````yaml POST /stores/{storeId}/webhooks
openapi: 3.1.0
info:
  title: caBRAPI
  version: 1.0.0
servers:
  - url: https://api.cabrapi.com.br/v1
security: []
paths:
  /stores/{storeId}/webhooks:
    post:
      tags:
        - Webhooks
      summary: Add webhook to store
      operationId: createWebhook
      parameters:
        - $ref: '#/components/parameters/StoreId'
      requestBody:
        content:
          application/json:
            schema:
              properties:
                events:
                  items:
                    enum:
                      - store.created
                      - store.updated
                      - store.deleted
                      - store.reordered
                      - product.created
                      - product.updated
                      - product.deleted
                      - product.reordered
                      - category.created
                      - category.updated
                      - category.deleted
                      - category.reordered
                      - coupon.created
                      - coupon.updated
                      - coupon.deleted
                      - coupon.reordered
                      - page.upserted
                      - page.deleted
                      - affiliate.created
                      - affiliate.updated
                      - affiliate.deleted
                      - payment.created
                      - payment.updated
                      - payment.deleted
                      - payment.status.changed
                    type: string
                  type: array
                url:
                  format: uri
                  maxLength: 200
                  minLength: 9
                  type: string
              required:
                - url
              type: object
        description: Webhook URL and optional event subscriptions.
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                properties:
                  code:
                    example: WEBHOOK_ADDED
                    type: string
                  events:
                    items:
                      enum:
                        - store.created
                        - store.updated
                        - store.deleted
                        - store.reordered
                        - product.created
                        - product.updated
                        - product.deleted
                        - product.reordered
                        - category.created
                        - category.updated
                        - category.deleted
                        - category.reordered
                        - coupon.created
                        - coupon.updated
                        - coupon.deleted
                        - coupon.reordered
                        - page.upserted
                        - page.deleted
                        - affiliate.created
                        - affiliate.updated
                        - affiliate.deleted
                        - payment.created
                        - payment.updated
                        - payment.deleted
                        - payment.status.changed
                      type: string
                    type: array
                  webhook:
                    format: uri
                    type: string
                required:
                  - code
                  - webhook
                  - events
                type: object
          description: Webhook added.
        '400':
          content:
            application/json:
              schema:
                type: object
                properties:
                  code:
                    example: WEBHOOK_LIMIT_REACHED
                    type: string
                  max:
                    example: 2
                    type: integer
                required:
                  - code
          description: >-
            Invalid request (e.g. INVALID_URL, INVALID_DATA,
            OWNER_API_KEY_MISSING, WEBHOOK_INVALID, WEBHOOK_ALREADY_EXISTS,
            WEBHOOK_LIMIT_REACHED).
        '401':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Missing or invalid API key.
        '403':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Forbidden (inactive plan or insufficient permissions).
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Resource not found.
        '429':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Rate limit exceeded.
        '500':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Internal server error.
        '503':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Service unavailable.
      security:
        - ApiKey: []
components:
  parameters:
    StoreId:
      in: path
      name: storeId
      required: true
      schema:
        type: string
        minLength: 1
        maxLength: 50
  schemas:
    Error:
      properties:
        code:
          example: STORE_NOT_FOUND
          type: string
      required:
        - code
      type: object
  securitySchemes:
    ApiKey:
      in: header
      name: Authorization
      type: apiKey
      x-default: YOUR_API_KEY_HERE

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.