# 商户执行接入

实现 record_only 商户桥接：接口入参、出参、错误码、结果回传与购买恢复顺序。

更新于 2026-11-06

[网页版本](https://www.longplayai.com/zh-hans/docs/guides/merchant-execution)

<a id="scope"></a>

## 商户原生执行

本页执行示例使用商户桥接版本 3，通过 POST /integrations/indiana 接收指令。record_only 模式下，Longplay 返回商户原生执行指令；商户保留支付渠道凭据、原生订单、权益发放和消费。Longplay API 使用协议 0.10，不兼容旧协议；API 协议与商户桥接版本独立。

- 每个 App/环境独立配置商户连接与签名密钥，scope 不携带支付渠道账户。
- 托管模式继续由 Longplay 执行渠道业务；record_only 使用 merchant 指令和归一化商户事实。
- 仅声明已实现的 profiles；试用、优惠、阶梯、席位、税、订阅变更和退款均须匹配指令，不能删字段降级执行。

<a id="prepared-terms"></a>

## 商户准备报价

在 `record_only` 模式下，商户须先支持商户桥接 v4 的 `operation.prepare` 准备命令，Longplay 才能冻结报价并生成 `merchantTerms`；确认报价时提交与之匹配的 `merchantConfirmation`。

准备接口使用 POST /integrations/indiana，请求与响应均使用 `X-Indiana-Merchant-Bridge-Version: 4` 版本头及 `bridgeVersion: 4` 封套。通过 Server SDK 的 `createMerchantBridgeProtocol({ manifest, authentication })` 创建协议编解码器，使用 `decodeRequest` 验签并核对作用域与准备权限，再用 `encodeResponse` 生成签名响应。

以下最小 `bridge.describe` 声明仅支持购买报价准备。替换为当前 App/环境的标识；在 `capabilities` 中声明 `preparations`，在 `preparationActions` 中只列出已实现的 `purchase`、`subscription_change` 或 `refund`。

**preparation.manifest.json**

```json
{
  "bridgeVersion": 4,
  "projectId": "44444444-4444-4444-8444-444444444444",
  "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee",
  "environment": "sandbox",
  "capabilities": [
    "preparations"
  ],
  "catalog": "none",
  "billingEvents": [],
  "profiles": [],
  "checkKinds": [],
  "preparationActions": [
    "purchase"
  ],
  "authorizationKinds": [],
  "nextActionTypes": [],
  "resultEvents": []
}
```

- `operation.prepare` 根据签名请求中已保存的业务意图计算并返回条款，不发起支付、履约或退款。用户确认条款后，`merchantConfirmation` 携带对应的 `quoteTermsDigest` 及所需同意的引用和版本。
- 下方桥接 v3 执行示例保留原有执行与查询流程。接入准备接口时，按请求版本分派到 v4 编解码器和准备处理器；仅复制 v3 的处理器或修改其 manifest 不能提供 `operation.prepare`。

<a id="transport"></a>

## 统一请求与响应

以下执行示例使用 POST、application/json 和版本头 X-Indiana-Merchant-Bridge-Version: 3。严格封套为 bridgeVersion、requestId、scope、command、data；scope 为 projectId、environmentId、environment，服务端与固定配置逐项核对。

**purchase.request.json**

```json
{
  "bridgeVersion": 3,
  "requestId": "11111111-1111-4111-8111-111111111111",
  "scope": {
    "projectId": "44444444-4444-4444-8444-444444444444",
    "environment": "sandbox",
    "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"
  },
  "command": "purchase.execute",
  "data": {
    "operationId": "11111111-1111-4111-8111-111111111111",
    "customerId": "22222222-2222-4222-8222-222222222222"
  }
}
```

**purchase.response.json**

```json
{
  "bridgeVersion": 3,
  "requestId": "55555555-5555-4555-8555-555555555555",
  "command": "purchase.execute",
  "scope": {
    "projectId": "44444444-4444-4444-8444-444444444444",
    "environment": "sandbox",
    "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"
  },
  "data": {
    "type": "purchase",
    "operationId": "11111111-1111-4111-8111-111111111111",
    "customerId": "22222222-2222-4222-8222-222222222222",
    "merchantExecutionId": "purchase_example",
    "merchantOrderId": "order_example",
    "paymentStatus": "pending",
    "fulfillmentStatus": "not_started",
    "recordingStatus": "not_ready",
    "checkoutUrl": "https://merchant.example/checkout/order_example",
    "checkoutExpiresAt": "2030-01-01T00:30:00.000Z",
    "updatedAt": "2030-01-01T00:00:00.000Z",
    "problem": null,
    "pollAfterMs": 2000
  }
}
```

HTTP 尝试使用新 requestId；业务始终保留原 operationId。请求上限 16 KiB，响应上限 256 KiB，拒绝重定向，用户响应设置 private, no-store。200/202 仅返回当前事实，不代表商业完成。SDK 不自动重试财务执行或打开 Checkout。

<a id="authentication"></a>

## 认证与权限

用户指令沿用商户登录和 CSRF。authorize 将原生用户绑定到当前 Customer，不能采用浏览器自选身份。Console/GOP 的服务请求使用每环境独立的 32 字节 Base64URL HMAC 密钥，密钥只留后端。服务签名不授予用户会话签发或任意财务操作权限。

**signature.txt**

```bash
indiana-merchant-bridge:3
request
POST
/integrations/indiana
<timestamp>
<exact JSON body>
```

签名前缀 `indiana-merchant-bridge` 和路径 `/integrations/indiana` 是协议固定使用的名称，沿用了 Longplay 早期的内部名称，请按原样使用。

请求和响应分别验签（响应 direction 为 response），时钟偏差最多 300 秒。使用导出的 signMerchantBridgeMessage / verifyMerchantBridgeMessage，密钥轮换保留在途旧密钥。财务指令还必须通过 Server SDK 实时读取原操作 authority，核对范围、Customer、指令类型与 confirmedAt。

<a id="commands"></a>

## 能力与指令

**manifest.json**

```json
{
  "bridgeVersion": 3,
  "projectId": "44444444-4444-4444-8444-444444444444",
  "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee",
  "environment": "sandbox",
  "capabilities": [
    "session",
    "catalog",
    "customer_commerce",
    "presentation",
    "presentation_events",
    "purchases",
    "operation_status",
    "billing_records",
    "subscription_changes",
    "refunds"
  ],
  "catalog": "static",
  "billingEvents": [
    "purchase.completed",
    "purchase.closed",
    "subscription.observed",
    "subscription.change.completed",
    "subscription.change.closed",
    "invoice.paid",
    "refund.updated"
  ],
  "profiles": [
    "purchase.subscription",
    "purchase.one_time",
    "purchase.prepaid",
    "purchase.trial",
    "purchase.seats",
    "purchase.tiered",
    "tax.automatic",
    "discount.percent.once",
    "discount.percent.repeating",
    "discount.percent.forever",
    "discount.amount.once",
    "discount.amount.repeating",
    "discount.amount.forever",
    "subscription.cancel.immediate",
    "subscription.cancel.renewal",
    "subscription.resume",
    "subscription.plan.immediate",
    "subscription.plan.renewal",
    "subscription.seats",
    "subscription.quantity",
    "subscription.billing_cycle",
    "subscription.proration",
    "refund.full",
    "refund.partial",
    "refund.revoke"
  ]
}
```

**指令权限**

| command | 权限 |
| --- | --- |
| session.create | merchant_user |
| catalog.read | merchant_catalog_reader |
| customer.commerce.read | merchant_user |
| presentation.resolve | merchant_user |
| presentation.report | merchant_user |
| purchase.execute | merchant_user |
| operation.read | merchant_user |
| subscription.change | merchant_user |
| refund.execute | merchant_refund_authority |

session.create、catalog.read、customer.commerce.read、presentation.resolve 的 data 为 {}；presentation.report 为 {decisionId,eventId}；purchase.execute、operation.read、subscription.change、refund.execute 为 {operationId,customerId}。bridge.ping 回显 challenge，bridge.describe 返回声明，无业务写入。

<a id="adapter"></a>

## 服务端与浏览器接入

**merchant-receiver.ts**

```ts
import { createLongplayServer, createMerchantBridgeHandler, createMerchantBridgeAuthorityResolver, type LongplayServerOptions, type MerchantBridgeHandlerOptions, type MerchantBridgeHandlers } from "@tinkerlandai/longplay-sdk/server";

// Your app provides its configuration, native login/CSRF check and commerce handlers.
type Native = Required<MerchantBridgeHandlers>;
declare const serverOptions: LongplayServerOptions;
declare const manifest: MerchantBridgeHandlerOptions["manifest"];
declare const authentication: MerchantBridgeHandlerOptions["authentication"];
declare const authorizeNativeCommand: MerchantBridgeHandlerOptions["authorize"];
declare const native: {
  createSession: Native["session.create"];
  readCatalog: Native["catalog.read"];
  readCommerce: Native["customer.commerce.read"];
  resolvePresentation: Native["presentation.resolve"];
  reportPresentation: Native["presentation.report"];
  executePurchase: Native["purchase.execute"];
  readOperation: Native["operation.read"];
  changeSubscription: Native["subscription.change"];
  executeRefund: Native["refund.execute"];
};

const longplay = createLongplayServer(serverOptions);
export const POST = createMerchantBridgeHandler({
  manifest,
  authentication,
  authorize: authorizeNativeCommand,
  resolveOperationAuthority: createMerchantBridgeAuthorityResolver(longplay),
  handlers: {
    "session.create": native.createSession,
    "catalog.read": native.readCatalog,
    "customer.commerce.read": native.readCommerce,
    "presentation.resolve": native.resolvePresentation,
    "presentation.report": native.reportPresentation,
    "purchase.execute": native.executePurchase,
    "operation.read": native.readOperation,
    "subscription.change": native.changeSubscription,
    "refund.execute": native.executeRefund,
  },
});
// Native handlers durably reserve the original operation before external effects.
// readOperation returns found or not_received and never starts an operation.
```

解析器沿用 `readSubscriptionOperation` / `readSubscriptionUpdate` / `readRefund`，只接受 Longplay 返回的 authority，不从浏览器报价或本地状态推算权限。处理器仍负责原生登录、CSRF、唯一执行预留和渠道幂等；SDK 的先查询检查不能替代并发锁。

浏览器 createMerchantBridge 使用原生登录，只发送当前 Customer 的原操作；退出或换号调用 reset()。Server Key、HMAC 密钥和退款管理员权限不进入浏览器。

<a id="checks"></a>

## 连接检查

Console 执行签名 Ping、声明发现和可用目录读取。能力或 profiles 声明只证明配置覆盖，不能代替实际支付、履约、退款和原操作恢复。部署商户接收器后分别验证用户与服务权限、同操作并发、未知结果、迟到事件和范围隔离。

<a id="session"></a>

## 签发 Customer 会话

**session.sh**

```bash
curl --fail-with-body --request POST "$MERCHANT_ORIGIN/integrations/indiana" \
  --header 'Content-Type: application/json' \
  --header 'X-Indiana-Merchant-Bridge-Version: 3' \
  --header "Cookie: $MERCHANT_COOKIE" \
  --header "Origin: $MERCHANT_ORIGIN" \
  --header "X-CSRF-Token: $MERCHANT_CSRF_TOKEN" \
  --data '{"bridgeVersion":3,"requestId":"11111111-1111-4111-8111-111111111111","scope":{"projectId":"44444444-4444-4444-8444-444444444444","environment":"sandbox","environmentId":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"},"command":"session.create","data":{}}'
```

**session.response.json**

```json
{
  "bridgeVersion": 3,
  "requestId": "55555555-5555-4555-8555-555555555555",
  "command": "session.create",
  "scope": {
    "projectId": "44444444-4444-4444-8444-444444444444",
    "environment": "sandbox",
    "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"
  },
  "data": {
    "nativeUserId": "88888888-8888-4888-8888-888888888888",
    "session": {
      "customerId": "22222222-2222-4222-8222-222222222222",
      "sessionId": "66666666-6666-4666-8666-666666666666",
      "accessToken": "gg_ct_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "refreshToken": "gg_rt_yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
      "expiresAt": "2030-01-01T01:00:00.000Z",
      "refreshExpiresAt": "2030-01-02T00:00:00.000Z"
    }
  }
}
```

**presentation.response.json**

```json
{
  "bridgeVersion": 3,
  "requestId": "55555555-5555-4555-8555-555555555555",
  "command": "presentation.resolve",
  "scope": {
    "projectId": "44444444-4444-4444-8444-444444444444",
    "environment": "sandbox",
    "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"
  },
  "data": {
    "nativeUserId": "88888888-8888-4888-8888-888888888888",
    "presentation": {
      "customerId": "22222222-2222-4222-8222-222222222222",
      "decisionId": "99999999-9999-4999-8999-999999999999",
      "offeringVersionId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
      "paywallVersionId": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
      "variant": "a"
    }
  }
}
```

后端验证原生用户后调用 Longplay createCustomerSession，向当前用户返回原始 accessToken/refreshToken 配对。商户不自行签发 Longplay token；Customer/Server-Key 权限分离。展示决策及固定 Offering/Paywall 来自 Longplay；实际展示后以稳定 eventId 回传。

<a id="catalog"></a>

## 原生目录

**catalog.sh**

```bash
curl --fail-with-body --request POST "$MERCHANT_ORIGIN/integrations/indiana" \
  --header 'Content-Type: application/json' \
  --header 'X-Indiana-Merchant-Bridge-Version: 3' \
  --header "X-Indiana-Bridge-Key-Id: $MERCHANT_BRIDGE_KEY_ID" \
  --header "X-Indiana-Bridge-Signature: $MERCHANT_BRIDGE_SIGNATURE" \
  --data '{"bridgeVersion":3,"requestId":"11111111-1111-4111-8111-111111111111","scope":{"projectId":"44444444-4444-4444-8444-444444444444","environment":"sandbox","environmentId":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"},"command":"catalog.read","data":{}}'
```

**catalog.response.json**

```json
{
  "bridgeVersion": 3,
  "requestId": "55555555-5555-4555-8555-555555555555",
  "command": "catalog.read",
  "scope": {
    "projectId": "44444444-4444-4444-8444-444444444444",
    "environment": "sandbox",
    "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"
  },
  "data": {
    "revision": "catalog-7",
    "updatedAt": "2030-01-01T00:00:00.000Z",
    "provider": "merchant",
    "items": [
      {
        "merchantProductId": "credits_1500",
        "productVersionId": "33333333-3333-4333-8333-333333333333",
        "name": "1500 credits",
        "kind": "credit_pack",
        "merchantPriceId": "native-price-1500",
        "currency": "usd",
        "amountMinor": 2500,
        "interval": "one_time",
        "intervalCount": 1,
        "includedCredits": "1500",
        "creditReset": "none",
        "creditPolicyId": "native-credit-pack-v1",
        "available": true
      }
    ]
  }
}
```

目录 provider 固定 merchant，merchantPriceId 为不透明原生引用。ProductVersion 与 Price 显式绑定；金额使用最小币种单位，目录币种为小写三字母。积分包为 one_time、creditReset=none；订阅为 month/year。creditPolicyId 说明原生发放与过期规则，不能授权重复发放。

<a id="purchase"></a>

## 执行确认购买

**purchase.sh**

```bash
curl --fail-with-body --request POST "$MERCHANT_ORIGIN/integrations/indiana" \
  --header 'Content-Type: application/json' \
  --header 'X-Indiana-Merchant-Bridge-Version: 3' \
  --header "Cookie: $MERCHANT_COOKIE" \
  --header "Origin: $MERCHANT_ORIGIN" \
  --header "X-CSRF-Token: $MERCHANT_CSRF_TOKEN" \
  --data '{"bridgeVersion":3,"requestId":"11111111-1111-4111-8111-111111111111","scope":{"projectId":"44444444-4444-4444-8444-444444444444","environment":"sandbox","environmentId":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"},"command":"purchase.execute","data":{"operationId":"11111111-1111-4111-8111-111111111111","customerId":"22222222-2222-4222-8222-222222222222"}}'
```

- 先通过 Longplay attach intent=confirm 确认原操作；商户 receiver 本身不根据浏览器写请求推断确认。
- 实时读取 authority；只有 confirmedAt 有值、initialExecutionAllowed 为 true、指令未过期且全部 profiles 受支持，才允许首次执行。
- 核对 operationId、Customer、配置和连接版本、Price 行、数量、金额、优惠、试用和税；商户渠道映射只发生在后端。
- 持久唯一键覆盖 App、环境、Customer、operationId。先可靠预留再调用渠道，渠道幂等键始终相同；并发或重投返回同一原生执行。

<a id="operation"></a>

## 读取原执行

**operation.sh**

```bash
curl --fail-with-body --request POST "$MERCHANT_ORIGIN/integrations/indiana" \
  --header 'Content-Type: application/json' \
  --header 'X-Indiana-Merchant-Bridge-Version: 3' \
  --header "Cookie: $MERCHANT_COOKIE" \
  --header "Origin: $MERCHANT_ORIGIN" \
  --header "X-CSRF-Token: $MERCHANT_CSRF_TOKEN" \
  --data '{"bridgeVersion":3,"requestId":"11111111-1111-4111-8111-111111111111","scope":{"projectId":"44444444-4444-4444-8444-444444444444","environment":"sandbox","environmentId":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"},"command":"operation.read","data":{"operationId":"11111111-1111-4111-8111-111111111111","customerId":"22222222-2222-4222-8222-222222222222"}}'
```

**operation.response.json**

```json
{
  "bridgeVersion": 3,
  "requestId": "55555555-5555-4555-8555-555555555555",
  "command": "operation.read",
  "scope": {
    "projectId": "44444444-4444-4444-8444-444444444444",
    "environment": "sandbox",
    "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"
  },
  "data": {
    "lookup": "found",
    "operationId": "11111111-1111-4111-8111-111111111111",
    "customerId": "22222222-2222-4222-8222-222222222222",
    "execution": {
      "type": "purchase",
      "operationId": "11111111-1111-4111-8111-111111111111",
      "customerId": "22222222-2222-4222-8222-222222222222",
      "merchantExecutionId": "purchase_example",
      "merchantOrderId": "order_example",
      "paymentStatus": "succeeded",
      "fulfillmentStatus": "applied",
      "recordingStatus": "accepted",
      "checkoutUrl": null,
      "checkoutExpiresAt": "2030-01-01T00:30:00.000Z",
      "updatedAt": "2030-01-01T00:05:00.000Z",
      "problem": null,
      "pollAfterMs": null
    },
    "readAt": "2030-01-01T00:05:00.000Z"
  }
}
```

operation.read 严格只读，返回 lookup=found 或 not_received。found 包含原 execution；not_received 的 execution 为 null，明确说明商户尚无绑定，不能据此创建或重新扣款。支付、原生履约与 Longplay 记账状态分别报告，Checkout 只允许未结束的原购买使用。

<a id="customer-state"></a>

## 原生商业状态

**commerce.sh**

```bash
curl --fail-with-body --request POST "$MERCHANT_ORIGIN/integrations/indiana" \
  --header 'Content-Type: application/json' \
  --header 'X-Indiana-Merchant-Bridge-Version: 3' \
  --header "Cookie: $MERCHANT_COOKIE" \
  --header "Origin: $MERCHANT_ORIGIN" \
  --header "X-CSRF-Token: $MERCHANT_CSRF_TOKEN" \
  --data '{"bridgeVersion":3,"requestId":"11111111-1111-4111-8111-111111111111","scope":{"projectId":"44444444-4444-4444-8444-444444444444","environment":"sandbox","environmentId":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"},"command":"customer.commerce.read","data":{}}'
```

**commerce.response.json**

```json
{
  "bridgeVersion": 3,
  "requestId": "55555555-5555-4555-8555-555555555555",
  "command": "customer.commerce.read",
  "scope": {
    "projectId": "44444444-4444-4444-8444-444444444444",
    "environment": "sandbox",
    "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"
  },
  "data": {
    "customerId": "22222222-2222-4222-8222-222222222222",
    "revision": "12",
    "observedAt": "2030-01-01T00:00:00.000Z",
    "subscriptions": [
      {
        "merchantSubscriptionId": "sub_example",
        "merchantProductId": "starter_month",
        "productVersionId": null,
        "status": "active",
        "currentPeriodStartsAt": "2030-01-01T00:00:00.000Z",
        "currentPeriodEndsAt": "2030-02-01T00:00:00.000Z",
        "cancelAtPeriodEnd": false,
        "scheduledChange": null
      }
    ],
    "purchaseHistory": {
      "complete": true,
      "hasPaidPurchase": true,
      "lastPaidAt": "2030-01-01T00:00:00.000Z"
    },
    "balances": [
      {
        "bucketId": "credit_pack_order_example",
        "key": "creation_credits",
        "available": "1500",
        "expiresAt": null,
        "nextResetAt": null
      }
    ]
  }
}
```

返回当前原生订阅、购买历史和按批次的余额。历史 complete=false 时不能断言新客资格。换号清除旧快照；业务后端继续授权实际访问和扣减。向 Longplay 同步商业事实只走可信后端。

<a id="recovery"></a>

## 变更、退款与恢复

subscription.change 与 refund.execute 使用相同的实时 authority、原操作查询和持久幂等流程。按原指令执行取消/恢复/套餐/席位/数量/账期/按比例差额；scheduled 与 applied 分开报告。退款绑定原 Invoice、金额、币种及撤权策略，所需订阅取消不得遗漏。

响应丢失或渠道超时，先恢复同一 operationId。RESULT_UNKNOWN 必须 retryable=false、recovery=recover_operation；不能新建购买、自动重试财务效果或从 pending 推断未执行。关闭页面只终止等待。原已确认执行的迟到结果仍需核对和投递。

<a id="billing-results"></a>

## 商户事实回传

商户验证自身渠道结果，在原生事务／恢复流程中可靠保存归一化事实，再由具备 billing:write 的 Server Key 调用 recordMerchantEvent。Longplay 路径为 /api/v1/merchant/events/record，使用当前 X-Indiana-Protocol，不使用桥接封套。商户无需发送 Stripe 对象或渠道密钥。

**record-merchant-event.request.json**

```json
{
  "eventId": "native:purchase:order_example",
  "type": "purchase.completed",
  "occurredAt": "2030-01-01T00:00:00.000Z",
  "operationId": "11111111-1111-4111-8111-111111111111",
  "customerId": "22222222-2222-4222-8222-222222222222",
  "merchantOrderId": "order_example",
  "paymentStatus": "paid",
  "invoice": {
    "merchantInvoiceId": "invoice_example",
    "currency": "USD",
    "subtotalMinor": 2500,
    "discountMinor": 0,
    "taxMinor": 0,
    "totalMinor": 2500,
    "paidMinor": 2500,
    "periodStartsAt": null,
    "periodEndsAt": null,
    "lines": [
      {
        "merchantLineId": "line_example",
        "priceId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
        "quantity": 1,
        "subtotalMinor": 2500,
        "discountMinor": 0,
        "taxMinor": 0,
        "totalMinor": 2500,
        "periodStartsAt": null,
        "periodEndsAt": null
      }
    ]
  },
  "subscription": null
}
```

**record-merchant-event.response.json**

```json
{
  "requestId": "55555555-5555-4555-8555-555555555555",
  "scope": {
    "projectId": "44444444-4444-4444-8444-444444444444",
    "environment": "sandbox"
  },
  "record": {
    "id": "77777777-7777-4777-8777-777777777777",
    "eventId": "native:purchase:order_example",
    "source": "merchant",
    "providerVerified": false,
    "outcome": "activated"
  }
}
```

**事件集合**

| 场景 | type | 规则 |
| --- | --- | --- |
| 购买 | purchase.completed | 原确认操作、订单及已核对发票/订阅。付费购买必须携带完整发票。 |
| 结束 | purchase.closed | failed、expired 或 canceled，不伪造成功。 |
| 订阅 | subscription.observed | 单调 revision、完整项目、有效期间与 hasDiscounts。operationId 为 null 时记录原生订阅，项目均为周期 Price。 |
| 变更 | subscription.change.completed | 原操作，scheduled 对应 scheduledFor，applied 不携带预约时间。 |
| 变更关闭 | subscription.change.closed | 原变更在生效前失败、过期或取消；保留订阅引用和可选的未付账单引用。 |
| 付款 | invoice.paid | 完整发票行、金额和期间。续费携带原生订阅引用；充值包、自动充值等一次性原生付款为 null。 |
| 退款 | refund.updated | 稳定退款引用、正数金额、币种及实际状态。原生退款 operationId 为 null，并以 merchantInvoiceId 指明原发票；成功后的 failed 冲回原退款。拒付资金也按原生退款上报，使用争议引用：扣回为 succeeded，退回为 failed。 |

**非财务结果**

| 场景 | type | 规则 |
| --- | --- | --- |
| 履约进度 | fulfillment.updated | 原已派发操作的原生履约进度；未完成的履约使操作保持待处理。 |
| 原生权益 | benefit.claimed / benefit.closed / benefit.updated | 原生权益的发放（资源、单位、数量、到期）、确定未发放的结果，以及之后的状态；保留原发放。 |
| 自动充值授权 | authorization.updated | 原生 `auto_topup` 授权的实际状态；同意或撤销不产生付款。 |
| 原生用量与余额 | usage.observed / balance.observed | 原生消耗或冲回（冲回须指明已记录的原消耗），以及商户自有余额读数；它们不能在 Longplay 中消费，也不代替权益检查。 |
| 优惠券核销 | coupon.redeemed | 未经 Longplay 操作的优惠券使用：携带 grantId，以及 productVersionId 加 subscriptionId，或 merchandiseId。任何支付执行模式都可使用。 |

recordMerchantEvent 是商户结果的唯一入口。除 coupon.redeemed 外，上述事件只在 `record_only` 环境接受；非财务结果不生成发票、收入、可用余额或平台用量，按同一 eventId 重放与冲突规则处理，同一修订的相同事实返回 duplicate，较旧修订返回 stale。

原生事实指 Longplay 未发起的真实交易，只记录金额和订阅，不归因到 Funnel Run。不要为 Longplay 操作创建的订单、订阅、发票或退款发送原生事实，它们使用原操作事件。原生订阅只记录订阅事实，不建立持有或余额。先记录订阅再记录其发票，先记录发票再记录其退款。同一退款较早的观察不会改变金额。

occurredAt 为真实观察时间的 ISO 字符串。eventId 在重试时保持不变，事件内容也不能改变。发票行保留 Price、数量、借/贷金额、优惠、税和期间，各行合计与发票一致；paidMinor 等于 totalMinor。原生订阅包含全部唯一 Price 项目。

可靠 outbox 使用固定事件 ID 至少一次投递，按上游错误和 Retry-After 恢复；永久冲突保留事件并处理原因。记账回执 providerVerified=false，不能代替原生履约或 Longplay 原操作完成，最终应重读两边真实状态。

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

## 错误与后续动作

**bridge-error.json**

```json
{
  "bridgeVersion": 3,
  "requestId": "55555555-5555-4555-8555-555555555555",
  "command": "purchase.execute",
  "scope": {
    "projectId": "44444444-4444-4444-8444-444444444444",
    "environment": "sandbox",
    "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"
  },
  "error": {
    "code": "MERCHANT_BRIDGE_TERMS_CHANGED",
    "message": "The quoted Price no longer matches the native catalog.",
    "retryable": false,
    "recovery": "refresh_catalog"
  }
}
```

保留结构化 code、retryable、recovery。未确认、范围不符、过期或能力缺失时先停止派发并修复原因。RESULT_UNKNOWN/RECOVERY_REQUIRED 只能恢复原操作。Longplay 上游认证故障属于后端配置问题，不等同于用户退出；记账错误保留 Longplay 原封套。

- [SDK](https://www.longplayai.com/zh-hans/docs/sdk/javascript.md)
- [支付连接](https://www.longplayai.com/zh-hans/docs/guides/commerce.md)
