TellaAI
API Reference/User Management

Referral API

Referral system endpoints for managing referral codes, rewards, and account credits

Referral API

The Referral API manages the complete referral system including referral codes, reward processing, account credits, and withdrawal functionality. Users can earn rewards by referring friends and manage their account credit balance.

Referral System Overview

The referral system allows users to:

  • Generate unique referral codes
  • Share codes with friends
  • Earn rewards when friends sign up and start trials
  • Manage account credits and withdrawals
  • Track referral progress and leaderboards

Data Models

ReferralCode Model

  • id: Unique identifier (string)
  • code: Unique referral code (string, e.g., "SP575988")
  • userId: Owner of the referral code (string)
  • isActive: Whether the code is active (boolean)
  • usageCount: Number of times code has been used (number)
  • maxUsage: Optional usage limit (number)
  • createdAt: Code creation date (ISO datetime)
  • updatedAt: Last update date (ISO datetime)

Referral Model

  • id: Unique identifier (string)
  • referrerId: User who shared the code (string)
  • refereeId: User who used the code (string)
  • referralCodeId: Associated referral code (string)
  • status: Referral status (PENDING, TRIAL_STARTED, COMPLETED, EXPIRED, CANCELLED)
  • signupDate: When referee signed up (ISO datetime)
  • trialStartDate: When referee started trial (ISO datetime, optional)
  • rewardClaimedDate: When rewards were claimed (ISO datetime, optional)
  • createdAt: Referral creation date (ISO datetime)
  • updatedAt: Last update date (ISO datetime)

ReferralReward Model

  • id: Unique identifier (string)
  • referralId: Associated referral (string)
  • rewardType: Type of reward (CASH, FREE_MONTH)
  • cashAmount: Cash reward amount (number, optional)
  • freeMonths: Free months reward (number, optional)
  • accountCredit: Amount credited to account (number, optional)
  • withdrawalRequested: Whether withdrawal was requested (boolean)
  • withdrawalCompleted: When withdrawal was completed (ISO datetime, optional)
  • userId: Reward recipient (string)
  • status: Reward status (PENDING, PROCESSING, COMPLETED, FAILED, EXPIRED)
  • claimedAt: When reward was claimed (ISO datetime, optional)
  • expiresAt: When reward expires (ISO datetime, optional)
  • stripePaymentId: Stripe payment ID for cash rewards (string, optional)
  • subscriptionExtension: Subscription extension details (string, optional)
  • createdAt: Reward creation date (ISO datetime)
  • updatedAt: Last update date (ISO datetime)

Endpoints

All referral endpoints require authentication and are scoped to the authenticated user.

Get Referral Dashboard

Retrieve comprehensive referral dashboard data including progress, rewards, and leaderboard.

GET /api/referral/dashboard

Response (200)

{
  "success": true,
  "data": {
    "totalEarned": 25.0,
    "earnedThisWeek": 10.0,
    "pendingAmount": 5.0,
    "leaderboard": [
      {
        "name": "John Doe",
        "amount": 50.0
      },
      {
        "name": "Jane Smith", 
        "amount": 35.0
      }
    ],
    "referralProgress": {
      "totalReferrals": 5,
      "goal": 10,
      "activeTrials": 3,
      "pending": 2,
      "recentReferrals": [
        {
          "initials": "JS",
          "name": "Jane Smith",
          "status": "Started trial",
          "date": "2024-01-15T10:30:00.000Z",
          "amount": 5.0,
          "pending": false
        }
      ]
    },
    "referralCode": "SP575988",
    "accountCredit": 15.0,
    "rewardsBreakdown": {
      "user": "You get: $5 cash OR 1 month free",
      "friend": "Your friend gets: 1 month free"
    },
    "howItWorks": [
      "Share your referral code with friends",
      "They sign up for Sophie using your code",
      "When they start their trial, you both get rewarded",
      "Choose between $5 cash or 1 month of Sophie Premium"
    ]
  }
}

Errors:

  • 401: Authentication required

Create Referral on Signup

Create a referral when a new user signs up using a referral code.

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

{
  "code": "SP575988"
}

Request Body Parameters

  • code: Referral code to use (required, string)

Response (200)

{
  "success": true,
  "data": {
    "referralId": "ref_abc123",
    "referrerId": "user_123",
    "refereeId": "user_456",
    "status": "PENDING",
    "signupDate": "2024-01-15T10:30:00.000Z"
  }
}

Errors:

  • 400: Invalid or inactive referral code
  • 400: Cannot use your own referral code
  • 400: Referral already exists
  • 401: Authentication required

Update Referral on Trial Start

Update referral status when a referred user starts their trial.

POST /api/referral/trial-start

Response (200)

{
  "success": true,
  "data": {
    "referralId": "ref_abc123",
    "rewards": [
      {
        "id": "reward_123",
        "rewardType": "CASH",
        "cashAmount": 5.0,
        "status": "PENDING",
        "userId": "user_123"
      },
      {
        "id": "reward_456", 
        "rewardType": "FREE_MONTH",
        "freeMonths": 1,
        "status": "PENDING",
        "userId": "user_456"
      }
    ]
  }
}

Errors:

  • 400: No pending referral found
  • 401: Authentication required

Process Reward

Process a referral reward (cash or free month).

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

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

Request Body Parameters

  • rewardId: Reward ID to process (required, string)
  • type: Reward type to process (required, "CASH" or "FREE_MONTH")

Response (200)

{
  "success": true,
  "message": "Reward processed successfully"
}

Errors:

  • 400: Reward not found
  • 400: Reward is not pending
  • 400: User does not have an active Stripe subscription (for FREE_MONTH)
  • 401: Authentication required

Request Withdrawal

Request withdrawal of account credits to Stripe payout.

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

{
  "amount": 25.0
}

Request Body Parameters

  • amount: Amount to withdraw (required, number, minimum: 10)

Response (200)

{
  "success": true,
  "message": "Withdrawal request submitted successfully",
  "data": {
    "withdrawalId": "reward_withdrawal_123",
    "amount": 25.0,
    "status": "PROCESSING",
    "stripePaymentId": "pi_1234567890"
  }
}

Errors:

  • 400: Insufficient account credit
  • 400: Minimum withdrawal amount is $10
  • 401: Authentication required

Get Account Credit Info

Retrieve account credit balance and withdrawal history.

GET /api/referral/account-credits

Response (200)

{
  "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"
      }
    ]
  }
}

Errors:

  • 401: Authentication required

Reward System

Reward Types

Cash Rewards

  • Amount: $5.00 per successful referral
  • Processing: Added to user's account credit balance
  • Withdrawal: Can be withdrawn via Stripe payout (minimum $10)
  • Status Flow: PENDING → PROCESSING → COMPLETED

Free Month Rewards

  • Amount: 1 month free subscription
  • Processing: Extends active subscription by 1 month
  • Requirements: User must have active Stripe subscription
  • Status Flow: PENDING → PROCESSING → COMPLETED

Reward Processing

// Process cash reward
await fetch('/api/referral/process-reward', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    rewardId: 'reward_123',
    type: 'CASH'
  })
});

// Process free month reward
await fetch('/api/referral/process-reward', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    rewardId: 'reward_456',
    type: 'FREE_MONTH'
  })
});

Account Credits & Withdrawals

Account Credit System

  • Earning: Cash rewards are added to account credit balance
  • Balance: Tracked in user's accountCredit field
  • Withdrawal: Minimum $10 withdrawal via Stripe payout
  • History: All withdrawals and pending rewards tracked

Withdrawal Process

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

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

Integration with Stripe

Payment Processing

  • Account Credits: Cash rewards added to user's account balance
  • Stripe Payouts: Withdrawals processed via Stripe Connect
  • Subscription Extensions: Free months extend active subscriptions
  • Payment Tracking: All payments tracked with Stripe payment IDs

Stripe Requirements

  • Customer ID: Users must have stripeCustomerId for payouts
  • Active Subscription: Required for free month rewards
  • Webhook Handling: Stripe webhooks handle payment confirmations

Notification System

Referral Notifications

  • Referral Created: Notifies referrer when someone uses their code
  • Trial Started: Notifies both users when trial begins
  • Reward Processed: Confirms successful reward processing
  • Withdrawal Status: Updates on withdrawal processing

Notification Types

// Referral milestone notifications
notifyReferralMilestone(userId, milestone);

// Trial start notifications  
notifyTrialStarted(referrerId, refereeId, refereeName);

// Reward processing notifications
notifyCashRewardProcessed(userId, amount);
notifyFreeMonthRewardProcessed(userId, months);

// Withdrawal notifications
notifyWithdrawalProcessed(userId, amount);

Security & Validation

Referral Code Validation

  • Uniqueness: Each user has one active referral code
  • Format: Alphanumeric codes (e.g., "SP575988")
  • Usage Limits: Optional maximum usage per code
  • Self-Referral Prevention: Users cannot use their own codes

Reward Security

  • Ownership: Users can only process their own rewards
  • Status Validation: Only pending rewards can be processed
  • Amount Validation: Withdrawal minimums enforced
  • Stripe Integration: Secure payment processing

Data Protection

  • User Isolation: Users can only access their own referral data
  • Audit Trail: All referral and reward events logged
  • Session Validation: All endpoints require valid authentication
  • Rate Limiting: API endpoints protected against abuse

Error Handling

Common Error Codes

  • INVALID_CODE: Referral code not found or inactive
  • SELF_REFERRAL: User attempted to use own code
  • DUPLICATE_REFERRAL: Referral already exists
  • NO_REFERRAL: No pending referral found
  • NOT_FOUND: Reward not found
  • NOT_PENDING: Reward is not in pending status
  • INSUFFICIENT_CREDIT: Insufficient account credit for withdrawal
  • MIN_AMOUNT: Withdrawal amount below minimum
  • PROCESSING_FAILED: Reward processing failed

Error Response Format

{
  "success": false,
  "error": "Invalid referral code",
  "code": "INVALID_CODE"
}

Best Practices

Frontend Integration

// Get dashboard data on page load
const dashboard = await fetch('/api/referral/dashboard');

// Process rewards when user clicks claim
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();
};

// Handle withdrawals
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

// Create referral on user signup
const referralResult = await ReferralService.createReferralOnSignup(
  prisma, userId, referralCode, notificationService
);

// Update referral when trial starts
const trialResult = await ReferralService.updateReferralOnTrialStart(
  prisma, userId, notificationService
);

// Process rewards
const rewardResult = await ReferralService.processReward(
  prisma, userId, rewardId, type, notificationService
);

Monitoring & Analytics

  • Referral Tracking: Monitor referral conversion rates
  • Reward Processing: Track reward processing success rates
  • Withdrawal Analytics: Monitor withdrawal patterns and amounts
  • User Engagement: Track referral dashboard usage
  • Error Monitoring: Monitor API error rates and types