Direct mail API for Webflow
Direct mail API for Webflow: when someone submits a form or places an order, a signed Webflow webhook calls a small endpoint you host, and that endpoint asks Mailr to print and mail a postcard or letter to the address on it. Each request carries an idempotency key built from the submission or order id, so a retried webhook never mails twice.
What to mail from Webflow
| When this happens | Mail this |
|---|---|
| form_submission on a catalog, sample or quote request form (filtered by form name) | A postcard in your own design to the address on the form. |
| ecomm_new_order, when it is the first order from that email | A thank-you postcard with a code for the next order. (First-order thank you) |
| ecomm_order_changed with status fulfilled | A review request card, sent 21 days later from your own scheduled job. (Review request) |
Set it up
- Name the form fields. Webflow sends each field keyed by its name, so name the address fields Name, Address, Address 2, City, State and ZIP. Make State a Select whose option values are two-letter codes (AZ, not Arizona): Mailr needs a two-letter state and a 5-digit or ZIP+4 code.
- Deploy the endpoint. Deploy the Worker below with npx wrangler deploy, after creating the KV namespace it uses to remember which customers already got a thank-you card. Set MAILR_API_KEY to a test key with npx wrangler secret put. The key never goes into Webflow: custom code and embeds there run in the visitor's browser.
- Create the webhooks with the API. In Site settings > Apps & integrations > API access, generate a site token that can write Sites and read Forms and Ecommerce. Create one form_submission webhook (with a filter on your form's name) and one ecomm_new_order webhook with POST /v2/sites/{site_id}/webhooks. Each response includes a secretKey, shown only then: save each as a Worker secret. Creating them through the API is what gives you a secret to check signatures with.
- Save your return address in Mailr. With a return address saved in Settings, requests can leave out from and Mailr prints the saved one.
- Test, then go live. Submit the form on your webflow.io staging domain with your own address. The postcard shows up in your Mailr dashboard and moves through every status in about 8 minutes, free. When it looks right, add funds and replace MAILR_API_KEY with your mlr_live_ key.
The endpoint: a Cloudflare Worker
// Receives Webflow's form_submission and ecomm_new_order webhooks and mails through Mailr.
// Secrets: MAILR_API_KEY, WEBFLOW_FORM_SECRET, WEBFLOW_ORDER_SECRET. KV namespace: MAILED.
export interface Env {
MAILR_API_KEY: string;
WEBFLOW_FORM_SECRET: string;
WEBFLOW_ORDER_SECRET: string;
MAILED: KVNamespace;
}
// Your design: start from a template's front.html and back.html in mailr.dev/downloads/mailr-kit.zip.
const FRONT = "<html>…your 6x9 front.html with {{first_name}}…</html>";
const BACK = "<html>…your 6x9 back.html…</html>";
const US_ZIP = /^\d{5}(-?\d{4})?$/;
export default {
async fetch(req: Request, env: Env): Promise<Response> {
const path = new URL(req.url).pathname;
const secret = path === "/webflow/form" ? env.WEBFLOW_FORM_SECRET : path === "/webflow/order" ? env.WEBFLOW_ORDER_SECRET : "";
if (req.method !== "POST" || !secret) return new Response("not found", { status: 404 });
const raw = await req.text();
if (!(await signed(req, raw, secret))) return new Response("bad signature", { status: 401 });
const { triggerType, payload } = JSON.parse(raw);
if (triggerType === "form_submission") return mailForm(payload, env);
if (triggerType === "ecomm_new_order") return mailFirstOrder(payload, env);
return new Response("ignored");
},
};
async function mailForm(p: any, env: Env): Promise<Response> {
const d = p.data; // keys are the field names you set in the Designer
const zip = String(d.ZIP ?? "").trim();
if (!d.Address || !US_ZIP.test(zip)) return new Response("no US address, skipped");
const name = String(d.Name ?? "").trim();
const { reply } = await mailr(env, "/postcards", "webflow-form-" + p.id, {
size: "6x9",
front: FRONT,
back: BACK,
to: { name: name.slice(0, 40), line1: d.Address, line2: d["Address 2"] || undefined, city: d.City, state: String(d.State ?? "").toUpperCase(), zip },
merge: { first_name: name.split(" ")[0].slice(0, 14) },
description: ("Webflow form: " + p.name).slice(0, 255),
});
return reply;
}
async function mailFirstOrder(o: any, env: Env): Promise<Response> {
const a = o.shippingAddress;
if (!a || !US_ZIP.test(String(a.postalCode ?? ""))) return new Response("no US shipping address, skipped");
const email = String(o.customerInfo?.email ?? "").toLowerCase();
if (email && (await env.MAILED.get("customer:" + email))) return new Response("not a first order, skipped");
const first = String(o.customerInfo?.fullName || a.addressee).split(" ")[0];
const { sent, id, reply } = await mailr(env, "/postcards", "webflow-order-" + o.orderId, {
size: "6x9",
template: "tmpl_thank_you",
to: { name: String(a.addressee).slice(0, 40), line1: a.line1, line2: a.line2 || undefined, city: a.city, state: a.state, zip: a.postalCode },
merge: { first_name: first.slice(0, 14), promo_code: "THANKS15" }, // promo_code: 12 characters max
description: "Webflow order " + o.orderId,
});
if (sent && email) await env.MAILED.put("customer:" + email, id);
return reply;
}
// One Mailr request. Webflow only counts a 200 as delivered and retries anything else up to 3 more times,
// 10 minutes apart. So: 200 when the piece was made (or replayed), 200 when retrying can't help (a bad
// address is logged), and 500 only when a retry can work (Mailr unreachable, balance short, same key in flight).
async function mailr(env: Env, path: string, idempotencyKey: string, body: object) {
const res = await fetch("https://api.mailr.dev/v1" + path, {
method: "POST",
headers: { Authorization: "Bearer " + env.MAILR_API_KEY, "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
body: JSON.stringify(body),
});
const data: any = await res.json().catch(() => ({}));
if (res.ok) return { sent: true, id: data.id as string, reply: new Response("mailed " + data.id) };
console.log("Mailr", res.status, idempotencyKey, data.error?.message);
const retry = res.status >= 500 || res.status === 402 || res.status === 409;
return { sent: false, id: "", reply: new Response("not mailed", { status: retry ? 500 : 200 }) };
}
// x-webflow-signature is the hex HMAC SHA-256 of "<x-webflow-timestamp>:<raw body>", keyed with the webhook's secret.
async function signed(req: Request, raw: string, secret: string) {
const ts = req.headers.get("x-webflow-timestamp") ?? "";
const sig = req.headers.get("x-webflow-signature") ?? "";
if (!ts || !sig || Math.abs(Date.now() - Number(ts)) > 5 * 60 * 1000) return false; // older than 5 minutes: possible replay
const enc = new TextEncoder();
const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(ts + ":" + raw)));
const hex = Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join("");
let diff = hex.length ^ sig.length;
for (let i = 0; i < hex.length; i++) diff |= hex.charCodeAt(i) ^ sig.charCodeAt(i);
return diff === 0;
}- Webflow counts a delivery as done only on a 200. Anything else is retried up to three more times, 10 minutes apart, and a webhook that keeps failing is deactivated (reactivating it takes Webflow support). That's why the Worker answers 200 for a bad address and logs it, and 500 only when a retry can succeed.
- Webflow signs with x-webflow-timestamp and x-webflow-signature. Its docs say webhooks added in the dashboard may arrive without those headers, while a webhook created through the API with a site token returns its own secretKey. The Worker rejects anything unsigned or older than 5 minutes.
- The Idempotency-Key is webflow-order-{orderId} or webflow-form-{event id}. Webflow's retries all land inside Mailr's 24-hour replay window, so a retried delivery returns the first postcard instead of printing a second.
- A form with a custom action URL skips Webflow's form handling, so form_submission never fires for it. Keep the form on Webflow's own handling.
- On the free Starter plan a site gets 50 form submissions in total, and forms on a custom domain need a Site plan. Checkout needs an Ecommerce plan. Webflow allows 75 webhooks per trigger type per site.
- The thank-you card checks a KV record per email, so it means first order since you turned this on. Customers who ordered before that would get one on their next order; load their emails into KV first if that matters.
What it costs
Each live piece is paid from your Mailr balance, printing and postage included: a 4x6 postcard is $0.85, a 6x9 $0.89 and an 8.5x11 letter $0.95 on pay as you go, less on a plan. Test pieces are free. All prices.
Templates that fit: First-order thank you (6x9), Review request (4x6).
Questions
Is there a Mailr app in the Webflow marketplace?
No. The integration is the Worker on this page calling Mailr's REST API, and a coding agent can adapt it from https://mailr.dev/llms.txt or the SKILL.md in the template kit.
Can I put the Mailr call in Webflow custom code instead?
No. Custom code and embeds ship to every visitor's browser, so anyone could read the key and mail on your account. The key lives in the Worker's secrets, and Webflow only ever talks to the Worker.
We run Webflow sites for many clients. One endpoint or several?
One Worker per client site is simplest: each has that client's Mailr key and its own Webflow secrets, and the logs stay separate. A Webflow webhook secret belongs to one webhook on one site, so a shared endpoint still needs a secret per site.
Can we mail every past customer or form lead in one go?
Yes. Export them from Webflow, keep the rows with a US address, and send them to POST /v1/batches, up to 1,000 recipients per request with one design and per-recipient merge values. A batch is checked in full before anything prints, so one bad ZIP stops that batch instead of half of it mailing. Use an Idempotency-Key such as webflow-backfill-{first order id}-{last order id} for each batch.
How do we see what was delivered?
Every piece is in the Mailr dashboard with its status. Mailr doesn't send webhooks yet, so to pull statuses into your own tools, call GET /v1/postcards/{id}, or list pieces with keyset pagination (limit up to 100, then starting_after).