Headless Paywalls (BYO-UI)
Bring Your Own UI
In headless mode the server decides what to sell to this caller and your app decides how to show it. You ask for a placement with getOffering(placement), the server answers with the selected offering and a presentation decision, you draw the screen, and you hand the chosen package back to the SDK to purchase.
Hosted vs. Headless
Hosted mode
BillDog renders the wall you designed in the Paywall Builder
paywall.configurations) and the offering it sells.Headless mode
Your code renders; BillDog resolves and bills
How a headless read works
Ask
The SDK posts render_mode: "headless" to get-wall-for-placement
Resolve
Campaign, audience, experiment arm and offering are decided on the server
Render
Your UI shows the packages; native SDKs attach live store prices
Purchase
The SDK runs the store flow; the server validates the receipt and grants entitlements
The request. POST /functions/v1/get-wall-for-placement withrender_mode: "headless". placement_identifier is optional: omit it (getOfferings()) and the server picks the project's offering for this caller, an audience-matched offering first, else the one flagged default, else the current one. Name it (getOffering(placement)) and the server resolves that placement. Never send the literal placement default.
The response. data is { mode: 'headless', placement, paywall: null, offering, offerings, entitlements, experiment, campaign, presentation, web_enabled, web_slug }. A headless read never creates a placement row and never reads or returns a wall.
Reading the result
offering is the selection, and it can be null
offering is exactly what the server selected for this caller. In offerings,is_current is true on that one offering and false on every other; is_defaultis the stored flag. When offering is null nothing was selected. Show nothing. Do not pick an entry from offerings in its place, and do not fall back to the current offering.
presentation: gated, holdout, withheld
gated: reaching this placement requires access; in headless mode your app owns the gate.holdout: this caller is in a holdout group, present nothing.withheld (sent only when true) with withheld_reason of holdout oraudience_excluded: offering is null because this caller was excluded, not because nothing is configured. All three arrive as HTTP 200. The 403 PLACEMENT_ACCESS_WITHHELD refusal is a hosted-mode answer.
Unknown placement is a typed error
A placement the project does not have answers 404 PLACEMENT_NOT_FOUND witherror.details.placement_identifier. It is never answered with the default offering, so a typo cannot sell the wrong thing. Each SDK surfaces it as a typed error (see the tabs below).
entitlements is a catalogue
entitlements lists what the project can grant (id, identifier,display_name, description). It is not what this caller holds. Read the caller's grants from customer info or check-entitlement.
Who is the caller?
X-BillDog-Device andX-BillDog-Device-Key) and, when the user is signed in with BillDog Auth, the session (X-BillDog-Session) on every request. Purchases and customer reads are attributed to the proven customer, never to an id typed into the request body.Offering and package wire shape
Offerings are snake_case on the wire. Each SDK maps them to its own model (camelCase on iOS, Android, React Native, Flutter and web). The native SDKs attach the live store product to each package asstoreProduct / product.
{
"id": "7b8d4f23-…",
"identifier": "premium_tier",
"display_name": "Premium Plan",
"description": null,
"is_current": true,
"is_default": false,
"metadata": { "cta_label": "Unlock Everything" },
"version": 1,
"packages": [ … ]
}{
"id": "e2a7c1d4-…",
"identifier": "annual",
"package_identifier": "annual",
"package_type": "annual",
"position": 0,
"metadata": { "badge": "Best Value" },
"app_store_promo_offer_id": null,
"play_offer_id": null,
"product": {
"id": "5f0b3e9a-…",
"product_identifier": "premium_annual",
"display_name": "Premium Annual",
"product_type": "subscription",
"subscription_period": "yearly",
"trial_duration_days": 7,
"price_usd": 49.99,
"app_store_product_id": "com.app.premium.annual",
"play_store_product_id": "premium_annual",
"stripe_price_id": "price_…"
}
}Platform samples
iOS (SwiftUI)
BillDog.shared.getOffering(placement:) returns a PlacementOffering(offering, presentation, placement, experiment,campaign, shouldPresent). purchase(package:) returns aPurchaseResult. Both throw BillDogError.
import SwiftUI
import BillDogFull
struct HeadlessPaywallView: View {
let placement = "onboarding"
@State private var result: PlacementOffering?
@State private var selectedPackage: Package?
@State private var isPurchasing = false
@State private var errorMessage: String?
@Environment(\.dismiss) private var dismiss
var body: some View {
VStack(spacing: 20) {
Text("Unlock Pro Access")
.font(.largeTitle.bold())
if let result {
if result.shouldPresent, let offering = result.offering {
ForEach(offering.packages, id: \.identifier) { pkg in
Button {
selectedPackage = pkg
} label: {
HStack {
VStack(alignment: .leading) {
Text(pkg.resolvedDisplayName).font(.headline)
if pkg.hasFreeTrial {
Text("Free trial included").font(.caption)
}
}
Spacer()
Text(pkg.localizedPriceString).font(.title3.bold())
}
.padding()
.background(selectedPackage?.identifier == pkg.identifier
? Color.blue.opacity(0.1) : Color(.systemGray6))
.cornerRadius(12)
}
.buttonStyle(.plain)
}
} else if result.presentation.holdout {
// Holdout: this user is deliberately shown nothing.
Text("Nothing to show right now")
} else {
// Withheld or no offering configured: do not fall back to another offering.
Text("No plan is available")
}
} else {
ProgressView()
}
Spacer()
if let errorMessage {
Text(errorMessage).font(.caption).foregroundColor(.red)
}
Button {
guard let pkg = selectedPackage else { return }
purchase(package: pkg)
} label: {
if isPurchasing { ProgressView() } else { Text("Continue").frame(maxWidth: .infinity) }
}
.buttonStyle(.borderedProminent)
.disabled(selectedPackage == nil || isPurchasing)
Button("Restore Purchases") { restore() }
.font(.footnote)
}
.padding()
.task { await load() }
.onDisappear {
BillDog.shared.trackPaywallDismissed(offering: result?.offering, placement: placement)
}
}
private func load() async {
do {
let resolved = try await BillDog.shared.getOffering(placement: placement)
result = resolved
selectedPackage = resolved.offering?.packages.first
if resolved.shouldPresent {
BillDog.shared.trackPaywallPresented(offering: resolved.offering, placement: placement)
}
} catch BillDogError.placementNotFound {
errorMessage = "Placement '\(placement)' does not exist in this project."
} catch {
errorMessage = error.localizedDescription
}
}
private func purchase(package: Package) {
isPurchasing = true
errorMessage = nil
Task {
defer { isPurchasing = false }
do {
switch try await BillDog.shared.purchase(package: package) {
case .purchased, .restored:
if BillDog.shared.hasEntitlement("pro") { dismiss() }
case .cancelled:
break
case .pending:
errorMessage = "Waiting for approval."
case .failed(let error):
errorMessage = error.message
}
} catch {
errorMessage = error.localizedDescription
}
}
}
private func restore() {
Task {
do {
if case .restored = try await BillDog.shared.restore(),
BillDog.shared.hasEntitlement("pro") {
dismiss()
}
} catch {
errorMessage = error.localizedDescription
}
}
}
}Android (Jetpack Compose)
BillDog is a Kotlin object. BillDog.getOffering(placement) returns aPlacementOffering and throws BillDogException (its error is the typedBillDogError, for example PlacementNotFound). BillDog.purchase(activity, pkg)returns a PurchaseResult.
package com.example.app.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import android.app.Activity
import io.billdog.core.BillDog
import io.billdog.core.BillDogError
import io.billdog.core.BillDogException
import io.billdog.core.PurchaseResult
import io.billdog.core.RestoreResult
import io.billdog.core.models.Package
import io.billdog.core.models.PlacementOffering
import kotlinx.coroutines.launch
@Composable
fun HeadlessPaywallScreen(
placement: String = "onboarding",
onSuccess: () -> Unit
) {
val scope = rememberCoroutineScope()
val activity = LocalContext.current as Activity
var result by remember { mutableStateOf<PlacementOffering?>(null) }
var selectedPackage by remember { mutableStateOf<Package?>(null) }
var isLoading by remember { mutableStateOf(false) }
var errorMessage by remember { mutableStateOf<String?>(null) }
LaunchedEffect(placement) {
try {
val resolved = BillDog.getOffering(placement)
result = resolved
selectedPackage = resolved.offering?.packages?.firstOrNull()
if (resolved.shouldPresent) {
BillDog.trackPaywallPresented(resolved.offering, placement)
}
} catch (e: BillDogException) {
errorMessage = when (e.error) {
is BillDogError.PlacementNotFound -> "Placement '$placement' does not exist in this project."
else -> e.error.message
}
}
}
DisposableEffect(placement) {
onDispose { BillDog.trackPaywallDismissed(result?.offering, placement) }
}
suspend fun hasPro(): Boolean =
BillDog.getCustomerInfo(forceRefresh = true).getOrNull()?.hasEntitlement("pro") == true
Column(modifier = Modifier.fillMaxSize().padding(24.dp)) {
Text("Choose Your Plan", style = MaterialTheme.typography.headlineMedium)
Spacer(Modifier.height(16.dp))
val resolved = result
when {
resolved == null -> CircularProgressIndicator()
resolved.shouldPresent -> resolved.offering?.packages?.forEach { pkg ->
val isSelected = selectedPackage?.identifier == pkg.identifier
Card(
modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp).clickable { selectedPackage = pkg },
colors = CardDefaults.cardColors(
containerColor = if (isSelected) MaterialTheme.colorScheme.primaryContainer
else MaterialTheme.colorScheme.surface
)
) {
Row(Modifier.padding(16.dp).fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text(pkg.storeProduct?.title ?: pkg.identifier, style = MaterialTheme.typography.titleMedium)
Text(pkg.localizedPriceString, style = MaterialTheme.typography.titleLarge)
}
}
}
resolved.presentation.holdout -> Text("Nothing to show right now")
else -> Text("No plan is available") // withheld, or no offering configured
}
Spacer(Modifier.weight(1f))
errorMessage?.let { Text(it, color = MaterialTheme.colorScheme.error) }
Button(
onClick = {
val pkg = selectedPackage ?: return@Button
isLoading = true
scope.launch {
try {
when (val purchase = BillDog.purchase(activity, pkg)) {
is PurchaseResult.Purchased, is PurchaseResult.Restored -> if (hasPro()) onSuccess()
is PurchaseResult.Cancelled -> Unit
is PurchaseResult.Pending -> errorMessage = "Waiting for approval."
is PurchaseResult.Failed -> errorMessage = purchase.error.message
}
} finally {
isLoading = false
}
}
},
modifier = Modifier.fillMaxWidth(),
enabled = selectedPackage != null && !isLoading
) { Text(if (isLoading) "Working…" else "Subscribe Now") }
TextButton(
onClick = {
scope.launch {
when (val restored = BillDog.restorePurchases()) {
is RestoreResult.Restored -> if (hasPro()) onSuccess()
is RestoreResult.Failed -> errorMessage = restored.error.message
}
}
},
modifier = Modifier.fillMaxWidth()
) { Text("Restore Purchases") }
}
}React Native
BillDog.getOffering(placement) returns an OfferingResult and rejects withPlacementNotFoundError or BillDogApiError. BillDog.purchasePackage(pkg)and BillDog.restore() never throw: they resolve a PurchaseResult /RestoreResult discriminated on type.
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, ActivityIndicator, StyleSheet } from 'react-native';
import {
BillDog,
PlacementNotFoundError,
type OfferingResult,
type Package,
} from '@billdog.io/react-native';
const PLACEMENT = 'onboarding';
export function HeadlessPaywall({ onPurchased }: { onPurchased: () => void }) {
const [result, setResult] = useState<OfferingResult | null>(null);
const [selectedPackage, setSelectedPackage] = useState<Package | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let offeringShown: OfferingResult['offering'] = null;
(async () => {
try {
const resolved = await BillDog.getOffering(PLACEMENT);
setResult(resolved);
setSelectedPackage(resolved.offering?.packages[0] ?? null);
const { holdout, withheld } = resolved.presentation;
if (resolved.offering && !holdout && !withheld) {
offeringShown = resolved.offering;
BillDog.trackPaywallPresented(resolved.offering, resolved.placement);
}
} catch (e) {
setError(e instanceof PlacementNotFoundError
? `Placement '${PLACEMENT}' does not exist in this project.`
: (e as Error).message);
}
})();
return () => {
if (offeringShown) BillDog.trackPaywallDismissed(offeringShown, PLACEMENT);
};
}, []);
const hasPro = async () => {
const info = await BillDog.getCustomerInfo();
return info?.entitlements.some((e) => e.identifier === 'pro' && e.isActive) ?? false;
};
const handlePurchase = async () => {
if (!selectedPackage) return;
setLoading(true);
const purchase = await BillDog.purchasePackage(selectedPackage);
setLoading(false);
switch (purchase.type) {
case 'purchased':
case 'restored':
if (await hasPro()) onPurchased();
break;
case 'cancelled':
break;
case 'pending':
setError('Waiting for approval.');
break;
case 'failed':
setError(purchase.error.message);
break;
}
};
const handleRestore = async () => {
const restored = await BillDog.restore();
if (restored.type === 'failed') setError(restored.error.message);
else if (await hasPro()) onPurchased();
};
if (!result) return <ActivityIndicator />;
const { offering, presentation } = result;
const showOffering = offering && !presentation.holdout && !presentation.withheld;
return (
<View style={styles.container}>
<Text style={styles.title}>Unlock Premium</Text>
{showOffering ? offering.packages.map((pkg) => (
<TouchableOpacity
key={pkg.identifier}
style={[styles.packageCard, selectedPackage?.identifier === pkg.identifier && styles.selectedCard]}
onPress={() => setSelectedPackage(pkg)}
>
<Text style={styles.packageName}>{pkg.product?.displayName ?? pkg.identifier}</Text>
<Text style={styles.price}>{pkg.product?.priceString ?? ''}</Text>
</TouchableOpacity>
)) : (
// Holdout, withheld, or nothing configured: show nothing else in its place.
<Text style={styles.subtitle}>{presentation.holdout ? 'Nothing to show right now' : 'No plan is available'}</Text>
)}
{error && <Text style={styles.error}>{error}</Text>}
<TouchableOpacity style={styles.buyButton} disabled={!selectedPackage || loading} onPress={handlePurchase}>
{loading ? <ActivityIndicator color="#fff" /> : <Text style={styles.buyText}>Subscribe</Text>}
</TouchableOpacity>
<TouchableOpacity onPress={handleRestore}>
<Text style={styles.restoreText}>Restore Purchases</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 24, justifyContent: 'center' },
title: { fontSize: 28, fontWeight: 'bold', textAlign: 'center', marginBottom: 8 },
subtitle: { fontSize: 16, color: '#666', textAlign: 'center', marginBottom: 24 },
packageCard: { flexDirection: 'row', justifyContent: 'space-between', padding: 16, borderRadius: 12, borderWidth: 1, borderColor: '#ddd', marginBottom: 12 },
selectedCard: { borderColor: '#0066FF', backgroundColor: '#F0F7FF' },
packageName: { fontSize: 16, fontWeight: '600' },
price: { fontSize: 18, fontWeight: 'bold' },
error: { color: '#c00', marginTop: 8 },
buyButton: { backgroundColor: '#0066FF', padding: 16, borderRadius: 12, alignItems: 'center', marginTop: 16 },
buyText: { color: '#fff', fontSize: 16, fontWeight: 'bold' },
restoreText: { textAlign: 'center', marginTop: 16, color: '#666' },
});Flutter
Methods are instance methods on BillDog.shared. getOffering(placement) never throws: it returns a sealed OfferingResult (OfferingAvailable, OfferingHoldout,OfferingWithheld, OfferingNotConfigured, OfferingFailed).purchasePackage(pkg) returns a sealed PurchaseResult.
import 'package:flutter/material.dart';
import 'package:billdog_flutter/billdog_flutter.dart';
class HeadlessPaywallPage extends StatefulWidget {
const HeadlessPaywallPage({super.key});
@override
State<HeadlessPaywallPage> createState() => _HeadlessPaywallPageState();
}
class _HeadlessPaywallPageState extends State<HeadlessPaywallPage> {
static const placement = 'onboarding';
OfferingResult? _result;
Package? _selectedPackage;
bool _loading = false;
String? _error;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final result = await BillDog.shared.getOffering(placement);
setState(() {
_result = result;
if (result is OfferingAvailable) {
_selectedPackage = result.offering.packages.firstOrNull;
} else if (result is OfferingFailed) {
final error = result.error;
_error = error is PlacementNotFoundError
? "Placement '$placement' does not exist in this project."
: error.message;
}
});
if (result is OfferingAvailable) {
await BillDog.shared.trackPaywallPresented(offering: result.offering, placement: placement);
}
}
@override
void dispose() {
BillDog.shared.trackPaywallDismissed(offering: _result?.offeringOrNull, placement: placement);
super.dispose();
}
Future<bool> _hasPro() async {
final info = await BillDog.shared.getCustomerInfo(policy: CacheFetchPolicy.fetchCurrent);
return info.hasEntitlement('pro');
}
Future<void> _purchase() async {
final pkg = _selectedPackage;
if (pkg == null) return;
setState(() => _loading = true);
final purchase = await BillDog.shared.purchasePackage(pkg);
setState(() => _loading = false);
switch (purchase) {
case Purchased() || Restored():
if (await _hasPro() && mounted) Navigator.pop(context);
case Cancelled():
break;
case Pending():
setState(() => _error = 'Waiting for approval.');
case Failed(:final error):
setState(() => _error = error.message);
}
}
Future<void> _restore() async {
switch (await BillDog.shared.restorePurchases()) {
case RestoredItems():
if (await _hasPro() && mounted) Navigator.pop(context);
case RestoreFailed(:final error):
setState(() => _error = error.message);
}
}
@override
Widget build(BuildContext context) {
final result = _result;
return Scaffold(
appBar: AppBar(title: const Text('Upgrade to Pro')),
body: Padding(
padding: const EdgeInsets.all(20),
child: Column(
children: [
if (result == null)
const CircularProgressIndicator()
else
switch (result) {
OfferingAvailable(:final offering) => Column(
children: offering.packages
.map((pkg) => RadioListTile<Package>(
title: Text(pkg.product?.name ?? pkg.identifier),
subtitle: Text(pkg.product?.localizedPrice ?? ''),
value: pkg,
groupValue: _selectedPackage,
onChanged: (val) => setState(() => _selectedPackage = val),
))
.toList(),
),
OfferingHoldout() => const Text('Nothing to show right now'),
// Withheld, not configured, or failed: never substitute another offering.
_ => const Text('No plan is available'),
},
const Spacer(),
if (_error != null) Text(_error!, style: const TextStyle(color: Colors.red)),
ElevatedButton(
onPressed: _loading || _selectedPackage == null ? null : _purchase,
child: _loading ? const CircularProgressIndicator() : const Text('Unlock Now'),
),
TextButton(onPressed: _restore, child: const Text('Restore Purchases')),
],
),
),
);
}
}Web (React)
@billdog.io/web default-exports a singleton; call configure once.getOffering(placement) returns an OfferingResult and throwsPlacementNotFoundError (from @billdog.io/core) for an unknown placement.purchaseProduct(productId) starts a Stripe web checkout and resolvestrue once the visitor has been handed to it; the purchase is recorded when the visitor returns. Pass the product's id.
import { useState, useEffect } from 'react';
import BillDog from '@billdog.io/web';
import { PlacementNotFoundError } from '@billdog.io/core';
import type { OfferingResult } from '@billdog.io/core';
BillDog.configure({ apiKey: 'bd_public_live_xxxxxxxx' });
export function WebPricingCards() {
const [result, setResult] = useState<OfferingResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
BillDog.getOffering('pricing_page')
.then((resolved) => {
setResult(resolved);
const { holdout, withheld } = resolved.presentation;
if (resolved.offering && !holdout && !withheld) {
BillDog.trackPaywallPresented(resolved.offering, resolved.placement);
}
})
.catch((e: unknown) => {
setError(e instanceof PlacementNotFoundError
? "Placement 'pricing_page' does not exist in this project."
: (e as Error).message);
});
}, []);
const handleCheckout = async (productId: string) => {
setLoading(true);
try {
// Redirects the browser to checkout. A server refusal is thrown as BillDogApiError.
const started = await BillDog.purchaseProduct(productId);
if (!started) setError('Checkout could not be started.');
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
};
if (error) return <p className="text-red-600">{error}</p>;
if (!result) return <p>Loading…</p>;
const { offering, presentation } = result;
if (!offering || presentation.holdout || presentation.withheld) {
// Nothing selected for this visitor. Do not show another offering in its place.
return <p>{presentation.holdout ? 'Nothing to show right now' : 'No plan is available'}</p>;
}
return (
<div className="grid md:grid-cols-2 gap-6 max-w-4xl mx-auto p-6">
{offering.packages.map((pkg) => (
<div key={pkg.identifier} className="border rounded-2xl p-6 flex flex-col justify-between">
<div>
<h3 className="text-xl font-bold">{pkg.product.title}</h3>
<p className="text-sm text-gray-500 mt-1">{pkg.product.description}</p>
<div className="text-3xl font-extrabold mt-4">{pkg.product.priceString}</div>
</div>
<button
onClick={() => handleCheckout(pkg.product.id)}
disabled={loading}
className="w-full mt-6 py-3 rounded-xl"
>
{loading ? 'Redirecting…' : 'Continue'}
</button>
</div>
))}
</div>
);
}Expo
Import from @billdog.io/expo: it re-exports the React Native SDK, so the result has the same shape (offering plus presentation) and packages carry product. The native module needs a development build; it is not in Expo Go.
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, ActivityIndicator, StyleSheet } from 'react-native';
import { BillDog, PlacementNotFoundError } from '@billdog.io/expo';
export function HeadlessPaywallModal({ placement = 'upgrade_screen', onSuccess }) {
const [result, setResult] = useState(null); // OfferingResult
const [selectedPackage, setSelectedPackage] = useState(null);
const [errorMessage, setErrorMessage] = useState(null);
const [purchasing, setPurchasing] = useState(false);
useEffect(() => {
let active = true;
// The offering this screen actually showed. A local, not state: the cleanup
// below runs with this render's closure, where state would still be null.
let offeringShown = null;
(async () => {
try {
const resolved = await BillDog.getOffering(placement);
if (!active) return;
setResult(resolved);
const { holdout, withheld } = resolved.presentation;
if (resolved.offering && !holdout && !withheld) {
setSelectedPackage(resolved.offering.packages[0] ?? null);
offeringShown = resolved.offering;
BillDog.trackPaywallPresented(resolved.offering, resolved.placement);
}
} catch (err) {
if (!active) return;
setErrorMessage(err instanceof PlacementNotFoundError
? `Placement '${placement}' does not exist in this project.`
: err.message);
}
})();
return () => {
active = false;
if (offeringShown) BillDog.trackPaywallDismissed(offeringShown, placement);
};
}, [placement]);
const handlePurchase = async () => {
if (!selectedPackage || purchasing) return;
setPurchasing(true);
setErrorMessage(null);
// purchasePackage never throws: it resolves a PurchaseResult discriminated on `type`.
const purchase = await BillDog.purchasePackage(selectedPackage);
setPurchasing(false);
switch (purchase.type) {
case 'purchased':
case 'restored':
onSuccess?.();
break;
case 'cancelled':
break;
case 'pending':
setErrorMessage('Purchase is pending approval.');
break;
case 'failed':
setErrorMessage(purchase.error.message);
break;
}
};
const handleRestore = async () => {
const restored = await BillDog.restore();
if (restored.type === 'failed') setErrorMessage(restored.error.message);
else onSuccess?.();
};
if (!result && !errorMessage) {
return (
<View style={styles.center}>
<ActivityIndicator size="large" />
</View>
);
}
const offering = result?.offering ?? null;
const presentation = result?.presentation;
const showOffering = offering && !presentation.holdout && !presentation.withheld;
return (
<View style={styles.container}>
<Text style={styles.title}>Unlock Premium</Text>
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
{showOffering ? offering.packages.map((pkg) => (
<TouchableOpacity
key={pkg.identifier}
style={[styles.packageCard, selectedPackage?.identifier === pkg.identifier && styles.selectedCard]}
onPress={() => setSelectedPackage(pkg)}
>
<Text style={styles.pkgTitle}>{pkg.product?.displayName ?? pkg.identifier}</Text>
<Text style={styles.pkgPrice}>{pkg.product?.priceString ?? ''}</Text>
</TouchableOpacity>
)) : result ? (
// Holdout, withheld, or nothing configured: show nothing else in its place.
<Text style={styles.subtitle}>{presentation.holdout ? 'Nothing to show right now' : 'No plan is available'}</Text>
) : null}
<TouchableOpacity
style={[styles.buyBtn, (!selectedPackage || purchasing) && styles.disabledBtn]}
onPress={handlePurchase}
disabled={!selectedPackage || purchasing}
>
<Text style={styles.buyBtnText}>{purchasing ? 'Processing…' : 'Subscribe Now'}</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.restoreBtn} onPress={handleRestore}>
<Text style={styles.restoreBtnText}>Restore Purchases</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: { padding: 24, flex: 1, justifyContent: 'center' },
center: { flex: 1, alignItems: 'center', justifyContent: 'center' },
title: { fontSize: 24, fontWeight: 'bold', textAlign: 'center', marginBottom: 20 },
subtitle: { fontSize: 16, color: '#666', textAlign: 'center', marginBottom: 12 },
error: { color: 'red', textAlign: 'center', marginBottom: 12 },
packageCard: { padding: 16, borderWidth: 1, borderColor: '#ccc', borderRadius: 10, marginVertical: 8 },
selectedCard: { borderColor: '#6366f1', borderWidth: 2, backgroundColor: '#f5f3ff' },
pkgTitle: { fontSize: 16, fontWeight: '600' },
pkgPrice: { fontSize: 14, color: '#666', marginTop: 4 },
buyBtn: { backgroundColor: '#6366f1', padding: 16, borderRadius: 10, marginTop: 16, alignItems: 'center' },
disabledBtn: { opacity: 0.5 },
buyBtnText: { color: '#fff', fontSize: 16, fontWeight: '600' },
restoreBtn: { padding: 12, marginTop: 8, alignItems: 'center' },
restoreBtnText: { color: '#666', fontSize: 14 },
});Experiments and analytics in headless mode
1. Experiment attribution
The result carries experiment (experiment_id, variant_id,variant_name) and campaign. Experiment conversions are credited on the server: a customer's first verified purchase after their exposure counts for the arm they were on, on every platform, whatever the client sends. On iOS, Android, React Native and Flutter, packages are also stamped with the offering and placement they came from, so offering-level revenue reports name the exact offering a purchase was made from.
2. Impressions and dismissals
BillDog cannot see your view lifecycle, so call trackPaywallPresented(offering, placement)when the screen appears and trackPaywallDismissed(offering, placement) when it goes away. These emit paywall_presented / paywall_dismissed withoffering_id, offering_identifier and placement_identifier. Nopaywall_id is sent: a headless presentation has no wall, and an invented id would show up as a phantom wall in every per-paywall report.
Do not track an impression you did not show
trackPaywallPresented when offering is non-null and the caller is neither in a holdout nor withheld. A holdout is measured by the absence of an impression.A read is an exposure
Web checkout from a custom paywall
A native paywall can send the user to BillDog web checkout instead of the store. The SDK opens the checkout in an in-app browser; when the app receives the return link the redemption token is redeemed and the entitlement granted.
// iOS — opens the checkout in a Safari sheet; resolves the redemption token once the return link arrives
let redemptionToken = try await BillDog.shared.purchaseViaWeb(productId: productId, from: viewController)
let redemption = try await BillDog.shared.redeemPurchase(token: redemptionToken)
// Android — resolves when the Custom Tab opens; the purchase completes on the return link
val opened = BillDog.purchaseViaWeb(context, productId, appUserId)
// React Native — 'completed' | 'opened' | 'failed'
const status = await BillDog.purchaseViaWeb(productId);
// Flutter — WebCheckoutResult with status completed | opened | cancelled | failed
final result = await BillDog.shared.purchaseViaWeb(productId);See the Web Checkout guide for the deep-link setup each platform needs.
Headless over REST (games, TV, desktop, custom engines)
Building for Unity, Unreal, Godot, a TV platform or a desktop app without an official SDK? Every SDK above is a client of the same endpoint, and you can call it directly. Official Unity, Roku, Capacitor, Cordova and Kotlin Multiplatform SDKs are coming soon; Roku Pay purchases are not supported yet.
1. Give the install a device proof
A public key says which project is asking, not who the player is. Generate a device id and device key once per install, store them with the app's other secrets, and send both on every request:
X-BillDog-Device:$BillDogAnonymousID:followed by a random UUID.X-BillDog-Device-Key:bdk_followed by 32 random bytes in base64url without padding (43 characters).
BillDog binds the key the first time it sees the device id, and that becomes the player's anonymous customer. Never regenerate the key for an id you already sent. If the pair is lost or refused, generate a new pair: the player becomes a new anonymous customer and gets purchases back with a restore (posting the store receipt). Without a proof, an offering read is still answered, but purchases, restores, entitlement checks and customer reads are refused with 403 PROOF_REQUIRED. A signed-in BillDog Auth user sends X-BillDog-Session instead.
2. Read the placement
curl -X POST https://api.billdog.io/v1/get-wall-for-placement \
-H "Content-Type: application/json" \
-H "X-BillDog-API-Key: bd_public_live_your_api_key_here" \
-H 'X-BillDog-Device: $BillDogAnonymousID:6f1c2e9a-4b7d-4e2a-9c51-0d3f8a6b2e17' \
-H "X-BillDog-Device-Key: bdk_<43 base64url characters>" \
-d '{
"render_mode": "headless",
"placement_identifier": "onboarding",
"platform": "unity",
"app_version": "2.4.0"
}'platformis required. It decides which store's packages come back:ios,android,web,amazon,roku, orunityfor a player with no mobile store (Editor, desktop, WebGL). A missing or unknown value is 400.placement_identifieris optional in headless mode. Without it you get the project's offering for this caller.- Optional targeting inputs:
country,app_version,custom_attributes. - The response is the shape described in Reading the result:
offeringis the selection,presentationcarries holdout, withheld and gated, andpaywallis alwaysnull.
3. Purchases, entitlements and impressions
- Store purchases made with your own store code (for example Unity IAP): post the receipt to
/process-purchasewith the same device proof. - Web checkout:
/create-web-checkoutreturns a hosted Stripe checkout URL for a product. - Access:
/check-entitlementwith the device proof answers whether this player holds an entitlement. - Impressions: send
paywall_presented/paywall_dismissedthrough/ingest-eventswithoffering_id,offering_identifierandplacement_identifier, and nopaywall_id.
Request and response bodies for each endpoint are in the API reference.
Errors to handle
- 404
PLACEMENT_NOT_FOUND: the placement does not exist in this project. It is never answered with another offering. - 401
PROOF_INVALID: the device id or key is malformed, unknown or revoked. Do not retry with the same pair; generate a new one. - 403
PROOF_REQUIRED: the call needs a device proof, a session or a secret key, and the request had none. - 409
PURCHASE_OWNER_CONFLICT: the receipt belongs to another customer and the project's collision policy does not let it move.
Breaking changes in this release
This release consolidates placement delivery and customer authority. BillDog has no obligation to earlier SDK versions, so nothing below is dual-accepted: update your app in one step.
Every platform
- Existing installs become a new guest on upgrade. Every SDK now generates a device key and sends it with the anonymous id on every request; an old anonymous id cannot be proven, so the server sees a new anonymous customer. A signed-in BillDog Auth user keeps their customer. Purchases follow the store receipt: a restore or a new purchase posts the receipt and the purchase moves to the proven customer.
- Host apps with their own login that want a purchase attributed to their user id need BillDog Auth (the SDK sends the session) or a secret-key call from their server that names the customer. Typing your user id into the client SDK's
app_user_idno longer attributes anything by itself. - The static identity hash is removed. Any request presenting
X-BillDog-Identity-Hashor a bodyidentity_hashis refused with 401PROOF_INVALID. - Offering reads go through
get-wall-for-placementwithrender_mode: "headless". The endpointsfetch-offering,fetch-offerings-for-placement,get-placement-config,get-placement-offeringandcreate-app-to-web-checkoutare deleted. Offering.paywallis gone on every platform: a headless read never returns a wall.- Holdout, withheld and empty are answers, not fallbacks: no SDK substitutes the current offering when the server selected none.
- Impressions of a paywall you draw yourself are
trackPaywallPresented/trackPaywallDismissed; they carry nopaywall_id. - New wire errors on customer-scoped endpoints:
PROOF_REQUIRED(403),PROOF_INVALID(401),REAUTH_REQUIRED(403),ACCESS_DENIEDwithreason: target_mismatch(403),PURCHASE_OWNER_CONFLICT(409),PLACEMENT_NOT_FOUND(404). record-external-purchasenow answers the standard nested error envelope{ success: false, error: { code, message, details } }instead of a flat{ error, error_code }body.- Account deletion is
deleteAccount()on each platform's BillDog Auth module; the server erases the account only for a session signed in within the last 15 minutes.
iOS (BillDogFull)
BillDog.shared.getOffering(placement:)returnsPlacementOffering(offering,presentation,placement,experiment,campaign,shouldPresent) instead ofOffering?.OfferingManager.getOfferingForPlacement(placementId:)returns the same type.Offering.paywallremoved.BillDogErrorgained typed casesproofRequired,proofInvalid,reauthenticationRequired,targetMismatch,purchaseOwnerConflict,placementAccessWithheld,placementNotFound, each withserverErrorCode.- New:
BillDog.shared.deviceProof,trackPaywallPresented(offering:placement:),trackPaywallDismissed(offering:placement:),BillDogAuth.shared.deleteAccount()/deleteAccountDetailed(),BillDog.shared.handleWebCheckout(url:). - RevenueCat:
BillDogRevenueCat.connect(…)andRevenueCatAdapterare replaced byBillDogRevenueCat.configure(config:…), which configures BillDog with RevenueCat as its purchase controller.
Android (io.billdog:billdog-core)
BillDog.getOffering(placement)returnsPlacementOfferingand throwsBillDogException(error, cause, statusCode, errorCode);OfferingManager.getOfferingForPlacementno longer returnsResult<Offering?>.Offering.paywallandPreviewPaywallResult.isDraft/projectNameremoved.BillDogErrorgainedProofRequired,ProofInvalid,ReauthenticationRequired,TargetMismatch,PurchaseOwnerConflict,PlacementAccessWithheld,PlacementNotFoundand publicCODE_*constants. New outcomes:DeepLinkResult.CheckoutFailed,RedemptionOutcome.Refused,PurchaseError.Refused.- New:
BillDog.getDeviceProof(),BillDog.executeAction(…),trackPaywallPresented/trackPaywallDismissed,BillDog.completeWebCheckout(uri),BillDogConfig.customUrlScheme,BillDogAuth.deleteAccount()(throwsApiException(message, statusCode, errorCode, authorityError)). - Trial eligibility is never answered eligible locally; it comes from the server.
Web (@billdog.io/core, @billdog.io/web, @billdog.io/auth)
getOffering(placement)returnsOfferingResult(offering,offerings,placement,presentation,experiment,campaign,entitlements) and throwsPlacementNotFoundError/PlacementAccessWithheldError/BillDogApiError.getOfferings()andgetCurrentOffering()are the project-default read.Offeringis one camelCase model (id,identifier,displayName,description,isCurrent,isDefault,packages,metadata); nopaywall.- Device proof is generated and sent automatically (
deviceProof.ts); newrotateDeviceProof(),peekDeviceProof(),BillDogApiError,BILLDOG_AUTHORITY_ERROR_CODES,shouldRotateDeviceProof(). @billdog.io/auth:attachTo(client)now also reads the client's device proof; newdeleteAccount(),BillDogReauthRequiredError;BillDogAuthErrorcarriesreasonanddetails.
React Native / Expo (@billdog.io/react-native, @billdog.io/expo)
- New headless reads
BillDog.getOffering(placement)(OfferingResult, rejects withPlacementNotFoundError/BillDogApiError),getOfferings(),getCurrentOffering(); one camelCaseOffering/Package/PackageProductmodel. - New
BillDogAuth.deleteAccount(),trackPaywallPresented/trackPaywallDismissed, and the Superwall bridgecreateSuperwallPurchaseController.
Flutter (billdog_flutter)
- New instance methods on
BillDog.shared:getOffering(placement)andgetOfferings()return a sealedOfferingResult(OfferingAvailable,OfferingHoldout,OfferingWithheld,OfferingNotConfigured,OfferingFailed);purchasePackage(package)returnsPurchaseResult. hasAccessForPlacement(placementId)is nowFuture<bool>: it asks the server and answersfalseon any failure (the placement's required entitlement, or any active one). NewServerRefusalErrorsubclasses (ProofRequiredError,ProofInvalidError,ReauthRequiredError,AccessDeniedError,PlacementNotFoundError,PurchaseOwnerConflictError),BillDogAuth.instance.deleteAccount(), and the optional packagebilldog_superwall.
Other platforms and custom engines (REST)
Direct REST callers need the same device proof the SDKs send: see Headless over REST.
Was this page helpful?
Or rate this page: