> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tensorone.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Subscription Management

> Manage subscriptions, plans, billing cycles, and recurring payments for TensorOne services and resources

Create and manage flexible subscription plans for GPU resources, AI services, storage, and custom service packages with automated billing and usage-based pricing.

## Request Parameters

**subscriptionId** `string`

Specific subscription ID to retrieve. If not provided, returns list of subscriptions.

**status** `array`

Filter by subscription status:

* `active` - Currently active subscriptions
* `trialing` - In trial period
* `past_due` - Payment overdue
* `canceled` - Canceled subscriptions
* `paused` - Temporarily paused
* `pending` - Pending activation
* `expired` - Expired subscriptions

**planType** `array`

Filter by plan types:

* `compute` - GPU compute subscriptions
* `ai_services` - AI service packages
* `storage` - Storage subscriptions
* `bandwidth` - Data transfer plans
* `enterprise` - Enterprise custom plans
* `developer` - Developer tier plans

**billingCycle** `array`

Filter by billing cycles:

* `monthly` - Monthly billing
* `quarterly` - Quarterly billing
* `annual` - Annual billing
* `usage_based` - Usage-based billing

**includeUsage** `boolean` (default: false)

Include current usage statistics for usage-based subscriptions

**includeUpcoming** `boolean` (default: false)

Include information about upcoming charges and renewals

**includeHistory** `boolean` (default: false)

Include subscription history and changes

## Response

**subscriptions** `array`

Array of subscription objects

**Subscription Object**

**subscriptionId** `string`

Unique subscription identifier

**status** `string`

Current subscription status

**plan** `object`

Subscription plan details

**Plan Details**

**planId** `string`

Unique plan identifier

**name** `string`

Plan name

**type** `string`

Plan type

**description** `string`

Plan description

**features** `array`

List of included features

**pricing** `object`

Subscription pricing information

**Pricing Details**

**basePrice** `number`

Base subscription price

**currency** `string`

Pricing currency

**billingCycle** `string`

Billing frequency

**usagePricing** `array`

Usage-based pricing tiers (if applicable)

**discounts** `array`

Applied discounts and promotions

**dates** `object`

Important subscription dates

**Subscription Dates**

**created** `string`

Subscription creation date

**activated** `string`

Activation date

**currentPeriodStart** `string`

Current billing period start

**currentPeriodEnd** `string`

Current billing period end

**nextBilling** `string`

Next billing date

**trialEnd** `string`

Trial period end date (if applicable)

**canceledAt** `string`

Cancellation date (if canceled)

**usage** `object`

Current usage statistics (if requested)

**Usage Statistics**

**currentPeriod** `object`

Usage for current billing period

**quotas** `object`

Resource quotas and limits

**overages** `object`

Usage beyond included amounts

**projectedCost** `number`

Projected cost for current period

**resources** `array`

Included and allocated resources

**Resource Allocation**

**resourceType** `string`

Type of resource (GPU hours, API calls, storage, etc.)

**includedAmount** `number`

Amount included in subscription

**usedAmount** `number`

Amount consumed in current period

**unit** `string`

Unit of measurement

**overagePrice** `number`

Price per unit for usage beyond included amount

**modifications** `array`

Pending modifications to subscription

**Subscription Modification**

**type** `string`

Modification type: `upgrade`, `downgrade`, `addon`, `removal`

**effectiveDate** `string`

When the modification takes effect

**details** `object`

Modification details

**priceImpact** `number`

Price change from modification

**paymentMethod** `object`

Payment method for subscription

**Payment Method**

**methodId** `string`

Payment method identifier

**type** `string`

Payment method type

**displayName** `string`

Payment method display name

**metadata** `object`

Additional subscription metadata

**Metadata**

**tags** `array`

Custom tags for organization

**notes** `string`

Internal notes

**customFields** `object`

Custom field values

**autoRenew** `boolean`

Whether subscription auto-renews

**summary** `object`

Subscription summary statistics

**Subscription Summary**

**totalSubscriptions** `integer`

Total number of subscriptions

**totalMonthlyRecurring** `number`

Total monthly recurring revenue

**totalAnnualRecurring** `number`

Total annual recurring revenue

**byStatus** `object`

Subscription count by status

**byPlanType** `object`

Subscription count by plan type

**upcomingRenewals** `integer`

Subscriptions renewing in next 30 days

**availablePlans** `array`

Available subscription plans

**Available Plan**

**planId** `string`

Plan identifier

**name** `string`

Plan name

**type** `string`

Plan type

**pricing** `object`

Plan pricing details

**features** `array`

Plan features and limits

**popular** `boolean`

Whether this is a popular plan

## Example

```bash cURL
curl -X GET "https://api.tensorone.ai/v2/billing/subscriptions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -G \
  -d "status[]=active&status[]=trialing" \
  -d "includeUsage=true" \
  -d "includeUpcoming=true"
```

```python Python
import requests
from datetime import datetime, timedelta
import calendar

def get_subscriptions(status=None, plan_types=None, include_usage=False):
    params = {
        'includeUsage': include_usage,
        'includeUpcoming': True,
        'includeHistory': False
    }
    
    if status:
        params['status'] = status if isinstance(status, list) else [status]
    if plan_types:
        params['planType'] = plan_types if isinstance(plan_types, list) else [plan_types]
    
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/subscriptions",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params=params
    )
    
    return response.json()

def create_subscription(plan_id, billing_cycle="monthly", trial_days=None):
    """Create a new subscription"""
    subscription_data = {
        "planId": plan_id,
        "billingCycle": billing_cycle,
        "trialDays": trial_days,
        "autoRenew": True,
        "metadata": {
            "source": "api_signup",
            "tags": ["production"]
        }
    }
    
    response = requests.post(
        "https://api.tensorone.ai/v2/billing/subscriptions",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=subscription_data
    )
    
    return response.json()

def modify_subscription(subscription_id, modifications):
    """Modify an existing subscription"""
    response = requests.put(
        f"https://api.tensorone.ai/v2/billing/subscriptions/{subscription_id}",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=modifications
    )
    
    return response.json()

# Get all active subscriptions with usage data
subscriptions_data = get_subscriptions(
    status=["active", "trialing"], 
    include_usage=True
)

print("📋 Subscription Management Dashboard")
print("=" * 38)

# Display summary
summary = subscriptions_data['summary']
print(f"Total Subscriptions: {summary['totalSubscriptions']}")
print(f"Monthly Recurring Revenue: ${summary['totalMonthlyRecurring']:,.2f}")
print(f"Annual Recurring Revenue: ${summary['totalAnnualRecurring']:,.2f}")
print(f"Upcoming Renewals (30 days): {summary['upcomingRenewals']}")

print()

# Status breakdown
print("📊 Subscription Status:")
print("-" * 22)
for status, count in summary['byStatus'].items():
    status_icon = {
        'active': '✅',
        'trialing': '🆓',
        'past_due': '⏰',
        'canceled': '❌',
        'paused': '⏸️',
        'pending': '⏳'
    }.get(status, '⚪')
    
    print(f"{status_icon} {status.title().replace('_', ' ')}: {count}")

print()

# Active subscriptions details
active_subs = [s for s in subscriptions_data['subscriptions'] if s['status'] in ['active', 'trialing']]
print(f"🔄 Active Subscriptions ({len(active_subs)}):")
print("-" * 30)

for sub in active_subs:
    sub_id = sub['subscriptionId']
    plan_name = sub['plan']['name']
    status = sub['status']
    base_price = sub['pricing']['basePrice']
    currency = sub['pricing']['currency']
    billing_cycle = sub['pricing']['billingCycle']
    
    # Calculate days until next billing
    next_billing = datetime.fromisoformat(sub['dates']['nextBilling'].replace('Z', '+00:00'))
    days_until_billing = (next_billing - datetime.now(next_billing.tzinfo)).days
    
    print(f"📦 {plan_name}")
    print(f"   ID: {sub_id}")
    print(f"   Status: {status.title()}")
    print(f"   Price: ${base_price:,.2f} {currency} ({billing_cycle})")
    print(f"   Next Billing: {next_billing.strftime('%Y-%m-%d')} ({days_until_billing} days)")
    
    # Show trial information
    if status == 'trialing' and sub['dates'].get('trialEnd'):
        trial_end = datetime.fromisoformat(sub['dates']['trialEnd'].replace('Z', '+00:00'))
        trial_days_left = (trial_end - datetime.now(trial_end.tzinfo)).days
        print(f"   🆓 Trial ends in {trial_days_left} days")
    
    # Show usage information
    if sub.get('usage'):
        usage = sub['usage']
        current_period = usage.get('currentPeriod', {})
        projected_cost = usage.get('projectedCost', base_price)
        
        print(f"   📊 Projected Cost: ${projected_cost:,.2f}")
        
        # Show resource usage
        if sub.get('resources'):
            print(f"   Resource Usage:")
            for resource in sub['resources']:
                resource_type = resource['resourceType']
                used = resource['usedAmount']
                included = resource['includedAmount']
                unit = resource['unit']
                usage_pct = (used / included * 100) if included > 0 else 0
                
                usage_bar = "█" * min(int(usage_pct / 10), 10)
                usage_color = "🟢" if usage_pct < 80 else "🟡" if usage_pct < 95 else "🔴"
                
                print(f"     {usage_color} {resource_type}: {used:,.1f}/{included:,.1f} {unit} ({usage_pct:.1f}%)")
                print(f"       {usage_bar}")
                
                # Show overage warning
                if used > included:
                    overage = used - included
                    overage_cost = overage * resource.get('overagePrice', 0)
                    print(f"       ⚠️  Overage: {overage:,.1f} {unit} (${overage_cost:,.2f})")
    
    # Show pending modifications
    if sub.get('modifications'):
        print(f"   🔄 Pending Changes:")
        for mod in sub['modifications']:
            mod_type = mod['type']
            effective_date = mod['effectiveDate']
            price_impact = mod.get('priceImpact', 0)
            
            impact_icon = "⬆️" if price_impact > 0 else "⬇️" if price_impact < 0 else "➡️"
            print(f"     {impact_icon} {mod_type.title()} (effective {effective_date})")
            if price_impact != 0:
                print(f"       Price change: {price_impact:+,.2f} {currency}")
    
    print()

# Subscription management functions
def upgrade_subscription(subscription_id, new_plan_id, effective_date=None):
    """Upgrade subscription to a higher tier"""
    modifications = {
        "type": "upgrade",
        "newPlanId": new_plan_id,
        "effectiveDate": effective_date or "immediate",
        "proration": True
    }
    
    result = modify_subscription(subscription_id, modifications)
    return result

def add_subscription_addon(subscription_id, addon_plan_id, quantity=1):
    """Add an addon to existing subscription"""
    modifications = {
        "type": "addon",
        "addonPlanId": addon_plan_id,
        "quantity": quantity,
        "effectiveDate": "immediate"
    }
    
    result = modify_subscription(subscription_id, modifications)
    return result

def pause_subscription(subscription_id, pause_until=None):
    """Pause subscription temporarily"""
    modifications = {
        "type": "pause",
        "pauseUntil": pause_until,  # ISO date or None for indefinite
        "reason": "temporary_pause"
    }
    
    result = modify_subscription(subscription_id, modifications)
    return result

def cancel_subscription(subscription_id, cancel_at_period_end=True, reason=None):
    """Cancel subscription"""
    cancellation_data = {
        "cancelAtPeriodEnd": cancel_at_period_end,
        "reason": reason or "customer_request",
        "feedback": {
            "reason": reason,
            "comments": ""
        }
    }
    
    response = requests.post(
        f"https://api.tensorone.ai/v2/billing/subscriptions/{subscription_id}/cancel",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=cancellation_data
    )
    
    return response.json()

# Usage monitoring and alerts
def check_usage_alerts():
    """Check for usage alerts and overage warnings"""
    print("⚠️  Usage Alerts and Warnings")
    print("=" * 30)
    
    alerts_found = False
    
    for sub in active_subs:
        sub_name = sub['plan']['name']
        
        if sub.get('resources'):
            for resource in sub['resources']:
                used = resource['usedAmount']
                included = resource['includedAmount']
                resource_type = resource['resourceType']
                
                usage_pct = (used / included * 100) if included > 0 else 0
                
                # High usage warning (>90%)
                if usage_pct > 90:
                    alerts_found = True
                    remaining = included - used
                    print(f"🔴 HIGH USAGE: {sub_name}")
                    print(f"   {resource_type}: {usage_pct:.1f}% used")
                    print(f"   Remaining: {remaining:,.1f} {resource['unit']}")
                    
                    if used > included:
                        overage = used - included
                        overage_cost = overage * resource.get('overagePrice', 0)
                        print(f"   💸 Overage cost: ${overage_cost:,.2f}")
                    
                    print()
                
                # Medium usage warning (>75%)
                elif usage_pct > 75:
                    alerts_found = True
                    print(f"🟡 Medium usage: {sub_name} - {resource_type} ({usage_pct:.1f}%)")
    
    if not alerts_found:
        print("✅ No usage alerts at this time")

check_usage_alerts()

# Subscription analytics
def analyze_subscription_trends():
    """Analyze subscription trends and metrics"""
    print("\n📈 Subscription Analytics")
    print("=" * 26)
    
    # Get historical data (this would be a separate API call)
    # For demo purposes, we'll simulate some analytics
    
    analytics = {
        'growth_rate': 15.2,  # Monthly growth rate
        'churn_rate': 3.1,    # Monthly churn rate
        'average_ltv': 2850.00,  # Customer lifetime value
        'mrr_growth': 450.00,    # Monthly MRR growth
        'popular_plans': {
            'GPU Pro': 45,
            'AI Developer': 32,
            'Enterprise': 12,
            'Starter': 28
        }
    }
    
    print(f"Monthly Growth Rate: {analytics['growth_rate']:+.1f}%")
    print(f"Monthly Churn Rate: {analytics['churn_rate']:.1f}%")
    print(f"Average Customer LTV: ${analytics['average_ltv']:,.2f}")
    print(f"MRR Growth: ${analytics['mrr_growth']:+,.2f}")
    
    print(f"\nMost Popular Plans:")
    for plan, count in analytics['popular_plans'].items():
        print(f"  {plan}: {count} subscribers")

# Subscription recommendations
def get_subscription_recommendations():
    """Get recommendations for subscription optimization"""
    print("\n💡 Subscription Recommendations")
    print("=" * 34)
    
    recommendations = []
    
    for sub in active_subs:
        # Check for upgrade opportunities
        if sub.get('usage'):
            usage = sub['usage']
            projected_cost = usage.get('projectedCost', 0)
            base_price = sub['pricing']['basePrice']
            
            if projected_cost > base_price * 1.5:  # 50% over base price
                recommendations.append({
                    'type': 'upgrade',
                    'subscription': sub['plan']['name'],
                    'reason': f'Usage exceeds plan by {((projected_cost/base_price)-1)*100:.0f}%',
                    'potential_savings': projected_cost - (base_price * 1.2)  # Assume 20% higher tier
                })
        
        # Check for downgrade opportunities (low usage)
        if sub.get('resources'):
            low_usage_resources = 0
            for resource in sub['resources']:
                usage_pct = (resource['usedAmount'] / resource['includedAmount'] * 100) if resource['includedAmount'] > 0 else 0
                if usage_pct < 30:  # Very low usage
                    low_usage_resources += 1
            
            if low_usage_resources > len(sub['resources']) / 2:  # More than half are underutilized
                recommendations.append({
                    'type': 'downgrade',
                    'subscription': sub['plan']['name'],
                    'reason': 'Low resource utilization across multiple resources',
                    'potential_savings': base_price * 0.3  # Estimate 30% savings
                })
    
    if recommendations:
        for rec in recommendations:
            rec_icon = "⬆️" if rec['type'] == 'upgrade' else "⬇️"
            print(f"{rec_icon} {rec['type'].title()}: {rec['subscription']}")
            print(f"   Reason: {rec['reason']}")
            if rec.get('potential_savings'):
                savings_type = 'savings' if rec['type'] == 'downgrade' else 'cost avoidance'
                print(f"   Potential {savings_type}: ${rec['potential_savings']:,.2f}/month")
            print()
    else:
        print("✅ No optimization recommendations at this time")

analyze_subscription_trends()
get_subscription_recommendations()
```

```javascript JavaScript
const getSubscriptions = async (options = {}) => {
  const params = new URLSearchParams({
    includeUsage: options.includeUsage || false,
    includeUpcoming: options.includeUpcoming || false,
    includeHistory: options.includeHistory || false
  });

  if (options.status) {
    const statuses = Array.isArray(options.status) ? options.status : [options.status];
    statuses.forEach(status => params.append('status[]', status));
  }

  if (options.planType) {
    const types = Array.isArray(options.planType) ? options.planType : [options.planType];
    types.forEach(type => params.append('planType[]', type));
  }

  const response = await fetch(`https://api.tensorone.ai/v2/billing/subscriptions?${params}`, {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY'
    }
  });

  return await response.json();
};

const createSubscription = async (planId, options = {}) => {
  const subscriptionData = {
    planId,
    billingCycle: options.billingCycle || 'monthly',
    trialDays: options.trialDays,
    autoRenew: options.autoRenew !== false,
    metadata: options.metadata || {}
  };

  const response = await fetch('https://api.tensorone.ai/v2/billing/subscriptions', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(subscriptionData)
  });

  return await response.json();
};

const modifySubscription = async (subscriptionId, modifications) => {
  const response = await fetch(`https://api.tensorone.ai/v2/billing/subscriptions/${subscriptionId}`, {
    method: 'PUT',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(modifications)
  });

  return await response.json();
};

// Get and display subscriptions
getSubscriptions({
  status: ['active', 'trialing'],
  includeUsage: true,
  includeUpcoming: true
}).then(data => {
  console.log('📋 Subscription Management Dashboard');
  console.log('====================================');
  
  const summary = data.summary;
  console.log(`Total Subscriptions: ${summary.totalSubscriptions}`);
  console.log(`Monthly Recurring Revenue: $${summary.totalMonthlyRecurring.toLocaleString()}`);
  console.log(`Annual Recurring Revenue: $${summary.totalAnnualRecurring.toLocaleString()}`);
  
  // Status breakdown
  console.log('\n📊 Subscription Status:');
  Object.entries(summary.byStatus).forEach(([status, count]) => {
    const statusIcon = {
      'active': '✅',
      'trialing': '🆓',
      'past_due': '⏰',
      'canceled': '❌',
      'paused': '⏸️'
    }[status] || '⚪';
    
    console.log(`${statusIcon} ${status.replace('_', ' ')}: ${count}`);
  });
  
  // Active subscriptions
  const activeSubscriptions = data.subscriptions.filter(s => 
    ['active', 'trialing'].includes(s.status)
  );
  
  console.log(`\n🔄 Active Subscriptions (${activeSubscriptions.length}):`);
  activeSubscriptions.forEach(sub => {
    const nextBilling = new Date(sub.dates.nextBilling);
    const daysUntilBilling = Math.ceil((nextBilling - new Date()) / (1000 * 60 * 60 * 24));
    
    console.log(`\n📦 ${sub.plan.name}`);
    console.log(`   Status: ${sub.status}`);
    console.log(`   Price: $${sub.pricing.basePrice.toLocaleString()} (${sub.pricing.billingCycle})`);
    console.log(`   Next billing: ${daysUntilBilling} days`);
    
    // Show trial information
    if (sub.status === 'trialing' && sub.dates.trialEnd) {
      const trialEnd = new Date(sub.dates.trialEnd);
      const trialDaysLeft = Math.ceil((trialEnd - new Date()) / (1000 * 60 * 60 * 24));
      console.log(`   🆓 Trial ends in ${trialDaysLeft} days`);
    }
    
    // Show usage
    if (sub.usage && sub.resources) {
      console.log(`   📊 Resource Usage:`);
      sub.resources.forEach(resource => {
        const usagePct = (resource.usedAmount / resource.includedAmount * 100).toFixed(1);
        const usageColor = usagePct < 80 ? '🟢' : usagePct < 95 ? '🟡' : '🔴';
        
        console.log(`     ${usageColor} ${resource.resourceType}: ${usagePct}%`);
        
        if (resource.usedAmount > resource.includedAmount) {
          const overage = resource.usedAmount - resource.includedAmount;
          const overageCost = overage * (resource.overagePrice || 0);
          console.log(`       ⚠️ Overage: ${overage.toFixed(1)} ${resource.unit} ($${overageCost.toFixed(2)})`);
        }
      });
    }
  });
});

// Subscription management functions
const upgradeSubscription = async (subscriptionId, newPlanId, effectiveDate = 'immediate') => {
  return await modifySubscription(subscriptionId, {
    type: 'upgrade',
    newPlanId,
    effectiveDate,
    proration: true
  });
};

const cancelSubscription = async (subscriptionId, cancelAtPeriodEnd = true, reason = null) => {
  const response = await fetch(`https://api.tensorone.ai/v2/billing/subscriptions/${subscriptionId}/cancel`, {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      cancelAtPeriodEnd,
      reason: reason || 'customer_request',
      feedback: {
        reason,
        comments: ''
      }
    })
  });

  return await response.json();
};

// Usage monitoring
const checkUsageAlerts = async () => {
  const data = await getSubscriptions({ 
    status: ['active'], 
    includeUsage: true 
  });
  
  console.log('\n⚠️ Usage Alerts:');
  
  let alertsFound = false;
  
  data.subscriptions.forEach(sub => {
    if (sub.resources) {
      sub.resources.forEach(resource => {
        const usagePct = (resource.usedAmount / resource.includedAmount) * 100;
        
        if (usagePct > 90) {
          alertsFound = true;
          console.log(`🔴 HIGH USAGE: ${sub.plan.name}`);
          console.log(`   ${resource.resourceType}: ${usagePct.toFixed(1)}% used`);
          
          if (resource.usedAmount > resource.includedAmount) {
            const overage = resource.usedAmount - resource.includedAmount;
            const cost = overage * (resource.overagePrice || 0);
            console.log(`   💸 Overage cost: $${cost.toFixed(2)}`);
          }
        }
      });
    }
  });
  
  if (!alertsFound) {
    console.log('✅ No usage alerts');
  }
};

// Analytics and recommendations
const analyzeSubscriptions = async () => {
  const data = await getSubscriptions({ includeUsage: true });
  
  console.log('\n📈 Subscription Analytics:');
  console.log('=========================');
  
  // Calculate metrics
  const totalMRR = data.summary.totalMonthlyRecurring;
  const totalSubscriptions = data.summary.totalSubscriptions;
  const avgRevenuePerUser = totalMRR / totalSubscriptions;
  
  console.log(`Average Revenue Per User: $${avgRevenuePerUser.toFixed(2)}`);
  console.log(`Total MRR: $${totalMRR.toLocaleString()}`);
  
  // Plan distribution
  console.log('\nPlan Distribution:');
  Object.entries(data.summary.byPlanType).forEach(([planType, count]) => {
    console.log(`${planType.replace('_', ' ')}: ${count} subscribers`);
  });
};
```

```json Response
{
  "subscriptions": [
    {
      "subscriptionId": "sub_gpu_pro_001",
      "status": "active",
      "plan": {
        "planId": "plan_gpu_pro",
        "name": "GPU Pro Plan",
        "type": "compute",
        "description": "Professional GPU compute with premium features",
        "features": [
          "100 GPU hours/month",
          "A100 and H100 access",
          "Priority scheduling",
          "24/7 support"
        ]
      },
      "pricing": {
        "basePrice": 499.00,
        "currency": "USD",
        "billingCycle": "monthly",
        "usagePricing": [
          {
            "resourceType": "gpu_hours",
            "includedAmount": 100,
            "overagePrice": 6.50
          }
        ],
        "discounts": [
          {
            "type": "annual_discount",
            "description": "10% annual billing discount",
            "amount": 49.90
          }
        ]
      },
      "dates": {
        "created": "2024-01-15T10:00:00Z",
        "activated": "2024-01-15T10:00:00Z",
        "currentPeriodStart": "2024-02-01T00:00:00Z",
        "currentPeriodEnd": "2024-02-29T23:59:59Z",
        "nextBilling": "2024-03-01T00:00:00Z",
        "trialEnd": null,
        "canceledAt": null
      },
      "usage": {
        "currentPeriod": {
          "gpuHours": 78.5,
          "apiCalls": 45623,
          "storageGB": 250.8
        },
        "quotas": {
          "gpuHours": 100,
          "storageGB": 500
        },
        "overages": {
          "gpuHours": 0,
          "storageGB": 0
        },
        "projectedCost": 499.00
      },
      "resources": [
        {
          "resourceType": "gpu_hours",
          "includedAmount": 100,
          "usedAmount": 78.5,
          "unit": "hours",
          "overagePrice": 6.50
        },
        {
          "resourceType": "storage",
          "includedAmount": 500,
          "usedAmount": 250.8,
          "unit": "GB",
          "overagePrice": 0.10
        }
      ],
      "modifications": [],
      "paymentMethod": {
        "methodId": "pm_card_1234567890",
        "type": "credit_card",
        "displayName": "Visa ****4242"
      },
      "metadata": {
        "tags": ["production", "primary"],
        "notes": "Main GPU subscription for production workloads",
        "customFields": {
          "department": "engineering",
          "project": "ml_research"
        },
        "autoRenew": true
      }
    },
    {
      "subscriptionId": "sub_ai_dev_002",
      "status": "trialing",
      "plan": {
        "planId": "plan_ai_developer",
        "name": "AI Developer Plan",
        "type": "ai_services",
        "description": "AI services package for developers",
        "features": [
          "10K AI API calls/month",
          "Text, image, voice generation",
          "Standard support",
          "Usage analytics"
        ]
      },
      "pricing": {
        "basePrice": 99.00,
        "currency": "USD",
        "billingCycle": "monthly",
        "usagePricing": [
          {
            "resourceType": "ai_api_calls",
            "includedAmount": 10000,
            "overagePrice": 0.015
          }
        ],
        "discounts": []
      },
      "dates": {
        "created": "2024-02-10T14:30:00Z",
        "activated": "2024-02-10T14:30:00Z",
        "currentPeriodStart": "2024-02-10T14:30:00Z",
        "currentPeriodEnd": "2024-02-24T14:30:00Z",
        "nextBilling": "2024-02-24T14:30:00Z",
        "trialEnd": "2024-02-24T14:30:00Z",
        "canceledAt": null
      },
      "usage": {
        "currentPeriod": {
          "aiApiCalls": 3247,
          "textGeneration": 1856,
          "imageGeneration": 891,
          "voiceSynthesis": 500
        },
        "quotas": {
          "aiApiCalls": 10000
        },
        "overages": {
          "aiApiCalls": 0
        },
        "projectedCost": 99.00
      },
      "resources": [
        {
          "resourceType": "ai_api_calls",
          "includedAmount": 10000,
          "usedAmount": 3247,
          "unit": "calls",
          "overagePrice": 0.015
        }
      ],
      "modifications": [
        {
          "type": "upgrade",
          "effectiveDate": "2024-02-24T14:30:00Z",
          "details": {
            "targetPlanId": "plan_ai_pro",
            "reason": "trial_conversion"
          },
          "priceImpact": 150.00
        }
      ],
      "paymentMethod": {
        "methodId": "pm_card_1234567890",
        "type": "credit_card",
        "displayName": "Visa ****4242"
      },
      "metadata": {
        "tags": ["trial", "ai_services"],
        "notes": "Trial subscription for AI services evaluation",
        "customFields": {
          "department": "product",
          "trial_source": "website_signup"
        },
        "autoRenew": true
      }
    }
  ],
  "summary": {
    "totalSubscriptions": 2,
    "totalMonthlyRecurring": 598.00,
    "totalAnnualRecurring": 7176.00,
    "byStatus": {
      "active": 1,
      "trialing": 1,
      "canceled": 0,
      "past_due": 0
    },
    "byPlanType": {
      "compute": 1,
      "ai_services": 1,
      "storage": 0,
      "enterprise": 0
    },
    "upcomingRenewals": 2
  },
  "availablePlans": [
    {
      "planId": "plan_starter",
      "name": "Starter Plan",
      "type": "compute",
      "pricing": {
        "basePrice": 49.00,
        "billingCycle": "monthly"
      },
      "features": [
        "10 GPU hours/month",
        "Basic support",
        "Standard GPUs only"
      ],
      "popular": false
    },
    {
      "planId": "plan_gpu_pro",
      "name": "GPU Pro Plan", 
      "type": "compute",
      "pricing": {
        "basePrice": 499.00,
        "billingCycle": "monthly"
      },
      "features": [
        "100 GPU hours/month",
        "A100 and H100 access",
        "Priority scheduling",
        "24/7 support"
      ],
      "popular": true
    },
    {
      "planId": "plan_enterprise",
      "name": "Enterprise Plan",
      "type": "enterprise",
      "pricing": {
        "basePrice": 2999.00,
        "billingCycle": "monthly"
      },
      "features": [
        "Unlimited GPU hours",
        "Dedicated resources",
        "Custom SLA",
        "Enterprise support"
      ],
      "popular": false
    }
  ]
}
```

## Subscription Operations

### Create and Manage Subscriptions

```python Python
def create_trial_subscription(plan_id, trial_days=14):
    """Create a subscription with trial period"""
    subscription_data = {
        "planId": plan_id,
        "billingCycle": "monthly",
        "trialDays": trial_days,
        "autoRenew": True,
        "metadata": {
            "source": "trial_signup",
            "tags": ["trial", "new_customer"]
        }
    }
    
    response = requests.post(
        "https://api.tensorone.ai/v2/billing/subscriptions",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=subscription_data
    )
    
    return response.json()

def upgrade_subscription_immediate(subscription_id, new_plan_id):
    """Upgrade subscription with immediate effect and proration"""
    modifications = {
        "type": "upgrade",
        "newPlanId": new_plan_id,
        "effectiveDate": "immediate",
        "proration": True,
        "reason": "customer_upgrade_request"
    }
    
    result = modify_subscription(subscription_id, modifications)
    return result

def schedule_subscription_change(subscription_id, new_plan_id, effective_date):
    """Schedule subscription change for future date"""
    modifications = {
        "type": "plan_change",
        "newPlanId": new_plan_id,
        "effectiveDate": effective_date,
        "proration": False,
        "reason": "scheduled_change"
    }
    
    result = modify_subscription(subscription_id, modifications)
    return result

def add_subscription_addons(subscription_id, addons):
    """Add multiple addons to subscription"""
    modifications = {
        "type": "addons",
        "addons": addons,  # [{"addonId": "addon_storage", "quantity": 2}]
        "effectiveDate": "immediate"
    }
    
    result = modify_subscription(subscription_id, modifications)
    return result

# Example subscription management workflow
def subscription_management_workflow():
    """Demonstrate subscription management operations"""
    print("🔄 Subscription Management Workflow")
    print("=" * 37)
    
    # Create trial subscription
    trial_sub = create_trial_subscription("plan_ai_developer", trial_days=14)
    if trial_sub.get('subscriptionId'):
        print(f"✅ Trial subscription created: {trial_sub['subscriptionId']}")
        
        # Simulate trial conversion after some time
        # upgrade_result = upgrade_subscription_immediate(
        #     trial_sub['subscriptionId'], 
        #     "plan_ai_pro"
        # )
        # print(f"✅ Upgraded to Pro plan: {upgrade_result.get('success', False)}")
    
    # Schedule plan change
    # schedule_result = schedule_subscription_change(
    #     "sub_existing_001",
    #     "plan_gpu_enterprise", 
    #     "2024-03-01"
    # )
    # print(f"✅ Scheduled plan change: {schedule_result.get('success', False)}")
    
    # Add storage addon
    storage_addons = [
        {"addonId": "addon_storage_1tb", "quantity": 1},
        {"addonId": "addon_backup", "quantity": 1}
    ]
    # addon_result = add_subscription_addons("sub_existing_001", storage_addons)
    # print(f"✅ Added storage addons: {addon_result.get('success', False)}")
    
    print("Subscription workflow completed (uncomment to execute)")

subscription_management_workflow()
```

### Subscription Analytics and Insights

```python Python
def get_subscription_analytics(time_period="last_12_months"):
    """Get comprehensive subscription analytics"""
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/subscriptions/analytics",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params={
            "timePeriod": time_period,
            "includeChurnAnalysis": True,
            "includeRevenueMetrics": True,
            "includeCohortAnalysis": True
        }
    )
    
    return response.json()

def analyze_subscription_health():
    """Analyze overall subscription health and metrics"""
    analytics = get_subscription_analytics()
    
    print("📊 Subscription Health Analytics")
    print("=" * 34)
    
    # Key metrics
    metrics = analytics.get('keyMetrics', {})
    print(f"Monthly Recurring Revenue: ${metrics.get('mrr', 0):,.2f}")
    print(f"Annual Recurring Revenue: ${metrics.get('arr', 0):,.2f}")
    print(f"Average Revenue Per User: ${metrics.get('arpu', 0):,.2f}")
    print(f"Customer Lifetime Value: ${metrics.get('ltv', 0):,.2f}")
    print(f"Monthly Churn Rate: {metrics.get('churnRate', 0):.2f}%")
    print(f"Net Revenue Retention: {metrics.get('nrr', 0):.1f}%")
    
    # Growth metrics
    growth = analytics.get('growth', {})
    print(f"\n📈 Growth Metrics:")
    print(f"MRR Growth Rate: {growth.get('mrrGrowthRate', 0):+.1f}%")
    print(f"New Subscriptions (30d): {growth.get('newSubscriptions30d', 0)}")
    print(f"Canceled Subscriptions (30d): {growth.get('canceledSubscriptions30d', 0)}")
    print(f"Upgrades (30d): {growth.get('upgrades30d', 0)}")
    print(f"Downgrades (30d): {growth.get('downgrades30d', 0)}")
    
    # Plan performance
    if analytics.get('planPerformance'):
        print(f"\n📋 Plan Performance:")
        for plan in analytics['planPerformance']:
            plan_name = plan['planName']
            subscribers = plan['subscribers']
            mrr = plan['mrr']
            churn_rate = plan['churnRate']
            
            print(f"  {plan_name}:")
            print(f"    Subscribers: {subscribers}")
            print(f"    MRR: ${mrr:,.2f}")
            print(f"    Churn Rate: {churn_rate:.1f}%")
    
    # Cohort analysis
    if analytics.get('cohortAnalysis'):
        print(f"\n👥 Cohort Analysis (Revenue Retention):")
        cohorts = analytics['cohortAnalysis']
        
        # Show recent cohorts
        for cohort in cohorts[-6:]:  # Last 6 months
            cohort_month = cohort['cohortMonth']
            month_0 = cohort['retention']['month0']  # Initial revenue
            month_6 = cohort['retention'].get('month6', 0)  # 6-month retention
            
            retention_rate = (month_6 / month_0 * 100) if month_0 > 0 else 0
            print(f"    {cohort_month}: {retention_rate:.0f}% revenue retention")
    
    return analytics

def identify_at_risk_subscriptions():
    """Identify subscriptions at risk of churn"""
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/subscriptions/risk-analysis",
        headers={"Authorization": "Bearer YOUR_API_KEY"}
    )
    
    risk_analysis = response.json()
    
    print("\n⚠️  At-Risk Subscription Analysis")
    print("=" * 35)
    
    if risk_analysis.get('atRiskSubscriptions'):
        high_risk = [s for s in risk_analysis['atRiskSubscriptions'] if s['riskScore'] >= 0.7]
        medium_risk = [s for s in risk_analysis['atRiskSubscriptions'] if 0.4 <= s['riskScore'] < 0.7]
        
        print(f"High Risk Subscriptions: {len(high_risk)}")
        print(f"Medium Risk Subscriptions: {len(medium_risk)}")
        
        # Show high-risk subscriptions
        if high_risk:
            print(f"\n🔴 High Risk Subscriptions:")
            for sub in high_risk[:5]:  # Top 5 high-risk
                print(f"  • {sub['planName']} (Score: {sub['riskScore']:.2f})")
                print(f"    Risk Factors: {', '.join(sub['riskFactors'])}")
                print(f"    Recommended Action: {sub['recommendedAction']}")
                print()
        
        # Risk factor analysis
        if risk_analysis.get('riskFactors'):
            print(f"📊 Common Risk Factors:")
            for factor, count in risk_analysis['riskFactors'].items():
                print(f"  {factor.replace('_', ' ').title()}: {count} subscriptions")
    else:
        print("✅ No high-risk subscriptions identified")

def subscription_revenue_forecast():
    """Generate subscription revenue forecast"""
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/subscriptions/forecast",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params={
            "forecastPeriod": "12_months",
            "includeScenarios": True
        }
    )
    
    forecast = response.json()
    
    print(f"\n🔮 Revenue Forecast (12 Months)")
    print("=" * 32)
    
    base_scenario = forecast.get('baseScenario', {})
    print(f"Base Case MRR Growth: {base_scenario.get('mrrGrowth', 0):+.1f}%")
    print(f"Projected MRR (12 months): ${base_scenario.get('projectedMrr', 0):,.2f}")
    print(f"Projected ARR (12 months): ${base_scenario.get('projectedArr', 0):,.2f}")
    
    # Scenario analysis
    if forecast.get('scenarios'):
        print(f"\nScenario Analysis:")
        for scenario_name, scenario in forecast['scenarios'].items():
            probability = scenario.get('probability', 0)
            projected_arr = scenario.get('projectedArr', 0)
            print(f"  {scenario_name.title()}: ${projected_arr:,.2f} ARR ({probability:.0%} probability)")
    
    return forecast

# Run analytics
analytics = analyze_subscription_health()
identify_at_risk_subscriptions()
forecast = subscription_revenue_forecast()
```

### Subscription Billing and Invoicing

```python Python
def get_subscription_billing_schedule(subscription_id):
    """Get billing schedule for subscription"""
    response = requests.get(
        f"https://api.tensorone.ai/v2/billing/subscriptions/{subscription_id}/billing-schedule",
        headers={"Authorization": "Bearer YOUR_API_KEY"}
    )
    
    return response.json()

def preview_subscription_changes(subscription_id, modifications):
    """Preview the billing impact of subscription changes"""
    response = requests.post(
        f"https://api.tensorone.ai/v2/billing/subscriptions/{subscription_id}/preview-changes",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=modifications
    )
    
    return response.json()

def process_subscription_invoice(subscription_id, billing_period):
    """Manually trigger invoice generation for subscription"""
    response = requests.post(
        f"https://api.tensorone.ai/v2/billing/subscriptions/{subscription_id}/invoice",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json={
            "billingPeriod": billing_period,
            "includeUsageCharges": True,
            "applyCredits": True
        }
    )
    
    return response.json()

def manage_subscription_billing():
    """Demonstrate subscription billing management"""
    print("💰 Subscription Billing Management")
    print("=" * 36)
    
    # Get billing schedule for a subscription
    # schedule = get_subscription_billing_schedule("sub_gpu_pro_001")
    # if schedule.get('billingEvents'):
    #     print("Upcoming Billing Events:")
    #     for event in schedule['billingEvents'][:5]:
    #         event_date = event['scheduledDate']
    #         event_type = event['eventType']
    #         estimated_amount = event['estimatedAmount']
    #         print(f"  {event_date}: {event_type} - ${estimated_amount:.2f}")
    
    # Preview upgrade impact
    upgrade_preview = {
        "type": "upgrade",
        "newPlanId": "plan_gpu_enterprise",
        "effectiveDate": "immediate"
    }
    
    # preview = preview_subscription_changes("sub_gpu_pro_001", upgrade_preview)
    # if preview.get('proration'):
    #     proration = preview['proration']
    #     print(f"\nUpgrade Preview:")
    #     print(f"  Prorated Credit: ${proration['credit']:.2f}")
    #     print(f"  New Plan Charge: ${proration['newCharge']:.2f}")
    #     print(f"  Net Amount: ${proration['netAmount']:.2f}")
    
    print("Billing management examples (uncomment to execute)")

def handle_failed_subscription_payments():
    """Handle failed subscription payments"""
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/subscriptions/payment-failures",
        headers={"Authorization": "Bearer YOUR_API_KEY"}
    )
    
    failures = response.json()
    
    print(f"\n💳 Failed Payment Management")
    print("=" * 30)
    
    if failures.get('failedSubscriptions'):
        print(f"Subscriptions with Failed Payments: {len(failures['failedSubscriptions'])}")
        
        for failure in failures['failedSubscriptions']:
            sub_id = failure['subscriptionId']
            plan_name = failure['planName']
            failed_amount = failure['failedAmount']
            failure_reason = failure['failureReason']
            retry_date = failure['nextRetryDate']
            
            print(f"\n❌ {plan_name} ({sub_id})")
            print(f"   Failed Amount: ${failed_amount:.2f}")
            print(f"   Reason: {failure_reason}")
            print(f"   Next Retry: {retry_date}")
            
            # Attempt retry
            retry_result = retry_subscription_payment(sub_id)
            if retry_result.get('success'):
                print(f"   ✅ Payment retry initiated")
            else:
                print(f"   ⚠️  Retry failed: {retry_result.get('error', 'Unknown error')}")
    else:
        print("✅ No failed payments")

def retry_subscription_payment(subscription_id):
    """Retry failed subscription payment"""
    response = requests.post(
        f"https://api.tensorone.ai/v2/billing/subscriptions/{subscription_id}/retry-payment",
        headers={"Authorization": "Bearer YOUR_API_KEY"}
    )
    
    return response.json()

manage_subscription_billing()
handle_failed_subscription_payments()
```

## Advanced Subscription Features

### Custom Enterprise Subscriptions

```python Python
def create_enterprise_subscription(custom_plan_config):
    """Create custom enterprise subscription"""
    enterprise_subscription = {
        "type": "enterprise_custom",
        "customPlan": custom_plan_config,
        "billingCycle": "annual",
        "contractTerm": "36_months",
        "customPricing": True,
        "dedicatedResources": True,
        "slaLevel": "enterprise",
        "metadata": {
            "tags": ["enterprise", "custom"],
            "accountManager": "enterprise@company.com"
        }
    }
    
    response = requests.post(
        "https://api.tensorone.ai/v2/billing/subscriptions/enterprise",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=enterprise_subscription
    )
    
    return response.json()

# Example enterprise plan configuration
enterprise_plan = {
    "name": "Custom Enterprise GPU Cluster",
    "description": "Dedicated GPU infrastructure with custom SLA",
    "resources": {
        "dedicatedGpuHours": "unlimited",
        "storageGB": 10000,
        "bandwidthGB": 50000,
        "supportLevel": "24x7_dedicated"
    },
    "customFeatures": [
        "Dedicated cluster allocation",
        "Custom container registry",
        "VPN connectivity",
        "Compliance certifications"
    ],
    "pricing": {
        "basePrice": 15000.00,
        "currency": "USD",
        "billingCycle": "monthly",
        "minimumCommitment": 12
    }
}

# enterprise_sub = create_enterprise_subscription(enterprise_plan)
# print(f"Enterprise subscription: {enterprise_sub.get('subscriptionId', 'Failed')}")
```

### Subscription Automation and Webhooks

```python Python
def setup_subscription_automation():
    """Configure subscription automation rules"""
    automation_config = {
        "trialConversion": {
            "enabled": True,
            "autoConvertOnUsage": True,
            "usageThreshold": 0.8,  # 80% of trial usage
            "reminderDays": [7, 3, 1]  # Days before trial ends
        },
        "paymentFailureHandling": {
            "maxRetries": 3,
            "retryInterval": "3d",
            "gracePeriod": "7d",
            "autoDowngrade": {
                "enabled": True,
                "downgradeTo": "plan_starter"
            }
        },
        "usageAlerts": {
            "enabled": True,
            "thresholds": [0.8, 0.9, 1.0],  # 80%, 90%, 100%
            "notificationChannels": ["email", "webhook"]
        },
        "renewalReminders": {
            "enabled": True,
            "reminderDays": [30, 7, 1],
            "includeUsageSummary": True
        }
    }
    
    response = requests.post(
        "https://api.tensorone.ai/v2/billing/subscriptions/automation",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=automation_config
    )
    
    return response.json()

def configure_subscription_webhooks():
    """Configure webhooks for subscription events"""
    webhook_config = {
        "url": "https://your-app.com/webhooks/subscriptions",
        "events": [
            "subscription.created",
            "subscription.updated", 
            "subscription.canceled",
            "subscription.trial_ending",
            "subscription.payment_failed",
            "subscription.usage_threshold"
        ],
        "secret": "webhook_secret_key",
        "retryPolicy": {
            "maxRetries": 3,
            "retryDelay": "30s"
        }
    }
    
    response = requests.post(
        "https://api.tensorone.ai/v2/billing/webhooks",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=webhook_config
    )
    
    return response.json()

# Setup automation
automation_result = setup_subscription_automation()
webhook_result = configure_subscription_webhooks()

print(f"Automation configured: {automation_result.get('success', False)}")
print(f"Webhooks configured: {webhook_result.get('webhookId', 'Failed')}")
```

## Best Practices

### Subscription Strategy

* **Plan Design**: Create clear value tiers with distinct feature sets
* **Trial Management**: Use trials strategically to convert prospects
* **Pricing Optimization**: Regularly analyze and optimize pricing
* **Feature Packaging**: Bundle features logically for different customer segments

### Customer Success

* **Usage Monitoring**: Proactively monitor usage patterns
* **Engagement Tracking**: Track feature usage and engagement
* **Churn Prevention**: Identify and address at-risk subscriptions
* **Upgrade Incentives**: Provide clear paths for plan upgrades

### Financial Management

* **Revenue Recognition**: Ensure proper revenue recognition practices
* **Forecasting**: Use subscription data for accurate revenue forecasting
* **Metrics Tracking**: Monitor key SaaS metrics (MRR, ARR, churn, LTV)
* **Payment Reliability**: Implement robust payment failure handling

> [!NOTE]
>
> Subscription changes take effect at the next billing cycle unless specified otherwise. Immediate changes may result in prorated charges or credits.

> [!TIP]
>
> Use usage-based pricing tiers to align costs with value for customers. Set up automated alerts for usage thresholds to help customers optimize their subscriptions.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.