PlandalfDocsSign inStart free trial

Developers

React package

Use @plandalf/react 2.0.0 to open a checkout from a React component. Its hooks also let you identify buyers, check access and display deadline timers.

Install and add the provider

npm install @plandalf/react

Wrap your app in <PlandalfProvider> once, near the root. apiBase is your organization's host.

import { createRoot } from 'react-dom/client';
import { PlandalfProvider } from '@plandalf/react';
import App from './App';

createRoot(document.getElementById('root')!).render(
  <PlandalfProvider apiBase="https://YOUR-ORG.plandalf.dev">
    <App />
  </PlandalfProvider>,
);

The provider takes every SDK config field as a prop, such as continuity, properties and metadata. It creates the SDK in your bundle, so you don't add the script tag. Open checkouts with the hooks. To use HTML attributes, follow Add the script.

Next.js App Router

Since the package starts with 'use client', you can render <PlandalfProvider> around {children} in your server layout. Use a client component for hooks and for any wrapper that passes functions to the provider. See the Next.js layout example.

Open a checkout

import { usePresent, FlowResultStatus } from '@plandalf/react';

export function BuyButton() {
  const { present, presenting } = usePresent();

  async function buy() {
    const result = await present('YOUR-CHECKOUT');
    if (result.status === FlowResultStatus.Complete) window.location.href = '/thanks';
  }

  return <button disabled={presenting} onClick={buy}>Buy now</button>;
}

present(slug, options) is the same as plandalf.present() and returns the same handle. presenting is true until the checkout closes.

Identify the buyer

Pass a signed buyer token as the provider's user prop. When you change the token, the provider calls identify(). If you pass an empty token, it calls reset().

<PlandalfProvider apiBase="https://YOUR-ORG.plandalf.dev" user={session?.plandalfToken ?? ''}>

Or use useUser(), which returns token, anonId, setUser(token) and resetUser(). How to sign the token is in Identify buyers.

Gates, deadline timers and referrals

  • <Gate>, useGate() and useGateTrigger(): see Gates.
  • usePromo(slug) returns a deadline timer's current tier, remaining seconds and spotsRemaining, plus present() to open the deadline timer's checkout at the tier's price. Reading the deadline timer keeps the buyer on the current page. useCountdown(slug) returns a ref to attach to the element that shows the countdown.
  • useReferral() returns referral, loading, decorate(url) and metadata(). See Referrals from code.
import { usePromo, useCountdown } from '@plandalf/react';

export function SaleBanner() {
  const { tier, loading, present } = usePromo('YOUR-PROMO');
  const { ref } = useCountdown<HTMLDivElement>('YOUR-PROMO');
  return (
    <section>
      <div ref={ref} />
      {!loading && tier && (
        <button onClick={() => present()}>Buy at {tier.label}</button>
      )}
    </section>
  );
}

Use the SDK directly

usePlandalf() returns the SDK instance from the provider, with present, mount, identify, reset, addGate, gate, promo, referral, configure and the rest. Outside a provider it throws.

const sdk = usePlandalf();
useEffect(() => {
  const flow = sdk.mount('#checkout', 'YOUR-CHECKOUT');
  return () => flow.close();
}, [sdk]);

Reference

Use FlowResultStatus and GateResultStatus to compare result statuses. Use FlowHandleEventType to compare checkout event types. The package also includes the older iframe embeds (Offer…Embed and Journey).

Components

<Gate>

Show children when the visitor has access, fallback when they don't (and loading while the check runs). Inside the fallback, useGateTrigger() opens the offer.

NameTypeWhat it is
check optionalGateCheck<any>Local check function — runs on mount to determine access silently
childrenReactNodeRendered when access is granted
fallback optionalReactNodeRendered when access is denied. Gets GateContext so it can call trigger().
flowstringFlow slug to present when the gate fails
loading optionalReactNodeRendered while the initial check is running
namestringUnique gate name
onAccess optional(result: GateResult) => voidCalled after the full gate flow completes
sync optionalGateSyncCallbackSync callback passed to sdk.gate() when the full gate flow is triggered

<Journey>

Groups iframe checkout embeds: they share its domain and customer, their events reach every subscriber, and when a checkout completes the buyer goes to options.success_url.

NameTypeWhat it is
childrenReactNodeContent, including the checkout embeds.
customer optionalCustomerInfoBuyer details the embeds inside prefill.
idstringJourney id.
optionsJourneyOptionsDomain and success URL for the embeds inside.
typestringJourney type, e.g. enroll, upgrade or conversion.

<OfferFullScreenEmbed>

An offer's checkout in a full-screen iframe.

NameTypeWhat it is
customer optionalCustomerInfoBuyer details to prefill. Defaults to the enclosing <Journey>'s customer.
domain optionalstringCheckout host. Defaults to the enclosing <Journey>'s domain, else https://checkout.plandalf.dev.
events optionalPartial<EmbedEventCallbacks>Callbacks for checkout events.
inheritParameters optionalbooleanCopy the page's query params onto the checkout URL.
isOpenbooleanShow the full-screen checkout.
offerstringOffer slug.
onClose() => voidCalled when the buyer closes it; set isOpen false here.
onComplete optional(checkout: any) => voidSame as events.onComplete.
onError optional(error: any) => voidSame as events.onError.
onSuccess optional(data: any) => voidSame as events.onSuccess.
parameters optionalRecord<string, any>Extra query params for the checkout URL.

<OfferPopupEmbed>

An offer's checkout in a popup iframe over the page.

NameTypeWhat it is
customer optionalCustomerInfoBuyer details to prefill. Defaults to the enclosing <Journey>'s customer.
domain optionalstringCheckout host. Defaults to the enclosing <Journey>'s domain, else https://checkout.plandalf.dev.
events optionalPartial<EmbedEventCallbacks>Callbacks for checkout events.
height optionalstringPopup height, as a CSS length. Overrides size.
inheritParameters optionalbooleanCopy the page's query params onto the checkout URL.
isOpenbooleanShow the popup.
offerstringOffer slug.
onClose() => voidCalled after the popup's close animation; set isOpen false here.
onComplete optional(checkout: any) => voidSame as events.onComplete.
onError optional(error: any) => voidSame as events.onError.
onSuccess optional(data: any) => voidSame as events.onSuccess.
parameters optionalRecord<string, any>Extra query params for the checkout URL.
size optional"small" | "medium" | "large"Popup size preset. Default medium.
width optionalstringPopup width, as a CSS length. Overrides size.

<OfferStandardEmbed>

An offer's checkout in an inline iframe that grows with its content.

NameTypeWhat it is
customer optionalCustomerInfoBuyer details to prefill. Defaults to the enclosing <Journey>'s customer.
domain optionalstringCheckout host. Defaults to the enclosing <Journey>'s domain, else https://checkout.plandalf.dev.
dynamicResize optionalbooleanGrow the iframe to fit the checkout's content. Default true.
events optionalPartial<EmbedEventCallbacks>Callbacks for checkout events.
inheritParameters optionalbooleanCopy the page's query params onto the checkout URL.
offerstringOffer slug.
onComplete optional(checkout: any) => voidSame as events.onComplete.
onError optional(error: any) => voidSame as events.onError.
onSuccess optional(data: any) => voidSame as events.onSuccess.
parameters optionalRecord<string, any>Extra query params for the checkout URL.

<PlandalfProvider>

Creates the SDK once with the config props and gives it to the hooks inside. When you pass user, the provider keeps the identity in step: a JWT calls identify(), an empty value calls reset().

NameTypeWhat it is
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.
childrenReactNodeYour app. Hooks inside reach the SDK.
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.
publicKey optionalstringOptional. The core SDK identifies the org via apiBase (your org's Plandalf URL); the key is only consumed by the legacy embed wrapper.
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.

Hooks

useCountdown

useCountdown<T>(slug: string, options?: CountdownOptions): { destroy: () => void; ref: RefObject<T | null> }

Render a promo's live countdown into the element you attach ref to (a <div> unless you pass another element type). Same widget as <div data-plandalf-promo="…">; removed on unmount.

NameTypeWhat it is
slugstring
options optionalCountdownOptions

Returns { destroy: () => void; ref: RefObject<T | null> }.

useEmbedEvents

useEmbedEvents(journey: JourneyContextValue | null, callbacks: Partial<EmbedEventCallbacks>): EmbedEventCallbacks

Combine an embed's own callbacks with its enclosing Journey's, so each event reaches both.

NameTypeWhat it is
journeyJourneyContextValue | nullFrom useJourneyOptional().
callbacksPartial<EmbedEventCallbacks>The embed's callbacks.

Returns EmbedEventCallbacks.

useGate

useGate(name: string, flow: string, check?: GateCheck<any>): { access: boolean | null; checking: boolean; result: GateResult | null; trigger: (sync?: GateSyncCallback, options?: Partial<FlowOpenOptions>) => Promise<GateResult> }

Register a gate and check it. access is null while the check runs, then true or false; trigger(sync?, options?) runs the full gate, presenting the offer when access is denied, and updates access and result.

NameTypeWhat it is
namestringGate name.
flowstringOffer slug to present when the check fails.
check optionalGateCheck<any>Returns true when the visitor already has access.

Returns { access: boolean | null; checking: boolean; result: GateResult | null; trigger: (sync?: GateSyncCallback, options?: Partial<FlowOpenOptions>) => Promise<GateResult> }.

useGateTrigger

useGateTrigger(): GateContextValue

Use inside a Gate's fallback to get the trigger that opens the paywall. ``tsx function UpgradePrompt() { const { trigger, checking } = useGateTrigger(); return <button disabled={checking} onClick={() => trigger()}>Upgrade</button>; } ``

Returns GateContextValue.

useJourney

useJourney(): JourneyContextValue

The enclosing <Journey>'s state. Throws outside a Journey.

Returns JourneyContextValue.

useJourneyOptional

useJourneyOptional(): JourneyContextValue | null

The enclosing <Journey>'s state, or null outside one.

Returns JourneyContextValue | null.

usePlandalf

usePlandalf(): Plandalf

The SDK instance from <PlandalfProvider>. Throws outside one.

Returns Plandalf.

usePresent

usePresent(): { present: (slug: string, options?: PresentOptions) => FlowHandle<FlowResult>; presenting: boolean }

present(slug, options?) with a presenting flag that is true until the offer closes.

Returns { present: (slug: string, options?: PresentOptions) => FlowHandle<FlowResult>; presenting: boolean }.

usePromo

usePromo(slug: string): UsePromoResult

Live state for a promo: the active tier, time left, spots left. Built on sdk.promo(slug) (one shared monitor per slug per page) with the auto-redirect off, so reading a promo from React never navigates the page.

NameTypeWhat it is
slugstring

Returns UsePromoResult.

useReferral

useReferral(): { decorate: (url: string) => string; loading: boolean; metadata: () => Record<string, string>; referral: Referral | null }

The visitor's affiliate referral (captured by the SDK from ?via= etc.). const { referral, loading, decorate } = useReferral(); <a href={decorate('https://buy.stripe.com/abc')}>Buy</a> Re-renders on captured / changed / expired. decorate(url) is a no-op until a referral exists.

Returns { decorate: (url: string) => string; loading: boolean; metadata: () => Record<string, string>; referral: Referral | null }.

useUser

useUser(): { anonId: string; resetUser: () => void; setUser: (t: string) => void; token: string | null }

The customer identity: token (the stored JWT or null), anonId, setUser(jwt) (calls identify() without waiting for validation) and resetUser() (calls reset()).

Returns { anonId: string; resetUser: () => void; setUser: (t: string) => void; token: string | null }.