# Dunning Email for Each Failed Stripe Payment

A B2B software company's billing team gets a dunning email drafted for each failed Stripe payment, from the invoice, the decline code and the customer's history.

[Run this on Rush](https://cloud.getrush.ai/run/draft-a-dunning-email-for-each-failed-payment/stripe/). Opens the console with this prompt ready to send. Connect Stripe there first.

## What the agent does

This is for a B2B software company that bills a few hundred customers each month through Stripe Billing, where a failed card on a 40-seat account is a phone call to someone's finance team, not a form email. Stripe's own retries and reminder emails cover the common case. What they cannot do is write the note a billing lead writes by hand: to a customer of four years whose card expired, a different note than to one in their second month whose bank declined for no stated reason. Each time a payment fails, the company's billing service starts one run that reads the invoice, the decline and the account, and drafts that note.

The billing lead connects Stripe once with `POST /me/connections {"type": "mcp", "name": "stripe", "url": "https://mcp.stripe.com/", "auth": {"mode": "bearer", "token": "<Stripe agent API key>"}}`. Stripe's MCP docs offer two sign-ins: OAuth, whose refresh tokens end 14 days after the first authorization, and an agent API key, which Stripe recommends for an agent that runs on its own and which carries only the permissions it is given. A job that fires at any hour suits the key, created in the Stripe Dashboard with read permissions only, so Stripe itself refuses any write. Every run names `"connections": ["stripe"]`, and the agent calls Stripe's API through the server's `stripe_api_read` tool, which runs any `GET` method.

The run's input carries the invoice id from Stripe's `invoice.payment_failed` event. The agent reads `GET /v1/invoices/{id}`: `customer_name`, `customer_email`, `amount_due`, `amount_remaining`, `currency`, `attempt_count`, `next_payment_attempt`, `billing_reason`, `collection_method`, `number` and `hosted_invoice_url`, the page where the customer can pay with another card. It lists `GET /v1/invoice_payments` for that invoice to find the payment intent, and reads `GET /v1/payment_intents/{id}` for `last_payment_error`: its `decline_code`, `code` and `advice_code`. Then it lists the customer's paid invoices with `GET /v1/invoices` filtered to that customer and `status` `paid`, to know how long they have paid and whether a card has failed before.

The draft follows Stripe's decline-code table. `expired_card` asks for a new card. `insufficient_funds` and `card_velocity_exceeded` ask for another payment method, without suggesting the customer is short of money. `authentication_required` asks the customer to pay on the hosted invoice page, where their bank can verify them. For `fraudulent`, `lost_card`, `stolen_card` and `merchant_blacklist`, Stripe says to present the decline as a generic one, so the draft says only that the card was declined. A `billing_reason` of `subscription_create` reads as a first payment, and the tone is a check-in rather than a reminder. The draft gives the amount, the invoice number, the next automatic retry when there is one, and the link, and states no consequence the company has not written into the prompt.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Draft a dunning email for Stripe invoice in_1QxR7mHk2Lw9Pa3T, whose payment just failed. Read only: use stripe_api_read and never stripe_api_write. 1) GET /v1/invoices/in_1QxR7mHk2Lw9Pa3T: customer, customer_name, customer_email, amount_due, amount_remaining, currency, attempt_count, next_payment_attempt, billing_reason, collection_method, number, hosted_invoice_url. 2) GET /v1/invoice_payments with invoice in_1QxR7mHk2Lw9Pa3T; for its payment_intent, GET /v1/payment_intents/{id} and read last_payment_error.decline_code, code and advice_code. 3) GET /v1/invoices with customer set to that customer and status paid, limit 100: count paid invoices, the first one's date, and any earlier invoice whose attempt_count is above 1. 4) Write the email from Dana Okafor, Billing, Fieldline Software. By decline_code: expired_card asks for a new card; insufficient_funds or card_velocity_exceeded asks for another payment method and says nothing about funds; authentication_required asks them to pay on the invoice link so their bank can confirm it; fraudulent, lost_card, stolen_card, merchant_blacklist and any unknown code say only that the card was declined. Give the amount, the invoice number, the next automatic retry date if next_payment_attempt is set, and hosted_invoice_url. Thank a customer of more than 12 months for their time with us; for billing_reason subscription_create, write a short check-in instead of a reminder. Under 140 words, no threats, no late fees, no account suspension. Return JSON {invoice, customer_email, decline_code, attempt_count, next_retry, months_as_customer, earlier_failures, subject, body, notes_for_billing}.",
  "connections": [
    "stripe"
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A drafted dunning email comes back for the billing team: its subject, its body and the address to send it to. Beside it are the facts it rests on, from the decline code and attempt count to the next retry date, how many months the customer has paid and whether a card of theirs has failed before. `notes_for_billing` holds what a person should know before sending, such as a decline Stripe says not to describe or an account whose earlier invoices also needed retries.

A person sends it. The billing service posts the draft to the team's queue, where the billing lead reads it, edits it if they know more (a renewal under negotiation, a champion who left), and sends it from their own mailbox. The agent sends no email, and with a read-only key it cannot retry the charge, change the subscription or mark the invoice uncollectible.

When the invoice was paid between the failure and the run, `amount_remaining` reads zero and the answer says so instead of drafting, so a late run never asks a customer who has already paid.

## Run it on every failed Stripe invoice payment

Stripe signs its webhooks with its own `Stripe-Signature` header and cannot send the `Authorization: Bearer` a Rush webhook trigger needs, so the company's billing service receives `invoice.payment_failed`, verifies the signature, and calls `POST /o/{org}/sessions` with the invoice id in `input` and a `request_id` that is a UUID v5 of the Stripe event id. Stripe can deliver one event more than once, and the same event id then starts no second run.

Each failure is its own run, so a month-end batch of declines drafts in parallel up to the key's `max_concurrent`, and the rest queue and start as slots free. The key's webhook posts `run.completed` with the draft in `data.result`, which the billing service files against the invoice.

## Why run it on Rush?

The Stripe key sits in Rush's connection, not in the billing service's environment or a laptop, and it reaches each run only because the run names it. Stripe's own permissions on the key keep the agent to reads, and the session's `accounts` records which connection each run used. Revoking the key in Stripe stops every future run at once.

Each run keeps a transcript of every `stripe_api_read` call with its path and what Stripe returned, so when a customer replies that the email got their history wrong, the billing lead can see exactly which invoices it counted. Each run has its own computer and cost, and `GET /o/{org}/sessions` lists them, so the team knows what drafting each month's dunning emails costs.

## Frequently asked questions

### What is a dunning email?

A message to a customer whose payment failed, asking them to fix it before the account is affected. Stripe Billing can send automatic reminders; this agent drafts the personal one a billing team sends to accounts that matter, using the invoice, the decline and the customer's history.

### Why not let the agent send it?

A dunning email to a long-standing customer is a relationship message, and the billing lead often knows something Stripe does not. The draft saves the lookup and the writing; the send stays with a person, from their own mailbox.

### Does it replace Stripe's automatic retries?

No. Retries and Stripe's own reminder emails keep running as configured. The draft quotes `next_payment_attempt`, so the customer knows when the card will be tried again if they update it.

### Why an agent API key instead of signing in?

Stripe's OAuth sessions end 14 days after authorization, which would stop an unattended job until someone signs in again. Stripe recommends an agent API key for an agent that runs on its own, and a key with read permissions only means Stripe refuses any write the agent attempts.

## More Stripe jobs

- [Report Failed Payments in Stripe](https://getrush.ai/run/failed-payments-report/stripe/)
- [Build a Monthly Revenue Report From Stripe](https://getrush.ai/run/monthly-revenue-report/stripe/)
- [Reconcile Stripe Payouts Against Charges](https://getrush.ai/run/reconcile-payouts/stripe/)

## More jobs like this: Run an agent per customer task

- [Chargeback Response Drafts for Each Square Dispute](https://getrush.ai/run/draft-each-chargeback-response/square/)
- [How Did My Client's Site Do Last Month? A Reporting App Drafts Each Agency's Client Reports From Vercel Web Analytics](https://getrush.ai/run/draft-each-clients-monthly-traffic-report/vercel/)
- [What Were Our Numbers Last Month? An Investor-Update App's Read-Only Metrics From Each Startup's Neon Database](https://getrush.ai/run/draft-monthly-metrics-for-investor-update/neon/)

## Keep reading

- [Connect Stripe to Rush once, then name it on any run](https://getrush.ai/integrations/stripe/)
- [Start your first run from the developer API quickstart](https://getrush.ai/docs/quickstart/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
