# Funnel 服务端决策指南

在可信后端用 SDK 调用 Remote Funnel，处理等待与重试，并回报采纳。

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

<a id="install"></a>

## 安装与配置

**terminal**

```bash
npm install --save-exact @tinkerlandai/longplay-sdk@latest
```

在 Console 的 接入 → 接入概览 页面顶部「接入范围」中复制「服务地址」（API origin）与「App ID」（App UUID）；Funnel UUID 来自已发布的目标 Funnel。API origin 不带 /api/v1。

**.env**

```bash
LONGPLAY_API_URL=https://api.longplayai.com
LONGPLAY_SERVER_KEY=<SERVER_KEY>
LONGPLAY_PROJECT_ID=<APP_UUID>
LONGPLAY_ENVIRONMENT=sandbox
LONGPLAY_FUNNEL_ID=<PUBLISHED_FUNNEL_UUID>
```

<a id="preconditions"></a>

## 开始之前

- 在 Console 发布目标 Funnel，并把求值模式设为 Remote。服务端决策只支持 Remote 模式。
- Server Key 需要 customers:write, sessions:create, funnels:run 权限。
- Run 使用启动它的 Key 的权限：Paywall 和 Offering 步骤需要 entitlements:read；在 Paywall 购买还需要 billing:write（报价、确认和取消）和 billing:read（读取结算与恢复结果）；领取或展示 Coupon 需要 offers:resolve。
- 在 Console 创建 Key 时点击「选择 Funnel 启动权限」，会一次选中这些权限：funnels:run、sessions:create、customers:write、entitlements:read、offers:resolve、billing:read、billing:write。
- `externalUserId` 使用后端已验证的用户 ID。
- `attributes` 传入本次判断需要的业务属性，Funnel 中的条件可以读取它们。

<a id="call"></a>

## 后端调用

**longplay.ts**

```ts
import {
  createFunnelCampaignClient,
  createFunnelDecisionClient,
  type LongplayServerOptions,
} from "@tinkerlandai/longplay-sdk/server";

const environment = process.env.LONGPLAY_ENVIRONMENT;
if (environment !== "sandbox" && environment !== "live")
  throw new Error("Set LONGPLAY_ENVIRONMENT to sandbox or live");
const options: LongplayServerOptions = {
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: {
    projectId: process.env.LONGPLAY_PROJECT_ID!,
    environment,
  },
};
const funnelId = process.env.LONGPLAY_FUNNEL_ID!;
const campaign = createFunnelCampaignClient({ ...options, funnelId });
const decisions = createFunnelDecisionClient({ ...options, funnelId });

export async function verifyFunnel() {
  const config = await decisions.configuration();
  if (config.evaluationMode !== "remote")
    throw new Error("Publish a Remote Funnel for server-side Decide");
  return config.versionId;
}

export async function decideForUser(input: {
  verifiedUserId: string;
  requestId: string;
  attributes: Record<string, string | number | boolean>;
}) {
  return campaign.decide({
    requestId: input.requestId,
    customer: { type: "externalUserId", value: input.verifiedUserId },
    attributes: input.attributes,
  });
}

export async function reportAdoption(input: {
  decisionId: string;
  eventId: string;
  occurredAt: string;
  reference: string;
}) {
  return decisions.reportUsed(input);
}
```

- 启动时调用一次 `verifyFunnel`，确认 Funnel 已发布且为 Remote 模式。
- `campaign.decide` 返回决策结果；`decision.value` 的内容由你在 Funnel 中配置的输出决定。
- 发送前保存 `requestId`；结果未知时用同一个 `requestId` 和输入重试。
- 最多等待约 30 秒。超时会抛出 `FunnelDecisionTimeoutError`，用其中的 `decisionId` 调用 `decisions.read` 读取结果。

<a id="receipt"></a>

## 回报采纳

用户按决策结果行动（如完成订阅）后，调用 `decisions.reportUsed` 上报（示例中封装为 `reportAdoption`），用于统计效果。保存 `eventId`，重试时使用同一个值。

**相关 SDK 方法**

| 方法 | 返回与恢复 |
| --- | --- |
| campaign.decide(input) | 等待决策完成；返回 FunnelDecision。结果未知时重放原 requestId 和完整输入。 |
| decisions.read(decisionId) | 读取已接受决策的 pending、completed 或 failed 状态。 |
| decisions.reportUsed(input) | 返回 caller_reported 回执；重试沿用原 eventId 和事实。 |

- [HTTP 报文与响应](https://www.longplayai.com/zh-hans/docs/api/funnel-decisions.md)
