---
title: "订阅与计费生命周期"
description: "让订阅经历试用期、各个计费周期、价格调整和取消。Flow 在持久的 Timer 和 Channel 上等待，所以一个订阅可以运行几个月。"
canonical_url: "https://docs.superdurable.io/zh-Hans/examples/subscription-and-billing-lifecycle/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/use-cases/subscription.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# 订阅与计费生命周期

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/examples/subscription-and-billing-lifecycle.go.md) · [Java](https://docs.superdurable.io/zh-Hans/examples/subscription-and-billing-lifecycle.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/examples/subscription-and-billing-lifecycle.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/examples/subscription-and-billing-lifecycle.rust.md)

让订阅经历试用期、各个计费周期、价格调整和取消。Flow 在持久的 Timer 和 Channel 上等待，所以一个订阅可以运行几个月。

**SDK：** Python · Go · TypeScript · Java · Rust

**展示：**[循环 Timer](https://docs.superdurable.io/zh-Hans/concepts/primitives/timer.md)、[静态并行 Step](https://docs.superdurable.io/zh-Hans/design-patterns/parallel/static-parallel-steps.md)。

**Flow 图：SubscriptionFlow**

**Step 列表**

1. `Initialize`（起始 Step）：Store the customer and start the trial, cancel, and charge update paths. 下一步：`Cancel`、`Trial`，或 `UpdateChargeAmount`。 写入 `billing-period-number`、`customer`。
2. `Cancel`：Wait for a cancel request and end the subscription. 下一步：Flow 立即完成。 读取 `customer`。
3. `ChargeCurrentBill`：Charge each billing period until the subscription ends. 下一步：Flow 立即完成，或 `ChargeCurrentBill`（再次）。 读取 `billing-period-number`、`customer`；写入 `billing-period-number`。
4. `Trial`：Wait for the trial period to end. 下一步：`ChargeCurrentBill`。 读取 `customer`。
5. `UpdateChargeAmount`：Apply each new charge amount the customer requests. 下一步：`UpdateChargeAmount`（再次）。 读取 `customer`、`update-charge-amount`；写入 `customer`。

**RPC 列表**

- `cancel_subscription_rpc`：发布到 `cancel-subscription`。
- `describe`：读取 `customer`。
- `get_customer`：读取 `customer`。
- `update_charge`：发布到 `update-charge-amount`。

例子: [examples/python/dex_examples/products/subscription/subscription_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/subscription/subscription_flow.py)

图和下面的说明对应 Python、Go、Java 和 TypeScript 示例。[Rust 示例](https://docs.superdurable.io/zh-Hans/examples/subscription-and-billing-lifecycle.md#rust-example)有所不同。

<a id="product-requirements"></a>

## 产品需求

<a id="产品需求"></a>

订阅计划规定试用时长、计费周期时长、计费周期数和扣费金额。订阅必须：

1. 发送欢迎邮件，试用期结束前不扣费。
2. 每个计费周期扣费一次。最后一个周期结束后，通知客户并结束。
3. 随时接受新的扣费金额。Flow 应用它之后开始的扣费使用新金额。
4. 随时接受取消：通知客户并结束订阅。
5. 通过 `describe` RPC 返回订阅计划。

<a id="flow-design"></a>

## Flow 设计

<a id="flow-设计"></a>

**Initialize** 把客户和计费周期计数器存进 Attribute，然后启动三个分支。**Trial** 发送欢迎邮件并等待试用期 Timer。随后 **ChargeCurrentBill** 循环运行：它的 WaitFor 把周期数加一并等待本周期的 Timer，它的 Execute 扣费后回到 **ChargeCurrentBill**。最后一个周期结束后，它通知客户并强制完成 Flow。**Cancel** 等待一条取消消息，通知客户并强制完成 Flow。**UpdateChargeAmount** 每次应用一个新金额，然后回到自身。

这个设计有两个关键选择：

- 每个分支都从 Attribute 读取客户和计划。更新金额的 RPC 只把新金额放进队列，由 **UpdateChargeAmount** 写入。在这个 Step 提交之后才开始的计费 Execute 会读到新金额。已经在运行的扣费仍用旧金额，重试时也一样。
- 强制完成 Flow 时，其他分支的等待也随之结束，不需要哪个分支去停止其他分支。

取消可能在一次扣费进行中到达。**Cancel** 会结束 Flow，但已经发给支付提供方的扣费仍可能完成。这种情况由你的退款和权益策略决定。

真实的支付调用需要[幂等键](https://docs.superdurable.io/zh-Hans/concepts/step.md#idempotency-keys)，因为被中断的 Step 可能再次运行。示例没有传。合适的键是 Flow ID 加计费周期数。WaitFor 在 Execute 扣费之前提交这个周期数，所以同一次扣费的每次重试都发送相同的键，提供方可以丢弃重复的请求。欢迎、结束和取消邮件也各需要自己的键，例如 Flow ID 加邮件用途。

<a id="core-implementation"></a>

## 核心实现

<a id="核心实现"></a>

每个标签页展示可运行示例中的 Flow 类。上面的图来自 Python 的 Flow；Go、TypeScript 和 Java 的 Step 相同。

**Python**

```python
class SubscriptionFlow(Flow[Customer]):
    billing_period_number = Attribute("billing-period-number", int)
    customer_details = Attribute("customer", Customer)
    cancel_subscription = Channel[None]("cancel-subscription", type(None))
    update_charge_amount = Channel("update-charge-amount", int)

    def __init__(self, service: MyDependencyService) -> None:
        self.service = service
        self.charge_current_bill = ChargeCurrentBill(
            service,
            self.customer_details,
            self.billing_period_number,
        )
        self.trial = Trial(
            service,
            self.customer_details,
            self.billing_period_number,
            self.charge_current_bill,
        )
        self.cancel = Cancel(
            service,
            self.customer_details,
            self.cancel_subscription,
        )
        self.update_charge_amount_step = UpdateChargeAmount(
            self.customer_details,
            self.update_charge_amount,
        )
        self.initialize = Initialize(
            self.customer_details,
            self.billing_period_number,
            self.trial,
            self.cancel,
            self.update_charge_amount_step,
        )

    def get_steps(self) -> StepList[Customer]:
        return StepList.start_step(self.initialize).other_steps(
            self.trial,
            self.charge_current_bill,
            self.cancel,
            self.update_charge_amount_step,
        )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(
            self.billing_period_number,
            self.customer_details,
            self.cancel_subscription,
            self.update_charge_amount,
        )

    @rpc
    def describe(self, context: Context) -> RPCResult[Subscription]:
        return RPCResult(self.customer_details.get(context).subscription)
```

例子: [examples/python/dex_examples/products/subscription/subscription_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/subscription/subscription_flow.py)

<a id="rust-example"></a>

## Rust 示例

Rust 示例更小，不调用任何服务。**Welcome** 保存订阅状态并记录一条欢迎事件，没有试用期。然后它启动两个分支。**Billing** 等待一天的 Timer，然后把已扣费周期数加一。**Control** 每次从一个命令 Channel 取一条消息，更新金额和取消的 RPC 都发布到这个 Channel。它把新金额或取消写进状态，取消时强制完成 Flow。最后一个周期之后，**Billing** 请求优雅完成，而优雅完成要等 **Control** 结束，所以这次运行只会因取消而结束。两个 Step 都在不加锁的情况下读写整个状态，所以一方可能覆盖另一方的改动。

在 playground 中，**Start** 创建一个三个周期、每期 1000 cents 的计划。调用 **Update charge amount**，然后用返回的 Flow ID 反复调用 **Describe**，直到它显示新金额。**Describe** 返回金额、已扣费周期数和取消标志。**Cancel** 结束这次运行。

<a id="run-it"></a>

## 运行

<a id="demo"></a>

<a id="演示"></a>

按[在 playground 里运行一个示例](https://docs.superdurable.io/zh-Hans/install.md#run-an-example-from-the-playground)启动一种语言的示例。然后在 [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) 中打开 **Subscription**：

1. **Start** 返回新的 Flow ID。它启动 20 秒的试用期和十个 10 秒的计费周期，每期扣费 100。
2. 用这个 Flow ID 调用 **Update charge amount**，新金额进入队列。反复调用 **Describe**，直到它显示新金额；此后开始的扣费使用它。
3. **Cancel** 把取消放进队列，随后 **Cancel** Step 结束订阅。

在 Dex Web 中打开这次运行的 **Events**。**Timeline** 显示价格更新和取消。**Graph** 显示取消结束 Flow 时，哪些 Step 已完成、哪些仍在等待。

[![Dex Web Timeline 展示订阅价格更新和取消](https://docs.superdurable.io/img/use-cases/subscription-timeline.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/subscription-timeline.png)

[![Dex Web Graph 展示订阅价格更新和取消](https://docs.superdurable.io/img/use-cases/subscription-graph.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/subscription-graph.png)

<a id="next"></a>

## 下一步

<a id="下一步"></a>

[用户入驻流程](https://docs.superdurable.io/zh-Hans/examples/user-onboarding-process.md)
