Developers
Webhooks
Receive signed events: Standard Webhooks signatures, verification in PHP, Node and Python, retries, test events and the event list.
On this page
Webhooks send an HTTPS POST to your server when something happens in your account. Each delivery is signed, so you can prove it came from us, and retried until your server accepts it.
Set up an endpoint#
- Build a route on your server that accepts
POSTwith a JSON body. - Register its URL in Developers → Webhooks, or with
POST /v1/webhook-endpoints(see the quickstart). - Choose the events to receive, or
*for all of them. - Save the signing secret (
whsec_…). It is shown once. - Press Send test event to try it.
Rules for the URL: it must be https:// on port 443, with no user name or password in it, and it must resolve to a public internet address. Private, loopback, link-local and cloud metadata addresses are refused with 422 webhook_url_not_allowed. We check this again before every delivery, and we never follow redirects. You can have up to 10 endpoints in each mode. Test endpoints only get test events; live endpoints only get live events.
What a delivery looks like#
POST /webhooks/studio HTTP/1.1
Host: example.com
Content-Type: application/json
User-Agent: MutexAI-Studio-Webhooks/1.0
webhook-id: evt_01JD3Y0B7R2K9W4Q6M8N1P3S5T
webhook-timestamp: 1794907920
webhook-signature: v1,fRxU6hOUWvhqcsPUn3Xqxqg8GEvanEtCGDQ7vUR641s=
{"id":"evt_01JD3Y0B7R2K9W4Q6M8N1P3S5T","type":"webhook.test","timestamp":"2026-11-17T09:32:00Z","livemode":false,"data":{"id":"we_01JD3XK5Z3Q8W3J9P2R7M4N6T1","object":"webhook_endpoint","message":"This is a test event from MutexAI Studio."}}
| Header | What it is |
|---|---|
webhook-id | The event id (evt_…). The same on every retry, so use it to skip duplicates. |
webhook-timestamp | When this attempt was sent, in Unix seconds. New on every retry. |
webhook-signature | One or more signatures, like v1,<base64>, separated by spaces. |
The body has the event id, its type, a timestamp, livemode and data. Payloads are thin on purpose: ids and status, never image bytes or long-lived links. Fetch the full object from the API when you need it.
Verify the signature#
We follow the Standard Webhooks specification, so any Standard Webhooks library works. The signature is:
base64( HMAC-SHA256( key, "{webhook-id}.{webhook-timestamp}.{raw body}" ) )
where key is your secret without the whsec_ prefix, base64-decoded to bytes. To verify:
- Read the raw body exactly as it arrived. If your framework parses JSON first, the bytes can change and the signature will not match.
- Refuse the request if
webhook-timestampis more than 5 minutes away from your clock. This stops replays. - Compute the signature and compare it, in constant time, with each
v1,value inwebhook-signature. One match is enough. - Answer with any
2xxstatus as soon as you can, then do the work in the background.
<?php
/**
* Verifies a MutexAI Studio webhook (Standard Webhooks, v1 signatures) and returns the event.
* Throws when a header is missing, the timestamp is outside the tolerance, or no signature matches.
*
* @param string $payload The raw request body, exactly as received. Do not decode it first.
* @param array<string, string|list<string>> $headers The request headers (any letter case).
* @param string $secret The endpoint's signing secret, "whsec_…".
* @return array<string, mixed>
*/
function verifyStudioWebhook(string $payload, array $headers, string $secret, int $toleranceSeconds = 300): array
{
$header = function (string $name) use ($headers): string {
foreach ($headers as $key => $value) {
if (strtolower((string) $key) === $name) {
return is_array($value) ? (string) ($value[0] ?? '') : (string) $value;
}
}
return '';
};
$id = $header('webhook-id');
$timestamp = $header('webhook-timestamp');
$signatures = $header('webhook-signature');
if ($id === '' || ! ctype_digit($timestamp) || $signatures === '') {
throw new RuntimeException('Missing webhook-id, webhook-timestamp or webhook-signature.');
}
if (abs(time() - (int) $timestamp) > $toleranceSeconds) {
throw new RuntimeException('The webhook timestamp is too old or too far in the future.');
}
$key = base64_decode(str_starts_with($secret, 'whsec_') ? substr($secret, 6) : $secret, true);
$expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$payload}", (string) $key, true));
// During a secret rotation the header holds several signatures, separated by spaces.
foreach (explode(' ', $signatures) as $signature) {
[$version, $value] = array_pad(explode(',', $signature, 2), 2, '');
if ($version === 'v1' && hash_equals($expected, $value)) {
return json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
}
}
throw new RuntimeException('No webhook signature matched.');
}
import crypto from 'node:crypto';
/**
* Verifies a MutexAI Studio webhook (Standard Webhooks, v1 signatures) and returns the event.
* `payload` must be the raw body string, exactly as received. Throws when verification fails.
*/
export function verifyStudioWebhook(payload, headers, secret, toleranceSeconds = 300) {
const header = (name) => {
const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
const value = entry ? entry[1] : '';
return Array.isArray(value) ? String(value[0] ?? '') : String(value ?? '');
};
const id = header('webhook-id');
const timestamp = header('webhook-timestamp');
const signatures = header('webhook-signature');
if (!id || !/^\d+$/.test(timestamp) || !signatures) {
throw new Error('Missing webhook-id, webhook-timestamp or webhook-signature.');
}
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) {
throw new Error('The webhook timestamp is too old or too far in the future.');
}
const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
const expected = crypto.createHmac('sha256', key).update(`${id}.${timestamp}.${payload}`).digest();
// During a secret rotation the header holds several signatures, separated by spaces.
for (const signature of signatures.split(' ')) {
const [version, value = ''] = signature.split(',', 2);
const given = Buffer.from(value, 'base64');
if (version === 'v1' && given.length === expected.length && crypto.timingSafeEqual(given, expected)) {
return JSON.parse(payload);
}
}
throw new Error('No webhook signature matched.');
}
import base64
import hashlib
import hmac
import json
import time
def verify_studio_webhook(payload: bytes, headers: dict, secret: str, tolerance_seconds: int = 300) -> dict:
"""Verify a MutexAI Studio webhook (Standard Webhooks, v1 signatures) and return the event.
`payload` must be the raw request body, exactly as received. Raises ValueError on failure.
"""
lowered = {str(key).lower(): value for key, value in headers.items()}
msg_id = lowered.get("webhook-id", "")
timestamp = lowered.get("webhook-timestamp", "")
signatures = lowered.get("webhook-signature", "")
if not msg_id or not timestamp.isdigit() or not signatures:
raise ValueError("Missing webhook-id, webhook-timestamp or webhook-signature.")
if abs(time.time() - int(timestamp)) > tolerance_seconds:
raise ValueError("The webhook timestamp is too old or too far in the future.")
key = base64.b64decode(secret.removeprefix("whsec_"))
signed = f"{msg_id}.{timestamp}.".encode() + payload
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
# During a secret rotation the header holds several signatures, separated by spaces.
for signature in signatures.split(" "):
version, _, value = signature.partition(",")
if version == "v1" and hmac.compare_digest(expected, value):
return json.loads(payload)
raise ValueError("No webhook signature matched.")
Using it in a web framework:
<?php
// routes/web.php (exclude this path from CSRF in bootstrap/app.php)
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::post('/webhooks/studio', function (Request $request) {
try {
$event = verifyStudioWebhook(
$request->getContent(), // the raw body
$request->headers->all(),
config('services.studio.webhook_secret'),
);
} catch (RuntimeException) {
abort(400);
}
// Answer fast, then do the work in a queued job. Use $event['id'] to skip duplicates.
HandleStudioEvent::dispatch($event);
return response()->noContent();
});
import express from 'express';
import { verifyStudioWebhook } from './verify.mjs';
const app = express();
// express.raw keeps the body as bytes, so the signature is checked on exactly what was sent.
app.post('/webhooks/studio', express.raw({ type: 'application/json' }), (req, res) => {
let event;
try {
event = verifyStudioWebhook(req.body.toString('utf8'), req.headers, process.env.STUDIO_WEBHOOK_SECRET);
} catch {
return res.sendStatus(400);
}
// Answer fast, then do the work in the background. Use event.id to skip duplicates.
queueStudioEvent(event);
res.sendStatus(204);
});
app.listen(3000);
import os
from flask import Flask, abort, request
from verify import verify_studio_webhook
app = Flask(__name__)
@app.post("/webhooks/studio")
def studio_webhook():
try:
event = verify_studio_webhook(request.get_data(), dict(request.headers), os.environ["STUDIO_WEBHOOK_SECRET"])
except ValueError:
abort(400)
# Answer fast, then do the work in the background. Use event["id"] to skip duplicates.
queue_studio_event(event)
return "", 204
Retries#
A delivery succeeds when your server answers with a 2xx status within 10 seconds. Anything else (a timeout, a 3xx redirect, a 4xx or 5xx) is a failure, and we try again after:
1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours, 1 day.
That is 8 attempts over about two days. Each attempt has a fresh timestamp and signature, but the same webhook-id.
- If an endpoint keeps failing for more than 3 days without one success, we turn it off and email you. Fix your server, then press Turn on on the endpoint.
- Every attempt is listed under Recent deliveries on the endpoint, with the status code, time taken and next retry. Resend queues a delivery again.
- Events can arrive more than once, and not always in order. Store the
webhook-idof events you have handled and skip repeats. Use thetimestampin the body, not the arrival order.
Rotate the secret#
Press Rotate secret on the endpoint to get a new one. For 24 hours we sign every delivery with both the new and the old secret, so webhook-signature holds two values. Deploy the new secret within that time and nothing is missed. The verification code above already accepts any matching signature.
Test events#
Send test event sends a webhook.test event to that one endpoint. It is signed and retried like any other event, and shows in the delivery log. You can also fetch any event you received to confirm it is real:
curl https://studio-api.mutexai.net/v1/events/evt_01JD3Y0B7R2K9W4Q6M8N1P3S5T \
-H "Authorization: Bearer $MUTEXAI_API_KEY"
{
"object": "event",
"id": "evt_01JD3Y0B7R2K9W4Q6M8N1P3S5T",
"type": "webhook.test",
"livemode": false,
"data": {
"id": "we_01JD3XK5Z3Q8W3J9P2R7M4N6T1",
"object": "webhook_endpoint",
"message": "This is a test event from MutexAI Studio."
},
"created_at": "2026-11-17T09:32:00Z"
}
GET /v1/events/{id} needs the webhooks:manage scope and only finds events in the key's own account and mode.
Event types#
| Type | When | Status |
|---|---|---|
set.succeeded |
A photo set is finished. Has the set id and its output ids. | Coming soon |
set.failed |
A photo set could not be finished. Held credits were returned. | Coming soon |
set.needs_confirmation |
We read the poster and need you to confirm the colours. | Coming soon |
background.succeeded |
A background job is finished. | Coming soon |
background.failed |
A background job failed and its credit was returned. | Coming soon |
logo.succeeded |
A logo job is finished. | Coming soon |
logo.failed |
A logo job failed and its credits were returned. | Coming soon |
moderation.blocked |
An upload or result was blocked by our content rules. | Coming soon |
credits.low_balance |
Your available credits fell below your low-balance level. | Coming soon |
credits.purchased |
A payment was confirmed and credits were added. | Coming soon |
api_key.revoked |
An API key was revoked. Has the key id, name, prefix and reason. | Sent today |
webhook.test |
Sent when you press "Send test event". You cannot subscribe to it; it always goes to the endpoint you tested. | Sent today |
You can subscribe to events that are coming soon now. Your endpoint starts getting them on the day they ship.
{
"id": "evt_01JD3Z8W4C6T2N8R0K5Q7M9P1X",
"type": "api_key.revoked",
"timestamp": "2026-11-17T10:05:41Z",
"livemode": true,
"data": {
"id": "key_01JD3V2M8Q4R6T9W1Y3B5C7D9F",
"name": "Shop backend",
"object": "api_key",
"prefix": "mx_live_Ab3dEf12_…",
"reason": "revoked_by_user"
}
}
Manage endpoints with the API#
/v1/webhook-endpoints
webhooks:manage
/v1/webhook-endpoints
webhooks:manage
/v1/webhook-endpoints/{id}
webhooks:manage
/v1/webhook-endpoints/{id}
webhooks:manage
curl -X DELETE https://studio-api.mutexai.net/v1/webhook-endpoints/we_01JD3XK5Z3Q8W3J9P2R7M4N6T1 \
-H "Authorization: Bearer $MUTEXAI_API_KEY"
{
"object": "webhook_endpoint",
"id": "we_01JD3XK5Z3Q8W3J9P2R7M4N6T1",
"deleted": true
}
Rotating the secret, sending test events, turning an endpoint back on and resending deliveries are in the dashboard. Full parameters are in the API reference.
Troubleshooting#
- Nothing arrives. Check the endpoint is on, subscribes to the event, and is in the same mode (test or live) as the event. Check your firewall allows our requests.
- Every signature fails. You are probably verifying a parsed and re-encoded body. Use the raw bytes. Also check you removed
whsec_and base64-decoded the secret. - Timestamps fail. Your server clock is off. Turn on NTP time sync.
- Deliveries time out. Answer within 10 seconds. Queue slow work instead of doing it before you answer.
- "blocked" in the delivery log. The URL now resolves to a private address. Fix its DNS.
Still stuck? Email [email protected] with what you tried and, for API problems, the request_id.