A failed subscription payment is usually not a lost customer. It is an expired card that nobody noticed. The gap between those two readings is where every dunning product makes or loses its money, and the gap is smaller than the industry pretends.
I built RebillKit after watching the same failure twice in my own projects. A renewal fails, the recovery email goes out, the customer opens it four days later, and the card-update link inside is dead. Stripe Billing Portal session URLs are created when you ask for them and they expire. Queue that URL inside an email and you have shipped a link with a shelf life shorter than the problem it solves.
This article is about the three decisions that came out of that observation:
- Recovery links are created on click, not on send.
- Credentials belong to the tenant, encrypted per field, and never come back out.
- The email is plain text from the tenant's own domain, because inbox placement is the actual product.
The dead link problem
Stripe's Billing Portal is the right place to change a card. It handles SCA, wallet cards and regional payment methods without you rebuilding any of it. The usual integration works like this:
const session = await stripe.billingPortal.sessions.create({ customer: customerId, return_url: returnUrl, flow_data: { type: 'payment_method_update' }, }); await sendEmail({ link: session.url }); That is correct code and a bad user experience, because session.url is a resource with a lifetime. The email outlives it. Worse, the failure is silent: the customer clicks, gets an expiry page, and concludes that your billing is broken.
RebillKit stores an opaque recovery token instead, and resolves it at click time:
GET /r/<43 base64url chars> -> validate token shape (32 decoded bytes) -> load email row, then the case -> case must be 'active' -> decrypt tenant Stripe restricted key -> create a fresh Billing Portal session -> 302 with Cache-Control: no-store Token generation is crypto.randomBytes(32).toString('base64url'). Validation checks the regex shape and then decodes it to confirm 32 bytes, so a truncated or padded token cannot reach the database. Closed cases return a 410 with a page that says the invoice is settled or the sequence ended. No Stripe error page, no retry loop, no confusion.
The cost of this design is one extra round trip on click, plus a Stripe API call. That is the whole trade: spend 300 ms at click time to remove an expiry date from the customer's inbox.
Zero custody: keys in, masks out
The part that made me hesitate was credential handling. Storing someone else's Stripe key is a liability, and asking for a full secret key would be careless. Two decisions follow.
First, the tenant creates a Stripe Restricted Key with the minimum scopes the product needs, plus their Stripe webhook signing secret and a Resend API key. Second, every one of those values is encrypted per field before it touches Firestore:
const IV_BYTES = 12; const AUTH_TAG_BYTES = 16; const KEY_BYTES = 32; const cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: 16 }); return { iv: iv.toString('base64'), authTag: cipher.getAuthTag().toString('base64'), ciphertext: ciphertext.toString('base64'), }; Each record stores three fields, not one blob, and decryption enforces the exact lengths:
const iv = decodeExact(enc.iv, 12, 'iv'); const authTag = decodeExact(enc.authTag, 16, 'authTag'); That strictness matters. A truncated IV or tag is a data corruption signal, and the right response is to fail closed rather than attempt a decrypt with whatever bytes arrived. The master key is 64 hex characters (32 bytes) held outside the database, which means a database dump alone is not enough to read a customer's credentials.
The UI never sees the plaintext after the save. It sees a mask produced by a fixed rule: known prefix, four bullets, and the last four characters only when the value is long enough that four characters are under a quarter of the secret tail. Anything starting with rk_, sk_, whsec_ or re_ is redacted in logs before the line is written, because the most common credential leak in a Node service is a console.log(requestBody) that nobody removed.
What this design does not do, and I would rather say it than let someone assume otherwise: the server can decrypt the keys while it is running. That is unavoidable if the server is the thing calling Stripe. Zero custody here means the keys belong to the tenant, are scoped to the tenant, are unreadable at rest, and are never shared between tenants. It does not mean the process never holds them in memory.
Plain text as a deliverability decision
The second half of the recovery rate is whether the email is read. Three constraints pushed the design:
- Send from the tenant's domain. A shared sending domain carries the reputation of everyone using it. The tenant's verified domain carries theirs, and their customers already expect mail from it.
- Plain text only. No HTML part, no tracking pixel, no image. A one-pixel tracker is a spam signal and a privacy problem in the same object.
- A human voice. The emails read like the founder wrote them, because the ones that get replies are the ones that get read. Three of them: immediately (plus 15 minutes), three days, seven days.
The code is deliberately dull:
await resend.emails.send( { from, to: [to], subject, text, reply_to: replyTo }, { idempotencyKey: emailId }, ); text, never html. The idempotency key is the internal email id, and the same id goes out as an X-Entity-Ref-ID header, so a retried dispatch cannot produce a duplicate message.
Inbox placement is influenced by domain reputation, sending history, content and recipient behaviour. I can control the content and the absence of tracking. I cannot promise the Primary tab, and no honest vendor can. What I can promise is that the message is shaped like the mail a person sends.
Idempotency everywhere, because Stripe retries
Stripe delivers webhooks at least once. A handler that assumes exactly once will eventually create two cases for one failed invoice, and the customer gets six emails.
Two guards, both boring:
- Event level. A
processed_webhook_eventsdocument is claimed inside a transaction before any work happens, with a five-minute processing lease. A replayed event finds the claim and exits. - Email level. The dispatcher claims each due row by moving it from
scheduledtosendinginside a transaction, then calls Resend. Two cron invocations racing on the same row cannot both win.
The cron endpoint authenticates with a shared secret compared in constant time, and runs every five minutes. Anything slower makes the "15 minutes after the failure" email a lie.
Attribution that under-claims
The recovery counter is the number a customer looks at when deciding whether the tool works, which is exactly why it should be conservative.
RebillKit only counts a save when the case was still active and attemptCount >= 1: at least one email actually went out. If the customer fixes their card five minutes after the failure, before the first email, that payment is not a RebillKit save. It would be easy to count it. It would also make every number on the dashboard meaningless.
When invoice.paid arrives, the case closes and any pending emails are cancelled. Recovery amounts are recorded per currency, because a customer paying in EUR and a customer paying in USD are not the same number and should never be added together.
What I left out on purpose
- No OAuth Stripe Connect flow. It is a better fit for a platform that already has a billing relationship with its users. It is also a review queue, and the Restricted Key path gets a tenant live in about two minutes.
- No percentage of recovered revenue. The pricing is $99 or 99 EUR once for the first 50 founders, then $29 or 29 EUR a month. A tool that takes a cut gets more expensive precisely when it succeeds.
- No customer data warehouse. Cases, emails and counters, nothing else. The less of someone's billing history I store, the less there is to leak.
Try the flow
The product runs at rebillkit.com. There is an in-memory simulator with seeded cases, no account needed, including the click-through to a Stripe test portal:
rebillkit.com/en/dashboard?demo=1
If you build subscription software, the useful question is not whether this specific tool fits. It is how many of your failed payments were recoverable and how many died on an expired link. That number is worth measuring either way.

