Request Parameters
Specific subscription ID to retrieve. If not provided, returns list of subscriptions.
Filter by subscription status:
active
- Currently active subscriptionstrialing
- In trial periodpast_due
- Payment overduecanceled
- Canceled subscriptionspaused
- Temporarily pausedpending
- Pending activationexpired
- Expired subscriptions
Filter by plan types:
compute
- GPU compute subscriptionsai_services
- AI service packagesstorage
- Storage subscriptionsbandwidth
- Data transfer plansenterprise
- Enterprise custom plansdeveloper
- Developer tier plans
Filter by billing cycles:
monthly
- Monthly billingquarterly
- Quarterly billingannual
- Annual billingusage_based
- Usage-based billing
Include current usage statistics for usage-based subscriptions
Include information about upcoming charges and renewals
Include subscription history and changes
Response
Array of subscription objects
Show Subscription Object
Show Subscription Object
Unique subscription identifier
Current subscription status
Important subscription dates
Show Subscription Dates
Show Subscription Dates
Subscription creation date
Activation date
Current billing period start
Current billing period end
Next billing date
Trial period end date (if applicable)
Cancellation date (if canceled)
Included and allocated resources
Subscription summary statistics
Show Subscription Summary
Show Subscription Summary
Total number of subscriptions
Total monthly recurring revenue
Total annual recurring revenue
Subscription count by status
Subscription count by plan type
Subscriptions renewing in next 30 days
Example
Copy
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"
Copy
{
"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
Copy
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
Copy
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
Copy
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
Copy
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
Copy
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
Subscription changes take effect at the next billing cycle unless specified otherwise. Immediate changes may result in prorated charges or credits.
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.