Developers
SDK reference
Every method on window.plandalf and the types it uses, generated from the SDK's source. For a guided tour, start with The Plandalf SDK.
Methods
These are on window.plandalf once the script has loaded. Before then, use the command queue.
plandalf.addGate
plandalf.addGate(name: string, flow: string, check?: GateCheck<any>): voidRegister a gate. A gate wraps a feature behind an access check. If the check fails (or is absent), the SDK presents the linked flow.
| Name | Type | What it is |
|---|---|---|
name | string | Gate name, used later with gate(name). |
flow | string | Offer slug to present when the check fails. |
check optional | GateCheck<any> | Returns true when the visitor already has access. Gets
the sync callback's result after a purchase. Omit to always present. |
Returns void.
plandalf.from
plandalf.from(el: Element): FlowHandle<unknown> | PromoHandle | ReferralHandle | nullThe live handle backing an element the SDK bound (a data-plandalf-* trigger or mount, or a promo/referral widget), or null.
| Name | Type | What it is |
|---|---|---|
el | Element | An element the SDK bound. |
Returns FlowHandle<unknown> | PromoHandle | ReferralHandle | null.
plandalf.gate
plandalf.gate(name: string, sync?: GateSyncCallback, opts?: Partial<FlowOpenOptions>): Promise<GateResult>Check a gate. If the check passes, resolves immediately with access: true. If it fails, presents the linked flow. After completion, sync returns fresh entitlements and the same check runs again with those values. Check/sync failures deny access without opening another checkout.
| Name | Type | What it is |
|---|---|---|
name | string | A gate registered with addGate(). |
sync optional | GateSyncCallback | Called with the purchase transaction after the flow completes; return fresh entitlements for the check to re-run against. |
opts optional | Partial<FlowOpenOptions> | Options for the presented flow (frame, size, prefill…). |
Returns Promise<GateResult>.
plandalf.getAnonId
plandalf.getAnonId(): stringGet the anonymous device ID. Always present — generated on first visit, persists forever. Use this to track anonymous visitors and link them to identified users later.
Returns string.
plandalf.identify
plandalf.identify(token: string): Promise<boolean>Store a server-signed customer JWT and validate it with the server. Async: resolves true when the server accepts the JWT, false when it rejects it or can't be reached. The token is kept in localStorage and sent with every later request.
| Name | Type | What it is |
|---|---|---|
token | string | Customer JWT (HS256, signed with one of the organization's API keys, kid header set to the key's id). |
Returns Promise<boolean>.
plandalf.mount
plandalf.mount(target: HTMLElement | string, slug: string, opts?: MountOptions): FlowHandle<Flow>Mount an offer inline. Mirrors present() but renders into the merchant's own container instead of a frame.
| Name | Type | What it is |
|---|---|---|
target | HTMLElement | string | Element, or CSS selector, to render the offer into. |
slug | string | Offer slug. |
opts optional | MountOptions | Promo slug, prefill, metadata, continuity and environment. Default {}. |
Returns FlowHandle<Flow>.
plandalf.present
plandalf.present(slug: string, opts?: PresentOptions): FlowHandle<FlowResult>Present a flow and wait for it to finish.
| Name | Type | What it is |
|---|---|---|
slug | string | Offer slug. |
opts optional | PresentOptions | Frame, size, promo slug, prefill properties,
Stripe metadata, session continuity and environment. Default {}. |
Returns FlowHandle<FlowResult>.
plandalf.promo
plandalf.promo(slug: string): PromoHandleOpen a live handle on a promo: await it for the active tier and time left, iterate .events for tier changes. The page redirects to the active tier's redirect_url when it doesn't match. The object form takes only the slug; use plandalf('promo', slug, options) to pass options such as target or redirect: false.
| Name | Type | What it is |
|---|---|---|
slug | string | Promo slug. |
Returns PromoHandle.
plandalf.ready
plandalf.ready(cb: (instance: Plandalf) => void): voidRun a callback once the SDK has started, or straight away if it already has.
| Name | Type | What it is |
|---|---|---|
cb | (instance: Plandalf) => void | Called with the SDK instance. |
Returns void.
plandalf.referral
plandalf.referral(opts?: ReferralHandleOptions): ReferralHandleThe page's referral handle (one per page, cached).
| Name | Type | What it is |
|---|---|---|
opts optional | ReferralHandleOptions | target mounts a <plandalf-referral> badge there;
variant, theme and template style it. Default {}. |
Returns ReferralHandle.
plandalf.reset
plandalf.reset(): voidClear the current user identity. The anonymous device ID is preserved — only the user token is removed. Next gate/present call will be anonymous.
Returns void.
Older names
| Name | Use instead |
|---|---|
resetUser | reset |
setUser | identify |
Commands
Call these as plandalf('name', …), before or after the script loads. configure, on, off, consent, setRef, getRef, getIdentity and getSessionAge only exist in this form.
| Command | What it does |
|---|---|
plandalf('addGate') | Register a gate. A gate wraps a feature behind an access check. If the check fails (or is absent), the SDK presents the linked flow. |
plandalf('configure') | Change SDK config after start (or before it, from the command queue): apiBase, ref, properties, metadata, referral and the other PlandalfConfig fields. |
plandalf('consent') | Give or withdraw consent for referral capture. Only matters when referral capture waits for consent (referral.consent: 'required' or data-config-referral-consent="required"). |
plandalf('gate') | Check a gate. If the check passes, resolves immediately with access: true. If it fails, presents the linked flow. After completion, sync returns fresh entitlements and the same check runs again with those values. Check/sync failures deny access without opening another checkout. |
plandalf('getIdentity') | Get the full visitor identity record. Contains anonymous_id, ref, first_seen_at, last_seen_at. |
plandalf('getRef') | Get the visitor ref (external identity from ?pf_ref=), or null. |
plandalf('getSessionAge') | Get seconds elapsed since this visitor first arrived (first_seen_at). |
plandalf('identify') | Identify the customer with a server-signed customer JWT. Same as plandalf.identify(token), but the command form returns nothing; call plandalf.identify() to await the validation result. |
plandalf('init') | Start the SDK yourself instead of letting it start on load. Only the first call does anything. Queue it before the script loads to pass your own config; without a queued init the SDK starts itself from the script tag's data-* attributes. |
plandalf('mount') | Render an offer inline inside an element. |
plandalf('off') | Stop listening for an event registered with plandalf('on', …). |
plandalf('on') | Listen for an SDK event. Queue it before the script loads to catch ready. Every event is also dispatched on window as plandalf:<event>. |
plandalf('open') | Alias of plandalf('present'). |
plandalf('present') | Open an offer in a frame. Also emits open, then complete, close or error through plandalf('on', …). |
plandalf('promo') | Open a live promo handle. Single entry point for everything promo-related on a host page. |
plandalf('ready') | Run a callback once the SDK has started, or straight away if it already has. |
plandalf('referral') | The page's referral handle (one per page, cached). |
plandalf('reset') | Clear the current user identity. The anonymous device ID is preserved — only the user token is removed. Next gate/present call will be anonymous. |
plandalf('setRef') | Set the visitor ref and store it in localStorage. Works before the SDK has started, so a landing page can queue it ahead of the script. |
Events
| Event | Sent when |
|---|---|
plandalf:badge-click | The visitor clicked the referral badge. Data: ReferralEventDetail (target is badge or cta). |
plandalf:badge-dismiss | The visitor dismissed the referral badge. Data: ReferralEventDetail. |
plandalf:badge-holdout | The visitor is in the badge holdout group, so no badge showed (attribution still counts). Data: ReferralEventDetail. |
plandalf:badge-shown | The referral badge became visible. Data: ReferralEventDetail. |
plandalf:change | Element only (plandalf:change, bubbles): the visitor picked another plan in a plan-selector widget. Detail: { planId }. |
plandalf:close | An offer opened with present closed. Data: { reason }. |
plandalf:complete | The buyer finished an offer opened with present. Data: the FlowResult. |
plandalf:error | An offer opened with present failed. Data: { error }. |
plandalf:expired | Element only (plandalf:expired, bubbles): a promo countdown reached zero, or the promo has no live config. Detail: { slug, ref }. |
plandalf:loaded | Window only (plandalf:loaded): the SDK script has run and window.plandalf is ready to call. |
plandalf:open | An offer is opening through plandalf('present') / plandalf('open'). Data: { slug }. |
plandalf:purchase | A purchase went through in any SDK checkout. Data: the purchase details, plus referral ({ code, partner: { name } }) when the visitor came through a partner link. |
plandalf:ready | The SDK has started. Data: { instance }. |
plandalf:referral | Every referral and badge event below. Data: { type, detail }. |
plandalf:referral-changed | The visitor arrived through a different partner's link. Data: ReferralEventDetail (from is the previous code). |
plandalf:referral-expired | The stored referral passed the program's attribution window. Data: ReferralEventDetail. |
plandalf:select | Element only (plandalf:select, bubbles): the visitor chose a plan in a pricing-table widget. Detail: { planId }. |
Checkout handles and bound elements also send start, purchase, complete and cancel; see Events.
Config
For plandalf('init', …), plandalf('configure', …) and <PlandalfProvider>.
SDK config: init(config), plandalf('init', config),
plandalf('configure', config) or <PlandalfProvider {...config}>.
| Property | Type | What it does |
|---|---|---|
apiBase optional | string | Origin the SDK calls for offers, checkouts and referrals, e.g.
https://acme.plandalf.dev. The browser bundle defaults it to the
origin the script loaded from (or data-api-base). |
autoScan optional | boolean | Reserved. The browser bundle always scans the page for
data-plandalf-* elements; this flag isn't read yet. |
cdnBase optional | string | Reserved. This version of the SDK doesn't read it. |
continuity optional | ContinuityScope | Session continuity default. Off by default — every present() mints a new session. Per-call overrides live on FlowOpenOptions. |
countdownBase optional | string | Base URL of the promo countdown service. Defaults to
https://countdown.plandalf.dev/<subdomain>/promo, with the subdomain
taken from apiBase. |
debug optional | boolean | Log what the SDK does to the console. Default false. |
metadata optional | Record<string, MetadataValue> | Stripe-bound pass-through. Forwarded to the Stripe Customer's metadata
field at customer-creation time so external affiliate trackers (Tolt,
Rewardful, FirstPromoter, …) can attribute via Customer.metadata.<key>
when email matching is unreliable. Function values are resolved lazily
at session-create time so () => window.tolt_referral reads the
up-to-date value even if the tracker's async script populated it after
page load. Per-call values on FlowOpenOptions override matching keys here.
See specs/sdk-checkout-config.md. |
prefetch optional | boolean | Download the checkout runtime once the page is idle, so the first
present() doesn't wait for it. On by default; turn off on pages that
rarely open a checkout. Also data-prefetch="false" on the script tag. |
properties optional | Record<string, unknown> | Form-field prefill defaults. Merchant-supplied; rendered into checkout
inputs (e.g. first_name, email, custom collected fields). Per-call
values on FlowOpenOptions override matching keys here.
See specs/sdk-checkout-config.md. |
ref optional | string | string[] | Merchant alias(es) for the visitor-identifier URL param. When the host
page emits the visitor's identity under a non-canonical name (Divi forms
locked to email, etc.), list those names here. Tried after pf_ref
and ref. Set via data-config-ref="…" on the SDK <script> tag, or via
plandalf('configure', { ref: … }). See specs/sdk-url-config.md. |
referral optional | false | ReferralOptions | Affiliate referral capture overrides (params, compatibility global /
cookie, metadata key, outbound hosts to decorate). Each field wins
over the program config from GET /client/referrals/config. false
disables capture on this page. Script tag: data-config-referral-params,
data-config-referral-decorate, … See specs/affiliates/sdk.md. |
user optional | string | Customer JWT (HS256, signed with one of the org's API keys, kid header set to the
ApiKey id). Set globally at init OR via plandalf.setUser(jwt). Per-call override
lives on FlowOpenOptions.user. The value is the raw JWT string, not a user object. |
referral
Init-time overrides (referral in plandalf('init', …) / configure, or
data-config-referral-* on the script tag). Each wins over the program
config returned by the server.
| Property | Type | What it does |
|---|---|---|
consent optional | boolean | "required" | Default capture behaviour is immediate. Set to 'required' to wait
until plandalf('consent', true) before reading URL params or storage. |
cookie optional | string | Mirror the token into this cookie name as well as pf_rt. |
decorate optional | string | string[] | Hostnames whose outbound links get pf_rt appended on click. |
global optional | string | window[global] = token — compatibility with an old tool's global. |
metadataKey optional | string | Key used by handle.metadata(). Default: program config (plandalf_referral). |
params optional | string | string[] | Link params that carry a partner code. Default: program config (via). |
Types
FlowHandle
The shape returned by plandalf.present() / plandalf.mount().
Awaitable like a regular Promise, plus:
- .events — async iterable of the v1 critical events
- .close() — dismiss the frame programmatically
| Property | Type | What it does |
|---|---|---|
events | AsyncIterable<FlowHandleEvent> | Live events; for await over it and break to stop. |
close | () => void | Close the offer's frame. |
FlowResult
Result of a presented flow. Always resolved from plandalf.present() —
successful completions and user dismissals both produce a FlowResult so
callers can branch on status without needing a .catch. Only real
errors (network failure, bad slug, etc.) reject the promise.
| Property | Type | What it does |
|---|---|---|
customer optional | Customer | Convenience — same as result.session.customer. |
mode optional | "live" | "test" | "preview" | test when the purchase used test cards (test domain, test link,
mode: 'test'). Never grant real access for a test purchase. |
reason optional | "complete" | "cancel" | "escape" | When dismissed, why — backdrop / close button / escape. |
redirectUrl optional | string | Where to redirect the customer after complete (if the offer configures one). |
session optional | CheckoutSessionPayload | The full CheckoutSession at the moment of completion (populated on
status='complete' only). Invoice + everything else lives in here —
inspect via result.session.uuid, result.session.total,
result.session.invoice, etc. |
status | FlowResultStatus | 'complete' = user finished the flow. 'dismissed' = closed early. |
test optional | boolean | Shorthand for mode === 'test'. |
CheckoutSessionPayload
Minimal shape of the CheckoutSession returned from commit. Extra fields from the server are preserved — we surface the well-known ones here for IntelliSense but consumers can read any key off the raw object.
| Property | Type | What it does |
|---|---|---|
client_secret optional | string | Client secret the payment form confirms with. |
currency optional | string | ISO currency code. |
customer optional | Customer | The buyer. |
discounts optional | unknown[] | Discounts applied. |
id | string | number | Session id. |
intent_id optional | string | Gateway intent id. |
intent_mode optional | string | Gateway mode of the intent (test or live). |
intent_type optional | string | Kind of gateway intent (payment or setup). |
line_items optional | unknown[] | Line items. |
properties optional | Record<string, unknown> | Form fields collected or prefilled. |
status | string | Session status. |
subtotal optional | number | Total before tax and discounts. |
tax optional | number | Tax. |
total optional | number | Amount charged. |
uuid | string | Session UUID. |
MountOptions
Options accepted by plandalf.mount(target, slug, opts?).
Inline mount has fewer knobs than present() because there's no frame —
no modality, no size preset (the mount fills its container), no confirm-close
gate (nothing to close).
| Property | Type | What it does |
|---|---|---|
continuity optional | ContinuityScope | Per-call continuity scope override. |
metadata optional | Record<string, string> | Per-call Stripe-customer metadata. Eager strings only. |
mode optional | "live" | "test" | "preview" | Environment for the session: 'test' | 'live' | 'preview'. Same rules as present()'s
mode: test applies on the organization's test domains, for people signed in to the
organization, with an identify() token carrying "mode": "test", or from a signed test
link (and needs the organization's Stripe test account); anywhere else it runs live. |
promo optional | string | Promo slug; the SDK resolves the active tier internally and applies its price. |
properties optional | Record<string, unknown> | Per-call form-field prefill. Wins over PlandalfConfig.properties on overlap. |
session optional | string | null | Session continuity token. Pass null to force fresh. Omit for default. |
subscription optional | string | Checkout-specific subscription to change. Omit for a new purchase. |
user optional | string | Per-call JWT override — overrides the global identify() for this mount. |
GateResult
What gate() resolves with.
| Property | Type | What it does |
|---|---|---|
access | boolean | Did the user get through the gate? |
entitlements optional | unknown | Return value from your sync callback (if provided) |
error optional | unknown | The original integration/check/sync failure when status is error. |
status | GateResultStatus | How access was resolved |
transaction optional | { customer?: unknown; flow: string; order?: unknown; status: "completed" | "failed"; subscription?: unknown; type: "purchase" | "cancellation" | "capture" | "recovery" | "upsell" } | The raw transaction from Plandalf (if a flow was presented) |
PromoHandle
What plandalf.promo(slug) returns. Await it for the promo's current
state (null when the promo has no live config); iterate .events for
tier changes; .close() stops watching.
| Property | Type | What it does |
|---|---|---|
events | AsyncIterable<PromoHandleEvent> | Live tier-change and expiry events. |
close | () => void | Stop polling, redirecting and dispatching events. |
PromoHandleOptions
Options for plandalf.promo(slug, options).
| Property | Type | What it does |
|---|---|---|
frame optional | "modal" | "slideout" | "bottom" | "fullscreen" | "inline" | Reserved for future 'modal' | 'slideout' | 'bottom' | 'fullscreen'
modes that present a promo widget inside a chrome frame instead of
inline. Today only 'inline' (the default — when target is set)
and headless (no target, no frame) work. |
interval optional | number | Poll cadence in ms. Default 1000. |
log optional | (args: unknown[]) => void | Optional logger; receives any [plandalf]-prefixed lines. |
redirect optional | boolean | Auto-redirect to active tier's redirect_url on URL mismatch. Default true. |
style optional | Record<string, unknown> | Per-mount style overrides on top of the merchant's saved promo
style. Only meaningful when target is set (no widget = nothing
to style). Same shape as <div data-plandalf-style='{...}'>. |
target optional | string | HTMLElement | Optional element (or selector) to mount a live ticking countdown
widget into. Same SVG the <div data-plandalf-promo="…"> auto-scan
produces. Omit for a headless monitor (no visible UI; just events
+ redirect side-effect). |
ResolvedPromo
A promo's state for this visitor: the active tier, time and spots left, and its config.
| Property | Type | What it does |
|---|---|---|
activeTier | { label: string; offer_item_id?: number; price?: string; price_amount?: number; price_currency?: string; price_id?: number; redirect_url?: string } | null | The tier on now (its label, price and redirect URL), or null once the promo has ended. |
config | { ignore_redirect_patterns?: string[]; name: string; offer?: string; offer_id?: number; slug: string; style: Record<string, unknown>; tiers: PromoTier[]; type: string; unenrolled_to_last_tier?: boolean } | The promo's settings. |
remaining | number | null | Seconds left on the active tier; null for a tier with no end. |
spotsRemaining | number | null | Spots left on a quantity-limited promo, else null. |
ReferralHandle
What plandalf.referral() returns. Await it for the visitor's referral
(or null), iterate .events, and use decorate() / metadata() to
carry the referral into checkouts Plandalf doesn't render.
| Property | Type | What it does |
|---|---|---|
events | AsyncIterable<ReferralEvent> | Referral and badge events, replaying what already happened on this page. |
close | () => void | Stop this handle's event stream. Capture carries on. |
decorate | (url: string) => string | Append pf_rt=<token> (and Stripe's client_reference_id on buy.stripe.com). No-op without a referral. |
metadata | () => Record<string, string> | { [metadata_key]: token } for server-created Stripe sessions, or {}. |
ReferralHandleOptions
Options for plandalf.referral(options).
| Property | Type | What it does |
|---|---|---|
target optional | string | HTMLElement | Element (or selector) to mount a <plandalf-referral> badge into. |
template optional | string | Badge wording with a single {partner} token. |
theme optional | "light" | "dark" | "auto" | Badge colours: light, dark, or follow the visitor's system setting. |
variant optional | BadgeVariant | Badge style. Default pill. |
Referral
A captured partner referral for this visitor.
| Property | Type | What it does |
|---|---|---|
clicked_at optional | string | ISO timestamp — when the click was recorded, when provided by the server. |
code | string | The partner's link code that was clicked. |
expires_at | string | ISO timestamp — end of the program's attribution window. |
holdout | boolean | Visitor is in the badge holdout group (badge suppressed; attribution unaffected). |
partner | ReferralPartner | The partner whose link was clicked. |
promo | { slug: string } | null | Present when the partner's link targets a Promo. |
token | string | Server-issued, unguessable, org-scoped token (rt_…). |
VisitorIdentity
Who the SDK thinks the visitor is, stored in localStorage.
| Property | Type | What it does |
|---|---|---|
anonymous_id | string | Random id for this browser, made on the first visit. |
first_seen_at | string | ISO time of the first visit. |
last_seen_at | string | ISO time of the latest visit. |
ref | string | null | Your id for the visitor (?pf_ref= or setRef()), or null. |
The options for present() are on Open a checkout.