Skip to content

feat(billing): email people 3 days before their free trial ends - #2467

Merged
gkhngyk merged 2 commits into
ansvisor:mainfrom
cihan-gyk:feature/trial-ending-email
Nov 17, 2026
Merged

gkhngyk merged 2 commits into
ansvisor:mainfrom
cihan-gyk:feature/trial-ending-email

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Nothing told people their free trial was ending. The webhook did not handle Stripe's customer.subscription.trial_will_end, so the card was charged on day 15 without warning.

This PR sends our own branded reminder 3 days before the trial ends. It works like the welcome email: the app sends Resend a custom event, trial.ending, and a Resend Automation sends the email. It runs on Cloud only.

Once the Automation is live, Stripe's own trial reminder can be turned off.

Changes

  • web/src/lib/billing/trial-ending.ts (new): handles trial_will_end.
    • It reads the subscription again from Stripe. It sends only if the subscription is still trialing, the trial ends later than now, and a charge is coming. Nothing is sent when cancel_at_period_end is on, or when cancel_at is on or before the trial end.
    • The email goes to the Stripe customer's email, which is the person who started the subscription. If there is none, it goes to the organization's admins. All reads are scoped to the subscription's organization, which must also hold the Stripe customer.
    • The amount and currency come from Stripe's preview of the invoice due at the trial end, so tax, discounts and add-ons are included. If Stripe can't say, they are left out. They are never guessed.
    • It sends exactly one email per trial (see below).
    • PostHog gets trial_ending_notified with plan, outcome, recipient, recipient_count, has_amount and organization_id. It is sent as the person who started the subscription, or else the first admin.
    • Each step logs one [trial-ending] line with a reason code and the subscription id. Email addresses and names are never logged.
  • web/src/app/api/stripe/webhook/route.ts: a new customer.subscription.trial_will_end case. It answers 500 only when Resend rate limited the event (429), so Stripe retries.
  • Help: the trial article (help/settings/trial-ai-credit.md) gets a "Before your trial ends" section with one sentence. approved-articles.json is regenerated, not hand-edited.
  • web/.env.example: a note that the webhook also sends trial.ending.
  • No migration, no new dependency, no lockfile change, no en.json change, no new server action.

Exactly once

There is no table for this. The webhook does not dedupe event ids, so the send is recorded on the Stripe subscription's metadata:

  1. If trial_reminder_sent_at is set for this trial end, nothing is sent.
  2. Otherwise a claim is written first: trial_reminder_sent_at, trial_reminder_trial_end and a new trial_reminder_claim id. After 1.5 s the claim is read back, and only the delivery whose claim id stayed sends. This stops two deliveries that arrive at the same moment from both sending.
  3. What happens next depends on Resend's answer (send-outcome.ts):
    • accepted: the claim stays and the webhook answers 200.
    • unknown (5xx, timeout or network error): the claim stays, because Resend may have the event. Nothing is sent again. The webhook answers 200.
    • rate limited (429): the claim is cleared and the webhook answers 500, so Stripe's retry can send it.
    • refused for good (any other 4xx: a bad address, a bad request, a bad key): a retry would fail too. The claim stays and is marked trial_reminder_outcome: refused. The webhook answers 200, so Stripe doesn't retry for 3 days. One [trial-ending] line logs the status, and PostHog gets outcome: refused.
  4. If any read fails before the claim (Stripe or the database), the handler throws and the webhook answers 500. Nothing was sent, so a retry is safe.

If some admins' sends are refused and others accepted, the reminder counts as sent. Writing the metadata makes Stripe send customer.subscription.updated. That handler writes the same values again, so nothing changes.

Ops steps

Stripe

  1. Go to Stripe › Developers › Webhooks (Workbench › Webhooks in the new Dashboard) and open the endpoint for /api/stripe/webhook.
  2. If the endpoint lists its events one by one, add customer.subscription.trial_will_end.
  3. Do this in both test mode and live mode.

Resend

  1. Create an Automation triggered by the custom event trial.ending.
  2. Its email uses a new template with these variables:
    • first_name (may be missing)
    • workspace_name
    • plan_name (may be missing)
    • trial_ends_at (ISO time, UTC)
    • trial_ends_on (a readable date in UTC, e.g. "November 20, 2026")
    • amount (formatted, e.g. "$249.00"; may be missing)
    • currency (e.g. "USD"; may be missing)
    • manage_url (the app's Billing page, where the plan is changed or canceled)
  3. Give the variables that may be missing a fallback value. For example, use "there" for first_name and "your plan's price" for amount.
  4. The cancel link is manage_url, not the Stripe portal. Cancel lives in our app.

RESEND_API_KEY is already set for the welcome email. Nothing new is needed.

Sending a reminder again by hand

A reminder Resend refused for good (trial_reminder_outcome: refused on the subscription) is not retried. To send it again after fixing the cause (for example the customer's email):

  1. In Stripe, open the subscription and delete the metadata keys trial_reminder_sent_at, trial_reminder_trial_end, trial_reminder_claim and trial_reminder_outcome.
  2. Open the subscription's customer.subscription.trial_will_end event under Developers › Events and click Resend.

Stripe's own trial reminder

  1. Keep Stripe's built-in trial reminder email on until this PR is deployed and the Resend Automation is live and tested. The setting is in Stripe › Settings › Billing › Subscriptions and emails.
  2. Then turn Stripe's reminder off, so people don't get two emails.

Example event payload

What the app posts to https://api.resend.com/events/send:

{
  "event": "trial.ending",
  "email": "[email protected]",
  "payload": {
    "first_name": "Ada",
    "workspace_name": "Example Workspace",
    "plan_name": "Growth",
    "trial_ends_at": "2026-11-20T10:00:00.000Z",
    "trial_ends_on": "November 20, 2026",
    "amount": "$249.00",
    "currency": "USD",
    "manage_url": "https://app.ansvisor.com/dashboard/settings/billing"
  }
}

How to test (Stripe test mode)

  1. Set up a local or preview app with NEXT_PUBLIC_IS_CLOUD=true, RESEND_API_KEY, NEXT_PUBLIC_APP_URL and the test-mode STRIPE_* keys. For a local app, run stripe listen --forward-to localhost:3000/api/stripe/webhook and use the secret it prints as STRIPE_WEBHOOK_SECRET.
  2. Start a free trial from the app with the test card 4242 4242 4242 4242.
  3. Move the trial end to about 2 days from now: stripe subscriptions update sub_... -d trial_end=<unix time>. Stripe sends customer.subscription.trial_will_end when 3 days or less are left. You can also use a test clock on a test customer.
  4. Look for these lines in the logs:
    • [trial-ending] claimed: customer(1) sub=sub_..., then [trial-ending] sent: accepted sub=sub_...
    • On the subscription in Stripe: metadata trial_reminder_sent_at, trial_reminder_trial_end and trial_reminder_claim.
    • In Resend: a trial.ending event with the payload above, the Automation run and the email.
    • In PostHog: trial_ending_notified with outcome: accepted.
    • A refused send logs [trial-ending] resend_refused:<status> sub=sub_.... A 429 adds (released: Stripe sends the event again). Any other 4xx adds (claim kept, not retried: ...).
  5. Resend the same event from the Stripe Dashboard. The log should say [trial-ending] skip: already_sent sub=sub_... and no second email is sent.
  6. Start a second test trial and cancel it in Billing, then move its trial end and wait for the event. The log should say skip: cancel_at_period_end and no email is sent.
  7. stripe trigger customer.subscription.trial_will_end only checks the wiring. Its subscription belongs to no workspace, so you should see a skip line such as skip: no_org.

Choices made

  • Only a rate limit is retried. A 429 makes Stripe send the event again. Any other 4xx keeps the claim, is marked refused and answers 200, so Stripe doesn't retry a lost cause for 3 days. A manual resend is still possible (see Ops steps).
  • A moved trial end gets a reminder for the new date. If staff extend a trial, the first email named a date that has passed without a charge. The new end date gets its own reminder.
  • The Resend template needs fallbacks. first_name, plan_name, amount and currency can be missing, so give them fallback values in the template.

Checks

  • npx tsc --noEmit -p .: clean.
  • Vitest: 30 files and 312 tests passed. That covers src/app/api/stripe, src/lib/billing, signup-event, resend-event, posthog-server, src/lib/help, src/i18n, use-server-exports and subscription-guard-coverage.
    • 23 new tests for the handler:
      • A trialing subscription sends once, with the right properties and URL.
      • Nothing is sent on cancel_at_period_end, a cancel before the trial end, not trialing, trial over, self-hosted or no key.
      • A second delivery sends nothing. Of two deliveries at once, only one sends.
      • A 429 clears the claim, answers retry, and the retry sends.
      • A 400, 401 or 422 keeps the claim, marks it refused, answers 200, logs one line and is not sent again.
      • A claim cleared by hand sends again.
      • Unknown (5xx, timeout) is marked and not resent.
      • No customer email goes to the org admins. If one admin is refused and another accepted, the reminder counts as sent.
      • The amount is left out when unknown.
      • The PostHog event is sent.
      • A moved trial end gets a new reminder.
    • 4 new route tests: dispatch, 500 on a rate limit, 500 on a read failure, and not called for other events.
  • ESLint and Prettier: clean on the changed TypeScript files.
  • git merge-tree --write-tree HEAD upstream/main: clean.

Generated by Claude Code

Handle Stripe's customer.subscription.trial_will_end in the webhook and
send Resend the `trial.ending` event for a branded trial reminder, like
the welcome's `user.signed_up`. Cloud only; only for a subscription that
is still trialing and will be charged (not set to cancel).

To the Stripe customer's e-mail, else the organization's admins, with the
workspace, plan, trial end, the first charge from Stripe's invoice
preview (left out when unknown) and the Billing page's link.

Once per trial without a migration: claimed on the subscription's
metadata (trial_reminder_sent_at, the trial end, a claim id), read back,
then sent. Accepted or unknown (5xx, timeout): kept. Refused (4xx):
released and the webhook answers 500, so Stripe's retry sends it.
PostHog gets trial_ending_notified with the plan and outcome.

Help: the trial article says we email 3 days before the trial ends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9
A 429 still releases the claim and answers Stripe 500, so Stripe's retry
sends it. Any other 4xx (a bad address, request or key) won't go through
on a retry: the claim stays, marked trial_reminder_outcome: refused, and
the webhook answers 200, so Stripe doesn't retry for 3 days. Clearing the
trial_reminder_* metadata and resending the event sends it again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good: the claim/settle/read-back guard, the 429-only retry and the cancel checks all hold up. Merging once CI is green.

@gkhngyk
gkhngyk merged commit ba85aed into ansvisor:main Nov 17, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants