TellaAI
API Reference/User Management

Payment API

Payment processing and subscription management using Better Auth's Stripe integration

Payment API

SophieAI uses Better Auth's Stripe integration for secure payment processing and subscription management. This guide covers the payment system architecture and how it integrates with the referral system.

Payment System Overview

The payment system provides:

  • Subscription Management: Automatic Stripe customer creation and subscription handling
  • Referral Rewards: Cash rewards and subscription extensions via Stripe
  • Account Credits: User account credit balance for referral rewards
  • Withdrawal Processing: Stripe payouts for account credit withdrawals
  • Webhook Handling: Automatic payment confirmation and subscription updates

Better Auth Stripe Integration

SophieAI leverages Better Auth's built-in Stripe plugin for secure payment processing:

Configuration

// From backend/src/lib/auth.ts
import { stripe } from "@better-auth/stripe";

export const auth = betterAuth({
  // ... other config
  plugins: [
    openAPI(),
    stripe({
      stripeClient,
      stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
      createCustomerOnSignUp: true,
    }),
  ],
});

Automatic Features

  • Customer Creation: Stripe customers automatically created on user signup
  • Session Management: Secure session handling with payment integration
  • Webhook Processing: Automatic webhook handling for payment events
  • Subscription Tracking: Built-in subscription status management

Payment Models

User Payment Fields

  • stripeCustomerId: Stripe customer identifier (string, optional)
  • accountCredit: User's account credit balance (number, default: 0)

Subscription Model

  • id: Unique identifier (string)
  • plan: Subscription plan name (string)
  • referenceId: Internal reference ID (string)
  • stripeCustomerId: Stripe customer ID (string)
  • stripeSubscriptionId: Stripe subscription ID (string)
  • status: Subscription status (string)
  • periodStart: Billing period start (ISO datetime)
  • periodEnd: Billing period end (ISO datetime)
  • cancelAtPeriodEnd: Whether to cancel at period end (boolean)
  • seats: Number of seats/licenses (number)
  • trialStart: Trial start date (ISO datetime, optional)
  • trialEnd: Trial end date (ISO datetime, optional)
  • userId: Associated user (string)
  • createdAt: Creation date (ISO datetime)
  • updatedAt: Last update date (ISO datetime)

Referral Payment Integration

Cash Rewards Processing

When users earn referral cash rewards:

  1. Reward Creation: Cash rewards added to user's accountCredit balance
  2. Account Tracking: Balance tracked in User.accountCredit field
  3. Withdrawal Request: Users can request withdrawals via Stripe payouts
  4. Payment Processing: Stripe handles secure payment distribution

Free Month Rewards

When users earn free month rewards:

  1. Subscription Extension: Active subscription extended by 1 month
  2. Stripe Integration: Uses Stripe API to modify subscription period
  3. Trial Extension: Extends trial_end date on subscription
  4. No Proration: Extensions applied without additional charges

Payment Endpoints

Referral Reward Processing

Process Cash Reward

POST /api/referral/process-reward
Content-Type: application/json

{
  "rewardId": "reward_123",
  "type": "CASH"
}

Process:

  1. Validates reward ownership and status
  2. Adds cash amount to user's accountCredit balance
  3. Updates reward status to COMPLETED
  4. Sends confirmation notification

Process Free Month Reward

POST /api/referral/process-reward
Content-Type: application/json

{
  "rewardId": "reward_456",
  "type": "FREE_MONTH"
}

Process:

  1. Validates user has active Stripe subscription
  2. Extends subscription period by 30 days
  3. Updates subscription trial_end date
  4. Sends confirmation notification

Account Credit Withdrawal

Request Withdrawal

POST /api/referral/withdraw
Content-Type: application/json

{
  "amount": 25.0
}

Process:

  1. Validates sufficient account credit balance
  2. Deducts amount from accountCredit
  3. Creates Stripe payout to user's connected account
  4. Tracks withdrawal status and payment ID

Get Account Credit Info

GET /api/referral/account-credits

Response:

{
  "success": true,
  "data": {
    "accountCredit": 35.0,
    "withdrawals": [
      {
        "id": "reward_withdrawal_123",
        "amount": 25.0,
        "status": "COMPLETED",
        "requestedAt": "2024-01-10T15:30:00.000Z",
        "completedAt": "2024-01-11T09:15:00.000Z"
      }
    ],
    "pendingRewards": [
      {
        "id": "reward_456",
        "amount": 5.0,
        "createdAt": "2024-01-15T10:30:00.000Z"
      }
    ]
  }
}

Stripe Integration Details

Customer Management

  • Automatic Creation: Stripe customers created on user signup via Better Auth
  • Customer ID Storage: stripeCustomerId stored in User model
  • Payment Methods: Better Auth handles payment method management
  • Subscription Linking: Subscriptions linked to Stripe customers

Webhook Processing

Better Auth's Stripe plugin automatically handles:

  • Payment Confirmations: Successful payment notifications
  • Subscription Updates: Status changes and renewals
  • Failed Payments: Payment failure notifications
  • Refund Processing: Refund confirmations

Security Features

  • Webhook Verification: All webhooks verified with secret
  • Customer Isolation: Users can only access their own payment data
  • Secure Tokens: Payment tokens handled securely by Better Auth
  • PCI Compliance: Stripe handles PCI compliance requirements

Environment Configuration

Required Environment Variables

# Stripe Configuration
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...

# Better Auth Configuration
BETTER_AUTH_URL=http://localhost:5000
CLIENT_ORIGIN=http://localhost:3000

Stripe Account Setup

  1. Create Stripe Account: Set up Stripe account for payment processing
  2. Configure Webhooks: Set up webhook endpoints for payment events
  3. Get API Keys: Obtain publishable and secret keys
  4. Test Mode: Use test keys for development

Payment Flow Examples

Referral Cash Reward Flow

// 1. User earns referral reward
const reward = await ReferralService.processReward(
  prisma, userId, rewardId, 'CASH', notificationService
);

// 2. Cash added to account credit
// User.accountCredit += 5.0

// 3. User requests withdrawal
const withdrawal = await ReferralService.requestWithdrawal(
  prisma, userId, 25.0, notificationService
);

// 4. Stripe payout processed
// Stripe payout created to user's connected account

Free Month Reward Flow

// 1. User earns free month reward
const reward = await ReferralService.processReward(
  prisma, userId, rewardId, 'FREE_MONTH', notificationService
);

// 2. Subscription extended
// Stripe subscription trial_end extended by 30 days

// 3. User gets free month
// No additional charges for the extended period

Error Handling

Common Payment Errors

  • INSUFFICIENT_CREDIT: User doesn't have enough account credit
  • MIN_AMOUNT: Withdrawal amount below $10 minimum
  • NO_SUBSCRIPTION: User doesn't have active subscription for free months
  • STRIPE_ERROR: Stripe API error during payment processing
  • WEBHOOK_FAILURE: Webhook verification or processing failure

Error Response Format

{
  "success": false,
  "error": "Insufficient account credit",
  "code": "INSUFFICIENT_CREDIT"
}

Best Practices

Frontend Integration

// Check account credit balance
const creditInfo = await fetch('/api/referral/account-credits');

// Process rewards
const processReward = async (rewardId, type) => {
  const response = await fetch('/api/referral/process-reward', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ rewardId, type })
  });
  return response.json();
};

// Request withdrawal
const requestWithdrawal = async (amount) => {
  const response = await fetch('/api/referral/withdraw', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ amount })
  });
  return response.json();
};

Backend Integration

// Better Auth handles most payment logic automatically
// Custom payment logic for referral rewards

// Process cash reward
const cashReward = await ReferralService.processReward(
  prisma, userId, rewardId, 'CASH', notificationService
);

// Process free month reward
const freeMonthReward = await ReferralService.processReward(
  prisma, userId, rewardId, 'FREE_MONTH', notificationService
);

// Handle withdrawal
const withdrawal = await ReferralService.requestWithdrawal(
  prisma, userId, amount, notificationService
);

Monitoring & Analytics

Payment Metrics

  • Referral Conversion: Track referral to reward conversion rates
  • Withdrawal Patterns: Monitor withdrawal amounts and frequencies
  • Payment Success: Track successful vs failed payment processing
  • Subscription Extensions: Monitor free month reward usage

Stripe Dashboard

  • Payment Analytics: Use Stripe dashboard for payment insights
  • Webhook Monitoring: Monitor webhook delivery and processing
  • Customer Analytics: Track customer payment behavior
  • Revenue Tracking: Monitor subscription revenue and referral payouts

Security Considerations

Payment Security

  • Stripe Compliance: All payments processed through PCI-compliant Stripe
  • Webhook Verification: All webhooks verified with secret
  • Customer Isolation: Users can only access their own payment data
  • Secure Storage: Payment tokens never stored in application database

Data Protection

  • Minimal Data Storage: Only necessary payment metadata stored
  • Encrypted Communication: All payment API calls use HTTPS
  • Audit Trail: All payment events logged for security
  • Access Control: Payment endpoints require authentication

Integration with Better Auth

Automatic Features

Better Auth's Stripe integration provides:

  • Customer Management: Automatic Stripe customer creation
  • Session Security: Secure session handling with payment context
  • Webhook Processing: Automatic webhook event handling
  • Subscription Management: Built-in subscription status tracking

Custom Extensions

SophieAI extends Better Auth's functionality with:

  • Referral Rewards: Custom reward processing logic
  • Account Credits: User account credit balance system
  • Withdrawal Processing: Custom withdrawal request handling
  • Notification Integration: Payment event notifications

For complete Better Auth Stripe integration documentation, refer to the Better Auth Stripe Plugin Documentation.