How to trigger dunning emails from Stripe webhooks: event map and code
Trigger dunning emails from Stripe webhooks by mapping invoice.payment_failed and three other events to email templates with code. This guide shows the exact payload fields to extract, signature verification with constructEvent, and an idempotent Node.js handler that prevents duplicate sends.
On this page
TL;DR: Stripe fires four events that drive dunning logic:invoice.payment_failed,invoice.payment_action_required,invoice.paid, andcustomer.subscription.deleted. Map each to a specific email template, verify the webhook signature withstripe.webhooks.constructEvent, and prevent duplicate sends by checking a database record before dispatching. The send.io Idempotency-Key header covers sequential retries for 24 hours, but it doesn't stop two concurrent deliveries from both passing the database check, so add a unique constraint onevent_idto make only one insert succeed.
Your Stripe webhook fires invoice.payment_failed, and your dunning email never arrives, but the bug isn't in your email provider. It sits in the mapping between the event and the send.
Most dunning guides stop at the event name. This one goes further: it maps each Stripe event to a specific email template, shows the exact payload fields to extract, and walks through a signature-verified, idempotent Node.js handler that dispatches through send.io's transactional API. The translation layer lets you swap payment gateways without rewriting your email logic, and the Stripe CLI workflow validates the complete flow locally before you deploy.
Mapping invoice.payment_failed to dunning flows
Stripe emits dozens of payment-related events, but only four matter for dunning logic. Each maps to a distinct email action, and confusing them produces the wrong message at the wrong time.
You can handle dunning in two ways: use Stripe's native retry logic with basic email notifications, or build a custom implementation that gives you full control over templates and retry cadence.
Feature | Native Stripe Dunning | Custom Implementation with send.io |
|---|---|---|
Complexity | Configure in Stripe Dashboard | Requires webhook handler code |
When to choose | Simple retry-only flows | Custom templates and retry cadence |
Email template control | Limited to Stripe's templates | Full control over design and content |
Once you decide on a custom implementation, these are the four Stripe events that drive the flow:
Stripe Event | Dunning Action | Suggested Email Template | Retry Cadence |
|---|---|---|---|
| Start dunning sequence and escalate email tone by | Payment failed notice | Configurable in Stripe; for example, 8 tries within 2 weeks with Smart Retries |
| Prompt customer authentication with a direct link to complete it | Action required notice | 1 send, no auto-retry |
| Stop dunning sequence and cancel pending sends for that invoice ID | Payment confirmation (optional, only if your product requires one) | N/A |
| Halt all dunning emails for that customer ID and mark pending sends as suppressed | Subscription canceled (your own template, sent only if you want to confirm the cancellation) | N/A |
Processing Stripe failed payment webhooks
The invoice.payment_failed event fires whenever an invoice payment attempt fails, on subscription and one-off invoices alike, whether from a declined payment (including soft declines) or a missing stored payment method. The webhook payload carries the invoice ID, customer email, amount due, attempt count, and next payment attempt timestamp.
Use invoice.payment_failed for subscription dunning, not charge.failed. The charge.failed event fires for any failed charge, including one-time payments. The invoice.payment_failed event is tied to an invoice and includes the attempt count and next retry timestamp that dunning logic requires.
The attempt_count attribute tells you how many collection attempts Stripe has made. Use this to escalate your email tone: a first failure gets a gentle nudge, a third failure gets a final notice before service suspension.
Mapping invoice action required webhooks
The invoice.payment_action_required event fires when a payment requires customer authentication, such as 3D Secure verification. Stripe cannot auto-retry these payments because the customer must complete authentication, so this event maps to a different template than a standard failure.
The email for this event should include a direct link to complete authentication, not a generic "update your payment method" message. The customer's payment method may be valid, but the issuer requires additional authentication before the charge can complete.
Mapping invoice.paid to email logic
The invoice.paid event should stop dunning, not start it. When this event arrives, query your database for any pending dunning emails scheduled for that invoice ID and cancel them.
Send a payment confirmation email only if your product requires one. Stripe's receipt email already confirms the charge, so a second confirmation from your app adds noise unless you include product-specific information such as updated access dates or invoice download links.
Handling customer.subscription.deleted
The customer.subscription.deleted event means the customer churned or you canceled their subscription manually. Either way, halt all dunning emails for that customer ID immediately.
Query your scheduled sends table for any pending dunning emails tied to that customer and mark them as suppressed. If you don't, you'll send a "please update your payment method" email to someone who no longer has a subscription, which generates an avoidable support request.
Defining the Stripe webhook to email schema
The mapping between Stripe's event payload and your email template variables is where most dunning implementations break. Define this schema explicitly before you write any handler code.
Mapping invoice.payment_failed webhooks
Extract these fields from the invoice.payment_failed payload:
Example payload (field values are illustrative):
{
"customer_email": "user@example.com",
"invoice_id": "in_1234567890",
"amount_due": 4900,
"attempt_count": 2,
"next_payment_attempt": 1798761600
}
Map each field to a template variable in your email. The amount_due arrives in cents, so divide by 100 before rendering. The next_payment_attempt is a Unix timestamp, so convert it to a human-readable date in your template. When Stripe has exhausted its retries, next_payment_attempt is null, so your template needs a fallback for that case.
Configuring invoice.payment_failed webhooks
In the Stripe Dashboard, go to Developers, then Webhooks, then Add endpoint. Set the endpoint URL to your webhook route (for example, https://api.yourapp.com/webhooks/stripe).
Under Events to send, select invoice.payment_failed, invoice.payment_action_required, invoice.paid, and customer.subscription.deleted. Stripe will send a test webhook to verify the endpoint before saving.
Copy the signing secret that Stripe generates. You'll need it for signature verification in your handler code.
Payment confirmation email template
The template for invoice.paid should include the invoice ID, amount paid, and a link to the receipt. This is your own template, not a Stripe-defined one, so you choose the subject line. One example: "Payment received for invoice {{invoice_id}}." Adapt the wording to your product and brand voice.
Body structure:
- Greeting with customer name
- Invoice number and amount
- Link to view receipt
- Next billing date (if applicable)
Subscription canceled email template
The template for customer.subscription.deleted should confirm the cancellation and explain what happens next. This is your own template, not a Stripe-defined one, so you choose the subject line. One example: "Your subscription has been canceled." Adapt the wording to your product and brand voice.
Body structure:
- Confirmation of cancellation
- Date access ends
- Link to reactivate (if applicable)
- Export data option (if applicable)
Implementing the Stripe webhook event handler
The handler code is where theory meets production. This section walks through a complete Node.js/Express implementation with signature verification, event routing, and duplicate prevention.
Securing webhooks with signature checks
Stripe signs every webhook request with a signature in the Stripe-Signature header. Verify this signature before processing the event, or you'll accept forged events from anyone who knows your endpoint URL.
The verification requires the raw request body, not parsed JSON, so use Express's express.raw() middleware on the webhook route and place it before express.json() in your middleware stack. If express.json() runs first it parses the body into an object, and signature verification fails because the hash no longer matches the original bytes Stripe signed.
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const app = express();
// Webhook route must use raw body parser
app.post('/webhooks/stripe',
express.raw({ type: 'application/json' }),
async (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
sig,
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
console.error(`Webhook signature verification failed: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Route to handler
await handleStripeEvent(event);
res.json({ received: true });
}
);
// JSON parser for all other routes
app.use(express.json());
Every retry from Stripe generates a new signature with an updated timestamp, so retries pass the default 5-minute tolerance window even if the original event is hours old.
Routing webhooks to dunning logic
Use a switch statement to route each event type to its handler function. Include a default case for unhandled events so you can log them without breaking the response.
async function handleStripeEvent(event) {
switch (event.type) {
case 'invoice.payment_failed':
await handlePaymentFailed(event.data.object);
break;
case 'invoice.payment_action_required':
await handleActionRequired(event.data.object);
break;
case 'invoice.paid':
await handlePaymentSucceeded(event.data.object);
break;
case 'customer.subscription.deleted':
await handleSubscriptionDeleted(event.data.object);
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
}
Return a 200 status code immediately after routing, even if the email send fails. Stripe retries webhooks for up to 3 days with exponential backoff, so a 500 response means you'll see the same event again.
Preventing duplicate email triggers
Stripe retries failed webhook deliveries, and network issues can cause the same event to arrive twice. Your handler must be idempotent: processing the same event twice should produce the same result as processing it once.
Use a check-before-send pattern. Query your database for an existing send record with the event ID before dispatching the email:
async function handlePaymentFailed(invoice) {
const eventId = invoice.id;
// Check if a dunning email was already sent for this event
const existing = await db.query(
'SELECT id FROM dunning_sends WHERE event_id = $1',
[eventId]
);
if (existing.rows.length > 0) {
console.log(`Already processed event ${eventId}, skipping`);
return;
}
// Send email and record the send
await sendDunningEmail(invoice);
await db.query(
'INSERT INTO dunning_sends (event_id, sent_at) VALUES ($1, NOW())',
[eventId]
);
}
This pattern prevents duplicate sends even if the webhook arrives multiple times. The database insert should use a unique constraint on event_id to handle race conditions between concurrent webhook deliveries. If two webhook requests for the same event arrive simultaneously, both will query the database, find no existing record, and attempt to send. The unique constraint ensures only one insert succeeds, and the second request's insert fails with a duplicate key error, preventing the duplicate send.
A second race condition can occur when invoice.payment_failed and invoice.paid arrive out of order due to network delays. Query for both event types before sending a dunning email, and skip the send if invoice.paid already exists for that invoice ID.
Handling webhook processing errors
If your email send fails after signature verification succeeds, don't return a 500 status. That tells Stripe to retry the webhook, which will fail again if the underlying issue (for example, a template error) hasn't been fixed.
Instead, log the error, push the event to a dead-letter queue, and return 200. A dead-letter queue stores failed events so you can inspect and retry them without blocking the main webhook flow. Tools like Bull, RabbitMQ, or a simple Postgres table all work for this pattern.
Production readiness checklist
Before deploying your webhook handler to production, verify each of these requirements:
- Signature verification runs on every webhook request with
stripe.webhooks.constructEvent - Webhook route uses
express.raw()middleware, notexpress.json() - Database state check prevents duplicate sends from the same event ID
- Idempotency-Key header includes event ID and attempt count
- Dead-letter queue captures failed email sends without blocking webhook response
- Scoped API key limited to sending from your sending domain, not primary account key
- Webhook signing secret stored in environment variable, not hardcoded
- Handler returns 200 status after routing, even if email send fails
- Event ID has unique constraint in database to handle concurrent deliveries
- Delivery event webhooks configured to trace email sends back to Stripe events
Secure code pattern for payment failure webhooks
A duplicate or forged dunning email reaches a customer when any one of three pieces fails: the Express route that preserves the raw body for signature checks, the dispatch function that maps the invoice to a send, and the send.io POST /emails call with its Idempotency-Key header. The code below shows each piece.
Setting up Stripe webhook routing
The Express route setup requires the raw body parser on the webhook path and the JSON parser on all other routes:
const express = require('express');
const app = express();
// Stripe webhook route (raw body)
app.post('/webhooks/stripe',
express.raw({ type: 'application/json' }),
stripeWebhookHandler
);
// All other routes (JSON body)
app.use(express.json());
The order matters. If you register express.json() before the webhook route, it parses the body and signature verification fails.
Dispatching Stripe events to emails
The dispatch function maps Stripe's event payload to send.io's POST /emails request body. The body requires from and subject, and a template object that carries the template id and its variables. Extract the customer email, template variables, and a client-generated idempotency key:
async function dispatchDunningEmail(invoice, templateId) {
const idempotencyKey = `stripe-${invoice.id}-attempt-${invoice.attempt_count}`;
const payload = {
from: 'billing@yourapp.com',
to: invoice.customer_email,
subject: `Payment failed for invoice ${invoice.id}`,
template: {
id: templateId,
variables: {
invoice_id: invoice.id,
amount_due: (invoice.amount_due / 100).toFixed(2),
attempt_count: invoice.attempt_count,
next_attempt: new Date(invoice.next_payment_attempt * 1000).toLocaleDateString()
}
}
};
return await sendEmail(payload, idempotencyKey);
}
In this example, the idempotency key is a string your code builds, not a format send.io prescribes. It combines the invoice ID and attempt count, so a retry of the same webhook event produces the same key. A new attempt (for example, attempt_count increments from 2 to 3) produces a different key and sends a new email. Any key that stays stable per business operation works, so choose a construction that matches how you define one send.
Executing transactional email sends
The send.io API call includes the Idempotency-Key header, which send.io stores for 24 hours. A retry with the same key returns the original result instead of sending a duplicate:
const fetch = require('node-fetch');
async function sendEmail(payload, idempotencyKey) {
const response = await fetch('https://api.send.io/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SENDIO_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const error = await response.json();
throw new Error(`send.io API error: ${error.message}`);
}
return await response.json();
}
The response includes a message ID you can log for tracing. send.io's delivery event webhooks fire when the email is delivered, bounced, or complained about, and they carry the message ID, event type, timestamp, and recipient.
Use a scoped API key limited to sending from your sending domain, not your primary account key. If the webhook handler is compromised, a scoped key limits the damage to sending email from that domain.
Isolating your event processing code
Build a translation layer that converts each gateway's event payload to a normalized schema, and your email dispatch code stays unchanged when you swap payment gateways or add a second one.
Standardizing Stripe event payloads
Define a normalized internal event schema that represents a payment failure, regardless of which gateway produced it:
interface PaymentFailureEvent {
customerId: string;
customerEmail: string;
amountDue: number;
currency: string;
attemptCount: number;
nextAttempt: Date | null;
gatewayEventId: string;
}
Your email dispatch code consumes this interface, not Stripe's raw payload. When you add a second gateway, you write a new translator function, not a new email handler.
Mapping other gateways to Stripe events
Braintree, Paddle, and Chargebee all emit payment failure events, but the payload structure differs. A translator function converts each gateway's event to the normalized schema:
- Braintree:
subscription_charged_unsuccessfullymaps toPaymentFailureEvent - Paddle:
subscription_payment_failedmaps toPaymentFailureEvent - Chargebee:
payment_failedmaps toPaymentFailureEvent
The email dispatch code stays unchanged. You add a new translator, register it in your webhook router, and the rest of the flow works without modification.
Coding a Stripe webhook translator
The translator function converts Stripe's invoice.payment_failed payload to the normalized schema:
function translateStripeInvoice(invoice: any): PaymentFailureEvent {
return {
customerId: invoice.customer,
customerEmail: invoice.customer_email,
amountDue: invoice.amount_due / 100,
currency: invoice.currency.toUpperCase(),
attemptCount: invoice.attempt_count,
nextAttempt: invoice.next_payment_attempt
? new Date(invoice.next_payment_attempt * 1000)
: null,
gatewayEventId: invoice.id
};
}
Register this translator in your webhook handler so your email dispatch code consumes PaymentFailureEvent objects, not gateway-specific JSON. Adding Braintree or Paddle requires a new translator function but zero changes to the email send logic, which reduces the migration test surface from your entire dunning flow to a single adapter.
Validating dunning flows with Stripe CLI
The Stripe CLI forwards test webhooks to your local endpoint, so you can validate the full flow without deploying to production.
Debug webhooks locally using Stripe CLI
Install the Stripe CLI and authenticate with your Stripe account. Start the listener with the stripe listen command:
stripe listen --forward-to localhost:4242/webhooks/stripe
The CLI prints a webhook signing secret. Set this as STRIPE_WEBHOOK_SECRET in your local environment, because it differs from your production secret.
Triggering payment failed webhooks
Trigger each of the four dunning events with the stripe trigger command:
stripe trigger invoice.payment_failed
stripe trigger invoice.payment_action_required
stripe trigger invoice.paid
stripe trigger customer.subscription.deleted
Each trigger creates a real test object in your Stripe account and fires the corresponding webhook. The CLI fixture for invoice.payment_failed creates and processes a test invoice, so your handler logs may show related events you didn't explicitly trigger, such as invoice.created and invoice.updated. In a live payment failure, Stripe sends invoice.updated alongside invoice.payment_failed, but invoice.created fires only when the invoice is first created. Check event.type in your logs to tell test-fixture events from production behavior.
Testing Stripe event delivery logic
After triggering an event, check your handler logs for the routing decision and the send.io API call. Verify the email was dispatched by checking the send.io webhook logs dashboard, which shows the message ID, event type, and timestamp for each delivery.
Query your database for the send record with the event ID to confirm idempotency. Trigger the same event again and verify the handler skips the send because the record already exists.
Test the failure path by temporarily breaking your send.io API key. The handler should log the error, push the event to the dead-letter queue, and return 200 to Stripe. Restore the key and manually retry the event from the queue.
Troubleshooting common webhook failures
Most webhook failures in this flow come from three places: the send.io API call, Stripe signature verification, and the handler itself. Each error below lists the symptom, the likely cause, and the fix. Start with the HTTP status code in your logs to find the right section.
401 unauthorized from send.io API
This error means your API key is missing, malformed, or not scoped for sending from your domain. Verify the Authorization header includes the Bearer prefix and check the key's scope. If the issue persists, rotate the credential: POST /mailboxes/{id}/password issues a new credential and immediately revokes the old one, so update SENDIO_API_KEY in your environment right after.
400 webhook signature verification failed
Stripe's constructEvent throws this error when the signature doesn't match the raw body. Confirm your webhook route uses express.raw() middleware and that STRIPE_WEBHOOK_SECRET matches the signing secret from the Stripe Dashboard. If you recently rotated the secret, update your environment variable.
500 internal server error in handler
A 500 response tells Stripe to retry the webhook, which compounds the problem if the underlying issue isn't transient. Log the full error, push the event to a dead-letter queue, and return 200 to Stripe. Fix the root cause (template error, missing database column, network timeout to send.io) before retrying events from the queue.
Payload mapping errors
If invoice.customer_email is undefined, the invoice was finalized without an email on the customer record. The field is a direct attribute of the invoice object and doesn't require expand: ['customer']. Add an email to the customer record, or read it from event.data.object.customer_email in the webhook payload and handle the null case. If amount_due renders as cents instead of dollars, divide by 100 before passing to the template.
Run the complete flow end to end in three steps: provision a scoped API key limited to sending from your domain, trigger invoice.payment_failed with the Stripe CLI, and verify the dunning email dispatch in the send.io webhook logs dashboard. The delivery event webhook fires with the message ID, recipient, and timestamp, which confirms the event-to-email mapping works before you deploy to production.
Choosing a provider for dunning sends and replies
Customers reply to dunning emails, so outbound sends and inbound replies often end up on two separate providers. Resend and Postmark both handle transactional dunning sends with similar API patterns, but each has a gap on the inbound side. Postmark has no agent inbox primitive for two-way email, and Resend's inbound implementation delivers metadata only.
send.io handles both directions under one credential: transactional sends with the same Idempotency-Key protection shown above, plus inbound routing and agent inboxes. You don't maintain separate providers for outbound dunning and inbound support replies. If you're migrating, send.io accepts Resend's request format as a drop-in: swap RESEND_BASE_URL and RESEND_API_KEY, and supported operations carry over without code changes, so you can keep existing dispatch code.
FAQs
How do you verify Stripe webhook signatures in production?
Use stripe.webhooks.constructEvent with the raw request body and your webhook signing secret. The express.raw() middleware is required on the webhook route, and it must run before express.json() in your middleware stack.
What happens if your webhook endpoint is down?
Stripe retries the webhook for up to 3 days with exponential backoff. Your handler must be idempotent because the same event ID can arrive multiple times, and each delivery attempt will trigger your email send logic unless you check for an existing send record first.
Should you send dunning emails for invoice.upcoming events?
No. The invoice.upcoming event is a notification that Stripe will attempt payment soon, not a payment failure. Use it for payment reminders, not dunning.
How do you prevent duplicate emails from webhook retries?
Use a database state check before send and a client-generated Idempotency-Key header on the send.io API call. send.io stores the key for 24 hours and returns the original result on retry instead of sending a duplicate.
Can you use the same handler for multiple payment gateways?
Yes. A translation layer that normalizes each gateway's events to a common schema lets you reuse the email dispatch code. You write a new translator function for each gateway, but the email logic stays unchanged.
Key terms glossary
Dunning email: A message sent to a customer after a subscription payment failure, requesting updated payment information or action to complete the charge and prevent service suspension.
Idempotency key: A client-generated unique identifier that prevents duplicate operations when a request is retried. send.io stores the key for 24 hours and returns the original result on retry.
Signature verification: The process of confirming a webhook request came from Stripe by validating the Stripe-Signature header against the raw request body using your webhook signing secret.
Dead-letter queue: A queue that stores events that failed processing, so they can be inspected and retried without blocking the main webhook flow or causing Stripe to retry the webhook.
Webhook payload: The JSON body of a webhook request, containing event data such as invoice ID, customer email, amount due, and attempt count.
Scoped API key: An API key with permissions limited to specific resources, such as sending from a single domain, so a compromised key can't access other account functions.