Your own code behind a webhook

Your agent can run on your own server, in any language, or in an n8n or Make scenario. Flutch sends it every customer message as one signed HTTPS POST and sends your JSON reply back to the customer's chat: Instagram, Telegram, web chat or the API. Flutch keeps the conversation and the contact card. When your agent decides a person should take over, it says so in the reply and Flutch hands the conversation to your team.

This page is the full contract: what Flutch sends, how to check the signature, what to answer and what happens when something fails.

Set up

  1. In the console, open Agents, click Create Agent and choose Your own code.
  2. Enter the HTTPS URL of your endpoint and click Create agent.
  3. Flutch shows the agent's Signing secret once. Copy it and put it on your server as FLUTCH_SIGNING_SECRET. The console then shows a handler that checks the signature.
  4. Click Send a test message. Your endpoint gets a signed request, and the console shows its answer and how long it took.
  5. Click Open Playground and write to the agent as a customer would.

Later you can change the URL, make a new secret or send another test message in the agent's Settings → General settings, block Your endpoint.

The test message is a normal signed request with "platform": "test", a threadId that starts with test- and the text This is a test message from the Flutch console. It creates no conversation in Flutch, and your reply is only shown in the console.

The request

Flutch sends one POST per customer message, with a JSON body in UTF-8.

HeaderValue
Content-Typeapplication/json
User-AgentFlutch-Webhook/1.0
X-Flutch-Request-IdUnique id of this request, the same as requestId in the body
X-Flutch-TimestampWhen the request was signed, in Unix seconds
X-Flutch-Signaturev1= and the HMAC-SHA256 of the request, in hex. Sent when the agent has a signing secret
json
{
  "type": "message",
  "requestId": "78f71562-d69e-4dce-9c2f-bf556b389734",
  "agentId": "6b0aff3b965d9efd2a6cca28",
  "threadId": "6b0b0093965d9efd2a6ccc25",
  "platform": "telegram",
  "user": { "id": "6b0aff3c965d9efd2a6cca3c", "name": "Anna" },
  "message": {
    "id": "6b0b0093965d9efd2a6ccc31",
    "text": "Hi! Do you deliver on Saturdays?",
    "trigger": null
  }
}
FieldWhat it is
typeAlways message for now. Check it, so a new kind of event does not reach your message handler by surprise
requestIdUnique per request
agentIdThe Flutch agent the message was sent to
threadIdThe conversation. It stays the same for every message in it, so use it as the key for your own state and history
platformThe channel the customer writes from: telegram, instagram-dm, instagram-comments, web, widget, api. test for the console's test message
user.idThe customer's id in Flutch. user.name is their name, or null
message.idId of the customer's message
message.textWhat the customer wrote
message.triggernull for a message the customer typed. Set when the platform made the turn: callback for a button press, scheduled for a scheduled wake-up, system_event for an event such as a completed order

Flutch sends only the current message, not the history. Keep the history on your side by threadId. When the customer sends a photo or a file without a caption, message.text describes it in square brackets, for example [The user sent an image, with no caption.]. The files themselves are not forwarded yet.

Check the signature

The signature is an HMAC-SHA256 with your signing secret as the key, over the timestamp, a dot and the raw request body:

v1=hex(HMAC_SHA256(secret, X-Flutch-Timestamp + "." + raw_body))

Check it on the exact bytes you received, before parsing the JSON: a parser that reorders keys or changes whitespace would change the body. Compare in constant time. Refuse requests whose timestamp is more than 5 minutes from your clock, so a recorded request cannot be replayed later. If you want to be strict about duplicates as well, remember the X-Flutch-Request-Id values of the last 5 minutes.

TypeScript

ts
import { createHmac, timingSafeEqual } from "node:crypto";

/** How old a request may be, in seconds. Older ones are refused as replays. */
const TOLERANCE_SECONDS = 300;

/**
 * Checks the X-Flutch-Signature of a request from Flutch.
 * Pass the body exactly as it arrived, before any JSON parsing.
 */
export function verifyFlutchSignature(
  rawBody: Buffer | string,
  timestamp: string | undefined,
  signature: string | undefined,
  secret: string,
  now: number = Math.floor(Date.now() / 1000),
): boolean {
  if (!timestamp || !/^\d+$/.test(timestamp)) return false;
  if (!signature || !signature.startsWith("v1=")) return false;
  if (Math.abs(now - Number(timestamp)) > TOLERANCE_SECONDS) return false;

  const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest();
  const received = Buffer.from(signature.slice("v1=".length), "hex");
  return received.length === expected.length && timingSafeEqual(received, expected);
}

With Express, take the body as raw bytes on this route:

ts
import express from "express";

const app = express();

app.post("/flutch", express.raw({ type: "application/json" }), (req, res) => {
  const ok = verifyFlutchSignature(
    req.body,
    req.get("X-Flutch-Timestamp"),
    req.get("X-Flutch-Signature"),
    process.env.FLUTCH_SIGNING_SECRET!,
  );
  if (!ok) return res.status(401).end();

  const event = JSON.parse(req.body.toString("utf8"));
  if (event.type !== "message") return res.status(400).end();

  res.json({ text: `You wrote: ${event.message.text}` });
});

app.listen(8080);

Python

python
import hashlib
import hmac
import time

# How old a request may be, in seconds. Older ones are refused as replays.
TOLERANCE_SECONDS = 300

def verify_flutch_signature(
    raw_body: bytes,
    timestamp: str | None,
    signature: str | None,
    secret: str,
    now: int | None = None,
) -> bool:
    """Checks the X-Flutch-Signature of a request from Flutch.

    Pass the body exactly as it arrived, before any JSON parsing.
    """
    if not timestamp or not timestamp.isdigit():
        return False
    if not signature or not signature.startswith("v1="):
        return False
    now = int(time.time()) if now is None else now
    if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(
        secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, signature[len("v1=") :])

With FastAPI:

python
import json
import os

from fastapi import FastAPI, HTTPException, Request

app = FastAPI()

@app.post("/flutch")
async def flutch(request: Request):
    raw = await request.body()
    if not verify_flutch_signature(
        raw,
        request.headers.get("x-flutch-timestamp"),
        request.headers.get("x-flutch-signature"),
        os.environ["FLUTCH_SIGNING_SECRET"],
    ):
        raise HTTPException(status_code=401)

    event = json.loads(raw)
    if event["type"] != "message":
        raise HTTPException(status_code=400)
    return {"text": f"You wrote: {event['message']['text']}"}

Changing the secret

Flutch shows a secret only once. If you lost it, or want to rotate it, click Make a new secret in Settings → General settings → Your endpoint. The new secret signs the next message, and the old one stops working. To switch without failed requests, let your server accept both secrets for a moment, make the new one, then drop the old one.

The reply

Answer with HTTP 200 (any 2xx works) and a JSON object:

json
{
  "text": "Yes, we deliver on Saturdays from 10 to 16.",
  "attachments": [
    {
      "type": "button",
      "value": { "type": "url", "text": "Delivery terms", "value": "https://example.com/delivery" }
    }
  ]
}
FieldTypeWhat it does
textstringThe reply the customer gets
attachmentsarrayImages, files, videos and buttons sent with the reply. Up to 10
escalatebooleantrue hands the conversation to your team, see below
reasonstringWhy a person is needed. It goes into your team's notification. Up to 500 characters, used with escalate: true

A reply needs at least one of: non-empty text, an attachment, or escalate: true. A field set to null counts as absent, and Flutch ignores fields it does not know.

Attachments

KindShape
Image{ "type": "image", "value": [{ "url": "https://…", "caption": "optional", "alt": "optional" }] }
File{ "type": "file", "value": { "url": "https://…", "fileName": "optional.pdf", "mimeType": "optional" } }
Video{ "type": "video", "value": { "url": "https://…", "mimeType": "optional" } }
Link button{ "type": "button", "value": { "type": "url", "text": "Label", "value": "https://…" } }
Reply button{ "type": "button", "value": { "type": "reply", "text": "Label", "value": "text to send" } }

All URLs must be http or https. A reply button sends its value back as the customer's next message, so your endpoint receives it like anything the customer types. Each channel renders attachments in its own way.

Hand the conversation to a person

Add "escalate": true when your agent should stop and a person should take over:

json
{
  "text": "I'll pass this to a colleague, they will reply here shortly.",
  "escalate": true,
  "reason": "Asks for a refund on order 1042"
}

Flutch then does what it does for any hand-over:

  1. The customer gets your text. With { "escalate": true } alone they get nothing from the agent.
  2. The conversation is marked as waiting for a person, and the agent's owner, or the person set in Settings → Handoff → Escalation recipient, gets a notification in Telegram or by email with your reason.
  3. While your team handles the conversation, the customer's messages go to the team and not to your endpoint. The team replies from the Flutch Inbox.
  4. The conversation comes back to your agent when someone clicks Return to agent. If nobody from the team writes for 30 minutes, the customer's next message goes to your agent again. Change the minutes in Settings → Handoff → Return to agent after, min.

Without a reason the notification says external_agent. On Instagram a person has less time to answer than on other channels: see Instagram: the 24-hour window and handing a chat to a person.

Errors and limits

Flutch waits up to 60 seconds for the whole reply and does not retry. The message fails when your endpoint:

  • answers with a status other than 2xx, including redirects (Flutch does not follow them);
  • does not answer within 60 seconds;
  • returns a body larger than 1 MB, a body that is not JSON, or JSON that breaks the contract above, for example an unknown attachment type or text that is not a string.

When a message the customer wrote fails, Flutch hands the conversation to your team the same way as escalate: true, with the reason generation_error, so a person can answer the customer.

LimitValue
Time for the whole reply60 seconds
Reply body1 MB
Attachments per reply10
reason500 characters
Signature tolerance5 minutes

The endpoint must be on the public internet. Addresses in private, loopback and link-local ranges are refused, also when a public host name resolves to one. Use https: the requests carry what your customers write.

Price

Processing of a message for an agent on your own code costs $0.002: the 1-second processing minimum. The time Flutch waits for your server is not counted. Your workspace starts with $5 of credit. Processing and storage are not charged yet. We will post the start date here four weeks ahead. When the balance goes below zero, the agent stops before your endpoint is called: see Balance: when agents stop and how they come back.

A LangGraph.js graph on the Flutch SDK

A graph served by @flutchai/flutch-sdk answers on /generate with its own request body, so it needs one small controller in the same Nest app to speak this contract. The controller checks the signature with verifyFlutchSignature from above, passes threadId as the checkpointer's thread_id, so the SDK keeps the history, sends the customer's text as the graph's input and returns { text }.

Create the app with NestFactory.create(AppModule, { rawBody: true }), so the signature is checked on the raw bytes, and add the controller to the module's controllers. global.support is the baseGraphType the module registers with UniversalGraphModule.forRoot.

ts
import {
  BadRequestException,
  Body,
  Controller,
  Headers,
  HttpCode,
  Inject,
  Post,
  Req,
  UnauthorizedException,
  type RawBodyRequest,
} from "@nestjs/common";
import type { Request } from "express";
import type { IGraphService } from "@flutchai/flutch-sdk";
import { verifyFlutchSignature } from "./verify-signature";

interface FlutchMessage {
  type: string;
  requestId: string;
  agentId: string;
  threadId: string;
  platform: string;
  user: { id: string };
  message: { text: string };
}

// main.ts: NestFactory.create(AppModule, { rawBody: true }), so the signature is checked on the raw bytes
@Controller("flutch")
export class FlutchWebhookController {
  constructor(@Inject("GRAPH_SERVICE") private readonly graphs: IGraphService) {}

  @Post()
  @HttpCode(200)
  async handle(
    @Req() req: RawBodyRequest<Request>,
    @Body() event: FlutchMessage,
    @Headers("x-flutch-timestamp") timestamp?: string,
    @Headers("x-flutch-signature") signature?: string,
  ) {
    const secret = process.env.FLUTCH_SIGNING_SECRET ?? "";
    if (!verifyFlutchSignature(req.rawBody ?? "", timestamp, signature, secret)) {
      throw new UnauthorizedException();
    }
    if (event.type !== "message") throw new BadRequestException();

    const result = await this.graphs.generateAnswer({
      requestId: event.requestId,
      input: { messages: [{ role: "user", content: event.message.text }] },
      config: {
        configurable: {
          thread_id: event.threadId,
          context: {
            threadId: event.threadId,
            userId: event.user.id,
            agentId: event.agentId,
            platform: event.platform,
          },
          graphSettings: { graphType: "global.support" },
        },
      },
    });
    return { text: result.text };
  }
}

The URL of this controller, for example https://your-app.example.com/flutch, is the endpoint you enter for the agent in the console. To hand the conversation to a person, return escalate: true and a reason together with the text, as above.

n8n

An n8n workflow works as the endpoint with three nodes:

  1. Webhook: HTTP Method POST, Respond Using 'Respond to Webhook' Node. Use its production URL in Flutch.
  2. Your logic, for example an AI Agent node with the prompt {{ $json.body.message.text }} and {{ $json.body.threadId }} as the memory session key.
  3. Respond to Webhook: Respond With JSON, Response Body {{ { "text": $json.output } }}. Written as one expression, the reply stays valid JSON when it contains quotes or line breaks.

To check the signature in n8n, turn on Raw Body in the Webhook node options and compute the same HMAC in a Code node. Self-hosted n8n allows the crypto module in Code nodes with NODE_FUNCTION_ALLOW_BUILTIN=crypto.