Receive a signed webhook #

View this page as Markdown

On this page

Prompt:

Stripe should tell the backend when a payment goes through. Set up the webhook.

Also works:

  • "Accept the payment provider's callbacks."
  • "Receive GitHub's push events on the backend."

Your AI tool stores the sender's signing secret (step 2), binds it to a setting (step 3), and writes the route that checks each delivery's signature (step 4). You then register the route's address in the sender's dashboard (step 6).

For a sender you control, follow A sender you control for the shared secret, header and signature format.

The sender needs no Turn Zero token or application sign-in. Your route verifies the sender's signature. To keep deliveries, save each accepted event in your application's database before acknowledging it, as Keep accepted deliveries describes.

What your AI tool does #

  • Reads the store-key skill (read_context, id skill:store-key) and follows it to store each environment's secret.
  • Binds the stored name to a setting in the manifest's settings, and submits the manifest again with submit_manifest.
  • Writes the route that checks each delivery's signature against that setting, as step 4's sample does.
  • Where only signed-in people may reach the app (an invited or workforce audience), lists the route's path in the audience's session_free_paths.
  • Deploys, promotes where the application has a development environment and you have agreed or already requested promotion, and confirms your test delivery with read_logs.
  • Asks you for each environment's signing secret as a file, never the value, or, where the sender asks you to choose it, writes a random one into a file unprinted. It gives you the route's address to register with the sender.

What you need #

  • The signing secret the sender issued for each environment, from the sender's dashboard, or one you choose where the sender asks you to (step 2). Stripe issues one for test mode and another for live mode.
  • An application that deploys (Deploy from your computer). For a new one, start from the hello-world template, which the scaffold line writes when it names no --template. Then add step 4's route to it. The database-service template's --resource writes routes that create and list records, which a webhook receiver does not use. Where you must keep the deliveries, start from database-service and replace its routes with step 4's (--template).

Without a shell, adapt the hello-world example files, or the database-service example files if you need a database. Then add step 4's webhook route.

Either way, the folder your AI tool deploys holds package.json at its top.

Before your AI starts #

For the AI tool: Check the following before starting.

  • Your AI tool connected and signed in (Connect your AI assistant).
  • list_applications returns the application's identifier, and read_status names its environments.
  • Each secret's file sits outside the application's folder, because a deploy's zip holds every file in that folder.

Steps #

The example is a Stripe webhook at the path /webhooks/stripe. Store a secret works through the same secret.

1. Choose the environments #

Each environment receives its own deliveries and checks them with its own secret. Production takes the sender's live secret. A development environment, once turned on, takes the test one (Test in development, then promote).

2. Store the shared secret #

The sender signs each delivery with the secret, and your route checks the signature with the same secret. So you store the value the sender issued.

Some senders ask you to choose the secret instead, as GitHub's webhooks do. Then your AI tool writes a random value for each environment into its own file, outside the application's folder and in a folder that exists, without printing it:

node -e "require('node:fs').writeFileSync(process.argv[1],require('node:crypto').randomBytes(32).toString('hex'),{mode:0o600,flag:'wx'})" "../secrets/webhook-secret-production.txt"
node -e "require('node:fs').writeFileSync(process.argv[1],require('node:crypto').randomBytes(32).toString('hex'),{mode:0o600,flag:'wx'})" "../secrets/webhook-secret-development.txt"

Your AI tool stores each environment's value from its file as below. You then copy each file's value into that environment's webhook at the sender, so both sides hold the same secret. Delete the files once the sender holds them.

Your AI tool calls store_secret with the name stripe-webhook-secret, the application, the environment, and the secret's file as value_file. It then runs the command line the call returns. It does this once for each environment. Supply the value without exposing it says who runs the line.

Never store this secret with generate. A created value is never returned, so no sender can hold it, and no delivery could carry a valid signature.

When the signing secret arrives later #

If the signing secret is not available yet, deploy the receiver with step 3's secret binding left out of the manifest. This guide's receiver then refuses every delivery with 400 and saves nothing.

When the value arrives, call store_secret afresh for each environment, using its private file, and run the returned command. That command expires fifteen minutes after the call, so request it when the value is ready. Keep the signing secret out of the application's database.

Then add the binding and submit the whole manifest. With one environment, deploy production; with two, deploy development, check it and promote with the owner's agreement. Restarting a copy without the binding does not add it.

3. Bind it to a setting #

A binding tells the platform to give your code the stored value as a setting, here STRIPE_WEBHOOK_SECRET. Your AI tool adds the binding to the manifest's settings and submits the whole manifest again with submit_manifest.

"settings": {
  "STRIPE_WEBHOOK_SECRET": { "secret": "stripe-webhook-secret" }
}

The response's settings rows show whether the name is stored for each environment. Bind a stored value to a setting gives the rules for settings.

4. Check the signature in the route #

The route reads the body as raw text, checks the Stripe-Signature header against the setting, and only then parses the JSON. Other senders name their own header and signing scheme in their documentation, and the check works the same way. A delivery without a valid signature is refused with 400 and changes nothing. A test runs this sample against a signed delivery, a changed body, an old timestamp, and a missing header.

import { createHmac, timingSafeEqual } from 'node:crypto';

// True where the header signs this raw body with the secret, within five minutes.
export function signatureIsValid(rawBody, header, secret, nowSeconds = Math.floor(Date.now() / 1000)) {
  if (typeof header !== 'string' || !secret) return false;
  const fields = header.split(',').map((field) => field.split('='));
  const timestamp = Number(fields.find(([key]) => key === 't')?.[1]);
  if (!Number.isInteger(timestamp) || Math.abs(nowSeconds - timestamp) > 300) return false;
  const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();
  return fields.some(([key, value]) => key === 'v1' && /^[0-9a-f]{64}$/.test(value ?? '') && timingSafeEqual(Buffer.from(value, 'hex'), expected));
}

// The route at POST /webhooks/stripe.
export async function handleStripeWebhook(req, res) {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  const rawBody = Buffer.concat(chunks).toString('utf8');
  if (!signatureIsValid(rawBody, req.headers['stripe-signature'], process.env.STRIPE_WEBHOOK_SECRET)) {
    console.log('webhook refused: no valid signature');
    res.writeHead(400).end();
    return;
  }
  const event = JSON.parse(rawBody);
  console.log(`webhook ${event.type} ${event.id}`);
  res.writeHead(200).end();
}

The check needs the body exactly as it arrived, so a framework must not parse it first. In Express, mount the route with express.raw({ type: 'application/json' }) and pass req.body.toString('utf8') to signatureIsValid.

A sender you control #

For a sender you control, use the scheme this sample checks and choose the shared secret as step 2 describes. Keep Stripe-Signature as the header name to use the sample and step 7's script unchanged. You may choose another header name if you change both the receiver's lookup and the sender to match.

The sender puts t=<t>,v1=<signature> in that header: t a timestamp in seconds, and v1 the lowercase hex HMAC-SHA256 of <t>.<raw body> under the shared secret. The route recomputes the HMAC, compares it with timingSafeEqual, and refuses a timestamp more than five minutes from its clock.

Find an unknown scheme in the sender's documentation, settings or support; refuse deliveries until you can verify them, without guessing. For an unsigned sender that lets you configure a secret header, compare it with the stored secret using timingSafeEqual. This shows someone holds the secret; it does not verify the body. Otherwise, treat deliveries only as notices: fetch the event from the sender's own API with your credential for that API before acting. If that is unavailable, refuse the delivery.

A sender may deliver the same event more than once. The sample logs deliveries only; it does not save events or prevent duplicate processing. Each delivery writes one console line, which step 7 reads.

Keep accepted deliveries #

For the AI tool: For a new application, follow Build a webhook receiver with a database. It covers saving signed deliveries once, checking development, and promoting the checked service.

For an existing application, add a delivery table through the migration steps in Add a database, then follow the storage and check instructions below. Adapt the walkthrough's delivery table as your next migration and its saveDelivery insert to your application. Keep the database credential in the backend; the sender needs neither that credential nor a Turn Zero token.

After checking the signature, insert the event's identifier, type, and payload before returning a successful response. Give the sender name and event identifier a unique constraint so a repeated delivery is recorded once. A duplicate already saved can receive a successful response without processing it again. If the write fails, return 500 so the sender can retry under its delivery policy.

Check a valid delivery, a repeated delivery, and an invalid signature locally and on development. Use query_database with environment: "development" to confirm the valid event was saved once and the invalid one was not saved; leaving out environment reads production. Keep signature verification before parsing or saving the body, as the sample shows.

To keep each delivery as a file instead, write it to a storage area from the same route, after the signature check and before the successful response. Call storage without end-user sign-in shows the calls. They use the backend's platform credential, so the sender still needs no Turn Zero token. Include the sender's name and event identifier in each filename. A repeated delivery then writes the same file again.

5. Open the path under a private audience #

Under a public audience, every request already reaches the route. Under invited or workforce, the platform refuses a request from anyone not signed in to your app, and a sender is never signed in. So your AI tool lists the route's path in the audience's session_free_paths, for example {"kind": "invited", "session_free_paths": ["/webhooks/stripe"]}.

The platform lets every request to a listed path through without checking who sent it. That is why the route makes step 4's check itself. Choose who may sign up gives the list's rules.

For a private page or action for the owner, follow A page for the owner alone.

6. Deploy, promote, and register the address #

Your AI tool deploys as Deploy from your computer describes. A deploy reads the value stored for its environment and gives it to your code as STRIPE_WEBHOOK_SECRET. A promote reads the production value the same way.

Your AI tool then gives you the route's address on each environment's hostname, such as https://<hostname>/webhooks/stripe. You register it in the sender's dashboard, the live address with the live secret and the test address with the test one.

7. Confirm a delivery #

You send a test event from the sender's dashboard. Your AI tool then calls read_logs for that environment with the source container, which returns the route's console lines. A line that starts with webhook and names the event's type means the delivery passed the check.

A webhook refused line means signature verification failed. Check the secret for that environment, the header, the unchanged request body, and the timestamp. Read logs and counters explains how to find the output.

Before a sender is set up, prove the check in a local run. Give the setting a test value of your own in .env, as Run your app on your computer describes.

Send the local route one delivery signed with that value, one with a changed body, and one with no signature. Sign and send them from one Node script, such as with fetch: a shell's quoting can change the body's bytes after signing, and the check then refuses a correct signature.

Save this as scripts/verify-webhook.mjs. A test runs it against the receiver above, including the checks that reject a changed body and a missing signature.

// scripts/verify-webhook.mjs
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';

const secret = process.env.STRIPE_WEBHOOK_SECRET;
if (!secret) throw new Error('Set STRIPE_WEBHOOK_SECRET to the local receiver\'s test secret.');
const address = process.argv[2] ?? 'http://127.0.0.1:3000/webhooks/stripe';
const body = JSON.stringify({ id: 'evt_local_check', type: 'payment_intent.succeeded' });
const timestamp = Math.floor(Date.now() / 1000);
const signature = createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');
const header = `t=${timestamp},v1=${signature}`;

async function send(text, signed) {
  const response = await fetch(address, {
    method: 'POST',
    headers: { 'content-type': 'application/json', ...(signed ? { 'Stripe-Signature': signed } : {}) },
    body: text,
  });
  await response.text();
  return response.status;
}

assert.equal(await send(body, header), 200, 'signed delivery');
assert.equal(await send(`${body} `, header), 400, 'changed body');
assert.equal(await send(body), 400, 'missing signature');
console.log('Webhook check passed: signed 200; changed body and missing signature 400.');

Unset STRIPE_WEBHOOK_SECRET in your shell, then start the local receiver with the same test secret, as the run guide explains. Then run node --env-file=.env scripts/verify-webhook.mjs from the application folder. Pass the local route's URL as the next argument if its port or path differs. The script prints success only when all three status checks pass. It logs no secret and needs no Turn Zero token or end-user sign-in.

Where your own system is the sender, it signs with the value in the file you stored from, on the machine that holds the file. The platform signs no test delivery with a stored secret, since any token could forge one. Sign with your own value as above and verify with step 4's sample. No library package signs or verifies webhook deliveries.

To check a deployed Stripe receiver, use the same script with that environment's route address and your own copy of its signing secret. Use a file you kept, or obtain the value from the sender's dashboard where it remains available. If you have no copy, use the sender's own test event instead; the platform never returns the stored value. For another sender, adapt the script to its documented header and signing scheme, and send the same event identifier twice to check a repeat.

Put that environment's secret in a private environment file as STRIPE_WEBHOOK_SECRET, outside the application folder and version control. From the application folder, replace these paths with your bare secret file and a new environment file in an existing private folder:

node -e "const fs=require('node:fs');fs.writeFileSync(process.argv[2],'STRIPE_WEBHOOK_SECRET='+fs.readFileSync(process.argv[1],'utf8').trim()+'\n',{mode:0o600,flag:'wx'})" "../secrets/stripe-test-secret.txt" "../secrets/stripe-check.env"

Unset STRIPE_WEBHOOK_SECRET in your shell so it cannot override the file. From the application folder, run:

node --env-file="<private environment file>" scripts/verify-webhook.mjs "https://<hostname>/webhooks/stripe"

Replace both placeholders with the file's path and that environment's hostname. Read the hostname from application.hostname in read_status's answer, explicitly naming the environment. Use the matching secret, not the local test value, and delete the private environment file after the check. Keep your computer's clock accurate: the receiver refuses a timestamp more than five minutes from its clock.

The signed delivery logs webhook payment_intent.succeeded evt_local_check; a database receiver saves that event once. Read the environment's container logs and, where used, its database. On an app with real users, run a production test only where the owner judges that write safe, as Check production explains.

Expected result #

A delivery the sender signed reaches the route, passes the check, and answers 200, and its console line names the event. A delivery with a missing or wrong signature answers 400 and changes nothing. Each environment checks its own deliveries with its own secret.

Refusals #

See the refusals reference for other platform errors.

Refusal Status Cause Remedy
setting_secret_missing 409 A deploy or promote found a bound name that is not stored for its environment. detail names the setting and the name, and next gives the store_secret call to make. Store the value there with store_secret for the application and the environment, as Store a secret describes, then deploy or promote again.
manifest_invalid 400 The manifest does not match its schema. violations lists the paths that fail. A session_free_paths entry that breaks a rule is named at its own place in the list. Correct each path and resubmit the whole manifest.
authentication_required 401 Under an invited or workforce audience, a delivery reached a path not listed in the audience's session_free_paths. List the route's path in the audience's session_free_paths, submit the manifest again, and deploy.