Store

Buying

The gate, the details a purchase needs, one tap that never charges twice, and what to show after.

The checkout. Less code than it looks, and two traps that each cost a fan real currency if you miss them.

The shape

import { Store } from '@xborglabs/fanbase-react'

function Checkout({ listing, requirementData }) {
  const selected = listing.listings.find((option) => option.isSale) ?? listing.listings[0]

  return (
    <Store.Listing listing={listing}>
      <Store.Checkout pricingOption={selected} requirementData={requirementData}>
        <GateMessage />
        <Store.Purchase asChild>
          <button className="your-button">Buy</button>
        </Store.Purchase>
      </Store.Checkout>
    </Store.Listing>
  )
}

Store.Checkout holds the price the fan picked and any details they filled in. Store.Purchase is the button that spends them, and it disables itself while the gate is locked or a purchase is in flight.

Pass the price you mean to charge. Without pricingOption, the checkout uses the first price on the listing, which for a sale item is the full price. See Sales.

The gate

Worked out before anything is sent, from data the page already has. Read it from the listing scope:

import { useStoreListing, resolveStorePriceChrome, useStore } from '@xborglabs/fanbase-react'

function GateMessage() {
  const { state } = useStoreListing()
  const { state: store } = useStore()
  const reason = state.gate.reason

  if (!reason) return null

  switch (reason.reason) {
    case 'MEMBERSHIP_REQUIRED':
      return <p>For {reason.requiredTierName} members. <a href="/membership">Upgrade</a></p>
    case 'OUT_OF_STOCK':
      return <p>Sold out.</p>
    case 'REQUIREMENTS_MISSING':
      return <DetailsForm />
    case 'INSUFFICIENT_BALANCE': {
      const chrome = resolveStorePriceChrome(state.pricingOption, store.balances, store.resourceTypes)
      return <p>Not enough {chrome?.name}. <a href="/quests">Earn more</a></p>
    }
  }
}
ReasonShowClears when
MEMBERSHIP_REQUIREDThe tier by name, and a way to upgradeThe fan's membership reaches that tier
OUT_OF_STOCKSold outThe item is restocked
REQUIREMENTS_MISSINGThe details formThe fan fills it in
INSUFFICIENT_BALANCEWhich currency they are short of, and where to earn itTheir balance rises

Only the first failing reason is reported, in that order.

A fan who is not signed in never gets INSUFFICIENT_BALANCE, because the SDK does not know their balance. Handle sign-in before checkout yourself. A buy button that sends a signed-out fan to sign-in is better than one that fails.

Name the tier from the reason. "For Premium members" tells a fan exactly what to do, and reading the name rather than hardcoding it keeps the copy right if the community renames the tier.

The purchase gateTry it
Fan's membership
Credits balance
800
Listing and fan
Away shirt, signed
Members only · ships to you
500 CreditsYou have 800
Checked in this order
  1. MembershipOK
  2. StockOK
  3. Details
    REQUIREMENTS_MISSING
    Reported
  4. BalanceNot reached
The checks run before any request, from data the page already has. Only the first failure is reported. Example data.

Details a purchase needs

Some listings need something from the fan: an email, a shipping address, a wallet address. Where those requirements live depends on the listing type, and the SDK reads the right place for you:

import {
  getPurchaseRequirementFields,
  getPurchaseRequirements,
  toPurchaseRequirementData,
} from '@xborglabs/fanbase-react'

const fields = getPurchaseRequirements(listing).flatMap(getPurchaseRequirementFields)

// render a form from `fields`, then on submit:
const requirementData = toPurchaseRequirementData(values)

Pass requirementData to Store.Checkout and REQUIREMENTS_MISSING clears.

Do not read listing.prize?.requirements yourself. Any listing can ask for details of its own, and a prize listing also asks for whatever its prize needs. getPurchaseRequirements returns both sets, without repeating a field both ask for, and only the fields a fan fills in, in the order a form should ask for them.

An address comes back as its parts in checkout order: country, recipient name, three address lines, city, state, postal code. Details a fan enters are saved to their profile by default, so they do not type their address twice. That is also why enrichRequirements on the provider matters: it is what reads those saved details back in.

Never retry with a new nonce

Worth reading twice.

Every purchase is sent with a nonce, a one-time key that stops the same purchase going through twice. The SDK generates one for you.

If a purchase fails with DuplicateNonceError, the first attempt almost certainly went through. The platform is refusing a repeat of a purchase it already accepted. It does not replay the original result, it just refuses.

So the fix is not to retry. It is to check:

import { DuplicateNonceError, usePurchases, useStoreListing } from '@xborglabs/fanbase-react'

const { actions } = useStoreListing()
const { refetch } = usePurchases()

try {
  await actions.purchase()
} catch (error) {
  if (error instanceof DuplicateNonceError) {
    await refetch() // the purchase is almost certainly in here
    return showPurchased()
  }
  throw error
}

Retrying with a fresh nonce is the one thing not to do. It is a new key, the platform accepts it, and the fan is charged twice for one item. The SDK never retries a purchase on its own for exactly this reason.

Errors

Every refusal comes back as a typed error. Switch on the class, never on the message.

ErrorMeansShow
DuplicateNonceErrorThis purchase already went throughSee above. Do not retry.
ListingUnavailableErrorThe listing was removedNo longer available
InsufficientBalanceErrorNot enough currencyShould not happen past the gate. Refetch the balance.
PrizeRequirementValidationErrorA detail was rejectedField-level errors on the form
SupplyDepletedErrorSold out, even though the card had stockSold out. See Stock.
PurchaseTransferErrorThe purchase could not completeA generic failure. Do not retry automatically.

PrizeRequirementValidationError also covers a fan below the membership tier and a fan below the level. The platform does not tell those apart from a bad email, which is the whole reason the gate is worked out up front.

After a purchase

A purchase settles into one of four outcomes, one per listing type. Branch on it rather than going back to the listing:

const { state } = useStore()
const outcome = state.settlement?.outcome

switch (outcome?.kind) {
  case 'item':
    return <ItemGranted itemId={outcome.itemId} />
  case 'prize':
    return outcome.awaitingFulfilment ? <Processing /> : <Granted />
  case 'lootbox':
    return <Reveal opening={outcome.opening} />
  case 'personalization':
    return <EquipPrompt id={outcome.personalizationId} />
}
kindBoughtShow
itemAn inventory itemIt, straight away
prizeA prizeGranted, or processing if it is being shipped
lootboxA loot boxThe reveal
personalizationA cosmeticAn offer to equip it now

The inventory item outcome is item, not inventoryItem. It matches what a loot box can contain, not the listing type.

For a loot box, the reveal is yours to animate, over outcome.opening. For a personalisation, useEquipPersonalization equips it in one step. Rewards and claims covers both.

After any purchase, the fan's balance, the listings, their purchase history and their inventory all refresh on their own.

Shopify orders

A prize fulfilled through Shopify comes back with awaitingFulfilment: true and a status of ALLOCATED. The Shopify order is created just after the purchase, not during it.

StatusMeansShow
ALLOCATEDBought, order not created yetProcessing
DISTRIBUTINGThe order is being fulfilledProcessing
DISTRIBUTEDThe fan has itDelivered

ALLOCATED is not an error. Do not show one.

The SDK does not poll for you. If you want the status to update live on the page, poll the one purchase:

import { usePurchase } from '@xborglabs/fanbase-react'

const { data } = usePurchase(purchaseId, { refetchInterval: 5000 })

Purchase history

import { usePurchases } from '@xborglabs/fanbase-react'

const { data } = usePurchases()

data?.results.map((purchase) => <PurchaseRow key={purchase.purchaseId} purchase={purchase} />)

The list is in results, with the count in total, so you can page it. Each row carries its delivery status. It covers store purchases only. Rewards from quests are not in here.

Components

ComponentUse
Store.ProviderReads listings, balances, tiers and currency names for the storefront
Store.ListingOne listing, with its gate worked out
Store.DescriptionRenders a listing's description, full or plain
Store.CheckoutHolds the chosen price and the fan's details
Store.PurchaseThe buy button

Store.Purchase takes asChild and renders your element. Full props in Components.

Checklist

  • The buy button is disabled while the gate is locked and while a purchase is in flight
  • A member-only listing names the tier it needs
  • A listing that needs an address shows the form, and buys once it is filled in
  • A DuplicateNonceError checks purchase history and never retries with a new nonce
  • A card that showed stock still handles SupplyDepletedError
  • Each of the four outcomes shows its own screen
  • A Shopify prize shows processing, not an error
  • The balance updates after a purchase without a refresh

On this page