Skip to content

Integrate app payments and pricing model#58

Merged
Jackson57279 merged 2 commits intomainfrom
cursor/integrate-app-payments-and-pricing-model-9114
Aug 12, 2025
Merged

Integrate app payments and pricing model#58
Jackson57279 merged 2 commits intomainfrom
cursor/integrate-app-payments-and-pricing-model-9114

Conversation

@Jackson57279
Copy link
Owner

@Jackson57279 Jackson57279 commented Aug 12, 2025

Integrates Autumn billing to enable Free and Pro chat message plans.

This PR sets up server-side Autumn endpoints in Convex, wraps the React app with AutumnProvider, gates and tracks AI chat messages based on plan limits, and enables Stripe checkout for the Pro plan via Autumn.


Open in Cursor Open in Web

Summary by CodeRabbit

  • New Features

    • Added billing-based limits for sending messages, with prompts to upgrade when limits are reached.
    • Enabled Pro plan checkout via Autumn directly from the pricing page.
    • Introduced app-wide Autumn integration for identity and access, including anonymous access with rate limiting.
    • Improved API routing to support Autumn-backed endpoints alongside existing requests.
  • Chores

    • Added Autumn client library dependency.
    • Updated environment template with Autumn configuration variables.

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

cursor bot commented Aug 12, 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 12, 2025

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

Project Deployment Preview Comments Updated (UTC)
zapdev Ready Preview Comment Aug 12, 2025 9:43pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 12, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Introduces Autumn billing/identity across server and client: HTTP routing adds Autumn identity and rate limiting; messages gated and usage tracked server-side; client chat and pricing UI integrate Autumn checks and checkout; app wrapped with AutumnProvider; environment variables and dependency for autumn-js added.

Changes

Cohort / File(s) Summary of changes
HTTP routing & identity
convex/http.ts
Added ROUTABLE_HTTP_METHODS routing for /api/autumn/* via autumn handler; implemented Clerk JWT verification, per-token rate limiting, and identity extraction; updated tRPC handling via fetchRequestHandler.
Server message gating & tracking
convex/messages.ts
Integrated Autumn checks to gate user message creation by plan; throws on limit; tracks usage post-insert.
Client chat feature gating
src/components/ChatInterface.tsx
Added Autumn-based pre-submit feature check with TTL cache; triggers checkout dialog on denial; refreshes customer state after messages; added error handling and toasts.
Pricing checkout (Autumn)
src/components/pricing/CustomPricingTable.tsx
Wired Pro plan to Autumn checkout with retries, toasts, and Sentry tagging; kept fallback non-Autumn flow; added env-based product ID override.
App provider setup
src/main.tsx
Introduced AutumnProvider wrapper with backend URL resolution and bearer token hook; wrapped App in both render branches.
Environment variables
env-template.txt
Added Autumn Billing section with AUTUMN_SECRET_KEY, VITE_AUTUMN_BACKEND_URL, VITE_AUTUMN_PRODUCT_PRO_ID.
Dependencies
package.json
Added dependency: autumn-js ^0.1.11; removed transient cheerio addition; formatting newline.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HTTP Router
  participant Autumn Handler
  participant Clerk
  participant tRPC

  Client->>HTTP Router: Request /api/autumn/* (any routable method)
  HTTP Router->>Autumn Handler: Dispatch with Authorization header
  Autumn Handler->>Autumn Handler: Rate-limit per token
  alt Bearer token present
    Autumn Handler->>Clerk: Verify JWT
    Clerk-->>Autumn Handler: {id,email}/error
  end
  Autumn Handler-->>Client: { customerId, customerData }
  Client->>HTTP Router: Request /trpc/*
  HTTP Router->>tRPC: fetchRequestHandler with context
  tRPC-->>Client: Response
Loading
sequenceDiagram
  participant User
  participant Chat UI
  participant Autumn SDK
  participant Backend
  participant Autumn Service

  User->>Chat UI: Submit message
  Chat UI->>Autumn SDK: checkFeature('messages')
  alt Allowed (cached or fresh)
    Chat UI->>Backend: create user message
    Backend-->>Chat UI: message created
    Chat UI->>Autumn SDK: refetchCustomer
    Chat UI->>Backend: get assistant reply
    Backend-->>Chat UI: assistant message
    Chat UI->>Autumn SDK: refetchCustomer
  else Denied
    Chat UI->>Autumn SDK: checkout(productId=pro)
    Autumn SDK-->>Autumn Service: Open checkout
    Autumn Service-->>Chat UI: Result (success/fail)
  end
Loading
sequenceDiagram
  participant User
  participant Pricing UI
  participant Autumn SDK
  participant Sentry

  User->>Pricing UI: Click Pro checkout
  Pricing UI->>Autumn SDK: checkout(productId from env)
  alt Success
    Autumn SDK-->>Pricing UI: Checkout initiated
  else Failure
    Autumn SDK-->>Pricing UI: Error
    Pricing UI->>Sentry: captureException + tags
    Pricing UI-->>User: Toast error
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

A hop, a skip, new plans take flight,
Autumn leaves guide checks just right.
Tokens whisper, limits sing,
Pro unlocks with a checkout spring.
Messages counted, gates aligned—
I thump in joy: code intertwined! 🐇🍂


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 875dde0 and 12300e5.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • convex/http.ts (2 hunks)
  • convex/messages.ts (3 hunks)
  • env-template.txt (1 hunks)
  • package.json (3 hunks)
  • src/components/ChatInterface.tsx (5 hunks)
  • src/components/pricing/CustomPricingTable.tsx (4 hunks)
  • src/main.tsx (3 hunks)
✨ 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/integrate-app-payments-and-pricing-model-9114

🪧 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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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 12, 2025

Claude finished @otdoges's task —— View job


PR Review: Integrate app payments and pricing model

I've thoroughly reviewed this PR that integrates Autumn billing to enable Free and Pro chat message plans. Here's my comprehensive analysis:

Review Tasks

  • Read repository guidelines (CLAUDE.md)
  • Analyze Convex backend changes (http.ts, messages.ts)
  • Review frontend integration (main.tsx, ChatInterface.tsx)
  • Examine pricing component updates
  • Assess security implications of payment integration
  • Check error handling and type safety
  • Evaluate performance considerations
  • Review dependency changes
  • Provide comprehensive feedback

🔍 Code Quality & Architecture

Strengths

  1. Clean Integration: Autumn.js is properly integrated using the provider pattern with AutumnProvider wrapping the app
  2. Secure Authentication: Proper JWT verification using Clerk's backend verification
  3. Feature Gating: Well-implemented client-side and server-side feature checks for message limits
  4. Type Safety: Good TypeScript usage throughout the integration
  5. Error Handling: Comprehensive error handling with proper user feedback via toasts

⚠️ Areas for Improvement

Security Concerns

  1. Environment Variable Exposure (src/main.tsx:62):

    const backendUrl = import.meta.env.VITE_AUTUMN_BACKEND_URL || import.meta.env.VITE_CONVEX_URL;
    • Good: Using fallback to Convex URL
    • ⚠️ Concern: Ensure VITE_AUTUMN_BACKEND_URL doesn't accidentally expose sensitive endpoints
  2. Token Security (convex/http.ts:72-95):

    identify: async ({ request }) => {
      const authHeader = request.headers.get('authorization') || request.headers.get('Authorization');
      const token = typeof authHeader === 'string' && authHeader.toLowerCase().startsWith('bearer ')
        ? authHeader.slice(7).trim()
        : undefined;
    • Good: Proper bearer token extraction
    • ⚠️ Recommendation: Add token expiration validation and rate limiting

Performance Considerations

  1. Feature Check Frequency (src/components/ChatInterface.tsx:413-422):

    const { data } = checkFeature({ featureId: 'messages' });
    • ⚠️ Concern: Feature check on every message submit - consider caching
    • Recommendation: Implement feature check caching with TTL
  2. Multiple API Calls (src/components/ChatInterface.tsx:491, 622):

    await refetchCustomer();
    • ⚠️ Concern: Multiple customer refetches could impact performance
    • Recommendation: Optimize refetch strategy

Error Handling

  1. Feature Gate Fallback (src/components/ChatInterface.tsx:413-422):

    try {
      const { data } = checkFeature({ featureId: 'messages' });
      if (!data?.allowed) {
        // Handle limit exceeded
      }
    } catch {}
    • ⚠️ Concern: Empty catch block silently ignores errors
    • Recommendation: Log errors for debugging
  2. Checkout Error Recovery (src/components/pricing/CustomPricingTable.tsx:127):

    await checkout({ productId: 'pro', dialog: CheckoutDialog });
    • Good: Proper error handling with Sentry integration
    • ⚠️ Recommendation: Add retry mechanism for transient failures

🛡️ Security Assessment

Backend Security (convex/http.ts)

  • JWT Verification: Proper Clerk JWT verification implementation
  • Authentication Context: Secure user identification in Autumn handler
  • Route Protection: All Autumn routes properly protected

Message Security (convex/messages.ts)

  • Feature Gating: Server-side validation before message creation
  • User Context: Proper user identification and ownership checks
  • Rate Limiting: Existing rate limiting preserved

Frontend Security

  • Token Management: Secure token handling with useAuthToken
  • ⚠️ XSS Prevention: Ensure all Autumn response data is properly sanitized

📊 Dependency Analysis (package.json)

New Dependencies

  • autumn-js@^0.1.11: Legitimate billing integration library
  • Total bundle impact: Minimal, appropriate for billing functionality

🧪 Test Coverage Recommendations

The PR lacks test coverage for critical billing flows:

  1. Unit Tests Needed:

    • Feature gate logic in ChatInterface
    • Autumn authentication flow
    • Error handling scenarios
  2. Integration Tests Needed:

    • End-to-end checkout flow
    • Message limit enforcement
    • Error recovery scenarios

🚀 Performance Optimization Suggestions

  1. Feature Check Caching:

    // Consider implementing:
    const { data, isLoading } = useFeatureCheck('messages', { 
      staleTime: 30000,  // 30s cache
      refetchOnWindowFocus: false 
    });
  2. Lazy Loading: Consider lazy loading the checkout dialog to reduce initial bundle size

  3. Error Boundary: Add error boundary around Autumn components for graceful degradation


🔧 Implementation Issues

Critical Issues

None identified - the implementation follows security best practices.

Minor Issues

  1. Hardcoded Product ID (src/components/ChatInterface.tsx:418):

    await checkout({ productId: 'pro', dialog: CheckoutDialog });
    • Recommendation: Consider making product IDs configurable
  2. Mixed Billing Systems: The pricing component still has fallback Stripe logic

    • Recommendation: Clean up unused Stripe integration code if fully migrating to Autumn

📝 Documentation Needs

  1. Environment Setup: The env-template.txt is well documented ✅
  2. API Documentation: Consider adding JSDoc comments for Autumn integration functions
  3. Error Codes: Document Autumn-specific error codes and their meanings

Final Assessment

This is a well-implemented integration with proper security considerations. The code follows established patterns and maintains the existing security posture.

Approval Recommendation: ✅ APPROVE

Rationale:

  • Security best practices followed
  • Proper error handling implemented
  • Clean architecture and code organization
  • No breaking changes to existing functionality
  • Comprehensive billing integration

Before Merging:

  1. Consider implementing feature check caching for performance
  2. Add unit tests for critical billing paths
  3. Remove unused Stripe code if fully migrating to Autumn
  4. Ensure proper monitoring is in place for billing events

@Jackson57279 Jackson57279 marked this pull request as ready for review August 12, 2025 21:40
@cursor
Copy link

cursor bot commented Aug 12, 2025

🚨 Bugbot Trial Expired

Your Bugbot trial has expired. Please purchase a license in the Cursor dashboard to continue using Bugbot.

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

const root = createRoot(document.getElementById('root')!);

function AutumnWrapper({ children }: { children: React.ReactNode }) {

Check warning

Code scanning / ESLint

Fast refresh only works when a file has exports. Move your component(s) to a separate file. Warning

Fast refresh only works when a file has exports. Move your component(s) to a separate file.
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