Guides · shopify order webhook to pdf invoice
Shopify Order Webhook to PDF Invoice
If you searched for Shopify order webhook to PDF invoice, you want every paid order to produce a PDF invoice in your own layout — stored in your system, attached to your own emails, or handed to your accounting tool — without installing another invoice app or running Chrome in your backend.
This guide subscribes to the orders/paid webhook, verifies Shopify’s HMAC, queues a DocuHook render in async mode so you answer Shopify well inside its 5-second limit, and collects the PDF afterwards.
Why the naive version breaks
Shopify is strict about webhook endpoints. Its docs give a one-second connection timeout and a five-second timeout for the whole request. Anything outside the 200 range counts as a failure, and Shopify retries 8 times over the next 4 hours. For subscriptions created through the Admin API, 8 consecutive failures delete the subscription.
Rendering a PDF inside that request — especially with a headless browser that has to cold-start — is the fastest way to lose your webhook. The fix is the same as for Stripe: verify, hand off, return 200.
Architecture
- Shopify POSTs the order JSON to your endpoint with
X-Shopify-Topic: orders/paidand anX-Shopify-Hmac-Sha256signature. - Your handler checks the HMAC against the raw body.
- It skips duplicates by
X-Shopify-Webhook-Id. - It maps the order to template JSON and POSTs it to DocuHook with
"mode": "async"→202+job_id. - It returns
200to Shopify. A cron route downloads the PDF from the job later.
1. Create the webhook
Two common setups:
- Store-level webhook: Shopify admin → Settings → Notifications → Webhooks → Create webhook, pick the order payment event, format JSON, and paste your HTTPS URL. The same page shows the key your webhooks are signed with.
- App webhook: subscribe your app to the
orders/paidtopic (for example inshopify.app.toml). Deliveries are signed with your app’s client secret.
App subscriptions to order topics need the read_orders scope, and customer fields such as name, email, and addresses also require approved access to protected customer data.
2. The invoice template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body { font-family: "DejaVu Sans", sans-serif; margin: 40px; color: #1b1b1b; font-size: 13px; }
h1 { font-size: 24px; margin-bottom: 4px; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { padding: 8px 0; border-bottom: 1px solid #e1e1e1; text-align: left; }
.num { text-align: right; }
</style>
</head>
<body>
<h1>Invoice {{order.name}}</h1>
<p>{{order.date}} · {{customer.name}} · {{customer.email}}</p>
<table>
<thead><tr><th>Product</th><th class="num">Qty</th><th class="num">Price</th></tr></thead>
<tbody>
<!--ROWS-->
</tbody>
</table>
<p class="num">Subtotal {{order.currency}} {{order.subtotal}}<br>
Tax {{order.currency}} {{order.tax}}<br>
<strong>Total {{order.currency}} {{order.total}}</strong></p>
</body>
</html>The <!--ROWS--> marker gets one row per line_items entry, built in code. Templates have no loops, and building indexed token rows keeps DocuHook in charge of escaping product titles.
3. The webhook route (Next.js App Router)
app/api/webhooks/shopify/route.ts — reading req.text() gives you the untouched body, which the HMAC needs:
import { createHmac, timingSafeEqual } from "node:crypto";
import { INVOICE_TEMPLATE } from "@/lib/invoice-template";
export const runtime = "nodejs";
function validHmac(raw: string, header: string | null): boolean {
if (!header) return false;
const digest = createHmac("sha256", process.env.SHOPIFY_WEBHOOK_SECRET!)
.update(raw, "utf8")
.digest();
const received = Buffer.from(header, "base64");
return received.length === digest.length && timingSafeEqual(digest, received);
}
function toTemplate(order: any) {
const rows = order.line_items
.map(
(_: unknown, i: number) =>
`<tr><td>{{items.${i}.title}}</td><td class="num">{{items.${i}.quantity}}</td><td class="num">{{order.currency}} {{items.${i}.price}}</td></tr>`
)
.join("\n");
const b = order.billing_address ?? {};
return {
html: INVOICE_TEMPLATE.replace("<!--ROWS-->", rows),
data: {
order: {
name: order.name, // e.g. "#1001"
date: String(order.created_at).slice(0, 10),
currency: order.currency,
subtotal: order.subtotal_price,
tax: order.total_tax,
total: order.total_price,
},
customer: {
name: [b.first_name, b.last_name].filter(Boolean).join(" "),
email: order.email ?? order.contact_email ?? "",
},
items: order.line_items.map((li: any) => ({
title: li.title,
quantity: li.quantity,
price: li.price,
})),
},
};
}
export async function POST(req: Request) {
const raw = await req.text();
if (!validHmac(raw, req.headers.get("x-shopify-hmac-sha256"))) {
return new Response("Invalid HMAC", { status: 401 });
}
if (req.headers.get("x-shopify-topic") !== "orders/paid") {
return new Response(null, { status: 200 });
}
const webhookId = req.headers.get("x-shopify-webhook-id") ?? "";
if (await alreadyProcessed(webhookId)) return new Response(null, { status: 200 });
const order = JSON.parse(raw);
const { data, html } = toTemplate(order);
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-${order.order_number}.pdf`,
}),
});
if (dh.status !== 202) return new Response("Render queue failed", { status: 500 });
const job = await dh.json(); // { job_id, status_url, result_url }
await saveJob({ webhookId, orderId: order.id, shop: req.headers.get("x-shopify-shop-domain"), ...job });
return new Response(null, { status: 200 });
}alreadyProcessed and saveJob are your persistence (a table keyed by webhook ID). Shopify says duplicates happen after timeouts and retries, and recommends exactly this X-Shopify-Webhook-Id check.
Money fields in Shopify’s REST-shaped webhook payloads (price, subtotal_price, total_tax, total_price) are already decimal strings in the shop currency, so no cents math is needed.
4. Download the PDF on a schedule
A cron route (Vercel Cron, a GitHub Action, or plain crontab) collects finished jobs:
// app/api/cron/invoices/route.ts
export async function GET() {
for (const job of await pendingJobs()) {
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) continue; // not ready yet
if (!res.ok) { await markFailed(job, await res.text()); continue; }
await storeInvoice(job.orderId, Buffer.from(await res.arrayBuffer()));
}
return Response.json({ ok: true });
}Results are temporary, so store the bytes (S3, R2, your DB) rather than the URL. If you ever want the merged HTML instead — to paste into an email body, say — add ?format=html to the result URL or send "format": "html" when you queue the job.
Dompdf caveat
The PDF is rendered by Dompdf after the merge, not by Chrome. That is why it is fast and needs no browser, and also why you should stick to tables and simple block layout. Flexbox and grid are not supported, and your Liquid-themed storefront CSS will not carry over unchanged. Product images work when their URLs are publicly reachable over HTTPS (Shopify CDN URLs are).
Checklist
- Webhook subscribed to
orders/paid, JSON format, HTTPS URL - HMAC computed over the raw body with the right secret (store key or app client secret)
- Duplicate deliveries skipped by
X-Shopify-Webhook-Id - Handler returns
200in well under 5 seconds - Cron collects
result_urlwithAccept: application/pdf - Watch monthly PDF volume against your plan (Free 100, Starter 2,500, Pro 10,000)
Related guides
- Stripe webhook to PDF invoice
- WooCommerce webhook to PDF invoice
- How to generate PDF from HTML in Next.js
- Webhook to PDF: Zapier / n8n vs API
The 3-line fix
After the HMAC check:
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
return new Response(null, { status: 200 }); // Shopify gets 200 fast; cron fetches the PDFTest your template in the live sandbox (no signup), check the API docs, or create an API key.