Skip to content

feat(payments): Stripe webhook, ledger fulfillment and receipt email - #1792

Draft
ArendPeter wants to merge 2 commits into
checkout-session-endpointfrom
stripe-webhook
Draft

ArendPeter wants to merge 2 commits into
checkout-session-endpointfrom
stripe-webhook

Conversation

@ArendPeter

@ArendPeter ArendPeter commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Human Summary

This adds webhooks so that the backend can respond to Stripe transactions and update the entitlements accordingly.

Summary

Stacked on #1790. Closes #1587.

POST /API/StripeWebhook is registered with express.raw before the app-wide express.json(), the same way as the SendGrid webhook, so the Stripe-Signature can be checked against the raw body. A bad signature gets a 400.

checkout.session.completed / async_payment_succeeded
  re-fetch the session from Stripe            # don't trust the payload
  payment_status !== 'paid' → 200, no-op      # granted later, on async_payment_succeeded
  fulfillTransaction(session.id)              # one DB transaction:
    completeIfPending                         #   'already_complete' → no-op (redelivery)
                                              #   'not_found' / 'expired' → throw → 500, Stripe redelivers
    EntitlementsDB.insert                     #   one 'purchase' row per line item, amount = quantity × unit_entitlement
  receipt email                               # only when newly completed; failure logged, still 200
checkout.session.expired      → markExpired
checkout.session.async_payment_failed → log; row stays pending
anything else                 → 200
 packages/backend/src/
+├── Controllers/stripeWebhookController.ts   # route handler + fulfillTransaction
 ├── Services/Stripe/                         # + retrieveCheckoutSession, constructWebhookEvent
 ├── Services/Email/EmailTemplates.ts         # + PaymentReceipt
 ├── Models/Transactions.ts                   # getByStripeSessionId(…, trx?); markExpired only touches pending rows
+├── Models/__mocks__/Database.ts             # mock db.transaction() that restores the mock stores on throw
 ├── __mocks__/ServiceLocator.ts              # + database()
 └── app.ts                                   # + POST /API/StripeWebhook

Notes:

  • Fulfillment grants each line's quantity × unit_entitlement, using the per-unit values saved on the transaction at checkout (feat(payments): Checkout Session endpoint and shared product catalog #1790). A pricing change after checkout can't change what was bought.
  • The receipt goes to the email the customer entered on the Stripe checkout page (customer_details.email), not the account email. It's itemized from the line_items snapshot, with a total, a link to the election admin page and feat(payments): Checkout Session endpoint and shared product catalog #1790's PAYMENT_DISCLAIMER. It's sent without the SendGrid unsubscribe group, since it's transactional.
  • markExpired now only changes a pending row, so a late expired event can't undo a completed purchase. The spec didn't ask for this.
  • Following the spec, a paid session whose row is expired returns 500, so Stripe retries it for about 3 days. That means someone paid and got nothing, so it may deserve an alert.
  • STRIPE_WEBHOOK_SECRET is documented in sample.env, with the stripe listen command and its four events. The Provision Stripe webhook endpoint & retrieve signing secret #1588 wizard isn't on this branch, so the new events still need to be added there.
  • Nothing finalizes the election and nothing calls updateElection(). The return page will finalize once the grant has landed.

Test plan

  • stripeWebhook.test.ts (12 tests), with events signed by Stripe.webhooks.generateTestHeaderString:
    • A bad signature returns 400.
    • completed + paid completes the row and inserts one entitlement per line item: 3 blocks → 300 voters, 1 block → 100 voters.
    • A redelivered event (and a later async_payment_succeeded) inserts nothing more and sends one receipt.
    • completed + unpaid grants nothing, then async_payment_succeeded grants.
    • expired marks the row expired. A late expired leaves a completed row complete.
    • A failed entitlement insert returns 500 and rolls back the status change, and the redelivery then succeeds.
    • An unknown session returns 500. A failed email still returns 200 with the grant committed.
    • The receipt is itemized ("Increase Voter Limit": $18.00 + $6.00 = $24.00) and carries the disclaimer.
  • I checked the tests can fail: dropping the paid check, or granting unit_entitlement without multiplying by quantity, made a test fail.
  • npm run build -ws passes. npm test -w @equal-vote/star-vote-backend passes all 38 suites (317 tests).
  • Manual: run stripe listen with the events in sample.env and set STRIPE_WEBHOOK_SECRET. Create a session through feat(payments): Checkout Session endpoint and shared product catalog #1790's endpoint and pay with a test card. The transactionsDB row should become complete, the entitlementsDB rows should appear, and a receipt should arrive. Run stripe trigger checkout.session.expired to check the expiry path.

🤖 Generated with Claude Code

@ArendPeter
ArendPeter added this pull request to stack #1791 November 15, 2026 17:48
@netlify

netlify Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for bettervoting ready!

Name Link
🔨 Latest commit 7ba0cf1
🔍 Latest deploy log https://app.netlify.com/projects/bettervoting/deploys/6af9f06826b8f0c46585b1e1
😎 Deploy Preview https://deploy-preview-1792--bettervoting.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@ArendPeter ArendPeter changed the title Add Stripe webhook: ledger fulfillment and receipt email feat(payments): Stripe webhook, ledger fulfillment and receipt email Nov 15, 2026
@netlify

netlify Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for bettervoting ready!

Name Link
🔨 Latest commit 9934f20
🔍 Latest deploy log https://app.netlify.com/projects/bettervoting/deploys/6afa2774028357b8fe8a3650
😎 Deploy Preview https://deploy-preview-1792--bettervoting.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

ArendPeter and others added 2 commits November 15, 2026 13:42
POST /API/StripeWebhook verifies the Stripe-Signature against the raw body
(400 on a bad signature). checkout.session.completed and
async_payment_succeeded re-fetch the session and, once paid, call
fulfillTransaction: completeIfPending plus one purchase entitlement per line
item, in one DB transaction. A redelivered event is a no-op. After commit, a
newly completed transaction gets an itemized receipt email; a send failure is
logged and the webhook still returns 200. expired marks the row expired (only
while pending); async_payment_failed is logged.

Implements #1587.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The checkout PR now defines PAYMENT_DISCLAIMER, so this branch no longer
needs to add or move it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

Build Stripe webhook endpoint, ledger fulfillment & receipt email

1 participant