Skip to content
Anlyon
Esc
↑↓navigate↵open⌘Jpreview
On this page

Events and webhooks

Subscribe an endpoint to approval, action, end-user and environment events, verify each delivery's signature, and act on the events.

Your app needs to know when something happens that it did not start: a refund is waiting for a reviewer, a call ended unknown and needs reconciling, a user connected their Gmail, someone halted production. Polling for all of that costs requests and adds delay. A webhook subscription tells you as it happens.

Anlyon POSTs a signed JSON envelope to your endpoint for each event you subscribe to. The SDKs verify the signature, so a forged request is rejected before your handler runs.

How it works

  1. Anlyon publishes platform events to a reserved topic named anlyon in your workspace.
  2. You subscribe an HTTPS endpoint to that topic, with the event types you want.
  3. For each matching event, Anlyon POSTs one envelope to the endpoint, signed with the subscription’s secret.
  4. Your handler verifies the signature, then reads the approval, invocation or effect the event names. The record is the source of truth. The event is a prompt to go and read it.

Subscribe an endpoint

Needs events:write, which is in the default set. The events land on the reserved topic of the workspace’s default environment, so create the subscription with a key bound to that environment.

import { Client } from '@anlyonhq/sdk';

const client = new Client({ apiKey: process.env.ANLYON_API_KEY! });

const { data } = await client.events.createSubscription('anlyon', {
  url: 'https://your-app.com/anlyon/events',
  eventTypes: ['approval.*', 'action.*', 'end_user.*', 'environment.*'],
  generateSecret: true,
});

console.log(data!.secret); // the signing secret is returned once, on create
curl -X POST https://api.anlyon.com/api/v2/events/topics/anlyon/subscriptions \
  -H "Authorization: Bearer $ANLYON_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/anlyon/events",
    "eventTypes": ["approval.*", "action.*", "end_user.*", "environment.*"],
    "generateSecret": true
  }'
import os
from anlyon import Client

client = Client(api_key=os.environ["ANLYON_API_KEY"])

subscription = client.events.create_subscription(
    "anlyon",
    url="https://your-app.com/anlyon/events",
    event_types=["approval.*", "action.*", "end_user.*", "environment.*"],
    generate_secret=True,
).data

print(subscription["secret"])  # the signing secret is returned once, on create

Store the secret as ANLYON_SIGNING_SECRET on the server that receives the webhooks. Event types match as exact names or prefix globs (approval.*). Left out, eventTypes is ["*"], every event. A subscription takes up to 50 patterns.

Events you can subscribe to

Event type When data carries
approval.requested An approval was created: by a gated action, a function plan or approvals.request approvalId, kind (action, custom or function_plan), title, expiresAt
approval.approved, approval.denied A decision was recorded, by a reviewer, a policy or the end user approvalId, kind, title
approval.expired Nobody decided in time approvalId, kind, title
action.succeeded, action.failed Anlyon made the call and recorded the outcome actionName, invocationId, and effectId for a governed action
action.unknown The outcome could not be confirmed. Reconcile before anyone retries actionName, invocationId, and effectId for a governed action
action.invocation.blocked A halt, or a refused check on a governed effect (such as a limit), stopped the call before dispatch invocationId, reason
end_user.connected, end_user.disconnected One of your users connected or disconnected an integration endUserId, integration
end_user.erased You erased an end user endUserId, in its erased form (erased~...)
secret.needs_reauth A connected account stopped working. Calls that use it are refused until it is reconnected secretName, integrationId, reason
environment.halted, environment.resumed The kill switch was thrown or released

Every data also carries environmentId. An approval or action event for a call made for one of your users also carries endUserId, and an approval event then carries decider (team or end_user).

Each delivery is one JSON envelope:

{
  "id": "evt_01JABCDEF",
  "topic": "anlyon",
  "type": "approval.requested",
  "timestamp": "2026-10-01T15:00:00.000Z",
  "data": {
    "environmentId": "6f1c2a9e-0b7d-4c3e-9a51-2d8e4f6b7c10",
    "approvalId": "apr_01JABCDEF",
    "kind": "action",
    "title": "Approve refund-order",
    "expiresAt": "2026-10-02T15:00:00.000Z",
    "endUserId": "user_123",
    "decider": "end_user"
  }
}

Events are best effort. Treat one as a prompt to read the approval, invocation or effect, and treat that record as the truth.

Verify the signature

A signed delivery carries an Anlyon-Signature header:

Anlyon-Signature: t=1234567890,v1=abc123def456...
  • t is the Unix time the signature was made.
  • v1 is an HMAC-SHA256 of the timestamp and the raw body.

A delivery is signed with the subscription’s secret when it has one, and with the workspace delivery secret otherwise. With neither, the delivery is unsigned. The header also carries a signed environment field, and the receivers can require the environment you expect. See Webhook signature verification for the format.

Verify against the raw body. A body that was parsed and serialized again does not match. The receivers refuse a timestamp more than 300 seconds from now by default (clockTolerance).

Notification webhooks use a different header and format. See Notifications.

Next.js

The SDK’s Next.js helpers verify the signature before your handler runs and answer 401 otherwise. Both read the secret from ANLYON_SIGNING_SECRET, or take signingSecret as an option.

// app/api/anlyon/route.ts
import { serve } from '@anlyonhq/sdk/nextjs';

export const { POST } = serve(async (request) => {
  const event = await request.json();

  switch (event.type) {
    case 'approval.requested':
      await notifyReviewers(event.data.approvalId);
      break;
    case 'action.unknown':
      await openReconciliationTicket(event.data.effectId ?? event.data.invocationId);
      break;
    case 'end_user.connected':
      await markConnected(event.data.endUserId, event.data.integration);
      break;
  }

  return { success: true };
});

verifySignature wraps a handler that returns its own Response:

// app/api/webhook/route.ts
import { verifySignature } from '@anlyonhq/sdk/nextjs';

export const POST = verifySignature(async (request) => {
  const event = await request.json();
  await handleEvent(event);
  return Response.json({ ok: true });
});

Any other framework

Outside Next.js, use the Receiver class:

import express from 'express';
import { Receiver } from '@anlyonhq/sdk';

const app = express();
const receiver = new Receiver({
  signingSecret: process.env.ANLYON_SIGNING_SECRET!,
});

app.post('/webhooks/anlyon', express.raw({ type: 'application/json' }), async (req, res) => {
  const signature = req.headers['anlyon-signature'] as string;
  const body = req.body.toString();

  // verify() returns a boolean. verifyOrThrow() throws instead.
  if (!receiver.verify({ signature, body })) {
    return res.status(401).send('Invalid signature');
  }

  const event = JSON.parse(body);
  if (event.type === 'action.unknown') {
    await openReconciliationTicket(event.data.effectId ?? event.data.invocationId);
  }

  res.status(200).send('OK');
});
import os
from flask import Flask, request
from anlyon import Receiver

app = Flask(__name__)
receiver = Receiver(os.environ["ANLYON_SIGNING_SECRET"])

@app.route("/webhooks/anlyon", methods=["POST"])
def handle_webhook():
    raw_body = request.get_data(as_text=True)

    if not receiver.verify(signature=request.headers.get("Anlyon-Signature"), body=raw_body):
        return "Invalid signature", 401

    event = request.get_json()
    if event["type"] == "action.unknown":
        open_reconciliation_ticket(event["data"].get("effectId") or event["data"]["invocationId"])
    return "OK", 200

Act on the common events

  • approval.requested with decider: "end_user": show the approval in your app to the user named in endUserId. List it with endUsers.approvals.list(endUserId, { status: 'pending' }). See Act for your users.
  • approval.requested for your team: post it where your reviewers are, or rely on the console inbox and Slack approvals.
  • action.unknown: do not retry. Read the effect, and let reconciliation settle it or resolve it by hand. See Agent payment retries.
  • action.invocation.blocked: read reason. environment_halted means the kill switch is on. impact_limit_exceeded means a limit had no room.
  • secret.needs_reauth: reconnect the account (anlyon connections reconnect <SECRET>, or the console).

Handle failures

Problem Cause Fix
Every delivery fails verification The body was parsed before verifying, or the wrong secret is set Verify the raw body. Use the secret returned on create, or rotate it with POST /api/v2/events/subscriptions/{id}/rotate-secret.
Verification fails on some deliveries only The server clock is off by more than 300 seconds Sync the clock, or raise clockTolerance.
No events arrive The subscription was made with a key for another environment, or the patterns match nothing Create it with a key for the workspace’s default environment. Check eventTypes.
403 on create The key lacks events:write Add the scope.
The same event twice A delivery can be repeated Deduplicate on the envelope id.

Good practice

  • Verify the signature before you read the body.
  • Make the handler safe to call more than once. Use the envelope id to deduplicate.
  • Answer 200 quickly and do slow work afterwards.
  • Do not act on the event body alone. Read the approval, invocation or effect it names.

Test locally

Using ngrok
# Start your local server, then expose it
ngrok http 3000

# Use the ngrok URL as the subscription URL
# https://abc123.ngrok.io/webhooks/anlyon
Using webhook.site
  1. Visit webhook.site
  2. Copy your unique URL
  3. Use it as the subscription URL while testing
  4. Read the incoming requests on the site

Next steps

Was this page helpful?