Send email from Stripe webhooks
Send order confirmations and failed-payment emails from Stripe events: verify the webhook signature, call Envello's API, and use the Stripe event id as the idempotency key so retries never send twice.
Updated · 2 min read
Stripe tells your server what happened through webhooks: a checkout completed, an invoice failed, a subscription was cancelled. Sending the customer an email from those events is the reliable way to do order confirmations and dunning, because the event fires whether the customer finished on your site or closed the tab.
The pattern has three parts. Verify Stripe's signature on the raw body. Send the email through Envello's API. Answer 200 quickly. Stripe retries a webhook that doesn't get a 2xx, so the send has to be safe to repeat, and that's what an idempotency key is for.
Setup
Install the three packages: npm install express stripe envello. Set STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET (the whsec_ value from the webhook endpoint in Stripe's dashboard, or from stripe listen locally) and ENVELLO_API_KEY. Verify the domain in your FROM address in Envello first; sends from an unverified domain are refused with a 403.
The webhook handler
One Express route handles both events. express.raw keeps the body as a Buffer, which constructEvent needs: if a JSON body parser runs first, the bytes change and every signature check fails.
import express from "express";
import Stripe from "stripe";
import { Envello } from "envello";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const envello = new Envello(process.env.ENVELLO_API_KEY);
const FROM = "Acme Billing <[email protected]>";
const app = express();
// Stripe signs the raw request bytes, so this route must get the body
// before any JSON parser touches it.
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(`Signature check failed: ${err.message}`);
}
try {
await handleEvent(event);
} catch (err) {
// A non-2xx makes Stripe retry. The idempotency key below means a retry
// that reaches Envello twice still sends one email.
console.error("Email for Stripe event failed", event.id, err);
return res.sendStatus(500);
}
res.sendStatus(200);
});
async function handleEvent(event) {
switch (event.type) {
case "checkout.session.completed":
return sendOrderConfirmation(event);
case "invoice.payment_failed":
return sendPaymentFailed(event);
default:
return; // Ignore everything else, but still answer 200.
}
}
async function sendOrderConfirmation(event) {
const session = event.data.object;
const email = session.customer_details?.email;
if (!email) return;
await envello.emails.send(
{
from: FROM,
to: email,
subject: "Your order is confirmed",
html: `<p>Thanks for your order. You paid ${formatAmount(session.amount_total, session.currency)}.</p>`,
tags: [
{ name: "source", value: "stripe" },
{ name: "type", value: "order_confirmation" },
],
},
{ idempotencyKey: `stripe:${event.id}` },
);
}
async function sendPaymentFailed(event) {
const invoice = event.data.object;
if (!invoice.customer_email) return;
await envello.emails.send(
{
from: FROM,
to: invoice.customer_email,
subject: "Your payment didn't go through",
html: `<p>We couldn't charge ${formatAmount(invoice.amount_due, invoice.currency)} for your subscription.</p>
<p><a href="${invoice.hosted_invoice_url}">Update your card and pay the invoice</a></p>`,
tags: [
{ name: "source", value: "stripe" },
{ name: "type", value: "payment_failed" },
],
},
{ idempotencyKey: `stripe:${event.id}` },
);
}
// Stripe amounts are in the currency's smallest unit. This assumes a
// two-decimal currency (EUR, USD); zero-decimal ones such as JPY differ.
function formatAmount(amount, currency) {
return new Intl.NumberFormat("en-IE", { style: "currency", currency: currency.toUpperCase() }).format(amount / 100);
}
app.listen(3000);Why the Stripe event id is the idempotency key
Stripe can deliver the same event more than once: after a timeout, a 5xx from your server, or a manual resend from the dashboard. Each delivery carries the same event.id. Passing stripe:<event id> as the idempotency key means Envello creates the email on the first call and returns the same result for any repeat within 24 hours, without sending again.
Don't generate the key with a random value inside the handler. A retry would get a new key and a second email. The key has to come from the event, and Envello accepts letters, digits and . _ : - up to 255 characters, which Stripe's evt_ ids fit.
Which Stripe events to use
Subscribe the webhook endpoint in Stripe only to the events you handle. Fewer events means fewer requests and a smaller log to read when something goes wrong.
| Stripe event | Where the address is | |
|---|---|---|
| Order confirmation (Checkout) | checkout.session.completed | data.object.customer_details.email |
| Failed payment / dunning | invoice.payment_failed | data.object.customer_email |
| Subscription receipt | invoice.paid | data.object.customer_email |
| Trial ending soon | customer.subscription.trial_will_end | Look up data.object.customer with stripe.customers.retrieve() |
| Cancellation confirmation | customer.subscription.deleted | Look up data.object.customer |
Don't send the same email twice
Stripe can email customers itself: receipts, failed-payment notices and upcoming-renewal reminders are settings in its dashboard. If you send your own version, switch Stripe's off for that email type, or customers get two messages for one event.
Test it locally
The Stripe CLI forwards test-mode events to your machine and can trigger them on demand. Use an env_test_ Envello key while you do this: test-mode emails are accepted and logged but never delivered, so you can trigger events all afternoon without mailing anyone.
stripe listen --forward-to localhost:3000/webhooks/stripe
# prints a whsec_... signing secret: use it as STRIPE_WEBHOOK_SECRET locally
stripe trigger checkout.session.completed
stripe trigger invoice.payment_failedIn production
Keep the handler fast. Stripe expects a quick response, and an email API call is usually well under a second, so sending inline is fine at modest volume. If the handler also writes to your database or calls other services, put the work on a queue and answer 200 straight away; the idempotency key still protects you if the queue retries.
Escape anything you interpolate into HTML that a customer controls, such as a name from Checkout. The amounts and Stripe-hosted URLs in the example come from Stripe, not from the customer.
Check your domain's SPF, DKIM, and DMARC records
Paste in a domain and see what's missing, plus the exact DNS records to fix it. Free, no account needed.
Check your domain →