Expo SDK reference

On this page

@tenthbilling/expo sells subscriptions, one-time purchases and credits in Expo apps. It buys through StoreKit 2 on iOS, Play Billing on Android and Stripe on the web, and Tenth's server verifies every purchase. New to Tenth? Start with the quickstart.

Install

Terminal
npx expo install @tenthbilling/expo expo-secure-store expo-crypto expo-constants expo-web-browser lucide-react-native react-native-svg

lucide-react-native and react-native-svg draw the default paywall's icons. To sell with Stripe PaymentSheet inside a native app, also install @stripe/stripe-react-native (see Stripe in native apps). Apps that don't sell that way don't need it.

Purchases need a development build, because the SDK includes native code. Build it with EAS (eas build --profile development) or locally (npx expo run:ios, npx expo run:android). In Expo Go it runs in preview mode.

Supported versions

DependencySupported
Expo SDK58 or later
React Native0.88 or later
React19.3 or later
iOS16.4 or later (StoreKit 2)
AndroidGoogle Play Billing Library 8
ArchitectureThe New Architecture and the old one
Web bundlerMetro, as Expo uses it (see Storage on the web)

These are the versions Tenth builds and tests against. Older Expo SDKs aren't supported.

Keys

Use one publishable key for every platform of an app environment. iOS, Android and web all share it; there are no per-platform keys. Use the test key in development builds and the live key in release builds.

Config plugin

Add the plugin to app.json (or app.config.js):

JSON
{
  "expo": {
    "scheme": "myapp",
    "plugins": [
      [
        "@tenthbilling/expo",
        { "googlePlayBilling": true, "storeKitConfig": "store/Tenth.storekit" }
      ]
    ]
  }
}

OptionTypeDefaultWhat it does
googlePlayBillingbooleantrueAdds the com.android.vending.BILLING permission. With false, the permission is removed from the merged manifest and Play purchases can't be made.
storeKitConfigstringnoneA .storekit file, relative to the project root, for StoreKit testing in Xcode. It's copied into the iOS project but never shipped in the app. Pick it in the scheme's Run → Options → StoreKit Configuration.

Unknown options and wrong types fail the prebuild with an error. iOS needs nothing else: StoreKit needs no entitlement or Info.plist key.

These are the only changes the plugin makes to the native projects, so you can review it without running a prebuild:

  • Android: in AndroidManifest.xml, it adds <uses-permission android:name="com.android.vending.BILLING" />. With googlePlayBilling: false, it adds the same permission with tools:node="remove" (and the tools namespace), so libraries can't bring it back in the merged manifest.
  • iOS: only when storeKitConfig is set, it copies the .storekit file into ios/<project name>/ and adds a file reference to the Xcode project. It isn't added to any build phase, so it never ships.
  • It doesn't change the Podfile, entitlements, Info.plist or Gradle files. The native module itself is linked by Expo's autolinking, like any Expo module.

storeKitConfig is for UI work only. Tenth's server refuses transactions from Xcode's StoreKit testing environment, so they never grant access. Use Apple Sandbox for real test purchases.

Set expo.scheme if any offering sends buyers to hosted Checkout or uses PaymentSheet; the SDK uses it to bring the customer back to the app.

TenthProvider

Wrap your app once, near the root. Every hook and component needs it.

TSX
import { TenthProvider } from '@tenthbilling/expo';

<TenthProvider apiKey="tenth_test_pk_..." getCustomerToken={getToken} userId={user?.id}>
  <App />
</TenthProvider>;

PropTypeDefaultDescription
apiKeystringrequiredYour publishable key (tenth_test_pk_... or tenth_live_pk_...). A secret key throws InvalidKeyError.
getCustomerToken() => Promise<string | null | undefined>noneReturns the signed-in user's token: Clerk's getToken, your OIDC provider's, or one your server minted. Return null when signed out.
userIdstring | nullnoneYour auth library's user ID. When it changes (sign-in, sign-out, switching accounts), the SDK refreshes right away instead of on the next launch or foreground.
apiUrlstringhttps://api.tenthbilling.comThe API origin. Must be https (plain http is allowed only for localhost and 127.0.0.1).
offlineGraceHoursnumber72How long cached access lasts without reaching Tenth. See Offline cache.
previewbooleanautomaticForces preview mode on or off. By default it's on for iOS and Android builds without the native store module, and off on web.
localestringthe device'sLocale for prices and paywall copy, such as en-US.
urlSchemestringexpo.schemeURL scheme for returning from hosted Checkout and bank redirects.
merchantDisplayNamestringthe app's name (expo.name)The name shown on Stripe's PaymentSheet.

The SDK calls getCustomerToken before each request and never stores the token. If it throws, the SDK treats the user as signed out. You can pass a new function on every render; the SDK always calls the latest one.

Changing apiKey, apiUrl, preview or offlineGraceHours creates a new SDK instance. The other options are read when the instance is created.

Signed-in and anonymous customers

Before sign-in, the SDK uses an anonymous customer: an ID it generates once per install and keeps in secure storage. On the first call with a token, it merges the anonymous customer into the signed-in one, so purchases made before sign-in follow the user. After that, the anonymous ID is forgotten, and a later signed-out session starts as a new anonymous customer.

The signed-in customer's app_user_id is the user ID claim of the token (sub by default), and it never changes; the anonymous ID becomes an alias of it. Customer identity covers how tokens are verified, and how to bill a team or workspace instead of a person.

When the identity changes, the SDK clears the state on screen before the new state arrives. One user's cached access is never shown to another.

Hooks

useEntitlement

TSX
const pro = useEntitlement('pro');
if (pro.loading) return null;
if (!pro.active) return <Paywall />;

Returns EntitlementInfo:

FieldTypeDescription
activebooleanThe customer has access now.
loadingbooleanTrue until the first state (cached or fresh) is available.
entitlementEntitlementState | nullDetails, or null when the customer never had this entitlement.

EntitlementState has these fields:

FieldTypeDescription
activebooleanAccess now.
source'purchase' | 'subscription' | 'grant' | nullWhat gives the access.
store'stripe' | 'apple' | 'google' | nullWhere the customer manages it.
expires_atstring | nullISO 8601 timestamp, or null for no expiry.
will_renewbooleanThe subscription renews at the end of the period.
in_gracebooleanA payment failed and the customer is in a grace period.
billing_issuebooleanThe last payment failed.
quantitynumber | nullFor quantity entitlements.

useCustomer

TSX
const { customer, loading, fromCache, error, refresh } = useCustomer();

FieldTypeDescription
customerCustomerState | nullThe customer's state (see below).
loadingbooleanTrue until the first state (cached or fresh) is available.
fromCachebooleanThe state is from the device cache, and a refresh is on its way.
errorTenthSdkError | nullThe last refresh's error, if it failed.
refresh() => Promise<void>Fetches the latest state now, for example from a "Refresh" button.

CustomerState has:

  • customer: { id, app_user_id, app_account_token, obfuscated_account_id, created_at }
  • entitlements: a record of EntitlementState by entitlement key
  • credits: a record of { balance, available } by credit type
  • subscriptions: an array of SubscriptionSummary: { id, product, store, status, current_period_start, current_period_end, trial_end, grace_period_end, cancel_at, will_renew, provisional }

useCredits

TSX
const credits = useCredits('ai_credits');
<Text>{credits.available} credits left</Text>;

FieldTypeDescription
balancenumberTotal balance. 0 when the customer has none.
availablenumberBalance minus credits held by open reservations.
loadingbooleanTrue until the first state is available.
debitfunctionSpends credits from the app (see below).

debit(amount, { idempotencyKey, metadata? }) spends credits from the device and then refreshes. It only works when the credit type allows spending from the app; otherwise Tenth refuses it. Pass the same idempotencyKey when retrying one spend, so it never debits twice. metadata is a record of string, number, boolean or null values: at most 20 keys, and strings up to 500 characters. It's stored with the transaction and sent in the credits.debited webhook.

For anything that costs you money, spend from your server with tenth.credits.debit instead. A modified app can skip a debit it's supposed to make.

useOffering

TSX
const { offering, products, paywall, path, loading, error, reload } = useOffering('black_friday');

Pass an offering key, or nothing for the current offering (the one Tenth targets at this customer, platform, country and app version). With no targeting rule matching, the current offering is the one marked as the default in the dashboard.

Offering keys are yours to choose. No key is special: useOffering('default') looks for an offering whose key is literally default, and fails with not_found if there isn't one. The only reserved key is current, which the dashboard doesn't accept.

FieldTypeDescription
offeringOffering | nullThe offering as configured in the dashboard.
productsPaywallProduct[]The products the customer can buy on this device, with store or Stripe prices.
paywallServedPaywall | nullThe published paywall config, or null (the SDK then uses its bundled default).
path'store' | 'web_link_out' | 'in_app_stripe' | 'none' | nullHow this offering sells on this platform.
loadingbooleanTrue while loading.
errorTenthSdkError | nullWhy loading failed.
reload() => voidLoads the offering again, skipping the SDK's cache.

The SDK keeps each loaded offering for 5 minutes. products leaves out anything that can't be sold here: products the store didn't return, Stripe products whose price Tenth couldn't read, and products on a Stripe path the app isn't set up for (see Web and Stripe).

useTenth and useTenthSnapshot

useTenth() returns the SDK instance from the nearest TenthProvider, for calls the hooks don't cover:

MemberDescription
refresh()Fetches the customer's state. Resolves with the CustomerState, or null if it failed. Concurrent calls share one request.
purchase(productKey, options?)Buys a product. Resolves with a PurchaseResult and never throws. Options below.
restore()Restores purchases. Resolves with a RestoreResult and never throws.
manageSubscription(subscriptionId?)Opens where the customer manages a subscription. Without an ID, it picks the subscription that renews. See Managing a subscription.
getOffering(key?, { force? })Loads an offering, as useOffering does.
debitCredits(creditType, amount, { idempotencyKey, metadata? })Spends credits from the app, as useCredits().debit does. Throws a TenthSdkError on failure.
subscribe(listener)Calls listener() (with no arguments) every time the state changes. Returns a function that unsubscribes. Read the new state with getSnapshot().
getSnapshot()The current TenthSnapshot (see below).
environment'test' or 'live', from the key.
previewWhether preview mode is on.
localeThe locale in use.

purchase options:

OptionDescription
offeringThe offering key to load the product from. Default: the current offering.
appleOfferIdAn App Store promotional offer ID. Tenth signs the offer on its server.
googleOfferIdA Google Play offer ID of the product's base plan, to buy that offer instead of the one the SDK would pick (see Google Play offers). An offer that Play didn't return for this customer fails with product_unavailable.

useTenthSnapshot() returns the raw state the other hooks read: { status, customer, fromCache, confirmedAt, error, preview, environment }. status is 'loading', 'ready' or 'error', and confirmedAt is when Tenth last confirmed the state, in milliseconds since the epoch.

Listening for changes

Hooks re-render on every change, so most apps need nothing else. Outside React (an analytics module, say), subscribe to the instance from useTenth(). This is the counterpart of RevenueCat's addCustomerInfoUpdateListener:

TSX
const tenth = useTenth();
useEffect(
  () =>
    tenth.subscribe(() => {
      const { customer } = tenth.getSnapshot();
      analytics.setPro(customer?.entitlements.pro?.active ?? false);
    }),
  [tenth],
);

Paywall

<Paywall /> renders the offering's published paywall: its template, copy, colors and image come from the dashboard, and its prices come from the store or Stripe.

TSX
<Paywall
  offering="black_friday"
  presentation="sheet"
  onPurchased={(product) => track('purchased', product.key)}
  onDismiss={() => setShowPaywall(false)}
/>

PropTypeDefaultDescription
offeringstringcurrent offeringThe offering key.
presentation'inline' | 'sheet' | 'modal''inline'inline renders in place. sheet slides up from the bottom on phones (a centered card on web). modal covers the screen.
slotsPaywallSlotsnoneYour own components for regions of the paywall. See Slots.
themePaywallThemeOverridesnoneTheme overrides that win over the dashboard's. See Theming.
localestringthe provider'sLocale for copy and prices.
onPurchased(product: PaywallProduct) => voidnoneCalled after a completed purchase.
onRestored() => voidnoneCalled after a restore that found purchases.
onDismiss() => voidnoneCalled when the customer closes the paywall.

The paywall handles its own loading, empty and error states, and shows notices for pending purchases, failed purchases and restores. Sheet and modal paywalls always have a close button. Inline paywalls show one only when you pass onDismiss and the dashboard config doesn't hide it. When the customer closes a sheet or modal, it hides itself and calls onDismiss.

If no paywall is published for the offering (or for the app as a default), the SDK uses a bundled default: the credits template when every product is a credit pack, hero for a single product, and tiers otherwise. If a published config can't be parsed by this SDK version, it also falls back to the default, so a remote change can never crash an app.

Gate

<Gate> shows its children only with an entitlement.

TSX
<Gate entitlement="pro" fallback={<Paywall />} loading={<Spinner />}>
  <ProScreen />
</Gate>

PropTypeDefaultDescription
entitlementstringrequiredThe entitlement key, such as pro.
fallbackReactNoderequiredShown without access. Usually <Paywall />.
loadingReactNodenothingShown before the first state (cached or fresh) is known.
childrenReactNoderequiredShown with access.

presentPaywall and presentPaywallIfNeeded

Show the paywall over the app from anywhere, such as an event handler:

TSX
import { presentPaywall, presentPaywallIfNeeded } from '@tenthbilling/expo';

const result = await presentPaywall({ offering: 'black_friday', presentation: 'sheet' });

const outcome = await presentPaywallIfNeeded({ entitlement: 'pro' });
if (outcome === 'purchased' || outcome === 'restored' || outcome === 'not_presented') {
  startExport();
}

Options (PresentPaywallOptions):

OptionTypeDefault
offeringstringcurrent offering
presentation'modal' | 'sheet''modal'
entitlementstringrequired, presentPaywallIfNeeded only

Both resolve with a PaywallResult when the paywall closes:

ResultMeaning
'purchased'The customer bought something.
'restored'A restore found purchases.
'cancelled'The customer closed the paywall, or a newer presentPaywall call replaced it.
'not_presented'presentPaywallIfNeeded only: the customer already has the entitlement.

presentPaywallIfNeeded checks the latest state first. If the SDK has no state yet or is still showing the device cache, it refreshes before deciding. Both functions need a mounted TenthProvider; called without one, they throw.

Slots

Slots replace one region of the paywall and keep the rest. Each slot is a React component.

TSX
import { Paywall, type PaywallSlots } from '@tenthbilling/expo';

const slots: PaywallSlots = {
  productCard: ({ product, selected, select }) => (
    <Pressable
      onPress={select}
      accessibilityRole="radio"
      accessibilityState={{ checked: selected }}
    >
      <Text>{product.name}</Text>
      <Text>{product.price.formatted}</Text>
    </Pressable>
  ),
};

<Paywall slots={slots} />;

SlotPropsReplaces
header{ title, subtitle, heroImageUrl }The hero image, title and subtitle.
productCard{ product, selected, select }Each product row.
featureList{ features }: an array of { text, icon? }The feature rows.
footer{ restore, restoring, termsUrl, privacyUrl }Restore purchases and the legal links.
closeButton{ close }The close button.

Notes:

  • productCard sits inside the paywall's radio group, so give it accessibilityRole="radio" and accessibilityState={{ checked: selected }}.
  • footer's restore is null when the dashboard config hides Restore purchases. termsUrl and privacyUrl are already checked to be https.
  • heroImageUrl is null when the template doesn't show an image.

The SDK also exports the paywall's own PaywallOption component (props: product, selected, onSelect, locale, showBadge?), so a custom slot can reuse it, and PaywallView, which renders a paywall from any PaywallController.

Theming

The dashboard sets the paywall's theme. The theme prop overrides it in code, with the same shape:

TSX
<Paywall
  theme={{
    light: { brand: '#0f5257', surface_raised: '#ffffff' },
    dark: { brand: '#5cbcb6' },
    display_font: 'FamiljenGrotesk_600SemiBold',
    color_scheme: 'system',
  }}
/>

FieldDescription
light, darkPer color scheme: brand, brand_hover and surface_raised, each a 6-digit hex color.
display_fontA font family your app has already loaded (for example with expo-font), used for titles. Letters, digits, spaces, _ and - only.
color_scheme'system' (follow the app, the default), 'light' or 'dark'.

Only these values can change, so prices, Restore purchases and legal links stay readable:

  • The text color on the brand color is picked automatically to reach 4.5:1 contrast.
  • Without brand_hover, the hover color is derived from brand.
  • A surface_raised color that would make text or control borders unreadable is ignored.
  • Invalid values (not a 6-digit hex color, or a font name with other characters) are ignored, never thrown on.

usePaywall: a fully custom paywall

usePaywall() gives you everything <Paywall /> renders from, so you can draw your own.

TSX
import { usePaywall } from '@tenthbilling/expo';

function MyPaywall() {
  const pw = usePaywall({ onPurchased: () => navigation.goBack() }); // the current offering

  if (pw.status === 'loading') return <Spinner />;
  if (pw.status === 'error') return <Text>{pw.error?.message}</Text>;
  if (pw.status === 'empty') return <Text>Nothing to buy right now.</Text>;

  return (
    <View>
      {pw.products.map((p) => (
        <Pressable key={p.key} onPress={() => pw.select(p.key)}>
          <Text>
            {p.name}: {p.price.formatted}
          </Text>
        </Pressable>
      ))}
      {pw.paymentStep}
      <Button title="Continue" disabled={pw.purchasing} onPress={() => pw.purchase()} />
      <Button title="Restore purchases" disabled={pw.restoring} onPress={() => pw.restore()} />
    </View>
  );
}

Options: offering, locale, onPurchased(product), onRestored().

It returns a PaywallController:

FieldDescription
status'loading', 'ready', 'empty' (no products to sell here) or 'error'.
error{ code, message } from loading or the last purchase or restore, or null.
productsPaywallProduct[] (see below).
selectedKeyThe selected product's key. Starts at the offering's highlighted product, else the first.
select(key)Selects a product.
purchase(key?, offer?)Buys the selected product (or key). offer takes { appleOfferId?, googleOfferId? }. Resolves with a PurchaseResult; never throws.
restore()Restores purchases. Resolves with a RestoreResult; never throws.
purchasing, restoringTrue while a purchase or restore is running.
paymentStepOn web, Stripe's payment form while a purchase is running, else null. Render it if you build your own web paywall.
cancelPaymentStep()Leaves the payment step.
config, assetsThe paywall config to render (published or default) and its image URLs.
preview, environment, localePreview mode, 'test' or 'live', and the locale.

A PaywallProduct has:

FieldDescription
keyThe catalog key.
type'subscription', 'non_consumable' or 'consumable'.
nameThe offering's label, else the catalog display name, else the store's name.
badgeThe offering's badge, such as "Best value", or null.
highlightedThe product the paywall selects when it opens.
price{ formatted, amountMicros, currency }. formatted is the store's own string, such as "$59.99". amountMicros is a bigint in millionths of the currency unit.
period{ unit, count } for subscriptions (unit is day, week, month or year), null otherwise.
introThe introductory offer this customer can get, or null: { kind, period, periods, price }, where kind is free_trial, pay_as_you_go or pay_up_front.
creditsCredits granted: { creditType, amount, per }, where per is purchase or period.
entitlementsThe entitlement keys it unlocks.

Two helpers from the paywall are exported for custom paywalls:

  • ctaLabel(product, { override?, locale? }) returns the purchase button's label, such as "Start 7-day free trial" or "Subscribe for $59.99/year".
  • resolveCopy(config.copy, locale) picks the copy for a locale: an exact match, then the bare language, then any locale with that language, then the default locale.

Purchase and restore results

A purchase resolves with one of:

statusMeaning
'purchased'Tenth confirmed the purchase and the customer has access.
'pending'Paid, or waiting on the store (Ask to Buy, a pending Play payment), but access hasn't appeared yet. It's picked up later; the paywall says so.
'cancelled'The customer backed out.
'failed'Comes with error: { code, message }. message is a sentence you can show the customer.

A restore resolves with status 'restored', 'nothing_to_restore' or 'failed' (with error).

How purchases work

  • App Store: the SDK sends each signed transaction to Tenth, which verifies it with Apple. Renewals, Ask to Buy approvals and purchases on other devices are picked up while the app runs. Whether the SDK finishes the transaction depends on Tenth's answer:

    Tenth's answerTransactionPurchase result
    AcceptedFinishedpurchased
    receipt_invalid, receipt_belongs_to_other_customer or validation_failedFinished, so it isn't sent again; retrying can't succeedfailed
    Tenth can't be reached, timed out, rate_limited, store_unavailable or any 5xxNot finishedpending
    Any other error, such as customer_token_invalid or provider_not_connectedNot finishedfailed

    An unfinished transaction is sent again on every launch and whenever StoreKit reports it, so it's picked up once the problem (a connection, a sign-in) is fixed.

  • Google Play: the SDK sends the purchase token to Tenth. Tenth acknowledges and consumes purchases on its server; the device never does. Unacknowledged purchases are sent again on every launch.
  • Changing plans on Google Play: when the device already owns an active Google Play subscription that the new one replaces, the SDK replaces it instead of adding a second subscription. A subscription is replaced when it's another base plan of the same Play subscription, or a product in the loaded offering that unlocks any of the same entitlements. Add-ons that unlock other entitlements are left alone. How it switches depends on the recurring price:

    New planWhat happens
    Costs more (same currency)Switches now and charges the prorated difference.
    Costs less (same currency)Switches at the next renewal.
    Same price, another currency, or not knownSwitches now, and the unused time is credited.

    On the App Store, StoreKit handles this itself for products in the same subscription group.

  • Restore sends the store's current purchases to Tenth and then refreshes, which also picks up web purchases. On iOS it may ask the customer to sign in to the App Store.

Google Play offers

A Google Play product in Tenth's catalog is a subscription ID plus, optionally, a base plan ID and an offer ID. Unless you pass googleOfferId, the SDK picks the offer like this:

  1. Only offers of the product's base plan count, if the catalog product names one.
  2. If the catalog product names an offer, that offer is used. If Play doesn't return it for this customer (they aren't eligible), the product is hidden.
  3. Otherwise, the first free-trial offer the customer is eligible for, then the base plan with no offer, then the first offer.

So a discounted introductory offer (not a free trial) is only used when you name it, in the catalog or with googleOfferId. Play decides which offers a customer is eligible for. Play doesn't check eligibility for developer-determined offers, though, and the choice is made on the device, so treat any offer Play returns as one any customer could buy.

Managing a subscription

manageSubscription() opens where the subscription is billed:

Subscription billed byOn iOS and AndroidOn the web
App StoreThe App Store's subscription settings (on iOS)https://apps.apple.com/account/subscriptions in a new tab
Google PlayPlay's subscription page for the product (on Android)https://play.google.com/store/account/subscriptions for the product
StripeStripe's customer portal in an in-app browserStripe's customer portal in a new tab

A store subscription viewed on the other platform (an App Store subscription on Android, say) opens the same web page as on the web. The customer has to sign in to the store there, and changes made in the store reach Tenth through the store's notifications.

Web and Stripe

Each offering has a purchase path, set in the dashboard. The SDK sells through it like this:

PlatformPathHow the customer pays
WebanyStripe's Payment Element, shown inside the paywall.
iOS and AndroidstoreStoreKit or Play Billing.
iOS and Androidin_app_stripeStripe PaymentSheet. Needs @tenthbilling/expo/payment-sheet.
iOS and Androidweb_link_outStripe's hosted Checkout in the system browser, then back to the app by its URL scheme.
anynoneNothing is sold; the paywall shows its empty state.

Stripe tells Tenth about a payment by webhook, so after a Stripe payment the SDK checks the customer's state every 2 seconds for up to 30 seconds. It resolves purchased once access appears, or pending if it doesn't appear in time. A later foreground refresh picks it up.

Stripe prices come from Tenth, which reads them from your Stripe account. If Tenth can't read a price, that product is hidden.

Selling on the web

  1. Add a web platform to the app in the dashboard.
  2. In Settings → Web, add your site's origin to Web origins, and to Stripe redirect origins so redirect-based payment methods can return to the page.

Card details go from Stripe's form straight to Stripe. If you build your own paywall with usePaywall(), render paymentStep while a purchase runs; that's where the form appears.

Stripe.js loads only when a payment form opens, not when your app starts, so visitors who never open a paywall don't contact Stripe. The form uses system fonts and requests nothing from Google Fonts or any other font host.

Content Security Policy

If your site sends a Content Security Policy, allow:

DirectiveSources
script-srchttps://js.stripe.com
frame-srchttps://js.stripe.com, https://hooks.stripe.com
connect-srchttps://api.tenthbilling.com (or your apiUrl), https://api.stripe.com
img-srchttps://api.tenthbilling.com (or your apiUrl), for paywall images, and https://*.stripe.com

Stripe documents its own requirements in its CSP guide; follow it if it lists more than this table.

Web footprint

Measured on Tenth's example Expo app, a production web export (npx expo export -p web) loads about 2.3 MB of JavaScript at startup, before compression. That includes React, React Native Web and the app itself, not just the SDK. The paywall imports each lucide-react-native icon on its own, so only the icons it draws are bundled.

Loaded later, only when a payment form opens:

  • the SDK's payment step, a separate chunk of about 25 KB;
  • Stripe.js, from https://js.stripe.com.

Storage on the web

The SDK keeps its cache and the anonymous ID in localStorage on the web, and in expo-secure-store (Keychain and Keystore) on iOS and Android. It picks the right one through Metro's platform extensions (.web.ts), so expo-secure-store is never bundled for the web. Install it anyway, because it's a peer dependency. A bundler without platform extensions isn't supported.

Stripe in native apps

For offerings with the in_app_stripe path, install Stripe's React Native SDK and import the entry point once, for example in your root layout:

Terminal
npx expo install @stripe/stripe-react-native

TSX
import '@tenthbilling/expo/payment-sheet';

Without the import, products on that path are hidden, and a purchase fails with payment_sheet_missing. PaymentSheet needs a development build. It's themed to match the paywall, and it shows merchantDisplayName.

For offerings with the web_link_out path, set expo.scheme in app.json (or the urlScheme prop) and set the app's URL scheme in Settings → Web. Without a scheme, products on that path are hidden. If the customer closes the browser without finishing, the SDK checks once more before reporting cancelled, in case they paid first.

Selling digital goods through Stripe inside a native app is subject to Apple's and Google's rules. You decide which path each offering uses, and you're responsible for following the stores' policies.

Preview mode

Preview mode lets you build the paywall and gating before your first native build. It turns on when the native store module isn't in the app (Expo Go, or a build without the config plugin), or when you set preview: true. On web it's off unless you set preview: true.

In preview mode:

  • products show placeholder prices in USD;
  • every purchase is simulated on the device only, whatever the offering's purchase path (store, in_app_stripe or web_link_out) and on web too: nothing is sent to Tenth, a store or Stripe, and the simulated access lasts until the app restarts;
  • the paywall shows a preview notice.

With a live key, simulated purchases are refused with preview_live_key, so a preview build can't pass for a working one.

Offline cache

The SDK caches the last state Tenth confirmed and shows it on launch, before the first refresh. On iOS and Android it's kept in the Keychain or Keystore (through expo-secure-store); on web it's in localStorage (see Storage on the web).

Cached access lasts at most offlineGraceHours (72 by default) after Tenth last confirmed it, and never past the entitlement's own expires_at. State fresh from the server is used as is; the server has already applied grace periods and billing retry.

The SDK refreshes:

  • on launch;
  • when the app returns to the foreground;
  • after every purchase and restore;
  • when userId changes;
  • when you call refresh().

The cache isn't tamper-proof. Use it to show and hide UI, and check anything that must not be bypassed on your server with @tenthbilling/node.

Errors

InvalidKeyError

TenthProvider throws InvalidKeyError when apiKey isn't a publishable key: a secret key, or anything malformed. The message never repeats the key. If you passed a secret key, rotate it in the dashboard.

TenthSdkError

Errors from hooks (useCustomer().error, useOffering().error) and from debit are TenthSdkErrors:

FieldTypeDescription
codestringTenth's stable error code, or one of the SDK's own (below).
messagestringA sentence you can show the customer.
statusnumber | nullHTTP status for API errors; null for errors raised on the device.
requestIdstring | nullThe API's request ID, to quote to support.
retryablebooleanWorth retrying later: network_error, timeout, store_unavailable, rate_limited, or any 5xx.

Purchases and restores never throw. Their failures carry the same code and message in error.

Each request to Tenth has 15 seconds to complete, including reading the response. The SDK doesn't retry a failed request by itself. What does repeat: unfinished store transactions are sent again on every launch, merging an anonymous customer is tried again on the next refresh, and after a Stripe payment the SDK polls the customer's state (see Web and Stripe). The state also refreshes on launch and on every return to the foreground.

Codes you may see:

CodeMeaning
network_errorTenth couldn't be reached.
timeoutThe request took longer than 15 seconds.
rate_limitedToo many requests (HTTP 429).
http_errorThe API returned an error without a code. status has the HTTP status. (The Node SDK names this case http_<status>, such as http_502.)
invalid_configapiUrl isn't an https URL.
store_unavailableThe store isn't responding. The purchase is safe; try again later.
receipt_invalidThe store couldn't confirm the purchase.
receipt_belongs_to_other_customerThe purchase belongs to a different account.
purchases_unavailablePurchases aren't available on this device, for example when in-app purchases are restricted.
product_unavailableThe product isn't in the loaded offering, the store didn't return it, or Play didn't return the googleOfferId you asked for.
preview_live_keyA purchase in preview mode with a live key.
payment_sheet_missingAn in_app_stripe purchase without import '@tenthbilling/expo/payment-sheet'.
stripe_not_readyStripe payments aren't set up for this app.
payment_step_unavailableA web purchase started outside a paywall that can show the payment form.
payment_failedStripe reported a failure, or Checkout couldn't be opened.
url_scheme_missingA web_link_out purchase without a URL scheme.
invalid_urlThe subscription management link wasn't https.
unknown_errorAnything else.

The API can return other stable codes too, and codes raised by the native store modules pass through as they are. Either way, message is a sentence you can show. Errors lists every code the API returns.

Types

The package exports these types for TypeScript. The published .d.ts files have the full definitions, with comments.

Coming from RevenueCat: Tenth's CustomerInfo is not RevenueCat's. It's what useCustomer() returns (state plus loading flags). The customer's state itself, the closest match to RevenueCat's CustomerInfo, is CustomerState.

TypeWhat it is
TenthProviderPropsThe props of TenthProvider (see TenthProvider).
TenthConfigThe options a Tenth instance is created with: apiKey, getCustomerToken, apiUrl, offlineGraceHours, preview, locale, urlScheme, merchantDisplayName. The provider builds it from its props.
TenthSnapshot{ status, customer, fromCache, confirmedAt, error, preview, environment }: what useTenthSnapshot() and getSnapshot() return.
CustomerState{ customer, entitlements, credits, subscriptions } (see useCustomer). The same shape as the server's GET /v1/customers/{id} and every webhook's customer.
EntitlementStateOne entry of CustomerState.entitlements (see useEntitlement).
CreditBalance{ balance, available }: one entry of CustomerState.credits.
SubscriptionSummaryOne entry of CustomerState.subscriptions.
CustomerInfoWhat useCustomer() returns: { customer, loading, fromCache, error, refresh }.
EntitlementInfoWhat useEntitlement() returns: { active, loading, entitlement }.
CreditsInfoWhat useCredits() returns: { balance, available, loading, debit }.
OfferingInfoWhat useOffering() returns: the LoadedOffering fields plus { loading, error, reload }.
LoadedOffering{ offering, products, paywall, path }: what getOffering() resolves with.
OfferingThe offering as Tenth serves it: { key, purchase_path, products }.
OfferingProductOne product of an Offering, before store prices are added: key, type, display_name, label, badge, is_highlighted, store_product_id, google_base_plan_id, google_offer_id, price (web only), entitlements and credits. Paywalls use PaywallProduct instead.
PaywallProductA product ready to sell, with the store's price (see usePaywall).
PaywallControllerWhat usePaywall() returns.
UsePaywallOptionsThe options of usePaywall().
PaywallProps, GatePropsThe props of <Paywall> and <Gate>.
PaywallPresentation'inline' | 'sheet' | 'modal'.
PaywallSlotsThe slot components of <Paywall> (see Slots).
PaywallThemeOverridesThe theme prop of <Paywall> (see Theming).
PaywallResult'purchased' | 'restored' | 'cancelled' | 'not_presented': what presentPaywall() resolves with.
PresentPaywallOptionsThe options of presentPaywall() and presentPaywallIfNeeded().
PurchaseResult{ status: 'purchased' | 'pending' | 'cancelled' }, or { status: 'failed', error } (see Purchase and restore results).
RestoreResult{ status: 'restored' | 'nothing_to_restore' | 'failed' }, with error when it failed.
RefreshReasonWhy a refresh ran: 'launch', 'foreground', 'purchase', 'manual' or 'identity'.
UpdateSourceThe interface behind the SDK's refresh triggers (launch and foreground). Apps don't need it.