Direct mail API for Squarespace
Direct mail API for Squarespace: when someone places an order or submits a form block, a small Worker or a Zap sends the address to Mailr, which prints the postcard or letter and mails it. Orders come from Squarespace's Orders API or its order.create webhook; form blocks go out through Squarespace's Zapier storage option.
What to mail from Squarespace
| When this happens | Mail this |
|---|---|
| A new order (order.create, or the Orders API checked every 15 minutes), on the customer's first order | A thank-you postcard with a code for the next order. (First-order thank you) |
| An order's fulfillmentStatus turns FULFILLED | A review request card 21 days later, from your own scheduled job. (Review request) |
| A form block submission, through the Zapier storage option | A postcard in your own design to the address on the form. |
Set it up
- Pick the route. One store: an API key and a Worker that reads new orders every 15 minutes. An app or agency with an approved Squarespace OAuth client: subscribe each site to order.create webhooks. Form blocks: Squarespace's Zapier storage option, because the Forms API is read-only and meant for Zapier.
- Create an API key. API keys come with Squarespace's Commerce Advanced plan. In Settings, under Advanced > Developer API Keys, create a key with Orders read-only access. Squarespace shows it once: save it as the Worker secret SQSP_API_KEY.
- Deploy the Worker. Create a KV namespace for the Worker's state, add the cron trigger from the comment at the top of the first tab, set MAILR_API_KEY and SQSP_API_KEY with npx wrangler secret put, and deploy. Save a return address in Mailr Settings so requests can leave out from.
- Test with test-mode orders. With a Mailr test key, the Worker only mails Squarespace orders placed in test mode, and with a live key only real ones. Place a test-mode order with your own US address; within 15 minutes the postcard is in your Mailr dashboard, moving through every status in about 8 minutes, free.
- Go live. Add funds in Mailr and set MAILR_API_KEY to your mlr_live_ key. The next run mails real orders.
The Worker, the webhook receiver and the Zap
// Cloudflare Worker on a cron: reads new Squarespace orders with an API key and mails a thank-you
// postcard on each customer's first order. Secrets: SQSP_API_KEY, MAILR_API_KEY. KV namespace: STATE.
// wrangler.toml: [triggers] crons = ["*/15 * * * *"]
export interface Env { SQSP_API_KEY: string; MAILR_API_KEY: string; STATE: KVNamespace }
const ORDERS = "https://api.squarespace.com/1.0/commerce/orders";
const UA = "acme-mailr-sync/1.0"; // Squarespace requires a User-Agent that names your app
export default {
async scheduled(_event: ScheduledController, env: Env, ctx: ExecutionContext) {
ctx.waitUntil(sync(env));
},
};
async function sync(env: Env) {
const now = new Date().toISOString();
const since = (await env.STATE.get("last_run")) ?? new Date(Date.now() - 3600_000).toISOString();
// modifiedAfter and modifiedBefore go together; later pages use the cursor alone. Up to 50 orders a page.
let url = ORDERS + "?modifiedAfter=" + encodeURIComponent(since) + "&modifiedBefore=" + encodeURIComponent(now);
let allDone = true;
while (url) {
const res = await fetch(url, { headers: { Authorization: "Bearer " + env.SQSP_API_KEY, "User-Agent": UA } });
if (!res.ok) throw new Error("Squarespace " + res.status); // last_run stays put; the next run tries again
const page: any = await res.json();
for (const order of page.result) allDone = (await thankFirstOrder(order, env)) && allDone;
url = page.pagination?.hasNextPage ? ORDERS + "?cursor=" + encodeURIComponent(page.pagination.nextPageCursor) : "";
}
// Move the window only when nothing needs a retry. Re-reading an order is safe: see the checks below.
if (allDone) await env.STATE.put("last_run", now);
}
// Returns false only when a later run should try this order again.
async function thankFirstOrder(o: any, env: Env): Promise<boolean> {
const testKey = env.MAILR_API_KEY.startsWith("mlr_test_");
if (Boolean(o.testmode) !== testKey) return true; // test-mode orders with a test key, real orders with a live key
if (o.fulfillmentStatus === "CANCELED" || Date.now() - Date.parse(o.createdOn) > 7 * 86400_000) return true; // old orders edited later
const a = o.shippingAddress ?? o.billingAddress;
if (!a || a.countryCode !== "US") return true;
const email = String(o.customerEmail ?? "").toLowerCase();
if (await env.STATE.get("customer:" + email)) return true; // already thanked
const res = await fetch("https://api.mailr.dev/v1/postcards", {
method: "POST",
headers: { Authorization: "Bearer " + env.MAILR_API_KEY, "Content-Type": "application/json", "Idempotency-Key": "sqsp-order-" + o.id },
body: JSON.stringify({
size: "6x9",
template: "tmpl_thank_you",
to: { name: (a.firstName + " " + a.lastName).trim().slice(0, 40), line1: a.address1, line2: a.address2 || undefined, city: a.city, state: a.state, zip: a.postalCode },
merge: { first_name: String(a.firstName).slice(0, 14), promo_code: "THANKS15" }, // promo_code: 12 characters max
description: "Squarespace order " + o.orderNumber,
}),
});
const piece: any = await res.json().catch(() => ({}));
if (res.ok) {
await env.STATE.put("customer:" + email, piece.id);
return true;
}
console.log("Mailr", res.status, "order", o.orderNumber, piece.error?.message);
return !(res.status >= 500 || res.status === 402 || res.status === 409); // a bad address won't fix itself
}- Squarespace's Webhook Subscriptions API only accepts OAuth tokens, and an OAuth client has to be registered and approved by Squarespace. A single store with an API key can't subscribe to webhooks, which is why the first tab reads the Orders API on a schedule instead.
- Squarespace needs a User-Agent header that describes your app on every request. The Orders API returns up to 50 orders a page sorted by modifiedOn; modifiedAfter and modifiedBefore must be sent together, and the cursor can't be combined with them.
- Webhook deliveries count as received on any 2xx. Squarespace retries failures for up to 48 hours, may deliver the same notification more than once or out of order, and may delete a subscription that keeps failing. The Idempotency-Key built from the site and order id turns repeats into replays of the first postcard.
- The polling Worker only advances its time window when every order went through or failed for good, so an outage at Mailr or a short balance is retried on the next run. The KV record per customer and the Idempotency-Key sqsp-order-{id} make re-reading an order safe.
- Form blocks can store submissions in the Contacts panel, a mailing list, email, Google Drive, Mailchimp or Zapier. Zapier is the option that runs your own step on each submission; it and Mailchimp need the Core, Plus or Advanced plan (or some legacy plans). Keep the Mailr key in the Zap, never in Code Injection, which runs in visitors' browsers.
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 extension for Squarespace?
No. The Worker or the Zap on this page is the integration, calling Mailr's REST API. A coding agent can adapt it from https://mailr.dev/llms.txt or the SKILL.md in the template kit.
Why poll every 15 minutes instead of using webhooks?
Squarespace only lets OAuth apps create webhook subscriptions. For one store, an API key and a 15-minute schedule get the same postcard out without registering an OAuth client, and a postcard doesn't need second-by-second timing. Agencies building an app across many client sites can use order.create instead (second tab).
Can we mail everyone who has already ordered?
Yes. Page through the Orders API (50 orders a page), keep the US shipping addresses, and send them to POST /v1/batches, up to 1,000 recipients per request with one design and each customer's own merge values. Every address is checked before anything prints, so a bad ZIP stops that batch rather than half of it mailing. Build each batch's Idempotency-Key from its first and last order number.
Will a customer get two postcards if an order is edited?
No. The Worker skips customers it has already thanked, and the Idempotency-Key sqsp-order-{order id} makes a repeated request within 24 hours return the first postcard instead of printing another.
How do we see what was delivered?
Every piece is in the Mailr dashboard with its status. Mailr doesn't send webhooks yet, so poll GET /v1/postcards/{id}, or list with keyset pagination, if you want statuses in your own reports.