Skip to content
Shortcut: /, ⌘K or Ctrl+K

Set up a webhook endpoint

Receive Polymorfa events at your server, verify each one and handle retries.

View as Markdown

Build an HTTPS endpoint that receives events for a project, register it with Polymorfa, verify each request's signature and send it a test event. At the end, your server receives events such as message.received and processes each one once.

Before you begin#

  • A project and its ID.
  • A team key or project token with Webhooks → Write (webhooks:manage). See API keys.
  • A public HTTPS URL that reaches your server. To develop on your own machine first, use polymorfa listen.

Build the handler #

Your handler must read the raw request body, check the X-Webhook-Signature header against it, store the event and answer 2xx. The signature is the lowercase hex HMAC-SHA256 of the exact body bytes, keyed with the endpoint's signing secret.

Anyone can send a request to a public URL, so cap the body size before you read or verify it. Each sample sets MAX_WEBHOOK_BYTES to 2 MiB and answers 413 for a larger request without buffering it. This is a sample default, not a documented Polymorfa maximum. Raise it if your events grow, but keep a limit.

Node.js
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";

const secret = process.env.POLYMORFA_WEBHOOK_SECRET;
if (!secret) throw new Error("Set POLYMORFA_WEBHOOK_SECRET to the endpoint signing secret.");

const app = express();
const MAX_WEBHOOK_BYTES = 2 * 1024 * 1024;

function validSignature(body, signature, secret) {
  const expected = createHmac("sha256", secret).update(body).digest();
  const received = Buffer.from(signature, "hex");
  return received.length === expected.length && timingSafeEqual(received, expected);
}

// express.raw rejects a larger body with 413, using Content-Length and the bytes streamed.
app.post("/polymorfa/webhook", express.raw({ type: "application/json", limit: MAX_WEBHOOK_BYTES }), async (req, res) => {
  const signature = req.header("x-webhook-signature") ?? "";
  if (!validSignature(req.body, signature, secret)) {
    return res.sendStatus(400);
  }

  const event = JSON.parse(req.body.toString("utf8"));
  if (await alreadyProcessed(event.id)) return res.sendStatus(200);
  await saveEvent(event);

  res.sendStatus(200);
});

app.listen(3000);
Python
import hashlib
import hmac
import json
import os

from flask import Flask, request

SECRET = os.environ.get("POLYMORFA_WEBHOOK_SECRET")
if not SECRET:
    raise SystemExit("Set POLYMORFA_WEBHOOK_SECRET to the endpoint signing secret.")

MAX_WEBHOOK_BYTES = 2 * 1024 * 1024

app = Flask(__name__)
# Flask answers 413 when the body is larger, without reading it all.
app.config["MAX_CONTENT_LENGTH"] = MAX_WEBHOOK_BYTES


def valid_signature(body: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)


@app.post("/polymorfa/webhook")
def polymorfa_webhook():
    body = request.get_data()
    signature = request.headers.get("X-Webhook-Signature", "")
    if not valid_signature(body, signature, SECRET):
        return "", 400

    event = json.loads(body)
    if not already_processed(event["id"]):
        save_event(event)
    return "", 200


if __name__ == "__main__":
    app.run(port=3000)
Go
package main

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

const maxWebhookBytes = 2 * 1024 * 1024 // MAX_WEBHOOK_BYTES

func validSignature(body []byte, signature, secret string) bool {
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write(body)
	return hmac.Equal([]byte(hex.EncodeToString(mac.Sum(nil))), []byte(signature))
}

func main() {
	secret := os.Getenv("POLYMORFA_WEBHOOK_SECRET")
	if secret == "" {
		log.Fatal("Set POLYMORFA_WEBHOOK_SECRET to the endpoint signing secret.")
	}
	http.HandleFunc("POST /polymorfa/webhook", func(w http.ResponseWriter, r *http.Request) {
		r.Body = http.MaxBytesReader(w, r.Body, maxWebhookBytes)
		body, err := io.ReadAll(r.Body)
		var tooLarge *http.MaxBytesError
		if errors.As(err, &tooLarge) {
			w.WriteHeader(http.StatusRequestEntityTooLarge)
			return
		}
		if err != nil || !validSignature(body, r.Header.Get("X-Webhook-Signature"), secret) {
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		var event struct {
			ID string `json:"id"`
		}
		if err := json.Unmarshal(body, &event); err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		if !alreadyProcessed(event.ID) {
			saveEvent(body)
		}
		w.WriteHeader(http.StatusOK)
	})
	log.Fatal(http.ListenAndServe(":3000", nil))
}
PHP
<?php
// Serve this file at /polymorfa/webhook.

$secret = getenv('POLYMORFA_WEBHOOK_SECRET');
if ($secret === false || $secret === '') {
    throw new RuntimeException('Set POLYMORFA_WEBHOOK_SECRET to the endpoint signing secret.');
}

const MAX_WEBHOOK_BYTES = 2 * 1024 * 1024;

if ((int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > MAX_WEBHOOK_BYTES) {
    http_response_code(413);
    exit;
}
// Read one byte past the limit so a body without Content-Length is caught too.
$body = file_get_contents('php://input', false, null, 0, MAX_WEBHOOK_BYTES + 1);
if ($body === false || strlen($body) > MAX_WEBHOOK_BYTES) {
    http_response_code(413);
    exit;
}
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', $body, $secret);
if (!hash_equals($expected, $signature)) {
    http_response_code(400);
    exit;
}

$event = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
if (!alreadyProcessed($event['id'])) {
    saveEvent($event);
}
http_response_code(200);
Ruby
require "json"
require "openssl"
require "sinatra"

secret = ENV["POLYMORFA_WEBHOOK_SECRET"].to_s
abort "Set POLYMORFA_WEBHOOK_SECRET to the endpoint signing secret." if secret.empty?

set :port, 3000

MAX_WEBHOOK_BYTES = 2 * 1024 * 1024

post "/polymorfa/webhook" do
  halt 413 if request.content_length.to_i > MAX_WEBHOOK_BYTES
  # Read one byte past the limit so a body without Content-Length is caught too.
  body = request.body.read(MAX_WEBHOOK_BYTES + 1).to_s
  halt 413 if body.bytesize > MAX_WEBHOOK_BYTES
  signature = request.env["HTTP_X_WEBHOOK_SIGNATURE"].to_s
  expected = OpenSSL::HMAC.hexdigest("SHA256", secret, body)
  halt 400 unless OpenSSL.secure_compare(expected, signature)

  event = JSON.parse(body)
  save_event(event) unless already_processed(event["id"])
  status 200
end
Java
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class WebhookServer {
    static final int MAX_WEBHOOK_BYTES = 2 * 1024 * 1024;

    public static void main(String[] args) throws Exception {
        var secret = System.getenv("POLYMORFA_WEBHOOK_SECRET");
        if (secret == null || secret.isEmpty()) {
            throw new IllegalStateException("Set POLYMORFA_WEBHOOK_SECRET to the endpoint signing secret.");
        }
        var server = HttpServer.create(new InetSocketAddress(3000), 0);
        server.createContext("/polymorfa/webhook", exchange -> {
            try {
                var declared = exchange.getRequestHeaders().getFirst("Content-Length");
                if (declared != null && declared.matches("\\d+") && Long.parseLong(declared) > MAX_WEBHOOK_BYTES) {
                    exchange.sendResponseHeaders(413, -1);
                    return;
                }
                // Read one byte past the limit so a chunked body is caught too.
                var body = exchange.getRequestBody().readNBytes(MAX_WEBHOOK_BYTES + 1);
                if (body.length > MAX_WEBHOOK_BYTES) {
                    exchange.sendResponseHeaders(413, -1);
                    return;
                }
                var signature = exchange.getRequestHeaders().getFirst("X-Webhook-Signature");
                if (!"POST".equals(exchange.getRequestMethod()) || signature == null || !validSignature(body, signature, secret)) {
                    exchange.sendResponseHeaders(400, -1);
                    return;
                }
                var payload = new String(body, StandardCharsets.UTF_8);
                // eventId reads the event "id" with your JSON library. Skip IDs you already stored.
                var id = eventId(payload);
                if (!alreadyProcessed(id)) saveEvent(payload);
                exchange.sendResponseHeaders(200, -1);
            } finally {
                exchange.close();
            }
        });
        server.start();
    }

    static boolean validSignature(byte[] body, String signature, String secret) {
        try {
            var mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            var expected = HexFormat.of().formatHex(mac.doFinal(body));
            return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8));
        } catch (Exception error) {
            return false;
        }
    }
}
C#
// An ASP.NET Core project (Microsoft.NET.Sdk.Web).
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

var app = WebApplication.Create(args);
var secret = Environment.GetEnvironmentVariable("POLYMORFA_WEBHOOK_SECRET");
if (string.IsNullOrEmpty(secret))
{
    throw new InvalidOperationException("Set POLYMORFA_WEBHOOK_SECRET to the endpoint signing secret.");
}

const int MaxWebhookBytes = 2 * 1024 * 1024; // MAX_WEBHOOK_BYTES

app.MapPost("/polymorfa/webhook", async (HttpRequest request) =>
{
    if (request.ContentLength > MaxWebhookBytes) return Results.StatusCode(StatusCodes.Status413PayloadTooLarge);

    // Count bytes while reading so a chunked body cannot grow past the limit.
    using var buffer = new MemoryStream();
    var chunk = new byte[16 * 1024];
    int read;
    while ((read = await request.Body.ReadAsync(chunk)) > 0)
    {
        if (buffer.Length + read > MaxWebhookBytes) return Results.StatusCode(StatusCodes.Status413PayloadTooLarge);
        buffer.Write(chunk, 0, read);
    }
    var body = buffer.ToArray();
    var expected = Convert.ToHexString(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), body)).ToLowerInvariant();
    var signature = request.Headers["X-Webhook-Signature"].ToString();
    if (!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(signature)))
    {
        return Results.BadRequest();
    }

    using var webhookEvent = JsonDocument.Parse(body);
    var id = webhookEvent.RootElement.GetProperty("id").GetString() ?? "";
    if (!AlreadyProcessed(id)) SaveEvent(webhookEvent);
    return Results.Ok();
});

app.Run("http://localhost:3000");
Rust
// Cargo.toml dependencies: axum = "0.8", hex = "0.4", hmac = "0.12", serde_json = "1",
// sha2 = "0.10", tokio = { version = "1", features = ["full"] }
use axum::{body::Bytes, extract::{DefaultBodyLimit, State}, http::{HeaderMap, StatusCode}, routing::post, Router};
use hmac::{Hmac, Mac};
use sha2::Sha256;

const MAX_WEBHOOK_BYTES: usize = 2 * 1024 * 1024;

// The Bytes extractor answers 413 once the body passes DefaultBodyLimit.
async fn polymorfa_webhook(State(secret): State<String>, headers: HeaderMap, body: Bytes) -> StatusCode {
    let signature = headers.get("x-webhook-signature").and_then(|value| value.to_str().ok()).unwrap_or("");
    let Ok(expected) = hex::decode(signature) else { return StatusCode::BAD_REQUEST };
    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes a key of any length");
    mac.update(&body);
    if mac.verify_slice(&expected).is_err() {
        return StatusCode::BAD_REQUEST;
    }

    let Ok(event) = serde_json::from_slice::<serde_json::Value>(&body) else { return StatusCode::BAD_REQUEST };
    if !already_processed(event["id"].as_str().unwrap_or_default()) {
        save_event(event);
    }
    StatusCode::OK
}

#[tokio::main]
async fn main() {
    let secret = std::env::var("POLYMORFA_WEBHOOK_SECRET").unwrap_or_default();
    if secret.is_empty() {
        panic!("Set POLYMORFA_WEBHOOK_SECRET to the endpoint signing secret.");
    }
    let app = Router::new().route("/polymorfa/webhook", post(polymorfa_webhook))
        .layer(DefaultBodyLimit::max(MAX_WEBHOOK_BYTES))
        .with_state(secret);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
TypeScript
import express from "express";
import { WebhookSignatureError, webhooks } from "@polymorfa/sdk";

const secret = process.env.POLYMORFA_WEBHOOK_SECRET;
if (!secret) throw new Error("Set POLYMORFA_WEBHOOK_SECRET to the endpoint signing secret.");

const app = express();
const MAX_WEBHOOK_BYTES = 2 * 1024 * 1024;

// Keep the raw bytes. Parsing and re-serializing JSON breaks the signature.
// express.raw rejects a larger body with 413 before the handler runs.
app.post("/polymorfa/webhook", express.raw({ type: "application/json", limit: MAX_WEBHOOK_BYTES }), async (req, res) => {
  let event;
  try {
    event = await webhooks.verify({
      body: req.body,
      signature: req.header("x-webhook-signature") ?? "",
      secret,
    });
  } catch (error) {
    if (error instanceof WebhookSignatureError) return res.sendStatus(400);
    throw error;
  }

  // Skip an event you already stored, then queue the work.
  if (await alreadyProcessed(event.id)) return res.sendStatus(200);
  await saveEvent(event);

  res.sendStatus(200);
});

app.listen(3000);

alreadyProcessed and saveEvent, in each language's naming style, stand for your own storage. In the Java example, eventId stands for reading the event id with your JSON library. Answer within 30 seconds: Polymorfa stops waiting after that and retries the event later. Do slow work after you respond.

Create the endpoint#

Register your URL and the event types you handle. The request requires an Idempotency-Key, so a retried create never makes two endpoints.

API

cURL
curl -X POST "https://api.polymorfa.com/platform/projects/$PROJECT_ID/webhooks" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Idempotency-Key: create-orders-webhook-1" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/polymorfa/webhook",
    "eventTypes": ["message.received", "message.ack", "session.status"]
  }'
TypeScript
const created = await project.webhooks.create(
  {
    url: "https://example.com/polymorfa/webhook",
    eventTypes: ["message.received", "message.ack", "session.status"],
  },
  { idempotencyKey: "create-orders-webhook-1" },
);

const webhookId = created.data.webhook.id;
const secret = created.data.secret; // Shown once. Store it now.

CLI

Shell
cat > webhook.json <<'JSON'
{
  "url": "https://example.com/polymorfa/webhook",
  "eventTypes": ["message.received", "message.ack", "session.status"]
}
JSON

polymorfa webhook create \
  --owner project \
  --project "$PROJECT_ID" \
  --input webhook.json \
  --secret-out ./webhook.secret

--secret-out writes the signing secret to a new file that only you can read.

The response contains the endpoint and its signing secret (abbreviated here):

JSON
{
  "data": {
    "webhook": {
      "id": "0190f2a4-7d21-7c3e-8a51-4b6f2e9d0c18",
      "projectId": "0190f29e-1b4c-7a2d-9e3f-5c8a6d7b4e21",
      "url": "https://example.com/polymorfa/webhook",
      "eventTypes": ["message.received", "message.ack", "session.status"],
      "enabled": true,
      "format": "native",
      "phoneOfflineStartDay": 10
    },
    "secret": "<signing secret>",
    "secretAvailable": true,
    "operationId": null,
    "idempotency": { "key": "create-orders-webhook-1", "replayed": false }
  }
}

Store secret in your secret manager and give it to your handler as POLYMORFA_WEBHOOK_SECRET. Polymorfa shows it only in this response. Repeating the request with the same key returns the same endpoint with secret: null and secretAvailable: false. If you lose the secret, rotate it.

You can also add the endpoint in the Console, under the project's Settings → Webhooks. Copy the secret from the confirmation dialog before you close it.

Send a test event#

Ask Polymorfa to deliver a synthetic polymorfa.test event to the endpoint. The test goes to this endpoint only, whatever its event types.

API

cURL
curl -X POST "https://api.polymorfa.com/platform/projects/$PROJECT_ID/webhooks/$WEBHOOK_ID/tests" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Idempotency-Key: test-orders-webhook-1"
TypeScript
const test = await project.webhooks.test(webhookId, {}, { idempotencyKey: "test-orders-webhook-1" });
console.log(test.data.eventId, test.data.deliveryId);

CLI

Shell
polymorfa webhook test "$WEBHOOK_ID" --owner project --project "$PROJECT_ID"

The response returns the eventId and deliveryId as soon as the delivery is queued. It does not wait for your server to answer.

Check the delivery#

Confirm that your handler logged the test event and answered 2xx. Then read the delivery from Polymorfa:

cURL
curl "https://api.polymorfa.com/platform/projects/$PROJECT_ID/webhook-deliveries/$DELIVERY_ID/attempts" \
  -H "Authorization: Bearer $POLYMORFA_KEY"
TypeScript
const attempts = await project.webhookDeliveries.listAttempts(test.data.deliveryId);

This needs webhook-deliveries:read. Each attempt shows your server's HTTP status. A 400 usually means the handler parsed the body before checking the signature, or used another endpoint's secret. You can also open the delivery from the project's Logs page in the Console. See Inspect deliveries and attempts.

Handle retries and duplicates #

Polymorfa delivers each event at least once:

  • It retries after a network error, a timeout, or a 408, 429 or 5xx answer. An event gets at most eight attempts over 24 hours, or fewer when the endpoint's retryPolicy.maximumAttempts is lower.
  • Any other non-2xx answer ends the delivery. Return 400 only for requests you will never accept, such as a bad signature.
  • A lost acknowledgement can deliver the same event twice. Retries keep the event id, so store it and skip an event you already processed.
  • Events can arrive out of order. Use each event's timestamp, not arrival order.

Every request carries X-Polymorfa-Delivery-ID and X-Polymorfa-Delivery-Attempt, which you can log to trace retries. See Retry configuration.

Forward events to your machine #

polymorfa listen streams a project's events to the CLI and forwards each one to a local URL. You do not need a public URL or a registered endpoint. It needs a team key or project token with Events → Read (events:listen) and access to event streams.

Shell
polymorfa listen \
  --project "$PROJECT_ID" \
  --event 'message.*' \
  --forward-to http://127.0.0.1:3000/polymorfa/webhook \
  --forward-secret-out ./local-forwarding.secret

The CLI signs forwarded requests with a secret it creates for this run, not with your endpoint's signing secret. The signature arrives in Polymorfa-Local-Signature as t=<unix seconds>,v1=<hex>, an HMAC-SHA256 of <unix seconds>.<body>. In development, verify it with webhooks.verifyLocal from the TypeScript SDK, which also rejects requests older than five minutes:

TypeScript
const event = await webhooks.verifyLocal({
  body: req.body,
  signature: req.header("polymorfa-local-signature") ?? "",
  secret: localForwardingSecret, // contents of ./local-forwarding.secret
});

Never accept local signatures in production. To generate events for a test number while polymorfa listen runs, use polymorfa trigger, for example polymorfa trigger message.received --project "$PROJECT_ID" --session <test-number>. It needs sandbox:write and access to test numbers. See Test events.

Next steps#