Webhooks

SalchiMail puede llamar a tu servidor cuando ocurre algo, para que no tengas que consultar. Los endpoints se crean en el panel, en app.salchimail.com. Cada endpoint tiene una URL HTTPS y su propio secreto de firma.

Eventos

type Cuándo se envía
batch.completed Un lote llega a completed o failed. Comprueba data.batch.status. No se envía para los lotes que cancelas
credits.low Un saldo de créditos cruza el umbral configurado en el panel (por defecto, el 10 % de la última concesión)

Cada entrega es un POST con un evento en JSON:

JSON
{
  "id": "evt_9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f",
  "object": "event",
  "type": "batch.completed",
  "livemode": true,
  "created_at": "2026-11-17T10:21:41Z",
  "data": {
    "batch": {
      "id": "bat_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b",
      "object": "batch",
      "livemode": true,
      "name": "November newsletter",
      "source": "json",
      "mode": "mailbox",
      "status": "completed",
      "total": 3,
      "unique": 3,
      "processed": 3,
      "summary": {
        "valid": 1,
        "invalid": 1,
        "risky": 0,
        "unknown": 1
      },
      "credits": {
        "type": "mailbox",
        "reserved": 0,
        "charged": 2
      },
      "created_at": "2026-11-17T09:50:00Z",
      "started_at": "2026-11-17T09:50:02Z",
      "finished_at": "2026-11-17T10:21:40Z",
      "deadline_at": "2026-11-23T09:50:02Z",
      "results_expire_at": "2026-12-17T10:21:40Z"
    }
  }
}

batch.completed trae el lote, no sus filas: descárgalas con GET /batches/{batch_id}/results (Limpieza de listas por lotes).

JSON
{
  "id": "evt_0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a",
  "object": "event",
  "type": "credits.low",
  "livemode": true,
  "created_at": "2026-11-17T11:02:13Z",
  "data": {
    "credit_type": "mailbox",
    "remaining": 249,
    "threshold": 250
  }
}

credits.low se envía una vez cada vez que un saldo cruza el umbral. Solo vuelve a enviarse cuando el saldo se ha recargado por encima del umbral y cae otra vez por debajo.

Verifica la firma

Cualquiera puede hacer un POST a tu URL, así que comprueba que cada entrega viene de SalchiMail antes de fiarte de ella. Toda entrega lleva esta cabecera:

HTTP
SalchiMail-Signature: t=1794909701,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
  • t es la hora de la entrega, en segundos Unix.
  • v1 es HMAC-SHA256(secreto_del_endpoint, "<t>.<cuerpo crudo de la petición>"), en hexadecimal.

Para verificar una entrega:

  1. Lee el cuerpo crudo, byte a byte, antes de interpretar el JSON. Volver a serializar el JSON cambia los bytes y rompe la firma.
  2. Calcula el HMAC-SHA256 de <t>.<cuerpo crudo> con el secreto de tu endpoint.
  3. Compáralo con v1 usando una comparación en tiempo constante.
  4. Rechaza la entrega cuando t tenga más de 5 minutos. Así evitas repeticiones maliciosas.
  5. Mientras se rota un secreto, la cabecera puede traer varios valores v1. Acepta la entrega si alguno coincide.

Estos servidores verifican la firma y atienden los dos eventos. Leen el secreto de SALCHIMAIL_WEBHOOK_SECRET.

JavaScript / TypeScript
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";

function isValidSignature(rawBody, header, secret, toleranceSeconds = 300) {
  const parts = (header ?? "").split(",").map((part) => part.split("="));
  const timestamp = parts.find(([key]) => key === "t")?.[1];
  const age = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (!timestamp || !(age <= toleranceSeconds)) return false;

  const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest();
  // Several v1 values can be present while a secret is rotated: accept if any matches.
  return parts.some(([key, value]) => {
    const signature = Buffer.from((key === "v1" && value) || "", "hex");
    return signature.length === expected.length && timingSafeEqual(signature, expected);
  });
}

createServer(async (req, res) => {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  const rawBody = Buffer.concat(chunks); // the raw bytes, before any JSON parsing

  if (!isValidSignature(rawBody, req.headers["salchimail-signature"], process.env.SALCHIMAIL_WEBHOOK_SECRET)) {
    res.writeHead(400).end();
    return;
  }
  const event = JSON.parse(rawBody);
  // Deduplicate by event.id, queue the work and answer within 10 seconds.
  if (event.type === "batch.completed") {
    console.log("batch finished:", event.data.batch.id, event.data.batch.status);
  } else if (event.type === "credits.low") {
    console.log("low credits:", event.data.credit_type, event.data.remaining);
  }
  res.writeHead(204).end();
}).listen(process.env.PORT ?? 3000);
Python
import hashlib
import hmac
import json
import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET = os.environ["SALCHIMAIL_WEBHOOK_SECRET"].encode()


def is_valid_signature(raw_body: bytes, header: str, secret: bytes, tolerance: int = 300) -> bool:
    parts = [part.split("=", 1) for part in header.split(",") if "=" in part]
    timestamp = next((value for key, value in parts if key == "t"), "")
    if not timestamp.isascii() or not timestamp.isdigit() or abs(time.time() - int(timestamp)) > tolerance:
        return False
    expected = hmac.new(secret, timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    # Several v1 values can be present while a secret is rotated: accept if any matches.
    return any(hmac.compare_digest(expected.encode(), value.encode()) for key, value in parts if key == "v1")


class Webhook(BaseHTTPRequestHandler):
    def do_POST(self):
        # The raw bytes, before any JSON parsing.
        raw_body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        if not is_valid_signature(raw_body, self.headers.get("SalchiMail-Signature", ""), SECRET):
            self.send_response(400)
            self.end_headers()
            return
        event = json.loads(raw_body)
        # Deduplicate by event["id"], queue the work and answer within 10 seconds.
        if event["type"] == "batch.completed":
            print("batch finished:", event["data"]["batch"]["id"], event["data"]["batch"]["status"], flush=True)
        elif event["type"] == "credits.low":
            print("low credits:", event["data"]["credit_type"], event["data"]["remaining"], flush=True)
        self.send_response(204)
        self.end_headers()


HTTPServer(("", int(os.environ.get("PORT", 3000))), Webhook).serve_forever()
PHP
<?php
function is_valid_signature(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
{
    $timestamp = "";
    $signatures = [];
    foreach (explode(",", $header) as $part) {
        [$key, $value] = array_pad(explode("=", $part, 2), 2, "");
        if ($key === "t") {
            $timestamp = $value;
        } elseif ($key === "v1") {
            $signatures[] = $value;
        }
    }
    if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > $tolerance) {
        return false;
    }
    $expected = hash_hmac("sha256", "$timestamp.$rawBody", $secret);
    // Several v1 values can be present while a secret is rotated: accept if any matches.
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}

$rawBody = file_get_contents("php://input"); // the raw bytes, before any JSON parsing
$header = $_SERVER["HTTP_SALCHIMAIL_SIGNATURE"] ?? "";
if (!is_valid_signature($rawBody, $header, getenv("SALCHIMAIL_WEBHOOK_SECRET"))) {
    http_response_code(400);
    exit;
}
$event = json_decode($rawBody, true);
// Deduplicate by $event["id"], queue the work and answer within 10 seconds.
if ($event["type"] === "batch.completed") {
    error_log("batch finished: {$event['data']['batch']['id']} {$event['data']['batch']['status']}");
} elseif ($event["type"] === "credits.low") {
    error_log("low credits: {$event['data']['credit_type']} {$event['data']['remaining']}");
}
http_response_code(204);
Go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func isValidSignature(rawBody []byte, header, secret string, tolerance time.Duration) bool {
	var timestamp string
	var signatures []string
	for _, part := range strings.Split(header, ",") {
		key, value, _ := strings.Cut(part, "=")
		switch key {
		case "t":
			timestamp = value
		case "v1":
			signatures = append(signatures, value)
		}
	}
	seconds, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil || time.Since(time.Unix(seconds, 0)).Abs() > tolerance {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(timestamp + "."))
	mac.Write(rawBody)
	expected := mac.Sum(nil)
	// Several v1 values can be present while a secret is rotated: accept if any matches.
	for _, signature := range signatures {
		if got, err := hex.DecodeString(signature); err == nil && hmac.Equal(got, expected) {
			return true
		}
	}
	return false
}

type event struct {
	ID   string `json:"id"`
	Type string `json:"type"`
	Data struct {
		Batch struct {
			ID     string `json:"id"`
			Status string `json:"status"`
		} `json:"batch"`
		CreditType string `json:"credit_type"`
		Remaining  int    `json:"remaining"`
	} `json:"data"`
}

func main() {
	secret := os.Getenv("SALCHIMAIL_WEBHOOK_SECRET")

	http.HandleFunc("POST /webhooks/salchimail", func(w http.ResponseWriter, r *http.Request) {
		// The raw bytes, before any JSON parsing.
		rawBody, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
		if err != nil || !isValidSignature(rawBody, r.Header.Get("SalchiMail-Signature"), secret, 5*time.Minute) {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		var e event
		if err := json.Unmarshal(rawBody, &e); err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		// Deduplicate by e.ID, queue the work and answer within 10 seconds.
		switch e.Type {
		case "batch.completed":
			log.Println("batch finished:", e.Data.Batch.ID, e.Data.Batch.Status)
		case "credits.low":
			log.Println("low credits:", e.Data.CreditType, e.Data.Remaining)
		}
		w.WriteHeader(http.StatusNoContent)
	})

	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	log.Fatal(http.ListenAndServe(":"+port, nil))
}

En un framework, asegúrate de recibir el cuerpo crudo. Si antes se ejecuta un intérprete de JSON, te quedas sin los bytes que se firmaron.

Responde rápido, trabaja después

  • Responde con cualquier 2xx en menos de 10 segundos. Encola el trabajo lento y hazlo después de responder.
  • Cualquier otra respuesta, o un tiempo de espera agotado, se reintenta con espera exponencial durante un máximo de 24 horas (8 intentos).
  • Una entrega puede llegar más de una vez y fuera de orden. Deduplica por el id del evento, que es el mismo en todos los reintentos.
  • Todos los eventos llevan livemode, como el resto de objetos de la API.

Lista de comprobación

  • La URL del endpoint usa HTTPS.
  • La firma se verifica contra el cuerpo crudo con una comparación en tiempo constante.
  • Las entregas con más de 5 minutos se rechazan.
  • Los eventos se deduplican por id.
  • El manejador responde 2xx antes de hacer el trabajo lento.
  • Los tipos de evento desconocidos se responden con 2xx y se ignoran: pueden añadirse tipos nuevos.

Ver esta página en Markdown