Launching soon
The managed service is not open yet: https://app.cleardp.in does not accept requests and accounts cannot be created. These pages describe the API as it ships. Join the waitlist to hear when it opens.
The signature
Every delivery carries a X-ClearDP-Signature header with two parts: the time it was signed, and an HMAC-SHA256 of that time and the raw body, keyed with your endpoint's signing secret.
# the header X-ClearDP-Signature: t=1727605442531,v1=5f2c8d0e9b7a41c3a6e2d4f18b9c0e7d3a5b6c8f1e2d4a7b9c0d3e5f6a8b1c2d # how v1 is computed signed_payload = t + "." + raw_body v1 = hex( HMAC_SHA256( key = signing_secret, signed_payload ) )
| Part | Meaning |
|---|---|
| t | When the delivery was signed, in Unix time milliseconds. A retry is signed again, with a new time. |
| v1 | The signature: lowercase hex, 64 characters. |
| signing secret | The whole secret shown when you created the endpoint, including the whsec_ prefix, used as UTF-8 text. Each endpoint has its own. |
Verify in four steps
Read the raw body and the header
Take the request body as bytes, before any JSON parsing, and split the header on commas into
tandv1. If either is missing, reject the request.Check the time
Reject the request if
tis more than 5 minutes from your server's clock, in either direction. This stops someone who captured a genuine delivery from sending it again later.Compute the expected signature
HMAC-SHA256, keyed with your signing secret, over
t, a full stop, and the raw body. Hex-encode the result.Compare in constant time
Compare your result with
v1using your language's constant-time comparison. On a mismatch answer401and do nothing else.
Code samples
Complete receivers that verify the signature, read the delivery id and answer quickly. Each has been tested against real signatures: it accepts a genuine delivery and rejects a changed body, an old timestamp and a wrong secret.
Node.js server.js · Express
const crypto = require("node:crypto"); const express = require("express"); const SECRET = process.env.CLEARDP_WEBHOOK_SECRET; // whsec_… const TOLERANCE_MS = 5 * 60 * 1000; function verifySignature(rawBody, header, secret) { const parts = {}; for (const item of String(header || "").split(",")) { const i = item.indexOf("="); if (i > 0) parts[item.slice(0, i).trim()] = item.slice(i + 1).trim(); } const t = Number(parts.t); if (!Number.isInteger(t) || !parts.v1) return false; if (Math.abs(Date.now() - t) > TOLERANCE_MS) return false; // stale or replayed const expected = crypto .createHmac("sha256", secret) .update(`${parts.t}.`) .update(rawBody) .digest("hex"); const a = Buffer.from(expected); const b = Buffer.from(parts.v1); return a.length === b.length && crypto.timingSafeEqual(a, b); } const app = express(); // express.raw keeps the exact bytes received; a parsed-and-reserialised body fails. app.post("/webhooks/consent", express.raw({ type: "application/json" }), (req, res) => { if (!verifySignature(req.body, req.get("X-ClearDP-Signature"), SECRET)) { return res.sendStatus(401); } const deliveryId = req.get("X-ClearDP-Delivery"); // skip ids you have already processed const event = JSON.parse(req.body.toString("utf8")); // Queue event for processing, then answer quickly. res.sendStatus(200); }); app.listen(8080);
Python app.py · Flask
import hashlib import hmac import os import time from flask import Flask, abort, request SECRET = os.environ["CLEARDP_WEBHOOK_SECRET"] # whsec_… TOLERANCE_MS = 5 * 60 * 1000 def verify_signature(raw_body: bytes, header: str, secret: str) -> bool: parts = {} for item in (header or "").split(","): key, sep, value = item.partition("=") if sep: parts[key.strip()] = value.strip() t, v1 = parts.get("t", ""), parts.get("v1", "") if not t.isdigit() or not v1: return False if abs(time.time() * 1000 - int(t)) > TOLERANCE_MS: return False # stale or replayed expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, v1) app = Flask(__name__) @app.post("/webhooks/consent") def consent_webhook(): raw_body = request.get_data() # the exact bytes received if not verify_signature(raw_body, request.headers.get("X-ClearDP-Signature", ""), SECRET): abort(401) delivery_id = request.headers.get("X-ClearDP-Delivery") # skip ids you have already processed event = request.get_json() # Queue event for processing, then answer quickly. return "", 200
Go main.go · net/http
package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "io" "net/http" "os" "strconv" "strings" "time" ) const tolerance = 5 * time.Minute func verifySignature(rawBody []byte, header, secret string, now time.Time) bool { var t, v1 string for _, item := range strings.Split(header, ",") { key, value, ok := strings.Cut(item, "=") if !ok { continue } switch strings.TrimSpace(key) { case "t": t = strings.TrimSpace(value) case "v1": v1 = strings.TrimSpace(value) } } ms, err := strconv.ParseInt(t, 10, 64) if err != nil || v1 == "" { return false } if age := now.Sub(time.UnixMilli(ms)); age > tolerance || age < -tolerance { return false // stale or replayed } mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(t + ".")) mac.Write(rawBody) expected := hex.EncodeToString(mac.Sum(nil)) return hmac.Equal([]byte(expected), []byte(v1)) } func consentWebhook(w http.ResponseWriter, r *http.Request) { rawBody, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // the exact bytes received if err != nil { http.Error(w, "unreadable body", http.StatusBadRequest) return } secret := os.Getenv("CLEARDP_WEBHOOK_SECRET") // whsec_… if !verifySignature(rawBody, r.Header.Get("X-ClearDP-Signature"), secret, time.Now()) { http.Error(w, "bad signature", http.StatusUnauthorized) return } deliveryID := r.Header.Get("X-ClearDP-Delivery") // skip ids you have already processed _ = deliveryID // Queue rawBody for processing, then answer quickly. w.WriteHeader(http.StatusOK) } func main() { http.HandleFunc("/webhooks/consent", consentWebhook) http.ListenAndServe(":8080", nil) }
PHP webhook.php
<?php const TOLERANCE_MS = 5 * 60 * 1000; function verify_signature(string $rawBody, string $header, string $secret): bool { $parts = []; foreach (explode(',', $header) as $item) { $kv = explode('=', $item, 2); if (count($kv) === 2) { $parts[trim($kv[0])] = trim($kv[1]); } } $t = $parts['t'] ?? ''; $v1 = $parts['v1'] ?? ''; if (!ctype_digit($t) || $v1 === '') { return false; } $nowMs = (int) floor(microtime(true) * 1000); if (abs($nowMs - (int) $t) > TOLERANCE_MS) { return false; // stale or replayed } $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret); return hash_equals($expected, $v1); } $rawBody = file_get_contents('php://input'); // the exact bytes received $header = $_SERVER['HTTP_X_CLEARDP_SIGNATURE'] ?? ''; $secret = getenv('CLEARDP_WEBHOOK_SECRET'); // whsec_… if (!verify_signature($rawBody, $header, $secret)) { http_response_code(401); exit; } $deliveryId = $_SERVER['HTTP_X_CLEARDP_DELIVERY'] ?? ''; // skip ids you have already processed $event = json_decode($rawBody, true); // Queue $event for processing, then answer quickly. http_response_code(200);
Java ConsentWebhookController.java · Spring Boot
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.HexFormat; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController public class ConsentWebhookController { private static final long TOLERANCE_MS = 5 * 60 * 1000L; private static final String SECRET = System.getenv("CLEARDP_WEBHOOK_SECRET"); // whsec_… static boolean verifySignature(byte[] rawBody, String header, String secret) { if (header == null || secret == null) return false; String t = null, v1 = null; for (String item : header.split(",")) { String[] kv = item.split("=", 2); if (kv.length != 2) continue; if (kv[0].trim().equals("t")) t = kv[1].trim(); if (kv[0].trim().equals("v1")) v1 = kv[1].trim(); } if (t == null || v1 == null || !t.matches("\\d+")) return false; if (Math.abs(System.currentTimeMillis() - Long.parseLong(t)) > TOLERANCE_MS) { return false; // stale or replayed } try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); mac.update((t + ".").getBytes(StandardCharsets.UTF_8)); String expected = HexFormat.of().formatHex(mac.doFinal(rawBody)); return MessageDigest.isEqual( expected.getBytes(StandardCharsets.UTF_8), v1.getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { return false; } } // byte[] keeps the exact bytes received; a parsed-and-reserialised body fails. @PostMapping("/webhooks/consent") public ResponseEntity<Void> receive( @RequestBody byte[] rawBody, @RequestHeader(value = "X-ClearDP-Signature", required = false) String signature, @RequestHeader(value = "X-ClearDP-Delivery", required = false) String deliveryId) { if (!verifySignature(rawBody, signature, SECRET)) { return ResponseEntity.status(401).build(); } // Skip deliveryId values you have already processed; queue the event, then answer. return ResponseEntity.ok().build(); } }
Ruby app.rb · Sinatra
require "json" require "openssl" require "sinatra" SECRET = ENV.fetch("CLEARDP_WEBHOOK_SECRET") # whsec_… TOLERANCE_MS = 5 * 60 * 1000 def verify_signature(raw_body, header, secret) parts = header.to_s.split(",").filter_map do |item| key, value = item.split("=", 2) [key.strip, value.strip] if value end.to_h t, v1 = parts["t"], parts["v1"] return false unless t&.match?(/\A\d+\z/) && v1 return false if ((Time.now.to_f * 1000).to_i - t.to_i).abs > TOLERANCE_MS # stale or replayed expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{raw_body}") expected.bytesize == v1.bytesize && OpenSSL.fixed_length_secure_compare(expected, v1) end post "/webhooks/consent" do raw_body = request.body.read # the exact bytes received halt 401 unless verify_signature(raw_body, request.env["HTTP_X_CLEARDP_SIGNATURE"], SECRET) delivery_id = request.env["HTTP_X_CLEARDP_DELIVERY"] # skip ids you have already processed event = JSON.parse(raw_body) # Queue event for processing, then answer quickly. status 200 end
C# Program.cs · ASP.NET Core
using System.Security.Cryptography; using System.Text; var app = WebApplication.CreateBuilder(args).Build(); var secret = Environment.GetEnvironmentVariable("CLEARDP_WEBHOOK_SECRET")!; // whsec_… app.MapPost("/webhooks/consent", async (HttpRequest request) => { using var buffer = new MemoryStream(); await request.Body.CopyToAsync(buffer); // the exact bytes received var rawBody = buffer.ToArray(); if (!VerifySignature(rawBody, request.Headers["X-ClearDP-Signature"].ToString(), secret)) return Results.Unauthorized(); var deliveryId = request.Headers["X-ClearDP-Delivery"].ToString(); // skip ids already processed // Queue the event for processing, then answer quickly. return Results.Ok(); }); app.Run(); static bool VerifySignature(byte[] rawBody, string header, string secret) { string? t = null, v1 = null; foreach (var item in header.Split(',')) { var kv = item.Split('=', 2); if (kv.Length != 2) continue; if (kv[0].Trim() == "t") t = kv[1].Trim(); if (kv[0].Trim() == "v1") v1 = kv[1].Trim(); } if (t is null || v1 is null || !long.TryParse(t, out var ms)) return false; if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - ms) > 5 * 60 * 1000) return false; // stale or replayed using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)); var message = Encoding.UTF8.GetBytes(t + ".").Concat(rawBody).ToArray(); var expected = Convert.ToHexString(hmac.ComputeHash(message)).ToLowerInvariant(); return CryptographicOperations.FixedTimeEquals( Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(v1)); }
Test it locally
The quickest check is Send test ping in the dashboard. To test before your receiver is reachable from the internet, sign a request yourself:
# A test delivery signed exactly as ClearDP signs one (bash + openssl)
SECRET="$CLEARDP_WEBHOOK_SECRET"
BODY='{"id":"evt_local_test","type":"ping","v":1,"data":{}}'
T=$(($(date +%s) * 1000)) # Unix time in milliseconds
SIG=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.*= //')
curl -i http://localhost:3000/webhooks/consent \
-H "Content-Type: application/json" \
-H "X-ClearDP-Event: ping" \
-H "X-ClearDP-Delivery: whd_local_test" \
-H "X-ClearDP-Signature: t=$T,v1=$SIG" \
--data-raw "$BODY"Your receiver should answer 200. Change one character of BODY after signing, and it should answer 401.
Common mistakes
| Symptom | Cause and fix |
|---|---|
| Every signature fails | The body was parsed and serialised again before verifying, so the bytes changed. Verify the raw body — for example, register a raw-body parser on the webhook route only. |
| Every signature fails | The secret was shortened or decoded. Use the whole string, including whsec_, as the key. Check it belongs to this endpoint. |
| Every request is “too old” | t is in milliseconds. Compare it with the current time in milliseconds, not seconds. |
| Some requests are “too old” | Your server's clock has drifted. Keep it synchronised with NTP. |
| Failures after rotating | The receiver still has the old secret. Update it — the old one stops working at once. |
Rotating the secret
Rotate when a secret may have leaked, when someone who held it leaves, or on your regular schedule. Open the endpoint in Webhooks and choose Rotate signing secret.
- The current secret stops working the moment you confirm. There is no overlap period.
- The new secret is shown once. Copy it straight into your secret store.
- Deliveries are signed with the new secret from their next attempt. Any rejected while you update your receiver are retried automatically, so a prompt update loses nothing — see the retry schedule.