Node.js API Client

This guide will get you all set up with our Node.js API Client, ready to integrate pricing, payments, authentication and more into your storefront.

The client is intended to be used for customer facing applications, with built-in security token handling including automatic refreshing of access tokens.

Getting started

Start by adding the package to your project

npm install @moonbase.sh/storefront-api --save

Now you're ready to instantiate the client itself:

import { MoonbaseClient } from '@moonbase.sh/storefront-api'

const client = new MoonbaseClient({
    endpoint: 'https://{YOUR-ACCOUNT-ID}.moonbase.sh',
});

Endpoint collections

The client exposes a number of endpoint collections:

  • Identity - For all authentication concerns
  • Inventory - For getting customer inventory of licenses & products
  • Orders - For handling order & cart contents
  • Storefront - For getting storefront products and bundles
  • Vouchers - For redeeming vouchers
  • Gifts - For opening and claiming gifts
  • Reviews - For reading product reviews and handling the customer's review and votes
  • Communications - For newsletter sign-ups and email preferences
  • Groups - For adding a signed-in customer to a customer list

All endpoint collections come with TypeScript types that explain the models.


Product reviews

client.reviews exposes get, getMore, getMine, submit, edit, withdraw and vote. Public reads need no sign-in. The other methods use the customer's session, refreshed by the client; keep server-side clients isolated per customer request.

import { hasRating, ProductReviewSort } from '@moonbase.sh/storefront-api'

let page = await client.reviews.get('helios', { sort: ProductReviewSort.Helpful })
if (hasRating(page.summary))
  console.log(page.summary.average, page.summary.count)

const reviews = [...page.items]
while (page.next) {
  page = await client.reviews.getMore(page.next)
  reviews.push(...page.items)
}

// After signing the customer in, and from their submit action:
const mine = await client.reviews.getMine('helios')
if (mine.eligibility.canReview) {
  const content = {
    rating: 5,
    title: 'Fits my workflow',
    body: 'The controls make it easy to get the sound I want.',
    displayName: 'Alex',
    anonymous: false,
    allowUse: true as const,
  }
  const result = mine.review
    ? await client.reviews.edit('helios', content)
    : await client.reviews.submit('helios', content)
  console.log(result.review?.status) // Usually 'underReview', before publication
}

Show the review-use notice and link your terms beside the submit button before sending allowUse: true. A second submit is a conflict, including after withdrawal; edit the existing review instead. Use the reported eligibility, next edit time and remaining revisions to explain a refused edit. The Storefront API review reference describes purchase eligibility, content limits, moderation and statuses.

Call client.reviews.withdraw(productId) to take the review down, even while reviews are disabled. client.reviews.vote(productId, reviewId, 'up') marks another review helpful; 'down' marks it unhelpful, and 'none' clears the vote. It returns updated vote totals. get also accepts stars, from 1 to 5; pagination retains its filter through getMore.

Purchase history

client.orders.getHistory() reads the signed-in customer's completed orders, newest first, and client.orders.getHistory(next) reads the next page. Each item can include completedAt and a receiptUrl that opens without authentication. The history endpoint explains pagination and receipts for externally settled orders.

client.orders.getReceipt(orderId) fetches a receipt as a PDF Blob using the customer session, for a download or viewer of your own.

Paying off a subscription

A subscription whose milestones end it can be paid off early where you allow it. While it can, payoff on the subscription says how many payments are left and their total, and once it is paid off, paidOffAt says when. client.inventory.subscriptions.payOff(id, returnUrl, embedded) opens the checkout for it, the way renew does:

const subscription = await client.inventory.subscriptions.getById(subscriptionId)
if (subscription.payoff) {
  const { location } = await client.inventory.subscriptions.payOff(subscription.id, window.location.href, false)
  window.location.assign(location) // The hosted checkout, which brings the customer back once paid
}

The Storefront API describes what paying it off does.

Gifts

On accounts with gift purchases turned on, a buyer can send an order to someone else, who claims it with the code from their gift email. client.gifts.peek(code) shows anyone with the code who it is from, the message and what it holds, and client.gifts.claim(code) adds it to the signed-in customer's account.

import { GiftAlreadyClaimedError, GiftClaimStatus, GiftUnavailableError } from '@moonbase.sh/storefront-api'

const code = '7KQ2-M9XP-4TRW-C8HD' // As the recipient typed it: case, spaces and dashes don't matter
const gift = await client.gifts.peek(code)
console.log(gift.senderName, gift.message, gift.products, gift.bundles)

if (gift.status === GiftClaimStatus.Unclaimed) {
  try {
    const claimed = await client.gifts.claim(code) // Needs a signed-in customer
    console.log(claimed.status) // 'ClaimedByYou'
  }
  catch (err) {
    if (err instanceof GiftAlreadyClaimedError) {
      // Someone else claimed it first
    }
    else if (err instanceof GiftUnavailableError) {
      // Refunded, so the code no longer works
    }
    else {
      throw err
    }
  }
}

Claiming a gift the customer already claimed is safe, and delivers anything an earlier attempt could not. An unknown code throws NotFoundError. Orders from client.orders.getHistory() carry gift when the buyer sent one. The Storefront API describes the gift model and its errors.

Customer lists

A customer list opened to sign-ups in Moonbase can be joined from your site, by its group ID. Sign-up, newsletter sign-ups and orders take the IDs alongside, and a list that can't be joined is skipped without an error:

// The last argument of signUp takes the options
await client.identity.signUp(name, email, password, null, true, true, false, { groupIds: ['beta-testers'] })

await client.communications.subscribe({ email, groupIds: ['helios-2-waitlist'] })

// Once the order exists, and before the customer pays. They join once it's paid
await client.orders.joinGroups(order.id, ['beta-testers'])

client.groups.join(groupId) adds the signed-in customer to a list on its own, and throws NotFoundError when the list can't be joined. client.identity.externalSignIn.redeem(code, { groupIds }) adds a customer to lists when signing in with a provider creates their account.

Sign-in providers

Where your store has Google, Apple, Facebook or Discord switched on, client.identity.externalSignIn signs customers in and up with them, keeping the PKCE verifier in the tab's sessionStorage for you. It runs in the browser, on an https page or localhost. features.signInProviders on client.vendor.get() lists the providers to show buttons for.

// The button: send the customer to the provider, in the same tab
const url = await client.identity.externalSignIn.start('Google', { resume: { productId: 'helios' } })
window.location.assign(url)

// Back on the page, take the answer off the address and finish the sign-in
const page = new URL(window.location.href)
if (page.searchParams.get('mb_intent') === 'external_sign_in') {
  const code = page.searchParams.get('mb_code')
  for (const key of ['mb_intent', 'mb_provider', 'mb_code', 'mb_error'])
    page.searchParams.delete(key)
  history.replaceState(null, '', page)

  if (!code) {
    client.identity.externalSignIn.discard() // mb_error: cancelled, failed, unavailable or expired
  }
  else {
    const result = await client.identity.externalSignIn.redeem(code)
    if (result.status === 'SignedIn')
      console.log(result.user, result.isNewAccount, result.resume) // The tokens are stored
    else if (result.status === 'ConfirmationRequired')
      console.log(`Check ${result.email} for a link to confirm it's you`)
  }
}

resume is anything your page needs to carry on afterwards, handed back by redeem or discard. From a sign-up form, pass its newsletter opt-in as start(provider, { communicationOptIn: true }), and redeem subscribes an account the sign-in creates. Pass redeem(code, { signUp: false }) on a site that takes no sign-ups, to only sign in customers who already have an account. The emailed confirmation link opens your site with mb_intent=confirm_sign_in, for confirm(code, provider), which signs the customer in, and in the browser that redeemed also links the provider to their account.

link(provider) starts adding a provider from a signed-in customer's account page, and its redeem answers Linked. unlink(login.id) removes one of user.logins. The Storefront API describes the flow and its errors.

Counting visits

Your dashboard counts visits to your store from the catalog request of the page load each visit begins on. The embedded storefront and the Vue and React SDKs flag it for you. In a storefront of your own, isArrival tells a new visit (opened from another site, a search, an ad or its address) from a reload or a move between your pages, and client.storefront.get passes it on:

import { isArrival, onPrerenderActivation, pageLoadHere, parseOffSiteReferrer } from '@moonbase.sh/storefront-api'

// The tags on this page's address, and the referring site when it's another one
const params = new URLSearchParams(window.location.search)
const utm = {
  source: params.get('utm_source') ?? undefined,
  campaign: params.get('utm_campaign') ?? undefined,
  referrer: parseOffSiteReferrer(document.referrer, window.location.origin),
}

const load = pageLoadHere()
const arrival = { consent: cookieBannerAnswer } // true or false, or leave it out until the visitor answers
const storefront = await client.storefront.get(utm, isArrival(utm, document.referrer, load) ? { arrival } : undefined)

// A page Chrome prerenders counts once someone sees it
if (isArrival(utm, document.referrer, { ...load, prerendering: false }))
  onPrerenderActivation(() => client.storefront.get(utm, { arrival }))

Was this page helpful?