@funnelsgrove/payments
v0.80.0
Published
Shared billing and checkout helpers for funnels.
Readme
@funnelsgrove/payments
Shared billing and checkout helpers for funnels.
Read this file before editing checkout code. Deeper implementation docs:
Owns provider-backed checkout primitives
@funnelsgrove/payments owns reusable payment contracts, provider adapters, checkout-session helpers, wallet slots, checkout UI primitives, and Checkout Session-scoped semantic analytics. Funnel code owns paywall layout, copy, when an offer opens, post-payment navigation, and the lifecycle completion callback after verified payment success.
Current Checkout Path
Render every visible wallet placement with StripeSubscriptionWalletSurface or StripeOneTimeWalletSurface, matching the resolved plan's payment mode. They are the normal current path for Apple Pay and Google Pay:
- Each surface owns one private Checkout Session per simultaneously visible wallet placement, isolated by its own
surfaceId. - Simultaneously visible placements may use the same plan and coupon; nothing is shared because each surface keeps its own session.
- Changing the selected plan replaces the surface’s Checkout Session and
clientSecret. A stablesurfaceIdidentifies the placement; it does not guarantee that the Stripe iframe survives a plan change. - If payment confirmation is already in flight when the selection changes, the success callback remains bound to the original confirmed Checkout Session.
Use these for new subscription paywalls:
StripeSubscriptionWalletSurfaceuseStripeSubscriptionCheckoutSessionStripeCheckoutDialogtrackPaidStripeSubscriptionCheckoutCompletedtrackStripeSubscriptionPaymentInfoSubmitted
For an inline subscription form with the device wallet first and card last, use
StripeWalletFirstCheckout. It shows one block per payment method: one wallet, Google Pay
on Android and Apple Pay elsewhere, preselected, with Stripe's own button; every other
method the offer supports (Pix, Klarna, …) as one block; and the card form.
- Pass the card hook's
clientSecret,checkoutSessionIdandstripePromise. While the Checkout Session is being created, passclientSecret={null}: the full layout renders and the wallet slot holds a progress bar at the button's height, so nothing moves when Stripe's button arrives. - Also pass
amountCentsandsummaryLabelfor the wallet sheet,customerEmail(set on the session before card confirmation, since the form has no email field),returnUrl,checkoutAnalytics, a completeStripeWalletFirstCheckoutCopyfrom the funnel's content, andthemeColor/buttonColor. - The card form has no name, email or terms text. Stripe asks for the postal code only for
card countries that use it (US, Canada, UK), which helps US issuers approve the payment.
Pass
paymentElementOptionsto override the card form's Payment Element options. Keys offields.billingDetailsmerge one by one with the defaults, for example{ fields: { billingDetails: { address: { country: 'auto', postalCode: 'never' } } } }. onCancelruns when the visitor closes the Apple Pay or Google Pay sheet without paying, for example to show an extra discount. The form is unlocked again by then.onError(message, details?)preserves the existing message argument and adds exportedStripeCheckoutErrorDetails:category,paymentMethod,providerDeclineCode,providerErrorCode, andproviderErrorType. The same callback contract applies toSharedStripeCheckoutV2DialogandStripeCheckoutExpressCheckoutButton. Provider fields and payment method are present when known; clearing callsonError(null)without details. Usedetails.category === 'payment_rejection'anddetails.paymentMethodto distinguish a card, Apple Pay, or Google Pay refusal. Wallet refusals are reported before the existing card fallback; wallet cancellation continues throughonCancel.- Where the browser cannot pay with that wallet, the wallet stays first and its slot shows
walletUnavailableNote({wallet}is replaced with the wallet name). The card remains one tap away. This is deliberate: the layout must not move. - Other methods follow CHECKOUT-BR-010:
create the card session with
paymentMethodTypes: ['card']so its form never shows another method, and pass the hook'savailablePaymentMethodTypesand the same hook input asmethodSessionInput(itsonError,onResetandonPreparationStartare not used; each block shows its own session error). Each other block then owns a Checkout Session restricted to its methods, created with its own idempotency key when the block is selected (at once when it is theinitialMethod, as soon as the card session has reported the offer's methods), and renders Stripe's Payment Element for that session, which collects what the method needs, e.g. the CPF for Pix. Without extras, withoutmethodSessionInput, or when the card session itself offers other methods (they would repeat), nothing changes. Once any block confirmed a payment the other blocks stay disabled, so one visitor cannot pay twice across sessions.methodssets the blocks and their order; the default is['wallet', 'other', 'card']. A method named in it, e.g.['wallet', 'pix', 'card'], gets its own block; unnamed extras share the'other'block when it is listed, else they are not offered.initialMethodmay name any block, including'other'or a method inside it.copy.methodLabelsnames the methods ({ pix: 'Pix' }); a missing type shows its capitalized name. - A failed payment shows over the blocks, not under them, so nothing below moves and the
visitor's input stays: a title per failure category, the bank's reason for a decline, a
retry button that closes it, and after a decline a button to the wallet (or to the card when
the wallet failed). A field the form can mark keeps its error inline.
copy.errorsoverrides the Englishtitles,bodies,retryLabel,dismissLabel,switchLabel({method}) andcloseLabel. WalletButtonis the wallet block's slot on its own: progress bar at the button's height, then Stripe's Apple Pay or Google Pay button, or the unavailable note. Inside an existingCheckoutProvideromitsession; for a standalone placement passsession={{ clientSecret, stripePromise, themeColor }}and it owns that session's scope.- The component owns
checkout_shown(once per mount,checkout_surface: inline),checkout_started(when the card or another method's form opens, or on wallet intent),add_payment_infoand verifiedcheckout_completed. Another method's session is created withcheckoutStartSource: 'checkout_render', so creating it is not a start. - After confirmation, the payment status stays in the form until the caller replaces it.
With the runtime's embedded completion, the success screen takes over. Otherwise
onSuccessruns, and then the page navigates toreturnUrl.
Use these for new one-time paywall plans:
StripeOneTimeWalletSurfaceuseStripeOneTimeCheckoutSessioncreateStripeOneTimeCheckoutStripeCheckoutDialog
StripeCheckoutDialog is the checkout dialog (ClaimBee paywall-v3 layout): order summary with
the discount timer and satisfaction line, the StripeWalletFirstCheckout blocks and a guarantee
line. It is a bottom sheet on phones and a centred modal from 640px wide. It takes every
StripeWalletFirstCheckout prop plus title, closeAriaLabel, onClose, summary and
guaranteeLabel. Mount it while open: one mount reports checkout_shown (surface dialog) and
queues checkout_started; closing reports checkout_canceled.
SharedStripeCheckoutV2Dialog keeps its props for existing funnels and renders the same
components: a dialog renders StripeCheckoutDialog (both variants; compact only drops the
satisfaction line) and presentation='inline' renders StripeWalletFirstCheckout in the page.
Its email field, PayPal slot, billing countries, wallet availability, card brands and
expired-session handler map onto the wallet-first props below. The old .shared-checkout-v2-*
classes of the dialog are gone; funnels that styled or queried them need the new markup.
StripeWalletFirstCheckout also accepts email (an email field in the card form; wallets show
only while the visitor keeps the session's email), supportedCountries and
unsupportedCountryMessage, initialWalletAvailable, hideUnavailableWallet, cardBrandLabels,
onInactiveCheckoutSession and onPaymentInfoSubmitted.
For a mixed Stripe/PayPal Offer Set, pass the selected binding's PayPalCheckout
as paypalCheckout. It is its own block after the wallet.
Set showSummary={false} on PayPalCheckout to omit its repeated plan caption.
Forward onPendingChange to paypalPending so an unresolved PayPal purchase keeps
the PayPal block selected and locks the others. The V2 dialog passes it only for the
dialog presentation. A PayPal-only Offer Set
uses PayPalCheckoutDialog around the same native checkout, without creating a
Stripe session. The funnel owns opening the dialog and post-success navigation.
A Paddle-only Offer Set uses PaddleCheckoutDialog around PaddleCheckout, with
resolvePublishedBillingRuntime(...).paddleOptionsByPlanKey[planKey] as its option.
Mounting it creates the attempt's Paddle transaction and opens it with Paddle.js inline
checkout (customerEmail prefills the buyer); reopening the same selection reuses the
recorded transaction. A declined card stays in Paddle's frame. Paddle's
checkout.completed only starts server status polling, and onSuccess runs once the
server reports succeeded. onClose closes the surface when the checkout cannot
continue. readPendingPaddleCheckout returns a paid but unconfirmed plan, which the paywall
keeps selected without offering another purchase. Paddle discounts are not mapped.
Use completeStripeOneClickPayment for normal post-checkout one-click upsells. It delegates the charge to funnelSdkService.chargeOneClickPayment and owns any required Stripe confirmation. Pass its optional checkoutAnalytics context to let the shared package emit checkout_completed only after succeeded, including after required confirmation. The context uses StripeSubscriptionCheckoutAnalyticsContext; completion is deduplicated by PaymentIntent ID, and analytics failures do not fail the payment. Funnel code supplies the context and completes its step; the shared package owns the analytics callback. chargeStripeOneClickPayment remains the lower-level charge-only primitive.
Solidgate browser checkout is available for controlled provider-routed funnels through
SolidgateCheckoutDialog, prepareSolidgateCheckout, and pollSolidgateCheckoutStatus. The dialog
mounts one official Solidgate form per attempt, destroys the remote form on replacement/unmount,
and never treats iframe success as funnel completion. Its onSuccess(checkout, { paymentMethod })
callback runs only after the provider-neutral status endpoint finds
canonical shared-ledger payment evidence. paymentMethod is apple_pay, google_pay, card or other, taken from the Solidgate
submit event for that attempt, and null when this page did not observe the submission.
For a Solidgate one-click upsell, call completeSolidgateOneClickPayment with the paid checkout's
attemptId as checkoutSessionId, the external userId, the published selection and a stable
idempotencyKey. It charges only a card saved by that payment, polls the new attempt, and emits
checkout_completed only for succeeded. Apple Pay and Google Pay must show their button again, so
when onSuccess reported apple_pay or google_pay, render the upsell as SolidgateCheckoutDialog
with layout: 'wallet' and checkoutType: 'one_time' instead of a one-click button. On
SolidgateSavedPaymentMethodUnavailableError (no reusable card), render SolidgateCheckoutDialog
with checkoutType: 'one_time'.
Localized funnel copy
Funnel content files own translated strings. Pass a complete SharedStripeCheckoutV2Copy
as the dialog's copy prop to translate its method tabs, country label and payment
status/fallback messages. Existing callers keep the English defaults. Stripe-owned
fields and provider errors use the stripeLocale option on both checkout-session
hooks; wallet surfaces accept it through their checkout input. Stripe clients are
cached by publishable key and locale so changing language cannot reuse another
language's client. Locale does not change a plan, currency or billing interval.
For Solidgate, pass language: 'es' to prepareSolidgateCheckout, or inside
SolidgateCheckoutDialog.request, to use Spanish for the provider form:
const checkout = await prepareSolidgateCheckout({ ...checkoutRequest, language: 'es' });Use a supported Solidgate language tag.
Map regional funnel locales explicitly (for example, es-ES to es); the API rejects
unsupported tags. Omitted/null language preserves browser selection. The dialog
captures language when preparing the attempt; close and reopen it to adopt a change.
Funnel-owned dialog text still comes from content and presentation.
See the checkout language contract.
ManageSubscriptionContent exported by this package extends the runtime content
with optional labels: ManageSubscriptionLabels. A localized funnel should make
labels required in its own content type and provide the complete English and
translated objects. The labels own section/status text, date locale and interval
templates ({count}), while subscription data and cancellation behavior remain
unchanged. Set errorMessagePolicy: 'content' to render load/cancel failures from
the content's errorMessages. The default 'server' policy preserves existing
error rendering independently of the selected labels.
Checkout email prompt
When the access email is missing or invalid, wallet surfaces render nothing.
The funnel's primary payment CTA (such as Get My Plan) opens CheckoutEmailDialog
and saves the email through the existing caller-owned identity update. Once the
caller adopts the saved email, wallet controls can mount. Provider email rejections
still open the surface's repair dialog; saving never confirms the old session.
For a wallet-first subscription flow, set walletFirst on each
StripeSubscriptionWalletSurface with the device payment method and an
onPayerEmail callback that saves the wallet email on the current Funnel User.
The wallet sheet opens before a Checkout Session exists; the shared surface
prepares and confirms the session after the email is saved. Render one surface
per visible placement and a separate card session for fallback. A Stripe
publishable key must be available before the wallet opens; otherwise the surface
reports the wallet unavailable so the caller can show card checkout.
Set walletFirst.buttonLabel for a single funnel-styled trial CTA; without it,
wallet-first mode renders the existing branded Apple Pay or Google Pay button.
The regular surface without walletFirst keeps its existing separate wallet
choices and card entry.
CheckoutEmailDialog defaults to a light surface regardless of the browser or
ancestor theme. It inherits the funnel font. Set inherited --checkout-email-*
CSS variables on the funnel root or .checkout-email-dialog to customize it:
background, foreground, muted, border, input-background,
button-background, button-foreground, focus, and error.
For example, --checkout-email-button-background: var(--color-primary) uses the
funnel accent. Set foreground/background pairs together for custom dark surfaces.
Existing dialog.checkout-email-dialog CSS overrides continue to work.
Influencers Store creator deals
A buyer who opens a funnel from an Influencers Store creator page arrives with
?is_ref=<referral id>. useCreatorDeal({ apiBaseUrl, funnelId }) reads that referral
(remembered for 30 days, so later steps keep it) and loads the deal from
GET /sdk/public/funnels/:funnelId/creator-deal. Show it with CreatorDealBanner above the
plan, and pass deal.couponId and deal.discountPercent to buildDiscountedPaywallPlans and
deal.couponId as the checkout couponId, so the plan, the checkout summary and the charge
agree:
const { deal } = useCreatorDeal(checkoutRuntimeConfig);
const display = buildDiscountedPaywallPlans({ plans, couponId: deal?.couponId ?? null, discountPercent: deal?.discountPercent ?? 0 })[0];
{deal ? <CreatorDealBanner deal={deal} price={{ original: display.oldPriceLabel, discounted: display.priceLabel }} /> : null}The API applies the same coupon on its own when a referred buyer checks out without one, so a funnel that never shows the banner still charges the deal.
For buyers who heard about the app from a creator without a link, add CreatorCodeField near the
plans. A working code opens a referral, remembers it like an is_ref visit and calls onApplied
with the deal (pass it to applyDeal from useCreatorDeal). Checkout metadata carries the
remembered referral as is_ref automatically.
Advanced Wallet Primitives
ApplePaySubscriptionCheckoutSlot, GooglePaySubscriptionCheckoutSlot, and WalletSubscriptionCheckoutSlot stay exported and runtime-compatible. They are backward-compatible advanced low-level primitives: reach for them only when a placement needs wiring the shared wallet surfaces do not cover. Never share one checkout hook result across placements; give each visible placement its own session.
Compatibility-Only Surfaces
Keep these exports available for saved drafts, old published artifacts, and controlled migrations. Do not use them for new subscription checkout work:
SharedStripeCheckoutDialogApplePaySubscribeButtonGooglePaySubscribeButtonAPPLE_PAY_QR_CODE_URL
When a live funnel still uses one of these, migrate the funnel deliberately with its own tests before removing the export.
Use This Package For
- billing catalog types and normalization helpers
- runtime-mode-aware plan catalog selection
- Stripe SDK and public payment API client helpers
- subscription checkout-session preparation, reuse, update, and recovery
- reusable plan-selector UI
- shared embedded checkout dialogs
- Stripe Express Checkout wallet slots and lower-level wallet primitives
- generic timed-offer display helpers
- checkout completion analytics handoff to
@funnelsgrove/analytics
Do Not Use This Package For
- funnel routing
- manifest validation
- funnel-owned billing catalog entries
- funnel-specific paywall layout or copy
- funnel-specific decisions about when to activate, upgrade, or recover an offer
- analytics transport internals
- direct provider SDK calls inside funnel paywall steps; add provider adapters here first, then wire the funnel to the shared session or slot
Public Surfaces
config/billing.config: billing catalog, mapping, plan, and discount contracts.services/publishedBillingRuntime.service: resolves one published runtime artifact into component-ready plans, defaults, upsells, downsells, discounts, and flow experiments.services/planCatalog.service: plan resolution and selection helpers.services/runtimeBillingPlanCatalog.service: test/live runtime catalog selection.services/paywallOffer.service: timed discount and display-plan helpers.providers/paymentProvider.types: provider-neutral checkout state shared by every adapter.providers/stripe/services/*: Stripe loader, Checkout Session, hosted checkout, one-click, analytics, and one-click completion.providers/stripe/hooks/*: Stripe-backed plan resolution and isolated card/wallet checkout-session state.providers/stripe/components/*: plan selector, checkout dialogs, Express Checkout wrappers, wallet slots, placeholders, and trust assets.providers/stripe/testing/*: Stripe wallet checkout smoke assertions.providers/solidgate/services/*: strict Solidgate checkout preparation, status, and bounded polling clients.providers/solidgate/components/*: the official-SDK checkout dialog and canonical verification lifecycle.components/ManageSubscriptionScreen: provider-neutral subscription management UI.
Funnels should call resolvePublishedBillingRuntime once at their runtime-provider boundary. Screens consume its resolved view and should not parse offer sets or pricing-experiment variants themselves. Pass the resolved stripePublishableKey into shared Stripe checkout hooks so Stripe.js can load while the Checkout Session request is still in flight; the key returned by that request remains the compatibility fallback.
The resolved provider is 'stripe' | 'solidgate' | 'paypal' | 'paddle'; 'paddle' was added in payments 0.75.0 with runtime 0.47.0. Type funnel props that receive it as ResolvedPublishedBillingRuntime['provider'] instead of a literal union, so a new provider does not break the funnel build.
Client implementation structure
Provider-neutral plan types, selection and recurrence live in
services/paywallPlans/, exposed through paywallPlans.service.ts.
publishedBillingRuntime and timed-offer helpers must not import a provider
service just to resolve or display plans. Shared config/services are checked for
provider dependencies in paymentBoundaries.test.ts.
Stripe browser operations live in providers/stripe/services/checkout/,
hostedCheckout/ and oneClick/.
Keep request mappers (requests.ts) beside the short async operation functions;
common validation and metadata normalization belong in the local shared/ folder.
stripeClient.ts owns the Stripe.js cache. One-click orchestration calls the
charge and confirmation functions in its own folder, without a workflow layer.
stripe.service.ts is the public export facade. From 0.12.0, all payment
transport uses V2. createStripePaymentIntent is removed: migrate to
createStripeOneTimeCheckout and its Checkout Session UI. Keep legacy published
bundles on their pinned releases until their own migration passes checkout QA.
Hosted checkout uses createStripeCheckoutSession with published profile,
provider and plan selection plus successUrl and cancelUrl. Deploy hosted V2
support before releasing this SDK. Subscription mutation callers forward the
listed subscriptionRef; no provider ownership is reconstructed in the browser.
HTTP transport belongs to the runtime SDK. No charge retry, V1 fallback or extra
conversion event is introduced.
Engineering Rules
- Keep every provider-specific component, hook, service, and test helper under
src/providers/<provider>. Add future providers as sibling folders; do not place provider SDK imports in rootcomponents,hooks, orservices. - Stripe owns real card fields and wallet controls. Local wallet buttons are placeholders until Stripe confirms availability.
- Keep
planIdas the funnel plan key and send Stripe's price id only asproviderPlanId; the API uses both fields to resolve the active test/live offer mapping. - Wallet unavailable state must fall back to card/manual checkout or disappear.
- Count
checkout_startedonly at shared UI boundaries: when a shared card dialog opens or when Stripe reports Apple Pay / Google Pay intent. Checkout Sessions use confirmation or cancellation as a fallback because Stripe omits their click callback. Cancellation recovers the start withcheckout_start_source: wallet_cancel; its timestamp is dismissal time, not wallet-open time. Closing the browser before either callback is still unobservable. Cancel has no payment-method field, so the method is included only when the element enables exactly one method. - Pass
checkoutAnalyticsto every current shared dialog and wallet surface. The package then ownscheckout_started,add_payment_info, and verifiedcheckout_completed, all deduplicated by the actual Checkout Session. - The package also owns
checkout_shown: a checkout form or payment button became visible. It is sent once per show with a new event ID andcheckout_surface:inline(wallet-first form, or the V2 dialog withpresentation='inline'),dialog(each V2 dialog open) orwallet(a standalone wallet surface, once per mount after Stripe reports a wallet available). It is not a conversion and is not sent to Meta or Google. - Payment submission triggers, validation, declines, and retry identity follow AE-BR-001–004. Keep that behavior inside shared checkout surfaces.
- Call funnel lifecycle
completeSteponly from the shared checkoutonSuccesscallback. Payment-info submission is not step completion. - Wallet slots may create render-only Checkout Sessions on mount so Apple Pay and Google Pay render before the visitor taps. Session creation is technical preparation and must never emit
checkout_started. - Shared checkout analytics deduplicates
checkout_startedby Checkout Session id. Wallet confirmation and cancellation may retry the start signal when the click callback is unavailable, without creating a duplicate. Cancellation never emits payment-info or purchase completion events. - Do not call
publicAnalyticsSdk.trackCheckoutShown,trackCheckoutStarted,trackPaymentInfoSubmitted, ortrackCheckoutCompleteddirectly from funnel checkout components. - Funnel paywalls should style wallet buttons through the shared slot API:
classNamefor the Stripe button/placeholder,slotClassNamefor the outer slot,appearancefor Stripe Elements appearance, andoptionsfor Stripe Express Checkout options. - Keep discount math reusable here, but keep offer activation timing in funnel code.
SharedStripeCheckoutV2Dialogforwards wallet-sheet cancellation toonCloseby default;onWalletCancelmay override that callback. Standalone wallet surfaces call theironCancelcallback. Funnel code chooses whether either callback opens a discount offer.- Checkout metadata must avoid sensitive raw query params and use
@funnelsgrove/analyticsmetadata helpers.
Build, Test, Publish
npm run test:run --workspace @funnelsgrove/payments
npm run build --workspace @funnelsgrove/payments
npm publish --workspace @funnelsgrove/payments --access publicThe build normalizes generated relative ESM imports to explicit .js files for published package consumers.
Checkout email repair
Checkout email recovery
owns the behavior. Pass onCustomerEmailCommit to wallet surfaces and the card
checkout dialog. It must save the access email, adopt the returned Funnel User, and
update the customerEmail and userId inputs used by checkout. Missing or invalid
email hides the wallet surface; the funnel's primary CTA collects it. Provider rejection can open the surface's repair dialog.
onResolveCustomerEmail can resolve a known identity before asking for input;
its caller must also adopt the resolved identity. emailDialogContent customizes
prompt copy. Keep beforeConfirm for immediate preparation only, without awaiting
human input or changing the access identity.
CheckoutEmailDialog is also exported for funnel-owned checkout entry controls,
including legacy wallet launchers. Mount it before wallet launch, persist through
onSave, and close through onClose; its completion never launches a wallet.
isValidCheckoutEmail and isCheckoutEmailError share validation and recovery
classification. onCustomerEmailChange in the card dialog reports a committed
email, not each draft keystroke, so typing cannot prepare sessions for unsaved input.
Offer price money
Published plans expose optional money: ProviderMoney; new mappings supply it. Discount presentation and purchase analytics use its amount, currency and exponent. amountCents remains a legacy wire alias and does not define the scale of structured money. Independent plans can use different currencies. Currency is selected by the provider price, not by an Offer Set setting.
Published offer selection and checkout attempts
Use resolvePublishedBillingRuntimeState with configuration, browser locale and experiment assignments that are ready. Its result is pending, resolved or error. Pending/error states must not prepare Stripe card/wallet or Solidgate checkout; the maintained templates render an inert zero-plan state rather than a starter catalog.
usePinnedPublishedBillingRuntime holds the complete resolved catalog at the first payment preparation. Wire its pin callback to preparation and release both the payment session and this snapshot on explicit reset. Displayed prices, provider, revision, source version, locale and experiment assignment then remain consistent through background updates. The visitor can still choose another plan within the pinned offer set. A new attempt after reset can adopt the latest configuration.
