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

# 混合计费模型

> 结合多种计费模式创建复杂的定价策略：订阅+使用、座席+附加功能、基础+超量等。

<Info>
  混合计费将两种或多种计费模型结合成一个单一的定价策略。这使您能够从不同维度捕获价值——经常性费用、使用量、座席和功能，同时为客户提供灵活性和可预测性。
</Info>

<CardGroup cols={2}>
  <Card title="Usage-Based Billing" icon="chart-line" href="/features/usage-based-billing/introduction">
    消费型定价的基础。
  </Card>

  <Card title="Subscriptions" icon="repeat" href="/features/subscription">
    经常性计费的基础。
  </Card>

  <Card title="Add-ons" icon="puzzle" href="/features/addons">
    使用可选升级扩展订阅。
  </Card>

  <Card title="Seat-Based Billing" icon="users" href="/features/seat-based-billing">
    每用户定价模型。
  </Card>
</CardGroup>

***

## 什么是混合计费？

混合计费将多种定价维度组合成一个产品提供。与仅选择统一价订阅或基于使用的定价相比，您可以将二者结合起来使用。

### 为什么使用混合计费？

| 商业目标       | 混合解决方案     |
| ---------- | ---------- |
| 可预测收入+增长潜力 | 基础订阅+超量使用  |
| 团队定价可扩展    | 每座席+功能附加   |
| 吸引客户，后期扩展  | 低基础费用+消费费用 |
| 企业灵活性      | 承诺支出+按需收费  |
| 可变使用的公平定价  | 包含津贴+按使用付费 |

### 常见混合模式

| 模型               | 描述                 | 示例                           | 原生支持    |
| ---------------- | ------------------ | ---------------------------- | ------- |
| **1. 订阅+使用**     | 基础费用+消费费用          | $49/月 + 每10K免费后每个API调用$0.01  | ✅ 完全支持  |
| **2. 订阅+座席**     | 平台费用+每用户费用         | $99/月 + 每座席$15               | ✅ 完全支持  |
| **3. 订阅+功能附加**   | 核心计划+可选升级          | $29/月 + $19/月分析 + \$9/月API访问 | ✅ 完全支持  |
| **4. 座席+使用**     | 每用户费用+消费超量         | $10/用户/月 + 每用户5GB后$0.05/GB   | ⚠️ 解决方案 |
| **5. 订阅+座席+使用**  | 平台 + 用户 + 消费（三重混合） | $199/月 + 每座席$20 + 超量使用       | ⚠️ 解决方案 |
| **6. 分级基础+使用超量** | 不同级别不同津贴           | 入门（5K调用）vs 专业（50K调用）+超量      | ✅ 完全支持  |
| **7. 订阅+按需收费**   | 经常性费用+可变手动费用       | \$99/月保证金+工作时间收费             | ✅ 完全支持  |

***

## 混合模型 1：订阅 + 使用

最常见的混合模型。客户支付基础订阅费以及超出包含津贴的使用费用。

### 如何运作

**专业计划：每月\$49**

* **包含**：每月10,000次API调用
* **超量**：每次调用\$0.005，超过10,000次

**计算示例**（本月客户使用25,000次调用）：

* 基础订阅：\$49.00
* 超量：（25,000 - 10,000）× $0.005 = $75.00
* **总计：\$124.00**

### 使用场景

* **API平台**：基础访问+按请求收费
* **AI/ML服务**：订阅+令牌/生成使用
* **存储服务**：基础计划+每GB超量
* **通信平台**：基础+每消息/分钟收费

### 实施

<Steps>
  <Step title="Create Usage Meter">
    设置一个仪表来跟踪可计费的使用维度。

    ```bash theme={null}
    Dashboard: Meters → Create Meter
    Event Name: "api.call"
    Aggregation: Count
    This tracks API calls per customer
    ```
  </Step>

  <Step title="Create Subscription Product with Usage Pricing">
    创建订阅产品并附加价格使用仪表。

    ```bash theme={null}
    Dashboard: Create Product → Subscription
    Name: "Pro Plan"
    Base Price: $49/month

    Then attach usage pricing:
    - Meter: api.call
    - Price per unit: $0.005
    - Free threshold: 10,000 (included in subscription)
    ```

    <Info>
      使用仪表直接附加到订阅产品上。使用费用自动计算并添加到订阅发票中。
    </Info>
  </Step>

  <Step title="Create Checkout Session">
    创建一个包含订阅产品的结账会话。

    ```typescript theme={null}
    const session = await client.checkoutSessions.create({
      product_cart: [
        { product_id: 'prod_pro_plan', quantity: 1 }
      ],
      customer: { email: 'customer@example.com' },
      return_url: 'https://yourapp.com/success'
    });
    ```
  </Step>

  <Step title="Send Usage Events">
    在整个计费期间跟踪使用情况。

    ```typescript theme={null}
    await fetch('https://test.dodopayments.com/events/ingest', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        events: [{
          event_id: `call_${Date.now()}`,
          customer_id: 'cus_123',
          event_name: 'api.call',
          timestamp: new Date().toISOString(),
          metadata: { endpoint: '/v1/generate' }
        }]
      })
    });
    ```
  </Step>
</Steps>

### 定价变化

<Tabs>
  <Tab title="Included Allowance">
    免费门槛覆盖基础订阅中包含的使用。

    **专业计划：每月\$49**

    * 包含：10,000次API调用
    * 超量：每次调用\$0.005，超过10,000次
    * 客户使用8,000→支付\$49（无超量）
  </Tab>

  <Tab title="Zero Base + Pure Usage">
    无基础费用，从首次使用开始每个单位都按量计费。

    **按使用计费：基础\$0/月**

    * 包含：0次API调用
    * 使用：从首次调用开始每次调用\$0.01
    * 客户使用5,000→支付\$50
  </Tab>

  <Tab title="Tiered Allowances">
    不同层级包含不同津贴。

    * **入门**：每月\$19（1,000次调用包含）
    * **专业**：每月\$49（10,000次调用包含）
    * **企业**：每月\$199（100,000次调用包含）
    * 所有层级：超量每次调用\$0.005
  </Tab>
</Tabs>

***

## 混合模型 2：订阅 + 座席

平台费用加上每用户费用。适用于团队协作工具和 B2B SaaS。

### 如何运作

**团队计划：每月$99 + 每座席$15**

* **基础平台费用**：每月\$99（包括3个座席）
* **附加座席**：每座席每月\$15

**计算示例**（12用户团队）：

* 平台费用：\$99.00
* 额外座席：(12 - 3) × $15 = $135.00
* **总计：每月\$234.00**

### 使用场景

* **协作工具**：工作区费用+每成员
* **CRM 系统**：平台授权+每销售代表
* **项目管理**：团队计划+每贡献者
* **开发者工具**：组织费用+每开发者

### 实施

<Steps>
  <Step title="Create Seat Add-on">
    为附加座席创建附加功能。

    ```bash theme={null}
    Dashboard: Products → Add-ons → Create Add-on
    Name: "Additional Seat"
    Price: $15/month
    Description: "Add another team member"
    ```
  </Step>

  <Step title="Create Base Subscription">
    创建包含平台费的订阅产品并附加附加功能。

    ```bash theme={null}
    Dashboard: Create Product → Subscription
    Name: "Team Plan"
    Price: $99/month
    Description: "Includes 3 team members"

    Then in Add-ons section:
    - Attach: "Additional Seat" add-on
    ```
  </Step>

  <Step title="Create Checkout with Seats">
    在结账时指定座席数量。

    ```typescript theme={null}
    const session = await client.checkoutSessions.create({
      product_cart: [{
        product_id: 'prod_team_plan',
        quantity: 1,
        addons: [{
          addon_id: 'addon_seat',
          quantity: 9  // 9 extra seats (12 total with 3 included)
        }]
      }],
      customer: { email: 'admin@company.com' },
      return_url: 'https://yourapp.com/success'
    });
    ```
  </Step>

  <Step title="Adjust Seats as Needed">
    在现有订阅中增加或减少座席。

    ```typescript theme={null}
    // Add 5 more seats
    await client.subscriptions.changePlan('sub_123', {
      product_id: 'prod_team_plan',
      quantity: 1,
      proration_billing_mode: 'prorated_immediately',
      addons: [{
        addon_id: 'addon_seat',
        quantity: 14  // New total: 14 extra seats
      }]
    });
    ```
  </Step>
</Steps>

### 定价变化

<Tabs>
  <Tab title="Included Seats">
    基本计划包括一些座席，对额外座席收费。

    **团队计划：每月\$99**

    * 包含：5个座席
    * 额外座席：每座席每月\$15
    * 20用户 = $99 + (15 × $15) = \$324/月
  </Tab>

  <Tab title="Pure Per-Seat">
    无平台费用，仅按每用户收费。

    **每用户：\$25/用户/月**

    * 无平台费用
    * 5用户 = \$125/月
    * 50用户 = \$1,250/月

    实现：将基础订阅价格设置为\$0，仅使用座席附加。
  </Tab>

  <Tab title="Tiered Per-Seat">
    更高层级的每座席价格降低。

    * **入门**：每座席\$20（1-10个座席）
    * **增长**：每座席\$15（11-50个座席）
    * **企业**：每座席\$10（51+个座席）

    实现：为每个层级创建独立的订阅产品，附加不同加价。
  </Tab>
</Tabs>

***

## 混合模型 3：订阅 + 功能附加

核心订阅及可选的功能升级，客户可以选择添加。

### 如何运作

**核心计划：每月\$29**

**可选附加**：

* 高级分析：+\$19/月
* API访问：+\$9/月
* 优先支持：+\$29/月
* 白标化：+\$49/月

**计算示例**（客户选择核心+分析+API访问）：

* 核心计划：\$29.00
* 分析：\$19.00
* API 访问：\$9.00
* **总计：每月\$57.00**

### 使用场景

* **SaaS平台**：核心功能+高级模块
* **营销工具**：基础工具+集成
* **分析产品**：仪表板+高级报告
* **安全软件**：基本保护+高级功能

### 实施

<Steps>
  <Step title="Create Feature Add-ons">
    为每个可选功能创建附加功能。

    ```bash theme={null}
    # Add-on 1: Advanced Analytics
    Dashboard: Products → Add-ons → Create Add-on
    Name: "Advanced Analytics"
    Price: $19/month

    # Add-on 2: API Access
    Name: "API Access"
    Price: $9/month

    # Add-on 3: Priority Support
    Name: "Priority Support"
    Price: $29/month

    # Add-on 4: White-label
    Name: "White-label"
    Price: $49/month
    ```
  </Step>

  <Step title="Create Core Subscription">
    定义您的基础订阅并附加所有功能附加。

    ```bash theme={null}
    Dashboard: Create Product → Subscription
    Name: "Core Plan"
    Price: $29/month

    Then in Add-ons section:
    - Attach all feature add-ons
    ```
  </Step>

  <Step title="Let Customers Choose">
    根据选择的功能结账。

    ```typescript theme={null}
    const session = await client.checkoutSessions.create({
      product_cart: [{
        product_id: 'prod_core_plan',
        quantity: 1,
        addons: [
          { addon_id: 'addon_analytics', quantity: 1 },
          { addon_id: 'addon_api_access', quantity: 1 }
          // Customer didn't select support or white-label
        ]
      }],
      return_url: 'https://yourapp.com/success'
    });
    ```
  </Step>

  <Step title="Add Features Later">
    客户可以在现有订阅中添加功能。

    ```typescript theme={null}
    // Customer wants to add Priority Support
    await client.subscriptions.changePlan('sub_123', {
      product_id: 'prod_core_plan',
      quantity: 1,
      proration_billing_mode: 'prorated_immediately',
      addons: [
        { addon_id: 'addon_analytics', quantity: 1 },
        { addon_id: 'addon_api_access', quantity: 1 },
        { addon_id: 'addon_priority_support', quantity: 1 }  // New!
      ]
    });
    ```
  </Step>
</Steps>

***

## 混合模型 4：座席 + 使用

每用户费用结合消费型费用。每个用户都有一个津贴。

<Warning>
  **约束**：Dodo Payments 当前不支持将使用仪表和附加功能附加到同一个订阅产品。本模型需要使用应用级别逻辑的解决方案。
</Warning>

<Info>
  **即将上线**：即将支持座席+使用混合计费的本地支持。这将允许您将使用仪表和座席附加功能附加到同一个订阅产品。
</Info>

### 如何运作

**团队分析：每用户每月\$20**

**每用户包含：**

* 每月5GB数据处理
* 超量：每GB超出津贴\$2

**计算示例**（10用户团队总共使用80GB）：

* 座席费用：10 × $20 = $200.00
* 包含数据：10 × 5 GB = 50 GB
* 超量：(80 - 50) × $2 = $60.00
* **总计：每月\$260.00**

### 使用场景

* **分析平台**：每分析师+数据处理
* **设计工具**：每设计师+存储/导出
* **开发环境**：每开发者+计算小时
* **通信工具**：每用户+消息/通话量

### 实现选项

由于您无法将使用仪表和附加功能附加到同一个订阅中，选择以下一种方法：

<Tabs>
  <Tab title="Option A: Usage Product + App-Managed Seats">
    使用基于使用的订阅，在您的应用内管理座席计费。

    <Steps>
      <Step title="Create Usage Meter">
        ```bash theme={null}
        Dashboard: Meters → Create Meter
        Event Name: "data.processed"
        Aggregation: Sum
        Property: "bytes"
        ```
      </Step>

      <Step title="Create Usage-Based Subscription">
        ```bash theme={null}
        Dashboard: Create Product → Subscription
        Name: "Team Analytics"
        Base Price: $0/month

        Attach usage pricing:
        - Meter: data.processed
        - Price per unit: $2/GB
        - Free threshold: 0 (managed by your app)
        ```
      </Step>

      <Step title="Manage Seats in Your Application">
        分别跟踪座席数量和计算座席费用。

        ```typescript theme={null}
        // Your application tracks seats and calculates total cost
        async function calculateMonthlyBill(customerId: string) {
          const seatCount = await getSeatCount(customerId);
          const seatFee = seatCount * 20; // $20/seat

          // Usage is billed by Dodo automatically
          // You invoice/charge seat fees separately or include in base price

          // Alternatively, adjust base subscription price when seats change
          const totalBasePrice = seatCount * 2000; // $20/seat in cents
          await client.subscriptions.update('sub_123', {
            // Update subscription to reflect seat-based pricing
          });
        }
        ```
      </Step>

      <Step title="Calculate Dynamic Free Threshold">
        根据座席数量调整包含的使用量。

        ```typescript theme={null}
        // When checking usage, apply per-seat allowance
        async function checkUsageOverage(customerId: string) {
          const seatCount = await getSeatCount(customerId);
          const includedGB = seatCount * 5; // 5 GB per user

          const currentUsage = await getUsageFromDodo(customerId);
          const overage = Math.max(0, currentUsage - includedGB);

          // Overage is billed by Dodo at $2/GB
          return { included: includedGB, used: currentUsage, overage };
        }
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="Option B: Seat Add-on + On-Demand Usage Charges">
    使用附加功能为座席收费，并通过按需收费手动计算使用。

    <Steps>
      <Step title="Create Seat Add-on">
        ```bash theme={null}
        Dashboard: Products → Add-ons → Create Add-on
        Name: "Team Member"
        Price: $20/month
        ```
      </Step>

      <Step title="Create Subscription with Add-on">
        ```bash theme={null}
        Dashboard: Create Product → Subscription
        Name: "Team Analytics"
        Base Price: $0/month

        Attach add-on:
        - "Team Member" add-on

        Enable on-demand charging
        ```
      </Step>

      <Step title="Track Usage in Your Application">
        ```typescript theme={null}
        // Track usage events in your system
        async function trackDataProcessed(customerId: string, bytes: number) {
          await saveUsageEvent({
            customer_id: customerId,
            event_type: 'data.processed',
            bytes: bytes,
            timestamp: new Date()
          });
        }
        ```
      </Step>

      <Step title="Charge Usage at End of Cycle">
        手动计算并收费使用过量。

        ```typescript theme={null}
        async function billUsageOverage(subscriptionId: string) {
          const subscription = await getSubscription(subscriptionId);
          const seatCount = subscription.addons.find(a => a.id === 'addon_seat')?.quantity || 0;

          const includedGB = seatCount * 5;
          const usedGB = await calculatePeriodUsage(subscription.customer_id);
          const overageGB = Math.max(0, usedGB - includedGB);

          if (overageGB > 0) {
            const overageCharge = overageGB * 200; // $2/GB in cents
            await client.subscriptions.charge(subscriptionId, {
              product_price: overageCharge,
              product_description: `Data overage: ${overageGB} GB × $2/GB`
            });
          }
        }
        ```
      </Step>
    </Steps>
  </Tab>
</Tabs>

<Info>
  **推荐方案**：选择方案B（座席附加+按需使用）通常更容易实现，因为Dodo自动处理座席计费。您只需跟踪和收费使用过量。
</Info>

***

## 混合模型 5：订阅 + 座席 + 使用（三重混合）

最全面的模型：平台费+每用户+消费。

<Warning>
  **约束**：Dodo Payments 当前不支持将使用仪表和附加功能附加到同一个订阅产品。本模型需要解决方案方法。
</Warning>

<Info>
  **即将上线**：即将支持三重混合计费（基础+座席+使用）的本地支持。这将允许您将使用仪表和座席附加功能附加到同一个订阅产品。
</Info>

### 如何运作

**企业平台**

* **平台费用**：每月\$199
* **每座席**：每用户每月\$25
* **使用**：每1,000次API调用（包含50K）\$0.10

**计算示例**（公司拥有20个用户，150,000次API调用）：

* 平台：\$199.00
* 座席：20 × $25 = $500.00
* 使用：(150K - 50K) × $0.10/1K = $10.00
* **总计：每月\$709.00**

### 使用场景

* **企业SaaS**：平台+团队+消费
* **数据平台**：工作区+分析师+查询
* **集成平台**：中心+连接器+交易
* **AI平台**：工作区+开发者+推理

### 实施选项

选择以下一种方案实现三重混合计费：

<Tabs>
  <Tab title="Option A: Base + Seats (Add-on) + On-Demand Usage">
    使用带座席附加的订阅，通过按需费用手动计算使用。

    **这是推荐的方法**，因为Dodo会自动处理平台费用和座席费用。

    <Steps>
      <Step title="Create Seat Add-on">
        ```bash theme={null}
        Dashboard: Products → Add-ons → Create Add-on
        Name: "User Seat"
        Price: $25/month
        ```
      </Step>

      <Step title="Create Subscription Product">
        ```bash theme={null}
        Dashboard: Create Product → Subscription
        Name: "Enterprise Platform"
        Base Price: $199/month

        Attach add-on:
        - "User Seat" add-on

        Enable on-demand charging
        ```
      </Step>

      <Step title="Create Checkout with Seats">
        ```typescript theme={null}
        const session = await client.checkoutSessions.create({
          product_cart: [{
            product_id: 'prod_enterprise_platform',
            quantity: 1,
            addons: [{
              addon_id: 'addon_user_seat',
              quantity: 20  // 20 users
            }]
          }],
          customer: { email: 'enterprise@company.com' },
          return_url: 'https://yourapp.com/success'
        });
        ```
      </Step>

      <Step title="Track Usage in Your Application">
        在您系统中存储使用事件。

        ```typescript theme={null}
        // Track API calls in your system
        async function trackApiCall(customerId: string, endpoint: string) {
          await saveUsageEvent({
            customer_id: customerId,
            event_type: 'api.call',
            endpoint: endpoint,
            timestamp: new Date()
          });
        }
        ```
      </Step>

      <Step title="Charge Usage at End of Cycle">
        通过按需费用计算并收费使用。

        ```typescript theme={null}
        async function billUsageOverage(subscriptionId: string) {
          const usage = await calculatePeriodUsage(subscriptionId);
          const includedCalls = 50000;
          const overageCalls = Math.max(0, usage.totalCalls - includedCalls);

          if (overageCalls > 0) {
            // $0.10 per 1000 calls = $0.0001 per call
            const overageCharge = Math.ceil(overageCalls / 1000) * 10; // cents
            await client.subscriptions.charge(subscriptionId, {
              product_price: overageCharge,
              product_description: `API usage: ${overageCalls.toLocaleString()} calls over 50K included`
            });
          }
        }
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="Option B: Base + Usage (Meter) + App-Managed Seats">
    使用带有使用仪表的订阅，管理应用程序中的座席计费。

    <Steps>
      <Step title="Create Usage Meter">
        ```bash theme={null}
        Dashboard: Meters → Create Meter
        Event Name: "api.call"
        Aggregation: Count
        ```
      </Step>

      <Step title="Create Subscription Product with Usage">
        ```bash theme={null}
        Dashboard: Create Product → Subscription
        Name: "Enterprise Platform"
        Base Price: $199/month

        Attach usage pricing:
        - Meter: api.call
        - Price: $0.10 per 1000 calls
        - Free threshold: 50,000
        ```
      </Step>

      <Step title="Manage Seats in Your Application">
        跟踪座席数量并相应调整基础订阅价格。

        ```typescript theme={null}
        // When seats change, update subscription price
        async function updateSeatCount(subscriptionId: string, newSeatCount: number) {
          const basePlatformFee = 19900; // $199 in cents
          const perSeatFee = 2500; // $25 in cents
          const totalPrice = basePlatformFee + (newSeatCount * perSeatFee);

          // Store seat count in your system
          await updateSeatsInDatabase(subscriptionId, newSeatCount);

          // Note: You may need to handle this via plan changes or
          // create multiple tier products for common seat counts
        }
        ```
      </Step>

      <Step title="Send Usage Events to Dodo">
        ```typescript theme={null}
        await fetch('https://test.dodopayments.com/events/ingest', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            events: [{
              event_id: `api_${Date.now()}`,
              customer_id: 'cus_enterprise',
              event_name: 'api.call',
              timestamp: new Date().toISOString()
            }]
          })
        });
        ```
      </Step>
    </Steps>
  </Tab>
</Tabs>

<Info>
  **推荐方案**：选择方案A（基础+座席+按需使用）通常更容易，因为Dodo会自动处理平台和座席计费。您只需跟踪使用并在每个计费周期结束时提交费用。
</Info>

***

## 混合模型 6：分级基础+使用超量

不同订阅层级，包含不同的津贴和超量费率。

### 如何运作

| 层级     | 价格      | 包含调用    | 超量费率        |
| ------ | ------- | ------- | ----------- |
| **入门** | 每月\$19  | 1,000   | 每次调用\$0.02  |
| **专业** | 每月\$79  | 25,000  | 每次调用\$0.01  |
| **商业** | 每月\$199 | 100,000 | 每次调用\$0.005 |
| **企业** | 每月\$499 | 500,000 | 每次调用\$0.002 |

### 实施

为每个层级创建单独的订阅产品，每个具有自己的使用配置：

```bash theme={null}
# For each tier, create a subscription product:

# Starter Tier
Dashboard: Create Product → Subscription
Name: "Starter"
Base Price: $19/month
Usage Pricing:
- Meter: api.call
- Price: $0.02/call
- Free threshold: 1,000

# Pro Tier
Name: "Pro"
Base Price: $79/month
Usage Pricing:
- Meter: api.call
- Price: $0.01/call
- Free threshold: 25,000

# ... and so on for Business and Enterprise
```

### 升级路径

当客户升级层级时，他们将获得：

* 更高的包含津贴
* 更低的超量费率
* 每美元的更多价值

```typescript theme={null}
// Customer upgrades from Starter to Pro
await client.subscriptions.changePlan('sub_123', {
  product_id: 'prod_pro',
  quantity: 1,
  proration_billing_mode: 'prorated_immediately'
});
```

***

## 混合模型 7：订阅 + 按需收费

经常性订阅加上可变的手动服务或超量费用。

### 如何运作

**保留计划：每月\$199**

**包含：**

* 平台访问
* 每月5小时咨询
* 邮件支持

**按需收费（根据需要）：**

* 额外咨询：每小时\$150
* 定制开发：每小时\$200
* 紧急支持：每次\$100

**计算示例**（本月）：

* 保留：\$199.00
* 额外咨询3小时：\$450.00
* 1次紧急支持：\$100.00
* **总计：\$749.00**

### 使用场景

* **咨询服务**：保留+按小时计费
* **管理服务**：基本费用+事件收费
* **代理服务**：每月费用+项目收费
* **支持计划**：SLA费用+每票或每小时

### 实施

<Steps>
  <Step title="Create On-Demand Subscription">
    设置启用按需收费的订阅。

    ```typescript theme={null}
    const subscription = await client.subscriptions.create({
      billing: {
        city: 'San Francisco',
        country: 'US',
        state: 'CA',
        street: '123 Main St',
        zipcode: '94105'
      },
      customer: { customer_id: 'cus_123' },
      product_id: 'prod_retainer',
      quantity: 1,
      payment_link: true,
      return_url: 'https://yourapp.com/success',
      on_demand: {
        mandate_only: false,
        product_price: 19900  // $199 initial charge
      }
    });
    ```
  </Step>

  <Step title="Charge for Services">
    提供服务时创建费用。

    ```typescript theme={null}
    // Charge for 3 hours of consulting
    await client.subscriptions.charge('sub_123', {
      product_price: 45000,  // $450.00 (3 × $150)
      product_description: 'Consulting - 3 hours (March 15)'
    });

    // Charge for emergency support incident
    await client.subscriptions.charge('sub_123', {
      product_price: 10000,  // $100.00
      product_description: 'Emergency support - Server outage (March 18)'
    });
    ```
  </Step>

  <Step title="Track and Invoice">
    所有费用都会显示在客户的发票上。

    ```typescript theme={null}
    // Retrieve subscription charges
    const payments = await client.payments.list({
      subscription_id: 'sub_123'
    });

    // Show itemized breakdown to customer
    payments.items.forEach(payment => {
      console.log(`${payment.description}: $${payment.amount / 100}`);
    });
    ```
  </Step>
</Steps>

***

## 实际案例

<Info>
  这些示例显示了理想的定价结构。由于使用仪表和附加功能无法附加到同一产品上，某些组合需要解决方案（使用按需收费处理使用或应用管理座席）。
</Info>

### 示例1：AI SaaS 平台

**定价结构：**

* **基础订阅**：每月\$99（平台访问，包含5个座席）
* **座席附加**：每座席每月\$20
* **功能附加**：自定义模型（$49/月），API访问（$29/月），优先队列（\$19/月）
* **使用超量**：每1,000个令牌超过100K后\$0.02（按需收费）

**实施**：使用带座席和功能附加的订阅。在应用程序中跟踪令牌使用量，并在计费周期结束时以按需收费方式收取费用。

**示例客户**（12个用户，500,000个令牌，自定义模型+API访问）：

| 组件     | 计算                   | 金额          |
| ------ | -------------------- | ----------- |
| 基础     | 平台费用                 | \$99        |
| 额外座席   | 7 × \$20             | \$140       |
| 自定义模型  | 附加功能                 | \$49        |
| API访问  | 附加功能                 | \$29        |
| 令牌超量   | 400K × \$0.02/1K（按需） | \$8         |
| **总计** |                      | **每月\$325** |

### 示例2：开发者工具平台

**层级选项：**

|        | 免费    | 专业     | 企业      |
| ------ | ----- | ------ | ------- |
| **价格** | \$0/月 | \$29/月 | \$199/月 |
| **用户** | 1     | 包括5个   | 无限      |
| **构建** | 100   | 1,000  | 10,000  |
| **存储** | 1 GB  | 10 GB  | 100 GB  |

**实施选项：**

**选项A**（以使用为重点）：为构建/存储创建具有使用仪表的产品。在应用程序中管理用户。

**选项B**（以座席为重点）：创建具有座席附加的产品。跟踪构建/存储使用，并通过按需收费处理超量。

**附加功能（如果选择选项B）：**

* 额外用户：每用户每月\$10
* 优先构建：每月\$19
* 自定义域名：每域名每月\$9

### 示例3：营销自动化

**定价结构：**

* **基础**：每月\$79（核心自动化功能，包含3个座席）
* **联系人层级**（附加功能）：包含1K，+5K（+$30），+25K（+$80），+100K（+\$200）
* **功能附加**：短信营销（$29/月），页面登录（$19/月），A/B测试（\$29/月）
* **团队座席**：每用户每月\$15附加
* **邮件量**：在应用程序中跟踪，通过按需收费处理超量（超限每千封邮件\$1）

**实施**：使用联系人层级附加、功能附加和座席附加的订阅。在应用程序中跟踪邮件发送，并通过按需收费处理超量。

***

## 实施最佳实践

### 定价页面清晰度

<Tip>
  使混合定价易于理解。在您的定价页面上突出显示基础费用、包括内容以及超量费的工作原理。
</Tip>

**良好示例**："$49/月包括10,000次API调用。附加调用：每次$0.005"

**不良示例**："\$49/月 + 使用费"

### 成本可预测性

帮助客户估算他们的成本：

```typescript theme={null}
// Provide a cost calculator
function estimateMonthlyCost({
  plan,
  seats,
  expectedUsage,
  addons
}: EstimateParams): number {
  let total = plan.basePrice;

  // Add seat costs
  const extraSeats = Math.max(0, seats - plan.includedSeats);
  total += extraSeats * plan.seatPrice;

  // Add usage overage
  const overage = Math.max(0, expectedUsage - plan.includedUsage);
  total += overage * plan.overageRate;

  // Add feature add-ons
  total += addons.reduce((sum, addon) => sum + addon.price, 0);

  return total;
}
```

### 使用可见性

实时显示给客户他们的使用情况：

```typescript theme={null}
// Display usage dashboard
async function getUsageSummary(subscriptionId: string) {
  const usage = await client.subscriptions.retrieveUsageHistory(subscriptionId);

  // Each item is a billing period; each meter reports its usage for that period.
  const latestPeriod = usage.items[0];

  return latestPeriod.meters.map((meter) => {
    const consumed = Number(meter.consumed_units);
    const chargeable = Number(meter.chargeable_units);
    return {
      meter: meter.name,
      current: consumed,
      included: meter.free_threshold,
      remaining: Math.max(0, meter.free_threshold - consumed),
      overage: chargeable,
      cost: meter.total_price
    };
  });
}
```

### 计费透明度

提供显示所有组成部分的详细发票：

| 项目                               | 金额           |
| -------------------------------- | ------------ |
| 专业计划（月度）                         | \$49.00      |
| 附加座席（7 × \$15.00）                | \$105.00     |
| API 使用 - 包含（10,000 次调用）          | \$0.00       |
| API 使用 - 超量（15,420次调用 × \$0.005） | \$77.10      |
| 高级分析附加                           | \$19.00      |
| **小计**                           | **\$250.10** |
| 税（8.5%）                          | \$21.26      |
| **应付总额**                         | **\$271.36** |

***

## 混合计费故障排除

<AccordionGroup>
  <Accordion title="Usage not being tracked correctly">
    **症状**：使用量显示0或不正确的值。

    **解决方案：**

    1. 验证事件接收是否正常（检查API响应）
    2. 确认`customer_id`匹配订阅客户
    3. 检查`event_name`匹配计量配置
    4. 验证事件的时间戳是否正确（不是未来日期）
  </Accordion>

  <Accordion title="Proration confusion with multiple components">
    **症状**：更改计划时客户被收取意外费用。

    **解决方案：**

    1. 使用`previewChangePlan` API显示准确费用之前进行确认
    2. 说明分摊适用于订阅和附加功能
    3. 考虑使用`difference_immediately`简化升级计费
  </Accordion>

  <Accordion title="Free threshold not applying correctly">
    **症状**：客户支付本应免费的使用费用。

    **解决方案：**

    1. 验证免费门槛是否配置在基于使用的产品上
    2. 检查门槛单位是否与事件聚合一致（调用与请求）
    3. 确认使用仪表是否正确附加到订阅产品上
  </Accordion>

  <Accordion title="Add-ons not appearing in checkout">
    **症状**：结账时无法添加座席或功能。

    **解决方案：**

    1. 验证附加功能是否附加到仪表板中的订阅产品上
    2. 检查API调用中的附加功能ID是否正确
    3. 确保附加功能货币与订阅产品货币相符
  </Accordion>
</AccordionGroup>

***

## 相关文档

<CardGroup cols={2}>
  <Card title="Products" icon="box" href="/features/products">
    所有产品类型和指南概览。
  </Card>

  <Card title="Usage-Based Billing Guide" icon="chart-line" href="/developer-resources/usage-based-billing-guide">
    完整的使用计费实现。
  </Card>

  <Card title="Subscription Management" icon="repeat" href="/features/subscription">
    管理经常性订阅。
  </Card>

  <Card title="Add-ons" icon="puzzle" href="/features/addons">
    使用附加功能扩展订阅。
  </Card>
</CardGroup>
