Web SDK Guide
Overview
This guide shows you how to integrate BillDog into your web application using TypeScript/JavaScript. The Web SDK runs in the browser: it manages subscriptions and renders paywalls. It declares react and react-dom 18 or later as peer dependencies, which npm installs for you if your app does not already have them.
Understanding Identifiers
All identifiers (products, offerings, packages, entitlements, placements) are project-scoped. Your API key determines which project's data is accessed. Different projects can safely use the same identifiers without conflicts. The key’s prefix also decides the environment: a bd_public_test_ key works with sandbox data and a bd_public_live_ key with production, so the same identifiers serve both and you move between them by switching keys. There are only these two environments; there is no staging environment.
Installation
Install the BillDog Web SDK package:
npm: @billdog.io/webnpm install @billdog.io/web@^1.2.0-beta.1Configuration
Initialize the SDK once at application startup, on every page load, with your project’s public key (bd_public_test_… or bd_public_live_…). The public key is meant to ship in browser code. Never put the secret key in client code.
import BillDog from '@billdog.io/web';
BillDog.configure({
apiKey: 'bd_public_live_...'
});Present a Paywall via Placements
The standard way to present a paywall is by registering a Placement. The server decides which paywall the placement shows, and the SDK presents it:
// Present the paywall for onboarding
const result = await BillDog.register('onboarding', undefined, {
onPresent: (placementId) => {
console.log('Paywall presented for:', placementId);
},
onDismiss: (placementId) => {
console.log('Dismissed paywall:', placementId);
}
});
// result.type: 'entitled' | 'purchased' | 'dismissed' | 'restored' | 'error'The second argument (params) is optional targeting input. It is sent to BillDog as the request’s custom attributes, which campaign audience rules match on, as on iOS and Android. For example, BillDog.register('onboarding', { source: 'landing_page' }) lets a campaign whose audience requires source = landing_page choose the paywall.
Purchases finish on the page the customer returns to
BillDog’s web checkout leaves your page for the payment provider. The customer comes back to a new page load, so the register call that opened the paywall is gone, and its onPurchaseSuccess handler never runs for a checkout. On the return page, configure() confirms the checkout with the server and tells your delegate. Pass the delegate to configure() on every page load:
BillDog.configure({
apiKey: 'bd_public_live_...',
delegate: {
onPurchaseCompleted: (productId, transaction) => {
// Confirmed by the server. hasEntitlement() already reflects it.
if (BillDog.hasEntitlement('premium_features')) unlockPremium();
},
// The customer came back, but the server has not confirmed the payment yet.
onWebCheckoutUnconfirmed: (productId, reason) => {
// Re-check later with getCustomerInfo()
},
onPurchaseCancelled: (productId) => {},
},
});onPurchaseCompleted runs once per checkout session, with the session as transaction.transactionId and the confirmed customer as transaction.customerInfo. Once it has been called for a session, loading that success URL again (back and forward, a second tab, a bookmark) does not call it again, for any customer, including after a log-out. The browser remembers the session ids it has reported (in localStorage, key billdog.web.reportedCheckouts, the last 50, session ids only) until the site’s data is cleared. With storage blocked, a reload may report it again.
If no delegate is set when the checkout is confirmed, the outcome waits for setDelegate on that page load. If the page is left first, the next load of the success URL reports it. An outcome is reported only to the customer it belongs to: it is dropped if the customer logs out or another customer logs in first. A visitor who returns as a guest and then logs in is still told, if the purchase is theirs once they log in.
Without a redemption token, the SDK confirms a return by reading the customer’s active purchases, not the checkout session itself. A customer who already has an active entitlement is confirmed by any success URL, including one for a checkout that never happened. Grant access from what the server says the customer holds (await BillDog.getCustomerInfo(); hasEntitlement() answers synchronously from the customer last read, which the confirmation refreshed), and treat onPurchaseCompleted as a cue to refresh your UI, not as proof of a new payment. With a redemption token, the server’s redemption is the confirmation, including for a one-time product that grants no entitlement. If the visitor logged in as a different customer while it was being redeemed, that customer is told onWebCheckoutUnconfirmed(productId, 'redeemed_for_another_customer') unless the purchase is theirs.
The same outcomes are also emitted on BillDog.eventBus (purchase_completed, web_checkout_unconfirmed, purchase_cancelled). The bus does not replay: subscribe in the same tick as configure(), before any await, or use the delegate. Only the delegate is told once per session: if no delegate heard a completion, its bus events fire again on the next load of the success URL.
What paywall buttons do in a browser
A paywall the Web SDK shows handles its buttons in the browser:
- Restore restores the customer’s purchases. If any were restored (or your purchase adapter’s
restorePurchases()answeredtrue), the paywall closes. - Copy and Share use the browser’s clipboard and share sheet.
- Manage Subscription, Request Refund, Upgrade and Downgrade open the customer’s billing portal from
billingPortalUrl(below). Without it they open nothing. You can also handle them yourself withonSubscriptionAction. - Server actions such as Grant Currency and Webhook run on BillDog’s servers for the current customer.
- A Deep Link opens a
billdog://link or a web address. An app’s own link (myapp://) means nothing to a browser, so it needs your handler. - A Custom Event reaches
onCustomEventand abilldog:paywall_custom_eventwindow event.
Creating a billing portal session needs your project’s secret key, which must never ship to a browser, so the portal comes from you. Give configure() either your Stripe customer-portal login link, or a function that asks your own server for a portal session (your server calls POST /v1/create-stripe-portal-session with the secret key) and returns its URL:
BillDog.configure({
apiKey: 'bd_public_live_...',
// Stripe's no-code customer portal link: the customer signs in by email.
billingPortalUrl: 'https://billing.stripe.com/p/login/...',
// Or a session from your server:
// billingPortalUrl: async () => (await fetch('/api/billing-portal')).json().then((r) => r.url),
});Pass your own handlers to presentPaywall to take any of these over:
await BillDog.presentPaywall('upgrade', {
onDeepLink: (url) => router.push(url),
onCustomEvent: (eventId, metadata) => myAnalytics.track(eventId, metadata),
onSubscriptionAction: (type, payload) => openAccountPage(type),
});Restore Purchases
restorePurchases() resolves true when the restore restored something and false when it found nothing to restore (or could not run here, for example for a restricted customer). A refusal from the server is thrown as BillDogApiError.
try {
if (await BillDog.restorePurchases()) {
// Something was restored, and hasEntitlement() already reflects it.
} else {
console.log('Nothing to restore');
}
} catch (err) {
// BillDogApiError: err.code is the server's code (PROOF_REQUIRED, NETWORK_ERROR, …)
console.error('Restore refused:', err);
}To know what was restored, call restore(). It answers the same result iOS, Android and React Native return, and never throws:
{ type: 'restored', items, customerInfo }: the restore ran.itemslists the purchases it restored (productId,transactionId) and is empty when there was nothing to restore.customerInfois the customer read after the restore, so its entitlements are current (it isnullif that read failed).{ type: 'failed', error }: the restore could not run.error.codeis the server’s code (for examplePROOF_REQUIREDorNETWORK_ERROR), or one ofNO_CUSTOMER,ACCESS_RESTRICTEDandIDENTITY_CHANGED(the customer logged out or switched while the restore ran, so its result is not reported as the new customer’s).
const result = await BillDog.restore();
if (result.type === 'failed') {
console.error('Restore failed:', result.error.code, result.error.message);
} else if (result.items.length === 0) {
console.log('Nothing to restore');
} else {
const hasPremium = BillDog.hasEntitlement('premium_features');
console.log('Restored', result.items.map((item) => item.productId), { hasPremium });
}A delegate set with setDelegate hears every restore once, from your code or a paywall’s Restore button, as onRestoreCompleted(itemCount, result).
Session replay
Session replay is part of @billdog.io/web and off by default. Turn it on with enableSessionReplay: true in configure. The recorder ships inside the package; in the ES module build it is a separate chunk that loads only once replay is on, so visitors on pages without replay don’t download it.
BillDog.configure({
apiKey: 'bd_public_live_...',
enableSessionReplay: true
});Journeys
The web SDK does not run journey steps unless you turn them on. enableJourneys defaults to false. With it off, a journey’s paywall, survey or custom-action step is queued on the server but never shown in the browser.
BillDog.configure({
apiKey: 'bd_public_live_...',
customerId: 'user_123', // journeys need an identified customer
enableJourneys: true
});- Journeys need an identified customer. The SDK fetches that customer’s queued steps once when it starts with a
customerId, and again whenlogInorsetCustomerIdchanges the identity. It does not poll in between, so a step queued mid-session is shown on the next page load or identity change. - A queued step expires 7 days after the journey queues it. If the customer doesn’t load your site in that time, the paywall or survey is never shown.
- A custom-action step reaches your code as a
journey_custom_actionevent; report the outcome withreportJourneyActionResult(id, result).
Paywall Caching
Caching is built into @billdog.io/web; there is no separate package to install. presentPaywall and fetchPaywall keep each placement’s paywall configuration in memory, keyed by placement and customer, for 7 days by default. A cached configuration is returned at once and refreshed in the background. The cache lives in memory, so it starts empty on every page load.
fetchPaywall reads a placement’s paywall without presenting it. For a customer you identified with logIn, it fills the same cache entry that presentPaywall reads, so a later presentPaywall does not wait for the configuration to download:
import BillDog from '@billdog.io/web';
await BillDog.logIn('user_123');
// Warm the cache before the user reaches the pricing page
const paywall = await BillDog.fetchPaywall('premium_offer');
// Later: served from the cache
await BillDog.presentPaywall('premium_offer');Analytics Tracking
// Track paywall view
await BillDog.trackEvent('paywall_view', {
paywall_id: 'paywall_123',
timestamp: Date.now(),
referrer: document.referrer
});
// Track button click
await BillDog.trackEvent('button_click', {
paywall_id: 'paywall_123',
button_text: 'Subscribe Now',
package_id: 'monthly'
});
// Track purchase
await BillDog.trackEvent('purchase', {
paywall_id: 'paywall_123',
product_id: 'premium_monthly',
price: 9.99,
currency: 'USD'
});Name the paywall paywall_id (snake_case): that is the property BillDog’s per-paywall reports group on, and a paywallId key is not read. If you render your own paywall from getOffering, record its impression with BillDog.trackPaywallPresented(offering) instead.
Checking Entitlements
The id you pass in is a user you already signed in
Identify the user with logIn(userId) first; getCustomerInfo() then reads that user’s record. It returns null instead of throwing when the read fails, so treat null as “unknown”, not as “no access”. getCustomerInfo reads the record a user owns — entitlements, purchases, analytics. It does not authenticate anybody. If you would rather BillDog signed them in — password, email or SMS code, Google, Apple, passkeys, second factors, organizations — see BillDog Auth. The session it issues carries the user’s entitlements inside the token, so your backend gates a paid feature with a claim check instead of this round-trip. See Authentication below.
// Once, after your own sign-in
await BillDog.logIn('user_uuid_123');
async function checkPremiumAccess() {
const customerInfo = await BillDog.getCustomerInfo();
if (!customerInfo) {
console.error('Could not read the customer record');
return;
}
const hasAccess = customerInfo.entitlements.some(e => e.identifier === 'premium_features' && e.isActive);
if (hasAccess) {
showPremiumContent();
} else {
showPaywall();
}
}React Integration
import { useState, useEffect } from 'react';
import BillDog, { type CustomerInfo } from '@billdog.io/web';
// Once, at startup (here with Vite; use your bundler's way of reading env vars)
BillDog.configure({
apiKey: import.meta.env.VITE_BILLDOG_API_KEY // bd_public_test_... or bd_public_live_...
});
function SubscriptionComponent({ userId }: { userId: string }) {
const [customerInfo, setCustomerInfo] = useState<CustomerInfo | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function loadData() {
try {
// logIn identifies the user and returns their record (null if the read failed)
setCustomerInfo(await BillDog.logIn(userId));
} catch (error) {
console.error('Error:', error);
} finally {
setLoading(false);
}
}
loadData();
}, [userId]);
if (loading) return <div>Loading...</div>;
const hasAccess = customerInfo?.entitlements.some(e => e.identifier === 'pro_features' && e.isActive);
const handleShowPaywall = () => {
BillDog.register('onboarding');
};
return (
<div>
<h1>Subscription Status: {hasAccess ? 'Premium Active' : 'Free Tier'}</h1>
{!hasAccess && <button onClick={handleShowPaywall}>Upgrade to Premium</button>}
</div>
);
}Vue Integration
<script setup>
import { ref, onMounted } from 'vue';
import BillDog from '@billdog.io/web';
const customerInfo = ref(null);
const loading = ref(true);
const hasAccess = ref(false);
onMounted(async () => {
try {
BillDog.configure({
apiKey: import.meta.env.VITE_BILLDOG_API_KEY // the public key
});
// logIn identifies the user and returns their record (null if the read failed)
const info = await BillDog.logIn('user_uuid_123');
customerInfo.value = info;
hasAccess.value = info?.entitlements.some(e => e.identifier === 'pro_features' && e.isActive) ?? false;
} catch (error) {
console.error('Error:', error);
} finally {
loading.value = false;
}
});
const handleShowPaywall = () => {
BillDog.register('onboarding');
};
</script>
<template>
<div v-if="loading">Loading...</div>
<div v-else>
<h1>Subscription Status: {{ hasAccess ? 'Premium Active' : 'Free Tier' }}</h1>
<button v-if="!hasAccess" @click="handleShowPaywall">Upgrade to Premium</button>
</div>
</template>TypeScript Types
// From @billdog.io/core (src/types/index.ts)
interface Offering {
id: string;
identifier: string;
displayName: string | null;
description: string | null;
isCurrent: boolean; // in a headless result: true on exactly the selected offering
isDefault: boolean;
packages: OfferingPackage[];
metadata: Record<string, any>;
}
type PackageType = 'weekly' | 'monthly' | 'two_month' | 'three_month' | 'six_month' | 'annual' | 'lifetime' | 'custom';
interface OfferingPackage {
identifier: string;
packageType: PackageType;
product: Product;
}
interface Product {
id: string; // products.id
identifier: string; // the store SKU for the platform (stripe_price_id on web)
title: string;
description: string;
price: string;
priceString: string;
currencyCode: string;
period?: string;
trialPeriod?: string;
}
// getOffering(placement) resolves this; offering is null when the server selected none
interface OfferingResult {
offering: Offering | null;
offerings: Offering[];
placement: OfferingPlacement | null;
presentation: OfferingPresentation;
experiment: OfferingExperiment | null;
campaign: OfferingCampaign | null;
entitlements: Array<Record<string, any>>; // the project's catalogue, not the visitor's grants
}
interface OfferingPresentation {
gated: boolean; // reaching this placement requires access
holdout: boolean; // present nothing
withheld: boolean; // withheld from this caller by a server decision
withheldReason: string | null;
requiredEntitlement: string | null; // when gated: null means any active entitlement grants access
interpretable: boolean; // false: the server's decision was missing or malformed; grant nothing
}Headless offerings
import { PlacementNotFoundError, BillDogApiError } from '@billdog.io/core';
try {
const result = await BillDog.getOffering('pricing_page');
if (result.offering && !result.presentation.holdout && !result.presentation.withheld) {
render(result.offering); // never substitute one of result.offerings when offering is null
}
} catch (e) {
if (e instanceof PlacementNotFoundError) { /* 404 PLACEMENT_NOT_FOUND */ }
else if (e instanceof BillDogApiError) { /* e.code: PROOF_REQUIRED, PROOF_INVALID, ACCESS_DENIED, ... */ }
}Error Handling
import { BillDogApiError } from '@billdog.io/core';
try {
const started = await BillDog.purchaseProduct(productId);
} catch (error) {
if (error instanceof BillDogApiError) {
switch (error.code) {
case 'PROOF_REQUIRED': // no proof accepted for a customer-scoped call
case 'PROOF_INVALID': // the device key or session was refused (error.reason)
case 'ACCESS_DENIED': // error.reason === 'target_mismatch': the body named another customer
case 'RATE_LIMITED':
default:
console.error(error.code, error.status, error.message);
}
} else {
console.error('Unknown error:', error);
}
}Authentication
Signing users in is a separate package, @billdog.io/auth. It works today on the web — there is no version to wait for. It issues a short-lived session token your own backend verifies offline, carrying the user’s entitlements in the token’s ent claim. That claim holds at most 64 entitlements and sets ent_truncated when a user has more.
Install and configure
npm install @billdog.io/auth@1.2.0-beta.1import { createBillDogAuth } from '@billdog.io/auth';
const auth = createBillDogAuth({
apiKey: 'bd_public_live_...', // public key — safe in a browser
onSessionChange: (session) => render(session),
});
// A page load restores the session from the refresh cookie. Null on a first
// visit is ordinary, not an error.
await auth.restore();Sign someone in
const result = await auth.attempt({
identifier: 'ada@example.com',
strategy: 'password',
password: '...',
});
// ALWAYS check this before reading result.session — session is null while a
// second factor is still owed.
if (result.mfaRequired) {
const done = await auth.attempt({
identifier: 'ada@example.com',
strategy: 'totp',
code: '123456',
mfaToken: result.mfaToken, // proves the first factor was accepted
});
console.log(done.session);
} else {
console.log(result.session);
}A wrong second factor is a restart, not a retry. The server spends the MFA challenge when it reads it, before it checks the code, so the mfaToken you are holding is already dead by the time the error comes back. Send the user back to the first factor rather than re-prompting for another code against the same token.
Send the session token with your own API calls, or hand it to the BillDog client once:
await fetch('/api/thing', { headers: auth.authHeaders() });
// Let the BillDog SDK send the session with its own calls:
BillDog.connectAuth(auth); // or: BillDog.configure({ apiKey, auth })Codes, and the identifier-kind trap
// A RETURNING user gets a fresh code from requestCode — signUp issues one
// only for a NEW identifier.
await auth.requestCode({ identifier: '+15551234567', kind: 'phone' });
await auth.attempt({
identifier: '+15551234567',
strategy: 'sms_code',
kind: 'phone', // selects the identity row
code: '123456',
});kind defaults to 'email', and it is what the server looks the identifier up by. A phone sign-in that omits kind: 'phone' matches no identity row at all and comes back as the same opaque 401 you get for a wrong password — a slow thing to debug if you do not know to look for it.
Where the tokens live
The session token is held in memory only — never in localStorage, never in a readable cookie, because anything a script can read an XSS can take. It lasts 90 seconds and the SDK refreshes it for you. The cost is that a page reload loses it, which is what the one restore() call on load is for.
The refresh token is the long-lived half. On hosted sign-in — your own verified domain — the server sets it as an httpOnly cookie that JavaScript cannot touch, and restore() uses it without ever seeing it. Drive the API cross-origin instead and the refresh token is returned to you, at which point storing it safely becomes your decision. That is the reason hosted sign-in runs on your own hostname.
Sign-up requirements, password reset and account deletion
// What the project requires before it accepts a sign-up
const cfg = await auth.config(); // { accessMode, botProtection, turnstileSiteKey, ... }
await auth.signUp({
identifier: 'ada@example.com',
password: '...',
invitationToken, // required when cfg.accessMode is 'invite_only'
captchaToken, // required when cfg.botProtection is on (a Turnstile token)
});
// Password reset: send a code, then set the new password with it
await auth.requestPasswordReset({ identifier: 'ada@example.com' });
await auth.resetPassword({ identifier: 'ada@example.com', code: '123456', newPassword: '...' });
// Delete the signed-in user's own account. Throws REAUTH_REQUIRED when the
// sign-in is older than 15 minutes: sign the user in again, then retry.
await auth.deleteAccount();Pass the same kind to requestPasswordReset and resetPassword for a phone number. What the SDK does not do is configure the project: SSO connections, SCIM tokens, password policy and the MFA mandate are set in the dashboard, because this is a client holding a public key. Full detail: BillDog Auth, Sessions & Tokens, Multi-Factor Auth, Verifying Tokens.
Debug with the BillDog Chrome extension
The BillDog extension for Chrome shows what the web SDK on the current page is doing, opens the in-page toolbar, and adds a "Generate a paywall for this app" button to App Store and Google Play listings. It stores no keys or tokens. It needs @billdog.io/web 1.1.2-beta.5 or later; on older versions it reports "older SDK".
- Debugger: click the BillDog icon on your page, then Debug this page. The side panel shows the SDK version, test or live key, customer and anonymous IDs, entitlements, feature flags and overrides, which paywall each placement resolved to, surveys, and recent events.
- Why a live site shows "state hidden": every script on a page can read what the SDK tells the extension, so the SDK shares its state only when the page uses a test key, when you configure it with
enableLogging: true, or while the BillDog toolbar is open on that page (launched from the dashboard or the extension). Otherwise it reports only its name and version. - Open toolbar: sends the page's origin and path (never its query string) and your saved project ID, if any, to billdog.io, where your signed-in session checks the project's toolbar allowlist and opens the toolbar there.
- The debugger reads the top frame only, so an SDK running inside an iframe isn't shown. It reads
@billdog.io/web; a page that runs only@billdog.io/analyticsshows "No BillDog SDK".
Best Practices
- Ship only the public key (
bd_public_…) in client code; never the secret key - Track all user interactions for analytics insights
- Implement proper error handling for network failures
- Fetch paywalls ahead of time with
fetchPaywallfor critical user journeys - Use TypeScript for better type safety
Next Steps
- BillDog Auth — sign users in, and gate features on the token instead of a round-trip
- Auth Quickstart — a working web sign-in in one page
- Verifying Tokens — the server side, with no network call on your request path
Was this page helpful?
Or rate this page: