Verify Paperform webhooks

Paperform doesn't sign webhooks, so there's no signature to check and no SDK to verify one. You add a custom header with a secret value when you create the webhook, and your endpoint compares the whole value in constant time. That authenticates the sender, but it doesn't protect the body or stop a replay.

The facts

Signature header
None (unsigned)
What to build
Compare your whole custom header value in constant time
Key
shared secret

Paperform webhook secret

Paperform doesn't issue a secret. You choose a header name and value with the Custom headers toggle when you create the webhook, and Paperform sends them on each request. Keep it in an environment variable, not in source code.

  • Turn on Custom headers when you create the webhook, then use + Add Header to set the name and value.
  • Headers belong to one webhook, so each webhook can have its own value.
  • Custom headers don't support answer piping, so a {{ key }} placeholder in a header isn't filled in.
  • The API's webhook schema lists no header field, so add the header in the form editor.
  • No rotation process is documented.

Source: Paperform docs ↗

Code

express/src/index.js
javascript
// Generated with: paperform-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');

const app = express();

/**
 * Constant-time string comparison. Hashing both sides first gives equal-length
 * buffers, so timingSafeEqual never throws and the secret's length isn't leaked.
 */
function safeEqual(a, b) {
  const ha = crypto.createHash('sha256').update(String(a)).digest();
  const hb = crypto.createHash('sha256').update(String(b)).digest();
  return crypto.timingSafeEqual(ha, hb);
}

/**
 * Paperform does not sign payloads. Authenticate with a secret custom header added to the
 * webhook (Custom headers toggle). The header name is user-chosen, and the whole header value
 * is compared (no Bearer parsing). A static credential authenticates the sender, not the body,
 * and gives no replay protection: use HTTPS and rotate it if it leaks.
 */
function verifyPaperformRequest(
  headers,
  {
    headerName = process.env.PAPERFORM_WEBHOOK_HEADER || 'Authorization',
    secret = process.env.PAPERFORM_WEBHOOK_SECRET,
  } = {}
) {
  if (!secret) return false; // never accept when unconfigured
  const received = headers[headerName.toLowerCase()]; // Node lowercases header names
  return Boolean(received) && safeEqual(received, secret);
}

// Paperform has no event types: the trigger (New Submission or Partial Submission) is a
// per-webhook setting. This example reads an optional ?trigger=new|partial query parameter
// that you add to the webhook URL yourself.
function handleSubmission(payload, trigger) {
  const { submission_id: id, data } = payload;
  const answers = Object.fromEntries(
    data.map((q) => [q.custom_key || q.key, q.value])
  );

  if (trigger === 'partial') {
    console.log(`Partial submission ${id}`, answers);
    // Your code: follow up on the abandoned form
  } else {
    console.log(`New submission ${id}`, answers);
    // Your code: create a record, notify a team (payload.charge is set for payments)
  }
}

// Read the body raw (any content type) so the request is authenticated before parsing.
app.post('/webhooks/paperform', express.raw({ type: '*/*' }), (req, res) => {
  if (!verifyPaperformRequest(req.headers)) {
    return res.status(401).json({ error: 'Invalid or missing webhook secret header' });
  }

  let payload;
  try {
    const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
    payload = JSON.parse(raw);
  } catch {
    return res.status(400).json({ error: 'Invalid JSON body' });
  }

  if (!payload || typeof payload !== 'object' || !Array.isArray(payload.data)) {
    return res.status(400).json({ error: 'Expected a JSON object with a data array' });
  }

  try {
    handleSubmission(payload, req.query.trigger === 'partial' ? 'partial' : 'new');
  } catch (err) {
    console.error('Error handling Paperform submission:', err);
    return res.status(500).json({ error: 'Handler error' });
  }

  res.status(200).json({ received: true });
});

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = app;
module.exports.verifyPaperformRequest = verifyPaperformRequest;

if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/paperform`);
  });
}
nextjs/app/webhooks/paperform/route.ts
typescript
// Generated with: paperform-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyPaperformRequest } from '../../../lib/verify-paperform';

interface PaperformQuestion {
  title: string;
  description: string | null;
  type: string;
  key: string;
  custom_key: string | null;
  value: unknown;
}

interface PaperformPayload {
  data: PaperformQuestion[];
  submission_id?: string;
  created_at?: string;
  ip_address?: string;
  charge?: unknown;
  [key: string]: unknown;
}

// Paperform has no event types: the trigger (New Submission or Partial Submission) is a
// per-webhook setting. This example reads an optional ?trigger=new|partial query parameter
// that you add to the webhook URL yourself.
function handleSubmission(payload: PaperformPayload, trigger: 'new' | 'partial'): void {
  const answers = Object.fromEntries(
    payload.data.map((q) => [q.custom_key || q.key, q.value])
  );

  if (trigger === 'partial') {
    console.log(`Partial submission ${payload.submission_id}`, answers);
    // Your code: follow up on the abandoned form
  } else {
    console.log(`New submission ${payload.submission_id}`, answers);
    // Your code: create a record, notify a team (payload.charge is set for payments)
  }
}

export async function POST(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifyPaperformRequest(request.headers)) {
    return NextResponse.json({ error: 'Invalid or missing webhook secret header' }, { status: 401 });
  }

  let payload: unknown;
  try {
    // Read as text so any content type is accepted.
    payload = JSON.parse(await request.text());
  } catch {
    return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
  }

  if (!payload || typeof payload !== 'object' || !Array.isArray((payload as PaperformPayload).data)) {
    return NextResponse.json({ error: 'Expected a JSON object with a data array' }, { status: 400 });
  }

  try {
    const trigger = request.nextUrl.searchParams.get('trigger') === 'partial' ? 'partial' : 'new';
    handleSubmission(payload as PaperformPayload, trigger);
  } catch (err) {
    console.error('Error handling Paperform submission:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: paperform-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import json
import os
from typing import Optional

from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()


def verify_paperform_request(
    headers, header_name: Optional[str] = None, secret: Optional[str] = None
) -> bool:
    """Paperform does not sign payloads. Authenticate with a secret custom header added to the
    webhook (Custom headers toggle). The header name is user-chosen, and the whole header value
    is compared (no Bearer parsing). A static credential authenticates the sender, not the body,
    and gives no replay protection: use HTTPS and rotate it if it leaks.
    """
    header_name = header_name or os.environ.get("PAPERFORM_WEBHOOK_HEADER") or "Authorization"
    secret = secret if secret is not None else os.environ.get("PAPERFORM_WEBHOOK_SECRET")
    if not secret:
        return False  # never accept when unconfigured
    received = headers.get(header_name)  # Starlette headers are case-insensitive
    if not received:
        return False
    # compare_digest on bytes: encode both sides (str raises TypeError on non-ASCII)
    return hmac.compare_digest(received.encode("utf-8"), secret.encode("utf-8"))


async def require_paperform_secret(request: Request) -> None:
    """FastAPI dependency: reject the request before the body is parsed."""
    if not verify_paperform_request(request.headers):
        raise HTTPException(status_code=401, detail="Invalid or missing webhook secret header")


def handle_submission(payload: dict, trigger: str) -> None:
    """Paperform has no event types: the trigger (New Submission or Partial Submission) is a
    per-webhook setting. This example reads an optional ?trigger=new|partial query parameter
    that you add to the webhook URL yourself.
    """
    submission_id = payload.get("submission_id")
    answers = {q.get("custom_key") or q.get("key"): q.get("value") for q in payload["data"]}

    if trigger == "partial":
        print(f"Partial submission {submission_id}", answers)
        # Your code: follow up on the abandoned form
    else:
        print(f"New submission {submission_id}", answers)
        # Your code: create a record, notify a team (payload["charge"] is set for payments)


@app.post("/webhooks/paperform", dependencies=[Depends(require_paperform_secret)])
async def paperform_webhook(request: Request, trigger: str = "new"):
    # Read the raw body so any content type is accepted.
    raw_body = await request.body()

    try:
        payload = json.loads(raw_body)
    except (json.JSONDecodeError, UnicodeDecodeError):
        raise HTTPException(status_code=400, detail="Invalid JSON body")

    if not isinstance(payload, dict) or not isinstance(payload.get("data"), list):
        raise HTTPException(status_code=400, detail="Expected a JSON object with a data array")

    try:
        handle_submission(payload, "partial" if trigger == "partial" else "new")
    except Exception as err:  # noqa: BLE001
        print(f"Error handling Paperform submission: {err}")
        raise HTTPException(status_code=500, detail="Handler error")

    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

From hookdeck/webhook-skills ↗

Or install the Paperform webhooks skill:

npx skills add hookdeck/webhook-skills --skill paperform-webhooks

Common failures

Prefix left out of the comparison

Compare the whole header value. If you typed Bearer abc as the value, the value to compare is Bearer abc, not abc.

Header name mismatch

You choose the name when you add the header. Your endpoint has to read the same name, and header names are case-insensitive.

Custom headers left off

Without the Custom headers toggle and an added header, the request carries no secret for your endpoint to check.

Answer piping in the header

Custom headers don't support answer piping, so a value built from {{ key }} won't hold the answer. Use a fixed secret.

From Hookdeck's Paperform guide

Let Event Gateway check your Paperform header.

Event Gateway compares the header you name with the exact value you enter on each Paperform request, and a request that doesn't match never reaches your service. It queues the rest and retries failures on your schedule.

Not affiliated with Paperform. Facts are compiled from public sources and linked inline.