Skip to content

fix(billing): add checkout metadata, harden webhook and customer creation#3265

Merged
PierreBrisorgueil merged 2 commits intomasterfrom
fix/billing-checkout-webhook
Mar 18, 2026
Merged

fix(billing): add checkout metadata, harden webhook and customer creation#3265
PierreBrisorgueil merged 2 commits intomasterfrom
fix/billing-checkout-webhook

Conversation

@PierreBrisorgueil
Copy link
Contributor

@PierreBrisorgueil PierreBrisorgueil commented Mar 17, 2026

Summary

Scope

  • Module(s) impacted: billing
  • Cross-module impact: none
  • Risk level: low

Validation

  • npm run lint
  • npm test
  • Manual checks done (if applicable)

Guardrails check

  • No secrets or credentials introduced (.env*, secrets/**, keys, tokens)
  • No risky rename/move of core stack paths
  • Changes remain merge-friendly for downstream projects
  • Tests added or updated when behavior changed

Notes for reviewers

Summary by CodeRabbit

Release Notes

  • New Features

    • Checkout sessions now include enhanced tracking metadata for better transaction monitoring.
  • Bug Fixes

    • Strengthened webhook security by returning generic error messages instead of exposing internal details.
    • Improved subscription creation reliability when handling concurrent requests.
    • Added fallback mechanism to better resolve organization information in webhook processing.
  • Chores

    • Updated tests to align with new error handling and metadata enhancements.

…tion

- Add organizationId and plan metadata to Stripe checkout sessions (#3259)
- Wrap SubscriptionRepository.create in try/catch for duplicate key race condition (#3260)
- Fallback to stripeCustomerId lookup when checkout metadata is missing (#3261)
- Remove Stripe error details from webhook signature failure response (#3262)

Closes #3259, closes #3260, closes #3261, closes #3262
@PierreBrisorgueil PierreBrisorgueil added the Fix A bug fix label Mar 17, 2026
@PierreBrisorgueil PierreBrisorgueil self-assigned this Mar 17, 2026
@coderabbitai
Copy link

coderabbitai bot commented Mar 17, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 19 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: a0497b8c-4e06-4c92-ad67-d98e594ca044

📥 Commits

Reviewing files that changed from the base of the PR and between 25ec063 and b0c5163.

📒 Files selected for processing (4)
  • modules/billing/services/billing.service.js
  • modules/billing/services/billing.webhook.service.js
  • modules/billing/tests/billing.checkout.unit.tests.js
  • modules/billing/tests/billing.service.unit.tests.js

Walkthrough

The changes address four billing issues: adding metadata to Stripe checkout sessions for organization and plan tracking; handling race conditions in concurrent subscription creation with duplicate key error catching; adding fallback organizationId resolution via stripeCustomerId lookup in the webhook handler; and hardening error responses to avoid leaking internal details.

Changes

Cohort / File(s) Summary
Billing Service and Webhook
modules/billing/controllers/billing.webhook.controller.js, modules/billing/services/billing.service.js, modules/billing/services/billing.webhook.service.js
Added metadata (organizationId, plan) to Stripe checkout sessions; implemented race condition handling for concurrent subscription creation with try/catch for duplicate key errors; added fallback organizationId resolution via SubscriptionRepository.findByStripeCustomerId in webhook handler; hardened webhook error response with generic message instead of exposing internal details.
Unit Tests
modules/billing/tests/billing.checkout.unit.tests.js, modules/billing/tests/billing.controller.unit.tests.js, modules/billing/tests/billing.service.unit.tests.js
Updated test expectations for generic error messages; added metadata assertions to checkout session tests; expanded webhook service tests with coverage for organizationId fallback paths when metadata is absent; introduced mock for findByStripeCustomerId repository method.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • PR #3257: Introduces billing service and webhook controller foundation that these changes directly extend with metadata, race condition handling, and fallback lookup logic.
  • PR #3249: Introduces subscription repository methods (create, findByOrganization, findByStripeCustomerId) that are directly used and relied upon by the race condition and fallback lookup implementations in this PR.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: checkout metadata addition, webhook hardening, and customer creation improvements.
Description check ✅ Passed The description covers all required template sections: summary of four changes, rationale, linked issues, scope, validation checklist completion, guardrails checks, and reviewer notes.
Linked Issues check ✅ Passed All four linked issues are addressed: #3259 (metadata added), #3260 (race condition handled), #3261 (fallback lookup), #3262 (error sanitization).
Out of Scope Changes check ✅ Passed All changes are scoped to the billing module and directly address the four linked issues; no unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/billing-checkout-webhook
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@PierreBrisorgueil PierreBrisorgueil marked this pull request as ready for review March 17, 2026 18:10
Copilot AI review requested due to automatic review settings March 17, 2026 18:10
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens the billing module’s Stripe checkout and webhook flow by adding checkout session metadata, improving robustness against customer/subscription race conditions, adding a webhook organizationId fallback lookup, and sanitizing webhook error responses.

Changes:

  • Add metadata (organization + plan) to Stripe Checkout sessions and update unit tests accordingly.
  • Handle Mongo duplicate-key races during subscription creation by retrying via a re-read.
  • Harden webhook handling by falling back to stripeCustomerId lookup and returning a generic signature-verification error message.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
modules/billing/services/billing.service.js Adds checkout metadata and duplicate-key race handling during subscription creation.
modules/billing/services/billing.webhook.service.js Adds fallback organization resolution via Stripe customer id during checkout.session.completed.
modules/billing/controllers/billing.webhook.controller.js Sanitizes webhook signature verification failure response.
modules/billing/tests/billing.checkout.unit.tests.js Updates checkout tests to assert metadata passed to Stripe.
modules/billing/tests/billing.service.unit.tests.js Adds webhook fallback tests for resolving org from customer id.
modules/billing/tests/billing.controller.unit.tests.js Updates expected webhook signature error message.

- Use planId instead of name for checkout metadata plan field
- Fix webhook fallback to extract organization._id from populated doc
- Use destructured stripeCustomerId for consistency in fallback
- Update test mocks to reflect populated organization shape
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
modules/billing/controllers/billing.webhook.controller.js (1)

31-66: ⚠️ Potential issue | 🟠 Major

Controller responses still bypass the required API envelope

The handler returns raw res.status(...).json(...) objects instead of the project envelope helper (responses.success(...) / equivalent error envelope), so this endpoint remains inconsistent with module-wide API response shape standards.

Based on learnings: Enforce project-wide API envelope: all backend endpoints should wrap responses in the { type, message, data } envelope via responses.success(res, message)(data).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@modules/billing/controllers/billing.webhook.controller.js` around lines 31 -
66, The controller's handleWebhook returns raw res.status(...).json(...)
responses; update it to use the project API envelope helpers instead: replace
success responses (the final 200) with responses.success(res, 'Webhook
received')({ received: true }) and replace all error responses (the 400
signature/config errors and the 500 catch) with the error envelope helper (e.g.,
responses.error(res, 'Webhook signature verification failed')( { error:
errMessage } ) or similar project error helper), ensuring every return in
handleWebhook uses responses.success/responses.error rather than direct
res.status/json; keep the same logic around getStripe,
stripe.webhooks.constructEvent, and BillingWebhookService calls.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@modules/billing/services/billing.service.js`:
- Around line 106-118: The checkout session metadata currently sets plan to
matchedPlan?.name, but downstream logic expects the internal plan key (planId);
change the metadata to use the canonical plan identifier instead: derive the
matched plan via the existing matchedPlan lookup (using plans and priceId) and
set metadata.plan to matchedPlan?.id or matchedPlan?.planId (whichever property
holds the internal key in your Plan objects) or a safe default like 'free';
update the metadata assignment in the stripe.checkout.sessions.create call so
metadata.plan contains the internal plan key rather than the display name.

---

Outside diff comments:
In `@modules/billing/controllers/billing.webhook.controller.js`:
- Around line 31-66: The controller's handleWebhook returns raw
res.status(...).json(...) responses; update it to use the project API envelope
helpers instead: replace success responses (the final 200) with
responses.success(res, 'Webhook received')({ received: true }) and replace all
error responses (the 400 signature/config errors and the 500 catch) with the
error envelope helper (e.g., responses.error(res, 'Webhook signature
verification failed')( { error: errMessage } ) or similar project error helper),
ensuring every return in handleWebhook uses responses.success/responses.error
rather than direct res.status/json; keep the same logic around getStripe,
stripe.webhooks.constructEvent, and BillingWebhookService calls.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: bb4ebf6e-3ea2-425f-8fd2-86bb696572f5

📥 Commits

Reviewing files that changed from the base of the PR and between f520d8a and 25ec063.

📒 Files selected for processing (6)
  • modules/billing/controllers/billing.webhook.controller.js
  • modules/billing/services/billing.service.js
  • modules/billing/services/billing.webhook.service.js
  • modules/billing/tests/billing.checkout.unit.tests.js
  • modules/billing/tests/billing.controller.unit.tests.js
  • modules/billing/tests/billing.service.unit.tests.js

@PierreBrisorgueil PierreBrisorgueil merged commit 0fe2056 into master Mar 18, 2026
3 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the fix/billing-checkout-webhook branch March 18, 2026 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Fix A bug fix

Projects

None yet

2 participants