---
title: "客户退款"
description: "Flow 根据订单和退款政策检查客户的退款申请，金额较大时等待经理审批，然后退款并给客户发邮件。Go 还有两个更大的退款 Flow：确定性策略和 agentic 审核。"
canonical_url: "https://docs.superdurable.io/zh-Hans/examples/customer-refund/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/use-cases/customer-refund.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/customer-refund.go.md) · [Java](https://docs.superdurable.io/zh-Hans/examples/customer-refund.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/examples/customer-refund.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/examples/customer-refund.rust.md)

Flow 根据订单和退款政策检查客户的退款申请，金额较大时等待经理审批，然后退款并给客户发邮件。Go 还有两个更大的退款 Flow：[确定性策略](https://docs.superdurable.io/zh-Hans/examples/customer-refund.md#deterministic-policy)和 [agentic 审核](https://docs.superdurable.io/zh-Hans/examples/customer-refund.md#agentic-review)。

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

**展示：** 通过 [Channel](https://docs.superdurable.io/zh-Hans/concepts/primitives/channel.md) 和 [RPC](https://docs.superdurable.io/zh-Hans/concepts/primitives/rpc.md) 完成经理审批、Dex Web [Action](https://docs.superdurable.io/zh-Hans/reference/web/dex-web.md#actions)、[幂等 key](https://docs.superdurable.io/zh-Hans/concepts/step.md#idempotency-keys)，以及 [Time Travel](https://docs.superdurable.io/zh-Hans/production-operations/operate-and-debug.md#time-travel)。

**Flow 图：CustomerRefundFlow**

**Step 列表**

1. `ReceiveRequest`（起始 Step）：Record the refund request and the customer's email address. 下一步：`CheckOrder`。 写入 `case-status`、`customer-email`。
2. `CheckOrder`：Look up the order in billing. 下一步：`CheckPolicy`。
3. `CheckPolicy`：Refund, deny, or ask a manager, by the refund policy. 下一步：`WriteCustomerMessage`、`RequestManagerApproval`，或 `IssueRefund`。 写入 `case-status`。
4. `CloseCase`：Close the case with its outcome. 下一步：Flow 完成。 写入 `case-status`。
5. `IssueRefund`：Refund the order through billing, once per case. 下一步：`WriteCustomerMessage`。 写入 `case-status`、`refund-id`。
6. `RequestManagerApproval`：Wait for a manager to approve or reject the refund. 下一步：`IssueRefund`，或 `WriteCustomerMessage`。 读取 `manager-decisions`；写入 `case-status`。
7. `SendMessage`：Email the message to the customer, once per case. 下一步：`CloseCase`。
8. `WriteCustomerMessage`：Ask the model to write the customer message. 下一步：`SendMessage`。 写入 `customer-message`。

**RPC 列表**

- `approve_refund`：读取 `case-status`；锁定 `case-status`；写入 `case-status`；发布到 `manager-decisions`。
- `reject_refund`：读取 `case-status`；锁定 `case-status`；写入 `case-status`；发布到 `manager-decisions`。

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

<a id="refund-with-manager-approval"></a>

## 经理审批的退款

这张图由 Python 源码生成。在 TypeScript、Java 和 Rust 中，**Check policy** 只有一条拒绝分支，而不是两条。在 Go 中，Flow 类型是 `ManagerApprovalRefundFlow`，因为 `CustomerRefundFlow` 已是确定性策略的 Go Flow。

**Check policy** 应用退款政策。超过 30 天的扣款，或没有记录到服务中断的扣款，会被拒绝。1,000 USD 或以下的金额直接进入 **Issue refund**，更大的金额进入 **Request manager approval**。这个 Step 在一个 Channel 上等待一条消息，再按经理的决定退款或拒绝。

**Python**

```python
class CheckPolicy(Step[RefundCase]):
    def execute(self, context: Context, input: RefundCase) -> StepDecision:
        order = input.order
        if order.days_since_charge > REFUND_WINDOW_DAYS:
            CASE_STATUS.set(context, "denied")
            note = "The charge is older than our 30-day refund window."
            return go_to(WriteCustomerMessage, replace(input, outcome="denied", note=note))
        if order.outage_hours == 0:
            CASE_STATUS.set(context, "denied")
            note = "We found no service interruption on this order."
            return go_to(WriteCustomerMessage, replace(input, outcome="denied", note=note))
        if order.amount_usd > MANAGER_APPROVAL_LIMIT_USD:
            CASE_STATUS.set(context, AWAITING_MANAGER)
            return go_to(RequestManagerApproval, input)
        return go_to(IssueRefund, input)


# dex:group group-id:control group-label:"Control"
# dex:explanation text:"Wait for a manager to approve or reject the refund."
class RequestManagerApproval(Step[RefundCase]):
    def wait_for(self, context: Context, input: RefundCase) -> Wait:
        return Wait.until(MANAGER_DECISIONS.for_one())

    def execute(self, context: Context, input: RefundCase) -> StepDecision:
        decision = MANAGER_DECISIONS.results(context)[0]
        if decision.approved:
            return go_to(IssueRefund, input)
        CASE_STATUS.set(context, "denied")
        return go_to(WriteCustomerMessage, replace(input, outcome="denied", note=decision.reason))
```

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

一个批准 RPC 和一个拒绝 RPC 把经理的决定发布到这个 Channel。每个 RPC 都要求填写原因，并且只在 `case-status` 为 `awaiting-manager` 时发布。在 Python、Go 和 TypeScript 中，这两个 RPC 同时是 Dex Web 的 Action：**Approve refund** 和 **Reject refund**。每种语言都能用示例的 `decide` 命令批准或拒绝。Java 和 Rust 没有 Action。

这个示例还展示了生产环境的退款需要什么：

- **Issue refund** 和 **Send message** 向 billing 和 email 传入由 Flow ID 生成的幂等 key：`refund-<Flow ID>` 和 `email-<Flow ID>`。被中断的 Step 可能再次运行，Time Travel 点之后的 Step 也会再次运行。每个 fake 服务遇到自己持久化记录里已有的 key 就跳过。Worker 必须共用这些记录；各用一份记录的 Worker 会各退一次款。
- **Issue refund** 遇到支付超时，每 5 秒重试一次。在 `fail-then-succeed` 场景中，Dex Web 里最后一个 **Issue refund** 事件显示第 3 次尝试成功，并保留最近一次失败的详情。
- 在 Python、Go 和 TypeScript 中，提供 payload key 文件后，Worker 和 Client 会加密 payload。`case-status` 和 `customer-email` 保持明文，所以 Dex Web 能显示它们。Dex Web 根据 `case-status` 判断 Action 的条件。

<a id="deterministic-policy"></a>

## 确定性策略

<a id="确定性策略"></a>

Go 中的 `CustomerRefundFlow` 先确认订单存在，再应用 30 天规则。**Issue refund** 用 case ID 加 `:refund` 生成 billing key，传给支付 provider，并随 Step 结果一起保存。如果 provider 拒绝退款，或者结果未知，Flow 会把这个结果记为 case 状态。

**Flow 图：CustomerRefundFlow**

**Step 列表**

1. `ReceiveRequest`（起始 Step）：Store the inbound refund request and start the case. 下一步：`CheckOrder`。
2. `CheckOrder`：Check the order and charge evidence for the refund. 下一步：`CheckPolicy`。 写入 `case-status`、`order-age-days`、`order-lookup`。
3. `CheckPolicy`：Evaluate refund policy and choose approve or deny. 下一步：`NotifyCustomer`、`IssueRefund`，或 `DenyRefund`。 读取 `order-age-days`、`order-lookup`；写入 `case-status`、`recommended-action`。
4. `CloseCase`：Close the refund case after notification. 下一步：Flow 完成。 读取 `case-status`；写入 `case-status`。
5. `DenyRefund`：Record a policy denial for the refund request. 下一步：`NotifyCustomer`。 写入 `case-status`。
6. `IssueRefund`：Issue the refund through billing. 下一步：`NotifyCustomer`。 写入 `billing-outcome`、`case-status`、`refund-key`。
7. `NotifyCustomer`：Notify the customer of the refund decision. 下一步：`CloseCase`。 读取 `case-status`。

**RPC 列表**

- `GetDexDisplay`：读取 `billing-outcome`、`charge-reference`、`operator-note`、`order-age-days`、`order-lookup`、`recommended-action`、`refund-amount`。
- `GetDexSummary`：读取 `charge-reference`、`recommended-action`、`refund-amount`。

例子: [examples/go/products/customer-refund/deterministic/workflow.go](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund/deterministic/workflow.go)

Summary 展示 charge reference、请求金额和 recommendation，Display 再加上证据、计费结果和可编辑的 operator note。它不声明任何 Action，用来说明没有 Action 的 Flow 在 Dex Web 中同样有效。源码：[`deterministic/workflow.go`](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund/deterministic/workflow.go)。

<a id="agentic-review"></a>

## Agentic 审核

<a id="agentic-审核"></a>

Go 中的 `AgenticCustomerRefundFlow` 在一个由 Step 组成的循环里收集证据。随后由 guardrail 自动执行决定，或等待经理审批。一个 OpenAI Connector Step 起草给客户的消息，由人确认或改写后再发送。Flow 在 billing 之前用单独的 Step 记录退款意图。billing Step 把 case ID 加 `:refund`（账户抵扣用 `:credit`）作为 key 传给 billing，并随结果一起保存。图中 Step 上的 ⚠ 表示一条失败路由；选中这个 Step 可以看到它通向哪里。

**Flow 图：AgenticCustomerRefundFlow**

**Step 列表**

1. `ReceiveRequestStep`（起始 Step）：Store the inbound refund request and open or reject the case. 下一步：`NotARefundStep`，或 `AgentDecisionStep`。 写入 `case-status`、`in-charge-ref`、`customer-email`、`in-email`、`operator-note`。
2. `GenerateCustomerMessageStep`：Generate the customer resolution message with OpenAI. 下一步：Flow 失败。 写入 `generated-customer-message`。
3. `ApplySubscriptionStep`：Apply any subscription change required by the resolution. 下一步：`PrepareCustomerMessageStep`，或 `SubscriptionFailedStep`（持续失败时）。 写入 `subscription-applied`。
4. `AuditIntentStep`：Record the approved refund intent before billing changes. 下一步：`OfferAccountCreditStep`，或 `IssueRefundStep`。 读取 `bound-action`。
5. `BillingFailedStep`：Handle a billing failure during refund or credit. 下一步：`PrepareCustomerMessageStep`。 写入 `billing-outcome`、`case-status`。
6. `CheckIdentityStep`：Verify the customer identity before collecting further evidence. 下一步：`AgentDecisionStep`。 写入 `ev-identity-status`。
7. `CheckIncidentsStep`：Check for active incidents that affect refund policy. 下一步：`AgentDecisionStep`。 写入 `evidence-state`、`ev-incident-days`、`ev-incident-status`。
8. `CloseCaseStep`：Close the refund case once resolution is final. 下一步：Flow 完成。
9. `ConfirmCustomerMessageStep`：Wait for a person to confirm or rewrite the customer message. 下一步：`SendCustomerMessageStep`。 读取 `gate-request-key`、`message-approval`。
10. `AgentDecisionStep`：Choose the next capability from gathered evidence and guardrails. 下一步：`NonConvergenceStep`、`CheckIdentityStep`、`GetSubscriptionStep`、`GetPaymentStep`、`GetUsageStep`、`GetSupportHistoryStep`、`CheckIncidentsStep`，或 `GuardrailStep`。 读取 `ev-history-cancel-requested`、`decision-rounds`、`ev-history-status`、`ev-identity-status`、`ev-incident-status`、`ev-payment-status`、`ev-history-prior-refunds`、`ev-subscription-status`、`ev-usage-pct-of-allowance`、`ev-usage-status`；写入 `case-status`、`decision-rounds`、`recommendation-rationale`、`recommended-action`。
11. `EmailFailedStep`：Handle a failure sending the customer resolution message. 下一步：`CloseCaseStep`。 写入 `case-status`、`email-sent`。
12. `GetPaymentStep`：Load the payment and charge evidence for the refund. 下一步：`AgentDecisionStep`。 写入 `ev-payment-age-days`、`ev-payment-amount`、`ev-payment-status`、`refund-amount`。
13. `GetSubscriptionStep`：Load the customer's subscription details for the case. 下一步：`AgentDecisionStep`。 写入 `ev-subscription-status`。
14. `GetSupportHistoryStep`：Load prior support history for this customer. 下一步：`AgentDecisionStep`。 写入 `ev-history-cancel-requested`、`ev-history-status`、`ev-history-prior-refunds`、`ev-history-tenure-years`。
15. `GetUsageStep`：Load usage signals that may support or deny a refund. 下一步：`AgentDecisionStep`。 写入 `ev-usage-pct-of-allowance`、`ev-usage-status`。
16. `GuardrailStep`：Apply refund guardrails and set the recommended action. 下一步：`RequestHumanApprovalStep`，或 `AuditIntentStep`。 读取 `gate-entries`、`recommended-action`；写入 `bound-action`、`case-status`、`gate-entries`、`gate-request-key`、`guardrail-rule`、`guardrail-verdict`。
17. `IssueRefundStep`：Issue the refund through billing. 下一步：`ApplySubscriptionStep`、`VerifyBillingStep`、`BillingFailedStep`，或 `BillingFailedStep`（持续失败时）。 写入 `billing-key`、`billing-outcome`、`case-status`。
18. `NonConvergenceStep`：Close the loop when the agent cannot converge on an action. 下一步：`CloseCaseStep`。 写入 `case-status`。
19. `NotARefundStep`：Mark the case as not a refund request. 下一步：`CloseCaseStep`。
20. `OfferAccountCreditStep`：Offer account credit instead of a cash refund. 下一步：`BillingFailedStep`，或 `ApplySubscriptionStep`。 写入 `billing-key`、`billing-outcome`、`case-status`。
21. `PrepareCustomerMessageStep`：Prepare the resolution context and fallback customer message. 下一步：Flow 失败，或 `GenerateCustomerMessageStep`。 读取 `case-status`；写入 `customer-message-context`。
22. `ReCheckStep`：Re-check evidence after a capability returns to the decision loop. 下一步：`PrepareCustomerMessageStep`，或 `AuditIntentStep`。 读取 `manager-verdict`；写入 `bound-action`、`case-status`。
23. `RequestHumanApprovalStep`：Ask a human to approve or reject the recommended refund action. 下一步：`ReCheckStep`。 读取 `gate-request-key`、`manager-approval`；写入 `manager-verdict`。
24. `SendCustomerMessageStep`：Send the customer the message a person confirmed. 下一步：`CloseCaseStep`，或 `EmailFailedStep`（持续失败时）。 读取 `case-status`、`customer-message-draft`；写入 `case-status`、`email-sent`。
25. `StoreGeneratedCustomerMessageStep`：Store the customer message generated by OpenAI and open the confirmation gate. 下一步：`ConfirmCustomerMessageStep`。 读取 `customer-message-context`、`gate-entries`；写入 `case-status`、`customer-message-draft`、`gate-entries`、`gate-request-key`。
26. `SubscriptionFailedStep`：Handle a subscription update failure after a resolution. 下一步：`PrepareCustomerMessageStep`。 写入 `case-status`、`subscription-applied`。
27. `UseFallbackCustomerMessageStep`：Use the deterministic customer message when OpenAI cannot confirm an answer. 下一步：`ConfirmCustomerMessageStep`。 读取 `customer-message-context`、`gate-entries`；写入 `case-status`、`customer-message-draft`、`gate-entries`、`gate-request-key`。
28. `VerifyBillingStep`：Verify the billing outcome after a refund or credit. 下一步：`ApplySubscriptionStep`、`CloseCaseStep`，或 `BillingFailedStep`。 读取 `billing-key`；写入 `billing-outcome`、`case-status`。

**RPC 列表**

- `ApproveRefund`：读取 `case-status`、`gate-request-key`；锁定 `case-status`、`gate-request-key`；发布到 `manager-approval`。
- `ConfirmCustomerMessage`：读取 `case-status`、`gate-request-key`；锁定 `case-status`、`customer-message-draft`、`gate-request-key`；写入 `case-status`；发布到 `message-approval`。
- `EditCustomerMessage`：读取 `case-status`、`gate-request-key`；锁定 `case-status`、`customer-message-draft`、`gate-request-key`；写入 `case-status`、`customer-message-draft`；发布到 `message-approval`。
- `GetDexDisplay`
- `GetDexSummary`：读取 `in-charge-ref`、`guardrail-rule`、`ev-payment-amount`、`recommended-action`。
- `RejectRefund`：读取 `case-status`、`gate-request-key`；锁定 `case-status`、`gate-request-key`；写入 `manager-rejection-reason`；发布到 `manager-approval`。

例子: [examples/go/products/customer-refund/agentic/workflow.go](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund/agentic/workflow.go)

Flow 每打开一道人工 gate，都会生成新的 gate key。`ApproveRefund` Action 直接显示为按钮，不需要输入。`RejectRefund` 要求填写原因，`EditCustomerMessage` 要求填写要发送的消息。这两个 Action 和 `ConfirmCustomerMessage` 还把 gate key 放在隐藏输入里，由 Dex Web 从页面打开时读到的 Attribute 值填入。RPC 发布之前会把它与当前 gate 比较；如果 gate 已经变了，RPC 返回错误，操作员刷新页面。每个 RPC 还会检查 case 状态，因为 Action 的可见性条件只决定按钮是否出现，不做任何授权。源码：[`agentic/workflow.go`](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund/agentic/workflow.go)。

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

## 运行

<a id="run-the-examples"></a>

<a id="运行示例"></a>

[Quick Start](https://docs.superdurable.io/zh-Hans/quick-start.md) 完整运行经理审批 Flow。[Python](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/customer_refund)、[Go](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund)、[TypeScript](https://github.com/superdurable/dex/tree/main/examples/typescript/src/products/customer-refund)、[Java](https://github.com/superdurable/dex/tree/main/examples/java/src/main/java/io/superdurable/dex/products/customerrefund) 和 [Rust](https://github.com/superdurable/dex/tree/main/examples/rust/src/products/customer_refund) 的示例文件夹列出了其他场景的命令：不需要经理的小额退款、拒绝、先失败后成功的退款，以及用 Time Travel 修复缺失的 billing 调用。Go 文件夹还能启动确定性和 agentic Flow。

要通过 HTTP 启动退款，先按[在 playground 里运行一个示例](https://docs.superdurable.io/zh-Hans/install.md#run-an-example-from-the-playground)启动一种语言的示例。然后打开[示例 playground](https://github.com/superdurable/dex/tree/main/examples/playground)，选择 **Customer refund with manager approval**。

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

## 下一步

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

[生产运维](https://docs.superdurable.io/zh-Hans/production-operations.md)：Dex 应用运行在四个组件上：你的应用、server、CLI 和 Web。
