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

# Webhooks

> Receba eventos de pedidos em tempo real via webhooks.

## Visao geral

Webhooks permitem que seu sistema receba notificacoes automaticas quando eventos ocorrem no YaVendio, como a criacao de um novo pedido. Em vez de consultar a API periodicamente, o YaVendio envia um `POST` HTTP para a URL que voce configurar.

## Eventos disponiveis

| Evento | Descricao |
| - | - |
| `order.created` | Um novo pedido e criado |
| `order.status_changed` | O status do pedido muda |

## Configurar um webhook

### 1. Registrar sua URL

```bash theme={null}
curl -X POST https://api.ya.onl/v1/webhooks \
  -H "X-API-Key: yv_live_v1_sua_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://seu-servidor.com/webhooks/yavendio",
    "events": ["order.created"],
    "description": "Notificacoes de pedidos"
  }'
```

Resposta:

```json theme={null}
{
  "id": "ep_2bNzYPyBRuC1mMYXXAvgSSuz4Fz",
  "url": "https://seu-servidor.com/webhooks/yavendio",
  "events": ["order.created"],
  "is_active": true,
  "description": "Notificacoes de pedidos",
  "created_at": "2026-03-22T10:00:00Z",
  "secret": "whsec_5LTSI03vOvKsLGbAibiB7GGgLDdJMtGk"
}
```

<Warning>
  O campo `secret` so e mostrado uma vez, ao criar o webhook. Guarde-o com seguranca — voce precisara dele para verificar as assinaturas.
</Warning>

### 2. Verificar a assinatura

Cada entrega inclui tres headers para verificacao:

| Header | Descricao |
| - | - |
| `Svix-Id` | ID unico da mensagem |
| `Svix-Timestamp` | Timestamp UNIX da assinatura |
| `Svix-Signature` | Assinatura HMAC-SHA256 do payload |

Exemplo de verificacao em Python:

```python theme={null}
import hmac
import hashlib
import base64

def verify_webhook(payload: bytes, headers: dict, secret: str) -> bool:
    msg_id = headers["Svix-Id"]
    timestamp = headers["Svix-Timestamp"]
    signature = headers["Svix-Signature"]

    # Construir a mensagem assinada
    to_sign = f"{msg_id}.{timestamp}.{payload.decode()}".encode()

    # Decodificar o secret (remover prefixo "whsec_" e decodificar base64)
    secret_bytes = base64.b64decode(secret.replace("whsec_", ""))

    # Calcular a assinatura esperada
    expected = base64.b64encode(
        hmac.new(secret_bytes, to_sign, hashlib.sha256).digest()
    ).decode()

    # Comparar com a assinatura recebida (formato: "v1,<base64>")
    received = signature.split(",")[1] if "," in signature else signature
    return hmac.compare_digest(expected, received)
```

Voce tambem pode usar a biblioteca oficial do Svix:

```bash theme={null}
pip install svix
```

```python theme={null}
from svix.webhooks import Webhook

wh = Webhook("whsec_5LTSI03vOvKsLGbAibiB7GGgLDdJMtGk")
payload = wh.verify(request.body, request.headers)
```

### 3. Formato do payload

O payload de `order.created` contem o pedido completo em formato JSON:

```json theme={null}
{
  "id": 176,
  "created_at": "2026-03-22T04:39:33.560884Z",
  "merchant_id": 1113,
  "currency": "PEN",
  "total_amount": "205.0",
  "delivery_fee": "10.0",
  "status": "pending",
  "payment_terms": "pending",
  "payment_method": "yape",
  "customer": {
    "name": "Juan Perez",
    "phone_number": "51999000111"
  },
  "variants": [
    {
      "id": 6110,
      "name": "AZUL - S",
      "quantity": 1,
      "base_price": 205.0
    }
  ]
}
```

<Note>
  O formato do payload e o esquema interno do YaVendio. Se a estrutura mudar (por exemplo, um novo campo for adicionado), e responsabilidade do receptor se adaptar.
</Note>

## Gerenciar webhooks

### Listar webhooks registrados

```bash theme={null}
curl https://api.ya.onl/v1/webhooks -H "X-API-Key: yv_live_v1_sua_api_key"
```

### Desativar um webhook

```bash theme={null}
curl -X PATCH https://api.ya.onl/v1/webhooks/{webhook_id} \
  -H "X-API-Key: yv_live_v1_sua_api_key" \
  -H "Content-Type: application/json" \
  -d '{"is_active": false}'
```

### Excluir um webhook

```bash theme={null}
curl -X DELETE https://api.ya.onl/v1/webhooks/{webhook_id} \
  -H "X-API-Key: yv_live_v1_sua_api_key"
```

### Consultar tentativas de entrega

```bash theme={null}
curl https://api.ya.onl/v1/webhooks/{webhook_id}/deliveries/{message_id} \
  -H "X-API-Key: yv_live_v1_sua_api_key"
```

## Tentativas

Se seu servidor nao responder com um codigo `2xx`, o YaVendio tentara novamente automaticamente com backoff exponencial. Apos multiplas falhas consecutivas, o webhook sera desativado automaticamente.

## Limites

* Maximo **20 webhooks** por comerciante
* Timeout de entrega: **30 segundos**
* Os eventos sao entregues em ordem cronologica, mas a entrega exatamente uma vez nao e garantida — projete seu receptor para ser **idempotente**


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