Webhooks

SalchiMail can call your server when something happens, so you do not have to poll. Endpoints are created in the dashboard at app.salchimail.com. Each endpoint has an HTTPS URL and its own signing secret.

Events

type Sent when
batch.completed A batch reaches completed or failed. Check data.batch.status. Not sent for batches you cancel
credits.low A credit balance crosses the threshold set in the dashboard (default: 10% of the last grant)

Each delivery is a POST with a JSON event:

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 carries the batch, not its rows: fetch them with GET /batches/{batch_id}/results (Clean a list in batches).

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 is sent once each time a balance crosses the threshold. It is sent again only after the balance has been topped up above the threshold and falls below it again.

Verify the signature

Anyone can post to your URL, so check that each delivery comes from SalchiMail before you trust it. Every delivery carries this header:

HTTP
SalchiMail-Signature: t=1794909701,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
  • t is the time of the delivery, in Unix seconds.
  • v1 is HMAC-SHA256(endpoint_secret, "<t>.<raw request body>"), in hexadecimal.

To verify a delivery:

  1. Read the raw body, byte for byte, before any JSON parsing. Re-serialising the JSON changes the bytes and breaks the signature.
  2. Compute the HMAC-SHA256 of <t>.<raw body> with your endpoint secret.
  3. Compare it with v1 using a constant-time comparison.
  4. Reject the delivery when t is more than 5 minutes old. This stops replays.
  5. While a secret is being rotated the header can carry several v1 values. Accept the delivery if any of them matches.

These servers verify the signature and handle both events. They read the secret from 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))
}

In a framework, make sure you get the raw body. A JSON body parser that runs first leaves you without the bytes that were signed.

Answer fast, work later

  • Answer with any 2xx within 10 seconds. Queue slow work and do it after you answer.
  • Any other answer, or a timeout, is retried with exponential backoff for up to 24 hours (8 attempts).
  • A delivery can arrive more than once and out of order. Deduplicate by the event id, which is the same across retries.
  • Every event carries livemode, like the rest of the API objects.

Checklist

  • The endpoint URL uses HTTPS.
  • The signature is verified against the raw body with a constant-time comparison.
  • Deliveries older than 5 minutes are rejected.
  • Events are deduplicated by id.
  • The handler answers 2xx before doing slow work.
  • Unknown event types are answered with 2xx and ignored: new types may be added.

View this page as Markdown