Developers

Webhooks

Get a signed HTTPS request the moment an API generation succeeds, fails or is canceled, instead of polling. Webhooks follow the open Standard Webhooks specification, so any of its libraries can verify them.

Overview

You register endpoints in Account › Webhooks. Each endpoint picks the events it wants, and receives them for every generation created through the API with any of your keys. Generations made on the website or in Discord don't send webhooks.

Delivery is at least once: the same event can arrive more than once, and events can arrive out of order. De-duplicate on the webhook-id header, and treat the generation in the API as the source of truth.

Quick start

  1. In Account › Webhooks, press Add endpoint, enter your public HTTPS URL and pick events.
  2. Copy the whsec_… signing secret. It's shown once; keep it in a secret manager or an environment variable such as CRAFTFUL_WEBHOOK_SECRET.
  3. Verify every request's signature (below) and answer with any 2xx within 15 seconds.
  4. Press Send test event and watch the result under Recent deliveries.
  5. On generation.succeeded, call GET /generations/{id} with your API key for the outputs and fresh download links.

Events

TypeSent when
generation.succeededAn API generation finished; its outputs are ready.
generation.failedAn API generation failed, for any error code. It was refunded.
generation.canceledA queued API generation was canceled. It was refunded.
webhook.testYou pressed “Send test event” in Account › Webhooks.

Payloads

Every body is JSON in the Standard Webhooks shape, {type, timestamp, data}, and deliberately thin. Payloads never contain media URLs: download links are bearer credentials that end up in logs. Fetch the generation for its outputs. A failed generation is refunded in full and carries an error with a stable code (the same codes as GET /generations/{id}).

generation.succeeded
{
  "type": "generation.succeeded",
  "timestamp": "2026-11-12T10:15:03.180Z",
  "data": {
    "object": "generation",
    "id": "gen_812345",
    "status": "succeeded",
    "mode": "video",
    "model": "seedance-2.5",
    "api_key_id": "key_8sT2kQ9vXc1mZ4pL",
    "cost_credits": 270,
    "credits_charged": 270,
    "credits_refunded": 0,
    "output_count": 1,
    "error": null
  }
}
generation.failed
{
  "type": "generation.failed",
  "timestamp": "2026-11-12T10:15:03.180Z",
  "data": {
    "object": "generation",
    "id": "gen_812345",
    "status": "failed",
    "mode": "video",
    "model": "seedance-2.5",
    "api_key_id": "key_8sT2kQ9vXc1mZ4pL",
    "cost_credits": 270,
    "credits_charged": 0,
    "credits_refunded": 270,
    "output_count": 0,
    "error": {
      "code": "provider_timeout",
      "message": "The model provider didn't finish in time. You weren't charged.",
      "retryable": true
    }
  }
}
webhook.test
{
  "type": "webhook.test",
  "timestamp": "2026-11-12T10:15:03.180Z",
  "data": {
    "object": "test",
    "message": "Hello from Craftful"
  }
}

New fields may be added to payloads at any time; ignore the ones you don't know. The OpenAPI document (openapi.json) describes every event under webhooks.

Headers

HeaderValue
webhook-idThe event id, evt_<n> (evt_test_… for test events). The same on every retry.
webhook-timestampUnix seconds of this attempt.
webhook-signaturev1,<base64 signature>. May hold several signatures separated by spaces; accept the request if any v1 one matches.
content-typeapplication/json
user-agentCraftful-Webhooks/1.0

Verify signatures

The signature is an HMAC-SHA256, keyed with the bytes of your secret (the base64 text after whsec_, decoded), over {webhook-id}.{webhook-timestamp}.{raw body}, then base64-encoded. Always verify against the raw request body, before any JSON parsing, and reject timestamps more than 5 minutes from your clock so a captured request can't be replayed.

The simplest way is a Standard Webhooks library (they exist for JavaScript, Python, Go, Ruby, PHP, Java, C#, Rust and Elixir):

Node.js (Express)
// npm install standardwebhooks express
import express from "express";
import { Webhook } from "standardwebhooks";

const app = express();
const wh = new Webhook(process.env.CRAFTFUL_WEBHOOK_SECRET); // "whsec_…"

// Verify against the raw body: the exact bytes that were signed.
app.post("/webhooks/craftful", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = wh.verify(req.body.toString("utf8"), req.headers);
  } catch {
    return res.status(400).send("Invalid signature");
  }
  res.sendStatus(204); // acknowledge first, then do the work

  // webhook-id is the same on every retry: skip ids you've already handled.
  if (event.type === "generation.succeeded") {
    const generation = await fetch(`https://craftful.ai/api/v1/generations/${event.data.id}`, {
      headers: { Authorization: `Bearer ${process.env.CRAFTFUL_API_KEY}` },
    }).then((r) => r.json());
    // generation.outputs[i].url are fresh signed download links
  }
});

app.listen(3000);
Python (FastAPI)
# pip install standardwebhooks fastapi
import os
from fastapi import FastAPI, Request, Response
from standardwebhooks.webhooks import Webhook

app = FastAPI()
wh = Webhook(os.environ["CRAFTFUL_WEBHOOK_SECRET"])  # "whsec_…"

@app.post("/webhooks/craftful")
async def craftful_webhook(request: Request):
    body = await request.body()  # the exact bytes that were signed
    try:
        event = wh.verify(body, dict(request.headers))
    except Exception:
        return Response(status_code=400)

    # webhook-id is the same on every retry: skip ids you've already handled,
    # and hand the work to a queue so you can answer quickly.
    if event["type"] == "generation.succeeded":
        ...  # GET /api/v1/generations/{event["data"]["id"]} for the outputs
    return Response(status_code=204)

Or verify by hand, with nothing but the standard library:

Node.js
import crypto from "node:crypto";

// rawBody: the request body exactly as received (a string), before any JSON parsing.
function verifyCraftfulWebhook(rawBody, headers, secret) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) throw new Error("Missing webhook headers");
  if (!/^\d+$/.test(timestamp)) throw new Error("Invalid timestamp");
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 5 * 60) throw new Error("Timestamp too old or too new");

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = crypto.createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest();
  const valid = signatures.split(" ").some((entry) => {
    const [version, signature] = entry.split(",");
    if (version !== "v1" || !signature) return false;
    const received = Buffer.from(signature, "base64");
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
  if (!valid) throw new Error("Invalid signature");
  return JSON.parse(rawBody);
}
Python
import base64, hashlib, hmac, json, time

# raw_body: the request body bytes exactly as received.
def verify_craftful_webhook(raw_body: bytes, headers, secret: str):
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        raise ValueError("Missing webhook headers")
    if not (timestamp.isascii() and timestamp.isdigit()):
        raise ValueError("Invalid timestamp")
    if abs(time.time() - int(timestamp)) > 5 * 60:
        raise ValueError("Timestamp too old or too new")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest())
    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        # Compare bytes: compare_digest refuses str with non-ASCII characters.
        if version == "v1" and hmac.compare_digest(signature.encode(), expected):
            return json.loads(raw_body)
    raise ValueError("Invalid signature")

Responding

  • Any 2xx within 15 seconds acknowledges the event. Answer first and do slow work afterwards, or on a queue. The connection itself (TCP and TLS) must be up within 5 seconds.
  • Redirects are never followed: a 3xx counts as a failure. Register the final URL.
  • 410 Gone tells us the endpoint no longer exists: it is disabled at once.
  • 429 and 503 may carry a Retry-After header (seconds or an HTTP date): we won't send that endpoint anything sooner.
  • 401, 403 and 429 mean you're refusing us (usually a signature check or a firewall): the endpoint is held back between tries, and if the refusals go on for over an hour (5 or more in a row), it is disabled. Rolling the secret mid-deploy can't trip it.
  • We read at most 64 KB of your response. The first 500 bytes, and the status code and latency, show in the endpoint's Recent deliveries to help you debug.

Retries

Anything other than a 2xx or a 410 (an error status, a timeout, a refused connection, a TLS error) is retried with this schedule, each wait ±10% so retries don't arrive in lockstep:

AttemptSent
1Right away
21 min after attempt 1
35 min after attempt 2
430 min after attempt 3
52 h after attempt 4
66 h after attempt 5
712 h after attempt 6
824 h after attempt 7
924 h after attempt 8

That's 9 attempts over about 2.9 days. Each attempt is signed with a fresh timestamp; webhook-id and the body stay the same. When the last attempt fails, the delivery is marked failed.

When your endpoint doesn't answer at all (a timeout, a refused connection, a TLS error) or answers 401, 403, 429 or 503, we hold back the whole endpoint, not just that delivery: nothing else is sent to it for 1 minute, then 5, then at most 15 minutes between tries (longer only if your Retry-After asks), however many deliveries are queued. The first other answer (a success, or any other status) ends the hold, and a successful test event ends it at once. Problems on our side, such as our DNS failing, don't count against your endpoint. If lookups of your domain keep failing for a day while ours answer other lookups, though, the problem is your domain's DNS: from then on each try counts as a failed attempt, as if your endpoint didn't answer.

Auto-disable and resending

  • When every attempt has failed for 4 days, across more than one delivery, with no success in between (or 3 deliveries in a row fail every attempt), the endpoint is disabled and shows as Failing. Any successful delivery resets the clock, and so does a day without any failure: one delivery your endpoint keeps rejecting can't disable it on its own.
  • Refusals (401, 403, 429) that go on for over an hour, 5 or more in a row, disable it too.
  • A URL that can't receive webhooks (for example one that points at a service Craftful itself uses) is disabled at its first attempt: change the URL and enable it again.
  • A disabled endpoint gets nothing. If you disabled it or it answered 410, its queued deliveries are canceled; if it was disabled for failing, refusing or its URL, they are marked failed, so you can resend them once it works again.
  • Enabling it again starts afresh and replays nothing. To catch up, use Resend failed (failed deliveries from the last 7 days, the oldest 100 at a time) or Resend on a single delivery (up to 29 days after its event). A resend starts a fresh retry schedule. Test events aren't resent: send a new one.
  • If you move to a plan with fewer endpoints, your oldest enabled endpoints up to the new limit keep working and the rest are paused (they get nothing) until you disable or delete others, or upgrade.
  • Delivery history is kept for 30 days after each event (and at least 7 days after a delivery last changed). A delivery still waiting 30 days after its event is marked failed, as Expired, not dropped; by then it is too old to resend.
  • Deliveries pause while an account is suspended and resume when it is restored.

Test events

Send test event posts a signed webhook.test event to the endpoint right away, with data: {object: "test", message: "Hello from Craftful"}. It gets one attempt, no retries and no resend, and never counts toward auto-disable. You can send 10 per endpoint per hour. The endpoint must be enabled.

URL rules

Endpoint URLs are checked when you add or change them, and again before every attempt:

  • https:// only, on port 443 or 1024-65535, with no user name or password in the URL.
  • The host must be public. Every address it resolves to must be a public unicast address: loopback, private (10/8, 172.16/12, 192.168/16), link-local (including 169.254.169.254), carrier-grade NAT (100.64/10), multicast, reserved and documentation ranges are refused, in IPv4, IPv6 and IPv4-mapped IPv6 form, as are local names such as localhost or *.internal.
  • Craftful's own hosts are refused.
  • So are the services Craftful itself relies on, such as Discord, Stripe and our AI providers, with all their subdomains: point webhooks at your own server, and forward from there if you need to.
  • We connect to the address we checked, so a DNS answer that changes in between can't redirect a delivery.

A refused URL gets the error invalid_webhook_url, with one of these reasons:

ReasonMeaning
schemeNot an https:// URL (or not a URL at all).
credentialsThe URL has a user name or password in it.
portA port other than 443 or 1024-65535.
private_addressThe URL names a private, local or reserved address, or a local name such as localhost or *.internal.
own_hostThe host is one of Craftful's own.
blocked_hostThe host belongs to a service Craftful relies on, such as Discord or Stripe.
unresolvableThe host name doesn't resolve to a public address: it doesn't resolve at all, or only to addresses we don't deliver to.

Signing secrets

  • Each endpoint has its own secret: whsec_ followed by 32 random bytes in base64. We show it once, when you add the endpoint or roll the secret.
  • Roll secret replaces it immediately: every delivery after that is signed only with the new secret, so update your receiver right away.
  • We store secrets encrypted, never in plain text.

Limits

Adding an endpoint, changing its URL, sending a test event and resending share a limit of 20 a minute per account. Each account has at most 2 deliveries in flight at a time, and accounts take turns when deliveries queue up.

  • Resends queue at most 1,000 deliveries per account per day (UTC), 100 per press of Resend failed. Resending a delivery that never got its full set of attempts (because its endpoint was disabled) doesn't count, the first time.
  • Up to 1,000 deliveries per endpoint are lined up to go out at once. More wait their turn, shown as pending and “queued”, and move up in order, oldest first, as earlier ones go out; waiting never fails them (one still waiting after 30 days expires).
  • To protect the services behind them, we send at most a few requests a second to any one host name or address, counting every account; more wait their turn (they aren't failed).
PlanWebhook endpoints
Free2
Pro5
Ultra10
Studio20