Android SDK Integration Guide
🎨 Unified Monetization, Engagement & Data SDK
BillDog is a modular Android SDK combining Paywalls & Billing, Product Analytics, In-App Messaging, and Surveys. Only import the modules you need to keep your build sizes minimal.
Overview & Core Architecture
BillDog is split into separate Gradle modules, so you add only the features you use. The Core module manages customer profiles, cached entitlements, and client network state. Feature modules plug in seamlessly to enable rich UI paywalls, user surveys, session replay, and push notifications.
Project-Scoped Identifiers
bd_public_test_…) for sandbox and a live key (bd_public_live_…) for production, and the identifier names stay the same when you switch between them. There is no staging key; leave environment at PRODUCTION — Environment.STAGING points at a host that is not publicly available. Use the public key in the app; the secret key (bd_secret_…) is for your server only, never ship it.1. Configure Repositories & Dependencies
Requirements: minSdk 21 or higher, and JDK 17 — the modules are compiled for JVM target 17, so set jvmTarget to 17 in your app module too.
BillDog publishes to Maven Central, so no extra repository or credentials are needed — confirm your settings.gradle resolves from it:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
}
}Import only the modules your application needs:
dependencies {
// Compose UI paywalls (brings billdog-core with it)
implementation("io.billdog:billdog-compose:1.2.0-beta.1")
// Google Play Billing. billdog-compose does NOT include it: without this
// line the SDK loads no store products and every purchase fails.
implementation("io.billdog:billdog-paywall:1.2.0-beta.1")
// Optional Features
implementation("io.billdog:billdog-analytics:1.2.0-beta.1")
implementation("io.billdog:billdog-replay:1.2.0-beta.1")
implementation("io.billdog:billdog-survey-compose:1.2.0-beta.1")
implementation("io.billdog:billdog-inappmessages:1.2.0-beta.1")
implementation("io.billdog:billdog-notifications:1.2.0-beta.1")
}billdog-notifications merges these permissions into your app’s manifest: POST_NOTIFICATIONS, VIBRATE, WAKE_LOCK and RECEIVE_BOOT_COMPLETED. It declares no exact-alarm permission: local reminders are scheduled with WorkManager, and use an exact alarm only when your app declares SCHEDULE_EXACT_ALARM itself and the user allows it. Versions up to 1.1.1-beta.4 also declared USE_EXACT_ALARM, which Google Play restricts to apps whose core function is an alarm or calendar; on those versions remove it in your own manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission
android:name="android.permission.USE_EXACT_ALARM"
tools:node="remove" />
</manifest>2. Initialize BillDog
Configure the SDK once in your custom Application class. Traffic routes automatically to api.billdog.io. Register each feature module with BillDog.use(module), before or after BillDog.configure: a module registered first is handed the network client and the config when configure runs.
import io.billdog.core.BillDog
import io.billdog.core.BillDogConfig
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
BillDog.configure(
context = this,
apiKey = "YOUR_API_KEY_HERE",
config = BillDogConfig(
apiKey = "YOUR_API_KEY_HERE",
enableLogging = BuildConfig.DEBUG,
environment = BillDogConfig.Environment.PRODUCTION
)
)
// Then register feature modules, e.g. BillDog.use(BillDogAnalytics())
}
}Register the class in AndroidManifest.xml, or it never runs:
<application
android:name=".MyApplication"
... >
</application>3. Manage Customer Identity
This links a user you have already authenticated elsewhere. 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 in the token, so your backend gates a paid feature with a claim check instead of a round-trip. See the 🔐 Authentication module below.
Associate sessions with authenticated users to synchronize entitlement states and analytics across devices:
// Link session to authenticated account (suspend — call from a coroutine)
lifecycleScope.launch {
BillDog.identify("user_uuid_123")
}
// Reset identity on user logout (switches to a NEW anonymous ID, not the
// one this install had before sign-in)
BillDog.logOut()4. Check Entitlements & Customer Info
Verify feature access dynamically using cached customer details:
lifecycleScope.launch {
val result = BillDog.getCustomerInfo()
result.onSuccess { customerInfo ->
val hasPremium = customerInfo.entitlements.any { it.identifier == "premium" && it.isActive }
if (hasPremium) {
// Unlock features
}
}
result.onFailure { error ->
Log.e("BillDog", "Failed to retrieve entitlements", error)
}
}5. Restore Purchases
Give users a Restore Purchases action for a new device or a reinstall. restorePurchases() is a suspend function that re-reads the user’s Google Play purchases and returns a RestoreResult; a failure is returned as RestoreResult.Failed, not thrown. Refresh customer info afterwards so the UI reflects what was restored.
import io.billdog.core.RestoreResult
lifecycleScope.launch {
when (val result = BillDog.restorePurchases()) {
is RestoreResult.Restored -> Log.d("BillDog", "Restored ${result.items.size} purchase(s)")
is RestoreResult.Failed -> Log.e("BillDog", "Restore failed: ${result.error}")
}
BillDog.getCustomerInfo(forceRefresh = true).onSuccess { info ->
val hasPremium = info.hasEntitlement("premium")
}
}🔌 Feature Modules Guides
Click on any module below to view detailed code snippets and APIs:
💳 Paywalls & Billing (billdog-compose)
Display Native Compose Paywalls or route purchasing through your own billing provider:
1. Present Paywall Screen
import io.billdog.compose.compose // the .compose extension
import io.billdog.core.BillDog
import io.billdog.core.PaywallPresentationHandler
import io.billdog.core.PostPurchaseBehavior
// identifier is a PAYWALL identifier — not a placement, offering or product
BillDog.getInstance().compose.presentPaywall(
activity = this,
identifier = "premium_offer",
handler = PaywallPresentationHandler(
onPurchaseSuccess = { productId ->
Log.d("BillDog", "Purchased $productId")
PostPurchaseBehavior.CLOSE
}
)
) { shown, _ ->
// true once the paywall is on screen — this is NOT a purchase result
if (!shown) Log.w("BillDog", "Paywall could not be shown")
}2. Custom Purchase Controller (Stripe, Paddle, etc.)
BillDog.configure(
context = this,
apiKey = "...",
config = BillDogConfig(apiKey = "..."),
purchaseController = object : PurchaseController {
override suspend fun purchase(productId: String): PurchaseResult {
// Trigger Stripe or custom billing request
return PurchaseResult.Purchased(
transactionId = "txn_123",
productId = productId
)
}
override suspend fun restorePurchases(): RestoreResult {
return RestoreResult.Restored(items = listOf())
}
}
)BillDog records what Google Play can prove: a controller that completes a Play purchase (RevenueCat, your own BillingClient) is recorded from the device, and BillDog never acknowledges it — that stays your controller’s job. A sale billed outside Play (Stripe, Paddle) is never recorded from the app, because the app cannot prove it: set the product up as a custom product and record each sale from your server with your secret key (Custom Purchases, record-external-purchase). Until your server does, the buyer has no entitlement in BillDog.
3. Detailed Purchase Parameters (Google Play Billing)
val params = PurchaseParams.Builder("pro_yearly")
.offerToken(currentOfferToken)
.obfuscatedProfileId("profile-uuid")
.isPersonalizedOffer(true) // Play's EU "personalised price" disclosure
.build()
// purchase is a suspend function
lifecycleScope.launch {
val result = BillDog.purchase(this@MainActivity, params)
Log.d("BillDog", "Purchase result: $result")
}isPersonalizedOffer is the disclosure Play shows EU buyers when a price was personalised; leave it unset and BillDog discloses for every EEA storefront. appAccountToken is deprecated and ignored: BillDog always binds the purchase to the customer’s own store-account token, so ownership can never be set from the app.
A plan change names the subscription it replaces with oldProductId; BillDog finds that purchase and Play replaces exactly it. replacementMode sets how (default IMMEDIATE_WITH_TIME_PRORATION). Without oldProductId, replacementMode is ignored when nothing can stack: no other subscription is held (a first purchase), or the product is a one-time purchase. When one is held, in any state (including a payment still pending), the purchase fails with a ConfigurationError and buys nothing, because it would be a second subscription billing beside the first.
BillDog learns what is held from Play when billdog-paywall is linked, and otherwise from your purchase controller’s heldSubscriptions() (the RevenueCat adapter reads its CustomerInfo). A purchase that depends on it (a plan change, or a replacementMode without oldProductId) fails and buys nothing when nobody can say, naming the cause: StoreUnavailable when trying again can help, a ConfigurationError when it cannot (no billdog-paywall, and a controller that doesn’t report). Without billdog-paywall, a replacementMode without oldProductId also fails whenever a subscription is held, because BillDog cannot ask Play whether the product is one. A purchase with neither field is unaffected:
lifecycleScope.launch {
val result = BillDog.purchase(
this@MainActivity,
PurchaseParams.Builder("pro_yearly")
.oldProductId("pro_monthly")
.replacementMode(GoogleReplacementMode.DEFERRED)
.build()
)
}upgradeSubscription makes the same replacement of exactly currentProductId. If that subscription isn’t held, or can’t be replaced yet (payment pending, not acknowledged), it fails with a ConfigurationError naming what is held. With no currentProductId it replaces the one subscription that can be replaced (one whose payment is pending, or that isn’t acknowledged yet, is skipped), and fails when there are several: BillDog never guesses which plan to change.
lifecycleScope.launch {
val result = BillDog.upgradeSubscription(
activity = this@MainActivity,
newProductId = "pro_yearly",
currentProductId = "pro_monthly",
replacementMode = GoogleReplacementMode.IMMEDIATE_WITH_TIME_PRORATION
)
}upgradeSubscriptionWithToken(activity, newProductId, oldPurchaseToken) is the variant for when you already hold the old purchase token.
📊 Product Analytics (billdog-analytics)
Track custom events, record transactions, and configure compliance filters (GDPR / Play Console):
1. Track Events & Revenue
import io.billdog.core.BillDog
import io.billdog.analytics.BillDogAnalytics
val analytics = BillDogAnalytics()
BillDog.use(analytics)
// Custom Events (canonical top-level API)
BillDog.trackEvent("item_crafted", mapOf("recipe" to "iron_sword"))
// Revenue Tracking (analytics module)
analytics.trackRevenue(amount = 9.99, currency = "USD", productId = "gold_pack")2. Advanced Super Properties
// Register super properties (attached to all events)
analytics.registerSuperProperties(mapOf("device_type" to "tablet"))
// Register super properties ONLY if not already set
analytics.registerSuperPropertiesOnce(mapOf("initial_referrer" to "google"))
// Unregister a specific property
analytics.unregisterSuperProperty("initial_referrer")
// Clear all super properties
analytics.clearSuperProperties()3. Advanced User Property Operations
// User property set, list union, and incremental counters
analytics.setUserProperties(mapOf("membership" to "gold"))
analytics.incrementUserProperty("games_played", 1.0)
analytics.unionUserProperty("completed_milestones", listOf("tutorial_done", "level_10"))4. Identity Aliasing (Linking Identities)
// Link current distinct ID to a new user account ID
analytics.alias(newId = "user_uuid_123", previousId = analytics.getDistinctId())5. Manual Queue Flushing & Distinct ID
// Get current active Distinct ID
val distinctId = analytics.getDistinctId()
// Trigger manual queue flush to send events to server immediately
analytics.flush()6. Event Duration Tracking (Timed Events)
// Start timer
analytics.timeEvent("level_completed")
// ... some time passes ...
// Emits event with a "$duration" property (in seconds)
BillDog.trackEvent("level_completed", mapOf("level_number" to 5))7. Event Filtering & Transformation (Analytics Plugins)
Intercept, modify, or drop events before queueing (PostHog's beforeSend equivalent):
class DataMaskingPlugin : AnalyticsPlugin {
override fun process(event: BillDogAnalyticsEvent): BillDogAnalyticsEvent? {
val properties = event.properties.toMutableMap()
// Example: Drop event if it meets a criteria
if (event.name == "debug_event") return null
// Example: Mask property values
if (properties.containsKey("email")) {
properties["email"] = "[REDACTED]"
}
return BillDogAnalyticsEvent(event.name, properties, event.timestamp)
}
}
// Add the custom plugin to the analytics flow
analytics.addPlugin(DataMaskingPlugin())8. Privacy-First Autocapture & Exceptions (Off by default)
// Opt-in to automatic session lifecycle and screen tracking
analytics.enableSessionTracking()
analytics.enableScreenTracking(application)
// Enable touch autocapture with automatic text masking
analytics.enableAutocapture(
application,
AutocaptureConfig(maskAllText = true)
)
// Enable uncaught exception logging without breaking crash reporting
analytics.enableExceptionAutocapture()📹 Session Replay (billdog-replay)
Record user sessions as high-fidelity masked screenshot replays (Off by default):
1. Start Replay Capture
import io.billdog.core.BillDog
import io.billdog.replay.BillDogReplay
import io.billdog.replay.SessionReplayConfig
// Recordings link to the analytics module's session on their own.
val replay = BillDogReplay()
BillDog.use(replay)
replay.enableSessionReplay(
application,
SessionReplayConfig(
captureIntervalMs = 1000,
sampleRate = 0.1 // Sample 10% of sessions
)
)2. UI Redaction Tags
Control what gets recorded in your View-based layouts. Replay reads the tag from a view’s android:tag (View.tag) or from its resource-id name:
bd-mask: covers the view and everything inside it with a solid black rectangle in the recording.- Password
EditTexts are always covered, and with the defaultmaskAllInputs = trueeveryEditTextis.maskAllText = truecovers everyTextViewtoo. - Jetpack Compose fields are not
EditTexts, so they are recorded, password fields included — cover the screen region yourself or keep replay off on those screens.
bd-no-capture is read only by analytics autocapture (it skips taps on that view); session replay ignores it, so use bd-mask to hide a view from replay.
💬 In-App Messaging (billdog-inappmessages)
Trigger customized banners, alerts, or full-screen modals configured via the dashboard:
import io.billdog.core.BillDog
import io.billdog.inappmessages.BillDogInAppMessaging
val messages = BillDogInAppMessaging.shared
BillDog.use(messages)
// Displays a matching campaign modal if screen parameters match its settings
messages.checkForMessages("purchase_intent_churn")📝 Surveys (billdog-survey / billdog-survey-compose)
Show user feedback surveys with headless or Compose UI layouts, using conditional branching:
import io.billdog.core.BillDog
// Presents Compose UI branching survey
BillDog.getSurveyPresenter()?.present(
surveyId = "post_purchase_feedback",
activity = this,
customerId = "user-123"
)🔔 Push Notifications (billdog-notifications)
Sync FCM device registration tokens and manage consent overrides:
import io.billdog.core.BillDog
import io.billdog.notifications.BillDogNotifications
val notifications = BillDogNotifications(context)
BillDog.use(notifications)
// Set consents
notifications.setConsentRequired(true)
notifications.setConsentGiven(true)Register the FCM token and forward messages from your own FirebaseMessagingService:
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import io.billdog.core.BillDog
import io.billdog.notifications.BillDogMessagingService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MyMessagingService : FirebaseMessagingService() {
private val billdog = BillDogMessagingService()
// Register the token with BillDog for the current app user. It needs only
// BillDog.configure (in your Application), not a loaded customer.
override fun onNewToken(token: String) {
CoroutineScope(Dispatchers.IO).launch {
BillDog.setDeviceToken(token)
.onFailure { Log.w("BillDog", "Push token registration failed", it) }
}
}
// Forward every message. BillDog shows its own pushes while the app is in
// the foreground and handles its silent entitlement-refresh pushes.
override fun onMessageReceived(message: RemoteMessage) {
val handled = billdog.onMessageReceived(
this, message.data, message.notification?.title, message.notification?.body
)
if (!handled) {
// Not a BillDog message: handle your own.
}
}
}BillDog.setDeviceToken is what registers the device for push. notifications.pushSubscription.updateToken(...) only records the token on the device and sends nothing to BillDog.
🪙 Virtual Currency (billdog-virtual-currency)
Read server-synced wallet balances in the app; grant currency from your server:
implementation("io.billdog:billdog-virtual-currency:1.2.0-beta.1")import android.util.Log
import io.billdog.core.BillDog
import io.billdog.virtualcurrency.VirtualCurrencyManager
// Register once (before or after BillDog.configure)
val wallet = VirtualCurrencyManager()
BillDog.use(wallet)
// Both reads are suspend functions
lifecycleScope.launch {
// Every active currency, with this customer's balance in it
val wallets = wallet.getAllCurrencies()
wallets.forEach { Log.d("BillDog", "${it.currency.code} (${it.currency.id}): ${it.balance}") }
// One currency, by its id or its code
val balance = wallet.getCurrencyBalance("COINS")
}Grant currency from your server, not the app. Writing to a wallet needs your project’s secret key, and the publishable key in the app is refused with 403. The wallet in the SDK is read-only, as in RevenueCat: addCurrency, deductCurrency, grantCurrency and exchangeCurrency are deprecated and throw a BillDogException(ConfigurationError) at once, without a request (Flutter and React Native do not offer them). Never ship the secret key in the app; call the API from your backend instead, then read the new balance in the app:
curl -X POST https://api.billdog.io/v1/virtual-currency/transactions \
-H "X-BillDog-API-Key: $BILLDOG_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{
"app_user_id": "user_uuid_123",
"currency_id": "YOUR_CURRENCY_ID",
"amount": 100,
"type": "GRANT",
"reason": "onboarding_reward"
}'app_user_id is the id you passed to identify. The answer carries the new balance.
🔐 Authentication (billdog-auth)
io.billdog:billdog-auth before that version, so pin the same version as your other BillDog modules (1.2.0-beta.1).1. Add the module and configure it
implementation("io.billdog:billdog-auth:1.2.0-beta.1")BillDog.configure(context = this, apiKey = "your_api_key")
BillDogAuth.configure(
context = this,
apiKey = "your_api_key",
baseUrl = "https://api.billdog.io/v1",
)2. Sign someone in
// Every BillDogAuth call is a suspend function: call it from a coroutine
lifecycleScope.launch {
when (val r = BillDogAuth.attempt(
identifier = "ada@example.com",
strategy = BillDogAuth.Strategy.PASSWORD,
password = password,
)) {
// customerId is the RECORD this person owns — entitlements, purchases,
// analytics. The person who signed in is the user; this is what they own.
is BillDogAuth.Result.Success -> show(r.customerId)
// First factor accepted. Finish with the second, passing mfaToken back.
// A WRONG CODE INVALIDATES IT — restart at the first factor rather than
// retrying with the same token.
is BillDogAuth.Result.MfaRequired -> BillDogAuth.attempt(
identifier = "ada@example.com",
strategy = BillDogAuth.Strategy.TOTP,
code = code,
mfaToken = r.mfaToken,
)
is BillDogAuth.Result.Failure -> showError(r.message)
else -> Unit
}
}3. Passwordless, and phone numbers
lifecycleScope.launch {
// A RETURNING user gets a fresh code from requestCode — signUp issues one
// only for a NEW identifier.
BillDogAuth.requestCode(
identifier = "+15551234567",
kind = BillDogAuth.IdentifierKind.PHONE,
)
BillDogAuth.attempt(
identifier = "+15551234567",
strategy = BillDogAuth.Strategy.SMS_CODE,
kind = BillDogAuth.IdentifierKind.PHONE, // selects the identity row
code = code,
)
}Strategy and IdentifierKind are enums, and that is load-bearing. Both were plain Strings once, and with every parameter a String the compiler could not tell a kind from a password — a caller mirroring signUp’s shape wrote attempt(phone, "sms_code", "phone"), which compiled and bound "phone" to the password slot. Only the enum-typed attempt exists now, so that call no longer compiles.
4. Restoring and ending a session
lifecycleScope.launch {
val session = BillDogAuth.restore() // null is ordinary on first launch
if (session == null && BillDogAuth.hasStoredSession) {
// Offline or a server error: still signed in, renewing in the background.
}
BillDogAuth.signOut() // "this" | "others" | "all"
}The refresh token is stored in EncryptedSharedPreferences; the session token stays in memory and is refreshed for you, with at most one refresh in flight however many callers ask. Organization calls (BillDogAuth.organizations(), createOrganization(...), … — extension functions in io.billdog.auth) and the BillDogPasskeys object ship in the same artifact — passkeys need two Credential Manager dependencies you add yourself, on purpose, so apps that never sign anyone in do not ship them.
5. Sign-up, password reset and account deletion
import io.billdog.auth.BillDogAuth
import io.billdog.auth.PasswordResult
import io.billdog.auth.requestPasswordReset // extension functions
import io.billdog.auth.resetPassword
lifecycleScope.launch {
// Sign-up sends a code; attempt(strategy = EMAIL_CODE) completes it
BillDogAuth.signUp(
identifier = "ada@example.com",
password = password,
invitationToken = inviteToken, // required when the project is invite-only
captchaToken = captchaToken, // required when bot protection is on
)
// Password reset: request a code, then present it with the new password
BillDogAuth.requestPasswordReset(identifier = "ada@example.com")
when (val r = BillDogAuth.resetPassword(
identifier = "ada@example.com",
code = code,
newPassword = newPassword,
)) {
is PasswordResult.Ok -> Log.d("BillDog", "Sessions ended: ${r.value.sessionsRevoked}")
is PasswordResult.Failure -> Log.w("BillDog", r.message)
}
// Delete the signed-in user's own account. Returns true or throws
// io.billdog.managers.ApiException.
try {
BillDogAuth.deleteAccount()
} catch (e: Exception) {
Log.w("BillDog", "Account deletion failed", e)
}
}Full detail: BillDog Auth, Sessions & Tokens, Passkeys.
Next Steps
- View complete API Reference
- SDK Glossary - Key terms and concepts explained
- BillDog Auth - sign users in, and gate features on the token
- Test your integration in sandbox mode
- Configure webhooks for real-time updates
- Implement proper error handling and retry logic
- Explore metadata customization for dynamic paywalls
Quick Start Interactive Tutorial
Android SDK Setup
Follow these steps to quickly integrate BillDog into your Android app
Add Dependencies
dependencies {
implementation("io.billdog:billdog-compose:1.2.0-beta.1")
implementation("io.billdog:billdog-paywall:1.2.0-beta.1") // Google Play Billing
}Add the BillDog Android SDK to your project. billdog-paywall carries Google Play Billing; without it the SDK cannot sell.
Configure BillDog
// In your Application class
BillDog.configure(
context = this,
apiKey = "YOUR_API_KEY_HERE",
config = BillDogConfig(
apiKey = "YOUR_API_KEY_HERE"
)
)Present Paywall
// From an Activity — register is a suspend function
lifecycleScope.launch {
BillDog.register("onboarding", this@MainActivity) { result ->
// Entitled, Purchased, Dismissed, Restored, Holdout or Error
Log.d("BillDog", "Placement result: $result")
}
}Example: SDK Client Snippet
An editable snippet to adapt and copy into your app. Nothing runs in the browser.
Android API Client
Android • kotlin • editable snippet
Was this page helpful?
Or rate this page: