Send a postcard when a Stripe payment fails or a customer cancels
To send a postcard when a Stripe payment fails, listen for two Stripe webhooks and call Mailr from them. When invoice.payment_failed arrives for the third time, mail a reminder; when customer.subscription.deleted arrives, mail a win-back postcard. The handler below does both and records what it sent, so a retried webhook never mails twice.
Why paper, and why the third retry
Stripe retries a failed card several times and emails the customer along the way. If the third retry still fails, those emails didn’t work. A short printed note on the kitchen counter is a different channel at the moment it matters. Waiting for the third retry also keeps cost down: a card that recovers on an earlier retry never triggers a mailing.
Paper mail isn’t in an envelope here, so keep it discreet: no amounts and no card details. The tmpl_payment_failed flat is written that way.
The webhook handler: failed payments and cancelled subscriptions
A Next.js App Router route using the official stripe package. It needs STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET and MAILR_API_KEY.
// app/api/stripe-webhook/route.js (Next.js App Router). npm install stripe
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
async function sendMail(path, body) {
const res = await fetch(`https://api.mailr.dev/v1/${path}`, {
method: "POST",
headers: { Authorization: `Bearer ${process.env.MAILR_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const piece = await res.json();
if (!res.ok) throw new Error(piece.error.message);
return piece;
}
// Stripe stores addresses as { line1, line2, city, state, postal_code }.
const toAddress = (customer) => ({
name: customer.name,
line1: customer.address.line1,
...(customer.address.line2 ? { line2: customer.address.line2 } : {}),
city: customer.address.city,
state: customer.address.state,
zip: customer.address.postal_code,
});
const FROM = { name: "Acme Outdoor", line1: "1 Example Way", city: "Phoenix", state: "AZ", zip: "85004" };
export async function POST(req) {
const event = stripe.webhooks.constructEvent(
await req.text(),
req.headers.get("stripe-signature"),
process.env.STRIPE_WEBHOOK_SECRET,
);
// Third failed retry: a calm reminder on paper, once per invoice.
if (event.type === "invoice.payment_failed") {
const invoice = event.data.object;
if (invoice.attempt_count >= 3 && !invoice.metadata?.mailr_piece) {
const customer = await stripe.customers.retrieve(invoice.customer);
if (customer.address?.line1) {
const piece = await sendMail("flats", {
size: "8.5x11",
template: "tmpl_payment_failed",
to: toAddress(customer),
from: FROM,
merge: {
first_name: (customer.name ?? "there").split(" ")[0],
plan: "Pro",
update_url: "acme.co/billing",
},
});
await stripe.invoices.update(invoice.id, { metadata: { mailr_piece: piece.id } });
}
}
}
// Cancelled subscription: a win-back postcard, once per subscription.
if (event.type === "customer.subscription.deleted") {
const subscription = event.data.object;
const customer = await stripe.customers.retrieve(subscription.customer);
if (customer.address?.line1 && !customer.metadata?.mailr_winback) {
const piece = await sendMail("postcards", {
size: "6x11",
template: "tmpl_winback",
to: toAddress(customer),
from: FROM,
merge: { first_name: (customer.name ?? "there").split(" ")[0], promo_code: "PEAK15", last_product: "Pro plan" },
});
await stripe.customers.update(customer.id, { metadata: { mailr_winback: piece.id } });
}
}
return Response.json({ received: true });
}How it avoids double mail
- The reminder writes the Mailr piece id into the invoice’s
metadata.mailr_pieceand skips any invoice that already has one. - The win-back writes
metadata.mailr_winbackon the customer, so a customer gets it once even across several cancellations. - Customers without a billing address on file are skipped instead of failing.
Send a welcome letter to new customers automatically
The same pattern works for a welcome note. When your app creates an account, or Stripe sends customer.subscription.created, send the welcome letter, an 8.5x11 flat, with POST /v1/flats and the merge fields first_name, company and founder_name. Record its id on the customer so it goes out once.
Win-back postcards for lapsed customers
Not every lapsed customer cancels. A nightly job that finds customers with no payment or login in 60 days can send the same win-back postcard the cancellation branch uses. Give win-back direct mail an offer code and a short link back to your app.
Set it up
- In Stripe, add a webhook endpoint for
https://your-app.com/api/stripe-webhookwith the eventsinvoice.payment_failedandcustomer.subscription.deleted. - Copy its signing secret into
STRIPE_WEBHOOK_SECRET. - Start with a Mailr test key, trigger a test failure with the Stripe CLI, and watch the piece appear in your Mailr dashboard.
- Change
planandupdate_urlto your own values.update_urlhas a 28-character limit, so use a short billing link.