# 管理发票生命周期

Operation / SDK: `manageInvoice` · `manage_invoice` · `ManageInvoice`

创建、定稿、发送、收款、作废或重开发票。

更新于 2026-11-05

[网页版本](https://www.longplayai.com/zh-hans/docs/api/manage-invoice)

<a id="request"></a>

## 请求

- **凭据**: Server Key，权限 `billing:write`。只在后端调用。
- **SDK**: JavaScript `createLongplayServer().manageInvoice` · Python `manage_invoice` · Go `ManageInvoice`
- **成功状态**: HTTP 200

响应为示例数据。

**cURL: request.sh**

```bash
curl -X POST "$LONGPLAY_API_URL/api/v1/invoices/manage" \
  -H "Authorization: Bearer $LONGPLAY_SERVER_KEY" \
  -H "X-Indiana-Protocol: 0.10" \
  -H "Content-Type: application/json" \
  -d '{
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d",
  "command": {
    "action": "finalize",
    "requestId": "0f58d1f8-069f-4288-8ec1-4ed10af55b45",
    "invoiceId": "01d9f76a-62d9-4688-8804-b4734805f049"
  }
}'
```

**TypeScript: manageInvoice.ts**

```ts
import { createLongplayServer } from "@tinkerlandai/longplay-sdk/server";

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

export async function manageInvoice() {
  return longplay.manageInvoice({
    customerId: "8b258f8b-4228-40fa-8d24-5b16428e686d",
    command: {
      action: "finalize",
      requestId: "0f58d1f8-069f-4288-8ec1-4ed10af55b45",
      invoiceId: "01d9f76a-62d9-4688-8804-b4734805f049",
    },
  });
}
```

**请求体: request.json**

```json
{
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d",
  "command": {
    "action": "finalize",
    "requestId": "0f58d1f8-069f-4288-8ec1-4ed10af55b45",
    "invoiceId": "01d9f76a-62d9-4688-8804-b4734805f049"
  }
}
```

**响应示例: response.json**

```json
{
  "requestId": "44f5fcb8-6ed8-41b8-818f-7571941c5fd5",
  "scope": {
    "projectId": "df5426d6-b335-403c-8f3e-b0f73d2e3511",
    "environment": "sandbox"
  },
  "operation": {
    "taskId": "8764ce16-8eb3-4036-860d-8043b1f4e4e1",
    "status": "ready",
    "invoice": {
      "id": "01d9f76a-62d9-4688-8804-b4734805f049",
      "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d",
      "providerInvoiceId": "1Example",
      "status": "draft",
      "currency": "USD",
      "totalMinor": "-1",
      "paidMinor": "1",
      "refundedMinor": "1",
      "hostedInvoiceUrl": "https://example.com/hostedinvoice",
      "createdAt": 1,
      "collectionMethod": "send_invoice"
    },
    "errorCode": "1Example"
  }
}
```

<a id="parameters"></a>

## 请求体参数

**application/json**

- `customerId` (uuid, required): Customer 的 UUID。
- `command` (object | object | object, required): 要执行的命令；其中的 `action` 或 `operation` 决定其余字段。
- `command.action` ("create" | enum | "reissue", required): 本次业务动作。不同动作的目标字段和数量要求不同，见请求结构与示例。
- `command.requestId` (uuid | uuid | uuid, required): 你的业务请求 UUID；同一次操作重试复用，新的操作生成新值。
- `command.params` (object | object, optional): 开票参数。
- `command.params.customer_id` (string, optional): Customer 的 ID。
- `command.params.plans` (array, optional): 要购买的 Product Version，可附带席位和 Feature 数量。
- `command.params.plans.plan_id` (string, required): Product 的 ID。
- `command.params.plans.version` (number, optional): 版本号。
- `command.params.plans.customize` (object, optional): 自定义设置。
- `command.params.plans.feature_quantities` (array, optional): Feature 数量。
- `command.params.plans.license_quantities` (array, optional): 许可数量。
- `command.params.plans.discounts` (array, optional): 折扣列表。
- `command.params.plans.prorate` (boolean, optional): 是否按比例计费。
- `command.params.custom_line_items` (array, optional): 自定义明细行。
- `command.params.custom_line_items.amount` (number, required): 金额（数字）。
- `command.params.custom_line_items.description` (string, required): 描述。
- `command.params.discounts` (array, optional): 折扣列表。
- `command.params.discounts.reward_id` (string, optional): 奖励 ID。
- `command.params.discounts.promotion_code` (string, optional): 促销码。
- `command.params.invoice_template_id` (string | string, optional): 发票模板的 ID。
- `command.params.net_terms_days` (integer | integer, optional): 付款期限（天）。
- `command.params.tax_rate_id` (string, optional): 应用于每一行的 Stripe 税率 ID（`txr_...`）。必须是与当前环境同一 Stripe 模式下的有效税率；不计税时省略。
- `command.params.period_start` (integer, optional): 周期开始时间。 min: 0 · max: 9007199254740991
- `command.params.period_end` (integer, optional): 周期结束时间。 min: 0 · max: 9007199254740991
- `command.params.preview` (boolean, optional): 预览标记。`previewInvoice` 无论取值如何都只计算、不创建发票；`createInvoice` 和 `manageInvoice` 会拒绝 `true`，请省略或传 `false`。
- `command.params.invoice_id` (string, optional): 要作废并重开的 Longplay 发票 ID。
- `command.params.update_customer_email` (email, optional): 仅用于 `reissue`：在开出替换发票前写入 Customer 对应 Stripe customer 的账单邮箱，Stripe 会将替换发票发送到该地址。省略则保留现有邮箱。
- `command.invoiceId` (uuid | uuid, optional): 发票的 ID。

<a id="response"></a>

## 响应字段

成功响应都包含 `requestId`（本次请求 ID，排查时提供）和 `scope`（App 与环境）。

**HTTP 200 · application/json**

- `requestId` (uuid, required): 服务端为这次 HTTP 请求生成的 UUID，排查时提供；它不是你的业务 requestId。
- `scope` (object, required): 响应实际所属的 App 和环境。Header 只能核对，不能切换 Key 范围。
- `scope.projectId` (string, required): 凭据绑定的 App ID。 minLength: 1
- `scope.environment` (enum, required): 独立数据范围：sandbox 或 live。 Values: `"sandbox"`, `"live"`.
- `operation` (object, required): 操作对象：状态、结果与恢复信息。
- `operation.taskId` (uuid, required): 任务的 ID。
- `operation.status` (enum, required): 状态，取值见允许值。 Values: `"ready"`, `"running"`, `"done"`, `"dead"`.
- `operation.invoice` (object | null, required): 发票。
- `operation.invoice.id` (uuid, required): 发票 的 ID。
- `operation.invoice.customerId` (uuid, required): Customer 的 UUID。
- `operation.invoice.providerInvoiceId` (string | null, required): 支付渠道中的发票的 ID。
- `operation.invoice.status` (enum, required): 状态，取值见允许值。 Values: `"draft"`, `"open"`, `"paid"`, `"void"`, `"uncollectible"`.
- `operation.invoice.currency` (string, required): 已发布价格支持的币种代码。
- `operation.invoice.totalMinor` (string, required): 金额，以最小货币单位计（如美分）。 pattern: ^-?\d+$
- `operation.invoice.paidMinor` (string, required): 金额，以最小货币单位计（如美分）。 pattern: ^\d+$
- `operation.invoice.refundedMinor` (string, required): 金额，以最小货币单位计（如美分）。 pattern: ^\d+$
- `operation.invoice.hostedInvoiceUrl` (uri | null, required): 发票托管页面链接。
- `operation.invoice.createdAt` (number, required): 记录创建时的 ISO 8601 UTC 时间。
- `operation.invoice.collectionMethod` (enum | null, required): 收款方式，取值见允许值。
- `operation.errorCode` (string | null, required): 错误码。

<a id="errors"></a>

## 错误

失败时返回错误对象，按 `error.code` 与 `error.recovery` 处理。下表是这个接口的凭据、作用域和幂等字段决定的错误；视请求内容还可能返回 `NOT_FOUND`（引用的资源不存在）、`NOT_CONFIGURED`（所需的集成未连接）或 `PAYLOAD_TOO_LARGE`。有些拒绝（如余额不足）不是错误，而是成功响应里的 `reason`。

**可能的错误**

| code | HTTP | 何时 | recovery |
| --- | --- | --- | --- |
| `INVALID_REQUEST` | 400 | 请求不符合本页的参数。缺少或无法解析协议头时分别返回 `UNSUPPORTED_PROTOCOL_VERSION` 或 `INVALID_PROTOCOL_VERSION`。 | `fix_request` |
| `UNAUTHENTICATED` | 401 | 凭据缺失、无效、过期或已撤销。 | `authenticate` |
| `FORBIDDEN` | 403 | 凭据没有 `billing:write` 权限。 | `check_permissions` |
| `SCOPE_MISMATCH` | 403 | `X-Indiana-Project` 或 `X-Indiana-Environment` 与凭据所属的 App 和环境不一致。 | `check_scope` |
| `CONFLICT` | 409 | 同一个 `requestId` 用了不同的输入（`reason: IDEMPOTENCY_CONFLICT`）。 | `resolve_conflict` |
| `RATE_LIMITED` | 429 | 请求过多；按 `Retry-After` 等待后用同一请求重试。 | `retry_same_request` |
| `SERVICE_UNAVAILABLE` | 503 | 服务暂时不可用；用同一请求重试。 | `retry_same_request` |
| `INTERNAL_ERROR` | 500 | 结果未知；先读取原操作，或用原 ID 和原输入重放。 | `recover_operation` |

- [错误码与恢复](https://www.longplayai.com/zh-hans/docs/api/errors.md)
- [请求约定](https://www.longplayai.com/zh-hans/docs/api.md)
- [全部接口](https://www.longplayai.com/zh-hans/docs/api/operations.md#invoices)
