settlekit/docs/WEBHOOKS.md
caelum0x 7ad4ec44c0 fix(sdk-go): VerifyEntitlement decoded the wrong field — always "not allowed"
VerifyEntitlementResult.Granted had json tag "granted", but the real API
(apps/api/src/routes/entitlements.ts -> packages/entitlements's
EntitlementService.verify / ServiceVerifyResult) has only ever returned
"allowed". encoding/json leaves unmatched fields at their zero value, so
Granted silently decoded to false for every real response — any Go backend
gating paid access via this SDK denied every real, fully-paid customer, with
no error ever raised. Same bug shape as the already-fixed Python x402
verifier (a27d0051): an SDK's only production path silently rejecting
everything real.

Rename Granted -> Allowed (json:"allowed"), add the Entitlement and Value
fields the API actually returns, and give Raw a real UnmarshalJSON instead of
a json:"-" tag that silently excluded it from ever being populated despite the
doc comment's "preserved in Raw" claim. Add Email support to
VerifyEntitlementInput/ListEntitlementsOptions, matching the API's own
"check by the buyer's checkout email instead of a customer id" capability,
which the Go SDK had no way to express. Add the first regression tests for
this file (sdks/go had none): one that would not even compile against the old
field names, proving this isn't a cosmetic rename.

Also fix a second real blocker for any Go developer trying to use this SDK at
all: go.mod's module path (github.com/settlekit/settlekit-go) and every
README/docs reference to it pointed at a GitHub org that does not exist
(confirmed 404 on github.com and the Go module proxy) — `go get` of the
documented path fails for everyone. Changed the module path to this
repository's real path (github.com/caelum0x/settlekit/sdks/go) and updated
sdks/go/README.md, docs/WEBHOOKS.md, docs/RELEASING-SDKS.md to match.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-26 17:47:07 +03:00

5.5 KiB

SettleKit Webhooks

Webhooks let your server react to SettleKit events in real time — a payment confirmed, an entitlement granted, a delivery completed, a subscription renewed. This guide covers registering endpoints, the event payload, and — most importantly — verifying signatures so you can trust the data.

Register an endpoint

curl -s -H "Authorization: Bearer $SETTLEKIT_API_KEY" -H "content-type: application/json" \
  -d '{"organizationId":"org_1","url":"https://yourapp.com/webhooks/settlekit","enabledEvents":["payment.confirmed","delivery.completed"]}' \
  $SETTLEKIT_API_URL/v1/webhooks/endpoints

The response includes a signingSecret (shown once) — store it as a secret on your server. SettleKit signs every delivery to this endpoint with it.

You can also register via any SDK, e.g. TypeScript:

const endpoint = await sk.webhooks.createEndpoint({
  organizationId: "org_1",
  url: "https://yourapp.com/webhooks/settlekit",
  enabledEvents: ["payment.confirmed"],
});
console.log(endpoint.signingSecret); // store this

The event payload

Each delivery POSTs a JSON event:

{
  "id": "evt_…",
  "type": "payment.confirmed",
  "data": { "paymentId": "pay_…", "amount": { "amount": "25.00", "currency": "USDC" } },
  "createdAt": "2026-06-16T00:00:00.000Z"
}

Verifying the signature (do this!)

Every delivery carries a Stripe-style signature header:

SettleKit-Signature: t=<unix-seconds>,v1=<hex hmac-sha256("<t>.<raw body>", signingSecret)>

During a secret rotation the header carries one v1 per active secret (t=..,v1=<new>,v1=<old>) until the grace window ends; accept the delivery when any v1 matches. The SDK verifiers (TypeScript, Python, Go, Rust) and the WooCommerce plugin already do.

Always verify against the RAW request body (the exact bytes you received) — never re-serialize the parsed JSON, since key order and whitespace must match. SettleKit's SDKs ship a constant-time verifier with replay protection (a default 5-minute tolerance on t).

TypeScript / Node

import { verifyWebhookSignature } from "@settlekit/sdk";
import express from "express";

const app = express();
// Capture the RAW body for this route.
app.post("/webhooks/settlekit", express.raw({ type: "application/json" }), (req, res) => {
  const raw = req.body.toString("utf8");
  const sig = req.header("SettleKit-Signature") ?? "";
  if (!verifyWebhookSignature(process.env.WEBHOOK_SECRET!, raw, sig)) {
    return res.status(400).send("invalid signature");
  }
  const event = JSON.parse(raw);
  // … handle event.type …
  res.json({ received: true });
});

Python

from settlekit import verify_webhook_signature
from fastapi import FastAPI, Request, Response

app = FastAPI()

@app.post("/webhooks/settlekit")
async def webhook(request: Request):
    raw = (await request.body()).decode("utf-8")
    sig = request.headers.get("settlekit-signature", "")
    if not verify_webhook_signature(os.environ["WEBHOOK_SECRET"], raw, sig):
        return Response(status_code=400, content="invalid signature")
    event = json.loads(raw)
    # … handle event["type"] …
    return {"received": True}

Go

import settlekit "github.com/caelum0x/settlekit/sdks/go"

func handler(w http.ResponseWriter, r *http.Request) {
    raw, _ := io.ReadAll(r.Body)
    sig := r.Header.Get(settlekit.SignatureHeader) // "SettleKit-Signature"
    if !settlekit.VerifySignature(os.Getenv("WEBHOOK_SECRET"), raw, sig) {
        http.Error(w, "invalid signature", http.StatusBadRequest)
        return
    }
    // … decode + handle the event …
    w.WriteHeader(http.StatusOK)
}

Retries & at-least-once delivery

SettleKit (and the optional services/webhook-relay) retry failed deliveries with exponential backoff (a short in-tick retry, then 1m, 2m, 4m ... capped at 6h, up to 24 attempts per delivery). Each delivery is signed with a 10 second timeout per attempt. After 100 failed attempts in a row (WEBHOOK_DISABLE_AFTER_FAILURES) the endpoint is disabled and its reason is shown in the dashboard; re-enable it once your server is fixed. Treat handlers as idempotent — key on event.id and ignore an event you've already processed. Return a 2xx quickly (do heavy work asynchronously); non-2xx responses are retried until the schedule is exhausted.

Tips

  • Respond fast (2xx) and process out-of-band; SettleKit times out slow handlers.
  • Verify before parsing untrusted JSON.
  • Rotate the signing secret with POST /v1/webhooks/endpoints/:id/rotate-secret ({ "graceHours": 24 }, 0-168). The previous secret keeps signing deliveries until the grace window ends, so deploy the new secret without downtime.
  • Send a signed webhook.test event to one endpoint: POST /v1/webhooks/endpoints/:id/test.
  • Event log: GET /v1/webhooks/deliveries (filters eventId, endpointId, status) lists every delivery with its attempts, response codes, errors and next retry; GET /v1/webhooks/deliveries/:id returns one with its history. Resend any event with POST /v1/webhooks/events/:id/resend (optionally { "endpointId": "..." }).
  • Stop or resume deliveries: POST /v1/webhooks/endpoints/:id/disable and /enable.
  • The dashboard Webhooks page has all of these (Send test, Rotate secret, Disable/Enable, Event log with Resend).
  • In dev, emit a test event: POST /v1/webhooks/events {organizationId,type,data} returns the signed deliveries so you can replay them locally.

See API.md for the full webhook endpoint reference.