Webhooks
Webhooks
Monotree sends an HTTPS POST to your endpoint when something changes, signed with your endpoint's secret.
A webhook is a call from Monotree to your server when something happens: a customer went live, a seller was added, someone wrote to your support desk. It saves you from asking again and again. Each thing that happens is an event, and each event sent to one of your endpoints is a delivery.
Webhook quickstart
- Add an endpoint and keep its secret:
curl -X POST https://partners.monotree.com/api/v1/webhooks \
-H "Authorization: Bearer $MONOTREE_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "url": "https://api.acme.example/hooks/monotree", "events": ["customer.live", "customer.failed"] }'{
"id": "whe_01jd1f4c8m2p0r6t9w3y5a7c1e",
"object": "webhook_endpoint",
"url": "https://api.acme.example/hooks/monotree",
"events": ["customer.live", "customer.failed"],
"active": true,
"secret": "whsec_v95lgXBNEH5oKrYg51rz944RoboXg95bZELO4u0E",
"sandbox": true
}- On your server, check the signature of every request against the raw body, answer
2xxat once, and do the work afterwards:
<?php
// hooks/monotree.php
$secret = getenv('MONOTREE_WEBHOOK_SECRET'); // whsec_…
$body = file_get_contents('php://input'); // the raw body, before any parsing
$header = $_SERVER['HTTP_MONOTREE_SIGNATURE'] ?? '';
$time = 0;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
if ($key === 't') {
$time = (int) $value;
} elseif ($key === 'v1') {
$signatures[] = $value;
}
}
$expected = hash_hmac('sha256', $time.'.'.$body, $secret);
$valid = abs(time() - $time) <= 300
&& array_filter($signatures, fn ($signature) => hash_equals($expected, $signature)) !== [];
if (! $valid) {
http_response_code(400);
exit;
}
$event = json_decode($body, true);
// put $event on your queue, keyed by $event['id'] so a repeat is skipped
http_response_code(200);// Node.js 18+, Express
import crypto from 'node:crypto';
import express from 'express';
const app = express();
const secret = process.env.MONOTREE_WEBHOOK_SECRET; // whsec_…
// express.raw keeps the raw body, which the signature is made over
app.post('/hooks/monotree', express.raw({ type: 'application/json' }), (req, res) => {
const parts = (req.get('Monotree-Signature') || '').split(',').map((part) => part.trim().split('='));
const time = Number((parts.find(([key]) => key === 't') || [])[1]);
const expected = crypto.createHmac('sha256', secret).update(`${time}.`).update(req.body).digest();
const valid = time
&& Math.abs(Date.now() / 1000 - time) <= 300
&& parts
.filter(([key]) => key === 'v1')
.map(([, value]) => Buffer.from(value || '', 'hex'))
.some((given) => given.length === expected.length && crypto.timingSafeEqual(given, expected));
if (!valid) return res.sendStatus(400);
const event = JSON.parse(req.body);
// put the event on your queue, keyed by event.id so a repeat is skipped
res.sendStatus(200);
});
app.listen(3000);# Python 3, Flask
import hashlib, hmac, json, os, time
from flask import Flask, abort, request
app = Flask(__name__)
secret = os.environ["MONOTREE_WEBHOOK_SECRET"] # whsec_…
@app.post("/hooks/monotree")
def monotree():
body = request.get_data() # the raw body, before any parsing
parts = [p.strip().split("=", 1) for p in request.headers.get("Monotree-Signature", "").split(",") if "=" in p]
t = next((int(value) for key, value in parts if key == "t" and value.isdigit()), 0)
expected = hmac.new(secret.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
valid = abs(time.time() - t) <= 300 and any(
hmac.compare_digest(expected, value) for key, value in parts if key == "v1"
)
if not valid:
abort(400)
event = json.loads(body)
# put the event on your queue, keyed by event["id"] so a repeat is skipped
return "", 200- Send yourself a
pingto see it work:
curl -X POST https://partners.monotree.com/api/v1/webhooks/whe_01jd1f4c8m2p0r6t9w3y5a7c1e/test \
-H "Authorization: Bearer $MONOTREE_TOKEN"The answer is the delivery, with your server's status code in response_code. The rest of this page explains each part.
Adding an endpoint
Add endpoints in the portal under Developers › Webhooks, or with Add a webhook endpoint. Each endpoint has:
- an
httpsURL that leads to a public address. AnhttpURL is refused (only an install of Monotree that runs locally or for tests takeshttpand local addresses). A URL whose host resolves to a private, loopback, link-local or otherwise reserved address is refused when you add it, and a delivery is not sent if the host has come to lead to one since; - the events it wants, or
*for all of them, including ones added later. A token subscribes an endpoint only to events it may read itself:customers:readforcustomer.*,seller.*andadoption.*events,support:readforsupport.*,webhooks:manageforwebhook_endpoint.*.*, and leavingeventsout, needs all three. Otherwise the answer is403 insufficient_ability, naming the ability that is missing. The same holds for the neweventswhen a token changes them. An admin in the portal can subscribe to everything; - a mode: an endpoint added with a live token gets live events, one added with a sandbox token gets sandbox events;
- a signing secret (
whsec_…), shown once when it is added. You can rotate it later.
You can have up to 10 endpoints per mode.
What is sent
Each event is a POST with a JSON body:
{
"id": "evt_01jcz8wg4h7v3y6n9q2k5m8p1r",
"object": "event",
"type": "customer.live",
"api_version": "1.0.0",
"created_at": "2026-11-12T09:42:18Z",
"sandbox": false,
"actor": { "type": "system", "name": "Monotree" },
"data": {
"customer": {
"id": "cus_01jcz8w3k1x9q2v7s4e6m0b5n8",
"object": "customer",
"status": "live",
"company_name": "Boulangerie Martin",
"company_id": "boulangeriemartin",
"url": "https://boulangeriemartin.monotree.com",
"external_ref": "org_48213"
},
"details": { "url": "https://boulangeriemartin.monotree.com", "admin_email": "claire@boulangeriemartin.example" }
}
}| Field | |
|---|---|
id |
The event's ID. The same on every retry and redelivery, and the ID Get an event takes |
type |
What happened. See Event types |
api_version |
The version of the API the event's data is written in, such as 1.0.0. See Versions |
created_at |
When it happened |
sandbox |
true for an event about sandbox data |
actor |
Who did it: type is user (a person in the portal), token (an API token, named API · <token name>) system (Monotree itself, such as a setup step), assistant (the support desk's assistant) or customer (someone at a customer who wrote to your support desk), with their name. null when nobody in particular did, as for an adoption alert |
data |
What the event is about |
For an event about a customer, data.customer is the whole customer as Get a customer returns it (trimmed in the example above), as it was right after the event, and data.details holds what is particular to the event. When an event has nothing to add, details is an empty object, {}: it is always an object, never a list and never left out. Other events carry their own object in data. See Event types.
The request carries these headers:
| Header | |
|---|---|
Monotree-Event |
The event type, such as customer.live |
Content-Type |
application/json |
Monotree-Event-Id |
The event's id (evt_…), so you can skip a repeat before parsing the body |
Monotree-Delivery |
The ID of this delivery (whd_…); the same on every retry |
Monotree-Api-Version |
The body's api_version |
Monotree-Signature |
t=<unix time>,v1=<signature>, see below. Two v1 values while a rotated secret is still valid |
User-Agent |
Monotree-Partners-Webhooks/1.0 |
Answering
Answer with any 2xx within 10 seconds. Do the work afterwards, in a queue on your side: a slow answer counts as a failure.
Anything else (another status, no answer in 10 seconds, no connection) is tried again:
| Try | Sent |
|---|---|
| 1 | at once |
| 2 | 10 seconds after try 1 failed |
| 3 | 1 minute later |
| 4 | 5 minutes later |
| 5 | 30 minutes later |
| 6 | 2 hours later |
That is six tries over about 2 hours and 36 minutes. After the sixth the delivery is failed and is not tried again by itself: redeliver it, or catch up. While it waits for its next try a delivery is retrying, and next_attempt_at says when. A redirect (3xx) is not followed: it counts as a failure, so give the final URL. A test event (ping) is tried once.
When an endpoint keeps failing
An endpoint that has had nothing but failed deliveries for 5 days in a row, at least 20 of them, is paused by Monotree: active turns false, paused_reason is failing and paused_at says since when. The check runs once a day. It counts from the endpoint's last delivered event, or from when it was last switched on.
When that happens:
- your company's admins get an email;
- a
webhook_endpoint.pausedevent goes to your other endpoints and to List events; - the portal shows Paused by Monotree next to the endpoint.
No events are sent to a paused endpoint, and none are kept waiting for it. Once your server answers again, switch the endpoint on in the portal or with PATCH /webhooks/{id} and "active": true, then catch up on what it missed. An endpoint you pause yourself has paused_reason: "manual".
Get a webhook endpoint shows an endpoint's health at a glance: failed_24h (deliveries that gave up in the last 24 hours) and last_delivery.
Catching up with GET /events
Every event is kept for 90 days, whether or not an endpoint was listening, and List events returns them with the same body their webhook carried. Use it when your server was down longer than the retries last, when an endpoint was paused, or to feed a new system.
Keep the id of the last event you handled and ask for what came after it:
curl "https://partners.monotree.com/api/v1/events?after=evt_01jcz8wg4h7v3y6n9q2k5m8p1r&limit=100" \
-H "Authorization: Bearer $MONOTREE_TOKEN"With after, events come oldest first, so you can handle them in order. While has_more is true, send the same call again with cursor set to next_cursor. type, customer and created_after narrow the list. If the event you name is older than 90 days the answer is 404: start from a time with created_after instead, and add order=asc to read forwards. The call needs the customers:read ability. To read support.* events the token also needs support:read, and for webhook_endpoint.* events webhooks:manage; events it may not read are left out of the list and answer 404 by their ID. Test events (ping) are not kept.
A sound integration uses both: webhooks to hear at once, and this list, read every few minutes or after a restart, to be sure nothing was missed. Run everything from your own system shows the loop.
Delivery log and redelivering
Which endpoints a token sees
Whoever controls an endpoint can have everything it gets, and everything it got, sent to a server of their choosing, and holds the secret your server trusts. So webhooks:manage alone is not enough to touch an endpoint. A token sees and touches an endpoint only when it may read:
- every event type the endpoint is subscribed to (
*means every type there is), and - every event type among the deliveries the endpoint still holds (the last 30 days).
For any other endpoint, every call answers 404 not_found, as if the endpoint were not there: reading it, changing its url, events, active or description, rotating its secret, sending a test event, deleting it, listing or reading its deliveries, and redelivering. List webhook endpoints leaves it out. A token for an integration that only manages its own endpoint needs the read abilities of that endpoint's events and no more; an endpoint for * is managed in the portal, or by a token with customers:read, support:read and webhooks:manage.
Every delivery, the body sent and your server's last answer are in the portal under Developers › Webhooks › Deliveries, and in the API with List deliveries and Get a delivery. Deliveries are kept for 30 days. Of your server's answer, the first 2,000 bytes are kept (response_body). Filter by status=failed to see what your server missed, by event_id to see how one event fared, or by event for one type.
Once your server is fixed, send a delivery again with Retry in the log or Redeliver a delivery. It is sent at once and the answer tells you how it went. Test events and redeliveries are sent while the call waits, so one endpoint takes at most 10 of them a minute. A delivered event can be sent again too, to try a change on your side. Retry all failed in the portal, or Redeliver failed deliveries, queues every failed delivery of the last 24 hours again (up to 100).
A redelivery is the same delivery starting over: the same Monotree-Delivery ID, the same body with the same event id, and the usual retries if it fails again. Its attempts start over at 1, and redeliveries counts how many times it was sent again, so a delivery that reads "1 try" after six failed ones says so. A retry that was already planned is replaced, so the event is not sent twice by Monotree. The body is the event as it was when it happened: read the customer if you need its state now.
Verifying signatures
Check every event before you trust it. The Monotree-Signature header looks like this:
Monotree-Signature: t=1794994938,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bdtis the Unix time (in seconds) at which Monotree sent this try.v1is the HMAC-SHA256 of the text<t>.<raw body>(the number, a full stop, then the body exactly as it arrived), with your endpoint's secret as the key, written as 64 lower-case hex characters. The whole secret is the key,whsec_included.
Compute the same value and compare it in constant time. Refuse events whose t is more than 5 minutes from your clock, so an old request cannot be replayed. Every try and every redelivery is signed afresh with a new t.
The quickstart has complete receivers in PHP, Node.js and Python. Below is the check alone, as a function, in five languages.
The header can hold more than one v1 (after a rotation, one for the new secret and one for the old). Accept the event if any of them matches, as the code below does.
function verifyMonotree(string $body, string $header, string $secret, int $tolerance = 300): bool
{
$time = 0;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
if ($key === 't') {
$time = (int) $value;
} elseif ($key === 'v1') {
$signatures[] = $value;
}
}
if (abs(time() - $time) > $tolerance) {
return false;
}
$expected = hash_hmac('sha256', $time.'.'.$body, $secret);
foreach ($signatures as $signature) {
if (hash_equals($expected, $signature)) {
return true;
}
}
return false;
}
$body = file_get_contents('php://input');
if (! verifyMonotree($body, $_SERVER['HTTP_MONOTREE_SIGNATURE'] ?? '', getenv('MONOTREE_WEBHOOK_SECRET'))) {
http_response_code(400);
exit;
}
$event = json_decode($body, true);import crypto from 'node:crypto';
export function verifyMonotree(rawBody, header, secret, tolerance = 300) {
const parts = header.split(',').map((p) => p.trim().split('='));
const time = Number((parts.find(([key]) => key === 't') || [])[1]);
if (!time || Math.abs(Date.now() / 1000 - time) > tolerance) return false;
const expected = crypto.createHmac('sha256', secret).update(`${time}.${rawBody}`).digest();
return parts
.filter(([key]) => key === 'v1')
.map(([, value]) => Buffer.from(value || '', 'hex'))
.some((given) => given.length === 32 && crypto.timingSafeEqual(expected, given));
}
// Express: keep the raw body for the check
app.post('/hooks/monotree', express.raw({ type: 'application/json' }), (req, res) => {
if (!verifyMonotree(req.body.toString(), req.get('Monotree-Signature') || '', process.env.MONOTREE_WEBHOOK_SECRET)) {
return res.sendStatus(400);
}
const event = JSON.parse(req.body);
res.sendStatus(200);
});import hashlib, hmac, time
def verify_monotree(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
parts = [p.strip().split("=", 1) for p in header.split(",") if "=" in p]
t = next((int(value) for key, value in parts if key == "t" and value.isdigit()), 0)
if abs(time.time() - t) > tolerance:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, value) for key, value in parts if key == "v1")
# Flask
@app.post("/hooks/monotree")
def monotree():
if not verify_monotree(request.get_data(), request.headers.get("Monotree-Signature", ""), os.environ["MONOTREE_WEBHOOK_SECRET"]):
abort(400)
event = request.get_json()
return "", 200func VerifyMonotree(body []byte, header, secret string, tolerance time.Duration) bool {
var t int64
var signatures []string
for _, part := range strings.Split(header, ",") {
kv := strings.SplitN(strings.TrimSpace(part), "=", 2)
if len(kv) != 2 {
continue
}
switch kv[0] {
case "t":
t, _ = strconv.ParseInt(kv[1], 10, 64)
case "v1":
signatures = append(signatures, kv[1])
}
}
if math.Abs(float64(time.Now().Unix()-t)) > tolerance.Seconds() {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
fmt.Fprintf(mac, "%d.%s", t, body)
expected := []byte(hex.EncodeToString(mac.Sum(nil)))
for _, signature := range signatures {
if hmac.Equal(expected, []byte(signature)) {
return true
}
}
return false
}public static boolean verifyMonotree(String body, String header, String secret) throws Exception {
long t = 0;
List<String> signatures = new ArrayList<>();
for (String part : header.split(",")) {
String[] kv = part.trim().split("=", 2);
if (kv.length == 2 && kv[0].equals("t")) t = Long.parseLong(kv[1]);
if (kv.length == 2 && kv[0].equals("v1")) signatures.add(kv[1]);
}
if (Math.abs(Instant.now().getEpochSecond() - t) > 300) return false;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] expected = HexFormat.of().formatHex(mac.doFinal((t + "." + body).getBytes(StandardCharsets.UTF_8))).getBytes();
boolean valid = false;
for (String signature : signatures) {
valid |= MessageDigest.isEqual(expected, signature.getBytes());
}
return valid;
}Use the raw body exactly as it arrived. Parsing and encoding the JSON again changes the bytes and breaks the signature.
Rotating the signing secret
Replace a secret from time to time, and at once if it may have leaked. In the portal choose Rotate secret in the endpoint's menu, or call Rotate the signing secret. The new secret is shown once.
To give you time to move your server over, the previous secret stays valid for 24 hours. Until then every event is signed with both, the new one first:
Monotree-Signature: t=1794994938,v1=<signature with the new secret>,v1=<signature with the previous secret>So nothing is refused while you deploy: a server that still has the old secret matches the second v1, one that has the new secret matches the first. After 24 hours only the new secret signs. previous_secret_expires_at on the endpoint says when.
Over the API, expire_previous_in sets that time in seconds, from 0 (the old secret stops at once: use it after a leak) to 7 days. The portal always uses 24 hours.
Duplicates and order
- An event can arrive more than once, for example when your answer was lost or a delivery was redelivered. Keep the
idof events you have handled (it is also in theMonotree-Event-Idheader) and skip repeats. - Events can arrive out of order across retries. Use
created_at, or the customer's state indata.customer, rather than arrival order. When in doubt, read the customer with Get a customer.
Testing
Press Test next to an endpoint in the portal, or call Send a test event. A ping event is sent at once and the answer shows your server's status code and time. Its id starts with evt_test_, and its data holds only a message. Sandbox and testing shows how to receive events on your own machine.