Skip to content
send.io
All posts

Order receipt email template: triggering a send from order.paid

Order receipt email template: Send receipts when order.paid fires using idempotency keys to prevent duplicates on retry. This guide shows you how to derive stable keys from order ID, verify webhook signatures, and handle redelivered events so no customer ever receives duplicate receipts.

On this page
TL;DR: send an order receipt when order.paid fires by deriving an idempotency key from order_id plus event type, verifying the webhook signature, and calling POST /emails with an Idempotency-Key header. send.io stores client-generated keys for 24 hours and returns the original result on retry, so redelivered events within that window never produce duplicate receipts. That window is send.io's own, and retention varies by provider, so don't rely on the key alone if a redelivery could arrive after 24 hours. Below: payload mapping from your payment provider's schema, a Node.js webhook handler with signature verification, curl examples for testing, and regression strategies for schema changes.

Payment providers redeliver order.paid on timeout, network failure, or manual retry. Without an idempotency key, each redelivery sends another receipt, so derive one from the order ID and event type to prevent duplicates.

The order.paid webhook is a promise that an order exists, not a guarantee that the event is new. Webhook providers redeliver events when your endpoint doesn't respond fast enough or when network issues prevent the acknowledgment from reaching the provider. This guide walks through the full implementation: mapping the payload to template variables, deriving an idempotency key from the order record, verifying the webhook signature, and testing the flow to confirm the idempotency key prevents duplicate sends on redelivery.

How order.paid maps to an order receipt email template

Your handler reads fields from the order.paid payload, maps each one to a template variable, and renders the receipt from those values. The event fires when payment completes for an order, and the payload carries the order ID, customer email, line items, total, currency, and timestamp your order receipt template needs. The mapping succeeds only if the field names match your provider's schema and you validate types before rendering.

Payload structure for order.paid

The exact structure depends on your payment provider, so treat the field names and template mapping below as an illustrative example, not a guaranteed schema. This guide uses a generic order event schema as the canonical example. A payment event payload typically carries type (what happened) and data.object (the resource it happened to). For an order payment, the data.object generally includes order ID, customer email, line items, amount, and currency.

Here's a typical order.paid payload mapped to template variables:

Example payload field

Suggested template variable

Illustrative value

data.object.id (your provider's order identifier, and the field name varies by provider)

{{order_id}} (a variable name you define in your own template)

ord_12345 (placeholder)

data.object.customer_email (your provider's customer email field, and the name varies by provider)

{{customer_email}} (a variable name you define in your own template)

customer@example.com (placeholder)

data.object.line_items (your provider's array of purchased items, and the field name and item shape vary by provider)

{{line_items}} (a variable name you define in your own template)

[{name: "Widget", qty: 2, price: 1500}] (placeholder)

data.object.amount_total (your provider's order total field, and the name and currency unit vary by provider)

{{total}} (a variable name you define in your own template)

3000 (placeholder)

data.object.currency (your provider's currency code field, and the name and code format vary by provider)

{{currency}} (a variable name you define in your own template)

usd (placeholder)

data.object.paid_at (your provider's payment timestamp field, and the name and time format vary by provider)

{{paid_at}} (a variable name you define in your own template)

1699564800 (placeholder Unix timestamp)

Extract these fields in your webhook handler and pass them to your template rendering layer. The template renders the receipt HTML with the order details, then your handler sends the rendered email via POST /emails.

Handling retries for order receipts

Webhook providers redeliver events when your endpoint doesn't respond within the timeout window, returns an error status, or times out. Most providers give your endpoint 5 to 30 seconds to respond before they treat the delivery as failed and retry it.

Treat every delivery as a potential redelivery: the event ID stays the same across redeliveries, so evt_12345 delivered three times is the same event three times. Without deduplication, you send three receipts.

The retry window varies by provider, but the pattern is consistent: exponential backoff with a maximum retry count. If your endpoint is down for maintenance when order.paid fires, the event arrives when your server comes back up. Your idempotency key stops the delayed delivery from duplicating a receipt you already sent.

Schema constraints for receipt data

Payment providers evolve their event schemas. A field you depend on today (data.object.line_items) might move, rename, or change type in a future API version. When that happens, your template rendering breaks silently: the receipt sends with missing or malformed data.

Validate the payload schema before you render. Check that required fields exist, have the expected types, and contain values your template can render. If validation fails, log the raw payload and return a 4xx so the provider retries after you fix the schema mapping.

Ensuring exactly-once delivery with idempotency keys

An idempotency key is a unique, client-generated value (like a UUID) sent with a request to an API endpoint. The server stores the key and returns the original result if it sees the same key again, instead of executing the operation twice. Retention windows vary by provider, so 24 hours is common but not universal. The provider comparison is under "How send.io handles event deduplication."

Causes of redundant webhook delivery

Three scenarios produce duplicate order.paid deliveries:

  1. Timeout on your endpoint: your handler takes longer than the provider's timeout window (typically 5-30 seconds), the provider marks the delivery as failed and retries.
  2. Network failure between provider and your load balancer: the provider sent the event and your handler processed it, but the response never made it back, so the provider retries.
  3. Manual retry from the provider dashboard: an engineer investigating a failed delivery clicks Resend in the provider UI and the event fires again with the same event ID.

All three produce the same result: your handler runs again with identical event data. Without idempotency, you send a duplicate receipt.

Generating idempotency keys from order.paid

Derive the key from stable, immutable fields in the event payload. send.io doesn't prescribe a key format, so the pattern below is one example, not a documented recommendation: receipt_{order_id}_{event_type}. Any format works if it stays identical across redeliveries of the same event and differs between distinct events.

Order ID

Event type

Example idempotency key

ord_12345 (placeholder)

order.paid

receipt_ord_12345_order.paid (built with the example pattern, and send.io doesn't derive or require this key)

ord_67890 (placeholder)

order.paid

receipt_ord_67890_order.paid (built with the example pattern, and send.io doesn't derive or require this key)

This pattern survives redelivery because the order ID and event type never change across retries of the same event. A hash of the full payload also works, but breaks when the provider adds a field (the hash changes, so the key changes, so deduplication fails). Order ID plus event type is more stable.

How send.io handles event deduplication

send.io stores client-generated idempotency keys for 24 hours and returns the original result on retry with the same key. The caller sets the Idempotency-Key header on POST /emails, and send.io does not derive a key from request content.

A request without the header has no deduplication protection, whether the caller is a server or an agent: send the same request twice without a key and send.io sends two emails.

send.io's 24-hour window matches Stripe's documented window, but retention is not standardized across providers: Adyen retains keys for 7 to 14 days, and PayPal's retention varies by API. If a redelivery could arrive after 24 hours, don't rely on the key alone to prevent a duplicate receipt.

Node.js handler for order receipt emails

Here's a complete Express.js webhook handler that verifies the signature, extracts the payload, derives an idempotency key, and sends the receipt via send.io.

Node.js handler for order.paid events

const express = require('express');
const crypto = require('crypto');

const app = express();

// Raw body parser for webhook verification
app.post('/webhooks/order-paid', express.raw({ type: 'application/json' }), async (req, res) => {
const signature = req.headers['x-webhook-signature'];
const secret = process.env.WEBHOOK_SECRET;

// Verify webhook signature
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(req.body)
.digest('hex');

if (signature !== expectedSignature) {
return res.status(401).json({ error: 'Invalid signature' });
}

const event = JSON.parse(req.body);

if (event.type !== 'order.paid') {
return res.status(200).json({ received: true });
}

const order = event.data.object;

// Validate required fields
if (!order.id || !order.customer_email || !order.line_items || !order.amount_total) {
console.error('Missing required fields:', order);
return res.status(400).json({ error: 'Invalid payload' });
}

// Derive idempotency key from order ID and event type
const idempotencyKey = `receipt_${order.id}_${event.type}`;

// Map payload to template variables
const templateData = {
order_id: order.id,
customer_email: order.customer_email,
line_items: order.line_items,
total: order.amount_total,
currency: order.currency,
paid_at: new Date(order.paid_at * 1000).toISOString()
};

// Render template (assuming a renderReceiptTemplate function exists)
const html = renderReceiptTemplate(templateData);

// Send via send.io
const response = await fetch('https://api.sendio.run/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SENDIO_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey
},
body: JSON.stringify({
// Placeholder sender in the "Name <address>" format; replace with your own address
from: 'Receipts <receipts@yourdomain.com>',
to: order.customer_email,
subject: `Receipt for order ${order.id}`,
html: html
})
});

if (!response.ok) {
console.error('send.io error:', await response.text());
return res.status(500).json({ error: 'Failed to send receipt' });
}

const result = await response.json();
console.log('Receipt sent:', result.id);

res.status(200).json({ received: true });
});

app.listen(3000);

send.io publishes framework-specific webhook verification guides for Express, Next.js, FastAPI, and other platforms. Each guide covers install, configuration, sending, receiving, and webhook verification against the raw request body.

Strategies for failure recovery

If the send.io API call fails (5xx response or network error), your handler returns 500 to the webhook provider. The provider retries the event, your handler runs again, and the idempotency key prevents a duplicate send if the first attempt succeeded but the response was lost.

For permanent failures (4xx from send.io, or a schema validation error), log the event to a dead-letter queue. AWS SQS supports dead-letter queues for messages that fail processing after a configured number of retries.

A DLQ pattern for failed receipt sends:

  1. Webhook handler attempts to send receipt and fails with a 4xx or schema validation error.
  2. Handler logs the event payload, idempotency key, and error response to a DLQ, then returns 200 to the webhook provider.
  3. A separate worker polls the DLQ, alerts on-call, and replays events after the schema or configuration issue is resolved.

Preventing duplicate email sends

The idempotency key is your only defense against duplicate sends. A database check ("has the system already sent a receipt for this order?") introduces a race condition: two redelivered events arrive simultaneously, both check the database, both find no record, both send.

Idempotency keys push deduplication to the email API, which stores the key atomically and returns the original result on retry. No race condition, no duplicate send.

Triggering receipts via curl: a practical guide

Test the receipt flow with curl before wiring the webhook. This verifies your template rendering, plus how POST /emails responds to repeated idempotency keys and to invalid requests, without a payment provider in the loop. It doesn't exercise webhook signature verification, which you test separately against your handler.

Handling retries without duplicates

Send the same request twice with the same idempotency key. The first returns a message ID. The second returns the same message ID, not a new send.

curl -X POST https://api.sendio.run/emails \
-H "Authorization: Bearer $SENDIO_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: receipt_ord_12345_order.paid" \
-d '{
"from": "Ada <ada@acme.com>",
"to": "customer@example.com",
"subject": "Receipt for order ord_12345",
"html": "<h1>Receipt</h1><p>Order ord_12345 paid $30.00</p>"
}'

Response (first request):

{
"id": "<message_id>",
"status": "queued"
}

The response shape above is illustrative. The status field and its queued value aren't confirmed in the send.io documentation, and the actual id value is generated when the email is queued. Check the API reference for the exact response fields.

Run the same curl command again. The response is identical: same id, no new send.

Expected API response outcomes

Status

Meaning

Handler behavior

200 with id

Email queued successfully

Log the message ID, return 200 to webhook provider

Success response with same id on retry

Idempotent replay, no duplicate send

Log the replay, return 200 to webhook provider

4xx with error message

Validation error (bad email, missing field)

Log the error, return 4xx so provider retries after fix

5xx with error message

send.io server error

Return 5xx so provider retries, and the idempotency key prevents a duplicate if the first attempt succeeded

Note: the API documentation says an idempotent replay returns the original result but doesn't specify the HTTP status code for a replay. Confirm it with the curl test above.

Design patterns for resilient email triggers

Receipt flows break when the event schema changes or the payload structure drifts from your template expectations. Derive idempotency keys and template variables from fields that stay immutable across the event lifecycle, such as order ID and event type.

Schema evolution and field stability

Order ID, event type, and paid timestamp are immutable. Line items, totals, and customer details can change if the order is updated (partial refund, address correction), so don't include them in the idempotency key.

If you need to send an updated receipt after an order change, use a different event type (order.updated) so the idempotency key differs and the send isn't deduplicated against the original receipt.

The order.paid event and its schema come from your payment provider, not send.io, so this guide's example schema is illustrative. The example receipt template reads id, customer_email, line_items (array), amount_total (number), currency, and paid_at. Confirm the equivalent field names and types against your provider's current event documentation before relying on them, and run the schema validation described under "Schema constraints for receipt data" whenever you update the field mapping.

Handling payload changes in event streams

Your webhook endpoint receives more than order.paid. It also gets order.refunded, order.canceled, and customer.updated. Filter by event type before processing:

if (event.type !== 'order.paid') {
return res.status(200).json({ received: true });
}

Return 200 for events you don't handle so the provider doesn't retry them. A 404 or 500 on an unhandled event type causes the provider to mark the delivery as failed and retry, cluttering your logs with noise.

For multiple event types, route each to a dedicated handler function that derives its own idempotency key, so order.paid and order.refunded for the same order ID produce different keys.

Testing your order receipt flow safely

Test the full flow in a sandbox environment before pointing a live webhook at your handler. Confirm that idempotency keys, signature verification, and error handling behave as expected there before you rely on them in production.

Verifying order.paid trigger logic

Trigger a test order.paid event from your payment provider's dashboard or CLI. Verify that your handler receives the event, validates the schema, derives the correct idempotency key, and calls POST /emails with the expected payload.

Check the send.io dashboard for the sent message. The message ID should match the response your handler logged. If the message doesn't appear, check your handler logs for a 4xx or 5xx from the send.io API.

Most payment providers offer CLI tools for triggering test webhook events locally. For example, the Stripe CLI supports stripe trigger checkout.session.completed to send a test event to a local endpoint, so run the equivalent command for your provider's order event, then verify that your handler processes it correctly.

Testing for duplicate email sends

Redeliver the same event from your payment provider's dashboard. Your handler should return 200, but send.io should not send a second receipt. The response from POST /emails will have the same message ID as the first send.

If a second receipt sends, your idempotency key derivation is wrong. Check that the key is stable across redeliveries: log the key on each handler run and confirm it's identical.

Run the same curl command from the "Handling retries without duplicates" section twice with the same idempotency key. Log both message IDs. If they differ, your key derivation is unstable. If they match, idempotency is working correctly.

Regression testing after schema changes

When your payment provider announces an API version upgrade, replay historical order.paid events against your staging environment. Verify that your schema validation catches any field renames or type changes, and that the template renders correctly with the new schema.

If a field moved, update your field mapping and redeploy before the provider's deprecation deadline. Test the updated handler with a redelivered event to confirm the idempotency key still derives correctly from the new payload structure.

Provision a send.io API key, test the idempotent receipt flow in the sandbox using the Node.js handler above, and verify that redelivered events return the original message ID without sending duplicate receipts.

FAQs

What happens if order.paid fires twice with the same idempotency key?

send.io returns the original result with the same message ID and does not send a duplicate receipt. The second request is a replay, not a new send.

How long does send.io store idempotency keys?

send.io stores idempotency keys for 24 hours. After 24 hours, the key expires and a retry with the same key sends a new email.

Can you send a receipt without an idempotency key?

Yes, but the send has no deduplication protection. If the webhook redelivers and you send without a key, send.io sends a duplicate receipt.

How do you handle partial refunds or order updates?

Use a different event type (order.refunded or order.updated) so the idempotency key differs from the original receipt. The new event triggers a new send with updated order details.

What fields should be logged when a receipt send fails?

Log the idempotency key, order ID, customer email, send.io error response, and the raw event payload. The idempotency key lets you correlate the failure across retries, and the raw payload helps debug schema issues.

Key terms glossary

Idempotency key: A unique, client-generated value sent with an API request to prevent duplicate operations. The server stores the key and returns the original result on retry with the same key.

Event redelivery: A webhook provider sends the same event multiple times when your endpoint doesn't respond successfully. The event ID stays the same across redeliveries.