logo

Use Cases & Implementation Patterns

Common use cases and implementation patterns for the Cherry.tv Affiliates API

Use Cases & Implementation Patterns

This page outlines common use cases for the Cherry.tv Affiliates API and provides implementation guidance for each scenario.

1. Model Directory Website

Build a comprehensive directory of models with search and filtering capabilities.

Features to Implement

  • Model Listings: Display paginated lists of models
  • Advanced Filtering: Filter by gender, tags, status, language
  • Search Functionality: Search by username or model name
  • Real-time Status: Show online/offline status
  • Affiliate Tracking: Include affiliate parameters in all links

Implementation Strategy

class ModelDirectory {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.cache = new Map();
  }
  
  async searchModels(filters = {}, page = 1, limit = 20) {
    const offset = (page - 1) * limit;
    
    const params = {
      ...filters,
      limit,
      offset,
      order: 'viewer',
      sort: 'desc'
    };
    
    return await this.getModels(params);
  }
  
  async getFeaturedModels() {
    return await this.getModels({
      status: 1, // Online only
      limit: 12,
      order: 'viewer',
      sort: 'desc'
    });
  }
  
  async getModelsByCategory(category) {
    return await this.getModels({
      category,
      status: 1,
      limit: 50
    });
  }
}

UI Components

  • Model cards with avatar, name, viewer count, tags
  • Filter sidebar with checkboxes and dropdowns
  • Pagination controls
  • Search bar with autocomplete
  • "Featured Models" section

2. Live Status Dashboard

Create a real-time dashboard showing model activity and statistics.

Features to Implement

  • Live Model Count: Total online models by category
  • Top Performers: Models with highest viewer counts
  • Activity Trends: Track model activity over time
  • Status Monitoring: Monitor specific models' online status

Implementation Example

class LiveDashboard {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.updateInterval = 30000; // 30 seconds
    this.isRunning = false;
  }
  
  async getOnlineStats() {
    const [females, males, couples, trans] = await Promise.all([
      this.getModels({ gender: 0, status: 1 }),
      this.getModels({ gender: 1, status: 1 }),
      this.getModels({ gender: 2, status: 1 }),
      this.getModels({ gender: 3, status: 1 })
    ]);
    
    return {
      total: females.length + males.length + couples.length + trans.length,
      females: females.length,
      males: males.length,
      couples: couples.length,
      trans: trans.length
    };
  }
  
  async getTopPerformers(limit = 10) {
    return await this.getModels({
      status: 1,
      limit,
      order: 'viewer',
      sort: 'desc'
    });
  }
  
  startLiveUpdates(callback) {
    this.isRunning = true;
    
    const update = async () => {
      if (!this.isRunning) return;
      
      try {
        const [stats, topPerformers] = await Promise.all([
          this.getOnlineStats(),
          this.getTopPerformers()
        ]);
        
        callback({ stats, topPerformers, timestamp: new Date() });
      } catch (error) {
        console.error('Dashboard update failed:', error);
      }
      
      setTimeout(update, this.updateInterval);
    };
    
    update();
  }
  
  stopLiveUpdates() {
    this.isRunning = false;
  }
}

3. Personalized Recommendations

Implement a recommendation system based on user preferences and viewing history.

Features to Implement

  • Preference Learning: Track user interactions with models
  • Similar Models: Find models with similar tags/categories
  • Trending Models: Show models gaining popularity
  • Personalized Feeds: Custom model lists per user

Implementation Pattern

class RecommendationEngine {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.userPreferences = new Map();
  }
  
  trackUserInteraction(userId, modelId, interactionType) {
    if (!this.userPreferences.has(userId)) {
      this.userPreferences.set(userId, {
        viewedModels: new Set(),
        preferredTags: new Map(),
        preferredGenders: new Map()
      });
    }
    
    const prefs = this.userPreferences.get(userId);
    prefs.viewedModels.add(modelId);
    
    // Update preferences based on interaction
    // Implementation depends on your tracking needs
  }
  
  async getRecommendations(userId, limit = 20) {
    const prefs = this.userPreferences.get(userId);
    if (!prefs) {
      // Return popular models for new users
      return await this.getModels({
        status: 1,
        limit,
        order: 'viewer',
        sort: 'desc'
      });
    }
    
    // Get models based on user preferences
    const topTags = Array.from(prefs.preferredTags.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, 3)
      .map(([tag]) => tag);
    
    if (topTags.length > 0) {
      return await this.getModels({
        tag: topTags[0], // Use most preferred tag
        status: 1,
        limit
      });
    }
    
    return await this.getModels({ status: 1, limit });
  }
}

Manage and track affiliate links with custom parameters.

Features to Implement

  • Link Generation: Create affiliate links with tracking parameters
  • Campaign Tracking: Track different marketing campaigns
  • Performance Analytics: Monitor click-through rates
  • A/B Testing: Test different link formats

Implementation Example

class AffiliateManager {
  constructor(apiKey, affiliateId) {
    this.apiKey = apiKey;
    this.affiliateId = affiliateId;
  }
  
  generateAffiliateLink(modelUsername, campaign = 'default', medium = 'web') {
    const baseUrl = `https://cherry.tv/${modelUsername}`;
    const params = new URLSearchParams({
      ref_affid: this.affiliateId,
      ref_oid: this.generateTrackingId(),
      utm_campaign: campaign,
      utm_medium: medium,
      utm_source: 'affiliate'
    });
    
    return `${baseUrl}?${params.toString()}`;
  }
  
  generateTrackingId() {
    return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
  
  async getModelsWithAffiliateLinks(filters = {}) {
    const models = await this.getModels(filters);
    
    return models.map(modelData => ({
      ...modelData,
      customAffiliateLink: this.generateAffiliateLink(
        modelData.model.username,
        filters.campaign || 'api'
      )
    }));
  }
}

5. Mobile App Integration

Integrate the API into mobile applications for iOS and Android.

React Native Example

import AsyncStorage from '@react-native-async-storage/async-storage';

class MobileAPIClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.cherry.tv';
  }
  
  async getModelsWithCache(filters = {}) {
    const cacheKey = `models_${JSON.stringify(filters)}`;
    
    try {
      // Try to get from cache first
      const cached = await AsyncStorage.getItem(cacheKey);
      if (cached) {
        const { data, timestamp } = JSON.parse(cached);
        // Use cache if less than 5 minutes old
        if (Date.now() - timestamp < 300000) {
          return data;
        }
      }
    } catch (error) {
      console.log('Cache read error:', error);
    }
    
    // Fetch fresh data
    const models = await this.getModels(filters);
    
    // Cache the result
    try {
      await AsyncStorage.setItem(cacheKey, JSON.stringify({
        data: models,
        timestamp: Date.now()
      }));
    } catch (error) {
      console.log('Cache write error:', error);
    }
    
    return models;
  }
  
  async getModels(filters = {}) {
    const params = new URLSearchParams({
      apiKey: this.apiKey,
      ...filters
    });
    
    const response = await fetch(`${this.baseUrl}/affiliates/v1/models?${params}`);
    
    if (!response.ok) {
      throw new Error(`API Error: ${response.status}`);
    }
    
    return await response.json();
  }
}

6. Webhook Integration

Set up webhooks to receive real-time notifications about model status changes.

Webhook Handler Example

const express = require('express');
const app = express();

app.use(express.json());

// Webhook endpoint
app.post('/webhooks/model-status', (req, res) => {
  const { modelId, status, timestamp } = req.body;
  
  // Process the status change
  handleModelStatusChange(modelId, status, timestamp);
  
  res.status(200).json({ received: true });
});

async function handleModelStatusChange(modelId, status, timestamp) {
  // Update local cache
  // Send push notifications
  // Update real-time dashboard
  // Log analytics event
  
  console.log(`Model ${modelId} status changed to ${status} at ${timestamp}`);
}

7. SEO-Optimized Model Pages

Create SEO-friendly pages for individual models.

Implementation Strategy

// Next.js example with SSR
export async function getServerSideProps({ params, query }) {
  const { username } = params;
  const apiKey = process.env.CHERRY_TV_API_KEY;
  
  try {
    // Get model info server-side for SEO
    const modelInfo = await getModelByUsername(username, apiKey);
    
    return {
      props: {
        modelInfo,
        affiliateParams: {
          ref_affid: query.ref_affid || '',
          ref_oid: query.ref_oid || '',
          utm_campaign: query.utm_campaign || ''
        }
      }
    };
  } catch (error) {
    return {
      notFound: true
    };
  }
}

export default function ModelPage({ modelInfo, affiliateParams }) {
  const model = modelInfo.model;
  
  return (
    <>
      <Head>
        <title>{model.name} - Live Cam Show | Cherry.tv</title>
        <meta name="description" content={`Watch ${model.name}'s live cam show. ${model.about}`} />
        <meta property="og:title" content={`${model.name} - Live Cam Show`} />
        <meta property="og:image" content={model.avatar} />
      </Head>
      
      <div className="model-page">
        <img src={model.avatar} alt={model.name} />
        <h1>{model.name}</h1>
        <p>{model.about}</p>
        
        <div className="model-stats">
          <span>Age: {model.age}</span>
          <span>Followers: {model.followers}</span>
          <span>Level: {model.level}</span>
        </div>
        
        <div className="model-tags">
          {model.tags.map(tag => (
            <span key={tag} className="tag">#{tag}</span>
          ))}
        </div>
        
        <a 
          href={generateAffiliateLink(model.username, affiliateParams)}
          className="watch-now-btn"
        >
          Watch Now
        </a>
      </div>
    </>
  );
}

Best Practices Summary

  1. Caching: Implement intelligent caching to reduce API calls
  2. Error Handling: Always handle API errors gracefully
  3. Rate Limiting: Respect API limits and implement backoff strategies
  4. Security: Never expose API keys in client-side code
  5. Performance: Use pagination and filtering to optimize data transfer
  6. User Experience: Provide loading states and error messages
  7. Analytics: Track user interactions for optimization
  8. SEO: Use server-side rendering for public pages
  9. Mobile: Optimize for mobile devices and slow connections
  10. Compliance: Ensure compliance with relevant regulations and platform policies

These use cases and patterns should provide a solid foundation for building applications with the Cherry.tv Affiliates API.