# Funnel server decision guide

Call a Remote Funnel from a trusted backend with the SDK, handle pending results and retries, and report adoption.

[Web version](https://www.longplayai.com/docs/guides/funnel-decisions)

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

## Install and configure

**terminal**

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

Copy the Service URL (API origin) and App ID (App UUID) from Integration scope at the top of Integrations → Integration overview in the Console. Use the UUID of the published target Funnel. The API origin does not include /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>

## Before you begin

- Publish the target Funnel in Console with Remote evaluation. Server decisions support Remote mode only.
- The Server Key needs customers:write, sessions:create, funnels:run.
- A Run uses the permissions of the Key that started it: Paywall and Offering steps need entitlements:read; buying from a Paywall also needs billing:write (quote, confirm and cancel) and billing:read (settlement and recovery reads); claiming or showing Coupons needs offers:resolve.
- In the Console's Create Key dialog, "Use Funnel start permissions" selects all of them: funnels:run, sessions:create, customers:write, entitlements:read, offers:resolve, billing:read, billing:write.
- Use a user ID your backend has verified as `externalUserId`.
- Pass the business attributes this decision needs in `attributes`; conditions in the Funnel can read them.

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

## Call from your backend

**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);
}
```

- Call `verifyFunnel` once at startup to confirm the Funnel is published in Remote mode.
- `campaign.decide` returns the decision; `decision.value` contains the output you configured in the Funnel.
- Save the `requestId` before sending; after an unknown result, retry with the same `requestId` and input.
- It waits up to about 30 seconds. A timeout throws `FunnelDecisionTimeoutError`; call `decisions.read` with its `decisionId` to get the result.

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

## Report adoption

When the user acts on the decision, for example by subscribing, call `decisions.reportUsed` (wrapped as `reportAdoption` in the example) to record it for reporting. Save the `eventId` and reuse it on retries.

**Related SDK methods**

| Method | Return and recovery |
| --- | --- |
| campaign.decide(input) | Waits for completion and returns FunnelDecision. Replay the original requestId and full input after an unknown outcome. |
| decisions.read(decisionId) | Reads a pending, completed, or failed accepted decision. |
| decisions.reportUsed(input) | Returns a caller_reported receipt. Reuse the eventId and fact on retry. |

- [HTTP requests and responses](https://www.longplayai.com/docs/api/funnel-decisions.md)
