---
title: "订单处理"
description: "向买家扣款，等卖家批准发货，然后发货。发货一直失败时，给买家退款。"
canonical_url: "https://docs.superdurable.io/zh-Hans/examples/order-processing/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/use-cases/order-processing.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/order-processing.go.md) · [Java](https://docs.superdurable.io/zh-Hans/examples/order-processing.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/examples/order-processing.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/examples/order-processing.rust.md)

向买家扣款，等卖家批准发货，然后发货。发货一直失败时，给买家退款。

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

**展示：**[提醒](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/reminder.md)、[Execute 失败恢复](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/execute-failure-recovery.md)和[等待 Step 完成](https://docs.superdurable.io/zh-Hans/design-patterns/responsive-update/wait-for-step-completion.md)。

**Flow 图：OrderProcessingFlow**

**Step 列表**

1. `Charge`（起始 Step）：Charge the customer for the order. 下一步：`Ship`。 写入 `order-status`。
2. `Refund`：Refund the order when shipping keeps failing. 下一步：Flow 完成。 写入 `order-status`。
3. `Ship`：Wait for seller approval, remind after 24 hours, then ship the order. 下一步：`Ship`（再次）、Flow 完成，或 `Refund`（持续失败时）。 写入 `order-status`。

**RPC 列表**

- `approve`：发布到 `seller-ok`。
- `describe`：读取 `order-status`。

例子: [examples/python/dex_examples/products/order-processing/order_processing_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/order-processing/order_processing_flow.py)

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

## Flow 设计

<a id="how-the-flow-works"></a>

- **Charge** 向买家扣款，并把 **order-status** Attribute 设为 `charged`。
- **Ship** 等待 **seller-ok** Channel 上的卖家批准，或一个 24 小时的 Timer。Timer 先触发时，Ship 发一封提醒，然后再等一轮。批准之后，它发货，把 **order-status** 设为 `shipped`，并以输出 `shipped:<订单 ID>` 完成 Flow。
- **Refund** 在 Ship 的重试用完后运行。它给买家退款，把 **order-status** 设为 `refunded`，并以 `refunded:<订单 ID>` 完成 Flow。图中 Step 上的 ⚠ 表示一条失败路由；选中这个 Step 可以看到它通向哪里。

**approve** RPC 把批准消息发到 **seller-ok**。**describe** RPC 返回 **order-status**。

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

## 核心实现

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

<a id="2-flow-steps-and-rpcs"></a>

<a id="2-flowstep-和-rpc"></a>

扣款、发货和退款调用都带上用订单 ID 构造的幂等键，订单 ID 也就是 Flow ID：`charge-<订单 ID>`、`ship-<订单 ID>` 和 `refund-<订单 ID>`。被中断的 Step 可能带着同一个键再次运行，所以支付和发货服务可以丢弃重复的调用。见 [幂等键](https://docs.superdurable.io/zh-Hans/concepts/step.md#idempotency-keys)。真实的提醒邮件也需要幂等键，因为被中断的 Step 可能再次运行。示例没有传。

每个 Step 的 Execute 有 3 秒的重试预算，让演示很快结束；代码注释建议生产环境用一小时。Ship 的失败路由转到 Refund，Refund 有自己的短重试。

Flow 通过 constructor 拿到服务（[Flow 包含什么](https://docs.superdurable.io/zh-Hans/concepts/flow.md#implement-a-flow)）。**order-status** 建了索引，所以可以按状态搜索 Flow。`dex:group` 和 `dex:explanation` 注释标注上图中的各个 Step。

**Python**

```python
order_status = Attribute(
    "order-status",
    str,
    AttributeIndex(IndexType.KEYWORD, "keyword1"),
)
seller_ok = Channel[str]("seller-ok", str)


# dex:group group-id:payment group-label:"Payment"
# dex:explanation text:"Charge the customer for the order."
class Charge(Step[OrderRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_retry=RetryPolicy(
                # One hour in production; 3 seconds keeps the demo short.
                total_duration=timedelta(seconds=3),
            )
        )

    def execute(self, context: Context, input: OrderRequest) -> StepDecision:
        self.service.charge_user(
            input.email,
            input.customer_id,
            input.amount,
            idempotency_key=f"charge-{input.order_id}",
        )
        order_status.set(context, "charged")
        return go_to(Ship, input)


# dex:group group-id:shipping group-label:"Shipping"
# dex:explanation text:"Wait for seller approval, remind after 24 hours, then ship the order."
class Ship(Step[OrderRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_retry=RetryPolicy(
                # One hour in production; 3 seconds keeps the demo short.
                total_duration=timedelta(seconds=3),
            )
        ).on_execute_failure_proceed_to(
            Refund,
            StepOptions(
                execute_retry=RetryPolicy(
                    # One hour in production; 3 seconds keeps the demo short.
                    total_duration=timedelta(seconds=3),
                )
            ),
        )

    def wait_for(self, context: Context, input: OrderRequest) -> Wait:
        return Wait.any_of(
            seller_ok.for_one(),
            Timer.by_duration(timedelta(hours=24)),
        )

    def execute(self, context: Context, input: OrderRequest) -> StepDecision:
        if context.has_timer_fired():
            self.service.send_email(
                input.email,
                "Reminder: approve shipment",
                "Please approve or provide a tracking number.",
            )
            return go_to(Ship, input)
        self.service.ship_item(
            input.order_id,
            input.test_fail_at_shipping,
            idempotency_key=f"ship-{input.order_id}",
        )
        order_status.set(context, "shipped")
        return graceful_complete(f"shipped:{input.order_id}")


# dex:group group-id:refund group-label:"Refund"
# dex:explanation text:"Refund the order when shipping keeps failing."
class Refund(Step[OrderRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service

    def execute(self, context: Context, input: OrderRequest) -> StepDecision:
        self.service.update_external_system(
            f"refund {input.order_id}", idempotency_key=f"refund-{input.order_id}"
        )
        order_status.set(context, "refunded")
        return graceful_complete(f"refunded:{input.order_id}")


class OrderProcessingFlow(Flow[OrderRequest]):
    def __init__(self, service: MyDependencyService) -> None:
        self.service = service
        self.refund = Refund(service)
        self.ship = Ship(service)
        self.charge = Charge(service)

    def get_steps(self) -> StepList[OrderRequest]:
        return StepList.start_step(self.charge).other_steps(self.ship, self.refund)

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(order_status, seller_ok)

    @rpc
    def approve(self, context: Context, _note: str) -> RPCResult[str]:
        seller_ok.publish(context, "approved")
        return RPCResult("ok")

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

例子: [examples/python/dex_examples/products/order-processing/order_processing_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/order-processing/order_processing_flow.py)

<a id="http-handlers"></a>

## HTTP 处理器

<a id="3-worker-and-client"></a>

<a id="4-controller"></a>

<a id="3-worker-和-client"></a>

示例应用在同一个进程里运行 Worker 和这些 handler。**start** 启动 Flow，用 Client 的 wait-for-Step-completion API 等 Charge 完成后才返回。**approve** 和 **describe** 调用同名的 RPC。

**Python**

```python
    @blueprint.get("/start")
    async def start() -> Response:
        flow_id = new_flow_id("order-processing")
        request = OrderRequest(
            flow_id,
            "buyer@example.com",
            "customer-1",
            42,
            optional_query("testFailAtShipping", "") == "true",
        )
        run_id = await app_state.client.start_flow(
            app_state.order_processing,
            flow_id,
            request,
            start_options(),
        )
        await app_state.client.wait_for_step_completion(
            flow_id,
            CHARGE_STEP,
            WaitForStepCompletionOptions(),
        )
        return started_flow(flow_id, run_id)

    @blueprint.get("/approve")
    async def approve() -> Response:
        output = await app_state.client.invoke_rpc(
            app_state.order_processing.approve,
            _required_flow_id(),
            optional_query("notes", ""),
        )
        return jsonify(output)

    @blueprint.get("/describe")
    async def describe() -> Response:
        flow_id = _required_flow_id()
        status = await app_state.client.invoke_rpc(
            app_state.order_processing.describe,
            flow_id,
        )
        return jsonify({"flowID": flow_id, "status": status})

    return blueprint


def _required_flow_id() -> str:
    """Reads the Flow ID from flowId, or from its alias workflowId."""
    return optional_query("workflowId", "") or required_query("flowId")
```

例子: [examples/python/dex_examples/products/order-processing/controller.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/order-processing/controller.py)

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

## 运行

<a id="1-start-dex"></a>

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

<a id="1-启动-dex"></a>

<a id="5-运行"></a>

按[在 playground 里运行一个示例](https://docs.superdurable.io/zh-Hans/install.md#run-an-example-from-the-playground)启动一种语言的示例。然后创建一个订单：

```bash
curl -s 'http://127.0.0.1:8080/products/order-processing/start'
```

从响应里复制 `flowID`。在 Dex Web（`dexcli dev` 打印的地址，例如 `http://127.0.0.1:8802`）里，这条 Flow 停在 Ship 等待。把 `FLOW_ID` 换成它，批准发货：

```bash
curl -s "http://127.0.0.1:8080/products/order-processing/approve?flowId=FLOW_ID"
```

这个调用把批准消息发到 **seller-ok**。随后 Ship 发货，Flow 完成；可以在 Dex Web 里看到这个过程。也可以在 [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) 里选择 **Order processing**，做同样的调用。

<a id="try-the-refund-path"></a>

### 试试退款路径

<a id="试试退款路径"></a>

创建一个发货总会失败的订单：

```bash
curl -s 'http://127.0.0.1:8080/products/order-processing/start?testFailAtShipping=true'
```

复制新的 `flowID`，像上面一样批准它。随后 Ship 一直失败，直到 3 秒的重试预算用完，然后 Refund 运行。在 Dex Web 里等到 Refund 完成，或者重复下面的调用，直到状态变成 **refunded**：

```bash
curl -s "http://127.0.0.1:8080/products/order-processing/describe?flowId=FLOW_ID"
```

在 Dex Web 的 **Events** 下，**Graph** 显示 Charge、Ship，然后是 Refund。

<a id="dex-web"></a>

## 在 Dex Web 中查看运行

<a id="6-dex-web"></a>

打开一次已批准的运行，选择 **Events**。**Timeline** 按顺序显示扣款、批准和发货；选中一个事件可以读取它的输入和输出。**Graph** 显示各 Step 如何衔接。

[![Dex Web Timeline 展示订单从扣款、批准到发货的过程](https://docs.superdurable.io/img/use-cases/order-processing-timeline.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/order-processing-timeline.png)

[![Dex Web Graph 展示订单从扣款、批准到发货的过程](https://docs.superdurable.io/img/use-cases/order-processing-graph.png)](https://docs.superdurable.io/zh-Hans/img/use-cases/order-processing-graph.png)

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

## 下一步

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

- [订阅与计费生命周期](https://docs.superdurable.io/zh-Hans/examples/subscription-and-billing-lifecycle.md)：下一个示例。
- [概念](https://docs.superdurable.io/zh-Hans/concepts.md)：这个示例用到的 Flow、Step、Channel 和 Timer。
- [应用](https://docs.superdurable.io/zh-Hans/concepts/application.md)：在你自己的服务里加入 Worker 和 Client。
- [示例](https://docs.superdurable.io/zh-Hans/examples.md)：更多示例。
