Signed Callbacks
When signing is switched on for an API key, every callback sent for that key is signed. Checking the signature proves the callback came from Metric and was not changed on the way.
What a signed callback looks like​
The body is the same JSON you receive today. We add three headers.
POST <your callback URL>
Content-Type: application/json
X-TIMESTAMP: 1786665600
X-SIGNATURE: 3f9a1c...
X-SIGNATURE-ALGORITHM: HMAC-SHA256
{ ...the usual callback body... }
| Header | Meaning |
|---|---|
X-TIMESTAMP | Unix time in seconds when we signed the callback |
X-SIGNATURE | HMAC-SHA256 of <X-TIMESTAMP>.<raw request body>, keyed with your signing secret, as lowercase hex |
X-SIGNATURE-ALGORITHM | Always HMAC-SHA256 |
Timestamps are in seconds, not milliseconds, and the tolerance is 5 minutes either side.
A handler that ignores these headers keeps working, so signing can be switched on before you start checking it.
Verify the signature​
Recompute the signature from the raw body and compare it with the one we sent.
- Read the raw request body: the bytes as received, before any JSON parsing.
- Build the string
<X-TIMESTAMP>.<raw body>. - Compute HMAC-SHA256 of that string with your signing secret, as lowercase hex.
- Compare it with
X-SIGNATUREusing a constant-time comparison. Reject the callback on a mismatch. - Reject the callback if
X-TIMESTAMPis more than 5 minutes from your server time. - Reject a
transactionnumberyou have already processed.
Steps 5 and 6 stop a genuine callback that someone captured from being sent to you again.
Use the raw body. A re-encoded body can differ in spacing, key order or number formatting, and a single changed byte fails the check.
- PHP
- Node (Express)
- Python
- Java
- C# (.NET)
- Go
$raw = file_get_contents('php://input');
$ts = $_SERVER['HTTP_X_TIMESTAMP'] ?? '';
$sig = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', $ts . '.' . $raw, $signingSecret);
if (!hash_equals($expected, $sig) || abs(time() - (int) $ts) > 300) {
http_response_code(401);
exit;
}
$payload = json_decode($raw, true);
app.post('/callback', express.raw({ type: 'application/json' }), (req, res) => {
const ts = req.get('X-TIMESTAMP') || '';
const sig = req.get('X-SIGNATURE') || '';
const expected = crypto.createHmac('sha256', signingSecret)
.update(`${ts}.${req.body}`) // req.body is the raw Buffer
.digest('hex');
const ok = sig.length === expected.length
&& crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))
&& Math.abs(Date.now() / 1000 - Number(ts)) <= 300;
if (!ok) return res.sendStatus(401);
const payload = JSON.parse(req.body);
res.sendStatus(200);
});
express.raw is what keeps the body as raw bytes. With express.json() the body is already parsed by the time your handler runs, and the signature cannot be checked.
Uses only the standard library. In Flask the raw body is request.get_data(); in Django it is request.body; in FastAPI it is await request.body().
import hashlib
import hmac
import time
def verify_signature(raw_body: bytes, timestamp: str, signature: str, signing_secret: str) -> bool:
signed = timestamp.encode() + b"." + raw_body
expected = hmac.new(signing_secret.encode(), signed, hashlib.sha256).hexdigest()
# constant-time comparison
if not hmac.compare_digest(expected.encode(), signature.encode()):
return False
return timestamp.isdigit() and abs(time.time() - int(timestamp)) <= 300
Uses only the JDK (Java 17 or later, for HexFormat). In Spring, declare the body parameter as @RequestBody byte[] rawBody so it reaches you unparsed.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
static boolean verifySignature(byte[] rawBody, String timestamp, String signature,
String signingSecret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(signingSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8));
String expected = HexFormat.of().formatHex(mac.doFinal(rawBody)); // lowercase hex
// constant-time comparison
if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
signature.getBytes(StandardCharsets.UTF_8))) {
return false;
}
try {
return Math.abs(Instant.now().getEpochSecond() - Long.parseLong(timestamp)) <= 300;
} catch (NumberFormatException e) {
return false;
}
}
Uses only the base class library (.NET 5 or later). In ASP.NET Core, read the raw body yourself from Request.Body into a byte[] instead of binding a model.
using System;
using System.Security.Cryptography;
using System.Text;
static bool VerifySignature(byte[] rawBody, string timestamp, string signature, string signingSecret)
{
byte[] prefix = Encoding.UTF8.GetBytes(timestamp + ".");
byte[] signed = new byte[prefix.Length + rawBody.Length];
Buffer.BlockCopy(prefix, 0, signed, 0, prefix.Length);
Buffer.BlockCopy(rawBody, 0, signed, prefix.Length, rawBody.Length);
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(signingSecret));
string expected = Convert.ToHexString(hmac.ComputeHash(signed)).ToLowerInvariant();
// constant-time comparison
if (!CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(signature ?? "")))
{
return false;
}
return long.TryParse(timestamp, out long ts)
&& Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ts) <= 300;
}
Convert.ToHexString returns uppercase, so it is lowercased before comparing.
Uses only the standard library. Read the raw body with io.ReadAll(r.Body) before decoding any JSON.
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"strconv"
"time"
)
func verifySignature(rawBody []byte, timestamp, signature, signingSecret string) bool {
mac := hmac.New(sha256.New, []byte(signingSecret))
mac.Write([]byte(timestamp + "."))
mac.Write(rawBody)
expected := hex.EncodeToString(mac.Sum(nil))
// constant-time comparison
if !hmac.Equal([]byte(expected), []byte(signature)) {
return false
}
ts, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
return false
}
age := time.Now().Unix() - ts
if age < 0 {
age = -age
}
return age <= 300
}