Payment received email template: confirming settlement without leaking PII
Payment received email template with four essential fields: amount, masked method, reference, and next steps without leaking PII. This article provides template code, webhook sanitization patterns, and a redaction checklist to prevent leaking cardholder data into email logs or inboxes.
On this page
L;DR: Build your payment confirmation email around four data points: amount settled, masked payment method, settlement reference, and next steps. Anything beyond those four adds risk. Treat every webhook field as untrusted input. Validate, escape, and redact before it touches a template variable. send.io's Idempotency-Key header prevents duplicate sends during webhook retries. Omitting it removes that deduplication protection.Your payment provider's webhook delivers customer data, and your email template interpolates it, so every extra field in the payload becomes a potential leak into the customer's inbox.
The risk in a payment confirmation email is not what you write, it is what you fail to exclude. This article covers the pipeline that strips PII before it reaches your template. A payment received email has one job: tell the customer the payment cleared. Any field beyond amount, masked method, reference, and next steps can become a liability if a template engine leaks it into an inbox, a log aggregator, or a support ticket.
Essential data points for payment emails
A payment received email template typically needs four fields. Each one serves a specific purpose for the customer. Fields beyond these four add risk with little added clarity.
Field | Why it is in the email | Handling rule |
|---|---|---|
Settled amount | Confirms the amount charged to the customer | An amount on its own is generally not treated as cardholder data |
Masked payment method | Identifies which card or account was used | Last four digits only, never the full PAN |
Internal settlement reference | Lets your support team locate the transaction | Internal IDs, not account numbers |
Fulfillment next steps | Tells the customer what happens with their order | Fulfillment details, not payment data |
Displaying payment totals and currency
The amount field answers the customer's first question. Format it with the correct currency symbol and decimal places. The Stripe payment_intent.succeeded webhook delivers the amount in the smallest currency unit (cents for USD, pence for GBP), so your template logic must divide by 100 before rendering. If you skip this step, a $49.99 charge displays as $4,999.00.
Masking payment methods for security
PCI DSS Requirement 3.4.1 mandates that you mask PANs when displayed, showing no more than the BIN (first six digits) and the last four digits. In practice, most payment emails show only the last four: "Visa ending in 4242."
This is the accepted convention. It gives the customer enough information to identify which card they used without exposing data that an attacker could use. Never include the full card number, expiration date, or CVV in any email body. PCI DSS Requirement 3.3.1 prohibits retaining CVV codes, track data, and PIN blocks after authorization, even in encrypted form. Including them in an email would conflict with that requirement.
Tracking settlements without PII
The settlement reference is your internal tracking ID for the transaction. It might be a Stripe payment_intent ID, a PayPal capture_id, or your own order number. This ID lets your support team look up the transaction without exposing any cardholder data.
Use a reference that means something to your system. An order number from your own system works. "Card 4242424242424242" does not. The reference should be sufficient for your support team to locate the transaction in your payment provider's dashboard, but it must pass through your authorization checks before anyone can use it to access transaction details.
Handling webhook payloads securely
Payment webhooks deliver more data than your template needs. A Stripe payment_intent.succeeded event includes the full PaymentIntent object with customer email, billing details, and payment method details. A PayPal PAYMENT.CAPTURE.COMPLETED webhook includes the resource object with amount breakdowns, seller receivable details, and payer information.
Your job is to extract the four fields you need and discard everything else before the data reaches your template engine. Treat the entire webhook payload as untrusted input.
Why unified inbound and outbound matter for payment flows
Resend's inbound webhook delivers metadata only, which means your payment reply parser can't read the message body without a separate layer. send.io's inbound routing is designed to send the message content to your webhook endpoint, so a customer reply to a payment confirmation can reach your support system with context intact. Confirm the exact inbound payload fields (body, headers, attachments) in the send.io API documentation before you build a parser against them. Postmark supports full inbound JSON webhooks. SendGrid delivers inbound messages as multipart/form-data. Neither offers an agent inbox primitive with scoped credentials. send.io combines inbound routing with agent inboxes, so an AI agent handling payment inquiries can use its own credentials instead of your primary account key.
Building compliant payment confirmation emails
Designing safe notification templates
A safe payment email template renders correctly with the minimum viable dataset. The raw HTML below renders a payment received email with only the four mandatory fields:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
@media (prefers-color-scheme: dark) {
body { background-color: #1a1a1a !important; }
.email-container { background-color: #2d2d2d !important; color: #e0e0e0 !important; }
.header { color: #ffffff !important; }
.detail-row { border-bottom: 1px solid #444 !important; }
}
</style>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
<div class="email-container" style="max-width: 600px; margin: 0 auto; padding: 40px 20px; background-color: #ffffff;">
<h1 class="header" style="color: #1a1a1a; font-size: 24px; margin-bottom: 30px;">Payment received</h1>
<p style="color: #4a4a4a; font-size: 16px; line-height: 1.6; margin-bottom: 30px;">
Your payment was received. Here are the details:
</p>
<div style="background-color: #f8f8f8; padding: 20px; border-radius: 8px; margin-bottom: 30px;">
<div class="detail-row" style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #e0e0e0;">
<span style="color: #666; font-size: 14px;">Amount</span>
<span class="amount" style="color: #1a1a1a; font-size: 18px; font-weight: 600;">{{amount}} {{currency}}</span>
</div>
<div class="detail-row" style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #e0e0e0;">
<span style="color: #666; font-size: 14px;">Payment method</span>
<span style="color: #1a1a1a; font-size: 14px;">{{payment_method}}</span>
</div>
<div class="detail-row" style="display: flex; justify-content: space-between; padding: 12px 0;">
<span style="color: #666; font-size: 14px;">Reference</span>
<span style="color: #1a1a1a; font-size: 14px;">{{reference}}</span>
</div>
</div>
<p style="color: #4a4a4a; font-size: 16px; line-height: 1.6; margin-bottom: 20px;">
{{next_steps}}
</p>
<p style="color: #999; font-size: 14px; line-height: 1.6; margin-top: 40px;">
If you have questions about this payment, reply to this email with reference {{reference}}.
</p>
</div>
</body>
</html>
This template includes dark mode support via the prefers-color-scheme media query, uses inline styles for maximum email client compatibility, and interpolates five variables: amount, currency, payment_method, reference, and next_steps. The four data points render across five template variables because amount and currency are separate.
Template code for payment receipts
If you're using React Email, the same template structure applies. Import Container, Heading, Text, Section, Row, and Column from @react-email/components and pass the same five props: amount, currency, paymentMethod, reference, and next_steps. The dark mode media query and inline styles remain identical.
Preventing PII leaks in template logic
The template itself exposes only the fields it renders. What you pass to it creates the risk. Your template engine will happily interpolate whatever you give it, including full card numbers, CVVs, and billing addresses if you're not careful.
Never pass the raw webhook payload to your template. Extract the fields you need, sanitize them, and pass only those fields to the template. If your template expects payment_method and you pass the entire payment_method_details object from a Stripe webhook, you still leak data the email doesn't need. Stripe's API exposes card details as masked values like brand and last4 rather than the full card number, but the object also carries card metadata and billing details that have no place in a customer-facing email. Check the Stripe PaymentIntent object reference for the exact fields your integration receives.
Stripping PII from settlement emails
Payment webhooks include fields you should never render in an email. Here's how to strip them before they reach your template.
Strip full PANs from email payloads
Never interpolate full card numbers from webhook payloads. Extract only payment_method_details.card.last4 and payment_method_details.card.brand, then format them as "Visa ending in 4242."
If you're logging webhook payloads for debugging, redact any card number fields before the log write. Your log aggregator typically doesn't qualify as a secure cardholder data environment.
Exclude CVV and card expiry fields
PCI DSS Requirement 3.3.1 prohibits retaining CVV codes after authorization. Your payment provider should never send you a CVV in a webhook payload, but if you're storing raw payloads for audit purposes, verify that no CVV field exists before you write to disk.
Card expiry dates carry less sensitivity than CVVs, but you don't need them in a payment confirmation email. The customer knows which card they used. The last four digits are sufficient for identification.
Strip account numbers from payloads
Bank account payments (ACH, SEPA, wire transfers) include account numbers in webhook payloads. The Adyen AUTHORISATION webhook includes bank account details for some payment methods. Mask these the same way you mask card numbers: last four digits only.
For bank transfers, the settlement reference becomes more important because the customer may need it to reconcile the payment in their own accounting system. Include it prominently.
Mask internal payment gateway IDs
Your payment provider's internal IDs (Stripe payment_intent IDs, PayPal capture_ids, Adyen pspReferences) are generally not PII, but they're not customer-friendly either. Use your own order ID as the primary reference in the email. Include the provider's ID in a footer or support section if your team needs it for troubleshooting.
The PayPal PAYMENT.CAPTURE.COMPLETED webhook includes both resource.id (the capture ID) and resource.supplementary_data.related_ids.order_id (your order ID if you set it). Use your order ID in the email body and reserve the capture ID for internal logs.
Remove PII from billing address fields
Billing addresses are PII. Stripe payment webhooks include billing address fields with line1, line2, city, state, postal_code, and country. Don't interpolate these into your payment confirmation email.
If you need to include an address for tax or regulatory reasons (some jurisdictions require it on invoices), send a link to a secure invoice PDF instead of rendering the address in the email body. The PDF can live behind authentication, the email cannot.
Sanitizing webhook data to prevent PII leakage
Validation and sanitization happen between the webhook endpoint and the template renderer. This is where you enforce the boundary between untrusted input and safe output.
Sanitizing webhook inputs for security
Validate every field you plan to use before you use it. Check that amount is a positive integer, that currency matches an ISO 4217 code, that last4 is exactly four digits, and that reference matches your expected format.
If a field fails validation, don't render the email. Log the failure, alert your team, and queue the event for manual review. A malformed webhook payload might indicate a bug in your payment provider's system, or it might indicate an attack.
Escaping input to prevent XSS attacks
OWASP's XSS Prevention Cheat Sheet Rule #1 is to HTML-encode before inserting untrusted data into HTML element content. In email, the risk is layout and markup injection rather than script execution, because email clients strip script tags and don’t run JavaScript. A customer’s name <script>alert('xss')</script>containing HTML tags can break the layout or inject visible markup if you interpolate it without escaping.
Escaping behavior varies across template engines, so verify it before you rely on it. Handlebars escapes HTML by default when you use the double-brace {{expression}} syntax. Jinja2 does not escape variables by default, as the Jinja HTML escaping documentation explains, so you need to enable autoescaping or apply the escape filter explicitly. React escapes interpolated values by default, but React Email compiles templates to static HTML, so confirm what your rendering step actually does. Concatenating HTML strings manually is error-prone, so avoid it.
Sanitizing customer names in templates
Customer names are untrusted input. They come from your payment provider's webhook, which got them from the customer at checkout, which means they can contain anything the customer typed.
Escape HTML entities, trim whitespace, and enforce a maximum length. A name field is not a place for emoji, HTML tags, or 500-character strings. If the name fails validation, fall back to a generic greeting: "Hello" instead of "Hello {{name}}."
Normalizing webhook currency formats
Different payment providers format amounts differently. Stripe uses the smallest currency unit (cents). PayPal uses decimal strings. Adyen uses minor units (also cents for most currencies). Your template should receive a consistent format.
Normalize to a decimal number with two places and a currency code. "49.99 USD" is unambiguous and most email clients render it consistently. If you're supporting multiple currencies, verify that your normalization logic handles zero-decimal currencies (JPY, KRW) correctly.
Pattern: triggering payment receipts from webhooks
The webhook handler is where sanitization, validation, and email triggering come together. The Node.js and Python examples below implement that pattern.
Preventing PII leaks in Node.js code
const express = require('express');
const app = express();
app.use(express.raw({ type: 'application/json' }));
function sanitizePaymentData(webhookPayload) {
const paymentIntent = webhookPayload.data.object;
if (!paymentIntent.amount || !paymentIntent.currency) {
throw new Error('Missing required payment fields');
}
return {
amount: (paymentIntent.amount / 100).toFixed(2),
currency: paymentIntent.currency.toUpperCase(),
paymentMethod: paymentIntent.payment_method_details?.card
? `${paymentIntent.payment_method_details.card.brand} ending in ${paymentIntent.payment_method_details.card.last4}`
: 'Payment method',
reference: paymentIntent.metadata?.order_id || paymentIntent.id,
nextSteps: 'Your order is being processed.' // Example copy. Set your own fulfillment message.
};
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
app.post('/webhooks/payment', async (req, res) => {
try {
const payload = JSON.parse(req.body.toString());
if (payload.type === 'payment_intent.succeeded') {
const sanitized = sanitizePaymentData(payload);
Object.keys(sanitized).forEach(key => {
if (typeof sanitized[key] === 'string') {
sanitized[key] = escapeHtml(sanitized[key]);
}
});
// send.io email endpoint: POST /emails on the api.send.io base URL.
// Confirm the exact path in https://developer.send.io/docs/api
// Store the API endpoint in your environment, not in source.
const response = await fetch(process.env.SENDIO_API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SENDIO_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': `payment-${sanitized.reference}`
},
body: JSON.stringify({
from: 'payments@yourdomain.com',
to: payload.data.object.receipt_email,
subject: 'Payment received',
html: renderPaymentTemplate(sanitized)
})
});
if (!response.ok) {
throw new Error(`send.io API error: ${response.status}`);
}
}
res.status(200).send('OK');
} catch (error) {
console.error('Webhook processing error:', error);
res.status(500).send('Internal error');
}
});
This handler validates the payload, sanitizes it, escapes HTML, and sends the email with an idempotency key to prevent duplicates during webhook retries.
Escaping PII in Python workflows
from fastapi import FastAPI, Request, HTTPException
import os
import httpx
from html import escape
app = FastAPI()
def sanitize_payment_data(webhook_payload: dict) -> dict:
payment = webhook_payload.get('data', {}).get('object', {})
amount = payment.get('amount')
currency = payment.get('currency')
if not amount or not currency:
raise ValueError('Missing required payment fields')
card_details = payment.get('payment_method_details', {}).get('card', {})
payment_method = (
f"{card_details.get('brand', 'Card')} ending in {card_details.get('last4', '****')}"
if card_details
else 'Payment method'
)
return {
'amount': f"{amount / 100:.2f}",
'currency': currency.upper(),
'payment_method': payment_method,
'reference': payment.get('metadata', {}).get('order_id') or payment.get('id'),
'next_steps': 'Your order is being processed.' # Example copy. Set your own fulfillment message.
}
@app.post('/webhooks/payment')
async def handle_payment_webhook(request: Request):
try:
payload = await request.json()
if payload.get('type') == 'payment_intent.succeeded':
sanitized = sanitize_payment_data(payload)
sanitized = {k: escape(str(v)) for k, v in sanitized.items()}
async with httpx.AsyncClient() as client:
# Store the API endpoint in your environment, not in source.
response = await client.post(
os.getenv('SENDIO_API_URL'),
headers={
'Authorization': f"Bearer {os.getenv('SENDIO_API_KEY')}",
'Content-Type': 'application/json',
'Idempotency-Key': f"payment-{sanitized['reference']}"
},
json={
'from': 'payments@yourdomain.com',
'to': payload['data']['object'].get('receipt_email'),
'subject': 'Payment received',
'html': render_payment_template(sanitized)
}
)
if response.status_code != 200:
raise HTTPException(status_code=500, detail='Email send failed')
return {'status': 'ok'}
except Exception as e:
print(f'Webhook processing error: {e}')
raise HTTPException(status_code=500, detail='Internal error')
The Python handler escapes every sanitized value with the standard library's html.escape, which converts &, <, >, and quotes to HTML entities. It then sends the email with the same Idempotency-Key pattern as the Node.js handler.
Validating payloads for PII leaks
Before you deploy a payment email flow, test it with a payload that contains PII in unexpected places. Send a test webhook with a customer name that includes HTML tags, a card number in a metadata field, and a CVV in a custom field. Verify that none of these values appear in the rendered email.
If you're using send.io, you can test template rendering in the sandbox before connecting a live webhook. The template versioning and preview features let you render templates with test data and preview the output without sending.
Managing unexpected webhook delivery errors
Webhooks fail. Networks time out. Payment providers retry. Your email pipeline needs to handle these failures without sending duplicate payment confirmations.
Managing partial payment edge cases
Some payment methods such as installments or subscriptions with proration produce partial captures. The PayPal PAYMENT.CAPTURE.COMPLETED webhook includes resource.seller_receivable_breakdown with gross_amount, paypal_fee, and net_amount. If you're capturing a partial amount, make sure your email shows the captured amount, not the authorized amount.
For multi-capture scenarios, decide whether to send one email per capture or one summary email after all captures complete.
Handling missing or null webhook data
Webhooks sometimes arrive with missing fields. If a required field like receipt_email is missing, don't send the email. Log the event, alert your team, and queue it for manual review. If an optional field is missing, use a sensible default.
Formatting non-base currency settlements
If you're accepting payments in multiple currencies, your settlement currency might differ from the charge currency. Provider webhooks don't expose currency conversion the same way. Check your payment provider's webhook documentation, such as the Adyen webhook types reference, to confirm whether the payload includes separate charge and settlement amounts, because field names and availability vary by provider and may not be included in the standard amount object.
Show the customer the charge amount in the charge currency. Show your internal team the settlement amount in your reporting. Don't mix the two in a customer-facing email.
Ensuring idempotency for email retries
Payment providers retry failed webhooks. Stripe retries for up to three days. If your webhook handler processes the same event twice, you may send two payment confirmation emails.
The send.io API supports idempotency via the Idempotency-Key header. Set this header to a unique value derived from the payment event (like payment-{payment_intent_id}), and send.io will return the original result for any retry with the same key within 24 hours instead of sending a duplicate email.
This is the difference between a payment email that sends once and one that may send three times during a retry storm. Set the idempotency key whenever you trigger transactional emails from webhooks. If you omit the Idempotency-Key header, send.io does not derive one from the request content, so the send has no deduplication protection.
Test the template rendering with sample webhook payloads and verify that your sanitization logic strips PII correctly in the send.io template rendering endpoint. You can simulate webhook retries to confirm that idempotency keys prevent duplicate sends before deploying to production.
FAQs
Should a payment confirmation email include a receipt PDF?
Generally no. Send a link to a hosted invoice PDF instead. The PDF includes full billing details and tax information behind authentication, while the email body stays minimal and PII-free.
How should a card number be masked safely?
Show only the last four digits: "Visa ending in 4242." PCI DSS Requirement 3.4.1 allows the BIN (first six) and last four, but last-four-only is the safer convention.
Can payment details be sent via a secure link instead?
Yes. A secure link to a customer portal reduces PII risk but adds friction. Use this approach for high-value transactions or when regulatory requirements demand detailed invoice data.
What happens if a webhook payload contains malicious input?
Validate and escape every field before templating. OWASP Rule #1 is to HTML-encode untrusted data before inserting it into HTML. Escaping defaults vary by engine: Handlebars escapes {{expression}} output by default, while Jinja2 requires autoescaping or an explicit escape filter. React Email compiles to static HTML, so verify what your rendering step does.
How long should payment confirmation email logs be retained?
Retain logs long enough to troubleshoot delivery issues and reconcile disputes. Set the retention window based on your dispute and chargeback timelines, your legal requirements, and your internal policy, and document the period you choose. Redact PII from logs before writing them. A log aggregator is not a PCI-compliant cardholder data environment.
Key terms glossary
PAN (Primary Account Number): The full card number, typically 8 to 19 digits per ISO/IEC 7812. PCI DSS requires masking PANs when displayed, showing no more than the first six and last four digits.
CVV (Card Verification Value): The three- or four-digit security code on a payment card. PCI DSS prohibits retaining CVVs after authorization, even in encrypted form.
Settlement reference: Your internal tracking ID for a payment transaction. This might be an order ID, a payment intent ID, or a capture ID, depending on your payment provider.
Dead-letter queue: A holding queue for webhook events that fail processing after multiple retries. Events in the dead-letter queue require manual review before reprocessing or discarding.
Idempotency key: A unique identifier for an API request that prevents duplicate operations during retries. send.io stores idempotency keys for 24 hours and returns the original result for retries with the same key.