DocuHook

Guides · stripe webhook to pdf invoice

Stripe Webhook to PDF Invoice

2026-11-17 · 8 min read

If you searched for Stripe webhook to PDF invoice, you probably want your own branded invoice — your layout, your fonts, extra fields your accountant asks for — generated the moment Stripe says an invoice is paid. And you want it without running Chrome inside the webhook handler.

This guide wires invoice.paid → your endpoint → DocuHook in async mode, so your endpoint acknowledges Stripe in milliseconds and the PDF is rendered off the request path.

First: do you even need this?

Stripe already hosts a PDF for every invoice — the invoice_pdf URL on the Invoice object. If Stripe’s standard layout and branding settings are enough, use that and stop here.

Build your own when you need things Stripe’s template does not do: a fully custom layout, legal text per country, a different language, your own invoice numbering on the document, or one template shared with your WooCommerce or Shopify store.

The problem with doing it inline

Stripe’s docs are explicit: your endpoint must quickly return a 2xx before any complex logic that could cause a timeout. If it does not, Stripe treats the delivery as failed and retries — in live mode for up to three days. Launching Puppeteer, waiting on a slow PDF render, or uploading to S3 inside that request is how you end up with duplicate invoices and a red Event deliveries tab.

So the handler should do only three things: verify the signature, hand the work off, return 200.

Architecture

  1. Stripe sends invoice.paid to POST /webhooks/stripe with a Stripe-Signature header.
  2. Your handler verifies it with the raw body and your whsec_… signing secret.
  3. It maps the invoice to template JSON and POSTs it to DocuHook with "mode": "async". DocuHook replies 202 with a job_id right away.
  4. Your handler stores the job and returns 200 to Stripe.
  5. A worker or cron GETs the job’s result_url as application/pdf and stores or emails the file.

1. Set up the endpoint in Stripe

In the Stripe Dashboard, open Workbench → Webhooks, create an event destination for your account, choose a snapshot payload, select invoice.paid, and enter your public HTTPS URL. Copy the signing secret (whsec_…).

Locally, the Stripe CLI forwards events and prints a test secret:

stripe listen --forward-to localhost:3000/webhooks/stripe
stripe trigger invoice.paid

2. The invoice template

One HTML file with {{path}} tokens and a <!--ROWS--> marker for line items:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
  body { font-family: "DejaVu Sans", sans-serif; margin: 40px; color: #14181c; font-size: 13px; }
  .brand { color: #635bff; font-size: 22px; font-weight: bold; }
  table { width: 100%; border-collapse: collapse; margin-top: 24px; }
  th, td { padding: 8px 0; border-bottom: 1px solid #e3e8ee; text-align: left; }
  .num { text-align: right; }
  .total td { font-weight: bold; border-bottom: none; }
</style>
</head>
<body>
  <div class="brand">Acme Inc.</div>
  <h1>Invoice {{invoice.number}}</h1>
  <p>Billed to {{customer.name}} · {{customer.email}}<br>Paid on {{invoice.paid_on}}</p>
  <table>
    <thead><tr><th>Description</th><th class="num">Qty</th><th class="num">Amount</th></tr></thead>
    <tbody>
      <!--ROWS-->
      <tr class="total"><td></td><td class="num">Total</td><td class="num">{{invoice.currency}} {{invoice.amount_paid}}</td></tr>
    </tbody>
  </table>
</body>
</html>

Stripe amounts are integers in the smallest currency unit (cents), so format them before sending. DocuHook substitutes values as text and HTML-escapes them; it does not do math or loops.

3. The webhook handler (Express)

npm install express stripe
import express from "express";
import Stripe from "stripe";
import fs from "node:fs";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const TEMPLATE = fs.readFileSync("./invoice.html", "utf8");
const app = express();

const money = (cents) => (cents / 100).toFixed(2); // adjust for zero-decimal currencies

function toTemplate(invoice) {
  const lines = invoice.lines.data;
  const rows = lines
    .map(
      (_, i) =>
        `<tr><td>{{lines.${i}.description}}</td><td class="num">{{lines.${i}.quantity}}</td><td class="num">{{invoice.currency}} {{lines.${i}.amount}}</td></tr>`
    )
    .join("\n");

  return {
    html: TEMPLATE.replace("<!--ROWS-->", rows),
    data: {
      invoice: {
        number: invoice.number,
        currency: invoice.currency.toUpperCase(),
        amount_paid: money(invoice.amount_paid),
        paid_on: new Date((invoice.status_transitions?.paid_at ?? invoice.created) * 1000).toISOString().slice(0, 10),
      },
      customer: { name: invoice.customer_name ?? "", email: invoice.customer_email ?? "" },
      lines: lines.map((l) => ({
        description: l.description ?? "",
        quantity: l.quantity ?? 1,
        amount: money(l.amount),
      })),
    },
  };
}

// Raw body is required for signature verification — no express.json() on this route
app.post("/webhooks/stripe", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      req.headers["stripe-signature"],
      process.env.STRIPE_WEBHOOK_SECRET
    );
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (event.type !== "invoice.paid") return res.sendStatus(200);
  if (await alreadyProcessed(event.id)) return res.sendStatus(200); // Stripe can deliver twice

  const { data, html } = toTemplate(event.data.object);

  const dh = await fetch("https://docuhook.com/api/v1/hooks/render", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.DOCUHOOK_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      mode: "async",
      data,
      html,
      filename: `invoice-${data.invoice.number}.pdf`,
    }),
  });

  if (dh.status !== 202) return res.sendStatus(500); // let Stripe retry

  const job = await dh.json(); // { job_id, status_url, result_url }
  await saveJob({ eventId: event.id, invoiceId: event.data.object.id, ...job });
  res.sendStatus(200);
});

app.listen(3000);

alreadyProcessed and saveJob are yours — a database table keyed by event.id is enough. Stripe’s docs recommend exactly that: log processed event IDs and skip repeats.

Two details worth knowing:

  • An Invoice embedded in an event carries a page of line items. If invoice.lines.has_more is true, fetch the rest with stripe.invoices.listLineItems(invoice.id) before mapping.
  • Newer Stripe API versions mark the line item quantity field as deprecated in favor of pricing details, which is why the code falls back to 1. Check the shape your account’s API version sends.

4. Collect the PDF

A cron job or queue worker picks up stored jobs and downloads the finished file. 202 means still pending; 200 with application/pdf is your invoice:

async function collect(job) {
  const res = await fetch(new URL(job.result_url, "https://docuhook.com"), {
    headers: {
      Authorization: `Bearer ${process.env.DOCUHOOK_API_KEY}`,
      Accept: "application/pdf",
    },
  });
  if (res.status === 202) return false; // try again next run
  if (!res.ok) throw new Error(`DocuHook ${res.status}: ${await res.text()}`);

  const pdf = Buffer.from(await res.arrayBuffer());
  await storeInvoicePdf(job.invoiceId, pdf); // S3, disk, or an email attachment
  return true;
}

Job results are kept for a limited time, so store the PDF instead of linking to result_url. Want HTML instead (for an email body)? Request the job with ?format=html, or send "format": "html" when you create it.

Why not @docuhook/node? You can use its hookRender(data, html) for step 3 — it returns { jobId, resultUrl }. For step 4 use plain fetch as above, because the SDK’s jobResult() asks for the JSON (HTML) form.

Dompdf caveat

DocuHook renders the PDF with Dompdf, not Chrome. It handles tables, borders, background colors, and images well, and can load fonts and images from HTTPS URLs. It does not support flexbox or grid, and complex modern CSS can look different from your browser preview. Build invoices with tables — they print reliably everywhere. Need Chrome-exact output? Ask for "format": "html" and print it in your own warm Chrome worker.

Checklist

  • Endpoint subscribed to invoice.paid (snapshot payload)
  • Raw body reaches constructEvent — no JSON middleware on that route
  • Processed event.ids stored; duplicates return 200 without re-rendering
  • Handler returns non-2xx only when you want Stripe to retry
  • Worker downloads result_url with Accept: application/pdf and stores the file
  • Free plan: 100 PDFs/month with a watermark; Starter removes it at 2,500/month — see plans

Related guides

The 3-line fix

Inside your verified invoice.paid handler:

const job = await fetch("https://docuhook.com/api/v1/hooks/render", { method: "POST", headers: { Authorization: `Bearer ${process.env.DOCUHOOK_API_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ mode: "async", data, html }) }).then((r) => r.json());
await saveJob(job); // 202 → job_id + result_url
res.sendStatus(200); // Stripe gets its 2xx immediately; a worker fetches the PDF

Try the template in the live sandbox (no signup), read the API docs, or get an API key.