Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@BilalG1
Copy link
Contributor

@BilalG1 BilalG1 commented Jan 13, 2026

Summary by CodeRabbit

  • Bug Fixes
    • Improved support for legacy Stripe subscription data handling with fallback mechanisms.
    • Enhanced error handling for missing or invalid subscription metadata to prevent processing failures.

✏️ Tip: You can customize this high-level summary in your review settings.

@cmux-agent
Copy link

cmux-agent bot commented Jan 13, 2026

Older cmux preview screenshots (latest comment is below)

Preview Screenshots

Open Diff Heatmap

Preview screenshots are being captured...

Workspace and dev browser links will appear here once the preview environment is ready.


Generated by cmux preview system

@vercel
Copy link

vercel bot commented Jan 13, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
stack-backend Ready Ready Preview, Comment Jan 13, 2026 7:52pm
stack-dashboard Ready Ready Preview, Comment Jan 13, 2026 7:52pm
stack-demo Ready Ready Preview, Comment Jan 13, 2026 7:52pm
stack-docs Ready Ready Preview, Comment Jan 13, 2026 7:52pm

@cmux-agent
Copy link

cmux-agent bot commented Jan 13, 2026

Older cmux preview screenshots (latest comment is below)

Preview Screenshots

Open Workspace (1 hr expiry) · Open Dev Browser (1 hr expiry) · Open Diff Heatmap

Screenshot capture was skipped.

No UI changes detected - screenshots skipped


Generated by cmux preview system

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 13, 2026

📝 Walkthrough

Walkthrough

This change adds parsing of Stripe subscription metadata to support legacy subscriptions. It derives product data from either product or offer fields, validates presence, parses JSON, and adds error handling for missing or invalid metadata. The productId now includes a fallback to use offerId when undefined.

Changes

Cohort / File(s) Summary
Stripe Metadata Parsing
apps/backend/src/lib/stripe.tsx
Added support for legacy Stripe subscriptions by parsing metadata from product or offer fields. Replaces direct JSON.parse with validated productJson value. Introduces fallback logic for productId to use offerId when undefined. Adds InputJsonValue type import and error handling for missing/invalid metadata.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Hop into the past with grace,
Legacy subscriptions find their place,
Metadata parsed with fallback care,
Offer or product, both fields fair,
Stripe's old secrets now laid bare!

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description is completely empty except for the template comment. No details about the changes, motivation, or impact are provided. Add a detailed description explaining the webhook failure being fixed, the root cause, the solution implemented, and any testing performed.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix stripe failing webhook' clearly describes the primary change: fixing a Stripe webhook issue. It is concise, specific, and directly relates to the code changes which handle Stripe subscription metadata parsing and error handling.

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

✨ Finishing touches
  • 📝 Generate docstrings

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.

@greptile-apps
Copy link
Contributor

greptile-apps bot commented Jan 13, 2026

Greptile Summary

Fixed webhook failures for legacy Stripe subscriptions by adding backward compatibility with the old offer metadata field names that existed before the migration to product field names.

  • Added fallback logic to check subscription.metadata.offer when subscription.metadata.product is missing
  • Added fallback logic to check subscription.metadata.offerId when subscription.metadata.productId is missing
  • Improved error handling with specific error messages when metadata is missing or contains invalid JSON
  • Parsed JSON once and reused the result to avoid duplicate parsing
  • Added type import for InputJsonValue from Prisma client

Confidence Score: 5/5

  • This PR is safe to merge with minimal risk
  • The changes add proper backward compatibility for a known breaking change (offer to product migration) with comprehensive error handling. The logic is straightforward, properly handles edge cases, and follows existing patterns in the codebase.
  • No files require special attention

Important Files Changed

Filename Overview
apps/backend/src/lib/stripe.tsx Added backward compatibility for old Stripe subscriptions with offer metadata, improved error handling for missing/invalid JSON metadata

Sequence Diagram

sequenceDiagram
    participant Stripe
    participant Webhook as Webhook Handler
    participant Sync as syncStripeSubscriptions
    participant DB as Database

    Stripe->>Webhook: POST /webhooks (subscription event)
    Webhook->>Webhook: Verify signature
    Webhook->>Webhook: Extract accountId & customerId
    Webhook->>Sync: syncStripeSubscriptions(stripe, accountId, customerId)
    
    Sync->>Stripe: Retrieve account metadata
    Sync->>Stripe: List subscriptions for customer
    
    loop For each subscription
        Sync->>Sync: Try metadata.product
        alt metadata.product exists
            Sync->>Sync: Use metadata.product
        else fallback to metadata.offer
            Sync->>Sync: Use metadata.offer (legacy)
        end
        
        alt metadata missing
            Sync-->>Webhook: Throw StackAssertionError
        end
        
        Sync->>Sync: JSON.parse(productString)
        
        alt Invalid JSON
            Sync-->>Webhook: Throw StackAssertionError
        end
        
        Sync->>Sync: Try metadata.productId ?? metadata.offerId
        
        Sync->>DB: upsert subscription
        DB-->>Sync: Success
    end
    
    Sync-->>Webhook: Success
    Webhook-->>Stripe: 200 OK
Loading

@greptile-apps
Copy link
Contributor

greptile-apps bot commented Jan 13, 2026

Greptile's behavior is changing!

From now on, if a review finishes with no comments, we will not post an additional "statistics" comment to confirm that our review found nothing to comment on. However, you can confirm that we reviewed your changes in the status check section.

This feature can be toggled off in your Code Review Settings by deselecting "Create a status check for each PR".

Copy link
Contributor

@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

🤖 Fix all issues with AI agents
In @apps/backend/src/lib/stripe.tsx:
- Around line 128-130: The productId assignment is using inconsistent casting
and lacks the same defensive validation as the product/offer handling; change
the fallback subscription.metadata.offerId to be cast as string | undefined
(matching product handling) and add a validation check that throws or returns an
error if both subscription.metadata.productId and subscription.metadata.offerId
are missing so productId never becomes null/undefined; update the productId
assignment (and any surrounding logic that uses productId) to use the validated,
cast value consistently.
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ee5b757 and 4471887.

📒 Files selected for processing (1)
  • apps/backend/src/lib/stripe.tsx
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: For blocking alerts and errors, never use toast, as they are easily missed by the user. Instead, use alerts
Keep hover/click transitions snappy and fast without pre-transition delays (e.g., no fade-in when hovering a button). Apply transitions after the action, like smooth fade-out when hover ends
NEVER try-catch-all, NEVER void a promise, and NEVER .catch(console.error). Use loading indicators for async operations. Use runAsynchronously or runAsynchronouslyWithAlert instead of general try-catch error handling
When creating hover transitions, avoid hover-enter transitions and use only hover-exit transitions (e.g., transition-colors hover:transition-none)
Don't use Date.now() for measuring elapsed (real) time; instead use performance.now()
Use ES6 maps instead of records wherever possible

Files:

  • apps/backend/src/lib/stripe.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: NEVER use Next.js dynamic functions if you can avoid them. Prefer using client components to keep pages static (e.g., use usePathname instead of await params)
Code defensively using ?? throwErr(...) instead of non-null assertions, with good error messages explicitly stating violated assumptions
Try to avoid the any type. When using any, leave a comment explaining why and how the type system fails or how errors would still be caught

Files:

  • apps/backend/src/lib/stripe.tsx
{.env*,**/*.{ts,tsx,js,jsx}}

📄 CodeRabbit inference engine (AGENTS.md)

All environment variables should be prefixed with STACK_ (or NEXT_PUBLIC_STACK_ if public) to ensure Turborepo picks up changes and improve readability

Files:

  • apps/backend/src/lib/stripe.tsx
🧠 Learnings (1)
📚 Learning: 2025-10-11T04:13:19.308Z
Learnt from: N2D4
Repo: stack-auth/stack-auth PR: 943
File: examples/convex/app/action/page.tsx:23-28
Timestamp: 2025-10-11T04:13:19.308Z
Learning: In the stack-auth codebase, use `runAsynchronouslyWithAlert` from `stackframe/stack-shared/dist/utils/promises` for async button click handlers and form submissions instead of manual try/catch blocks. This utility automatically handles errors and shows alerts to users.

Applied to files:

  • apps/backend/src/lib/stripe.tsx
🧬 Code graph analysis (1)
apps/backend/src/lib/stripe.tsx (2)
packages/stack-shared/src/utils/errors.tsx (1)
  • StackAssertionError (69-85)
packages/stack-shared/src/utils/results.tsx (1)
  • error (36-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
  • GitHub Check: all-good
  • GitHub Check: Vercel Agent Review
  • GitHub Check: check_prisma_migrations (22.x)
  • GitHub Check: lint_and_build (latest)
  • GitHub Check: setup-tests
  • GitHub Check: restart-dev-and-test
  • GitHub Check: docker
  • GitHub Check: build (22.x)
  • GitHub Check: build (22.x)
  • GitHub Check: setup-tests-with-custom-base-port
  • GitHub Check: E2E Tests (Node 22.x, Freestyle prod)
  • GitHub Check: restart-dev-and-test-with-custom-base-port
  • GitHub Check: E2E Tests (Node 22.x, Freestyle mock)
🔇 Additional comments (3)
apps/backend/src/lib/stripe.tsx (3)

9-9: LGTM!

The InputJsonValue import is correctly added to properly type the parsed JSON metadata.


96-106: LGTM!

Good backward-compatible handling for legacy subscriptions. The try-catch is appropriately scoped to JSON parsing (not a try-catch-all), and the StackAssertionError includes helpful context for debugging.


115-123: LGTM!

The update path correctly uses the pre-validated productJson value.

@BilalG1 BilalG1 requested a review from N2D4 January 13, 2026 19:22
@BilalG1 BilalG1 assigned N2D4 and unassigned BilalG1 Jan 13, 2026
@github-actions github-actions bot assigned BilalG1 and unassigned N2D4 Jan 13, 2026
@cmux-agent
Copy link

cmux-agent bot commented Jan 13, 2026

Preview Screenshots

Open Diff Heatmap

Preview screenshots are being captured...

Workspace and dev browser links will appear here once the preview environment is ready.


Generated by cmux preview system

@BilalG1 BilalG1 enabled auto-merge (squash) January 13, 2026 19:45
@BilalG1 BilalG1 merged commit ea6a8cb into dev Jan 13, 2026
27 checks passed
@BilalG1 BilalG1 deleted the fix-stripe-failing-webhook branch January 13, 2026 20:24
@coderabbitai coderabbitai bot mentioned this pull request Jan 20, 2026
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