# 运行 Funnel

从后端启动 Run 并在浏览器展示，使用 Campaign、外部信号与 Funnel 命令。

更新于 2026-11-05

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

<a id="choose"></a>

## 选择接入方式

**接入方式**

| 需求 | 使用 |
| --- | --- |
| 向用户展示已发布的 Funnel 页面 | `createFunnelStartClient` + `showFunnelRun` |
| 后端只需要一个结果（如推荐套餐） | `createFunnelCampaignClient().decide` |
| 按频率限制展示活动 | `createFunnelCampaignClient().start` |
| 把外部事件交给等待中的 Funnel | `createFunnelOrchestrationClient().signal` |

<a id="start"></a>

## 启动并展示 Funnel

后端启动 Run 并签发 Customer Token，浏览器用这两个值展示 Funnel。后端 Key 需要 `funnels:run`、`sessions:create` 和 `customers:write`。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`。

**后端: server/funnel.ts**

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

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

export async function startOnboarding(verifiedUserId: string, requestId: string) {
  const started = await funnels.start({
    funnelId: process.env.LONGPLAY_FUNNEL_ID!,
    requestId, // persisted; reuse it with the same input after an unknown result
    customer: { type: "externalUserId", value: verifiedUserId },
    locale: "en",
    parameters: {
      source: "signup",
      // Required when the Funnel shows a Paywall.
      commerce: { provider: "stripe", currency: "USD" },
    },
  });
  const customerSession = await longplay.createCustomerSession(started.customerId!);
  return { runToken: started.runToken, started, customerSession };
}
```

**浏览器: app/funnel.ts**

```ts
import {
  createLongplay,
  createFunnelRunController,
  showFunnelRun,
  type CustomerSession,
  type FunnelRuntimeResponse,
} from "@tinkerlandai/longplay-sdk";

export async function showOnboarding(
  container: HTMLElement,
  session: {
    runToken: string;
    started: FunnelRuntimeResponse;
    customerSession: CustomerSession;
  },
) {
  const options = {
    baseUrl: "https://api.longplayai.com",
    scope: { projectId: "<APP_UUID>", environment: "sandbox" as const },
  };
  const longplay = createLongplay(options);
  longplay.identify(session.customerSession);
  const controller = createFunnelRunController({
    ...options,
    session: longplay.session,
    runToken: session.runToken,
    // The first screen renders from this reply. Leave it out after a reload.
    initialResponse: session.started,
  });
  return showFunnelRun(container, {
    client: controller,
    onComplete: (run) => console.log("completed", run),
    onError: (error) => console.error(error),
  });
}
```

Funnel 有 Paywall 时，启动必须传 `parameters.commerce`，写明 `provider` 和 `currency`。缺少时请求返回 400，不会创建 Run。

- 保存 `requestId`；响应丢失时用同一个值重试，会得到同一个 Run。
- 已暂停的 Funnel 以 409 `CONFLICT` 拒绝新的启动；显示为暂时不可用。用原 `requestId` 重放仍返回原 Run。
- Funnel 中的支付和发券在服务端完成，浏览器关闭不影响已经开始的处理。

<a id="campaign"></a>

## 按频率展示活动

`start` 在冷却时间内或已有进行中的 Run 时返回 `suppressed: true` 和下次可展示的时间 `retryAt`。

**campaign.ts**

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

const campaign = createFunnelCampaignClient({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
  funnelId: process.env.LONGPLAY_FUNNEL_ID!,
});

export async function maybeShowCampaign(verifiedUserId: string, requestId: string) {
  const result = await campaign.start({
    requestId,
    customer: { type: "externalUserId", value: verifiedUserId },
    locale: "en",
    parameters: { placement: "home" },
    cooldownSeconds: 86400,
  });
  if ("suppressed" in result) return { show: false as const, retryAt: result.retryAt };
  return { show: true as const, runToken: result.runToken };
}
```

- [只获取结果：Funnel 服务端决策](https://www.longplayai.com/zh-hans/docs/guides/funnel-decisions.md)

<a id="signal"></a>

## 发送外部事件

Funnel 停在等待节点时，后端提交外部事件；`eventId` 用于去重。

> `eventName` 必须与等待节点里的事件名完全一致（区分大小写）。事件名以字母开头，只含字母、数字、`_`、`.` 和 `-`，最长 64 个字符，例如 `kyc_approved` 或 `kyc.approved`。

**signal.ts**

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

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

// eventId is persisted with your business event, so retries are deduplicated.
export async function reportKycApproved(runId: string, eventId: string) {
  const { accepted } = await orchestration.signal({
    runId,
    nodeId: "wait_for_kyc",
    eventName: "kyc_approved",
    eventId,
    data: { level: "full" },
  });
  return accepted ? orchestration.readResults(runId) : null;
}
```

<a id="local"></a>

## 在浏览器中求值（Local 模式）

发布为 Local 模式的 Funnel 可以在浏览器中直接启动，用户不必等待服务端计算。规则对所有人可见，涉及资格或价格的判断请使用默认的服务端模式。

**local-funnel.ts**

```ts
import {
  createConfigurationSync,
  createLocalFunnelClient,
  showFunnelRun,
} from "@tinkerlandai/longplay-sdk";

const baseUrl = "https://api.longplayai.com";
const configuration = createConfigurationSync({
  origin: baseUrl,
  scope: { projectId: "<APP_UUID>", environment: "sandbox", environmentId: "<ENVIRONMENT_UUID>" },
});

export async function showLocalFunnel(
  container: HTMLElement,
  customerToken: string,
  requestId: string,
) {
  const flow = await createLocalFunnelClient({
    baseUrl,
    configuration,
    funnelId: "<PUBLISHED_FUNNEL_UUID>",
    credential: customerToken,
  });
  const started = await flow.start({ requestId, locale: "en", parameters: {} });
  // Keep started.runToken to restore the same Run later with flow.restore(runToken).
  return showFunnelRun(container, { client: started.controller });
}
```

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

## 通过 HTTP 调用

所有 Funnel 命令都发送到 `POST /api/v1/funnels`，由请求体的 `operation` 选择。

- [全部 Funnel 命令](https://www.longplayai.com/zh-hans/docs/api/operations.md#funnel-commands)
