Save a signed webhook in a database with a function #

View this page as Markdown

On this page

Start with a serverless test app. Declare a database and bind the development signing secret, then write the function that accepts signed Stripe test events and saves each event once in PostgreSQL. The function checks the signature before it reads the event or writes a row. Test it on your computer and in the app's development environment.

What your AI does #

  • Prepares the function and its database migration in a serverless test app.
  • Binds the development signing secret from a private file.
  • Checks a valid delivery, a duplicate and a changed body. It reads the test rows through the signed-in database tool.

What you need #

  • A signed-in AI coding agent and a terminal with Turn Zero Command.
  • The owner's choice to use a serverless test app with a development environment and a shared database.
  • A test signing secret in a private file outside the app folder. For this exercise, choose your own test secret. To receive events directly from Stripe, use the signing secret for that test endpoint. Stripe's signature guide.

Steps #

1. Declare a database and bind the secret #

Use a serverless test app. To create one, call create_application with its name and kind: "serverless". Keep its application ID.

If the app has production alone, ask the owner before turning on development. While you wait, limit the work to reading its settings and preparing local files the owner has approved. If the owner declines, stop and report that the test is on hold. After approval, call create_environment with the application ID. Check that read_status lists development.

Call store_secret with the application ID, environment: "development", name: "stripe-webhook-secret" and the private file's path as value_file. Run the returned command from the app folder. Store a webhook signing secret.

Save this as manifest.json in the app folder. Its public audience lets Stripe reach the endpoint, and the function checks each delivery's signature. For this test app, the webhook is the only route.

{
  "manifest_version": 1,
  "services": [{ "kind": "database" }],
  "region": "usa",
  "egress": [],
  "audience": { "kind": "public" },
  "packages": [],
  "settings": {
    "STRIPE_WEBHOOK_SECRET": { "secret": "stripe-webhook-secret" }
  }
}

If you use an existing test app, add the database and secret binding to its full manifest. Keep its other settings, including its audience. If it already declares a database, keep that declaration.

Submit the full manifest with submit_manifest and the application ID. Follow any setup calls it returns.

2. Add the migration and dependency #

Save this as migrations/0001_webhook_events.sql. The primary key gives each event ID one row. Turn Zero applies the migration before the deployed version serves.

CREATE TABLE stripe_webhook_events (
  event_id text PRIMARY KEY,
  payload jsonb NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now()
);

Save this as package.json. Run npm install in the app folder and keep the generated lockfile.

{
  "name": "stripe-webhook-db",
  "private": true,
  "type": "module",
  "dependencies": { "pg": "8.22.0" }
}

3. Write the function #

Save this as functions/webhooks/stripe.js. The function verifies the signature against the original request bytes before decoding the body or saving the event. It accepts a timestamp within five minutes of its clock and reads at most 256 KiB per request.

import pg from 'pg';

const encoder = new TextEncoder();
const maxBytes = 256 * 1024;
let pool;

function failure(status, error, headers) {
  return Response.json({ error }, { status, headers });
}

async function readBody(request) {
  if (!request.body) return new Uint8Array();
  const reader = request.body.getReader();
  const chunks = [];
  let size = 0;
  try {
    for (;;) {
      const { done, value } = await reader.read();
      if (done) break;
      size += value.byteLength;
      if (size > maxBytes) {
        await reader.cancel();
        return null;
      }
      chunks.push(value);
    }
  } finally {
    reader.releaseLock();
  }

  const body = new Uint8Array(size);
  let offset = 0;
  for (const chunk of chunks) {
    body.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return body;
}

async function verifies(header, body, secret) {
  const fields = header.split(',').map(field => field.trim());
  const timestamps = fields.filter(field => field.startsWith('t='));
  if (timestamps.length !== 1) return false;
  const timestamp = timestamps[0].slice(2);
  const now = Math.floor(Date.now() / 1000);
  if (!/^\d{1,12}$/.test(timestamp) || Math.abs(now - Number(timestamp)) > 300) {
    return false;
  }

  const prefix = encoder.encode(timestamp + '.');
  const signed = new Uint8Array(prefix.length + body.length);
  signed.set(prefix);
  signed.set(body, prefix.length);
  const key = await crypto.subtle.importKey(
    'raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']
  );

  for (const field of fields) {
    if (!/^v1=[0-9a-f]{64}$/.test(field)) continue;
    const digest = Uint8Array.from(
      field.slice(3).match(/../g), pair => Number.parseInt(pair, 16)
    );
    if (await crypto.subtle.verify('HMAC', key, digest, signed)) return true;
  }
  return false;
}

function database(url) {
  if (!pool) {
    pool = new pg.Pool({
      connectionString: url,
      max: 1,
      connectionTimeoutMillis: 5000
    });
    pool.on('error', () => console.error('Webhook database connection failed'));
  }
  return pool;
}

export default {
  async fetch(request) {
    if (new URL(request.url).pathname !== '/webhooks/stripe') {
      return failure(404, 'not_found');
    }
    if (request.method !== 'POST') {
      return failure(405, 'method_not_allowed', { allow: 'POST' });
    }

    const secret = process.env.STRIPE_WEBHOOK_SECRET;
    const databaseUrl = process.env.APP_DATABASE_URL;
    if (!secret || !databaseUrl) return failure(503, 'receiver_not_configured');

    const signature = request.headers.get('stripe-signature');
    if (!signature) return failure(400, 'invalid_signature');
    let body;
    try {
      body = await readBody(request);
    } catch {
      return failure(400, 'unreadable_body');
    }
    if (!body) return failure(413, 'payload_too_large');
    if (!await verifies(signature, body, secret)) {
      return failure(400, 'invalid_signature');
    }

    let event;
    let payload;
    try {
      payload = new TextDecoder('utf-8', { fatal: true }).decode(body);
      event = JSON.parse(payload);
    } catch {
      return failure(400, 'invalid_event');
    }
    if (typeof event?.id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(event.id)) {
      return failure(400, 'invalid_event');
    }

    try {
      const result = await database(databaseUrl).query(
        `INSERT INTO stripe_webhook_events (event_id, payload)
         VALUES ($1, $2::jsonb)
         ON CONFLICT (event_id) DO NOTHING`,
        [event.id, payload]
      );
      return Response.json({ accepted: true, duplicate: result.rowCount === 0 });
    } catch {
      console.error('Webhook database write failed');
      return failure(503, 'database_unavailable');
    }
  }
};

The function waits for the insert before it sends HTTP 200. A repeat finds the existing row, keeps its contents and returns duplicate: true. The handler uses the database connection in APP_DATABASE_URL and keeps one connection per worker.

4. Test on your computer #

Run the provision command below with your app's ID in place of APPLICATION_ID. Follow any calls the command prints. This writes the development database setting to .env.

turnzero provision --application APPLICATION_ID

Copy the test signing secret from the private file into STRIPE_WEBHOOK_SECRET in .env without printing it. Keep .env private and out of version control. turnzero deploy excludes .env and node_modules.

Run turnzero run --port 3000 from the app folder. The command installs no dependencies for you. It applies the migration before it serves the function.

Save this test as test/send-webhooks.mjs. The test signs a new event, repeats its exact body, then changes its ID while keeping the original signature.

import assert from 'node:assert/strict';
import { createHmac, randomUUID } from 'node:crypto';

const target = new URL(process.argv[2]);
const secret = process.env.STRIPE_WEBHOOK_SECRET;
assert.ok(secret, 'Set STRIPE_WEBHOOK_SECRET in your private test environment');

const id = 'evt_test_' + randomUUID();
const changedId = id + '_changed';
const body = JSON.stringify({ id, type: 'test.webhook', livemode: false });
const timestamp = Math.floor(Date.now() / 1000);
const digest = createHmac('sha256', secret)
  .update(timestamp + '.')
  .update(body)
  .digest('hex');
const signature = 't=' + timestamp + ',v1=' + digest;

async function send(payload, status, expected) {
  const response = await fetch(target, {
    method: 'POST',
    redirect: 'error',
    headers: { 'content-type': 'application/json', 'stripe-signature': signature },
    body: payload
  });
  assert.equal(response.status, status);
  assert.deepEqual(await response.json(), expected);
}

await send(body, 200, { accepted: true, duplicate: false });
await send(body, 200, { accepted: true, duplicate: true });
await send(JSON.stringify({ id: changedId, type: 'test.webhook', livemode: false }), 400, {
  error: 'invalid_signature'
});
console.log('Saved event ID:', id);
console.log('Rejected event ID:', changedId);

While the local run is up, run the test from the app folder.

node --env-file=.env test/send-webhooks.mjs http://localhost:3000/webhooks/stripe

Check the two IDs with the database query in step 5. Use the development database for the query because this local run uses the provisioned development connection.

5. Deploy and check development #

Read read_status for the app and confirm it has a development environment. Run turnzero deploy from the app folder on a computer authorized for deploys. For the first deploy checks, see Deploy functions. Call read_status with the application ID, environment: "development" and wait_seconds until settled is true. Confirm the deploy succeeded. If a deploy answer is lost, read status before repeating it. In application.environments.development, check functions for /webhooks/stripe and copy hostname.

Replace your-development-host.example with that hostname, then run the test. The test generates fresh event IDs for each run.

node --env-file=.env test/send-webhooks.mjs https://your-development-host.example/webhooks/stripe

Call query_database under your signed-in connection with the application ID, environment: "development" and this query as sql. Replace the two example IDs with the IDs the test printed.

SELECT event_id, received_at
FROM stripe_webhook_events
WHERE event_id IN ('evt_test_saved_id', 'evt_test_rejected_id');

Expect one row for the saved ID and none for the rejected ID. The query reads the table without a public route for its contents.

Expected result #

The first delivery saves one row. The repeat succeeds without adding a row. The changed body returns HTTP 400 and leaves the table unchanged. Report the local and development results separately. If you had to retry the deploy, report the original refusal and what you changed. Include the fresh test’s HTTP status and what the database query found.

Refusals #

What you see Cause Remedy
HTTP 400 invalid_signature The signature is missing or invalid, or its timestamp is outside the allowed window. Check the test endpoint's secret and sign the exact bytes you send with a fresh timestamp.
HTTP 400 unreadable_body or invalid_event The handler could not read the body or did not find valid JSON with an event ID. Send a complete UTF-8 JSON body with an event ID. Sign the bytes you send.
HTTP 404 or 405 The request used the wrong path or HTTP method. Send POST to /webhooks/stripe on the development hostname.
HTTP 413 payload_too_large The event exceeds the example's 256 KiB limit. Use a smaller test event.
HTTP 503 receiver_not_configured The handler did not receive a signing secret or a database address. Check the secret binding and the development database setting. Deploy again to apply a changed binding.
HTTP 503 database_unavailable The handler could not save the event. Check the deploy outcome for migration errors. Check that the table exists and development can reach the database. Fix the problem and run a fresh test.
setting_secret_missing during deploy The manifest names a secret that development does not have. Store stripe-webhook-secret in development and check the manifest binding. Deploy again to development and run a fresh test.