Webhooks: Verify Signatures
Webhook signing lets your server verify that a notification came from Carusell and that its body arrived intact. You can enable signing separately for each settlement account. It covers payment, refund, disbursement and 3-D Secure notifications sent by Carusell, including those sent to a URL supplied for an individual transaction.
Get your signing key
If this endpoint already receives webhooks, test your verifier with the sample request and read the rollout steps before asking for a key. Issuing the key enables signing for newly scheduled notifications.
Ask Carusell Support to issue a webhook signing key for your settlement account. In the Client Portal, open that account, find Webhook signing and select Show key next to Current key. Store it in your server's secret store. Use a separate configuration for sandbox and production.
If several accounts send to the same endpoint, decide how it will select a key. The notification body has no settlement account ID. You can give each account its own callback path and configure the corresponding key for that path. If you need one URL and one key for several of your accounts, ask Support to configure a shared key. With a shared key, match the verified transaction to the account in your own records.
What a signed request looks like
Signing adds two HTTP headers. Header names are case-insensitive. Accounts without a signing key send unsigned notifications with both headers omitted. The JSON fields for each transaction type are described in Webhooks: Example.
| Header | Value |
|---|---|
webhook-id | Decimal identifier of this notification. Keep the exact header text as a string. Automatic retries use the same ID. |
webhook-signature | One or two space-separated v1,<base64> entries. During key rotation the current key's signature comes first. |
Use this test-only key to verify the request below locally. The example uses an abbreviated payment body so you can reproduce the signature byte for byte.
whsec_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA=POST /webhooks/carusell HTTP/1.1
Content-Type: application/json
webhook-id: 381450123456789012
webhook-signature: v1,Mr6rN82pn59wmwubiFwFaD/YHHS/y4aTJOxkecQbs2Y=
{"transactionId":"381402340362944512","status":"CAPTURED"}The example body starts at { and ends at }, with no trailing newline. The signature shown matches those exact bytes. Adding a space after the colon or changing the notification ID must make verification fail.
Verify before parsing JSON
- Read the two headers and the raw request body. Configure your framework to preserve the body bytes before any JSON parser runs.
- Remove the
whsec_prefix from your key and decode the remainder using standard Base64. - Concatenate the UTF-8 bytes of the exact
webhook-idheader value, one period (., byte0x2E) and the raw body bytes. Compute HMAC-SHA256 with the decoded key. Encode the binary digest in standard Base64 and prefix it withv1,. - Split the signature header on spaces. Use a constant-time comparison with each supported entry. Accept the signature if any entry matches a key you trust for this account. Ignore unknown signature versions. Reject a partial header pair or a signature that fails verification.
Determine whether signing is required from your own configuration for the callback path or settlement account. If both headers are missing on a shared endpoint, use your own transaction records to identify the account. Missing headers alone cannot establish that an account accepts unsigned notifications.
Carusell does not send a webhook-timestamp. A verifier that requires that header or includes a timestamp in the signed bytes will reject these requests.
Python
Decode configured keys once at startup. Pass the current key and, during a planned rotation, any previous key you still trust. With Flask, use request.get_data() for the body and request.headers.get(...) for the headers.
import base64
import hmac
def decode_key(secret):
if not secret.startswith("whsec_"):
raise ValueError("Invalid signing key prefix")
encoded = secret[6:]
if "=" not in encoded:
encoded += "=" * (-len(encoded) % 4)
key = base64.b64decode(encoded, validate=True)
if not 24 <= len(key) <= 64:
raise ValueError("Invalid signing key length")
return key
def verify_webhook(raw_body, webhook_id, signature_header, keys):
if not isinstance(webhook_id, str) or not webhook_id.isascii() or not webhook_id.isdecimal():
return False
if not signature_header:
return False
signed = webhook_id.encode("ascii") + b"." + raw_body
entries = signature_header.encode("utf-8").split()
for key in keys:
digest = hmac.digest(key, signed, "sha256")
expected = b"v1," + base64.b64encode(digest)
if any(hmac.compare_digest(expected, entry) for entry in entries):
return True
return False
# At startup: keys = [decode_key(secret) for secret in configured_secrets]
# In Flask: verify_webhook(request.get_data(), request.headers.get("webhook-id"),
# request.headers.get("webhook-signature"), keys)Node.js
Pass the raw body as a Buffer. In Express, register this route with express.raw({ type: 'application/json' }) before any global express.json() middleware. Read the headers with req.get('webhook-id') and req.get('webhook-signature').
const { createHmac, timingSafeEqual } = require('node:crypto');
function decodeKey(secret) {
if (!secret.startsWith('whsec_')) throw new Error('Invalid signing key prefix');
const key = Buffer.from(atob(secret.slice(6)), 'latin1');
if (key.length < 24 || key.length > 64) throw new Error('Invalid signing key length');
return key;
}
function verifyWebhook(rawBody, webhookId, signatureHeader, keys) {
if (!Buffer.isBuffer(rawBody)) return false;
if (typeof webhookId !== 'string' || !webhookId || /[^0-9]/.test(webhookId)) return false;
if (!signatureHeader) return false;
const entries = signatureHeader.split(/\s+/).map(entry => Buffer.from(entry, 'utf8'));
return keys.some(key => {
const digest = createHmac('sha256', key)
.update(webhookId + '.', 'utf8')
.update(rawBody)
.digest('base64');
const expected = Buffer.from('v1,' + digest, 'ascii');
return entries.some(entry =>
entry.length === expected.length && timingSafeEqual(entry, expected)
);
});
}
// At startup: const keys = configuredSecrets.map(decodeKey);
// In Express: verifyWebhook(req.body, req.get('webhook-id'), req.get('webhook-signature'), keys);Acknowledge deliveries and handle duplicates
Verify every attempt, including a delivery whose ID you recognise. Automatic retries keep the notification ID and the keys selected for its first delivery. The JSON can be serialised differently on a retry, so verify the signature against the body received on that attempt.
| Your endpoint receives | How to respond |
|---|---|
| A valid new notification | Durably record or enqueue it with its ID, then return HTTP 2xx. A unique constraint on the ID can prevent concurrent deliveries from queuing the same work twice. |
| A valid notification already recorded | Return 2xx without repeating the action. |
| A missing or invalid signature on an endpoint that requires signing | Reject the request, for example with HTTP 401. Do not apply the update. A non-2xx response triggers the normal retry schedule. |
Support can send a fresh notification for the current status of a payment, refund or disbursement. When signing is active, it has a new webhook-id and uses the keys active at resend time. For example, if a payment advanced from AUTHORIZED to CAPTURED, the new notification reports CAPTURED. A manual resend cannot recreate an earlier status or the original 3-D Secure challenge.
Make transaction updates idempotent as well. Receiving CAPTURED again for the same payment must not credit the order twice. The signature has no timestamp or built-in expiry, so a valid signature alone does not establish when the notification was sent.
Enable signing on an existing endpoint
Test the verifier with the example above before requesting a key. Once Support enables signing, newly scheduled notifications carry the headers. Pending automatic retries of earlier unsigned notifications can still arrive during the retry window, roughly four days under the published retry schedule.
During the transition, verify signed requests immediately and reject invalid or incomplete signatures. If both headers are absent and the route is still in its migration window:
- Locate the transaction in your own records and identify its settlement account and order. If you cannot match it, leave the order unchanged.
- Retrieve the current transaction using your authenticated API credentials. Use Get Payment by ID, Get Refund by ID or Get Disbursement by ID.
- Update the matched order using the status, amount and currency from the API response. Treat the unsigned notification only as a prompt to perform the lookup.
For an unsigned 3-D Secure challenge during the transition, do not use the supplied acsUrl or cReq. A status lookup cannot authenticate these fields. Contact Support about the affected payment. Once earlier unsigned deliveries have cleared, require both headers on that account's route.
Rotate or replace a key
For a planned rotation, ask Support to issue a new key and agree how long the previous key should also sign new notifications. The overlap can be set from 0 to 720 hours (30 days). Retrieve the new key in the Client Portal and deploy it to your verifier. During the overlap, a newly scheduled notification carries two signatures in one header. Either signature can verify the request.
Automatic retries of notifications scheduled before rotation may still carry only the old signature. Keep the previous key available for verification until those deliveries have cleared, even if the signing overlap ends sooner. Under the published schedule the final attempt is roughly four days after the first.
If a key may have been compromised, immediately remove it from every verifier that trusts it. Give Support the list of all settlement accounts that use that key and request a replacement with zero overlap on each account. Configure the replacement key for each affected route. To reconcile affected payments, refunds or disbursements, retrieve their current state through the authenticated API or ask Support for fresh signed status notifications.
Updated about 5 hours ago
