Guides Checking access

Checking access

Gate features in your popup, content scripts, options page and background with getUser, hasAccess and onChange, and keep server features safe.

Every access check has three steps: load the user with bill.getUser(), decide with bill.hasAccess(), and re-render when bill.onChange() reports a new state. Use this page to gate features in each part of your extension.

// popup.js
import { bill } from './bill'

function render(user) {
  document.querySelector('#pro-features').hidden = !bill.hasAccess(user, 'pro')
  document.querySelector('#upgrade').hidden = bill.hasAccess(user, 'pro')
}

document.querySelector('#upgrade').addEventListener('click', () => bill.openCheckout())

render(await bill.getUser())
bill.onChange(render) // fires in every context after a purchase, refund or trial end

The shared bill client and bill.startBackground() are set up in the Quick start. Using React, Vue, Svelte or another framework in a UI page? Its binding does these three steps for you: see Frameworks.

Opening checkout closes the popup. The background keeps watching the checkout tab, so when the buyer reopens the popup after paying, getUser() already returns the upgraded state. Pages that stay open during checkout, such as a side panel or the options page, are re-rendered by onChange the moment payment completes. For a ready-made upgrade screen, use the Paywall UI.

What counts as access

bill.hasAccess(user, feature?) returns true when:

  • an install free trial is running (a trial unlocks every feature, even though user.paid stays false), or
  • no feature is given and user.paid is true (any active entitlement), or
  • a feature is given and user.entitlements contains it.

It returns false once the state’s signed entitlement token has expired, which bounds how long a cached state can be trusted offline. Paid access includes one-time purchases, active subscriptions (including canceled ones until cancelAt, and PayPal subscription trials), license keys, and access you granted manually in the dashboard. See the SDK reference for the exact rules.

Feature-level gating

When you sell more than one product, give each product an entitlement key in the dashboard under Sell → Products (for example pro and team) and check keys instead of paid:

function render(user) {
  // Any paid product, or a running trial
  document.querySelector('#export').disabled = !bill.hasAccess(user)

  // Only buyers of the product whose entitlement key is "team"
  document.querySelector('#team-settings').hidden = !bill.hasAccess(user, 'team')

  // A feature that belongs to several products
  document.querySelector('#sync').hidden = !['pro', 'team'].some((key) => bill.hasAccess(user, key))

  document.querySelector('#plan-name').textContent = user.plan?.name ?? 'Free'
}

After the first getUser() in a context, you can omit the user: bill.hasAccess('pro') uses the last state this context has seen. That is handy in event handlers:

document.querySelector('#export').addEventListener('click', () => {
  if (!bill.hasAccess('pro')) return bill.openCheckout()
  exportEverything()
})

Content scripts

Content scripts run inside web pages, so the SDK never calls the API from them: the request would carry the page’s origin. Every call from a content script is forwarded to your service worker, which answers it through bill.startBackground(). Without it, calls reject with background_unavailable. Content scripts always use this vanilla API, even when your popup uses a framework binding.

This content script adds a “Summarize” button to pages for Pro users and removes it if access ends:

// content.js
import { bill } from './bill'

const BUTTON_ID = 'focus-tabs-summarize'

function createButton() {
  const button = document.createElement('button')
  button.id = BUTTON_ID
  button.type = 'button'
  button.textContent = 'Summarize'
  button.style.cssText = 'position:fixed;bottom:16px;right:16px;z-index:2147483647'
  button.addEventListener('click', () => {
    if (!bill.hasAccess('pro')) return bill.openCheckout()
    summarize(document.querySelector('article')?.innerText ?? '')
  })
  return button
}

function apply(user) {
  const existing = document.getElementById(BUTTON_ID)
  if (bill.hasAccess(user, 'pro')) {
    if (!existing) document.body.append(createButton())
  } else {
    existing?.remove()
  }
}

bill.onChange(apply)

bill.getUser().then(apply).catch((err) => {
  // Leave the page untouched if the extension cannot answer
  console.debug('Focus Tabs: access check failed', err.code)
})

onChange fires in content scripts too, so a purchase made in another tab unlocks the button on every open page without a reload. bill.openCheckout() and the other open* calls work from content scripts as well; the background opens the tab.

Content scripts listed in manifest.json cannot use import at runtime: bundle each one into a single file, or use the global build.

Options page

The options page is the right place for an account section: plan, status, email, install ID and a Manage subscription button.

// options.js
import { bill } from './bill'

const $ = (id) => document.getElementById(id)
const formatDate = (iso) => new Date(iso).toLocaleDateString()

function describeStatus(user) {
  if (user.trial.active) return `Free trial, ${user.trial.daysLeft} days left`
  const sub = user.subscription
  if (sub) {
    if (sub.cancelAt) return `Canceled, access until ${formatDate(sub.cancelAt)}`
    if (sub.status === 'past_due') return 'Payment failed: update your payment method in PayPal'
    if (sub.status === 'suspended') return 'Paused'
    if (sub.trialEndsAt && new Date(sub.trialEndsAt) > new Date()) {
      return `Trial, first payment on ${formatDate(sub.trialEndsAt)}`
    }
    if (sub.currentPeriodEnd) return `Active, renews ${formatDate(sub.currentPeriodEnd)}`
    return 'Active'
  }
  return user.paid ? 'Active' : 'Free'
}

function render(user) {
  $('acc-plan').textContent = user.plan?.name ?? 'Free'
  $('acc-status').textContent = describeStatus(user)
  $('acc-email').textContent = user.customer?.email ?? 'Not linked'
  $('acc-install').textContent = user.installId
  $('acc-manage').hidden = !user.customer
}

$('acc-manage').addEventListener('click', () => bill.openPortal())
$('acc-restore').addEventListener('click', () => bill.openRestore())

bill.onChange(render)
render(await bill.getUser())
  • Set every value with textContent, never innerHTML. Customer names and emails come from buyers and are untrusted text.
  • Manage subscription opens the customer portal. Hide it until the install is linked to a customer.
  • Restore purchase links this install to an earlier purchase: see Restore purchases.
  • Add a trial button with Free trials and a license key form with License keys.
  • The install ID appears in the dashboard under Installs. Ask users to paste it in support requests.

Background-only features

Context menu items, keyboard commands, alarms and network rules have no page UI. Check access in the service worker right before doing the work:

// background.js
import { bill } from './bill'

bill.startBackground()

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'summarize-selection',
    title: 'Summarize selection',
    contexts: ['selection'],
  })
})

chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  if (info.menuItemId !== 'summarize-selection') return
  const user = await bill.getUser()
  if (!bill.hasAccess(user, 'pro')) return bill.openCheckout()
  await summarizeSelection(info.selectionText ?? '', tab)
})

// Keep the menu title honest as access changes
bill.onChange((user) => {
  chrome.contextMenus.update('summarize-selection', {
    title: bill.hasAccess(user, 'pro') ? 'Summarize selection' : 'Summarize selection (Pro)',
  })
})

This example also needs the contextMenus permission. Register every listener, including bill.startBackground(), at the top level so they survive service worker restarts. In the background, getUser() reads the cache directly, so it is fast enough to call on every click.

Server-side features

Signed entitlement tokens stop anyone from unlocking features by editing storage, but the extension’s own code can always be modified. That is fine for UI features. It is not fine for anything that costs you money or exposes data on your server, such as an AI endpoint or cloud sync.

For those, never trust a flag sent by the extension. Send the install ID and check access on your server with the Server API:

// popup.js (extension)
const installId = await bill.getInstallId()

const response = await fetch('https://api.yourdomain.com/summarize', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-Install-Id': installId },
  body: JSON.stringify({ text }),
})
// server.js (your backend, Node 18+)
const API_BASE = 'https://api.extensionbill.com'

export async function installHasFeature(installId, entitlementKey) {
  const response = await fetch(`${API_BASE}/v1/installs/${encodeURIComponent(installId)}`, {
    headers: { Authorization: `Bearer ${process.env.EXTENSIONBILL_SECRET_KEY}` },
  })
  if (response.status === 404) return false
  if (!response.ok) throw new Error(`ExtensionBill responded ${response.status}`)

  const { user } = await response.json()
  return user.entitlements.includes(entitlementKey) || user.trial.active
}

GET /v1/installs/:installId returns the install record and the same UserState the SDK sees. Authenticate it with a secret key (sk_test_… or sk_live_…) that lives only on your server. Cache the result for a short time, and listen to webhooks such as entitlement.revoked to react instantly.

Customize

Offline behaviour

The SDK keeps the last state in chrome.storage.local, so checks keep working without a connection:

  • getUser() returns the cached state when it is under 5 minutes old, and also when the API cannot be reached.
  • A cached state is trusted until its signed entitlement token expires, 72 hours after the last successful check. After that, getUser() returns a free state and hasAccess() returns false until the extension is back online.
  • refresh() always goes to the network and rejects when offline. Use getUser() for gating and refresh() only behind an explicit “Refresh” button.

Details are in Caching and offline grace.

First run while offline

Before the install has ever been registered there is nothing cached, so getUser() rejects with network_error or timeout. Show a friendly message instead of an empty popup:

try {
  render(await bill.getUser())
} catch (err) {
  document.querySelector('#error').textContent =
    'Could not reach the server. Check your connection and reopen this popup.'
}