Verify webhook signatures
Anyone can send a POST request to your webhook URL. Before marking an order as paid, check that the request really comes from Senfenico, that its content wasn’t modified, and that it is recent.
Headers sent
Section titled “Headers sent”| Header | Content |
|---|---|
X-Senfenico-Timestamp |
When this attempt was sent, in Unix seconds (e.g. 1795675230) |
X-Senfenico-Signature |
v1= followed by the hex HMAC-SHA256 signature |
X-Senfenico-Delivery |
Event identifier, the same on every retry: use it to drop duplicates |
X-Webhook-Hash |
Legacy signature, still sent for existing integrations (see below) |
How the signature is computed
Section titled “How the signature is computed”X-Senfenico-Signature = "v1=" + hex( HMAC-SHA256( webhook_secret_key, timestamp + "." + raw_body ) )| Element | Value |
|---|---|
webhook_secret_key |
The key shown under the Signing secret label in Developer › Webhooks in the dashboard. The same key is used in test and live mode. |
timestamp |
The exact value of the X-Senfenico-Timestamp header |
raw_body |
The exact bytes received, before any JSON decoding |
Verify in 4 steps
Section titled “Verify in 4 steps”- Read the request’s raw body and the
X-Senfenico-TimestampandX-Senfenico-Signatureheaders. - Reject the request if the timestamp is more than 5 minutes away from your server’s clock. This check is what stops an intercepted request from being replayed.
- Compute
HMAC-SHA256(secret_key, timestamp + "." + raw_body)as hex. - Compare it with the value after
v1=using a constant-time comparison (hash_equals,hmac.compare_digest,crypto.timingSafeEqual). If any check fails, return400and do nothing else.
Complete examples
Section titled “Complete examples”Each example verifies the signature, then decodes data, which is a JSON string. The PHP and Laravel examples use str_starts_with, available from PHP 8.0.
<?phpconst SENFENICO_WEBHOOK_SECRET = 'your_webhook_secret_key';
function verify_senfenico( string $payload, ?string $timestamp, ?string $signature, string $secret, int $tolerance = 300): bool { if (!$timestamp || !ctype_digit($timestamp)) return false; if (!$signature || !str_starts_with($signature, 'v1=')) { return false; } if (abs(time() - (int) $timestamp) > $tolerance) return false; $expected = hash_hmac('sha256', $timestamp . '.' . $payload, $secret); return hash_equals($expected, substr($signature, 3));}
$payload = file_get_contents('php://input'); // raw body$timestamp = $_SERVER['HTTP_X_SENFENICO_TIMESTAMP'] ?? null;$signature = $_SERVER['HTTP_X_SENFENICO_SIGNATURE'] ?? null;
$ok = verify_senfenico( $payload, $timestamp, $signature, SENFENICO_WEBHOOK_SECRET);if (!$ok) { http_response_code(400); exit;}
$event = json_decode($payload, true);$data = is_string($event['data']) ? json_decode($event['data'], true) : $event['data'];
switch ($event['event']) { case 'charge.success': case 'checkout.success': // mark order $data['reference'] as paid (once) break; case 'charge.failed': // ... break;}
http_response_code(200);// routes/api.php — exclude this route from CSRF middleware if it lives in web.phpRoute::post('/webhooks/senfenico', function (Illuminate\Http\Request $request) { $payload = $request->getContent(); // raw body $timestamp = (string) $request->header('X-Senfenico-Timestamp'); $signature = (string) $request->header('X-Senfenico-Signature'); $secret = config('services.senfenico.webhook_secret');
$fresh = ctype_digit($timestamp) && abs(time() - (int) $timestamp) <= 300; $valid = str_starts_with($signature, 'v1=') && hash_equals( hash_hmac('sha256', $timestamp . '.' . $payload, $secret), substr($signature, 3) );
if (!$fresh || !$valid) { return response('', 400); }
$event = json_decode($payload, true); $data = is_string($event['data']) ? json_decode($event['data'], true) : $event['data'];
// dispatch(new HandleSenfenicoEvent($event['event'], $data));
return response('', 200);});import hashlib, hmac, json, os, timefrom flask import Flask, request
app = Flask(__name__)SECRET = os.environ["SENFENICO_WEBHOOK_SECRET"]
def verify_senfenico( raw_body: bytes, timestamp, signature, secret: str, tolerance: int = 300,) -> bool: if not timestamp or not signature or not signature.startswith("v1="): return False try: ts = int(timestamp) except ValueError: return False if abs(time.time() - ts) > tolerance: return False message = timestamp.encode() + b"." + raw_body expected = hmac.new( secret.encode(), message, hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature[3:])
@app.post("/webhooks/senfenico")def senfenico_webhook(): raw = request.get_data() # raw body, not request.json if not verify_senfenico(raw, request.headers.get("X-Senfenico-Timestamp"), request.headers.get("X-Senfenico-Signature"), SECRET): return "", 400
event = json.loads(raw) data = event["data"] if isinstance(data, str): data = json.loads(data)
if event["event"] in ("charge.success", "checkout.success"): ... # mark order data["reference"] as paid (once)
return "", 200import hashlib, hmac, json, timefrom django.conf import settingsfrom django.http import HttpResponsefrom django.views.decorators.csrf import csrf_exemptfrom django.views.decorators.http import require_POST
def verify_senfenico( raw_body: bytes, timestamp, signature, secret: str, tolerance: int = 300,) -> bool: if not timestamp or not signature or not signature.startswith("v1="): return False try: ts = int(timestamp) except ValueError: return False if abs(time.time() - ts) > tolerance: return False message = timestamp.encode() + b"." + raw_body expected = hmac.new( secret.encode(), message, hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature[3:])
@csrf_exempt@require_POSTdef senfenico_webhook(request): raw = request.body # raw body if not verify_senfenico(raw, request.headers.get("X-Senfenico-Timestamp"), request.headers.get("X-Senfenico-Signature"), settings.SENFENICO_WEBHOOK_SECRET): return HttpResponse(status=400)
event = json.loads(raw) data = event["data"] if isinstance(data, str): data = json.loads(data) # handle event["event"] / data["reference"] return HttpResponse(status=200)import crypto from 'node:crypto';import express from 'express';
const app = express();const SECRET = process.env.SENFENICO_WEBHOOK_SECRET;
function verifySenfenico( rawBody, timestamp, signature, secret, toleranceSec = 300) { if (!timestamp || !signature || !signature.startsWith('v1=')) return false; const ts = Number(timestamp); if (!Number.isInteger(ts)) return false; if (Math.abs(Date.now() / 1000 - ts) > toleranceSec) return false; const expected = crypto .createHmac('sha256', secret) .update(`${timestamp}.`) .update(rawBody) .digest('hex'); const a = Buffer.from(expected); const b = Buffer.from(signature.slice(3)); return a.length === b.length && crypto.timingSafeEqual(a, b);}
// express.raw() keeps the raw body — don't use express.json() on this routeconst raw = express.raw({ type: 'application/json' });
app.post('/webhooks/senfenico', raw, (req, res) => { const ok = verifySenfenico( req.body, req.get('X-Senfenico-Timestamp'), req.get('X-Senfenico-Signature'), SECRET ); if (!ok) return res.sendStatus(400);
const event = JSON.parse(req.body); const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
if (event.event === 'charge.success' || event.event === 'checkout.success') { // mark order data.reference as paid (once) }
res.sendStatus(200);});Test your verification
Section titled “Test your verification”Compute the expected signature for a body saved in body.json, using the timestamp you received:
printf '%s.' "$TIMESTAMP" | cat - body.json \ | openssl dgst -sha256 -hmac "$SENFENICO_WEBHOOK_SECRET"The output must equal the value after v1= in X-Senfenico-Signature. To receive real test events, create a charge with an sk_test_ key and a test number.
Troubleshooting
Section titled “Troubleshooting”| Symptom | Likely cause |
|---|---|
| Signature never matches | Re-serialized body instead of raw body, or a JSON middleware consumed the body before your code |
| Matches only without accents | JSON was decoded and re-encoded (é became é) |
| Rejected as “too old” although the signature is right | Your server clock drifts: enable NTP time sync |
| Fails with the right key | A space or newline copied with the secret, or v1= not stripped before comparing |
| No webhook received | Private URL, 301/302 redirect, or a response outside 2xx (see requirements) |
Legacy signature (X-Webhook-Hash)
Section titled “Legacy signature (X-Webhook-Hash)”Existing integrations and the PHP and Python SDKs (Webhook::constructEvent / Webhook.construct_event) use the X-Webhook-Hash header. It is still sent with every webhook:
X-Webhook-Hash = hex( SHA-256( raw_body + webhook_secret_key ) )It has no timestamp, so it does not protect against replay. Use X-Senfenico-Signature for new integrations. If you keep the legacy header, still compare in constant time and process each X-Senfenico-Delivery only once.
Extra protection
Section titled “Extra protection”The same event can arrive more than once: store each processed X-Senfenico-Delivery (or event + reference pair) and skip duplicates.
Before you fulfill a valuable order, fetch the object from the API and check its status, amount and live_mode.
Keep the secret server-side, in an environment variable, never in Git.