Skip to main content

Payment Provider Hooks

Hooks for integrating with payment providers (Stripe, LemonSqueezy, Polar), managing checkout flows, setup intents, and provider selection.

useSelectedCheckoutProvider

Accesses the user's selected checkout provider from the LayoutThemeContext. Provides helpers for checking provider availability and fallback logic.

useSelectedCheckoutProvider(): UseSelectedCheckoutProviderReturn

Return Values

PropertyTypeDescription
checkoutProviderCheckoutProviderCurrently selected provider
setCheckoutProvider(provider) => voidUpdate the selected provider
configuredProvidersCheckoutProvider[]All providers with valid credentials
getActiveProvider() => CheckoutProvider | nullSelected if configured, else first available
isProviderConfigured(provider) => booleanCheck if a specific provider is configured
isCurrentProviderConfigured() => booleanCheck if the selection is valid
getFallbackProvider() => CheckoutProvider | nullFirst configured provider
import { useSelectedCheckoutProvider } from '@/hooks/use-selected-checkout-provider';

function CheckoutFlow() {
const { getActiveProvider } = useSelectedCheckoutProvider();
const provider = getActiveProvider();

switch (provider) {
case 'stripe': return <StripeCheckout />;
case 'lemonsqueezy': return <LemonSqueezyCheckout />;
case 'polar': return <PolarCheckout />;
default: return <p>No payment provider configured</p>;
}
}

useStripeProducts

Fetches products from the Stripe API when dynamic pricing is enabled. Caches products with React Query.

useStripeProducts(options?: UseStripeProductsOptions): UseQueryResult<StripeProductsApiResponse>

Options

OptionTypeDefaultDescription
enabledbooleanNEXT_PUBLIC_STRIPE_DYNAMIC_PRICING === 'true'Whether to fetch products
staleTimenumber300000 (5min)Cache stale time in ms

Response Data

FieldTypeDescription
productsStripeProduct[]Fetched Stripe products
sponsorAdsobjectSponsor ad pricing (weekly/monthly)
stripeConfigRecord<plan, PlanConfig>Multi-currency price IDs per plan
useDynamicPricingStatus(): {
isDynamicPricingActive: boolean;
hasProducts: boolean;
hasSponsorPricing: boolean;
hasStripeConfig: boolean;
}
const { data, isLoading } = useStripeProducts();

if (data?.products) {
// Render dynamic product cards
}

useSetupIntent

Manages Stripe SetupIntent creation and caching for saving payment methods. Provides comprehensive error handling, retry logic, and cache management.

useSetupIntent(options?: UseSetupIntentOptions): UseSetupIntentReturn

Options

OptionTypeDefaultDescription
enabledbooleantrueWhether to create a SetupIntent
paramsCreateSetupIntentParams--Parameters for intent creation
onSuccess(data) => void--Success callback
onError(error) => void--Error callback
suppressSuccessToastbooleanfalseSkip the success toast

Return Values

PropertyTypeDescription
setupIntentSetupIntentResponse | undefinedThe created SetupIntent
clientSecretstring | undefinedClient secret for Stripe Elements
isReadybooleantrue when intent is ready for payment method
isLoading / isFetchingbooleanLoading states
refetch() => voidRe-create the SetupIntent
invalidateCache() => voidInvalidate cached intents
clearCache() => voidRemove all cached intents
prefetch(params?) => Promise<void>Pre-create an intent
HookPurpose
useCreateSetupIntentMutation hook for creating new SetupIntents
useGetSetupIntentFetch an existing SetupIntent by ID
useSetupIntentCacheCache management utilities
useSetupIntentManagerCombined query + mutation + cache hook
useCreateSetupIntentWithCustomParamsCreate intent with customer name
const { clientSecret, isReady } = useSetupIntent({
suppressSuccessToast: true,
});

if (isReady && clientSecret) {
return <Elements stripe={stripePromise} options={{ clientSecret }}>
<PaymentForm />
</Elements>;
}

useCheckoutButton

Encapsulates LemonSqueezy checkout button logic, supporting both redirect and embedded checkout modes.

useCheckoutButton(params?: CheckoutButtonParams): UseCheckoutButtonReturn

Parameters

ParamTypeDefaultDescription
defaultEmailstring''Pre-filled customer email
defaultPricenumber--Default price amount
variantIdnumber--LemonSqueezy variant ID
metadataRecord<string, any>{}Custom metadata for the checkout
embeddedbooleanfalseUse embedded checkout instead of redirect
onPaymentSuccess(res?) => void--Success callback (embedded mode)
onClose() => void--Close callback (embedded mode)
darkboolean--Dark mode for checkout UI

Return Values

PropertyTypeDescription
customPricenumber | undefinedCurrent custom price
isLoadingbooleanCheckout creation in progress
isErrorbooleanWhether an error occurred
checkoutUrlstring | nullEmbedded checkout URL
isEmbedReadybooleanWhether embedded checkout is loaded
handleClick() => Promise<void>Simple button click handler
handleSubmit(e: FormEvent) => Promise<void>Form submission handler
handlePriceChange(e: ChangeEvent) => voidPrice input handler
clearCheckout() => voidClear embedded checkout
const { handleClick, isLoading } = useCheckoutButton({
variantId: 12345,
metadata: { plan: 'premium' },
});

return (
<button onClick={handleClick} disabled={isLoading}>
{isLoading ? 'Processing...' : 'Buy Now'}
</button>
);

useProviderPayment

Aggregates payment data from the configured provider (Stripe or LemonSqueezy). Combines billing data, checkouts, subscriptions, and statistics into a unified interface.

useProviderPayment(): UseProviderPaymentReturn

Return Values

PropertyTypeDescription
providerPaymentProviderActive payment provider
paymentsPayment[]Provider-specific payment history
stripePaymentsPayment[]Stripe-only payments
lemonSqueezyPaymentsPayment[]LemonSqueezy-only payments
totalSpentnumberSum of all payment amounts
activePaymentsnumberCount of paid/active payments
monthlyAveragenumberAverage payment amount
subscriptionSubscriptionCurrent subscription data
loadingbooleanCombined loading state
refresh() => voidRefresh all payment data
hasPaymentHistorybooleanWhether any payments exist
hasSubscriptionHistorybooleanWhether subscription history exists

LemonSqueezy Hooks

useLemonSqueezyCheckouts

Fetches and manages LemonSqueezy checkout records with filtering and pagination.

PropertyDescription
checkoutsArray of CheckoutData records
paginationPage info (total, page, limit, hasMore)
updateFiltersUpdate status/email/date filters
refreshRefresh checkout data

useSubscriptionActions

Mutation hooks for LemonSqueezy subscription management:

ActionDescription
updatePlanChange subscription plan/variant
cancelSubscriptionCancel with optional period-end flag
pauseSubscriptionPause with mode (void or free)
resumeSubscriptionResume a paused subscription
reactivateSubscriptionReactivate a cancelled subscription

useUpdateSubscription

Updates a LemonSqueezy subscription (plan changes, billing updates).


Polar Hooks

usePolarCheckout

Creates Polar checkout sessions with support for redirect and embedded modes.

ParamTypeDescription
embeddedbooleanUse embedded checkout
onSuccess(data) => voidSuccess callback

usePolarSubscription

Manages Polar subscription lifecycle (cancel, reactivate) with query cache invalidation.


Summary Table

HookProviderPurposeSource File
useSelectedCheckoutProviderAllProvider selection and fallbackuse-selected-checkout-provider.ts
useStripeProductsStripeFetch dynamic productsuse-stripe-products.ts
useSetupIntentStripeManage SetupIntentsuse-setup-intent.ts
useCheckoutButtonLemonSqueezyCheckout button logicuse-checkout-button.ts
useProviderPaymentAllUnified payment datause-provider-payment.ts
useLemonSqueezyCheckoutsLemonSqueezyCheckout recordsuse-lemonsqueezy-checkouts.ts
useSubscriptionActionsLemonSqueezySubscription CRUDuse-lemonsqueezy-subscription.ts
useUpdateSubscriptionLemonSqueezySubscription updatesuse-lemonsqueezy-update.ts
usePolarCheckoutPolarCheckout sessionsuse-polar-checkout.ts
usePolarSubscriptionPolarSubscription managementuse-polar-subscription.ts