Guides
Webhooks
Uncart tells your system what happened on its side by sending a POST request to an HTTPS endpoint you run. Each delivery is signed with your shop's signing secret. Check the signature before you trust anything in the body. The events page lists every event and its payload.
The signature header
Each delivery carries an Uncart-Signature header. It holds the time and the signature, separated by a comma, as in this one.
t=1793102400,v1=4cd78aee7968966ff586a3015df0de132355fbf770b24602a2472ad440997138
t is when Uncart signed the delivery, in whole seconds since 1970 (Unix time). Each v1 is a hex HMAC-SHA256, keyed with a signing secret, of the text t, a dot, and the raw body. For the body {"id":"evt_docs_example","type":"example"} that text is 1793102400.{"id":"evt_docs_example","type":"example"}. While you rotate the secret, there are two v1 parts, one for each secret. Ignore any part you don't know, such as a later v2. One matching v1 is enough.
Checking it
- Read the body as raw bytes, before any JSON parser touches it. A parsed and re-serialised body has different bytes, and its signature won't match.
- Refuse the delivery if
tis more than five minutes away from your clock, in either direction. Five minutes is 300 seconds, and a delivery exactly 300 seconds off still counts. - Compute the HMAC for each secret you hold and compare it with each
v1in constant time. - Answer
2xxonly after you have checked the signature and stored the event.
The code below does steps 2 and 3. It has no dependencies. Uncart's tests run each version against Uncart's own signer, including tampered headers, changed bodies, stale and future timestamps, and both secrets during a rotation.
// Checks that a webhook came from Uncart. Node.js 18 or newer, no dependencies.
// rawBody is the request body exactly as it arrived (a Buffer), never re-serialised JSON.
// secrets holds your signing secret, or both of them while you rotate.
import { createHmac, timingSafeEqual } from 'node:crypto';
const TOLERANCE_SECONDS = 300;
export function verifyUncartSignature(header, rawBody, secrets, now = Date.now() / 1000) {
const nowSeconds = Math.floor(now);
if (typeof header !== 'string' || header === '' || header.length > 1024) return false;
let timestamp;
const signatures = [];
for (const part of header.split(',')) {
const at = part.indexOf('=');
const name = at < 0 ? part : part.slice(0, at);
const value = at < 0 ? '' : part.slice(at + 1);
if (name === 't') {
if (timestamp !== undefined || !/^(0|[1-9][0-9]{0,11})$/.test(value)) return false;
timestamp = Number(value);
} else if (name === 'v1') {
if (!/^[0-9a-f]{64}$/.test(value)) return false;
signatures.push(Buffer.from(value, 'hex'));
}
// Other parts are for later signature schemes. Ignore them.
}
if (timestamp === undefined || signatures.length === 0) return false;
if (Math.abs(nowSeconds - timestamp) > TOLERANCE_SECONDS) return false;
let valid = false;
for (const secret of secrets) {
if (typeof secret !== 'string' || !secret.startsWith('uc_whsec_')) continue;
const hmac = createHmac('sha256', secret);
const expected = hmac.update(`${timestamp}.`).update(rawBody).digest();
for (const given of signatures) {
if (timingSafeEqual(expected, given)) valid = true;
}
}
return valid;
}
<?php
// Checks that a webhook came from Uncart. PHP 8.0 or newer, no extra extensions.
// $rawBody is the request body exactly as it arrived: file_get_contents('php://input').
// $secrets holds your signing secret, or both of them while you rotate.
const UNCART_TOLERANCE_SECONDS = 300;
function uncart_verify_signature(
string $header,
string $rawBody,
array $secrets,
?int $now = null
): bool {
$now = $now ?? time();
if ($header === '' || strlen($header) > 1024) {
return false;
}
$timestamp = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$name, $value] = array_pad(explode('=', $part, 2), 2, '');
if ($name === 't') {
if ($timestamp !== null || !preg_match('/^(0|[1-9][0-9]{0,11})$/D', $value)) {
return false;
}
$timestamp = (int) $value;
} elseif ($name === 'v1') {
if (!preg_match('/^[0-9a-f]{64}$/D', $value)) {
return false;
}
$signatures[] = $value;
}
// Other parts are for later signature schemes. Ignore them.
}
if ($timestamp === null || count($signatures) === 0) {
return false;
}
if (abs($now - $timestamp) > UNCART_TOLERANCE_SECONDS) {
return false;
}
$valid = false;
foreach ($secrets as $secret) {
if (!is_string($secret) || !str_starts_with($secret, 'uc_whsec_')) {
continue;
}
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
foreach ($signatures as $given) {
if (hash_equals($expected, $given)) {
$valid = true;
}
}
}
return $valid;
}
# Checks that a webhook came from Uncart. Python 3.9 or newer, standard library only.
# raw_body is the request body exactly as it arrived (bytes), never re-serialised JSON.
# secrets holds your signing secret, or both of them while you rotate.
import hashlib
import hmac
import re
import time
TOLERANCE_SECONDS = 300
def verify_uncart_signature(header, raw_body, secrets, now=None):
now = int(time.time()) if now is None else now
if not isinstance(header, str) or not header or len(header) > 1024:
return False
timestamp = None
signatures = []
for part in header.split(","):
name, _, value = part.partition("=")
if name == "t":
if timestamp is not None or not re.fullmatch(r"0|[1-9][0-9]{0,11}", value):
return False
timestamp = int(value)
elif name == "v1":
if not re.fullmatch(r"[0-9a-f]{64}", value):
return False
signatures.append(value)
# Other parts are for later signature schemes. Ignore them.
if timestamp is None or not signatures:
return False
if abs(now - timestamp) > TOLERANCE_SECONDS:
return False
valid = False
for secret in secrets:
if not isinstance(secret, str) or not secret.startswith("uc_whsec_"):
continue
message = str(timestamp).encode() + b"." + raw_body
expected = hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()
for given in signatures:
if hmac.compare_digest(expected, given):
valid = True
return valid
Rotating the signing secret
Rotating gives you a new secret and keeps the old one valid for an overlap you choose, from zero to seven days, one day by default. During the overlap every delivery is signed with both. Your endpoint can switch whenever you deploy.
- Rotate on the Connection page and copy the new secret. It is shown once.
- Deploy your endpoint with both secrets in its list.
- When the overlap ends, remove the old secret.
There are never more than two valid secrets. Rotating again during an overlap ends the older one at once. If a secret leaks, rotate with an overlap of zero. That ends the old secret immediately.
Repeated deliveries
A signature stops a forged or changed body, and an old one replayed later. It doesn't stop the same delivery arriving twice within its five minutes, and Uncart sends an event again when your endpoint didn't answer with a 2xx in time, on its retry schedule, for up to about three days. Every event has an id. Keep the ids you have handled for at least four days, as long as Uncart may send an event again, and ignore an event whose id you have already seen.
Events can arrive out of order: a retried event may come after a newer one. When the order matters (go_live.changed says where your shop stands now), order them by their created time and keep the newest.