fix(billing): add checkout metadata, harden webhook and customer creation#3265
fix(billing): add checkout metadata, harden webhook and customer creation#3265PierreBrisorgueil merged 2 commits intomasterfrom
Conversation
…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
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (4)
WalkthroughThe 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
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. Comment |
There was a problem hiding this comment.
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
stripeCustomerIdlookup 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
There was a problem hiding this comment.
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 | 🟠 MajorController 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 viaresponses.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
📒 Files selected for processing (6)
modules/billing/controllers/billing.webhook.controller.jsmodules/billing/services/billing.service.jsmodules/billing/services/billing.webhook.service.jsmodules/billing/tests/billing.checkout.unit.tests.jsmodules/billing/tests/billing.controller.unit.tests.jsmodules/billing/tests/billing.service.unit.tests.js
Summary
Scope
billingnonelowValidation
npm run lintnpm testGuardrails check
.env*,secrets/**, keys, tokens)Notes for reviewers
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Chores