Code Examples
Curated, tested code snippets for common BillDog integration patterns. Most examples are shown in several languages using tab switching.
Initialize SDK & Fetch Paywall
import BillDogFull
// Initialize in AppDelegate or App init
BillDog.shared.configure(config: BillDogConfig(apiKey: "YOUR_API_KEY"))
// Present the paywall registered for a placement
func showPaywall() {
BillDog.shared.register(placement: "onboarding") { result in
switch result {
case .entitled:
print("User already entitled — no paywall shown")
case .purchased(let productId):
print("Purchased: \(productId)")
case .restored:
print("Purchases restored")
case .dismissed:
print("Paywall dismissed")
case .error(let error):
print("Failed to present paywall: \(error)")
default:
break
}
}
}Handle Purchase Callback
// Observe purchase outcomes with a PaywallPresentationHandler
let handler = PaywallPresentationHandler()
handler.onPurchaseSuccess = { productId in
print("Purchased: \(productId)")
// Unlock content or navigate
return .close
}
handler.onDismiss = { _ in print("Paywall dismissed") }
handler.onError = { error in print("Paywall error: \(error)") }
// Attach the handler when presenting the placement's paywall
Task {
let paywallVC = try await BillDog.shared.getPaywall(
forPlacement: "onboarding",
handler: handler
)
present(paywallVC, animated: true)
}Check Entitlement Status
// Fast synchronous check against cached customer state
let hasAccess = BillDog.shared.hasEntitlement("premium")
// Get detailed entitlement info from CustomerInfo
let info = try await BillDog.shared.getCustomerInfo()
if let entitlement = info.entitlements.first(where: { $0.identifier == "premium" }) {
print("Active: \(entitlement.isActive)")
print("Expires: \(entitlement.expiresAt ?? "never")")
print("Products: \(entitlement.productIds)")
}Track Custom Events
// Track a custom event (top-level convenience)
BillDog.shared.trackEvent("tutorial_completed", properties: [
"step_count": 5,
"duration_seconds": 120,
])
// Revenue lives on the analytics module. Register it once at startup:
// let analytics = BillDogAnalyticsManager()
// BillDog.shared.use(module: analytics)
analytics.trackRevenue(
amount: 9.99,
currency: "USD",
productId: "premium_monthly"
)Set User Properties
// Identify the user (top-level)
BillDog.shared.setUserId("user_12345")
// User properties live on the analytics module (see setup above)
analytics.setUserProperties([
"plan": "free",
"signup_date": "2025-01-15",
"app_version": "2.1.0",
"preferred_language": "en",
])Signing a user in with BillDog Auth does not switch the SDK’s current customer. The session is separate from analytics identity, so make the identify call above yourself after sign-in, passing the token’s sub claim — the user who signed in — or the SDK carries on with the anonymous id it already had.
Sign a user in
Web sign-in with @billdog.io/auth. The session token it issues lasts about 90 seconds and the SDK refreshes it for you; it is held in memory only, never in localStorage. Auth also ships on iOS, Android, React Native, Expo and Flutter — see the Auth quickstart.
import { 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();
const result = await auth.attempt({
identifier: 'ada@example.com',
strategy: 'password',
password: '…',
});
// ALWAYS check this before reading the session — it is null when 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);
}Verify a token on your backend
verifyToken() is a local signature check against a cached JWKS, so a hot route pays no network call. The environment option defaults to 'production', and that default is a security control: sandbox and production identities are different people in BillDog, so a backend serving real users must refuse a sandbox token even though it is genuinely signed. Use hasEntitlement() rather than reading ent yourself — the claim is capped at 64 entitlements and sets ent_truncated once it is cut. The full claim set is in Verifying Tokens.
import { verifyToken, hasEntitlement, BillDogAuthError } from 'billdogeng-node';
app.use(async (req, res, next) => {
try {
const claims = await verifyToken(req.headers.authorization!.slice(7), {
projectId: process.env.BILLDOG_PROJECT_ID!,
environment: 'production', // defaults to 'production'
});
if (!hasEntitlement(claims, 'pro')) return res.status(403).end();
req.userId = claims.sub; // the person who signed in
req.customerId = claims.cus; // the record they own, for joining BillDog data
next();
} catch (e) {
if (e instanceof BillDogAuthError) return res.status(401).end();
throw e;
}
});Was this page helpful?
Or rate this page: