Skip to content

Fetch and cache active stripe subscription#50

Merged
Jackson57279 merged 2 commits intomainfrom
cursor/fetch-and-cache-active-stripe-subscription-fff9
Aug 9, 2025
Merged

Fetch and cache active stripe subscription#50
Jackson57279 merged 2 commits intomainfrom
cursor/fetch-and-cache-active-stripe-subscription-fff9

Conversation

@Jackson57279
Copy link
Owner

@Jackson57279 Jackson57279 commented Aug 9, 2025

Update Stripe webhook to fetch and cache the most recent active subscription status.

Previously, the code fetched only one subscription, which could be stale or cancelled, leading to incorrect caching of the user's subscription status. This change ensures the correct, most recent active subscription is identified and cached.


Open in Cursor Open in Web

Summary by CodeRabbit

  • New Features
    • Introduced support for Stripe webhooks to automatically process and update subscription and payment status.
    • Subscription details are now kept up-to-date based on real-time Stripe events, improving account accuracy.

Co-authored-by: dogesman098 <dogesman098@gmail.com>
@cursor
Copy link

cursor bot commented Aug 9, 2025

Cursor Agent can help with this pull request. Just @cursor in comments and I'll start working on changes in this branch.
Learn more about Cursor Agents

@vercel
Copy link

vercel bot commented Aug 9, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
zapdev ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 9, 2025 10:56pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 9, 2025

Walkthrough

A new API endpoint for handling Stripe webhooks has been added. This handler processes specific Stripe event types related to subscriptions and payments, verifies webhook signatures, extracts and synchronizes customer subscription data to a key-value store, and returns appropriate HTTP status codes. The default body parser is disabled for raw request access.

Changes

Cohort / File(s) Change Summary
Stripe Webhook API Endpoint
api/stripe-webhook.ts
Introduced a Stripe webhook handler that processes subscription/payment events, verifies signatures, synchronizes customer subscription data to a cache, and configures raw body parsing. Added exported types and configuration.

Sequence Diagram(s)

sequenceDiagram
    participant Stripe
    participant API Handler
    participant KeyValueStore

    Stripe->>API Handler: POST /api/stripe-webhook (with event payload)
    API Handler->>API Handler: Verify HTTP method and required headers
    API Handler->>API Handler: Verify Stripe signature using secret
    API Handler->>API Handler: Parse and filter event type
    API Handler->>API Handler: Extract customer ID
    API Handler->>Stripe: Fetch all subscriptions for customer
    API Handler->>API Handler: Select active/trialing subscription
    API Handler->>KeyValueStore: Cache subscription data (or 'none')
    API Handler-->>Stripe: Return HTTP 200 or error status
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

A bunny hops where webhooks stream,
Stripe events arrive, a coder’s dream.
Subscriptions checked, the cache renewed,
Payment details neatly queued.
With careful paws, the handler’s spun—
A whiskered job, securely done!
🐇💳✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cursor/fetch-and-cache-active-stripe-subscription-fff9

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@claude
Copy link

claude bot commented Aug 9, 2025

Claude encountered an error —— View job


I'll analyze this and get back to you.

@Jackson57279 Jackson57279 marked this pull request as ready for review August 9, 2025 22:53
@Jackson57279
Copy link
Owner Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 9, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
@claude
Copy link

claude bot commented Aug 9, 2025

Claude encountered an error —— View job


I'll analyze this and get back to you.

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: 0

♻️ Duplicate comments (2)
api/stripe-webhook.ts (2)

100-110: Remove any and correctly handle Buffer for Stripe signature verification (fixes ESLint and robustness).

Accessing rawBody via (req as any) fails lint and misses the case where req.body is a Buffer. Use a typed request and support both string and Buffer.

Apply this diff within this block:

-  const rawBody = (req as any).rawBody || (req.body && typeof req.body === 'string' ? req.body : undefined);
+  const rawBody =
+    (req as RawBodyRequest).rawBody ??
+    (typeof req.body === 'string' || Buffer.isBuffer(req.body) ? req.body : undefined);

Add this small type near the imports (outside this range):

type RawBodyRequest = VercelRequest & { rawBody?: string | Buffer };

114-120: Eliminate any and robustly extract customerId across event payload shapes.

event.data.object varies by event; avoid any and handle both string and expanded objects safely.

Apply this diff within this block:

-    if (allowedEvents.includes(event.type)) {
-      const obj: any = event.data?.object ?? {};
-      const customerId = obj.customer as string | undefined;
-      if (customerId && typeof customerId === 'string') {
-        await syncStripeDataToKV(customerId);
-      }
-    }
+    if (allowedEvents.includes(event.type)) {
+      const customerId = extractCustomerId(event.data?.object);
+      if (customerId) {
+        await syncStripeDataToKV(customerId);
+      }
+    }

Add this helper (outside this range, e.g., below the StripeSubCache type):

function extractCustomerId(obj: unknown): string | undefined {
  if (!obj || typeof obj !== 'object') return undefined;
  const customer = (obj as { customer?: unknown }).customer;
  if (typeof customer === 'string') return customer;
  if (customer && typeof customer === 'object') {
    const id = (customer as { id?: unknown }).id;
    if (typeof id === 'string') return id;
  }
  return undefined;
}
🧹 Nitpick comments (4)
api/stripe-webhook.ts (4)

6-26: Optional: strengthen type-safety for event names.

Typing the allowlist makes typos impossible to compile.

Apply:

-const allowedEvents: string[] = [
+const allowedEvents = [
   'checkout.session.completed',
   'customer.subscription.created',
   'customer.subscription.updated',
   'customer.subscription.deleted',
   'customer.subscription.paused',
   'customer.subscription.resumed',
   'customer.subscription.pending_update_applied',
   'customer.subscription.pending_update_expired',
   'customer.subscription.trial_will_end',
   'invoice.paid',
   'invoice.payment_failed',
   'invoice.payment_action_required',
   'invoice.upcoming',
   'invoice.marked_uncollectible',
   'invoice.payment_succeeded',
   'payment_intent.succeeded',
   'payment_intent.payment_failed',
   'payment_intent.canceled',
-];
+ ] as const;

Optionally:

// type AllowedEvent = typeof allowedEvents[number]; // for narrowed checks if needed

69-75: Multi-item subscriptions: selecting only the first item may be misleading.

If a subscription can have multiple items, using items.data[0] could cache the wrong price. Consider deriving the “primary” item or caching all price IDs.

Example (cache all price IDs without breaking shape):

-    priceId: subscription.items.data[0]?.price?.id ?? null,
+    priceId:
+      subscription.items.data.find((it) => it.price?.active)?.price?.id ??
+      subscription.items.data[0]?.price?.id ??
+      null,

76-83: Payment method fallback: also check latest invoice’s payment intent.

default_payment_method on the subscription is often null; card details are frequently on latest_invoice.payment_intent.payment_method. Consider expanding and falling back to that for more complete caching.

Possible approach (requires expanding nested fields):

-  const subscriptions = await stripe.subscriptions.list({
+  const subscriptions = await stripe.subscriptions.list({
     customer: customerId,
     limit: 100,
     status: 'all',
-    expand: ['data.default_payment_method'],
+    expand: ['data.default_payment_method', 'data.latest_invoice.payment_intent.payment_method'],
   });

Then, when building paymentMethod, fallback if default_payment_method is missing:

const pmFromSub = typeof subscription.default_payment_method !== 'string' ? subscription.default_payment_method : null;
const pmFromPI =
  (typeof subscription.latest_invoice !== 'string' &&
    subscription.latest_invoice?.payment_intent &&
    typeof subscription.latest_invoice.payment_intent !== 'string' &&
    subscription.latest_invoice.payment_intent.payment_method &&
    typeof subscription.latest_invoice.payment_intent.payment_method !== 'string'
      ? subscription.latest_invoice.payment_intent.payment_method
      : null) || null;

const pm = pmFromSub ?? pmFromPI;

paymentMethod: pm
  ? {
      brand: pm.card?.brand ?? null,
      last4: pm.card?.last4 ?? null,
    }
  : null,

124-130: Good failure handling, minor nit: include error class in logs.

Logging message is fine; optionally log name to aid triage.

-    console.error('[STRIPE WEBHOOK] Error', errorMessage);
+    console.error('[STRIPE WEBHOOK] Error', { message: errorMessage, name: (err as any)?.name });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 12f89bb and 9c61ca9.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • api/stripe-webhook.ts (1 hunks)
🧰 Additional context used
🪛 ESLint
api/stripe-webhook.ts

[error] 103-103: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)


[error] 115-115: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

🪛 GitHub Check: ESLint
api/stripe-webhook.ts

[failure] 103-103: Disallow the any type
Unexpected any. Specify a different type.


[failure] 115-115: Disallow the any type
Unexpected any. Specify a different type.

🔇 Additional comments (3)
api/stripe-webhook.ts (3)

56-63: Confirm business rule: exclude past_due (and possibly unpaid) from candidates?

Currently only active/trialing qualify. If users with past_due should retain access, consider including it (and maybe unpaid) to avoid caching status: 'none'.

If inclusion is intended, minimal change:

-  .filter((s) => s.status === 'active' || s.status === 'trialing')
+  .filter((s) => s.status === 'active' || s.status === 'trialing' || s.status === 'past_due')

89-94: LGTM: Method restriction and Allow header are correct.

POST-only with Allow: POST is handled properly.


133-137: LGTM: Body parser disabled for raw signature verification.

This matches Stripe’s requirement for using the raw request body.

@Jackson57279 Jackson57279 merged commit 2a0f0ef into main Aug 9, 2025
11 of 12 checks passed
@Jackson57279 Jackson57279 deleted the cursor/fetch-and-cache-active-stripe-subscription-fff9 branch August 9, 2025 23:02
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.

2 participants