1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
| from enum import Enum from decimal import Decimal from datetime import datetime, timedelta import stripe
class SubscriptionPlan(Enum): FREE = "free" BASIC = "basic" PREMIUM = "premium" ENTERPRISE = "enterprise"
class BillingService: def __init__(self, stripe_api_key): stripe.api_key = stripe_api_key self.plans = { SubscriptionPlan.FREE: { 'price': Decimal('0'), 'features': ['basic_features'], 'limits': {'users': 5, 'storage_gb': 1, 'api_calls': 1000} }, SubscriptionPlan.BASIC: { 'price': Decimal('29.99'), 'features': ['basic_features', 'advanced_reports'], 'limits': {'users': 25, 'storage_gb': 10, 'api_calls': 10000} }, SubscriptionPlan.PREMIUM: { 'price': Decimal('99.99'), 'features': ['basic_features', 'advanced_reports', 'integrations'], 'limits': {'users': 100, 'storage_gb': 100, 'api_calls': 100000} }, SubscriptionPlan.ENTERPRISE: { 'price': Decimal('299.99'), 'features': ['all_features'], 'limits': {'users': -1, 'storage_gb': -1, 'api_calls': -1} } } def create_subscription(self, tenant_id, plan, payment_method_id): """创建订阅""" try: customer = stripe.Customer.create( metadata={'tenant_id': tenant_id} ) stripe.PaymentMethod.attach( payment_method_id, customer=customer.id ) stripe.Customer.modify( customer.id, invoice_settings={'default_payment_method': payment_method_id} ) subscription = stripe.Subscription.create( customer=customer.id, items=[{'price': self.get_stripe_price_id(plan)}], metadata={'tenant_id': tenant_id, 'plan': plan.value} ) self.update_tenant_subscription(tenant_id, plan, subscription.id) return { 'subscription_id': subscription.id, 'status': subscription.status, 'current_period_end': subscription.current_period_end } except stripe.error.StripeError as e: raise Exception(f"订阅创建失败: {str(e)}") def check_feature_access(self, tenant_id, feature): """检查功能访问权限""" tenant_plan = self.get_tenant_plan(tenant_id) plan_config = self.plans[tenant_plan] if feature in plan_config['features'] or 'all_features' in plan_config['features']: return True return False def check_usage_limit(self, tenant_id, resource, current_usage): """检查使用限制""" tenant_plan = self.get_tenant_plan(tenant_id) plan_config = self.plans[tenant_plan] limit = plan_config['limits'].get(resource, 0) if limit == -1: return True return current_usage < limit def get_usage_stats(self, tenant_id): """获取使用统计""" return { 'users': self.count_tenant_users(tenant_id), 'storage_gb': self.calculate_storage_usage(tenant_id), 'api_calls': self.count_api_calls(tenant_id) } def generate_invoice(self, tenant_id, billing_period): """生成账单""" tenant_plan = self.get_tenant_plan(tenant_id) plan_config = self.plans[tenant_plan] usage_stats = self.get_usage_stats(tenant_id) invoice = { 'tenant_id': tenant_id, 'billing_period': billing_period, 'plan': tenant_plan.value, 'base_amount': plan_config['price'], 'usage_charges': self.calculate_usage_charges(tenant_plan, usage_stats), 'total_amount': plan_config['price'], 'generated_at': datetime.utcnow() } invoice['total_amount'] += invoice['usage_charges'] return invoice def calculate_usage_charges(self, plan, usage_stats): """计算超额使用费用""" charges = Decimal('0') plan_config = self.plans[plan] for resource, usage in usage_stats.items(): limit = plan_config['limits'].get(resource, 0) if limit > 0 and usage > limit: overage = usage - limit if resource == 'users': charges += overage * Decimal('5.00') elif resource == 'storage_gb': charges += overage * Decimal('0.50') elif resource == 'api_calls': charges += (overage / 1000) * Decimal('0.10') return charges def upgrade_subscription(self, tenant_id, new_plan): """升级订阅""" current_subscription = self.get_tenant_subscription(tenant_id) try: stripe.Subscription.modify( current_subscription['stripe_id'], items=[{ 'id': current_subscription['item_id'], 'price': self.get_stripe_price_id(new_plan) }], proration_behavior='create_prorations' ) self.update_tenant_subscription(tenant_id, new_plan, current_subscription['stripe_id']) return True except stripe.error.StripeError as e: raise Exception(f"订阅升级失败: {str(e)}") def get_tenant_plan(self, tenant_id): pass def update_tenant_subscription(self, tenant_id, plan, subscription_id): pass def get_stripe_price_id(self, plan): price_mapping = { SubscriptionPlan.BASIC: 'price_basic_monthly', SubscriptionPlan.PREMIUM: 'price_premium_monthly', SubscriptionPlan.ENTERPRISE: 'price_enterprise_monthly' } return price_mapping.get(plan)
|