Webhooks

Recibe notificaciones en tiempo real cuando ocurren eventos en tu tienda de Karrito.

4 min de lecturaapi, webhooks, eventos, integracionActualizado: 18 de marzo de 2026

Que son los webhooks

Los webhooks son notificaciones HTTP que Karrito envia a tu servidor cuando ocurre un evento en tu tienda. En lugar de hacer polling a la API para verificar si hay ordenes nuevas, tu servidor recibe un POST automatico cada vez que algo relevante sucede.

Esto te permite:

  • Notificar a tu equipo en Slack cuando llega un pedido
  • Agregar ordenes automaticamente a Google Sheets
  • Enviar emails de confirmacion con tu propio sistema
  • Sincronizar datos con tu ERP o CRM

Configurar tu webhook

  1. Ve a SettingsIntegraciones en tu panel de admin
  2. En la seccion Webhooks, haz click en Agregar webhook
  3. Ingresa la URL de tu servidor (debe ser HTTPS)
  4. Selecciona los eventos que quieres recibir
  5. Guarda la configuracion

Karrito te mostrara un webhook secret que necesitas para verificar las firmas. Guardalo en un lugar seguro.

Eventos disponibles

Evento Cuando se dispara
order.created Un cliente crea un nuevo pedido
order.updated El estado de un pedido cambia (ej: pending → confirmed)

Formato del payload

Cada webhook envia un POST con Content-Type: application/json y el siguiente formato:

order.created

{
  "event": "order.created",
  "timestamp": "2026-03-17T16:45:00.000Z",
  "data": {
    "id": "clxo1a2b3c4d5e6f7g8h9",
    "orderNumber": "KRT-001042",
    "status": "pending",
    "customerName": "Maria Rodriguez",
    "customerPhone": "+18095551234",
    "items": [
      {
        "productName": "Camisa azul clasica",
        "variantName": "Talla M",
        "quantity": 2,
        "unitPrice": 25.00,
        "subtotal": 50.00
      }
    ],
    "total": 50.00,
    "notes": null,
    "createdAt": "2026-03-17T16:45:00.000Z"
  }
}

order.updated

{
  "event": "order.updated",
  "timestamp": "2026-03-17T17:10:00.000Z",
  "data": {
    "id": "clxo1a2b3c4d5e6f7g8h9",
    "orderNumber": "KRT-001042",
    "previousStatus": "pending",
    "newStatus": "confirmed",
    "updatedAt": "2026-03-17T17:10:00.000Z"
  }
}

Verificar la firma

Cada peticion de webhook incluye un header X-Karrito-Signature con una firma HMAC-SHA256 del body. Verificar esta firma garantiza que la peticion realmente viene de Karrito y no de un tercero.

Como verificar (Node.js)

import crypto from "crypto";

function verifyWebhookSignature(body, signature, secret) {
  const expected = crypto
    .createHmac("sha256", secret)
    .update(body)
    .digest("hex");

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

// En tu handler
app.post("/webhooks/karrito", (req, res) => {
  const signature = req.headers["x-karrito-signature"];
  const isValid = verifyWebhookSignature(
    JSON.stringify(req.body),
    signature,
    process.env.KARRITO_WEBHOOK_SECRET
  );

  if (!isValid) {
    return res.status(401).json({ error: "Firma invalida" });
  }

  const { event, data } = req.body;

  switch (event) {
    case "order.created":
      console.log(`Nuevo pedido: ${data.orderNumber}`);
      break;
    case "order.updated":
      console.log(`Pedido ${data.orderNumber}: ${data.previousStatus} → ${data.newStatus}`);
      break;
  }

  res.status(200).json({ received: true });
});

Importante: Siempre usa crypto.timingSafeEqual para comparar firmas. Comparar strings con === es vulnerable a timing attacks.

Reintentos

Si tu servidor no responde con un status 2xx dentro de 10 segundos, Karrito reintenta la entrega:

Intento Espera
1er reintento 30 segundos
2do reintento 5 minutos
3er reintento 30 minutos

Despues de 3 intentos fallidos, el webhook se marca como fallido. Puedes ver el historial de entregas en SettingsIntegracionesWebhooksVer logs.

Buenas practicas

  • Responde rapido — Tu endpoint debe responder con 200 lo antes posible. Si necesitas procesar datos, hazlo en background (cola de mensajes, worker) y responde inmediato
  • Maneja duplicados — En casos raros, un webhook puede entregarse mas de una vez. Usa el id del recurso para deduplicar
  • Verifica siempre — Nunca confies en un webhook sin verificar la firma, incluso en desarrollo
  • Usa HTTPS — Solo aceptamos URLs con HTTPS. Las URLs HTTP se rechazan

Ejemplo completo: servidor con Express

import express from "express";
import crypto from "crypto";

const app = express();
app.use(express.json());

const WEBHOOK_SECRET = process.env.KARRITO_WEBHOOK_SECRET;

app.post("/webhooks/karrito", (req, res) => {
  // 1. Verificar firma
  const signature = req.headers["x-karrito-signature"];
  const expected = crypto
    .createHmac("sha256", WEBHOOK_SECRET)
    .update(JSON.stringify(req.body))
    .digest("hex");

  if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
    return res.status(401).json({ error: "Firma invalida" });
  }

  // 2. Procesar evento
  const { event, data } = req.body;

  if (event === "order.created") {
    // Enviar notificacion a Slack, agregar a Google Sheets, etc.
    console.log(`Nuevo pedido ${data.orderNumber}: $${data.total}`);
  }

  // 3. Responder rapido
  res.status(200).json({ received: true });
});

app.listen(3000, () => console.log("Webhook server en puerto 3000"));

Siguiente paso

Revisa los limites de uso de la API para planificar tus integraciones.