> ## 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.

# Adicionar Webhook à Loja

> Adiciona um novo webhook à loja, respeitando o limite do plano.

## ➕ Adicionar Webhook à Loja

Este endpoint permite adicionar uma nova URL de webhook à loja, respeitando o limite máximo permitido pelo plano.

### 🔐 Autenticação

Esta rota exige autenticação via API Key, enviada no header da requisição:

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

### 📥 Parâmetros de Rota

| Parâmetro | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `storeId` | `string (UUID)` | Sim | ID da loja |

### 📥 Body da Requisição

| Campo | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `url` | `string` | Sim | URL do endpoint de webhook (URI válida, mínimo 9 e máximo 200 caracteres) |
| `events` | `string[]` | Não | Lista de eventos assinados pelo webhook. Se omitido ou vazio, inscreve em todos os eventos disponíveis. |

### 📋 Exemplo de Requisição

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

### 📊 Exemplo de Resposta (200)

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

> **Atualizar eventos (`PUT` / `PATCH`):** Você também pode enviar `PUT` ou `PATCH /v1/stores/{storeId}/webhooks` com `{ "url": "...", "events": [...] }` (ao menos 1 evento válido obrigatório) para atualizar os eventos de um webhook existente; em caso de sucesso, retorna `200` com `code: "WEBHOOK_UPDATED"`, `"webhook"` e `"events"` (ou `404 WEBHOOK_NOT_FOUND` se a URL não estiver cadastrada).

### ❌ Possíveis Erros

| Status | Code | Quando acontece |
| - | - | - |
| `400` | `STORE_ID_REQUIRED` | Código morto: a rota exige `storeId`; nunca dispara na prática. |
| `400` | `INVALID_URL` | Body inválido ou URL ausente/fora do padrão. |
| `400` | `INVALID_DATA` | Algum evento informado em `events` é inválido. |
| `400` | `OWNER_API_KEY_MISSING` | Dono da loja sem API Key cadastrada para criptografia do teste. |
| `400` | `WEBHOOK_INVALID` | URL respondeu com status HTTP de erro no teste de webhook (se a URL estiver inacessível/inválida por rede, retorna `500 WEBHOOK_ERROR`). |
| `400` | `WEBHOOK_ALREADY_EXISTS` | URL de webhook já cadastrada para a loja. |
| `400` | `WEBHOOK_LIMIT_REACHED` | Limite de webhooks atingido para o plano da loja (inclui o campo `"max"` no JSON de resposta). |
| `401` | `API_KEY_NOT_PROVIDED` | Header `Authorization` não enviado. |
| `401` | `INVALID_API_KEY` | API Key inválida ou não encontrada. |
| `403` | `USER_DISABLED` | Conta do usuário desativada ou excluída. |
| `403` | `NO_ACTIVE_SUBSCRIPTION` | Conta sem plano ativo. |
| `404` | `STORE_NOT_FOUND` | Loja não existe ou não pertence à sua conta. |
| `429` | `RATE_LIMIT_EXCEEDED` | Limite de requisições por minuto do plano excedido. |
| `500` | `WEBHOOK_ERROR` | Falha interna ao processar a requisição. |
| `503` | `SERVICE_UNAVAILABLE` | Serviço temporariamente indisponível. |


## 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.