Webhooks

Verify signatures

Every webhook request carries a Signature header. Check it before you trust the body: it proves the request came from Jodie and wasn't changed on the way.

How the signature is made

The Signature header is the HMAC-SHA256 of the raw request body, keyed with the endpoint's signing secret, written as lowercase hex.

To verify a request:

  1. Read the request body as raw bytes, before any JSON parsing.
  2. Work out the HMAC-SHA256 of those bytes using your signing secret.
  3. Compare your result with the Signature header using a constant-time comparison.
  4. If they don't match, or the header is missing, reply 401 and stop.
  5. Otherwise, parse the JSON, act on event_type and reply with a 2xx status within 3 seconds.

Use the body exactly as received. Parsing the JSON and encoding it again changes the bytes (spacing, key order, escaped characters), and the signature will no longer match.

Each endpoint has its own secret. Find it on the endpoint's page in the app, under Endpoint › Signing secret. Test events are signed the same way, so you can check your code with Send test event.

Headers sent with every request

HeaderValue
SignatureHMAC-SHA256 of the raw request body, keyed with your signing secret, as hex.
Event-TypeThe kind of activity, the same as event_type in the body.
Delivery-IdUnique per delivery. Use it to ignore duplicates.
Account-IdYour account ID.
Test-EventOnly on test events, set to true.

Content-Type: application/json and a User-Agent header are also sent.

Code examples

Each example is a complete receiver that reads WEBHOOK_SECRET from the environment, rejects a missing or wrong signature with 401, and replies 200 otherwise. Every one has been run against real signed payloads, including non-ASCII text.

Node.js

Built with Express. File: server.mjs

import crypto from "node:crypto";
import express from "express";

const app = express();

app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const expected = crypto
    .createHmac("sha256", process.env.WEBHOOK_SECRET)
    .update(req.body)
    .digest("hex");
  const received = req.get("Signature") ?? "";

  if (
    received.length !== expected.length ||
    !crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected))
  ) {
    return res.sendStatus(401);
  }

  const event = JSON.parse(req.body.toString("utf8"));
  console.log(event.event_type);

  res.sendStatus(200);
});

app.listen(8080);

Python

Built with Flask. File: app.py

import hashlib
import hmac
import os

from flask import Flask, abort, request

app = Flask(__name__)


@app.post("/webhook")
def webhook():
    body = request.get_data()
    expected = hmac.new(
        os.environ["WEBHOOK_SECRET"].encode(), body, hashlib.sha256
    ).hexdigest()
    received = request.headers.get("Signature", "")

    if not hmac.compare_digest(expected, received):
        abort(401)

    event = request.get_json()
    print(event["event_type"])

    return "", 200

PHP

Built with Plain PHP. File: webhook.php

<?php

$body = file_get_contents('php://input');
$expected = hash_hmac('sha256', $body, getenv('WEBHOOK_SECRET'));
$received = $_SERVER['HTTP_SIGNATURE'] ?? '';

if (! hash_equals($expected, $received)) {
    http_response_code(401);
    exit;
}

$event = json_decode($body, true);
error_log($event['event_type']);

http_response_code(200);

Ruby

Built with Sinatra. File: app.rb

require "json"
require "openssl"
require "rack/utils"
require "sinatra"

post "/webhook" do
  body = request.body.read
  expected = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("WEBHOOK_SECRET"), body)
  received = request.env["HTTP_SIGNATURE"].to_s

  halt 401 unless Rack::Utils.secure_compare(expected, received)

  event = JSON.parse(body)
  puts event["event_type"]

  status 200
end

Go

Built with net/http. File: main.go

package main

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

func webhook(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "unreadable body", http.StatusBadRequest)
		return
	}

	mac := hmac.New(sha256.New, []byte(os.Getenv("WEBHOOK_SECRET")))
	mac.Write(body)
	expected := hex.EncodeToString(mac.Sum(nil))

	if !hmac.Equal([]byte(expected), []byte(r.Header.Get("Signature"))) {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}

	var event map[string]any
	if err := json.Unmarshal(body, &event); err != nil {
		http.Error(w, "invalid JSON", http.StatusBadRequest)
		return
	}
	log.Println(event["event_type"])

	w.WriteHeader(http.StatusOK)
}

func main() {
	http.HandleFunc("/webhook", webhook)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Rust

Built with axum, hmac, sha2, hex. File: main.rs

use axum::{body::Bytes, http::HeaderMap, http::StatusCode, routing::post, Router};
use hmac::{Hmac, Mac};
use sha2::Sha256;

async fn webhook(headers: HeaderMap, body: Bytes) -> StatusCode {
    let secret = std::env::var("WEBHOOK_SECRET").expect("WEBHOOK_SECRET is set");
    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("any key length works");
    mac.update(&body);

    let received = headers
        .get("Signature")
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default();
    let Ok(signature) = hex::decode(received) else {
        return StatusCode::UNAUTHORIZED;
    };
    if mac.verify_slice(&signature).is_err() {
        return StatusCode::UNAUTHORIZED;
    }

    let Ok(event) = serde_json::from_slice::<serde_json::Value>(&body) else {
        return StatusCode::BAD_REQUEST;
    };
    println!("{}", event["event_type"]);

    StatusCode::OK
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/webhook", post(webhook));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Java

Built with JDK HttpServer, Java 17+. File: WebhookReceiver.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 WebhookReceiver {
    public static void main(String[] args) throws Exception {
        byte[] secret = System.getenv("WEBHOOK_SECRET").getBytes(StandardCharsets.UTF_8);
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);

        server.createContext("/webhook", exchange -> {
            try (exchange) {
                byte[] body = exchange.getRequestBody().readAllBytes();
                String received = exchange.getRequestHeaders().getFirst("Signature");

                Mac mac = Mac.getInstance("HmacSHA256");
                mac.init(new SecretKeySpec(secret, "HmacSHA256"));
                String expected = HexFormat.of().formatHex(mac.doFinal(body));

                boolean valid = received != null && MessageDigest.isEqual(
                    expected.getBytes(StandardCharsets.UTF_8),
                    received.getBytes(StandardCharsets.UTF_8)
                );

                exchange.sendResponseHeaders(valid ? 200 : 401, -1);
            } catch (Exception exception) {
                exchange.sendResponseHeaders(500, -1);
            }
        });

        server.start();
    }
}

C#

Built with ASP.NET Core. File: Program.cs

using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

var app = WebApplication.Create(args);
var secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("WEBHOOK_SECRET")!);

app.MapPost("/webhook", async (HttpRequest request) =>
{
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer);
    var body = buffer.ToArray();

    var expected = Convert.ToHexString(HMACSHA256.HashData(secret, body)).ToLowerInvariant();
    var received = request.Headers["Signature"].ToString();

    if (!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(received)))
    {
        return Results.Unauthorized();
    }

    using var payload = JsonDocument.Parse(body);
    Console.WriteLine(payload.RootElement.GetProperty("event_type").GetString());

    return Results.Ok();
});

app.Run("http://0.0.0.0:8080");

Common mistakes

  • Parsing before verifying. Frameworks often parse JSON for you. Use the raw-body option shown above (express.raw, request.get_data(), php://input), not the parsed object.
  • Trimming or re-encoding the secret. Use the secret exactly as copied from the app.
  • Comparing with ==. Use the constant-time comparison in each example so the check doesn't leak timing information.
  • Slow handlers. Reply within 3 seconds. If your work takes longer, store the payload, reply 200, and process it in the background.

Need a hand?

Our team can help you connect Jodie to your systems.

Email [email protected]