PlandalfDocsSign inStart free trial

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>): void

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.

NameTypeWhat it is
namestringGate name, used later with gate(name).
flowstringOffer slug to present when the check fails.
check optionalGateCheck<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 | null

The live handle backing an element the SDK bound (a data-plandalf-* trigger or mount, or a promo/referral widget), or null.

NameTypeWhat it is
elElementAn 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.

NameTypeWhat it is
namestringA gate registered with addGate().
sync optionalGateSyncCallbackCalled with the purchase transaction after the flow completes; return fresh entitlements for the check to re-run against.
opts optionalPartial<FlowOpenOptions>Options for the presented flow (frame, size, prefill…).

Returns Promise<GateResult>.

plandalf.getAnonId

plandalf.getAnonId(): string

Get 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.

NameTypeWhat it is
tokenstringCustomer 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.

NameTypeWhat it is
targetHTMLElement | stringElement, or CSS selector, to render the offer into.
slugstringOffer slug.
opts optionalMountOptionsPromo 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.

NameTypeWhat it is
slugstringOffer slug.
opts optionalPresentOptionsFrame, size, promo slug, prefill properties, Stripe metadata, session continuity and environment. Default {}.

Returns FlowHandle<FlowResult>.

plandalf.promo

plandalf.promo(slug: string): PromoHandle

Open 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.

NameTypeWhat it is
slugstringPromo slug.

Returns PromoHandle.

plandalf.ready

plandalf.ready(cb: (instance: Plandalf) => void): void

Run a callback once the SDK has started, or straight away if it already has.

NameTypeWhat it is
cb(instance: Plandalf) => voidCalled with the SDK instance.

Returns void.

plandalf.referral

plandalf.referral(opts?: ReferralHandleOptions): ReferralHandle

The page's referral handle (one per page, cached).

NameTypeWhat it is
opts optionalReferralHandleOptionstarget mounts a <plandalf-referral> badge there; variant, theme and template style it. Default {}.

Returns ReferralHandle.

plandalf.reset

plandalf.reset(): void

Clear 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

NameUse instead
resetUserreset
setUseridentify

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.

CommandWhat 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

EventSent when
plandalf:badge-clickThe visitor clicked the referral badge. Data: ReferralEventDetail (target is badge or cta).
plandalf:badge-dismissThe visitor dismissed the referral badge. Data: ReferralEventDetail.
plandalf:badge-holdoutThe visitor is in the badge holdout group, so no badge showed (attribution still counts). Data: ReferralEventDetail.
plandalf:badge-shownThe referral badge became visible. Data: ReferralEventDetail.
plandalf:changeElement only (plandalf:change, bubbles): the visitor picked another plan in a plan-selector widget. Detail: { planId }.
plandalf:closeAn offer opened with present closed. Data: { reason }.
plandalf:completeThe buyer finished an offer opened with present. Data: the FlowResult.
plandalf:errorAn offer opened with present failed. Data: { error }.
plandalf:expiredElement only (plandalf:expired, bubbles): a promo countdown reached zero, or the promo has no live config. Detail: { slug, ref }.
plandalf:loadedWindow only (plandalf:loaded): the SDK script has run and window.plandalf is ready to call.
plandalf:openAn offer is opening through plandalf('present') / plandalf('open'). Data: { slug }.
plandalf:purchaseA 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:readyThe SDK has started. Data: { instance }.
plandalf:referralEvery referral and badge event below. Data: { type, detail }.
plandalf:referral-changedThe visitor arrived through a different partner's link. Data: ReferralEventDetail (from is the previous code).
plandalf:referral-expiredThe stored referral passed the program's attribution window. Data: ReferralEventDetail.
plandalf:selectElement 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}>.

PropertyTypeWhat it does
apiBase optionalstringOrigin 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 optionalbooleanReserved. The browser bundle always scans the page for data-plandalf-* elements; this flag isn't read yet.
cdnBase optionalstringReserved. This version of the SDK doesn't read it.
continuity optionalContinuityScopeSession continuity default. Off by default — every present() mints a new session. Per-call overrides live on FlowOpenOptions.
countdownBase optionalstringBase URL of the promo countdown service. Defaults to https://countdown.plandalf.dev/<subdomain>/promo, with the subdomain taken from apiBase.
debug optionalbooleanLog what the SDK does to the console. Default false.
metadata optionalRecord<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 optionalbooleanDownload 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 optionalRecord<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 optionalstring | 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 optionalfalse | ReferralOptionsAffiliate 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 optionalstringCustomer 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.

PropertyTypeWhat it does
consent optionalboolean | "required"Default capture behaviour is immediate. Set to 'required' to wait until plandalf('consent', true) before reading URL params or storage.
cookie optionalstringMirror the token into this cookie name as well as pf_rt.
decorate optionalstring | string[]Hostnames whose outbound links get pf_rt appended on click.
global optionalstringwindow[global] = token — compatibility with an old tool's global.
metadataKey optionalstringKey used by handle.metadata(). Default: program config (plandalf_referral).
params optionalstring | 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

PropertyTypeWhat it does
eventsAsyncIterable<FlowHandleEvent>Live events; for await over it and break to stop.
close() => voidClose 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.

PropertyTypeWhat it does
customer optionalCustomerConvenience — 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 optionalstringWhere to redirect the customer after complete (if the offer configures one).
session optionalCheckoutSessionPayloadThe 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.
statusFlowResultStatus'complete' = user finished the flow. 'dismissed' = closed early.
test optionalbooleanShorthand 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.

PropertyTypeWhat it does
client_secret optionalstringClient secret the payment form confirms with.
currency optionalstringISO currency code.
customer optionalCustomerThe buyer.
discounts optionalunknown[]Discounts applied.
idstring | numberSession id.
intent_id optionalstringGateway intent id.
intent_mode optionalstringGateway mode of the intent (test or live).
intent_type optionalstringKind of gateway intent (payment or setup).
line_items optionalunknown[]Line items.
properties optionalRecord<string, unknown>Form fields collected or prefilled.
statusstringSession status.
subtotal optionalnumberTotal before tax and discounts.
tax optionalnumberTax.
total optionalnumberAmount charged.
uuidstringSession 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).

PropertyTypeWhat it does
continuity optionalContinuityScopePer-call continuity scope override.
metadata optionalRecord<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 optionalstringPromo slug; the SDK resolves the active tier internally and applies its price.
properties optionalRecord<string, unknown>Per-call form-field prefill. Wins over PlandalfConfig.properties on overlap.
session optionalstring | nullSession continuity token. Pass null to force fresh. Omit for default.
subscription optionalstringCheckout-specific subscription to change. Omit for a new purchase.
user optionalstringPer-call JWT override — overrides the global identify() for this mount.

GateResult

What gate() resolves with.

PropertyTypeWhat it does
accessbooleanDid the user get through the gate?
entitlements optionalunknownReturn value from your sync callback (if provided)
error optionalunknownThe original integration/check/sync failure when status is error.
statusGateResultStatusHow 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.

PropertyTypeWhat it does
eventsAsyncIterable<PromoHandleEvent>Live tier-change and expiry events.
close() => voidStop polling, redirecting and dispatching events.

PromoHandleOptions

Options for plandalf.promo(slug, options).

PropertyTypeWhat 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 optionalnumberPoll cadence in ms. Default 1000.
log optional(args: unknown[]) => voidOptional logger; receives any [plandalf]-prefixed lines.
redirect optionalbooleanAuto-redirect to active tier's redirect_url on URL mismatch. Default true.
style optionalRecord<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 optionalstring | HTMLElementOptional 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.

PropertyTypeWhat it does
activeTier{ label: string; offer_item_id?: number; price?: string; price_amount?: number; price_currency?: string; price_id?: number; redirect_url?: string } | nullThe 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.
remainingnumber | nullSeconds left on the active tier; null for a tier with no end.
spotsRemainingnumber | nullSpots 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.

PropertyTypeWhat it does
eventsAsyncIterable<ReferralEvent>Referral and badge events, replaying what already happened on this page.
close() => voidStop this handle's event stream. Capture carries on.
decorate(url: string) => stringAppend 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).

PropertyTypeWhat it does
target optionalstring | HTMLElementElement (or selector) to mount a <plandalf-referral> badge into.
template optionalstringBadge wording with a single {partner} token.
theme optional"light" | "dark" | "auto"Badge colours: light, dark, or follow the visitor's system setting.
variant optionalBadgeVariantBadge style. Default pill.

Referral

A captured partner referral for this visitor.

PropertyTypeWhat it does
clicked_at optionalstringISO timestamp — when the click was recorded, when provided by the server.
codestringThe partner's link code that was clicked.
expires_atstringISO timestamp — end of the program's attribution window.
holdoutbooleanVisitor is in the badge holdout group (badge suppressed; attribution unaffected).
partnerReferralPartnerThe partner whose link was clicked.
promo{ slug: string } | nullPresent when the partner's link targets a Promo.
tokenstringServer-issued, unguessable, org-scoped token (rt_…).

VisitorIdentity

Who the SDK thinks the visitor is, stored in localStorage.

PropertyTypeWhat it does
anonymous_idstringRandom id for this browser, made on the first visit.
first_seen_atstringISO time of the first visit.
last_seen_atstringISO time of the latest visit.
refstring | nullYour id for the visitor (?pf_ref= or setRef()), or null.

The options for present() are on Open a checkout.