# Advertiser Integration Source: https://docs.encorekit.com/advertisers/integration Track conversions on your website when users from Encore-integrated apps complete your offers, so you get credited for each completion. The Encore SDK allows you to track conversions when users from Encore-integrated apps complete offers on your website. When users successfully complete your offers, you'll be credited for the conversion. ## How it works 1. Users discover your offers in Encore-integrated apps 2. Users click through to your website with a special tracking token 3. Your website loads our SDK to activate the tracking session 4. When users complete your offer, the SDK records the conversion You'll need two things: the JavaScript SDK included on your offer pages (**frontend integration**), and your own **completion validation** to verify users actually completed your offer before recording the conversion. ## Quick start **1. Add the SDK to your landing pages** Include the Encore SDK on pages where users from Encore-integrated apps will land (your offer pages, sign-up pages, etc.). > [tab] HTML script tag > > ```html theme={null} > > > > Your Offer Page > > > > > > > > > > ``` > [tab] React (dynamic loading) > > ```jsx theme={null} > import { useEffect } from 'react'; > > function OfferPage() { > useEffect(() => { > // Dynamically load Encore SDK > const script = document.createElement('script'); > script.src = 'https://encore.joinyaw.com/encore-advertiser-sdk.js'; > script.async = true; > > script.onload = async () => { > await window.EncoreSDK.activateSession(); > }; > > document.body.appendChild(script); > > return () => { > document.body.removeChild(script); > }; > }, []); > > return ( >
> {/* Your offer page content */} >
> ); > } > ``` **2. Add conversion tracking to your success pages** Add conversion tracking to your success/confirmation pages where users complete your offer. > [tab] HTML script tag > > ```html theme={null} > > > > Success - Thank You! > > > >

Thank you for completing our offer!

> > > > > > > ``` > [tab] React (dynamic loading) > > ```jsx theme={null} > import { useEffect } from 'react'; > > function SuccessPage() { > useEffect(() => { > const script = document.createElement('script'); > script.src = 'https://encore.joinyaw.com/encore-advertiser-sdk.js'; > script.async = true; > > script.onload = async () => { > // Verify completion > const completionValid = await verifyOfferCompletion(); > > if (!completionValid) return; > > // Record conversion > await window.EncoreSDK.recordCompletion(window.location.href); > }; > > document.body.appendChild(script); > > return () => { > document.body.removeChild(script); > }; > }, []); > > // Replace with your actual completion validation > async function verifyOfferCompletion() { > // Your validation logic here > return true; > } > > return ( >
>

Thank you for completing our offer!

> {/* Your success page content */} >
> ); > } > ``` > [!NOTE] > > * **Completion validation**: always verify users actually completed your offer before calling `recordCompletion()`. > * **Token detection**: the SDK automatically detects Encore users via URL parameters; no additional configuration needed. # Welcome Source: https://docs.encorekit.com/index Increase your app's ARPU with premium brand offers: real perks, funded by brands, presented at the moments your users care about most. Encore turns moments you already own into a new revenue stream. At a moment your user just earned (a purchase, a streak, a milestone) your app presents a **premium brand offer**: a real perk a brand funds to acquire customers. Never an ad, and never paid for by you or your users. Publishers use Encore to earn per-activation bounty revenue and to lift subscription ARPU. ## What are you building? > [card] [Reward Users](/publishers/use-cases/post-action-reward) > > Earn bounty revenue from moments of accomplishment: celebrate a purchase, streak, or milestone with a brand-funded reward at a moment your app already owns. > [card] [Reduce Churn](/publishers/use-cases/churn-intervention) > > Recover revenue from users about to leave: catch a cancellation or paywall-abandonment moment and present an offer that offsets their subscription cost. ## Pick your platform > [card] [iOS](/publishers/ios/quickstart/install) > > Swift SDK with managed rendering and StoreKit purchase plumbing. > [card] [Android](/publishers/android/quickstart/install) > > Kotlin SDK with managed rendering and Google Play Billing support. > [card] [Web](/publishers/web/quickstart/install) > > Framework-agnostic JavaScript SDK for React, Vue, Svelte, Angular, or plain JavaScript. > [!NOTE] > > Using a cross-platform framework? Use the [React Native](/publishers/react-native/quickstart/install) or [Flutter](/publishers/flutter/quickstart/install) SDK. Building a game in Unity? Use the [Unity package](/publishers/unity/quickstart/install). # Add Subscription Product Source: https://docs.encorekit.com/publishers/android/guides/add-subscription-product Pick the Google Play subscription your purchase controller buys when a user accepts an offer. ## Overview > [!NOTE] > > This step applies to **Reduce Churn** placements only. A [reward placement](/publishers/guides/reward-placements) never runs a purchase, so an app that presents only reward placements can skip it. Now that placements are presenting, choose the subscription product Encore offers. When a user accepts an offer at a churn moment, Encore hands the product you pick to your registered purchase controller, which runs a real Google Play subscription purchase, and Google Play handles all entitlement state; no custom entitlement tracking code is needed in your app. The setup itself is store-console work, done once in Google Play Console and your app's **Entitlements** step: > [card] [Google Play Subscription Product](/publishers/android/platform-setup/subscription-product) > > Connect your Google Play catalog and pick the subscription, base plan, and offer Encore uses, let Encore create one for you, or enter a Product ID manually. *** ## What the SDK does with the Product ID at runtime You never hard-code the Product ID in your app; Encore delivers it to the SDK as **remote configuration**: * The SDK reads the configured subscription Product ID from your app's Encore config automatically. * When a user accepts an offer, the SDK invokes your registered [`EncorePurchaseController`](../sdk-reference/purchase-controller) with that Product ID as `request.productId` and awaits your verdict. Because it's remote config, changing the product in the Encore Dashboard takes effect without an app update. > [!WARNING] > > A configured product with no registered purchase controller never charges anyone: the claim flow still completes, the result records `PublisherOutcome.NotAttempted`, a warning is logged at every log level, and the `sdk_iap_no_purchase_controller` analytics event makes the misconfiguration visible. *** ## Next Steps * [Configure Analytics](../quickstart/configure-analytics) - Forward Google Play subscription events so Encore can measure offer impact # Integration Patterns Source: https://docs.encorekit.com/publishers/android/guides/integration-patterns How to wire Encore offer results into your Kotlin app: awaiting the result, the callback form, and the outcomes stream. ## Overview `Encore.placement(id).show()` returns a [`PresentationResult`](../sdk-reference/presentation-result): the complete factual record of the presentation. It never throws, and it resolves exactly once. Three rules cover almost every integration: 1. **Invoke `show()` from the right context.** The call is safe from any thread or scope, but it needs a foreground Activity. The callback form is always delivered on the main thread; the suspending form resumes in your caller's context. 2. **Results are values: await inline for control flow.** Branch on the record where the call site already owns what happens next, or take the callback form when the call site isn't a coroutine. 3. **`Encore.outcomes` is for passive observers.** Analytics, logging, and entitlement sync consume the stream instead of owning a call site. Mixing is fine. The outcomes stream can feed telemetry while awaited results drive control flow on the same placement. *** ## Await the result Use this when the place you call `show()` from already owns the follow-up logic. ### Basic example ```kotlin theme={null} import androidx.lifecycle.lifecycleScope import com.encorekit.encore.Encore import com.encorekit.encore.features.offers.PublisherOutcome import kotlinx.coroutines.launch class CancelActivity : AppCompatActivity() { fun onCancelTapped() { lifecycleScope.launch { val result = Encore.placement("cancel_flow").show() val converted = result.claim != null || result.publisher == PublisherOutcome.Purchased if (converted) { // The user claimed an offer or completed your purchase finish() } else { // Dismissed, declined, no offers, control cohort, error result.error?.let(::logPresentationError) proceedWithCancellation() } // Code that runs in all branches lives here, written once analytics.track("cancel_flow_resolved") } } } ``` There is no SDK-computed "unlocked" verdict; branch on the raw facts (see [PresentationResult](../sdk-reference/presentation-result)). When the mechanism detail matters, read the record: ```kotlin theme={null} when (result) { is PresentationResult.NotPresented -> log(result.reason) // NoOffers, NotConfigured, error... is PresentationResult.Presented -> { result.claim?.let { syncEntitlement(it.campaignId, it.transactionId) } if (result.outcome.publisher == PublisherOutcome.Purchased) refreshSubscriptions() log("closed via ${result.outcome.dismissal.value}") } } ``` ### From Compose `onClick` is synchronous, so launch a coroutine on the lifecycle scope: ```kotlin theme={null} @Composable fun CancelButton() { val scope = rememberCoroutineScope() Button(onClick = { scope.launch { val result = Encore.placement("cancel_flow").show() if (result.claim == null && result.publisher != PublisherOutcome.Purchased) { proceedWithCancellation() } } }) { Text("Cancel Subscription") } } ``` See [PresentationResult](../sdk-reference/presentation-result) for the full record and fact readers. *** ## Callback form Use this when the call site isn't a coroutine and you don't want to manage a scope. The callback is delivered exactly once, on the main thread: ```kotlin theme={null} Button(onClick = { Encore.placement("cancel_flow").show { result -> if (result.claim == null && result.publisher != PublisherOutcome.Purchased) { proceedWithCancellation() } } }) { Text("Cancel Subscription") } ``` Result delivery is not foreground-gated: the callback fires even if your Activity backgrounded mid-flow, so don't touch views without checking your own lifecycle. *** ## The outcomes stream For observation that shouldn't live at every call site, collect [`Encore.outcomes`](../sdk-reference/outcomes) once, right after `configure()`. There is no replay, so subscribe at startup: ```kotlin theme={null} import com.encorekit.encore.Encore import com.encorekit.encore.features.offers.PlacementOutcome class MyApp : Application() { override fun onCreate() { super.onCreate() Encore.shared.configure( context = this, apiKey = "pk_live_...", purchaseController = AppPurchases(billing), ) appScope.launch { Encore.outcomes.collect { outcome -> when (outcome) { is PlacementOutcome.Presentation -> analytics.log("encore_outcome", outcome.placementId, outcome.result) is PlacementOutcome.StrictUnlockVerified -> grantEntitlement(outcome.transactionId) } } } } } ``` The stream observes; it never drives control flow. Fallback logic (proceed with the cancellation, show your own paywall) belongs at the call site, off the returned result. *** ## Platform-specific notes * **`show()` never throws.** Every failure is a value: `NotPresented(reason)`, with errors carried as `NotPresentedReason.Error`. There is no need for a try/catch around any `show()` call. * **`show()` is safe to call from any thread or scope.** The suspending form does its work on a background dispatcher and hops to Main internally. The callback form is always delivered on the main thread; the suspending form resumes in your caller's context. * **The no-arg overloads auto-resolve the current foreground Activity.** `show(activity)` and `show(activity) { result -> }` are available when you need to bind to a specific one. Nothing in the foreground resolves to `NotPresented(NoForegroundActivity)`. * **Purchases run through your registered [`EncorePurchaseController`](../sdk-reference/purchase-controller).** There is no billing code path inside the SDK, so the awaited result's `publisher` axis is your own controller's verdict reflected back. * **JVM target**: the SDK is built with JVM target 17. Your app must match (most modern Android Gradle plugins default to this). *** ## See also * [Quickstart: Present Offers](/publishers/android/quickstart/present-offers) * [SDK Reference: `placement()`](../sdk-reference/placement) * [SDK Reference: `PresentationResult`](../sdk-reference/presentation-result) * [SDK Reference: `Encore.outcomes`](../sdk-reference/outcomes) # Routine updates Source: https://docs.encorekit.com/publishers/android/guides/updating-sdk How to update the Encore Android SDK and how its versioning works. ## Overview The Encore Android SDK ships on **Maven Central**. Updating is the standard Gradle dependency flow, with no token or authenticated repository required. *** ## Versioning policy Encore follows [Semantic Versioning](https://semver.org): | Version change | Example | What it means | | :- | :- | :- | | Patch | `2.0.0` → `2.0.1` | Bug fixes only. Always safe to update. | | Minor | `2.0.1` → `2.1.0` | New features, backward compatible. Safe to update. | | Major | `1.4.x` → `2.0.0` | Breaking changes. Follow that version's migration guide. | Keep your dependency pinned within a major version so patch and minor updates arrive through a routine sync and a major version never lands without you opting in: ```kotlin theme={null} dependencies { implementation("com.encorekit:encore:2.+") } ``` > [!NOTE] > > Upgrading across a major version? See [Updating to 2.x](./updating-to-2-x) for the step-by-step migration guide. *** ## Update the dependency Bump the version in your `build.gradle.kts` (or version catalog), then sync: ```bash theme={null} ./gradlew --refresh-dependencies build ``` If you pin an exact version (recommended for reproducible builds), change it explicitly: ```kotlin theme={null} implementation("com.encorekit:encore:2.0.0") ``` *** ## Verify the update Check the resolved version in Android Studio's **External Libraries**, or: ```bash theme={null} ./gradlew :app:dependencies --configuration releaseRuntimeClasspath | grep encorekit ``` *** If you encounter issues after updating, reach out to [admin@encorekit.com](mailto:admin@encorekit.com). # Updating to 2.x Source: https://docs.encorekit.com/publishers/android/guides/updating-to-2-x Step-by-step migration guide for upgrading the Encore Android SDK from 1.x to 2.x. ## Overview SDK 2.0 is a breaking release that makes the integration surface simpler and harder to misuse: * **`show()` returns one result record and never throws.** Errors arrive as values on the result instead of as exceptions. * **Purchases run through a registered [`EncorePurchaseController`](../sdk-reference/purchase-controller).** The SDK never runs purchase code you didn't write; the built-in Play Billing fallback is removed. * **Global handler closures are retired.** Results are values at the call site; passive observation moves to the [`Encore.outcomes`](../sdk-reference/outcomes) stream. * **The callback form is always delivered on the main thread; the suspending form resumes in your caller's context.** `show()` itself is safe to call from any thread or scope. 2.0 removes the 1.x legacy surface outright rather than deprecating it, so every call site that needs attention fails to compile. Work through the steps below until the project builds, then run the [verification checklist](#verify-the-migration). The [removed API table](#removed-apis-at-a-glance) maps every 1.x symbol to its replacement. *** ## Step 1: Update the dependency ```kotlin theme={null} dependencies { implementation("com.encorekit:encore:2.0.0") } ``` Sync and build. The compile errors that appear are your migration worklist; each one corresponds to a step below. *** ## Step 2: Register a purchase controller This is the largest change. In 1.x, purchases ran through the `onPurchaseRequest` closure, and if no handler was registered the SDK bought the product itself through Play Billing and reported it via `onPurchaseComplete`. 2.0 removes the closure, the completion callback, and the built-in Play Billing fallback: that fallback bypassed whatever receipt validation, restore handling, and entitlement bookkeeping your app already has, and it made a missing registration look like a working purchase instead of a misconfiguration. Implement the controller and pass it to [`configure()`](../sdk-reference/configure): ```kotlin RevenueCat theme={null} class RevenueCatController : EncorePurchaseController { override suspend fun purchase( activity: Activity, request: PurchaseRequest, ): EncorePurchaseResult { return try { val product = Purchases.sharedInstance .awaitGetProducts(listOf(request.productId)) .firstOrNull() ?: error("Product not in RC catalog: ${request.productId}") Purchases.sharedInstance.awaitPurchase( PurchaseParams.Builder(activity, product).build() ) EncorePurchaseResult.Purchased } catch (e: PurchasesTransactionException) { if (e.userCancelled) EncorePurchaseResult.Cancelled else throw e } } } Encore.shared.configure( context = this, apiKey = "pk_...", purchaseController = RevenueCatController(), ) ``` ```kotlin Your own billing stack theme={null} class AppPurchases(private val billing: MyBillingStack) : EncorePurchaseController { // Runs on Dispatchers.Main.immediate. Throw for real failures; map // "user cancelled" to Cancelled. Do not retain or finish the activity. override suspend fun purchase( activity: Activity, request: PurchaseRequest, ): EncorePurchaseResult { return when (billing.purchase(activity, request.productId, request.promoOfferId)) { MyOutcome.Success -> EncorePurchaseResult.Purchased MyOutcome.Cancelled -> EncorePurchaseResult.Cancelled MyOutcome.Deferred -> EncorePurchaseResult.Pending // parental approval / SCA } } } Encore.shared.configure( context = this, apiKey = "pk_...", purchaseController = AppPurchases(billing), ) ``` Return `Purchased`, `Cancelled`, or `Pending`; throw for real failures. The full contract is in [`EncorePurchaseController`](../sdk-reference/purchase-controller). *** ## Step 3: Update show() call sites `show()` returns the full result record and never throws. The 1.x scope-taking overloads become an explicit callback form: ```kotlin theme={null} // 1.x: fire-and-forget with a scope Encore.placement("cancel_flow").show(activity, lifecycleScope) // 2.0: callback form; delivered exactly once, on the main thread Encore.placement("cancel_flow").show(activity) { result -> if (result.claim == null && result.publisher != PublisherOutcome.Purchased) proceedWithCancellation() } ``` Result delivery is not foreground-gated: the callback fires even if your Activity backgrounded mid-flow. Don't touch views without checking your own lifecycle. The suspending form works from any thread or scope: ```kotlin theme={null} val result = Encore.placement("cancel_flow").show(activity) val converted = result.claim != null || result.publisher == PublisherOutcome.Purchased if (converted) grantAccess() else proceedWithCancellation() ``` *** ## Step 4: Update result handling 1.x modeled the result as a flat triad (`Completed`, `Dismissed(reason)`, `NoOffers`), which forced a claim and a purchase to compete for a single winning case. 2.0 records the facts independently: 2.0 splits the result into `NotPresented(reason)` and `Presented(outcome)`; see [PresentationResult](../sdk-reference/presentation-result) for the full shape. The record carries **raw facts only**: there is no SDK-computed "unlocked" verdict, so your integration decides what a claim means. Branch on the facts your flow cares about: ```kotlin theme={null} val result = Encore.placement("paywall").show(activity) if (result.claim != null || result.publisher == PublisherOutcome.Purchased) { grantAccess() // the user claimed an offer or completed your purchase } else { result.error?.let(::log) // presentation failures are values runOriginalFlow() // dismissed, declined, no offers, control cohort, ... } ``` `result.claim` surfaces the claimed offer whenever the advertiser funnel reached `Claimed` or `Verified`; read `result.advertiser` directly to tell the two apart. When the mechanism detail matters, read the record: ```kotlin theme={null} when (result) { is PresentationResult.NotPresented -> log(result.reason) is PresentationResult.Presented -> { result.claim?.let { syncEntitlement(it.campaignId, it.transactionId) } if (result.outcome.publisher == PublisherOutcome.Purchased) refreshSubscriptions() log("closed via ${result.outcome.dismissal.value}") } } ``` *** ## Step 5: Replace global callbacks with the outcomes stream `onPassthrough` and `onPurchaseComplete` are removed. Handle fallback inline at the call site (Step 4), and move passive observation (analytics, logging, cross-cutting state) to the `Encore.outcomes` stream: ```kotlin theme={null} // Application.onCreate, right after configure. There is no replay, so // subscribe at startup. appScope.launch { Encore.outcomes.collect { outcome -> when (outcome) { is PlacementOutcome.Presentation -> analytics.log("encore_outcome", outcome.placementId, outcome.result) is PlacementOutcome.StrictUnlockVerified -> grantEntitlement(outcome.transactionId) // strict-mode cross-launch settlement } } } ``` Every `show()` resolution lands on `Encore.outcomes`, including `NotPresented`, plus strict-unlock verifications that settle on a later launch. *** ## Removed APIs at a glance | 1.x surface | 2.0 replacement | | :- | :- | | `PresentationResult.Completed(offerId, campaignId)` | `Presented(outcome)` with [`outcome.advertiser`](../sdk-reference/presentation-result#advertiseroutcome) = `Claimed(offer)` / `Verified(offer)` | | `PresentationResult.Dismissed(reason)` | `Presented(outcome)`; `outcome.dismissal` is the [`DismissReason`](../sdk-reference/dismiss-reason) | | `PresentationResult.NoOffers` | [`NotPresented(NoOffers)`](../sdk-reference/presentation-result#notpresentedreason) | | `DismissReason.USER_CLOSED` etc. | `DismissReason.UserTappedClose` etc.: one enum, raw values are the wire values | | `onPurchaseRequest { }` | `EncorePurchaseController` at `configure()` | | `onPurchaseComplete { }` | [`result.publisher`](../sdk-reference/presentation-result#publisheroutcome) `== PublisherOutcome.Purchased` / `Encore.outcomes` | | `onPassthrough { }` | Inline fallback off `result.claim == null && result.publisher != PublisherOutcome.Purchased` | | `Encore.shared.purchaseSubscription(...)` + Play Billing fallback | Removed; your controller owns the purchase, so you already have the result | | `BillingPurchaseResult` | Removed; the transaction belongs to your billing stack | | `show(activity, scope)` / `show(scope)` | `show(activity) { result -> }` / `show { result -> }` | | `placements.notifyResult` observation | `Encore.outcomes` (SharedFlow) | *** ## Behavior changes to be aware of These compile fine but behave differently at runtime: * **Claim-then-purchase records both funnels.** 1.x collapsed the flow to a single winner. 2.0 carries `advertiser = Claimed(...)` and `publisher = Purchased` side by side, and the result is delivered once, after the purchase resolves (later than 1.x fired its callbacks). * **Strict mode records the claim, and verification upgrades it.** With [`UnlockMode`](../sdk-reference/configure#unlock-modes)`.Strict`, the record says `advertiser = Claimed(...)` immediately, and in-session verification upgrades it to `Verified(...)`. A claim that ends unverified re-verifies across launches and surfaces as [`PlacementOutcome.StrictUnlockVerified`](../sdk-reference/outcomes) on `Encore.outcomes`; the persistence rules are in [unlock modes](../sdk-reference/configure#unlock-modes). * **The offer sheet no longer recreates on rotation or dark-mode changes**, so mid-flow configuration changes can't produce spurious results, and a dead flow (killed sheet) resolves as `Presented(dismissal = Interrupted)` instead of wedging `show()` in "already presenting". * **Gesture dismissal now reports `swipe_dismiss`** in analytics (previously lumped into `close_button`). On the SDUI sheet, which is the default render path, this covers both dragging the sheet down and tapping outside it; on the native fallback sheet only dragging reports it. All other event names and close-reason strings are unchanged on the wire. > [!WARNING] > > **Backup rules caveat for strict mode.** The SDK ships an include-only Auto Backup allowlist: it includes `com.encorekit.encore.xml` (the cross-install NCL identity file) and excludes its pending-claims file by omission. If your app replaces the SDK's backup rules wholesale (`tools:replace` on the manifest attributes), keep `com.encorekit.encore.xml` included and keep `com.encorekit.encore.pending.xml` out of your include list. Runtime guards back the pending-claims exclusion up either way. New in 2.x with no migration required: placements can declare a claim-only reward surface (`Encore.placement("streak_complete")`[`.useCase(UseCase.REWARD_USERS)`](../sdk-reference/placement#use-cases)) with per-presentation `headline()` / `subheadline()` copy overrides. The surface fires *after* the user has already done something worth celebrating, and reward presentations never run a purchase and never show the paywall layout. *** ## Verify the migration > [!TIP] > > Confirm each of these before shipping: 1. The project compiles with no references to removed 1.x APIs. 2. If a subscription product is configured for your app, an `EncorePurchaseController` is registered at `configure` time. 3. Every fallback path (your original paywall or flow) runs off the raw facts (`result.claim == null && result.publisher != PublisherOutcome.Purchased`), not a removed callback. 4. If you subscribe to `Encore.outcomes`, the subscription starts at app startup (there is no replay). 5. Test the full flow on a device: present a placement, claim an offer, complete a purchase, and dismiss without acting. Each path should resolve exactly once with the result you expect. *** If you hit anything this guide doesn't cover, reach out to [admin@encorekit.com](mailto:admin@encorekit.com). # Real-Time Developer Notifications Source: https://docs.encorekit.com/publishers/android/platform-setup/server-notifications Point Google Play's subscription lifecycle notifications at Encore so your dashboard can track subscription events and measure offer impact. ## Overview Encore uses Google Play's **Real-Time Developer Notifications** (RTDN) to track subscription lifecycle events: trial starts, renewals, expirations, and cancellations. These events power the **Analytics** section of your dashboard and the lift measurement behind the [Reduce Churn](/publishers/use-cases/churn-intervention) use case. > [!WARNING] > > Without this step, Encore cannot track subscription outcomes. Analytics will show no data. *** ## Choose your integration method > [tab] Set Up RTDN (Recommended) > > Configure Google Play to send real-time subscription notifications directly to Encore. This is the most reliable integration. > > ### Prerequisites > > * A **Google Cloud project** linked to your Google Play Console > * **Cloud Pub/Sub API** enabled in the Google Cloud project > > ### Steps > > **1. Enable Cloud Pub/Sub API** > > Go to the [Google Cloud Console](https://console.cloud.google.com/apis/library/pubsub.googleapis.com) and enable the **Cloud Pub/Sub API** for your project. > > **2. Create a Pub/Sub Topic** > > 1. Go to **Cloud Pub/Sub > Topics** > 2. Click **Create Topic** > 3. Name it (e.g., `encore-play-notifications`) > 4. Click **Create** > > **3. Create a Push Subscription** > > 1. On your topic, click **Create Subscription** > 2. Set **Delivery type** to **Push** > 3. Set the **Endpoint URL** to: > > ``` > https://api.encorekit.com/encore/webhooks/google > ``` > > 4. Click **Create** > > **4. Grant Google Play Publisher Access** > > 1. Select your topic and click **Show Info Panel** > 2. Click **Add Principal** > 3. Add `google-play-developer-notifications@system.gserviceaccount.com` > 4. Grant the **Pub/Sub Publisher** role > 5. Click **Save** > > **5. Configure in Google Play Console** > > 1. Go to [Google Play Console](https://play.google.com/console) > 2. Navigate to **Monetization setup** (under Settings) > 3. In the **Real-time developer notifications** section, enter your topic name: > > ``` > projects/{your-project-id}/topics/encore-play-notifications > ``` > > 4. Click **Send test notification** to verify > 5. Click **Save** > [tab] Forward from Your Server > > If you already have RTDN configured and don't want to change it, forward each notification to Encore from your existing handler. > > ```javascript theme={null} > app.post('/webhooks/google-play', async (req, res) => { > // Forward the raw Pub/Sub push body to Encore > await fetch('https://api.encorekit.com/encore/webhooks/google', { > method: 'POST', > headers: { 'Content-Type': 'application/json' }, > body: JSON.stringify(req.body), > }); > > // Continue with your existing logic... > res.sendStatus(200); > }); > ``` > > > [!NOTE] > > > > Encore verifies the notification payload independently; no shared secrets or additional configuration are needed. Simply forward the raw request body as-is. *** ## Need help? If you have questions about configuring Real-Time Developer Notifications or the forwarding setup, contact us at [admin@encorekit.com](mailto:admin@encorekit.com). # Google Play Subscription Product Source: https://docs.encorekit.com/publishers/android/platform-setup/subscription-product Connect your Google Play catalog and pick, or create, the subscription product Encore offers. ## Overview When a user accepts an offer, Encore hands the product you configure here to your app's [purchase controller](../sdk-reference/purchase-controller), which runs a real Google Play subscription purchase, and Google Play owns entitlement state from then on. This page is the store-console half of that setup: connect your Google Play catalog so Encore can auto-sync your subscriptions (and their offers), then pick the product from a dropdown (or let Encore create one for you). > [!NOTE] > > Connect your Google Play service account once, then pick your subscription from the auto-synced list. Manual Product ID entry remains available as a fallback if you don't connect a credential. *** ## Connect your Google Play catalog (recommended) Encore reads your Google Play catalog through a **service account** from the Play Developer API. You upload it in the **Entitlements** phase of the [Integration Progress](/quickstart#integration-progress) tracker (the step labelled **Connect store**). **1. Create a service account in Google Cloud Console** Service accounts are created in the **Google Cloud Console**, not in Play Console. Go to [Google Cloud Console → IAM & Admin → Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts), making sure you're in the Cloud project linked to your Play developer account. Click **Create service account** and give it a name. Once created, copy its email address; it looks like `name@project-id.iam.gserviceaccount.com`. **2. Download the JSON key file** Open the service account, go to the **Keys** tab, and choose **Add key → Create new key → JSON**. The **JSON** key file downloads automatically; store it securely. **3. Grant the three required permissions in Play Console** Now switch to **Play Console → Users and permissions → Invite new users**, and paste the service account email you copied. Grant it these three app-specific permissions **on this app**: * **View app information (read-only)** * **View financial data** * **Manage store presence** Encore uses these to read your existing catalog, verify your subscription configuration, and create new subscriptions on your behalf when you use the suggested-product flow. **4. Upload to Encore** In your app's **Entitlements** step, choose the service-account **JSON** file and click **Upload and verify**. Encore verifies the credential with Google, reads your catalog, and shows how many subscriptions and offers it found. You can re-run the sync anytime with **Sync now**. **5. Pick your subscription, base plan, and offer** Once the catalog syncs, the **Subscription product** section shows a picker. Work top-down: pick your subscription, then (if it has more than one base plan) the base plan, then the offer: 1. **Subscription**: choose the product that gates entitlements. 2. **Base plan**: a Google Play subscription can expose several base plans (e.g. monthly, annual, a seasonal 12-month plan) at different prices. The base plan you pick determines the **price and billing period** the user sees and is charged. 3. **Offer**: within the chosen base plan, pick the **offer** (e.g. a free trial) users see at purchase. Choose **No offer** to charge the base plan immediately. > [!NOTE] > > The base-plan step only appears for Play subscriptions that expose more than one base plan; single-base-plan products skip straight to the offer. iOS has no base plans (each subscription is its own product), so this step doesn't apply there either. **6. Don't have a product yet? Let Encore create one** If you don't already have a suitable subscription, Encore can pre-fill a recommended annual product (priced from your existing catalog, with a free trial) and **create it in Google Play Console for you**, base plan, price, and trial offer included. Review the fields and confirm, and Encore writes the subscription. > [!NOTE] > > Newly created products land in your Play Console catalog as a draft. Review the auto-filled base plan, price, and trial offer, then activate both the base plan and the subscription; products in **Draft** state cannot be purchased. *** ## Manual Product ID entry (fallback) If you haven't connected a store credential, you can still enter a Product ID by hand. Create the subscription yourself in Google Play Console, then enter its details in the Encore Dashboard. **1. Create the subscription in Google Play Console** Go to [play.google.com/console](https://play.google.com/console) → your app → **Monetize → Subscriptions** → **Create subscription**. | Field | Value | | - | - | | **Product Type** | Subscription (auto-renewing) | | **Product ID** | `{your.package.name}.encore.annual.1m.trial` | | **Base Plan** | 1 Year, auto-renewing | | **Offer** | Free Trial, 1 Month | Add a base plan with your billing period and pricing, add a **Free trial** offer, then **Activate** both the base plan and the subscription. Products in "Draft" state cannot be purchased. > [!WARNING] > > The **Product ID** and **Base Plan ID** cannot be changed or reused after creation. **2. Enter the details in Encore** In your app's **Entitlements** step, type the **Product ID** (e.g. `com.yourapp.encore.annual.1m.trial`) and, if you want a specific trial, the optional **Offer ID** (e.g. `intro-7d-trial`) into the fallback inputs and save. *** ## How Encore stores your credential > [!NOTE] > > Uploaded credentials are **encrypted at rest**. The service-account JSON is held continuously (Real-Time Developer Notifications depend on it) and its scope is enforced server-side. You can **remove** the credential at any time from the same Entitlements step. *** ## Next step > [card] [Real-Time Developer Notifications](/publishers/android/platform-setup/server-notifications) > > Forward Google Play's subscription lifecycle events to Encore so your dashboard can measure offer impact. # Configure the SDK Source: https://docs.encorekit.com/publishers/android/quickstart/configure Initialize the Encore SDK with your API key at app launch. ## Overview As soon as your app launches, you need to configure the SDK with your **API Key**. Retrieve your publishable **Live** key yourself from the Dashboard under **Settings → Project API Keys** (use the **Test** key for staging and local development). *** ## Initialize Encore in your app Call `configure()` in your `Application.onCreate()` so the SDK is ready before any Activity starts. ```kotlin theme={null} // YourApplication.kt import android.app.Application import com.encorekit.encore.Encore class YourApplication : Application() { override fun onCreate() { super.onCreate() // Configure Encore with your API key Encore.shared.configure(this, apiKey = "pk_your_api_key_here") } } ``` > [!WARNING] > > Make sure your custom `Application` class is registered in `AndroidManifest.xml`: > > ```xml theme={null} > android:name=".YourApplication" > ... > > ``` This configures a shared instance of `Encore`, the primary class for interacting with the SDK's API. Make sure to replace `pk_your_api_key_here` with your public API key. > [!NOTE] > > Can't find your API key? Open your project's **Settings → Project API Keys** in the [Encore Dashboard](https://dashboard.encorekit.com) and copy the **Live** key (or **Test** for non-production builds). *** ## Register a purchase controller If your app sells a subscription product through Encore offers, register an [`EncorePurchaseController`](../sdk-reference/purchase-controller) at configure time. The SDK has no built-in billing: when a user accepts an offer that requires a purchase, the SDK calls your controller, which performs the purchase through your billing code and reports back. Add the controller to the call you already have. `configure()` runs once per process: a second call logs a warning and is ignored, so a controller passed to it never registers. ```kotlin theme={null} // The same single call from the step above, now with your controller Encore.shared.configure( context = this, apiKey = "pk_your_api_key_here", purchaseController = AppPurchases(billing), ) ``` See [Presenting Offers](./present-offers#handle-purchases) for where the controller runs, and [EncorePurchaseController](../sdk-reference/purchase-controller) for RevenueCat, Play Billing, and custom implementations. Apps that use Encore offers without a subscription product can skip the controller: with no product configured, no purchase is ever attempted. *** ## Next Steps Now that Encore is configured, you're ready to: * [User Management](./user-management) - Identify users for entitlement tracking * [Present Offers](./present-offers) - Show promotional offers and read the result # Configure Analytics Source: https://docs.encorekit.com/publishers/android/quickstart/configure-analytics Forward Google Play subscription events to Encore so your dashboard can measure offer impact. ## Overview Encore measures offer impact from your subscription lifecycle events: trial starts, renewals, expirations, and cancellations. Until Google Play's **Real-Time Developer Notifications** reach Encore, the Analytics section of your dashboard shows no data. Wiring them up is console work, done once in Google Cloud and Play Console (or your own webhook handler): > [card] [Real-Time Developer Notifications](/publishers/android/platform-setup/server-notifications) > > Point a Pub/Sub push subscription at Encore's webhook URL, or forward notifications from your existing server handler. *** ## Next Steps You've completed the Encore integration! Here's what to explore next: * [Encore Dashboard](https://dashboard.encorekit.com) - Monitor analytics and manage your app * [User Management](./user-management) - Identify users and set attributes for personalized offers * [Reward Placements](/publishers/guides/reward-placements) - Reward a user at a moment they just earned, with copy you set per call * [Reduce Churn](/publishers/use-cases/churn-intervention) - Present offers in a cancel flow or after a paywall decline, and the moments to target # Install the SDK Source: https://docs.encorekit.com/publishers/android/quickstart/install Add the Encore Android SDK to your project via Gradle. ## Overview The Encore Android SDK lets your app present premium brand offers, real perks funded by brands, at the moments you choose. It is available on **Maven Central**; no additional repository configuration is required. *** ## Install via Gradle ### Step 1: Add the Dependency Add the SDK to your app-level `build.gradle.kts`: ```kotlin theme={null} // app/build.gradle.kts dependencies { implementation("com.encorekit:encore:2.4.0") } ``` Use 2.4.0 or later: trigger components and `Encore.claim` need it. > [!NOTE] > > `mavenCentral()` is included by default in Android projects. No additional repository setup is needed. ### Step 2: Sync and Verify Sync your Gradle project, then verify the SDK is available: ```kotlin theme={null} import com.encorekit.encore.Encore ``` **Installation complete!** *** ## Next Steps Now that the SDK is installed, continue with the integration: * **[Configure the SDK](/publishers/android/quickstart/configure)** - Set up your API key and initialize Encore * **[Identify Users](/publishers/android/quickstart/user-management)** - Learn how to identify users for offer tracking # Presenting Offers Source: https://docs.encorekit.com/publishers/android/quickstart/present-offers Present Encore's reward sheet at a moment your user just earned, or a Reduce Churn sheet in a cancel flow, in your Android app. ## Overview Encore presents a premium brand offer (a real perk a brand funds to acquire customers, such as a free trial, discount, or credit) at a moment you choose. Start with **Reward Users**: a reward sheet at a moment the user just earned, such as a completed purchase, a streak, or a milestone, at no cost to you. The other use case, **Reduce Churn**, presents offers in a cancel flow or after a paywall decline. *** ## Present an offer `show()` is a suspend function that resolves once the presentation is over, with one complete result record, and it never throws. It is safe to call from any thread or scope: > [tab] Reward Users > > ```kotlin theme={null} > lifecycleScope.launch { > val result = Encore.placement("streak_day_7") > .useCase(UseCase.REWARD_USERS) > .headline("Nice work, Sam!") // optional; falls back to the copy resolved for your app > .show() > result.claim?.let { claim -> > // The user claimed an offer. Keep claim.transactionId; it carries the attribution. > claim.transactionId?.let(::persistClaim) > } > // Every other result: carry on with your own celebration screen. > } > ``` > > Select `UseCase.REWARD_USERS` on every reward placement. A reward placement never runs a purchase and never falls back to the paywall layout, so it needs no subscription product and no purchase controller. The walkthrough, including per-call copy, is the [Reward Placements guide](/publishers/guides/reward-placements). > [tab] Reduce Churn > > ```kotlin theme={null} > lifecycleScope.launch { > val result = Encore.placement("cancellation_flow").show() > val converted = result.claim != null || result.publisher == PublisherOutcome.Purchased > if (converted) { > // The user claimed an offer or completed your purchase > finish() > } else { > proceedWithCancellation() > } > } > ``` > > A placement that omits `useCase()` is a Reduce Churn placement. Never block the user's original action: when the result shows no claim and no purchase (dismissed, no offers, control cohort, error), run your original flow. The result carries raw facts: `result.claim` is the claimed offer (or `null`), `result.publisher` is your purchase funnel's outcome, and `result.error` surfaces presentation failures as values. There is no SDK-computed "unlocked" verdict; your integration branches on the facts your flow cares about. Contracts: [`placement()`](../sdk-reference/placement) · [`PresentationResult`](../sdk-reference/presentation-result). > [!TIP] > > `result.claim` means the user tapped through to an offer, not that they finished it. ### Callback form If the call site isn't a coroutine, use the callback overload. The callback is delivered exactly once, on the main thread: ```kotlin theme={null} Encore.placement("streak_day_7").useCase(UseCase.REWARD_USERS).show { result -> result.claim?.let { claim -> // The user claimed an offer. } } ``` Both forms auto-resolve the current foreground Activity; `show(activity)` and `show(activity) { result -> }` overloads are available when you need to bind to a specific Activity. *** ## Handle purchases This section applies to Reduce Churn placements only. A reward placement never runs a purchase, so an app that presents only reward placements can skip it. If your app has a subscription product configured, register an [`EncorePurchaseController`](../sdk-reference/purchase-controller) at `configure()` time. When a user accepts an offer that leads to a purchase, Encore invokes your controller with the product to buy and awaits your verdict: ```kotlin theme={null} Encore.shared.configure( context = this, apiKey = "pk_...", purchaseController = AppPurchases(billing), // RevenueCat, Play Billing, or your own stack ) ``` The SDK never runs purchase code you didn't write: with no controller registered, the claim flow still completes, the result records `PublisherOutcome.NotAttempted`, and nothing is ever charged. If your app uses Encore offers without a subscription product, no controller is needed. *** ## Observe outcomes passively For cross-cutting concerns (analytics, logging, entitlement sync) that shouldn't live at every call site, collect the [`Encore.outcomes`](../sdk-reference/outcomes) stream. Subscribe at app startup; there is no replay: ```kotlin theme={null} appScope.launch { Encore.outcomes.collect { outcome -> when (outcome) { is PlacementOutcome.Presentation -> analytics.log("encore_outcome", outcome.placementId, outcome.result) is PlacementOutcome.StrictUnlockVerified -> grantEntitlement(outcome.transactionId) } } } ``` *** ## Placement IDs Use meaningful placement IDs to track where offers are triggered in your app: ```kotlin theme={null} // When the user keeps a streak lifecycleScope.launch { Encore.placement("streak_day_7").useCase(UseCase.REWARD_USERS).show() } // After a completed purchase lifecycleScope.launch { Encore.placement("purchase_complete").useCase(UseCase.REWARD_USERS).show() } // In your cancellation flow (Reduce Churn) lifecycleScope.launch { Encore.placement("cancellation_flow").show() } ``` Placement IDs appear in your Encore Dashboard analytics, letting you measure conversion rates per placement. > [!TIP] > > Await the result at the call site by default; see [Android Integration Patterns](/publishers/android/guides/integration-patterns) for the callback and outcomes-stream shapes. *** ## Bring users back to finish their gift Put a Claim Reminder on your home tab. It stays hidden until the user claims a gift, then reminds them to finish. Once they do, it thanks them or steps aside. Encore manages that. You can also put a Gifts Button on your reward screen, so users can open their gifts there whenever offers are waiting. Both need version 2.4.0 or later of the SDK. See the [trigger components quickstart](/publishers/triggers/quickstart). ## Next Steps * [Reward Placements](/publishers/guides/reward-placements) - Reward a user at a moment they just earned, with copy you set per call * [Configure Analytics](./configure-analytics) - Track offer performance and measure impact * [Add Subscription Product](../guides/add-subscription-product) - Reduce Churn only: create a Google Play subscription product and connect it to Encore # User Management Source: https://docs.encorekit.com/publishers/android/quickstart/user-management Identifying users, setting attributes, and managing identity in your Android app. ## Overview Encore requires user identification to track entitlements and prevent abuse across devices. You can also set user attributes to enable targeted offers and personalization. *** ## Anonymous Users Encore **automatically generates** a random user ID that persists until the user clears app data, uninstalls, or calls `reset()`. This anonymous ID is stored locally and allows entitlement tracking to work immediately without requiring explicit user identification. The auto-generated ID is a standard UUID (e.g., `550e8400-e29b-41d4-a716-446655440000`). You can call `Encore.shared.reset()` to reset this ID and clear any cached data. *** ## Identified Users If you use your own user management system, call `identify()` when you have a user's identity: ```kotlin theme={null} // After retrieving a user's ID from login or account creation Encore.shared.identify(userId = user.id) ``` A blank or whitespace-only `userId` is ignored and never persists; the current identity is left untouched and the SDK logs a warning. This enables the SDK to: * Associate promotional access with your user account * Sync entitlements across devices when the user logs in * Track conversion attribution accurately *** ## Resetting User Identity When a user logs out, call `reset()`: ```kotlin theme={null} // When the user signs out Encore.shared.reset() ``` This will: * Reset the user ID to a new auto-generated anonymous ID * Clear cached configuration data Your registered purchase controller survives `reset()`: it is app infrastructure, not user state, so logging a user out does not require re-registering it. *** ## Setting User Attributes > [!NOTE] > > **Strongly recommended.** Country and language already shape which offers a user is shown. Once you know who the user is, send what your app already knows, such as country and anything of your own in `custom`. Gender is accepted only from an app rated 18+ in its store listing, so leave it out otherwise. ```kotlin theme={null} import com.encorekit.encore.Encore import com.encorekit.encore.core.canonical.user.UserAttributes val attributes = UserAttributes( countryCode = "US", age = 25, custom = mapOf("signupSource" to "referral"), ) Encore.shared.setUserAttributes(attributes) ``` Encore follows the device language. If your app has its own language picker, also call `setLanguage` with the user's choice. > [!WARNING] > > Only pass what you have a lawful basis to share, such as the user's consent. Pass the user's age in whole years as `age`, or their date of birth as `dateOfBirth` (`YYYY-MM-DD`), whichever your app has. The SDK works the age out on the device and never sends the date; given both, it uses the lower age. If you hold only a range, send its lowest end as `age`. A user under 18 is still served offers, from age-appropriate inventory only and with no per-user personalization. See [Sending an age](/publishers/offers-api/reference/user-attributes#sending-an-age). User attributes enable: * **Personalized offers** based on user data (subscription tier, usage, etc.) * **Audience targeting** with specific offers in the Encore dashboard * **Conversion context tracking** for analytics ### Usage Set attributes using the `UserAttributes` class. Every value is a string except `age`, a whole number of years; `dateOfBirth` is a `YYYY-MM-DD` string. Use the `custom` map, which takes strings, for app-specific fields: ```kotlin theme={null} Encore.shared.setUserAttributes( UserAttributes( email = "user@example.com", subscriptionTier = "premium", monthsSubscribed = "6", custom = mapOf( "cancelReason" to "too_expensive" ) ) ) ``` You can also set user attributes when identifying: ```kotlin theme={null} Encore.shared.identify( userId = "user_12345", attributes = UserAttributes( email = "user@example.com", subscriptionTier = "premium", monthsSubscribed = "6" ) ) ``` **Important:** `setUserAttributes()` **merges** with existing attributes; it does not replace them. *** ## Implementation Examples ### With Login ```kotlin theme={null} class YourApplication : Application() { override fun onCreate() { super.onCreate() Encore.shared.configure(this, apiKey = "pk_your_api_key") } } // After successful login class LoginActivity : AppCompatActivity() { private fun handleSuccessfulLogin(user: User) { Encore.shared.identify( userId = user.id, attributes = UserAttributes( email = user.email, subscriptionTier = user.subscriptionTier ) ) navigateToMain() } } // On logout class SettingsActivity : AppCompatActivity() { private fun handleLogout() { Encore.shared.reset() authManager.logout() navigateToLogin() } } ``` ### Jetpack Compose with Login ```kotlin theme={null} @Composable fun SettingsScreen(authManager: AuthManager) { Button(onClick = { Encore.shared.reset() authManager.logout() }) { Text("Log Out") } } ``` ### Apps Without Login If your app doesn't require users to log in, you don't need to do anything special: ```kotlin theme={null} class YourApplication : Application() { override fun onCreate() { super.onCreate() Encore.shared.configure(this, apiKey = "pk_your_api_key") } } // You can still set attributes for anonymous users Encore.shared.setUserAttributes( UserAttributes(custom = mapOf("cancelReason" to "too_expensive")) ) ``` *** ## Next Steps * [Present Offers](./present-offers) - Present a reward sheet at a moment your user just earned, and read the result * [Add Subscription Product](../guides/add-subscription-product) - Reduce Churn only: create a Google Play subscription product and connect it to Encore # clearLanguage() Source: https://docs.encorekit.com/publishers/android/sdk-reference/clear-language Remove the language set with setLanguage() so Encore copy follows the device language again Removes the language you set with [`setLanguage()`](./set-language), so Encore serves copy in the device's language again. Every other attribute and the current user stay as they are. > [!NOTE] > > New in Android SDK 2.3.0. React Native and Flutter forward it from the release that pins native 2.3.0. ## Signature ```kotlin theme={null} fun clearLanguage() ``` ## Parameters This method takes no parameters. ## Behavior * When a language was set, the SDK removes it and fetches its configuration and offers again. * When no language was set, or before [`configure()`](./configure), the call does nothing. * It is the only call that removes the language. [`reset()`](./reset) and logout leave it in place. * It also removes a language set through the deprecated `language` attribute. * The SDK always sends the device language as `Accept-Language`. This call only removes the override that outranks it. ## Usage Call it when the user picks "System default" in your app's own language picker: ```kotlin theme={null} fun onLanguageChanged(code: String?) { if (code != null) { Encore.shared.setLanguage(code) } else { Encore.shared.clearLanguage() } } ``` ## Related * [setLanguage()](./set-language): set a language override * [Localization](/publishers/concepts/localization): how Encore picks the language it serves # configure() Source: https://docs.encorekit.com/publishers/android/sdk-reference/configure Initialize the Encore SDK with your public API key, purchase controller, and unlock mode Configures the shared Encore instance for use throughout your app. This must be called once, typically in your `Application.onCreate()`, before using any other SDK methods. > [!WARNING] > > Call `configure()` before using any other SDK methods. Until then, `show()` resolves to `NotPresented(NotConfigured)` and other calls log `EncoreError.Integration.NotConfigured`. A second call logs a warning and returns without applying anything, so every argument, including the purchase controller, must be passed to the first call. ## Signature ```kotlin theme={null} fun configure( context: Context, apiKey: String, purchaseController: EncorePurchaseController? = null, unlock: UnlockMode = UnlockMode.Optimistic, logLevel: LogLevel = LogLevel.NONE, ) ``` ## Parameters | Name | Type | Default | Description | | - | - | - | - | | `context` | Context | required | Your application context | | `apiKey` | String | required | Your Live Key or Test Key from the Encore Dashboard settings | | `purchaseController` | [EncorePurchaseController](./purchase-controller)? | `null` | The single purchase path. Required if your app has a subscription product configured; with none registered, a configured product resolves `PublisherOutcome.NotAttempted` and nothing is ever charged | | `unlock` | [UnlockMode](#unlock-modes) | `UnlockMode.Optimistic` | The in-flow claim-verification mechanism | | `logLevel` | [LogLevel](#log-levels) | `LogLevel.NONE` | Logging verbosity level | > [!WARNING] > > The SDK has no built-in billing. If a subscription product is configured for your app but no controller is registered, the result records `PublisherOutcome.NotAttempted`, a warning is logged naming the product, and the `sdk_iap_no_purchase_controller` analytics event is emitted. Nothing is ever charged. See [EncorePurchaseController](./purchase-controller). > [!NOTE] > > Registering a controller is build-time wiring, not user state: it survives [`reset()`](./reset), so logging a user out does not require re-registering. ### Unlock modes ```kotlin theme={null} enum class UnlockMode { Optimistic, // Record the claim and finish; no in-sheet verification runs Strict, // In-sheet verification poll; unverified claims persist and // re-verify across launches (PlacementOutcome.StrictUnlockVerified) } ``` The mode selects how a claim flow runs, never how a result is read, and the SDK computes no verdict over the record; hosts branch on the raw axes. Optimistic records `Claimed`; `Verified` is reachable only under `Strict`, where an in-sheet poll can upgrade the axis in-session. With `UnlockMode.Strict`, a claim that ends unverified in-session is persisted and re-checked on later launches and foregrounds until the server settles it, surfacing on [`Encore.outcomes`](./outcomes) as `PlacementOutcome.StrictUnlockVerified`. Pending claims are cleared by [`reset()`](./reset) and by [`identify()`](./identify) with a different user, and never grant anything by themselves. ### Log levels ```kotlin theme={null} enum class LogLevel { NONE, // No logging (recommended for production) ERROR, // Only errors WARN, // Warnings and errors INFO, // Milestones, warnings, and errors DEBUG, // Everything (verbose, development only) } ``` > [!NOTE] > > Higher levels include all lower levels. For example, `INFO` will also show warnings and errors. ### API keys Encore supports two types of API keys: | Key Type | Format | Description | | - | - | - | | **Live Key** | `pk_live_...` | Production key with standard geo-filtering based on offers' configured regions | | **Test Key** | `pk_test_...` | Development key. Serves demo offers instead of your inventory, and bypasses geo-filtering | > [!NOTE] > > Use the test key (`pk_test_...`) during development to exercise the entire entitlement lifecycle end to end. It serves a demo catalog, so the claim, the advertiser page, and the unlock all work without a live campaign or a real payout. > > **Your own offers do not appear under a test key.** For that, use the live key and accept that the traffic is recorded. See [what a test key serves](/publishers/offers-api/overview#what-a-test-key-serves). > [!WARNING] > > Always use your live key (`pk_live_...`) in production builds. The test key is for development and testing only. ## Usage ### Basic configuration ```kotlin theme={null} class MyApplication : Application() { override fun onCreate() { super.onCreate() Encore.shared.configure(this, apiKey = "pk_your_api_key") } } ``` ### With a purchase controller If your app has a subscription product configured, register the controller here. Registration is build-time wiring, not user state: it survives `reset()`. ```kotlin theme={null} Encore.shared.configure( context = this, apiKey = "pk_your_api_key", purchaseController = AppPurchases(billing), unlock = UnlockMode.Optimistic, ) ``` See [EncorePurchaseController](./purchase-controller) for the contract and complete implementations. ### With debug logging (development) ```kotlin theme={null} Encore.shared.configure( context = this, apiKey = if (BuildConfig.DEBUG) "pk_test_your_key" else "pk_live_your_key", logLevel = if (BuildConfig.DEBUG) LogLevel.DEBUG else LogLevel.NONE, ) ``` > [!TIP] > > Use `LogLevel.DEBUG` during development to see detailed SDK logs, then use `LogLevel.NONE` for production builds. ## Related * [EncorePurchaseController](./purchase-controller): the contract the `purchaseController` argument must satisfy * [Encore.outcomes](./outcomes): where `UnlockMode.Strict` surfaces cross-launch verifications * [Configure the SDK](../quickstart/configure): the quickstart walkthrough # DismissReason Source: https://docs.encorekit.com/publishers/android/sdk-reference/dismiss-reason How a presented offer sheet went away The `dismissal` axis of a presented flow's [`Outcome`](./presentation-result): how the sheet actually ended. These are business outcomes, not errors. Genuine failures arrive as values in `NotPresented(NotPresentedReason.Error(...))`, never here. `value` is the analytics wire value: the same string lands in `decline_reason` on `sdk_offer_sheet_dismissed`, unmapped. ## Definition ```kotlin theme={null} enum class DismissReason(val value: String) { UserTappedClose("close_button"), UserSwipedDown("swipe_dismiss"), Cooldown("provisional_cooldown"), FlowCompleted("flow_completed"), Interrupted("interrupted"), // Emission-only analytics values; Outcome.dismissal never carries these. OfferClaimed("offer_claimed"), AppBackgrounded("app_backgrounded"), AppTerminated("app_terminated"), } ``` ## Cases | Case | Wire value | Description | | - | - | - | | `UserTappedClose` | `close_button` | The user tapped the close button or used the back gesture; on the native fallback sheet a tap outside the sheet also reports this | | `UserSwipedDown` | `swipe_dismiss` | The user dismissed by gesture. On the server-driven sheet (the default) this covers dragging down and tapping outside; on the native fallback sheet only dragging reports it | | `Cooldown` | `provisional_cooldown` | The server refused the claim with an HTTP 409 other than "already completed", and the SDK closed the sheet. In practice this is the trial limit: the user has reached your app's limit on completed offers. The name and wire value are historical; there is no cross-offer cooldown. From 2.3.0, an offer the user already completed is not reported here: the sheet drops it, and closes with `FlowCompleted` when it was the last one | | `FlowCompleted` | `flow_completed` | The flow finished on its own and the SDK closed the sheet | | `Interrupted` | `interrupted` | The SDK force-ended a dead flow (structural reconciliation), not the user | `dismissal` always records how the sheet actually ended: `FlowCompleted` when the SDK closed it on its own, and the user's gesture when a post-claim or success screen kept it up and they closed it themselves. The last three cases (`OfferClaimed`, `AppBackgrounded`, `AppTerminated`) are emission-only analytics values. `Outcome.dismissal` never carries them: a claim is advertiser-axis data, and the two lifecycle interruptions fire while the sheet is still up. > [!NOTE] > > Reasons a sheet never appeared at all (`NoOffers`, `ExperimentControl`, `NotConfigured`, `AlreadyPresenting`, `NoForegroundActivity`, `UseCaseUnavailable`, `IapFirstDeclined`, `Error`) live on [`NotPresentedReason`](./presentation-result#notpresentedreason), not here. ## Usage Most apps never branch on the dismissal: the canonical check is on the claim and purchase facts, and every non-success falls through to the original flow. ```kotlin theme={null} lifecycleScope.launch { val result = Encore.placement("cancel_flow").show() if (result.claim != null || result.publisher == PublisherOutcome.Purchased) { grantAccess() } else { result.dismissal?.let { analytics.track("offer_dismissed", it.value) } proceedWithCancellation() } } ``` ## Related * [PresentationResult](./presentation-result), the record `dismissal` is one axis of * [EncoreError](./errors), genuine failures carried as values on `NotPresented(NotPresentedReason.Error(...))` # EncoreError Source: https://docs.encorekit.com/publishers/android/sdk-reference/errors EncoreError values carried on presentation results: the four categories and how to read them All failures the Encore SDK reports are subclasses of `EncoreError`, organized into four categories by cause. `show()` never throws: presentation failures arrive as values, in `NotPresented(NotPresentedReason.Error(...))` on the [PresentationResult](./presentation-result), and claim failures as `AdvertiserOutcome.Failed(error)`. `EncoreError` extends `Exception` because errors still travel as throwables where the platform expects them: inside the SDK, and out of your [purchase controller](./purchase-controller), which throws for a real purchase failure and lands on the record as `PublisherOutcome.Failed`. ## Hierarchy ```kotlin theme={null} sealed class EncoreError(message: String, cause: Throwable? = null) : Exception sealed class Integration(message: String) : EncoreError data object NotConfigured : Integration data object InvalidApiKey : Integration data object InvalidUrl : Integration sealed class Protocol(message: String) : EncoreError class Http(status: Int, body: String?) : Protocol class Api(status: Int, code: String?, message: String) : Protocol class Decoding(cause: Throwable) : Protocol sealed class Transport(message: String, cause: Throwable?) : EncoreError class Network(cause: Throwable) : Transport class Persistence(cause: Throwable) : Transport class Domain(message: String) : EncoreError ``` ## Error categories ### Integration: SDK misuse Errors caused by incorrect SDK setup. These are preventable by following the integration guide. | Error | Message | Cause | | - | - | - | | `NotConfigured` | "Encore SDK not configured. Call Encore.configure() before use." | Called a method before `configure()` | | `InvalidApiKey` | "Invalid API key. Please check your API key and try again." | Empty or malformed API key | | `InvalidUrl` | "Failed to construct a valid URL for the API request." | Internal URL construction failure | ### Protocol: response failures Errors from the API layer: HTTP failures, malformed responses, or API-level errors. | Error | Properties | Description | | - | - | - | | `Http` | `status: Int`, `body: String?` | Non-2xx HTTP response | | `Api` | `status: Int`, `code: String?`, `message: String` | API returned a structured error | | `Decoding` | None of its own | Failed to decode JSON response; the underlying throwable is folded into `message` and is not exposed as `cause` | ### Transport: infrastructure failures Errors from the network or persistence layer. | Error | Properties | Description | | - | - | - | | `Network` | `cause: Throwable?` | Network connectivity issue (timeout, DNS, etc.) | | `Persistence` | `cause: Throwable?` | Local storage read/write failure | ### Domain: business rule violations | Error | Properties | Description | | - | - | - | | `Domain` | `message: String` | A business rule was violated | ## Usage `show()` never throws. A presentation-level failure arrives as `NotPresented(NotPresentedReason.Error(...))`, and `result.error` reads it directly: ```kotlin theme={null} lifecycleScope.launch { val result = Encore.placement("cancel_flow").show() when (val error = result.error) { null -> { /* no presentation-level failure; read the record */ } is EncoreError.Transport.Network -> Log.e("Encore", "Network error: ${error.cause?.message}") is EncoreError.Protocol.Http -> Log.e("Encore", "HTTP ${error.status}: ${error.body}") else -> Log.e("Encore", "Presentation failed: ${error.message}") } } ``` A claim that errored after the sheet appeared surfaces on the advertiser axis instead, as `AdvertiserOutcome.Failed(error)`; see [PresentationResult](./presentation-result). > [!TIP] > > In production, log `result.error` broadly. Only branch on specific subtypes when you handle them differently (e.g. showing a "no internet" message for `Transport.Network`). ## Related * [PresentationResult](./presentation-result): where `result.error` and `AdvertiserOutcome.Failed` live * [EncorePurchaseController](./purchase-controller): throwing from it records `PublisherOutcome.Failed` # identify() Source: https://docs.encorekit.com/publishers/android/sdk-reference/identify Associate your user ID with Encore Links your user ID to the SDK's anonymous ID for cross-device entitlement tracking and attribution. Call this after a successful login to sync the user's entitlements across devices. ## Signature ```kotlin theme={null} fun identify( userId: String, attributes: UserAttributes? = null ) ``` ## Parameters | Name | Type | Description | | - | - | - | | `userId` | String | Your user's unique identifier from your auth system. A blank or whitespace-only value is ignored: it never persists or replaces the current identity, and the SDK logs a warning. | | `attributes` | [UserAttributes](./user-attributes)? | Optional structured attributes to set for the user in one call. Defaults to `null`. | ## Usage ### Basic identification ```kotlin theme={null} // After successful login Encore.shared.identify(userId = user.id) ``` ### With attributes ```kotlin theme={null} Encore.shared.identify( userId = user.id, attributes = UserAttributes( email = user.email, subscriptionTier = user.plan, monthsSubscribed = user.monthsActive.toString() ) ) ``` > [!TIP] > > Call `identify()` after a successful login. On logout, call [`reset()`](./reset) to clear the user ID and cached entitlements. ## Related * [UserAttributes](./user-attributes): the attribute fields this call accepts * [setUserAttributes()](./set-user-attributes): updates attributes without changing identity * [reset()](./reset): clears the identity on logout # Encore.outcomes Source: https://docs.encorekit.com/publishers/android/sdk-reference/outcomes Passive stream of every placement outcome A `SharedFlow` that multicasts every placement outcome: each `show()` resolution (including `NotPresented`) and cross-launch strict-unlock verifications. Use it for cross-cutting observation (analytics, logging, entitlement sync) that shouldn't repeat at every call site; control flow belongs at the call site, off the returned [`PresentationResult`](./presentation-result). ## Definition ```kotlin theme={null} // On the Encore companion; exists before configure() val outcomes: SharedFlow sealed class PlacementOutcome { data class Presentation( val placementId: String, val result: PresentationResult, ) : PlacementOutcome() data class StrictUnlockVerified(val transactionId: String) : PlacementOutcome() } ``` ## Events | Event | When it fires | | - | - | | `Presentation` | A presentation ran (or was declined) and its record sealed. Emitted the moment the record seals, before any direct `onResult` delivery | | `StrictUnlockVerified` | A previously claimed offer verified server-side after its presentation ended (strict-mode cross-launch reconciliation). `transactionId` joins back to the sealed record's `ClaimedOffer.transactionId` | > [!WARNING] > > There is no replay: late subscribers miss earlier outcomes by design (results can carry user-scoped claim data). Subscribe at app startup, right after `configure()`. ## Usage ```kotlin theme={null} // Application.onCreate, right after configure. There is no replay, so // subscribe at startup. appScope.launch { Encore.outcomes.collect { outcome -> when (outcome) { is PlacementOutcome.Presentation -> analytics.log("encore_outcome", outcome.placementId, outcome.result) is PlacementOutcome.StrictUnlockVerified -> grantEntitlement(outcome.transactionId) // strict-mode cross-launch settlement } } } ``` ## Behavior * **Exists before `configure()`**: the flow lives on the `Encore` companion, so subscribing first and configuring second is safe. * **Non-suspending emission**: a slow collector can never stall the SDK; under backpressure the oldest buffered outcome is dropped. * **`StrictUnlockVerified` only occurs under `UnlockMode.Strict`**: a claim that ends unverified in-session re-verifies on later launches until the server settles it; see [unlock modes](./configure#unlock-modes) for the persistence rules. ## Related * [PresentationResult](./presentation-result): the record carried by `Presentation` * [configure()](./configure): `UnlockMode` selection # Overview Source: https://docs.encorekit.com/publishers/android/sdk-reference/overview Complete reference documentation for the Encore Android SDK Contracts for the Encore Android SDK: the methods you call, the controller you implement, and the types they exchange. > [!NOTE] > > **Looking for integration guides?** > > * **New to Encore?** Start with the [Getting Started Guide](/quickstart) for portal-guided setup > * **Step-by-step integration:** See the [Android Quickstart](/publishers/android/quickstart/install) for installation and configuration > * **Wiring results into your app:** See [Integration Patterns](/publishers/android/guides/integration-patterns) ## Core methods > [card] [configure()](/publishers/android/sdk-reference/configure) > > Initialize the SDK with your public API key, purchase controller, and unlock mode > [card] [identify()](/publishers/android/sdk-reference/identify) > > Associate your user ID with Encore for cross-device tracking > [card] [setUserAttributes()](/publishers/android/sdk-reference/set-user-attributes) > > Set structured attributes for targeting and analytics > [card] [setLanguage()](/publishers/android/sdk-reference/set-language) > > Set the language Encore serves copy in, overriding the device language > [card] [clearLanguage()](/publishers/android/sdk-reference/clear-language) > > Drop a language override so copy follows the device language again > [card] [reset()](/publishers/android/sdk-reference/reset) > > Clear user identification and cached entitlements on logout ## Presenting offers > [card] [placement()](/publishers/android/sdk-reference/placement) > > Fluent builder for presenting offers, with suspending and callback forms > [card] [EncorePurchaseController](/publishers/android/sdk-reference/purchase-controller) > > The controller your app registers so purchases run through your billing code > [card] [Encore.outcomes](/publishers/android/sdk-reference/outcomes) > > SharedFlow of every placement resolution, for passive observers ## Types and configuration > [card] [UserAttributes](/publishers/android/sdk-reference/user-attributes) > > Structured user attributes for targeting and personalization > [card] [PresentationResult](/publishers/android/sdk-reference/presentation-result) > > The factual record a presentation resolves to > [card] [DismissReason](/publishers/android/sdk-reference/dismiss-reason) > > How a presented offer sheet went away ## Error handling > [card] [EncoreError](/publishers/android/sdk-reference/errors) > > Errors the SDK reports, carried as values on the result record ## Basic integration ```kotlin theme={null} // 1. Configure at launch, registering your purchase controller if your // app sells a product through Encore offers Encore.shared.configure( context = this, apiKey = "pk_live_your_key", purchaseController = AppPurchases(billing), ) // 2. Identify the user after login Encore.shared.identify(userId = user.id) // 3. Present an offer and branch on the result lifecycleScope.launch { val result = Encore.placement("cancellation_flow").show() if (result.claim != null || result.publisher == PublisherOutcome.Purchased) { // The user claimed an offer or completed your purchase. } else { proceedWithCancellation() // dismissed, declined, nothing appeared, ... } } ``` > [!NOTE] > > `show()` never throws. Failures arrive as `NotPresented(NotPresentedReason.Error(...))` on the [`PresentationResult`](./presentation-result), so fallback logic lives in one place. > [!TIP] > > For passive observation (analytics, logging, entitlement sync), collect the [`Encore.outcomes`](./outcomes) stream once at startup instead of repeating the work at every call site. # placement() Source: https://docs.encorekit.com/publishers/android/sdk-reference/placement Present Encore offers to users via a fluent builder API ## Purpose Create and present Encore offers using a fluent builder API. Fetches available offers for the current user and presents them in a native offer sheet. `show()` returns the complete [`PresentationResult`](./presentation-result) record and never throws. ## Signature ```kotlin theme={null} // Create a placement fun placement(id: String? = null): PlacementBuilder class PlacementBuilder { // Builder configuration fun useCase(useCase: UseCase): PlacementBuilder fun headline(text: String): PlacementBuilder fun subheadline(text: String): PlacementBuilder fun publisherReward(reward: PublisherReward): PlacementBuilder // 2.3.0+ // Present (suspend); safe to call from any thread or scope suspend fun show(activity: Activity): PresentationResult suspend fun show(): PresentationResult // Present (callback); delivered exactly once, on the main thread fun show(activity: Activity, onResult: (PresentationResult) -> Unit) fun show(onResult: (PresentationResult) -> Unit) } ``` ## Methods | Method | Parameters | Description | | - | - | - | | `placement()` | `id: String?` | Creates a placement with optional identifier. If omitted, auto-generates a unique ID | | `useCase()` | `useCase: UseCase` | Which product surface this presentation is. Defaults to `UseCase.REDUCE_CHURN`; see [Use cases](#use-cases) | | `headline()` | `text: String` | Overrides the headline for this presentation. The whole string, not a fragment. Encore never translates it, so localize and pluralize it however your app already does. A blank string is ignored. See [Localization](/publishers/concepts/localization) | | `subheadline()` | `text: String` | Sibling of `headline()` for the line beneath it | | `show(activity)` | `activity: Activity` | Suspending; fetches offers, presents the sheet, and resolves once the record seals. Returns [`PresentationResult`](./presentation-result) | | `show()` | none | Suspending; auto-resolves the current foreground Activity. Nothing in the foreground resolves to `NotPresented(NoForegroundActivity)` | | `show(activity) { }` / `show { }` | `onResult: (PresentationResult) -> Unit` | Callback forms; `onResult` is delivered exactly once, on the main thread, regardless of foreground state | | `publisherReward()` | `reward: PublisherReward` | 2.3.0+. The prize your app pays for trying an offer. See [Reward for Trying](/publishers/guides/reward-for-trying) | > [!NOTE] > > `show()` never throws: every failure is a value on the result, including calling before `configure()` (`NotPresented(NotConfigured)`). The suspending forms are safe to call from any thread or scope; the body runs on a background dispatcher and UI work is hopped to Main internally. Copy overrides resolve in strict priority order, first one set wins: this override, then the copy Encore resolved for your app, then the shipped template default. A blank string is ignored, so the chain falls through rather than rendering an empty line. See [Where the copy comes from](/publishers/use-cases/post-action-reward#where-the-copy-comes-from). ### Use cases A use case selects which template the backend resolves and which funnel the presentation is counted in. It is a different axis from the placement ID: one use case holds many placements. | Case | Description | | - | - | | `UseCase.REDUCE_CHURN` | Second-chance monetization of a paywall decline. The default | | `UseCase.REWARD_USERS` | Rewarding a user *after* something they already did (a completed purchase, a milestone, a streak, a level), never as a way to sell. Claim-only: no in-app purchase runs anywhere in the path, and it never falls back to the paywall layout. If the use case is not enabled for your app, the result is `NotPresented(UseCaseUnavailable)`, a correct no-op | Each case carries a fixed wire value (`"churn-intervention"` and `"post-action-reward"`) that the backend stores and that analytics splits the funnel on. The constant names are the API surface; the wire values are the contract. ## Usage ### Suspend (recommended) ```kotlin theme={null} lifecycleScope.launch { val result = Encore.placement("cancel_flow").show() val converted = result.claim != null || result.publisher == PublisherOutcome.Purchased if (converted) grantAccess() else proceedWithCancellation() } ``` ### Callback form ```kotlin theme={null} Encore.placement("cancel_flow").show { result -> if (result.claim == null && result.publisher != PublisherOutcome.Purchased) { proceedWithCancellation() } } ``` Result delivery is not foreground-gated: the callback fires even if your Activity backgrounded mid-flow. Don't touch views without checking your own lifecycle. ### Reward surface ```kotlin theme={null} lifecycleScope.launch { Encore.placement("streak_complete") .useCase(UseCase.REWARD_USERS) .headline("That's three days in a row staying informed 🔥") .subheadline("Here's a little thank you from us") .show() } ``` ### Reward for trying From 2.3.0, `publisherReward()` describes a prize your app pays for trying an offer. When the user says they finished and Encore's server grants the prize, `result.claim?.userConfirmedCompletion` is true on the result `show()` returns (or passes to `show(onResult:)`), and your app grants the prize from that result only (the outcomes stream carries the same result, so granting from both pays twice). The server keys the prize on the ID you pass to `identify()`, so only identified users are promised one. Setup, the daily limit, and when the flag stays false: [Reward for Trying](/publishers/guides/reward-for-trying). ### With named placements for analytics ```kotlin theme={null} // Placement ID appears in your Dashboard analytics and on Encore.outcomes Encore.placement("onboarding_upsell").show { } Encore.placement("cancel_flow").show { } Encore.placement("settings_upgrade").show { } ``` > [!TIP] > > Provide a descriptive placement ID to identify this specific placement in your analytics. If omitted, a random ID is generated. ## Appearance The sheet renders in light, dark, or automatic appearance, following the appearance mode configured for your app in the Encore dashboard. Automatic is the default: the sheet follows your host app's theme, falling back to the device setting when that theme can't be read. The sheet runs in its own Activity, so this is what keeps it visually part of the app it presents over rather than following the device past a host that pins its own style. ## Claim CTA toggle `Encore.shared.isClaimEnabled` controls whether the claim CTA on offer cards is tappable. It is runtime-mutable by design: flip it to `false` to gray out and disable the claim button, and back to `true` to re-enable it. ```kotlin theme={null} Encore.shared.isClaimEnabled = false ``` ## Related * [PresentationResult](./presentation-result): the returned record and its fact readers * [Encore.outcomes](./outcomes): every resolution also lands on the passive stream * [Integration Patterns](../guides/integration-patterns): choosing between the suspend and callback forms # PresentationResult Source: https://docs.encorekit.com/publishers/android/sdk-reference/presentation-result The complete factual record of a placement presentation The result of showing an offer to a user: either nothing appeared (`NotPresented` with a reason), or a sheet appeared and the record carries two independent funnels (advertiser claim, publisher purchase) plus how the sheet was dismissed. `show()` returns this record and never throws; errors are values on it. ## Definition ```kotlin theme={null} sealed class PresentationResult { data class NotPresented(val reason: NotPresentedReason) : PresentationResult() data class Presented(val outcome: Outcome) : PresentationResult() data class Outcome( val advertiser: AdvertiserOutcome = AdvertiserOutcome.NotAttempted, val publisher: PublisherOutcome = PublisherOutcome.NotAttempted, val dismissal: DismissReason, ) } ``` The `Outcome` fields are independent axes; `NotAttempted` is a real value ("funnel open, nothing entered it"), never null. ## Fact readers Convenience properties on every result, so most call sites never need the `when`: | Reader | Type | Meaning | | - | - | - | | `result.claim` | `ClaimedOffer?` | The offer the user claimed, when the advertiser funnel reached `Claimed` or `Verified` | | `result.advertiser` | `AdvertiserOutcome?` | `null` means never presented; `NotAttempted` means presented, funnel untouched | | `result.publisher` | `PublisherOutcome?` | Your purchase controller's verdict, same null semantics | | `result.dismissal` | [`DismissReason`](./dismiss-reason)`?` | How the sheet ended, same null semantics | | `result.error` | `EncoreError?` | The presentation-level failure, when that's why nothing appeared | ```kotlin theme={null} data class ClaimedOffer( val campaignId: String, val advertiserName: String, val transactionId: String? = null, val userConfirmedCompletion: Boolean = false, // 2.3.0+: the user said they finished, and the server granted the prize ) ``` `userConfirmedCompletion` is true only when the placement passed a prize, the user said they finished the offer, and Encore's server granted the prize: the first Yes per user per offer, within your daily limit, for a user your app identified. It is still the user's word: Encore books no transaction or payout for it, and it never changes the stage (`Claimed`, or `Verified` in strict mode). It stays false in an app set to pay only when the brand confirms; credit those prizes from the `offer_completed` webhook. See [Reward for Trying](/publishers/guides/reward-for-trying). > [!NOTE] > > The record carries raw facts only; there is no SDK-computed `unlocked` or `isPurchased` verdict. What a claim means is a property of the flow that served it, so hosts branch on the axes: `result.claim != null || result.publisher == PublisherOutcome.Purchased`. The configured `UnlockMode` selects only the in-flow verification mechanism; it never changes how a result is read. ## The axes ### AdvertiserOutcome Encore's funnel: how far the claim got. ```kotlin theme={null} sealed class AdvertiserOutcome { data object NotAttempted : AdvertiserOutcome() data class Claimed(val offer: ClaimedOffer) : AdvertiserOutcome() // on-device claim data class Verified(val offer: ClaimedOffer) : AdvertiserOutcome() // confirmed in-session (Strict only) data object Cooldown : AdvertiserOutcome() // claim refused (HTTP 409) data class Failed(val error: EncoreError) : AdvertiserOutcome() } ``` | Case | Description | | - | - | | `NotAttempted` | The user never entered the claim funnel | | `Claimed(offer)` | Claim flow completed on-device; server verification not (yet) observed | | `Verified(offer)` | Server-level confirmation observed in-session. Strict mode only: Optimistic never polls, so this value never appears. | | `Cooldown` | The server refused the claim with an HTTP 409 other than "already completed". In practice this is the trial limit: the user has reached your app's limit on completed offers. From 2.3.0 an offer the user already completed is not reported as `Cooldown`: the sheet drops that offer instead | | `Failed(error)` | Claim errored; the SDK-side failure the host never saw | ### PublisherOutcome Your funnel: what your [purchase controller](./purchase-controller) reported back. ```kotlin theme={null} enum class PublisherOutcome { NotAttempted, Purchased, Cancelled, Pending, // deferred (parental approval / SCA); may complete later via Google Play Failed, } ``` | Case | Description | | - | - | | `NotAttempted` | No purchase was attempted (including when no controller is registered, or when no usable foreground Activity exists at the invocation instant) | | `Purchased` | Your controller returned `Purchased` | | `Cancelled` | The user backed out of your purchase flow | | `Pending` | Deferred (parental approval / SCA); may complete later via Google Play | | `Failed` | Your controller threw, cancelled its own coroutine, or never resolved within the ceiling | ### DismissReason How a presented sheet went away: the user's closing gesture, a server-side rejection, or the SDK ending the flow itself. Every case, its analytics wire value, and the emission-only values that never reach a record are in [`DismissReason`](./dismiss-reason). ### NotPresentedReason Why no sheet ever appeared. ```kotlin theme={null} sealed class NotPresentedReason { data object NotConfigured : NotPresentedReason() data object AlreadyPresenting : NotPresentedReason() data object NoOffers : NotPresentedReason() data object ExperimentControl : NotPresentedReason() data object NoForegroundActivity : NotPresentedReason() data object UseCaseUnavailable : NotPresentedReason() data object IapFirstDeclined : NotPresentedReason() data class Error(val error: EncoreError) : NotPresentedReason() } ``` | Case | Description | | - | - | | `NotConfigured` | `configure()` was not called | | `AlreadyPresenting` | A presentation is already in flight | | `NoOffers` | No offers matched this user; don't retry immediately | | `ExperimentControl` | Experiment control cohort; exposure logged, no UI by design | | `NoForegroundActivity` | No foreground Activity was available | | `UseCaseUnavailable` | The requested `UseCase` resolved no layout (typically not enabled for this app); a correct no-op, never an error | | `IapFirstDeclined` | A purchase-first layout ran its purchase before any UI and the user cancelled | | `Error(error)` | Network, decoding, or integration failure, carried as an `EncoreError` value | ## Usage Most call sites branch on the facts: ```kotlin theme={null} lifecycleScope.launch { val result = Encore.placement("cancel_flow").show() val converted = result.claim != null || result.publisher == PublisherOutcome.Purchased if (converted) grantAccess() else proceedWithCancellation() } ``` When the mechanism detail matters, read the record: ```kotlin theme={null} when (result) { is PresentationResult.NotPresented -> log(result.reason) is PresentationResult.Presented -> { result.claim?.let { syncEntitlement(it.campaignId, it.transactionId) } if (result.outcome.publisher == PublisherOutcome.Purchased) refreshSubscriptions() log("closed via ${result.outcome.dismissal.value}") } } ``` To distinguish an unverified claim from a verified one, read `result.advertiser` directly. ## Related * [DismissReason](./dismiss-reason): every case of the `dismissal` axis and its wire value * [Encore.outcomes](./outcomes): every result also lands on the passive stream * [EncorePurchaseController](./purchase-controller): where the `publisher` axis comes from # EncorePurchaseController Source: https://docs.encorekit.com/publishers/android/sdk-reference/purchase-controller The single purchase path: your billing code, invoked by the SDK The single purchase path: the SDK never runs purchase code you didn't write. You register a controller at [`configure()`](./configure); when a user accepts an offer that leads to a purchase, Encore invokes it with the product to buy and awaits your verdict. ## Definition ```kotlin theme={null} interface EncorePurchaseController { suspend fun purchase(activity: Activity, request: PurchaseRequest): EncorePurchaseResult } enum class EncorePurchaseResult { Purchased, Cancelled, Pending, // Deferred (parental approval / SCA); may complete later via Google Play } ``` ## PurchaseRequest What your controller receives when Encore needs a purchase. ```kotlin theme={null} data class PurchaseRequest( val productId: String, // Google Play product to purchase val placementId: String?, // the placement that triggered it val promoOfferId: String? = null, // promotional offer, when applicable val basePlanId: String? = null, // base plan to select, for multi-base-plan products ) ``` | Property | Type | Description | | - | - | - | | `productId` | `String` | The Google Play product identifier to purchase | | `placementId` | `String?` | The placement that triggered this purchase | | `promoOfferId` | `String?` | Promotional offer identifier, when applicable | | `basePlanId` | `String?` | Google Play base plan ID, when the product exposes multiple base plans. Select this base plan when routing through your own billing layer | ## Implementations ```kotlin RevenueCat theme={null} class RevenueCatController : EncorePurchaseController { override suspend fun purchase( activity: Activity, request: PurchaseRequest, ): EncorePurchaseResult { return try { val product = Purchases.sharedInstance .awaitGetProducts(listOf(request.productId)) .firstOrNull() ?: error("Product not in RC catalog: ${request.productId}") Purchases.sharedInstance.awaitPurchase( PurchaseParams.Builder(activity, product).build() ) EncorePurchaseResult.Purchased } catch (e: PurchasesTransactionException) { if (e.userCancelled) EncorePurchaseResult.Cancelled else throw e } } } ``` ```kotlin Your own billing stack theme={null} class AppPurchases(private val billing: MyBillingStack) : EncorePurchaseController { // Runs on Dispatchers.Main.immediate. Throw for real failures; map // "user cancelled" to Cancelled. Do not retain or finish the activity. override suspend fun purchase( activity: Activity, request: PurchaseRequest, ): EncorePurchaseResult { return when (billing.purchase(activity, request.productId, request.promoOfferId)) { MyOutcome.Success -> EncorePurchaseResult.Purchased MyOutcome.Cancelled -> EncorePurchaseResult.Cancelled MyOutcome.Deferred -> EncorePurchaseResult.Pending // parental approval / SCA } } } ``` A production Play Billing controller also connects the billing client, launches the flow on the `activity` you receive, and acknowledges the purchase before returning `Purchased`. Follow [Google's Play Billing integration guide](https://developer.android.com/google/play/billing/integrate) for those steps; the contract below is everything Encore requires of you. ## The contract * One invocation returns one verdict, or throws. A returned value lands on the result record as the `publisher` axis (`PublisherOutcome.Purchased` / `Cancelled` / `Pending`) and on [`Encore.outcomes`](./outcomes); a throw lands as `PublisherOutcome.Failed`. * The controller is invoked on `Dispatchers.Main.immediate`. Usually this happens inside the sheet's lifetime, so your billing UI overlays the sheet and the sheet resolves after you return. One exception: a purchase-first variant invokes your controller over your own Activity before any Encore UI exists, and returning `Cancelled` there means no sheet is shown and the result is `NotPresented(IapFirstDeclined)`. * The `activity` parameter is valid only for the duration of the call. Do not retain it; do not `finish()` it. * A thrown exception carries your error type into analytics (`controller_threw: `); cancelling your own coroutine carries only the generic `controller_threw: CancellationException`. Bound your own pre-flight steps (connecting a billing client, catalog lookups) with short timeouts; only the user-facing purchase dialog deserves long waits. * A controller that never resolves is abandoned as failed after 5 minutes. A purchase that completes late within a bounded window is still recorded and linked; beyond that, the Play server notification backstops the money facts. ## Related * [configure()](./configure), which accepts the controller and defines what happens when none is registered * [PresentationResult](./presentation-result), where the verdict lands as the `publisher` axis * [Configure the SDK](../quickstart/configure#register-a-purchase-controller) for the registration walkthrough * [Updating to 2.x](../guides/updating-to-2-x) if you are migrating an existing integration # reset() Source: https://docs.encorekit.com/publishers/android/sdk-reference/reset Clear user identification and cached entitlements Resets the current user session by clearing the user ID and all cached entitlements. Call this when a user logs out to ensure the next user session starts fresh with a new anonymous ID. > [!NOTE] > > The language set with [`setLanguage()`](./set-language) survives `reset()`. It is a preference of the device, like appearance, not user state, so a logout leaves it in place. Only [`clearLanguage()`](./clear-language) removes it. ## Signature ```kotlin theme={null} fun reset() ``` ## Parameters This method takes no parameters. ## Usage ### Basic logout flow ```kotlin theme={null} fun handleLogout() { // Clear your app's session data authService.logout() // Reset Encore to clear user ID and entitlements Encore.shared.reset() // Navigate to login screen navigateToLogin() } ``` > [!TIP] > > After calling `reset()`, the SDK automatically generates a new anonymous user ID. You don't need to call `configure()` again. > [!NOTE] > > The registered [purchase controller](./purchase-controller) survives `reset()`: it is app infrastructure, not user state. Pending strict-unlock claims do not survive; they belong to the previous user and are cleared. ## Related * [identify()](./identify): re-associates a user ID after the next login * [configure()](./configure): registers the purchase controller that survives this call # setLanguage() Source: https://docs.encorekit.com/publishers/android/sdk-reference/set-language Set the language Encore serves copy in, overriding the device language until you clear it Sets the language Encore serves its copy and offers in. It outranks the device language on every request the SDK makes. Use it when your app has its own language picker, or when the user's app language differs from their device language. > [!NOTE] > > New in Android SDK 2.3.0. React Native and Flutter forward it from the release that pins native 2.3.0. ## Signature ```kotlin theme={null} fun setLanguage(tag: String) ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `tag` | string | A well-formed BCP-47 language tag, for example `es`, `es-MX`, or `pt-BR`. The SDK normalizes its case, so `PT-br` becomes `pt-BR`, and Encore keeps only the language part, so `es-MX` serves `es`. See [Language tags](/publishers/concepts/localization#language-tags) for what is accepted | ## Behavior * The SDK keeps the language on the device until you call [`clearLanguage()`](./clear-language), so it survives relaunches. Encore never stores it on its servers. * It is a preference of the device, not user state, so [`reset()`](./reset) and logout leave it in place. * When the language changes, the SDK fetches its configuration and offers again. * Setting the language already in effect does nothing. * An invalid tag, such as `pt_BR` or `english`, is logged and ignored. `setLanguage()` never throws, and the language already in effect stays. * Before [`configure()`](./configure), the call logs that the SDK is not configured and does nothing. * The language is served only when your app has it enabled. Otherwise Encore falls back to the device languages, then your app's default language. See [Localization](/publishers/concepts/localization). * The device language is still sent as `Accept-Language`. This call adds the override that outranks it. ## Replaces the `language` attribute Setting the language through `UserAttributes(language = ...)` is deprecated. It still works and calls `setLanguage()` for you, logging a warning once per app process, and it is removed at the next major release. The language is no longer saved with the other attributes. A language saved through the attribute on an earlier release carries over the first time the new SDK starts. Unlike `setLanguage()`, the attribute and the carry-over still accept a locale identifier and turn it into a tag, so `pt_BR` becomes `pt-BR` and `de_DE@currency=EUR` becomes `de-DE`. See [the deprecated attribute](/publishers/concepts/localization#the-language-user-attribute-is-deprecated). A language set through the attribute is stored as the same override, so it also survives `reset()`. ## Usage Call it from your app's own language picker, and call `clearLanguage()` when the user picks "System default": ```kotlin theme={null} fun onLanguageChanged(code: String?) { if (code != null) { Encore.shared.setLanguage(code) } else { Encore.shared.clearLanguage() } } ``` ## Related * [clearLanguage()](./clear-language): go back to the device language * [UserAttributes](./user-attributes): the deprecated `language` attribute * [Localization](/publishers/concepts/localization): how Encore picks the language it serves # setUserAttributes() Source: https://docs.encorekit.com/publishers/android/sdk-reference/set-user-attributes Set custom attributes for targeting and analytics Stores structured attributes for the current user to power offer targeting, personalization, and analytics. Attributes are **merged** with existing attributes; they do not replace them entirely. ## Signature ```kotlin theme={null} fun setUserAttributes(attributes: UserAttributes) ``` > [!NOTE] > > Attributes are **merged**, not replaced. If you set `email` and `subscriptionTier`, then later set `monthsSubscribed`, all three attributes will be preserved. ## Parameters | Name | Type | Description | | - | - | - | | `attributes` | [UserAttributes](./user-attributes) | Structured attributes object containing user metadata for targeting and analytics. See [UserAttributes](./user-attributes) for all available fields. | ## Usage ### Basic attributes ```kotlin theme={null} Encore.shared.setUserAttributes( UserAttributes( email = "user@example.com", subscriptionTier = "premium", monthsSubscribed = "6" ) ) ``` ## Related * [UserAttributes](./user-attributes): every field, its format, and an example value * [identify()](./identify): sets a user ID and attributes in one call # UserAttributes Source: https://docs.encorekit.com/publishers/android/sdk-reference/user-attributes Structured user attributes for targeting and analytics A data class for storing user metadata used in offer targeting, personalization, and analytics. All fields are optional, and setting them merges with the attributes already stored for the user. ## Structure ```kotlin theme={null} data class UserAttributes( val email: String? = null, val firstName: String? = null, val lastName: String? = null, val phoneNumber: String? = null, val postalCode: String? = null, val city: String? = null, val state: String? = null, val countryCode: String? = null, val latitude: String? = null, val longitude: String? = null, val dateOfBirth: String? = null, val gender: String? = null, val language: String? = null, val subscriptionTier: String? = null, val monthsSubscribed: String? = null, val billingCycle: String? = null, val lastPaymentAmount: String? = null, val lastActiveDate: String? = null, val totalSessions: String? = null, val custom: Map = emptyMap(), // Last in the constructor: pass it by name, as `age = 25`. val age: Int? = null, ) ``` ## Field reference ### Identity and basic info | Field | Type | Format | Example | Description | | - | - | - | - | - | | `email` | String? | email address | `user@example.com` | User's email address | | `firstName` | String? | free-form string | `Jane` | User's first name | | `lastName` | String? | free-form string | `Doe` | User's last name | | `phoneNumber` | String? | E.164 or local | `+442071838750` | User's phone number | ### Location | Field | Type | Format | Example | Description | | - | - | - | - | - | | `postalCode` | String? | postal/ZIP code | `SW1A 1AA` | Postal or ZIP code | | `city` | String? | free-form string | `San Francisco` | City name | | `state` | String? | abbr or full | `CA` | State/province | | `countryCode` | String? | ISO 3166-1 alpha-2 | `US` | Country code | | `latitude` | String? | decimal degrees | `37.7749` | Geographic latitude | | `longitude` | String? | decimal degrees | `-122.4194` | Geographic longitude | ### Demographics | Field | Type | Format | Example | Description | | - | - | - | - | - | | `age` | Int? | whole years, 0 to 120 | `25` | The user's age. Send the lowest end of a range. A user under 18 is served age-appropriate offers with no per-user personalization. Not saved between launches: pass `dateOfBirth`, or set `age` on every launch | | `dateOfBirth` | String? | `YYYY-MM-DD` | `2001-04-18` | The user's date of birth. The SDK works the age out from it on the device and never sends the date. Given `age` too, the lower age is used. An unreadable or future date gives no age | | `gender` | String? | free-form string | `female` | User's gender. Accepted only from an app rated 18+ in its store listing | | `language` | String? | BCP-47 tag | `es`, `es-MX` | **Deprecated.** Use [`setLanguage()`](./set-language) instead. From the release that adds `setLanguage()`, setting this field calls it for you and logs a warning once. Removed at the next major release. See [Localization](/publishers/concepts/localization) | ### Subscription and billing | Field | Type | Format | Example | Description | | - | - | - | - | - | | `subscriptionTier` | String? | plan name | `free`, `premium`, `pro` | Current subscription plan/tier | | `monthsSubscribed` | String? | integer string | `6` | Number of months subscribed | | `billingCycle` | String? | enum string | `monthly`, `annual` | Billing frequency | | `lastPaymentAmount` | String? | decimal as string | `9.99` | Amount of last payment | ### Engagement | Field | Type | Format | Example | Description | | - | - | - | - | - | | `lastActiveDate` | String? | ISO 8601 datetime | `2024-03-15T14:30:00Z` | Timestamp of last activity | | `totalSessions` | String? | integer string | `42` | Total number of sessions | ### Custom attributes | Field | Type | Format | Example | Description | | - | - | - | - | - | | `custom` | Map\ | key-value pairs | `mapOf("churnRisk" to "high")` | Any additional attributes not covered above | ## Usage ```kotlin theme={null} val attributes = UserAttributes( email = "user@example.com", subscriptionTier = "premium", monthsSubscribed = "6" ) Encore.shared.setUserAttributes(attributes) ``` ## Related * [setUserAttributes()](./set-user-attributes): merges these attributes into the current user's profile * [identify()](./identify): accepts the same attributes alongside your user ID # Localization Source: https://docs.encorekit.com/publishers/concepts/localization How Encore picks each user's language, which copy it translates, which copy stays yours, and how to check what was served. Encore serves translated copy to each user in their language. The SDKs send the device or browser language for you, Encore resolves it against the languages enabled for your app, and the sheet and its offers come back in that language. Copy you pass per call is the one exception: Encore shows it exactly as you wrote it. Read this page when your app ships in more than one language, when a user reports seeing English in a translated app, or when you need to know what a `locale` field in a response means. ## How Encore picks the language Every request resolves to one served language. Encore takes the first candidate that is enabled for your app: | Order | Candidate | Where it comes from | | - | - | - | | 1 | Your app's language | `setLanguage()` in the SDKs. On the API, `?language=` on `/config` and `/ui-config`, `attributes.language` in the body of `/offers/feed`, `/offers/message`, and `/offers/search`, or `language` in the body of `/offers/catalog`. `/creators/links` has no explicit language; see [Check what was served](#check-what-was-served) | | 2 | The device or browser languages | The `Accept-Language` header, tried in the order the user ranked them | | 3 | Your app's default language | Set by Encore when your languages are enabled. `en` unless you asked for another | A candidate is used only when your app has that language enabled. One that is not enabled is skipped, not rejected. Encore walks the device's languages in order and serves the first one your app has enabled. A device set to French, then Spanish, on an app with only English and Spanish enabled gets Spanish. The app's default language is served only when none of the user's languages is enabled. English is always enabled, so a device that lists English always has a match. **Encore serves by language, not by region.** It accepts any BCP-47 tag and keeps only the language part, so `es-MX`, `es-ES`, and `es` all serve `es`. Send whichever form you already have. Two consequences worth knowing: * `pt` is translated as Brazilian Portuguese, so users in Portugal see Brazilian spelling. * `zh` is translated as Simplified Chinese, so users in Taiwan and Hong Kong see Simplified characters. ## What the SDKs send for you You do not have to do anything for a user to get their own language. | Surface | What it sends | | - | - | | iOS | The device's preferred languages as `Accept-Language` on every request | | Android | The device's languages as `Accept-Language` on every request, from Android SDK 2.3.0. Earlier releases send nothing, so set the `language` user attribute if you need translated copy on them | | Web SDK | The browser's own `Accept-Language` | | React Native, Flutter, Unity | Whatever the SDK underneath sends: the native SDK, or the web SDK in a Unity WebGL build | ## Override the language Call `setLanguage()` when your app has its own language picker, or when the user's app language differs from their device language. It outranks the device language on every request the SDK makes. The SDK keeps the language on the device, across launches, until you clear it. Encore never stores it on its servers. ```swift iOS theme={null} Encore.shared.setLanguage("es") ``` ```kotlin Android theme={null} Encore.shared.setLanguage("es") ``` ```typescript React Native theme={null} await Encore.setLanguage('es'); ``` ```dart Flutter theme={null} await Encore.shared.setLanguage('es'); ``` ```javascript Web theme={null} Encore.setLanguage('es'); ``` ```csharp Unity theme={null} Encore.SetLanguage("es"); ``` To go back to the device language, for example when the user picks "System default" in your picker, call `clearLanguage()`. It keeps the user and every other attribute. The language is a preference of the device, like appearance, not user state. `reset()` and logout leave it in place, and only `clearLanguage()` removes it. ```swift iOS theme={null} Encore.shared.clearLanguage() ``` ```kotlin Android theme={null} Encore.shared.clearLanguage() ``` ```typescript React Native theme={null} await Encore.clearLanguage(); ``` ```dart Flutter theme={null} await Encore.shared.clearLanguage(); ``` ```javascript Web theme={null} Encore.clearLanguage(); ``` ```csharp Unity theme={null} Encore.ClearLanguage(); ``` `setLanguage()` and `clearLanguage()` are new in iOS SDK 2.3.0, Android SDK 2.3.0, and the web SDK release that includes language support. React Native and Flutter add them in the release that pins native 2.3.0. On the web SDK, call `setLanguage()` after [`configure()`](/publishers/web/sdk-reference/configure); `configure()` takes no language. Reference: `setLanguage()` on [iOS](/publishers/ios/sdk-reference/set-language), [Android](/publishers/android/sdk-reference/set-language), [React Native](/publishers/react-native/sdk-reference/set-language), [Flutter](/publishers/flutter/sdk-reference/set-language), [web](/publishers/web/sdk-reference/set-language), and [Unity](/publishers/unity/sdk-reference/set-language). ### Language tags `setLanguage()` takes a language tag in the BCP-47 syntax (RFC 5646) and checks it before anything is sent. The rule is narrower than the RFC on purpose, and the same on every SDK: * The tag starts with a language code of two or three letters, for example `en`, `pt`, or `fil`. Longer language codes and old tags such as `i-klingon` are rejected. * Its parts are separated by hyphens only. `pt-BR` is accepted, `pt_BR` is not. * Case does not matter, so `PT-br` is the same as `pt-BR`. * The tag has no surrounding spaces or trailing newline. `' en'` and `'en\n'` are rejected. * A language name is not a tag. `english` is rejected; use `en`. * Extended language forms are not accepted, because Encore resolves a tag to its language and region and would pick the wrong language. `zh-yue-HK` is rejected; pass the preferred form `yue-HK`. Every SDK checks the same rule, so a tag accepted on one platform is accepted on all of them. After the check, a withdrawn ISO 639 code is replaced by its current one: `iw` becomes `he`, `in` becomes `id`, `ji` becomes `yi`, and `jw` becomes `jv`. Every SDK and Encore's own resolver do this, so `setLanguage("iw")` serves Hebrew everywhere. Encore's resolver also serves `nb` (Norwegian Bokmål) as `no`. Every SDK also normalizes the case of an accepted tag, following RFC 5646: the language is lowercase, a region is uppercase, a script is title case, and everything else is lowercase. `PT-br` becomes `pt-BR`, and `en-US-X-Twain` becomes `en-US-x-twain`. The language you set stays on the device. It is never sent as a user attribute or in an `identify()` call, and Encore's analytics record only the language that was served. What happens to a tag that fails the check depends on the SDK: | SDK | Invalid tag | | - | - | | iOS, Android, web | Logged and ignored. The language already in effect stays | | React Native | The returned `Promise` rejects: a `RangeError` for a malformed tag, a `TypeError` for a value that is not a string | | Flutter | The returned `Future` completes with an `ArgumentError` | | Unity | `SetLanguage()` throws `ArgumentException` only for a null or empty tag. Any other invalid tag goes to the SDK underneath, which logs it and ignores it | ### The `language` user attribute is deprecated Earlier releases set the language through the `language` field of `setUserAttributes()`. That field still works: from the releases in the preceding paragraph, setting it calls `setLanguage()` for you and logs a deprecation warning once. It is removed at the next major release, so move to `setLanguage()`. A language your app saved through the attribute on an earlier release carries over the first time the new SDK starts, so users keep their language when they update. A language set through the attribute is stored as the same override, so it also survives `reset()`. Because some apps pass a locale identifier, the deprecated attribute still accepts one and turns it into a tag before forwarding it: surrounding spaces are trimmed, anything from `@` on is dropped, and `_` becomes `-`, so `de_DE@currency=EUR` becomes `de-DE` and `pt_BR` becomes `pt-BR`. The first-launch carry-over does the same, so no user loses their language on upgrade. `setLanguage()` itself is strict and accepts none of these forms; see [Language tags](#language-tags). ## What Encore translates Encore translates the copy it serves from its own side. Once a language is enabled for your app, these arrive translated: * The headline and subheadline you set for your app in the Encore dashboard * Use-case copy: the reward headline and subheadline on [Reward Users](/publishers/use-cases/post-action-reward) * The copy inside each sheet variant, including its button labels * Campaign copy: each offer's `perk` on `/offers/feed`, `/offers/message`, `/offers/catalog`, `/offers/search`, and [`/creators/links`](/publishers/offers-api/reference/creator-links), and its display properties on the responses that carry them (`/offers/feed`, `/offers/catalog`, and `/offers/search`) * Category names on `/offers/search`, as `categoryDisplayName` and `categoryGroupDisplayName` (see [Offer search](#offer-search)) * The SDK's own button and status words (see [SDK strings](#sdk-strings)) Offer creative text (`title`, `subtitle`, `description`, `ctaText`, `tooltipText`, and the redemption instructions) is no longer translated. Creative text that already has translations keeps serving them. New creative text is shown in its source copy, and the campaign copy around it is translated. Encore machine-translates this copy and checks each result automatically. What happens next depends on where the copy is shown: * Your app's own copy (the dashboard headline and subheadline, and use-case copy) goes live once it passes the checks. * Offer copy is shared by every app that runs the offer, so a person at Encore approves each machine translation before it goes live. This includes a perk Encore set for your app alone. * Sheet-variant copy, SDK strings, and category names are also shared by every app, so a person at Encore approves each translation before it goes live. When the English of an offer's copy changes, its old translations stop serving, and the new English shows until the new translations are approved. The Encore team can also correct any string by hand. Once approved, a hand correction always wins over the machine translation. A field without a translation yet falls back to its source copy on its own. One untranslated field never blanks the sheet or pulls the rest of it back into English. ## What stays yours Copy you pass per call is never translated. That means `.headline()` and `.subheadline()` on the placement builder in the iOS, Android, React Native, and Flutter SDKs, `.Headline()` and `.Subheadline()` in the Unity package, and the `headline` and `subheadline` placement options in the Web SDK. Encore shows the string exactly as you passed it, so localize it the way your app already localizes its own strings. ```swift theme={null} let result = await Encore.shared.placement("milestone_reached") .useCase(.rewardUsers) .headline(String(localized: "reward.headline")) // your string, your translation .show() ``` Reference: [`placement()` on iOS](/publishers/ios/sdk-reference/placement). The per-call value still outranks the Encore-resolved copy. If you pass an English headline to a Spanish user, the headline stays English while the rest of the sheet is Spanish. Pass a per-call headline only when you can supply it in the user's language, and otherwise let the translated copy through. The full order is in [Where the copy comes from](/publishers/use-cases/post-action-reward#where-the-copy-comes-from). ## Enabling languages Encore enables languages for each app. To add one, contact [admin@encorekit.com](mailto:admin@encorekit.com) with the app and the languages you want. Encore can translate a language for your app before enabling it, so the copy can be read first, but no user is served a language until it is enabled. Until then, every user of that app gets the default language. * English is always enabled and cannot be turned off. * A new language can be enabled only once the SDK's own strings are approved in it, so a sheet never mixes translated copy with English buttons. Languages already enabled for your app keep serving. ## Check what was served `/config`, `/offers/search`, and `/offers/catalog` report the language they served in a `locale` field. It is always language-only, for example `es`. Compare it with the language you asked for to see whether a request fell back. `/offers/feed`, `/offers/message`, and `/creators/links` translate their copy the same way but return no `locale`. In every row, a language is used only when your app has it enabled; otherwise the next source decides. | Endpoint | Where the language comes from | `locale` in the response | | - | - | - | | `GET /config` (every SDK) | `?language=`, then `Accept-Language`, then the app default | Yes | | `POST /offers/search` (Web SDK) | `attributes.language` in the body, then `Accept-Language`, then the app default | Yes | | [`POST /offers/catalog`](/publishers/offers-api/reference/catalog) | `language` in the body, then `Accept-Language`, then the app default | Yes | | [`POST /offers/feed`](/publishers/offers-api/reference/feed) | `attributes.language` in the body (required), then `Accept-Language`, then the app default | No | | [`POST /offers/message`](/publishers/offers-api/reference/message) | `attributes.language` in the body (required), then `Accept-Language`, then the app default | No | | [`POST /creators/links`](/publishers/offers-api/reference/creator-links) | `Accept-Language`, then the app default. There is no `language` body field | No | `?language=` on `/config` works the same way as `setLanguage()`: region codes are stripped and it outranks `Accept-Language`. The SDKs add it for you after `setLanguage()`. The legacy `/ui-config` endpoint accepts the same parameter. To see what a device receives, request the config with a language hint and read `locale`: ```bash theme={null} curl -s "https://api.encorekit.com/encore/publisher/sdk/v1/config?userId=test-user&sdkVersion=2.0.0&language=es" \ -H "X-API-Key: pk_test_your_key" | jq '.locale' ``` `"es"` means Spanish is enabled and was served. Your default language, usually `"en"`, means Spanish is not enabled for the app yet. ## Right-to-left languages When the served language is Arabic, Hebrew, Persian, or Urdu, the sheet lays itself out right to left. Text aligns to the start edge, arrows and chevrons point the other way, and swipes on carousels and the slide-to-claim control follow reading order. On iOS, Android, and web the direction follows the served language, not the host app, so English copy shown to a user with an Arabic device stays left to right. The Web SDK also sets `lang` and `dir` on the dialog, so screen readers use the right voice. ## Offline and first launch The iOS and Android SDKs cache the last config they received, stamped with the language it was fetched for. A cached copy is only reused for the same language. After a language change the SDK fetches the copy again in the new language. If that copy cannot arrive in time, for example offline, and there is no cached copy for the language, the sheet renders the copy shipped inside the SDK. That built-in copy is English. ## Offer search `POST /offers/search` is the call the Web SDK makes to fill its sheet. From the September 2026 backend release, each offer in its response carries two display names in the served language: | Field | Type | What it holds | | - | - | - | | `categoryDisplayName` | string \| `null` | `category` translated for display. `null` when the offer has no category | | `categoryGroupDisplayName` | string \| `null` | `categoryGroup` translated for display, for example the label on a category tab | `category` and `categoryGroup` stay English on every response, so group and filter on them and show the display names. Both display names fall back to English when a translation is missing. ## SDK strings Encore also translates the SDK's own words: button labels such as "Claim", status lines on the confirmation screens, and accessibility labels. You do nothing to get them. From the September 2026 backend release, the `/config` response carries them under `ui.values` in two maps: * `strings` maps a string id to its translated text. * `plurals` maps a string id to its plural forms from the Unicode Common Locale Data Repository (CLDR) (`zero`, `one`, `two`, `few`, `many`, `other`), where `other` is always present and `${count}` stands for the number. Every SDK writes the number with ASCII digits (`0` to `9`) and no thousands separator, in every language, so `1200` stays `1200`. Each map holds only the ids that have an approved translation in the served language, and neither is sent for English. The SDK uses its built-in English for any id that is missing, one id at a time, so a partly translated language never blanks a button. iOS SDK 2.3.0, Android SDK 2.3.0, and the web SDK release that includes language support read these maps. React Native and Flutter read them from the release that pins native 2.3.0. Older SDKs ignore them and show English. ## Related * [Where the copy comes from](/publishers/use-cases/post-action-reward#where-the-copy-comes-from): the priority order for headline and subheadline * `setLanguage()`: [iOS](/publishers/ios/sdk-reference/set-language), [Android](/publishers/android/sdk-reference/set-language), [React Native](/publishers/react-native/sdk-reference/set-language), [Flutter](/publishers/flutter/sdk-reference/set-language), [Web](/publishers/web/sdk-reference/set-language), [Unity](/publishers/unity/sdk-reference/set-language) * `clearLanguage()`: [iOS](/publishers/ios/sdk-reference/clear-language), [Android](/publishers/android/sdk-reference/clear-language), [React Native](/publishers/react-native/sdk-reference/clear-language), [Flutter](/publishers/flutter/sdk-reference/clear-language), [Web](/publishers/web/sdk-reference/clear-language), [Unity](/publishers/unity/sdk-reference/clear-language) # Add Subscription Product Source: https://docs.encorekit.com/publishers/flutter/guides/add-subscription-product Set up the App Store and Google Play subscriptions Encore purchases when a user accepts an offer. ## Overview > [!NOTE] > > This step applies to **Reduce Churn** placements only. A [reward placement](/publishers/guides/reward-placements) never runs a purchase, so an app that presents only reward placements can skip it. Now that placements are presenting, choose the subscription product Encore offers. When a user accepts an offer at a churn moment, Encore triggers a real subscription purchase using the product you select, and the native stores (App Store and Google Play) handle all entitlement state. Since Flutter apps run on both iOS and Android, you complete the store-console setup once per platform. Each store's Platform Integration page walks through connecting the catalog and picking (or creating) the product: > [card] [App Store Subscription Product](/publishers/ios/platform-setup/subscription-product) > > Connect your App Store Connect catalog and pick the subscription Encore offers, or let Encore create one for you. > [card] [Google Play Subscription Product](/publishers/android/platform-setup/subscription-product) > > Connect your Google Play catalog and pick the subscription, base plan, and offer, or let Encore create one for you. *** ## Configure Analytics To track subscription events and measure offer impact, forward each store's server notifications to Encore: > [card] [App Store Server Notifications](/publishers/ios/platform-setup/server-notifications) > > Point Apple's subscription lifecycle webhooks at Encore, or forward them from your own server. > [card] [Real-Time Developer Notifications](/publishers/android/platform-setup/server-notifications) > > Point Google Play's Pub/Sub notifications at Encore, or forward them from your own server. *** ## Next Steps * [Encore Dashboard](https://dashboard.encorekit.com): monitor analytics and manage your app * [iOS SDK Reference](/publishers/ios/sdk-reference/configure): the API contract for the underlying iOS SDK * [Android SDK Reference](/publishers/android/sdk-reference/configure): the API contract for the underlying Android SDK # Flutter Integration Patterns Source: https://docs.encorekit.com/publishers/flutter/guides/integration-patterns Where the purchase controller, the call site, and the outcomes stream each belong in a Flutter app. ## Overview SDK 2.0 replaced the 1.x choice between "async result" and "global handlers" with three pieces that each have one job. There is no pattern to pick: the question is only *where each piece lives* in your app. | Piece | Job | Where it goes | | :- | :- | :- | | `EncorePurchaseController` | Runs a purchase when a user accepts an offer | Passed to `Encore.shared.configure`, in `main()` | | `show()` result | Drives control flow for *this* call site | At the call site, awaited | | `Encore.shared.outcomes` | Passive observation: analytics, app-owned state, debug overlays | Subscribed once at startup | The rule of thumb: **control flow at the call site, observation on the stream, purchases in the controller.** Nothing in 2.0 requires a global handler to run your fallback. *** ## 1. The purchase controller Dart cannot implement a Swift protocol or a Kotlin interface, so each native plugin owns the conformance and forwards over the method channel, suspending until Dart answers. What you implement is a plain Dart interface, registered once. ```dart theme={null} class AppPurchases implements EncorePurchaseController { @override Future purchase(EncorePurchaseRequest request) async { try { await billing.purchase(request.productId, basePlanId: request.basePlanId); return EncorePurchaseResult.purchased; } on UserCancelled { return EncorePurchaseResult.cancelled; } on PurchaseDeferred { return EncorePurchaseResult.pending; } // Anything else propagates — Encore records EncorePublisherOutcome.failed. } } Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Encore.shared.configure( apiKey: 'pk_live_...', purchaseController: AppPurchases(), ); runApp(const MyApp()); } ``` Registration happens at `configure` and nowhere else, because both native SDKs bind the controller once there and expose no setter. It survives `reset()`. > [!WARNING] > > **Map your deferred branch to `pending`, not `cancelled`.** Ask to Buy (parental approval) on iOS, and SCA or a pending Play transaction on Android, mean the user has neither bought nor abandoned. The store's webhook settles it later, possibly days later. Reporting it as a cancellation records a live sale as a decline, on the presentation record and everywhere downstream of it. This is exactly what 1.x's boolean `onPurchaseRequestResult` forced, and the reason it was removed rather than shimmed. The bridge refuses to guess: an answer it does not recognize throws rather than defaulting to `purchased`, since a phantom success grants access nobody paid for. Registering none is supported: the SDK never attempts a purchase at all, and every presentation records `EncorePublisherOutcome.notAttempted`. *** ## 2. Control flow at the call site `show()` never throws, so there is no `try`/`catch` to write and no case where your fallback silently fails to run. ```dart theme={null} Future onCancelTapped(BuildContext context) async { final result = await Encore.placement('cancel_flow').show(); final converted = result.claim != null || result.publisher == EncorePublisherOutcome.purchased; if (!context.mounted) return; if (converted) { Navigator.of(context).pushReplacementNamed('/home'); } else { await proceedWithCancellation(); } // Code that runs in both branches lives here, written once. analytics.track('cancel_flow_resolved'); } ``` ### When the widget can't see your continuation logic In 1.x this was the reason to reach for global handlers. In 2.0, keep the call site local and hand the *decision* outward: ```dart theme={null} Future presentThenContinue( String placementId, Future Function() onDeclined, ) async { final result = await Encore.placement(placementId).show(); final converted = result.claim != null || result.publisher == EncorePublisherOutcome.purchased; if (!converted) await onDeclined(); return result; } ``` One helper, used from every call site, keeps the "did Encore intercept" reading in a single place without a global handler whose firing order you have to reason about. *** ## 3. Observation on the stream ```dart theme={null} Encore.shared.outcomes.listen((outcome) { switch (outcome) { case EncorePlacementPresentation(:final placementId, :final result): analytics.log('encore_presentation', placementId, result); case EncoreStrictUnlockVerified(:final transactionId): entitlements.refresh(transactionId); } }); ``` Unlike the 1.x `setOn*` setters, which replaced the previous handler, this is a broadcast stream: several listeners can subscribe at once, matching the `AsyncStream` (iOS) and `SharedFlow` (Android) it bridges. There is **no replay**. The native streams buffer nothing for late subscribers, by design, since outcomes can carry user-scoped claim data. Subscribe at startup if you want all of them. The stream is also the only way to see `EncoreStrictUnlockVerified`, a strict-mode claim the server confirmed after its flow ended, possibly on a later launch. No `show()` return value can carry that, which is the stream's reason for existing. It requires `EncoreUnlockMode.strict` on `configure`; under the default `optimistic` it never fires. *** ## Reading the record ```dart theme={null} sealed class EncorePresentationResult {} final class EncoreNotPresented extends EncorePresentationResult { final EncoreNotPresentedReason reason; final String? errorType; final String? errorMessage; } final class EncorePresented extends EncorePresentationResult { final EncorePresentationOutcome outcome; // advertiser, publisher, dismissal } ``` Dart 3 sealed classes give you an exhaustive `switch`, and the compiler tells you when you've forgotten a branch. Fact readers (`result.claim`, `result.advertiser`, `result.publisher`, `result.dismissal`) let a call site that cares about one axis skip the pattern match; they return `null` when nothing was presented, which is a different fact from `notAttempted`. > [!NOTE] > > `EncoreNotPresented` is not a synonym for "something went wrong". It also covers `noOffers`, `experimentControl`, and `useCaseUnavailable`, all healthy states that still need your original flow to continue. Run your fallback off the whole no-claim, no-purchase reading, not off the `error` reason. The publisher, dismissal, and not-presented enums map an unrecognized wire value to an explicit `unknown` case. An unrecognized advertiser outcome reads as `EncoreAdvertiserNotAttempted`. *** ## Platform-specific notes * **Native renders the UI.** SwiftUI on iOS, Compose on Android. The plugin is a thin bridge over platform channels. * **Some axis values are platform-specific.** `noForegroundActivity` and `iapFirstDeclined` are Android-only; `unsupportedOS`, `userCancelled`, `lastOfferDeclined`, and `dismissed` are iOS-only. Code written against the full enum is portable. * **Android's `Activity` is absorbed by the plugin**, not surfaced to Dart. It is valid only for the duration of the call and must never be retained, so one Dart contract covers both platforms. * **`Encore.placement(id)` is static.** Both `Encore.placement('id')` and `Encore.shared.placement('id')` work; the instance form is deprecated. *** ## See also * [Quickstart: Present Offers](/publishers/flutter/quickstart/present-offers) * [Updating to 2.x](./updating-to-2-x), if you are migrating an existing 1.x integration * Platform detail: [iOS SDK reference](/publishers/ios/sdk-reference/presentation-result) and [Android SDK reference](/publishers/android/sdk-reference/presentation-result) # Routine updates Source: https://docs.encorekit.com/publishers/flutter/guides/updating-sdk How to update the Encore Flutter SDK and how its versioning works. ## Overview The Encore Flutter SDK is published as the public **`encore_flutter`** package on [pub.dev](https://pub.dev/packages/encore_flutter). Because the plugin bundles the native iOS (`EncoreKit` CocoaPod) and Android (`com.encorekit:encore` AAR) SDKs, updating is a two-part flow: bump the Dart package, then refresh the native iOS pods so the updated `EncoreKit` binary is picked up. *** ## Versioning policy Encore follows [Semantic Versioning](https://semver.org): | Version change | Example | What it means | | :- | :- | :- | | Patch | `2.0.0` → `2.0.1` | Bug fixes only. Always safe to update. | | Minor | `2.0.1` → `2.1.0` | New features, backward compatible. Safe to update. | | Major | `1.0.x` → `2.0.0` | Breaking changes. Follow that version's migration guide. | Use a caret constraint so patch and minor updates arrive through a routine `flutter pub upgrade` and a major version never lands without you opting in: ```yaml theme={null} dependencies: encore_flutter: ^2.0.0 ``` The plugin pins the native SDKs it was built against, so a plugin update is also a native update on both platforms. That is why a plugin major tracks a native major. > [!NOTE] > > Upgrading across a major version? See [Updating to 2.x](./updating-to-2-x) for the step-by-step migration guide. *** ## Check the current and latest version Your currently resolved version is recorded in `pubspec.lock`. The latest published version is listed on the package's [pub.dev page](https://pub.dev/packages/encore_flutter). You can also check from the command line: ```bash theme={null} flutter pub outdated ``` This lists your current, upgradable, and latest resolvable versions for every dependency, including `encore_flutter`. *** ## Update the package **1. Upgrade within your major version** ```bash theme={null} flutter pub upgrade encore_flutter ``` This resolves the newest release your constraint allows, without editing `pubspec.yaml`. **2. Refresh the native iOS pods** The `EncoreKit` CocoaPod is pulled in transitively by the plugin. Run `pod install` with `--repo-update` so CocoaPods fetches the newest spec and installs the updated native binary: ```bash theme={null} cd ios && pod install --repo-update && cd .. ``` > [!NOTE] > > Android requires no separate step: the updated `com.encorekit:encore` AAR is resolved automatically by Gradle on your next build. **3. Rebuild the app** ```bash theme={null} flutter run ``` Building fresh ensures both the Dart layer and the updated native SDKs are compiled in. *** ## Verify the update Confirm the resolved version in `pubspec.lock` matches the latest release in your major, or re-run: ```bash theme={null} flutter pub outdated ``` *** If you encounter issues after updating, reach out to [admin@encorekit.com](mailto:admin@encorekit.com). # Updating to 2.x Source: https://docs.encorekit.com/publishers/flutter/guides/updating-to-2-x Step-by-step migration guide for upgrading the encore_flutter plugin from 1.x to 2.x. ## Overview `encore_flutter` 2.0 moves the plugin onto the native Encore 2.0 surface (EncoreKit 2.0.0 on iOS, `com.encorekit:encore` 2.0.1 on Android). Both natives removed the global purchase and passthrough handlers and replaced the presentation result with a factual two-funnel record, so this is a breaking release: * **Purchases run through an `EncorePurchaseController`** you implement and register at `configure`. The SDK never runs purchase code you didn't write. * **`show()` never throws.** Every failure, including "nothing was presented", is a value on the result. * **The result is a factual record**, not a verdict: two independent funnels plus how the sheet ended. * **`Encore.shared.outcomes`** is the passive observation channel, and the only way to see cross-launch verifications. > [!WARNING] > > **There is no compatibility shim for `onPurchaseRequest`.** The new answer is three-valued and 1.x's `onPurchaseRequestResult(bool)` has no way to say "deferred". A shim would have to guess, and every guess reports an Ask to Buy or SCA purchase as either a decline or a completed sale. Silently misreporting revenue is worse than a compile error, so the 1.x API is gone rather than quietly wrong. *** ## Step 1: Update the package ```yaml theme={null} dependencies: encore_flutter: ^2.0.0 ``` ```bash theme={null} flutter pub get cd ios && pod install --repo-update && cd .. ``` 2.0 removes the 1.x surface outright rather than deprecating it, so every call site that needs attention fails to analyze. Run `flutter analyze`: the errors are your migration worklist, and each one maps to a step below. The [removed API table](#removed-apis-at-a-glance) maps every 1.x symbol to its replacement. *** ## Step 2: Implement a purchase controller This is the largest change. Dart cannot implement a Swift protocol or a Kotlin interface, so each native plugin owns the conformance and forwards over the method channel, suspending until Dart answers. The Dart-side API is an interface you implement and register at `configure`, mirroring where both natives bind it. **Before** ```dart theme={null} Encore.shared.onPurchaseRequest((request) async { final products = await Purchases.getProducts([request.productId]); if (products.isNotEmpty) { await Purchases.purchaseStoreProduct(products.first); } }); ``` **After** ```dart theme={null} class AppPurchases implements EncorePurchaseController { @override Future purchase(EncorePurchaseRequest request) async { final products = await Purchases.getProducts([request.productId]); if (products.isEmpty) throw StateError('unknown product ${request.productId}'); try { await Purchases.purchaseStoreProduct(products.first); return EncorePurchaseResult.purchased; } on PlatformException catch (e) { if (PurchasesErrorHelper.getErrorCode(e) == PurchasesErrorCode.purchaseCancelledError) { return EncorePurchaseResult.cancelled; } rethrow; // a real failure — Encore records it as EncorePublisherOutcome.failed } } } await Encore.shared.configure( apiKey: 'pk_...', purchaseController: AppPurchases(), ); ``` Two things changed beyond the shape: 1. **The controller reports an outcome.** 1.x's `onPurchaseRequest` could not report success at all, and `onPurchaseRequestResult` could only report a `bool`. The controller returns an `EncorePurchaseResult`, and an unrecognized answer throws rather than defaulting to `purchased`, because a phantom success grants access nobody paid for. 2. **Throwing is meaningful.** A throw is recorded as `EncorePublisherOutcome.failed`, and the flow continues. Map your billing layer's "user cancelled" throw to `EncorePurchaseResult.cancelled` rather than letting it propagate. ### `pending` is not a failure ```dart theme={null} enum EncorePurchaseResult { purchased, cancelled, pending } ``` `pending` means the store **deferred** the purchase: Ask to Buy (parental approval) on iOS, or SCA or a pending Play transaction on Android. The user has neither bought nor abandoned. The purchase may settle minutes or days later, and the store's eventual webhook is the source of truth. 1.x's boolean `onPurchaseRequestResult` could not express this state, so it reported every deferred purchase as a failure. When you map your billing layer onto `EncorePurchaseResult`, returning `cancelled` for a deferred purchase silently misreports revenue: a sale still in flight is recorded as a decline, on the presentation record and in every analytics surface downstream. Route your billing library's deferred branch to `EncorePurchaseResult.pending`. ### Registration The controller can only be registered at `configure`, because both native SDKs bind it once there and expose no setter afterwards. `hasPurchaseController` is sent explicitly, so native builds its bridge only when Dart registered one. Registering none is a supported configuration, not a broken one: the SDK never attempts a purchase at all, which is a different and more accurate behavior than registering a controller that always fails. Every presentation records `EncorePublisherOutcome.notAttempted`. > [!NOTE] > > The controller survives [`reset()`](../quickstart/user-management). It is app-level infrastructure, not user state, so logging a user out does not require re-registering it. > [!NOTE] > > Android's native controller also hands over the foreground `Activity`. The plugin **absorbs** it, since it is valid only for the duration of the call and must never be retained, and iOS has no equivalent. One Dart contract therefore covers both platforms. *** ## Step 3: Update `show()` call sites and results `show()` never throws. `EncorePresentationResult` is now a sealed pair, and the 1.x `Granted` / `Claimed` / `NotGranted` cases are gone. **Before** ```dart theme={null} switch (result) { case EncorePresentationResultGranted(:final offerId): grantAccess(); case EncorePresentationResultNotGranted(:final reason): proceedWithCancellation(reason); } ``` **After** ```dart theme={null} final result = await Encore.placement('cancel_flow').show(); switch (result) { case EncoreNotPresented(:final reason): proceedWithCancellation(reason); case EncorePresented(:final outcome): final converted = outcome.advertiser is EncoreAdvertiserClaimed || outcome.advertiser is EncoreAdvertiserVerified || outcome.publisher == EncorePublisherOutcome.purchased; converted ? grantAccess() : proceedWithCancellation(outcome.dismissal); } ``` `result.claim` reads the claimed offer directly when you don't want to pattern-match the whole record: ```dart theme={null} final converted = result.claim != null || result.publisher == EncorePublisherOutcome.purchased; ``` The record carries **raw facts only**. There is deliberately no SDK-computed "unlocked" verdict, because what a claim means is a property of the variant flow that served it, and a projection over app-global config can contradict the flow that actually ran. | 1.x case | Closest 2.0 reading | | :- | :- | | `EncorePresentationResultGranted` | `EncorePresented` with `result.claim != null` | | `EncorePresentationResultClaimed` | `EncorePresented` with `result.claim != null` | | `EncorePresentationResultNotGranted(reason)` | Either `EncoreNotPresented(reason)` (nothing was shown) or `EncorePresented` with no claim and no purchase; `outcome.dismissal` says how it ended | | A thrown presentation error | `EncoreNotPresented(reason: EncoreNotPresentedReason.error)` with `errorType` / `errorMessage` | > [!NOTE] > > `EncoreNotPresented` is not a synonym for failure. It also covers `noOffers`, `experimentControl`, and `useCaseUnavailable`, all healthy states that still need your original flow to continue. Every decoder maps an unrecognized value to an explicit `unknown` rather than to a neighbouring case, so a newer native can never be silently misread as `notAttempted`. *** ## Step 4: Replace `onPassthrough` and `onPurchaseComplete` Both are removed, and each was verified absent from both native SDKs before deletion. * **`onPurchaseComplete`**, along with `EncoreBillingPurchaseResult`, is gone: the SDK no longer runs purchases itself, so there is no native purchase to report, and your controller already sees every purchase it runs. * **`onPassthrough`** becomes a reading of the record. "Encore did not intercept" is now: ```dart theme={null} final passedThrough = result is EncoreNotPresented || (result.claim == null && result.publisher != EncorePublisherOutcome.purchased); ``` For cross-cutting observation, subscribe to the outcomes stream instead: ```dart theme={null} Encore.shared.outcomes.listen((outcome) { switch (outcome) { case EncorePlacementPresentation(:final placementId, :final result): analytics.log('encore_presentation', placementId, result); case EncoreStrictUnlockVerified(:final transactionId): entitlements.refresh(transactionId); } }); ``` The stream is multicast and has **no replay**: subscribe at startup, or you miss outcomes emitted before you subscribed. It earns its place through `EncoreStrictUnlockVerified`, which resolves after its flow ended, possibly on a later launch, and so can never be a `show()` return value. `EncoreUnlockMode.strict` on `configure` is what makes that event reachable. *** ## Removed APIs at a glance | 1.x surface | 2.0 replacement | | :- | :- | | `Encore.shared.onPurchaseRequest(handler)` | `EncorePurchaseController` passed to `configure(purchaseController:)` | | `Encore.shared.onPurchaseRequestResult(bool)` | The controller's `EncorePurchaseResult` return value, which can also say `pending` | | `Encore.shared.onPurchaseComplete(handler)` and `EncoreBillingPurchaseResult` | Removed; your controller already knows | | `Encore.shared.onPassthrough(handler)` | Read the record at the call site, or subscribe to `Encore.shared.outcomes` | | `Encore.shared.placements.setClaimEnabled(bool)` and `EncorePlacements` | `Encore.shared.setClaimEnabled(bool)` | | `EncorePresentationResultGranted` / `Claimed` / `NotGranted` | `EncorePresented(outcome)` / `EncoreNotPresented(reason)` | | A thrown `show()` | `EncoreNotPresented(reason: EncoreNotPresentedReason.error)` | | *(no 1.x equivalent)* | `Encore.shared.outcomes`, the outcomes stream | | *(no 1.x equivalent)* | `EncoreUnlockMode` on `configure` | | *(no 1.x equivalent)* | `EncorePurchaseRequest.basePlanId` | *** ## Behavior changes to be aware of These analyze fine but behave differently at runtime: * **Errors no longer throw.** Old `try`/`catch` fallback blocks around `show()` are dead code; run fallback off `EncoreNotPresented` instead. * **Claim-then-purchase records both funnels.** 1.x collapsed the flow to a single winner. 2.0 carries the advertiser claim and `publisher: purchased` side by side. * **A deferred purchase is now visible**, provided your controller returns `EncorePurchaseResult.pending` for it. * **`EncoreUseCase` now actually reaches the native SDK.** In 1.x the value was dropped at the bridge, because neither native plugin implemented the channel method carrying it, so `EncoreUseCase.rewardUsers` could never present and `headline` / `subheadline` overrides were silently ignored. Both bridges now forward all three on every `show()`, which also retires the `use_case_unsupported` degradation path. *** ## New in 2.0 ```dart theme={null} await Encore.shared.configure( apiKey: 'pk_...', purchaseController: AppPurchases(), unlock: EncoreUnlockMode.strict, ); await Encore.placement('milestone_reached') .useCase(EncoreUseCase.rewardUsers) .headline("That's three days in a row staying informed 🔥") .subheadline("Here's a little thank you from us") .show(); ``` * **The outcomes stream**, including late `EncoreStrictUnlockVerified` events that survive process death. * **`EncoreUnlockMode`.** `strict` verifies claims server-side and persists unverified claims across launches; `optimistic` (the default, and 1.x's behavior) records the claim and finishes. * **A working reward surface**, claim-only, which never falls back to the churn-intervention sheet. * **`EncoreClaimedOffer`** carrying `campaignId`, `advertiserName`, and the `transactionId` that joins a claim to its later verification. *** ## Verify the migration > [!TIP] > > Confirm each of these before shipping: 1. `flutter analyze` is clean, with no references to removed 1.x APIs. 2. If your Encore flows include an in-app purchase, an `EncorePurchaseController` is passed to `configure`. 3. Your controller returns `pending` for deferred purchases, and `cancelled` only for a genuine user cancellation. 4. Every fallback path runs off the no-claim, no-purchase reading, not a `catch` block. 5. Test the full flow on a device on both platforms: present a placement, claim an offer, complete a purchase, and dismiss without acting. Each path should resolve exactly once with the result you expect. *** If you hit anything this guide doesn't cover, reach out to [admin@encorekit.com](mailto:admin@encorekit.com). # Configure the SDK Source: https://docs.encorekit.com/publishers/flutter/quickstart/configure Initialize the Encore SDK with your API key and purchase controller at app startup. ## Overview As soon as your app launches, configure the SDK with your **API Key**. This initializes the native Encore SDK on whichever platform the app is running on (iOS or Android). If your Encore flows include an in-app purchase, you register your **purchase controller** here too, and only here: both native SDKs bind the controller inside `configure` and expose no setter afterwards. *** ## Initialize Encore in Your App Call `configure` early in your app lifecycle, before identifying users or presenting offers. The recommended place is in `main()`: ```dart theme={null} import 'package:flutter/material.dart'; import 'package:encore_flutter/encore_flutter.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Encore.shared.configure( apiKey: 'pk_your_api_key_here', purchaseController: AppPurchases(), // your billing stack ); runApp(const MyApp()); } ``` Replace `pk_your_api_key_here` with your publishable **Live** key, which you retrieve yourself from the Dashboard under **Settings → Project API Keys** (use the **Test** key for staging and local development). > [!NOTE] > > Can't find your API key? Open your project's **Settings → Project API Keys** in the [Encore Dashboard](https://dashboard.encorekit.com) and copy the **Live** key (or **Test** for non-production builds). *** ## Register a purchase controller Encore controls *when* a purchase happens; your app owns *how*. Implement `EncorePurchaseController` and pass the instance to `configure`. This is the SDK's only purchase path: it never runs purchase code you did not write. ```dart theme={null} class AppPurchases implements EncorePurchaseController { @override Future purchase(EncorePurchaseRequest request) async { // request.productId - store product to purchase // request.placementId - which placement triggered this (optional) // request.promoOfferId - App Store promotional offer (iOS, optional) // request.basePlanId - Play base plan to select (Android, optional) try { await mySubscriptionManager.purchase(request.productId); return EncorePurchaseResult.purchased; } on UserCancelled { return EncorePurchaseResult.cancelled; } on PurchaseDeferred { return EncorePurchaseResult.pending; } // Throw for a real failure — Encore records it and resolves the // presentation with EncorePublisherOutcome.failed. } } ``` > [!WARNING] > > **`pending` is a first-class result, not a soft failure.** It means Ask to Buy (parental approval) on iOS, or SCA or a pending Play transaction on Android: the user has neither bought nor abandoned, and the store's eventual webhook is the source of truth. > > The 1.x boolean handler could not express this state, so it reported every deferred purchase as a failure. Returning `EncorePurchaseResult.cancelled` for a deferred purchase silently misreports revenue, recording a sale that is still in flight as a decline. Route your billing library's deferred branch to `EncorePurchaseResult.pending`. Registration survives `reset()`: the controller is app-level infrastructure, not user state. If your Encore flows have no in-app purchase, omit the argument. The SDK then never attempts a purchase at all, and every presentation records `EncorePublisherOutcome.notAttempted`. That is a supported configuration, and a different behavior from registering a controller that always fails. > [!NOTE] > > Android's native controller also hands over the foreground `Activity`. The plugin absorbs it, since it is valid only for the duration of the call, so one Dart contract covers both platforms. *** ## Configuration options ```dart theme={null} await Encore.shared.configure( apiKey: 'pk_your_api_key_here', purchaseController: AppPurchases(), logLevel: EncoreLogLevel.debug, unlock: EncoreUnlockMode.optimistic, ); ``` | Option | Type | Default | Description | | - | - | - | - | | `purchaseController` | `EncorePurchaseController?` | `null` | Your purchase path. Omit if your flows include no in-app purchase | | `logLevel` | `EncoreLogLevel` | `none` | Logging verbosity. Set back to `none` before shipping | | `unlock` | `EncoreUnlockMode` | `optimistic` | How a claim is verified. `strict` verifies server-side and persists unverified claims across launches, surfacing late confirmations as `EncoreStrictUnlockVerified` on `Encore.shared.outcomes` | `unlock` selects how a claim flow *runs*, never how a result is read: the presentation record is written identically in both modes. *** ## Next Steps Now that Encore is configured, you're ready to: * **[User Management](./user-management)**: identify users for entitlement tracking * **[Present Offers](./present-offers)**: show promotional offers and read the result # Install the SDK Source: https://docs.encorekit.com/publishers/flutter/quickstart/install Add the Encore Flutter SDK to your project. The plugin bridges to the native iOS and Android SDKs via platform channels. ## Overview The Encore Flutter SDK lets your app present premium brand offers, real perks funded by brands, at the moments you choose. The plugin wraps the native iOS (`Encore.xcframework`) and Android (`com.encorekit:encore` AAR) SDKs: all offer UI, billing, analytics, and entitlement logic runs natively, and the Flutter layer is a thin bridge via platform channels. You'll add the Dart package, then configure platform-specific dependencies for iOS and Android. *** ## Prerequisites The plugin requires **Dart 3.0** or later and **Flutter 3.10** or later. Before installing the SDK, obtain your **API Key** (starts with `pk_...`) from the Encore Dashboard. > [!NOTE] > > **Don't have an API key?** Visit [dashboard.encorekit.com](https://dashboard.encorekit.com) to create an account, add your app, and receive your API key automatically. *** ## Step 1: Add the Dart Package Add the Encore Flutter SDK to your `pubspec.yaml`: ```yaml theme={null} dependencies: encore_flutter: ^2.4.0 ``` Then fetch dependencies: ```bash theme={null} flutter pub get ``` Trigger components need 2.4.0 or later. This documentation describes the **2.x** surface. The plugin pins the native SDKs it was built against (EncoreKit 2.x on iOS, `com.encorekit:encore` 2.x on Android), so a plugin major tracks a native major. > [!NOTE] > > Migrating an existing 1.x integration? 2.0 is a breaking release. [Updating to 2.x](/publishers/flutter/guides/updating-to-2-x) walks the migration step by step. *** ## Step 2: iOS Setup The `EncoreKit` CocoaPod is automatically included as a transitive dependency of the Flutter plugin, so no manual pod configuration is needed. ### Set Deployment Target In your `ios/Podfile`, ensure the platform is set to iOS 15.0 or higher: ```ruby theme={null} platform :ios, '15.0' ``` ### Install Pods ```bash theme={null} cd ios && pod install && cd .. ``` *** ## Step 3: Android Setup The `com.encorekit:encore` AAR is automatically included as a transitive dependency of the Flutter plugin, so no manual Gradle configuration is needed. ### Set Min SDK Version In your `android/app/build.gradle.kts`, ensure `minSdk` is set to 26 or higher: ```kotlin theme={null} android { defaultConfig { minSdk = 26 } } ``` *** ## Step 4: Verify Installation After completing the platform setup, verify the SDK is available: ```dart theme={null} import 'package:encore_flutter/encore_flutter.dart'; ``` Build and run your app to confirm everything compiles: ```bash theme={null} flutter run ``` **Installation complete!** *** ## Next Steps Now that the SDK is installed, continue with the integration: * **[Configure the SDK](/publishers/flutter/quickstart/configure)**: set up your API key and initialize Encore * **[Identify Users](/publishers/flutter/quickstart/user-management)**: associate user identity for offer tracking *** ## Already Installed? If you've already installed the SDK and need to update to a newer version, see [Updating the SDK](/publishers/flutter/guides/updating-sdk). # Presenting Offers Source: https://docs.encorekit.com/publishers/flutter/quickstart/present-offers Present Encore's reward sheet at a moment your user just earned, or a Reduce Churn sheet in a cancel flow, in your Flutter app. ## Overview Encore presents a premium brand offer (a real perk a brand funds to acquire customers, such as a free trial, discount, or credit) at a moment you choose. Start with **Reward Users**: a reward sheet at a moment the user just earned, such as a completed purchase, a streak, or a milestone, at no cost to you. The other use case, **Reduce Churn**, presents offers in a cancel flow or after a paywall decline. *** ## Present an offer The native SDK renders all offer UI natively (SwiftUI on iOS, Jetpack Compose on Android); the Flutter layer triggers presentation and receives the result. `show()` **never throws**. Every failure, including "nothing was presented", is a value on the returned `EncorePresentationResult`: > [tab] Reward Users > > ```dart theme={null} > import 'package:encore_flutter/encore_flutter.dart'; > > Future onStreakKept() async { > final result = await Encore.placement('streak_day_7') > .useCase(EncoreUseCase.rewardUsers) > .headline('Nice work, Sam!') // optional; falls back to the copy resolved for your app > .show(); > > final claim = result.claim; > if (claim != null) { > // The user claimed an offer. Keep claim.transactionId; it carries the attribution. > final transactionId = claim.transactionId; > if (transactionId != null) persistClaim(transactionId); > } > // Every other result: carry on with your own celebration screen. > } > ``` > > Select `EncoreUseCase.rewardUsers` on every reward placement. A reward placement never runs a purchase and never falls back to the paywall sheet, so it needs no subscription product and no purchase controller. The walkthrough, including per-call copy, is the [Reward Placements guide](/publishers/guides/reward-placements). > [tab] Reduce Churn > > ```dart theme={null} > Future onCancelTapped() async { > final result = await Encore.placement('cancel_flow').show(); > > final converted = result.claim != null || > result.publisher == EncorePublisherOutcome.purchased; > if (converted) { > // The user claimed an offer or completed your purchase. > grantAccess(); > } else { > // Dismissed, declined, no offers, control cohort, or an error. > await proceedWithCancellation(); > } > } > ``` > > A placement that omits `useCase()` is a Reduce Churn placement. Never block the user's original action: when the result shows no claim and no purchase, run your original flow. Contracts: [`placement()`](../sdk-reference/placement) · [`EncorePresentationResult`](../sdk-reference/presentation-result). > [!TIP] > > `result.claim` means the user tapped through to an offer, not that they finished it. *** ## Read the result `EncorePresentationResult` is a sealed pair, so Dart 3 gives you an exhaustive `switch`: ```dart theme={null} switch (result) { case EncoreNotPresented(:final reason): // Nothing appeared. Continue the user's original action. proceedWithCancellation(reason); case EncorePresented(:final outcome): final converted = outcome.advertiser is EncoreAdvertiserClaimed || outcome.advertiser is EncoreAdvertiserVerified || outcome.publisher == EncorePublisherOutcome.purchased; converted ? grantAccess() : proceedWithCancellation(outcome.dismissal); } ``` Fact readers give you one axis at a time when you don't want to pattern-match the whole record: ```dart theme={null} final converted = result.claim != null || result.publisher == EncorePublisherOutcome.purchased; ``` A presented record carries **two independent funnels** plus how the sheet went away: | Field | What it reports | | - | - | | `advertiser` | Encore's funnel: `EncoreAdvertiserNotAttempted`, `Claimed`, `Verified`, `Cooldown`, or `Failed` | | `publisher` | Your funnel: what your purchase controller reported | | `dismissal` | How the sheet went away | | `claim` | The claimed offer behind a `Claimed` or `Verified` advertiser outcome, else `null` | One presentation can claim an offer **and** run a purchase, so both are recorded rather than competing for one winning case. `notAttempted` is a real value, meaning "the funnel was open and nothing entered it", never null. `claim` carries the offer itself: ```dart theme={null} class EncoreClaimedOffer { /// The claimed offer. Null on Android, whose claim record carries only the /// campaign; on iOS an offer *is* a campaign, so this equals [campaignId]. final String? offerId; final String campaignId; /// The brand behind the offer. final String advertiserName; /// Joins this claim to a later [EncoreStrictUnlockVerified] outcome, and to /// the server-side completion event that can land days afterwards. Nullable: /// the transaction write can fail while the claim still happened. final String? transactionId; } ``` **`transactionId` is the one to hold on to.** The brand-side completion lands later, sometimes days later, and reaches your server through the [offer-completed webhook](/publishers/offers-api/reference/offer-completed-webhook), which carries the same value; credit the user once per `transactionId`. It is the only way to match the result your app just received against the completion it eventually produces. > [!NOTE] > > There is deliberately no SDK-computed "unlocked" verdict. What a claim means is a property of the variant flow that served it, so any projection over app-global config can contradict the flow that actually ran. Branch on the raw axes. ### When nothing was presented `EncoreNotPresented` is not a synonym for failure: | Reason | Meaning | | - | - | | `noOffers` | No offers matched this user. Don't retry immediately | | `experimentControl` | Control cohort: exposure logged, no UI by design | | `useCaseUnavailable` | The requested use case resolved no layout for this app | | `alreadyPresenting` | A presentation is already on screen | | `noForegroundActivity` | Android only: no foreground Activity was available | | `unsupportedOS` | iOS only: the device is below the SDK's minimum OS version | | `iapFirstDeclined` | Android only: an IAP-first layout ran its purchase before any UI and the user declined | | `error` | A network, decoding, or integration failure. Read `errorType` and `errorMessage` | | `notConfigured` | A method was called before `configure()` | Run your fallback for all of them, and log only the `error` case. *** ## Purchases This section applies to Reduce Churn placements only. A reward placement never runs a purchase, so an app that presents only reward placements can skip it. A user who accepts an offer that carries an in-app purchase triggers your registered `EncorePurchaseController`. It is registered at `configure`; see [Configure the SDK](./configure). ```dart theme={null} class AppPurchases implements EncorePurchaseController { @override Future purchase(EncorePurchaseRequest request) async { try { await mySubscriptionManager.purchase(request.productId); return EncorePurchaseResult.purchased; } on UserCancelled { return EncorePurchaseResult.cancelled; } on PurchaseDeferred { return EncorePurchaseResult.pending; } } } ``` > [!WARNING] > > **Return `pending` for deferred purchases.** Ask to Buy on iOS, or SCA or a pending Play transaction on Android, means the user has neither bought nor abandoned; the store's webhook settles it later. Returning `cancelled` for these silently misreports revenue, recording a live sale as a decline. *** ## Observe outcomes globally For analytics forwarding, app-owned state, or a debug overlay, listen to the outcomes stream. It is multicast, so several listeners can subscribe at once. ```dart theme={null} Encore.shared.outcomes.listen((outcome) { switch (outcome) { case EncorePlacementPresentation(:final placementId, :final result): analytics.log('encore_presentation', placementId, result); case EncoreStrictUnlockVerified(:final transactionId): // A strict claim the server confirmed after its flow ended, possibly on // a later launch. entitlements.refresh(transactionId); } }); ``` There is no replay, so subscribe at startup. *** ## Full example: cancel flow ```dart theme={null} import 'package:flutter/material.dart'; import 'package:encore_flutter/encore_flutter.dart'; class CancelScreen extends StatelessWidget { const CancelScreen({super.key}); Future _onCancel(BuildContext context) async { final result = await Encore.placement('cancel_flow').show(); final converted = result.claim != null || result.publisher == EncorePublisherOutcome.purchased; if (!context.mounted) return; if (converted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Offer applied!')), ); } else { await proceedWithCancellation(); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Account')), body: Center( child: FilledButton( onPressed: () => _onCancel(context), child: const Text('Cancel Subscription'), ), ), ); } } ``` *** ## Bring users back to finish their gift Put a Claim Reminder on your home tab. It stays hidden until the user claims a gift, then reminds them to finish. Once they do, it thanks them or steps aside. Encore manages that. You can also put a Gifts Button on your reward screen, so users can open their gifts there whenever offers are waiting. Both need version 2.4.0 or later of the SDK. See the [trigger components quickstart](/publishers/triggers/quickstart). ## Next Steps * **[Reward Placements](/publishers/guides/reward-placements)**: reward a user at a moment they just earned, with copy you set per call * **[Add Subscription Product](../guides/add-subscription-product)**: Reduce Churn only. Create a subscription product and connect it to Encore * **[Integration Patterns](/publishers/flutter/guides/integration-patterns)**: where the controller, the call site, and the stream each belong # User Management Source: https://docs.encorekit.com/publishers/flutter/quickstart/user-management Identifying users, setting attributes, and managing identity in your Flutter app. ## Overview Encore requires user identification to track entitlements and prevent abuse across devices. You can also set user attributes to enable targeted offers and personalization. *** ## Anonymous Users Encore **automatically generates** a random user ID that persists until the user deletes/reinstalls your app or calls `reset()`. This anonymous ID is stored securely on the native side and allows entitlement tracking to work immediately without requiring explicit user identification. *** ## Identified Users If you use your own user management system, call `identify` when you have a user's identity: ```dart theme={null} await Encore.shared.identify(userId: user.id); ``` This enables the SDK to: * Associate promotional access with your user account * Sync entitlements across devices when the user logs in * Track conversion attribution accurately *** ## Setting User Attributes > [!NOTE] > > **Strongly recommended.** Country and language already shape which offers a user is shown. Once you know who the user is, send what your app already knows, such as country and anything of your own in `custom`. Gender is accepted only from an app rated 18+ in its store listing, so leave it out otherwise. ```dart theme={null} final attributes = EncoreUserAttributes( countryCode: 'US', age: 25, custom: {'signupSource': 'referral'}, ); await Encore.shared.setUserAttributes(attributes); ``` Encore follows the device language. If your app has its own language picker, also call `setLanguage` with the user's choice. > [!WARNING] > > Only pass what you have a lawful basis to share, such as the user's consent. Pass the user's age in whole years as `age`, or their date of birth as `dateOfBirth` (`YYYY-MM-DD`), whichever your app has. The SDK works the age out on the device and never sends the date; given both, it uses the lower age. If you hold only a range, send its lowest end as `age`. A user under 18 is still served offers, from age-appropriate inventory only and with no per-user personalization. See [Sending an age](/publishers/offers-api/reference/user-attributes#sending-an-age). User attributes enable personalized offers, audience targeting, and conversion context tracking. Set attributes using the `EncoreUserAttributes` class. Every value is a string except `age`, a whole number of years; `dateOfBirth` is a `YYYY-MM-DD` string. Use the `custom` map, which takes strings, for app-specific fields. See [EncoreUserAttributes](/publishers/flutter/sdk-reference/user-attributes) for every field and its format: ```dart theme={null} await Encore.shared.setUserAttributes( EncoreUserAttributes( email: 'user@example.com', subscriptionTier: 'premium', monthsSubscribed: '6', custom: {'cancelReason': 'too_expensive'}, ), ); ``` You can also set attributes when identifying: ```dart theme={null} await Encore.shared.identify( userId: 'user_12345', attributes: EncoreUserAttributes( email: 'user@example.com', subscriptionTier: 'premium', ), ); ``` > [!TIP] > > `setUserAttributes()` **merges** with existing attributes. It does not replace them. Attributes passed to `identify()` do the opposite: they replace the stored set, so prefer `setUserAttributes()` for later updates. *** ## Resetting User Identity When a user logs out, call `reset()`: ```dart theme={null} await Encore.shared.reset(); ``` This will: * Reset the user ID to a new auto-generated anonymous ID * Clear cached entitlement data (iOS) * Clear all user attributes Your registered `EncorePurchaseController` **survives** `reset()`. It is app-level infrastructure, not user state, so logging a user out does not require re-registering it (and it cannot be re-registered outside [`configure`](./configure)). *** ## Full Example ```dart theme={null} import 'package:flutter/material.dart'; import 'package:encore_flutter/encore_flutter.dart'; class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { @override void initState() { super.initState(); _initEncore(); } Future _initEncore() async { await Encore.shared.configure( apiKey: 'pk_your_api_key', purchaseController: AppPurchases(), ); // If the user is already logged in if (authManager.isAuthenticated) { await Encore.shared.identify( userId: authManager.userId, attributes: EncoreUserAttributes( email: authManager.email, subscriptionTier: authManager.tier, ), ); } } void _onLogout() async { await Encore.shared.reset(); authManager.logout(); } @override Widget build(BuildContext context) { return MaterialApp(home: HomeScreen(onLogout: _onLogout)); } } ``` *** ## Apps Without Login If your app doesn't require users to log in, you don't need to call `identify`. The SDK uses an auto-generated anonymous ID. You can still set attributes: ```dart theme={null} await Encore.shared.setUserAttributes( EncoreUserAttributes(custom: {'cancelReason': 'too_expensive'}), ); await Encore.placement('cancel_flow').show(); ``` *** ## Next Steps * **[Present Offers](./present-offers)**: present a reward sheet at a moment your user just earned, and read the result * **[Add Subscription Product](../guides/add-subscription-product)**: Reduce Churn only. Create a subscription product and connect it to Encore # clearLanguage() Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/clear-language Remove the language set with setLanguage() so Encore copy follows the device language again Removes the language you set with [`setLanguage()`](./set-language), so Encore serves copy in the device's language again. Every other attribute and the current user stay as they are. > [!NOTE] > > New in the Flutter SDK release that pins native 2.3.0. ## Signature ```dart theme={null} Future clearLanguage() ``` ## Parameters This method takes no parameters. ## Behavior * When a language was set, the SDK removes it and fetches its configuration and offers again. * When no language was set, the call does nothing. * It is the only call that removes the language. [`reset()`](./reset) and logout leave it in place. * It also removes a language set through the deprecated `language` attribute. * The SDK always sends the device language as `Accept-Language`. This call only removes the override that outranks it. ## Usage Call it when the user picks "System default" in your app's own language picker: ```dart theme={null} Future onLanguageChanged(String? code) async { if (code != null) { await Encore.shared.setLanguage(code); } else { await Encore.shared.clearLanguage(); } } ``` ## Related * [setLanguage()](./set-language): set a language override * [Localization](/publishers/concepts/localization): how Encore picks the language it serves # configure() Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/configure Initialize the Encore SDK with your public API key, purchase controller, and unlock mode Configures the shared Encore instance for use throughout your app. Call it once, at app startup, before any other SDK method. If your Encore flows include an in-app purchase, pass your [purchase controller](./purchase-controller) here. Both native SDKs bind the controller inside `configure` and expose no setter afterwards, so this is the only place to register it. ## Signature ```dart theme={null} Future configure({ required String apiKey, EncorePurchaseController? purchaseController, EncoreLogLevel logLevel = EncoreLogLevel.none, EncoreUnlockMode unlock = EncoreUnlockMode.optimistic, }) ``` ## Parameters | Name | Type | Default | Description | | - | - | - | - | | `apiKey` | `String` | *(required)* | Your Live Key or Test Key from the Encore Dashboard settings | | `purchaseController` | [`EncorePurchaseController?`](./purchase-controller) | `null` | Your billing code, bound as the SDK's single purchase path. Omit it if your Encore flows have no in-app purchase. See [Configuring without a purchase controller](#configuring-without-a-purchase-controller) | | `logLevel` | [`EncoreLogLevel`](#encoreloglevel) | `EncoreLogLevel.none` | Native logging verbosity | | `unlock` | [`EncoreUnlockMode`](#encoreunlockmode) | `EncoreUnlockMode.optimistic` | How a claim grants access | ### EncoreLogLevel ```dart theme={null} enum EncoreLogLevel { none, error, warn, info, debug } ``` Use `EncoreLogLevel.debug` during development to see detailed native logs, then `EncoreLogLevel.none` for production builds. ### EncoreUnlockMode ```dart theme={null} enum EncoreUnlockMode { optimistic, strict } ``` | Value | Behavior | | - | - | | `optimistic` | Records the claim and finishes. No in-sheet verification runs. The default | | `strict` | Verifies the claim server-side on return, and persists unverified claims so they are re-checked across launches. Those settle later as [`EncoreStrictUnlockVerified`](./outcomes#late-strict-unlock-verification) on `Encore.shared.outcomes` | Set once, at configure. It selects how a claim flow *runs*, never how a result is read: the presentation record is written identically in both modes. ### API keys | Key type | Format | Description | | - | - | - | | **Live Key** | `pk_live_...` | Production key with standard geo-filtering based on offers' configured regions | | **Test Key** | `pk_test_...` | Development key. Serves demo offers instead of your inventory, and bypasses geo-filtering | > [!NOTE] > > Use the test key (`pk_test_...`) during development to exercise the entire entitlement lifecycle end to end. It serves a demo catalog, so the claim, the advertiser page, and the unlock all work without a live campaign or a real payout. > > **Your own offers do not appear under a test key.** For that, use the live key and accept that the traffic is recorded. See [what a test key serves](/publishers/offers-api/overview#what-a-test-key-serves). > [!WARNING] > > Always use your live key (`pk_live_...`) in production builds. ## Usage ```dart theme={null} import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:encore_flutter/encore_flutter.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Encore.shared.configure( apiKey: 'pk_live_your_key', purchaseController: AppPurchases(), logLevel: kDebugMode ? EncoreLogLevel.debug : EncoreLogLevel.none, unlock: EncoreUnlockMode.strict, ); runApp(const MyApp()); } ``` ## Calling configure more than once Call `configure()` exactly once. Repeat calls are not safe to rely on: * **Android ignores a repeat call entirely**, controller included, so a controller the first call omitted can never be added. * **A repeat call without a controller** clears the Dart-side controller while the native side still routes purchases to the plugin, so every later purchase records `EncorePublisherOutcome.failed`. ## Configuring without a purchase controller If your Encore flows include no in-app purchase, omit the argument. The SDK then never attempts a purchase, and every presentation records `EncorePublisherOutcome.notAttempted`. That is a supported configuration. > [!NOTE] > > Methods called before `configure()` do nothing: `identify()`, `setUserAttributes()`, and `reset()` complete without effect, and `show()` resolves `EncoreNotPresented` with `EncoreNotPresentedReason.notConfigured`. ## Related * [EncorePurchaseController](./purchase-controller): the shape of the `purchaseController` argument * [outcomes](./outcomes): the stream that `EncoreUnlockMode.strict` feeds late verifications into * [Configure the SDK](/publishers/flutter/quickstart/configure) for the step-by-step walkthrough # EncoreDismissReason Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/dismiss-reason How a presented offer sheet went away The `dismissal` on a presented [`EncorePresentationResult`](./presentation-result). Its wire values are shared by every Encore SDK. ## Definition ```dart theme={null} enum EncoreDismissReason { userTappedClose('close_button'), userSwipedDown('swipe_dismiss'), userCancelled('user_cancelled'), lastOfferDeclined('last_offer_declined'), dismissed('dismissed'), cooldown('provisional_cooldown'), flowCompleted('flow_completed'), interrupted('interrupted'), unknown('unknown'); final String nativeValue; } ``` ## Values | Value | Wire value | Meaning | Platform | | - | - | - | - | | `userTappedClose` | `close_button` | The user tapped the close control | Both | | `userSwipedDown` | `swipe_dismiss` | The user swiped the sheet away | Both | | `userCancelled` | `user_cancelled` | The user cancelled out of the flow | iOS | | `lastOfferDeclined` | `last_offer_declined` | The user declined the final offer in the flow | iOS | | `dismissed` | `dismissed` | Generic dismissal | iOS | | `cooldown` | `provisional_cooldown` | On Android, the server refused the claim with an HTTP 409 other than "already completed" (in practice the trial limit: the user has reached your app's limit on completed offers), and the SDK closed the sheet. The name is historical; there is no cross-offer cooldown. iOS no longer produces it from iOS SDK 2.3.0. On both, from 2.3.0, an offer the user already completed is dropped from the sheet instead, which closes as `flowCompleted` when it was the last one | Android (iOS before 2.3.0) | | `flowCompleted` | `flow_completed` | The flow finished on its own and the SDK closed the sheet | Both | | `interrupted` | `interrupted` | The SDK force-ended a dead flow, not the user | Both | | `unknown` | `unknown` | A value this plugin version doesn't recognize, from a newer native SDK | Both | ## Usage ```dart theme={null} final result = await Encore.placement('cancel_flow').show(); if (result.dismissal == EncoreDismissReason.userTappedClose) { analytics.log('encore_closed_without_claim'); } ``` `result.dismissal` is `null` when nothing was presented. ## Related * [EncorePresentationResult](./presentation-result): the record this value is part of * [placement()](./placement): the call that produces the record # Errors Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/errors Error handling in the Encore Flutter SDK: errors as values on the result, plus the platform exceptions the plugin can raise The SDK reports failures as **values**, not exceptions. `show()` never throws on iOS or Android, so a missing `try`/`catch` can't break an integration. There is no typed error class in Dart: a native failure arrives as an `errorType` string plus a human-readable `errorMessage`. ## errorType values `errorType` is the stable identifier from the native SDKs' shared error vocabulary. | `errorType` | Cause | | - | - | | `not_configured` | A method was called before `configure()` | | `invalid_api_key` | Empty or malformed API key | | `invalid_url` | Internal URL construction failure | | `http_error` | Non-2xx HTTP response | | `api_error` | The API returned a structured error | | `decoding_error` | A response failed to decode | | `network_error` | Connectivity issue: timeout, DNS, and so on | | `persistence_error` | Local storage read or write failure | | `domain_error` | A business rule was violated. Android also reports any unexpected native failure during `show()` this way | | `unknown_error` | A failure iOS could not classify. iOS only | ## Where errors arrive ### Presentation failures A failure that stopped the sheet from appearing lands on the [`EncorePresentationResult`](./presentation-result) as `EncoreNotPresented` with `reason == EncoreNotPresentedReason.error`: ```dart theme={null} final result = await Encore.placement('cancel_flow').show(); if (result case EncoreNotPresented(:final reason, :final errorType, :final errorMessage)) { if (reason == EncoreNotPresentedReason.error) { debugPrint('Encore: $errorType $errorMessage'); } proceedWithCancellation(); // run your fallback either way } ``` > [!WARNING] > > Do not gate your fallback on the error branch. `EncoreNotPresented` also covers `noOffers`, `experimentControl`, and `useCaseUnavailable`, none of which are failures, and all of which still need your original flow to continue. ### Claim failures A claim that errored *after* the sheet appeared surfaces on the advertiser funnel instead, as `EncoreAdvertiserFailed` with its own `errorType` and `errorMessage`. The user never saw it. ### Purchase failures Throwing from your [purchase controller](./purchase-controller) records `EncorePublisherOutcome.failed`, and the flow continues. Return `EncorePurchaseResult.cancelled` for a user cancellation and `EncorePurchaseResult.pending` for a deferred purchase rather than throwing either. ## Platform exceptions The methods other than `show()` are thin calls over a platform channel, and can raise a `PlatformException` for integration faults: | Code | Cause | | - | - | | `INVALID_ARGS` | A required argument was missing on the channel. The typed Dart API normally prevents this | | `NO_CONTEXT` | Android only: the plugin was called before it was attached to a Flutter engine | Calling the plugin on web or desktop throws `MissingPluginException`, because the plugin implements iOS and Android only. ## Related * [EncorePresentationResult](./presentation-result): where presentation and claim failures land * [EncorePurchaseController](./purchase-controller): purchase-side failures * Platform detail: [iOS errors](/publishers/ios/sdk-reference/errors) and [Android errors](/publishers/android/sdk-reference/errors) # identify() Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/identify Link your signed-in user ID to Encore for cross-device entitlements and attribution, optionally with attributes Links your user ID to the SDK's anonymous ID for cross-device entitlement tracking and attribution. Call it after a successful login to sync the user's entitlements across devices. ## Signature ```dart theme={null} Future identify({ required String userId, EncoreUserAttributes? attributes, }) ``` The `Future` completes once the call reaches the native SDK. It does not wait for the network. ## Parameters | Name | Type | Description | | - | - | - | | `userId` | `String` | Your user's unique identifier from your auth system. An empty or whitespace-only ID is ignored with a warning | | `attributes` | [`EncoreUserAttributes?`](./user-attributes) | Optional attributes to store with the identity, in the same call | > [!WARNING] > > **Attributes passed to `identify()` replace the stored set; they are not merged.** When the call changes the user or the attributes, the stored set becomes what you pass, so a field you leave out does not carry over. To add or change attributes without touching the others, call [`setUserAttributes()`](./set-user-attributes), which merges. > > An empty `EncoreUserAttributes()` counts as no attributes, so it leaves the stored set unchanged. ## Usage ### Basic identification ```dart theme={null} await Encore.shared.identify(userId: user.id); ``` ### With attributes ```dart theme={null} await Encore.shared.identify( userId: user.id, attributes: EncoreUserAttributes( email: user.email, subscriptionTier: user.plan, monthsSubscribed: user.monthsActive.toString(), ), ); ``` ### Identify, then add attributes as you learn them ```dart theme={null} await Encore.shared.identify(userId: user.id); // Later, when the profile loads. Merges with what is already stored. await Encore.shared.setUserAttributes( EncoreUserAttributes(countryCode: 'US'), ); ``` > [!TIP] > > Call `identify()` after a successful login. On logout, call [`reset()`](./reset) to clear the user ID and attributes. ## Related * [EncoreUserAttributes](./user-attributes): every field, its format, and an example value * [setUserAttributes()](./set-user-attributes): merges attributes into the current profile * [reset()](./reset): the logout counterpart # outcomes Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/outcomes Broadcast stream of every placement resolution, plus late strict-unlock verifications `Encore.shared.outcomes` is the passive observation channel. It mirrors Swift's `AsyncStream` and Kotlin's `SharedFlow` of placement outcomes. Use it for anything that watches results without owning a call site: analytics forwarding, app-owned state, a debug overlay. Control flow belongs at the call site, on the value [`show()`](./placement) returns. ## Signature ```dart theme={null} Stream get outcomes sealed class EncorePlacementOutcome {} final class EncorePlacementPresentation extends EncorePlacementOutcome { final String placementId; final EncorePresentationResult result; } final class EncoreStrictUnlockVerified extends EncorePlacementOutcome { final String transactionId; } ``` ## Usage ```dart theme={null} final subscription = Encore.shared.outcomes.listen((outcome) { switch (outcome) { case EncorePlacementPresentation(:final placementId, :final result): analytics.log('encore_presentation', placementId, result); case EncoreStrictUnlockVerified(:final transactionId): // A claim the server confirmed after its flow ended. entitlements.refresh(transactionId); } }); // When the observer goes away: await subscription.cancel(); ``` `EncorePlacementOutcome` is sealed, so the `switch` is exhaustive. ## Behavior * **It is a broadcast stream.** Several listeners can subscribe at once, matching the multicast streams both native SDKs expose. * **There is no replay.** Nothing is buffered for late listeners, by design, since outcomes can carry user-scoped claim data. Subscribe at startup if you want all of them. * **Every `show()` the SDK resolves emits**, including the ones that presented nothing. An `EncoreNotPresented` result still arrives as an `EncorePlacementPresentation`, carrying the same [`EncorePresentationResult`](./presentation-result) the call site received. * **Events the plugin doesn't recognize are dropped**, so a newer native SDK can't emit something this version would misread. ## Late strict-unlock verification `EncoreStrictUnlockVerified` is the stream's reason for existing. It has no `show()` equivalent, because it resolves *after* its flow ended, possibly on a later launch. With `unlock: EncoreUnlockMode.strict` on [`configure()`](./configure), a claim that ends unverified persists across process death and is re-checked on later launches. When verification completes, the event is emitted. On iOS the native SDK refreshes its entitlement cache first; Android keeps no such cache, so refresh your own access state when the event arrives. Its `transactionId` matches the [`EncoreClaimedOffer.transactionId`](./presentation-result#encoreclaimedoffer) recorded on the original result, so you can join the two. Under the default `EncoreUnlockMode.optimistic`, this event never fires. ## Related * [EncorePresentationResult](./presentation-result): the payload of `EncorePlacementPresentation` * [configure()](./configure): the `unlock` option that makes `EncoreStrictUnlockVerified` reachable # Overview Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/overview Every method, controller, and type in the encore_flutter plugin, with Dart signatures and platform differences Contracts for the `encore_flutter` plugin: the methods you call, the controller you implement, and the types they exchange. Every symbol on these pages is exported from `package:encore_flutter/encore_flutter.dart`. > [!NOTE] > > **Looking for integration guides?** > > * **New to Encore?** Start with the [Getting Started Guide](/quickstart) for portal-guided setup > * **Step-by-step integration:** See the [Flutter Quickstart](/publishers/flutter/quickstart/install) for installation and configuration > * **Wiring results into your app:** See [Integration Patterns](/publishers/flutter/guides/integration-patterns) ## Core methods > [card] [configure()](/publishers/flutter/sdk-reference/configure) > > Initialize the SDK with your public API key, purchase controller, and unlock mode > [card] [identify()](/publishers/flutter/sdk-reference/identify) > > Associate your user ID with Encore for cross-device tracking > [card] [setUserAttributes()](/publishers/flutter/sdk-reference/set-user-attributes) > > Merge structured attributes into the current user's profile > [card] [setLanguage()](/publishers/flutter/sdk-reference/set-language) > > Set the language Encore serves copy in, overriding the device language > [card] [clearLanguage()](/publishers/flutter/sdk-reference/clear-language) > > Drop a language override so copy follows the device language again > [card] [reset()](/publishers/flutter/sdk-reference/reset) > > Clear the user ID and attributes on logout ## Presenting offers > [card] [placement()](/publishers/flutter/sdk-reference/placement) > > Immutable builder for presenting offers, resolving to a result record > [card] [EncorePurchaseController](/publishers/flutter/sdk-reference/purchase-controller) > > The controller your app registers so purchases run through your billing code > [card] [outcomes](/publishers/flutter/sdk-reference/outcomes) > > Broadcast stream of every placement resolution, for passive observers > [card] [setClaimEnabled()](/publishers/flutter/sdk-reference/set-claim-enabled) > > Dim and disable the claim button on offer cards at runtime ## Types > [card] [EncoreUserAttributes](/publishers/flutter/sdk-reference/user-attributes) > > Every user attribute, its format, and an example value > [card] [EncorePresentationResult](/publishers/flutter/sdk-reference/presentation-result) > > The factual record a presentation resolves to > [card] [EncoreDismissReason](/publishers/flutter/sdk-reference/dismiss-reason) > > How a presented offer sheet went away ## Error handling > [card] [Errors](/publishers/flutter/sdk-reference/errors) > > Error values on the result record, and the platform exceptions the plugin can raise ## Basic integration ```dart theme={null} import 'package:encore_flutter/encore_flutter.dart'; // 1. Configure at launch, registering your purchase controller if your // app sells a product through Encore offers await Encore.shared.configure( apiKey: 'pk_live_your_key', purchaseController: AppPurchases(), ); // 2. Identify the user after login, and add attributes as you learn them await Encore.shared.identify(userId: user.id); await Encore.shared.setUserAttributes( EncoreUserAttributes(countryCode: 'US'), ); // 3. Present an offer and branch on the result final result = await Encore.placement('cancel_flow').show(); if (result.claim != null || result.publisher == EncorePublisherOutcome.purchased) { // The user claimed an offer or completed your purchase. } else { proceedWithCancellation(); // dismissed, declined, nothing appeared, ... } ``` > [!NOTE] > > `show()` never throws on iOS or Android. Failures arrive as `EncoreNotPresented` on the [`EncorePresentationResult`](./presentation-result), so fallback logic lives in one place. > [!TIP] > > For passive observation (analytics, logging, entitlement sync), listen to [`Encore.shared.outcomes`](./outcomes) once at startup instead of repeating the work at every call site. ## Platform support The plugin runs on iOS and Android only; it bridges to the native Encore SDKs over platform channels, and all offer UI renders natively. Calls on web or desktop throw `MissingPluginException`. See [Errors](./errors#platform-exceptions). # placement() Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/placement Present Encore offers with an immutable builder that resolves to a result record Creates a placement builder for presenting offers. It is the one way to present, and it matches the builder across every Encore SDK. ## Signature ```dart theme={null} static EncorePlacementBuilder placement([String? id]) class EncorePlacementBuilder { EncorePlacementBuilder useCase(EncoreUseCase useCase); EncorePlacementBuilder headline(String text); EncorePlacementBuilder subheadline(String text); EncorePlacementBuilder publisherReward(EncorePublisherReward reward); // 2.3.0+ Future show(); } ``` `placement()` is static: call it as `Encore.placement('cancel_flow')`. Each option returns a **new** builder, so a builder can be reused or shared without one call site changing the configuration of any other. ## Parameters | Name | Type | Description | | - | - | - | | `id` | `String?` | The placement identifier configured in the Encore Dashboard. Pass it so results and analytics are attributed to the right placement | ## show() ```dart theme={null} final result = await Encore.placement('cancel_flow').show(); ``` `show()` fetches offers, presents the native offer sheet, and completes when the presentation record is sealed. It **never throws** on iOS or Android: every failure, including "nothing was presented", is a value on the returned [`EncorePresentationResult`](./presentation-result). ```dart theme={null} final result = await Encore.placement('cancel_flow').show(); if (result.claim != null || result.publisher == EncorePublisherOutcome.purchased) { grantAccess(); } else { proceedWithCancellation(); } ``` ## Use cases `useCase()` selects which Encore surface the placement presents. It defaults to `EncoreUseCase.reduceChurn`. ```dart theme={null} await Encore.placement('workout_completed') .useCase(EncoreUseCase.rewardUsers) .headline('Five workouts this week 🔥') .subheadline("Here's a little thank you from us") .show(); ``` ```dart theme={null} enum EncoreUseCase { reduceChurn('churn-intervention'), rewardUsers('post-action-reward'); final String nativeValue; } ``` | Case | Wire value | Surface | | - | - | - | | `EncoreUseCase.reduceChurn` | `churn-intervention` | Second-chance monetization after a paywall decline. The default | | `EncoreUseCase.rewardUsers` | `post-action-reward` | A brand-funded reward at a moment the user just accomplished something. Claim-only; never presents IAP | The case names describe the capability; `nativeValue` is the label the backend stores. > [!NOTE] > > A use case with no enabled variant resolves `EncoreNotPresented` with `EncoreNotPresentedReason.useCaseUnavailable` rather than falling back to the churn-intervention sheet. ## Copy overrides `headline()` and `subheadline()` override the sheet's copy for one presentation, on **every** use case. The native side writes the value into the variable the active template reads. Priority order, first one set wins: this value, then the copy Encore resolved for your app, then the shipped template default. A blank string is ignored. Encore never translates a string you pass, so localization, pluralization, wording, and emoji stay yours. The Encore-resolved copy beneath it is translated into the user's language; see [Localization](/publishers/concepts/localization). ## Reward for trying From 2.3.0, `publisherReward()` takes an `EncorePublisherReward(id:, title:, detail:, iconUrl:)`, where `detail` and `iconUrl` are optional, and describes a prize your app pays for trying an offer. When the user says they finished and Encore's server grants the prize, `result.claim?.userConfirmedCompletion` is true on the result `show()` returns, and your app grants the prize from that result only. De-duplicate on your own user ID plus `campaignId`, because `transactionId` can be null. Setup, the daily limit, and when the flag stays false: [Reward for Trying](/publishers/guides/reward-for-trying). ## Platform notes * **iOS** presents only on iOS 17 or later. On older versions `show()` resolves `EncoreNotPresented` with `EncoreNotPresentedReason.unsupportedOS`, even though the plugin installs on iOS 15. * **Android** attaches the sheet to the Activity the plugin is bound to. With no foreground Activity, `show()` resolves `EncoreNotPresentedReason.noForegroundActivity`. ## Related * [EncorePresentationResult](./presentation-result): what `show()` resolves to * [EncorePurchaseController](./purchase-controller): the purchase path a presented offer runs through * [Reward Users](/publishers/use-cases/post-action-reward) and [Reduce Churn](/publishers/use-cases/churn-intervention) for what each surface is for # EncorePresentationResult Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/presentation-result The factual record of a placement presentation: two independent funnels plus how the sheet ended What [`show()`](./placement) resolves to. Either nothing ever appeared, or the interaction ran and the record carries **two independent funnels** plus how the sheet went away. `show()` never throws on iOS or Android. Presentation-level failures arrive here as values. ## Structure ```dart theme={null} sealed class EncorePresentationResult { // Fact readers: null when nothing was presented EncoreClaimedOffer? get claim; EncoreAdvertiserOutcome? get advertiser; EncorePublisherOutcome? get publisher; EncoreDismissReason? get dismissal; } final class EncoreNotPresented extends EncorePresentationResult { final EncoreNotPresentedReason reason; final String? errorType; // set when reason is error final String? errorMessage; // set when reason is error } final class EncorePresented extends EncorePresentationResult { final EncorePresentationOutcome outcome; } class EncorePresentationOutcome { final EncoreAdvertiserOutcome advertiser; // Encore's funnel: how far the claim got final EncorePublisherOutcome publisher; // your funnel: what your controller reported final EncoreDismissReason dismissal; // how the sheet went away } ``` The two funnels are independent, not competing cases: a single presentation can claim an offer **and** run a purchase, and both are recorded. `notAttempted` is a real value, meaning "the funnel was open and nothing entered it", never a missing one. ## Reading it The fact readers give you one axis at a time: ```dart theme={null} final result = await Encore.placement('cancel_flow').show(); final converted = result.claim != null || result.publisher == EncorePublisherOutcome.purchased; converted ? grantAccess() : proceedWithCancellation(); ``` `EncorePresentationResult` is sealed, so Dart 3 gives you an exhaustive `switch` when the mechanism matters: ```dart theme={null} switch (result) { case EncoreNotPresented(:final reason): proceedWithCancellation(); // nothing was shown; reason says why case EncorePresented(:final outcome): analytics.log('encore_presentation', { 'advertiser': outcome.advertiser.runtimeType.toString(), 'publisher': outcome.publisher.nativeValue, 'dismissal': outcome.dismissal.nativeValue, }); } ``` ## EncorePublisherOutcome Your funnel: what your [purchase controller](./purchase-controller) reported back. | Value | Wire value | Meaning | | - | - | - | | `notAttempted` | `not_attempted` | No purchase was attempted. Also what a presentation records when no purchase controller is registered | | `purchased` | `purchased` | Your controller returned `EncorePurchaseResult.purchased` | | `cancelled` | `cancelled` | Your controller returned `EncorePurchaseResult.cancelled` | | `pending` | `pending` | Your controller returned `EncorePurchaseResult.pending`: the store deferred the purchase and it may settle later | | `failed` | `failed` | Your controller threw | | `unknown` | `unknown` | A value this plugin version doesn't recognize, from a newer native SDK | Treat `pending` as neither a purchase nor an abandonment; see [EncorePurchaseController](./purchase-controller#definition) for what it means. ## EncoreAdvertiserOutcome Encore's funnel: how far the offer claim got. A sealed class with five cases. ```dart theme={null} sealed class EncoreAdvertiserOutcome {} final class EncoreAdvertiserNotAttempted extends EncoreAdvertiserOutcome {} final class EncoreAdvertiserClaimed extends EncoreAdvertiserOutcome { final EncoreClaimedOffer offer; } final class EncoreAdvertiserVerified extends EncoreAdvertiserOutcome { final EncoreClaimedOffer offer; } final class EncoreAdvertiserCooldown extends EncoreAdvertiserOutcome {} final class EncoreAdvertiserFailed extends EncoreAdvertiserOutcome { final String? errorType; final String? errorMessage; } ``` | Case | Meaning | | - | - | | `EncoreAdvertiserNotAttempted` | The claim funnel was open and nothing entered it | | `EncoreAdvertiserClaimed` | The claim completed on-device; server verification not (yet) observed | | `EncoreAdvertiserVerified` | Server-level confirmation was observed in-session | | `EncoreAdvertiserCooldown` | On Android, the server refused the claim with an HTTP 409 other than "already completed". In practice this is the trial limit: the user has reached your app's limit on completed offers. iOS no longer produces it from iOS SDK 2.3.0, where a refused claim is an ordinary claim error and the sheet stays open. On both, from 2.3.0, an offer the user already completed is not reported here: the sheet drops it and the user picks another | | `EncoreAdvertiserFailed` | The claim errored. An SDK-side failure the user never saw. See [Errors](./errors) | `result.claim` is shorthand for the offer behind a `Claimed` or `Verified` outcome, and `null` otherwise. Read `advertiser` directly when you need to tell the two apart. ### EncoreClaimedOffer ```dart theme={null} class EncoreClaimedOffer { final String? offerId; final String campaignId; final String advertiserName; final String? transactionId; final bool userConfirmedCompletion; } ``` | Property | Type | Description | | - | - | - | | `offerId` | `String?` | The claimed offer. Always `null` on Android, whose claim record carries only the campaign. On iOS an offer *is* a campaign, so this equals `campaignId` | | `campaignId` | `String` | The campaign behind the offer | | `advertiserName` | `String` | The brand behind the offer | | `transactionId` | `String?` | Joins this claim to a later [`EncoreStrictUnlockVerified`](./outcomes) outcome and to the server-side completion event. Nullable, because the transaction write can fail while the claim still happened | | `userConfirmedCompletion` | `bool` | 2.3.0+. True when the user said they finished a reward for trying offer and Encore's server granted your prize. It is the user's own word, not a verified conversion. See [Reward for Trying](/publishers/guides/reward-for-trying) | **`transactionId` is the one to keep.** The brand-side completion can land days later and reaches your server through the [offer-completed webhook](/publishers/offers-api/reference/offer-completed-webhook), which carries the same value. It is the only way to match this result to the completion it eventually produces. ## EncoreDismissReason How a presented sheet went away. See [EncoreDismissReason](./dismiss-reason) for every value. ## EncoreNotPresentedReason Why no sheet ever appeared. | Value | Wire value | Meaning | Platform | | - | - | - | - | | `notConfigured` | `not_configured` | `show()` was called before `configure()` | Both | | `alreadyPresenting` | `already_presenting` | A presentation is already on screen | Both | | `noOffers` | `no_offer_available` | No offers matched this user. Don't retry immediately | Both | | `experimentControl` | `experiment_control` | Control cohort: exposure logged, no UI by design | Both | | `useCaseUnavailable` | `use_case_unavailable` | The requested use case resolved no layout for this app | Both | | `noForegroundActivity` | `no_foreground` | No foreground Activity was available when the SDK needed one | Android | | `unsupportedOS` | `unsupported_ios` | The device is below the SDK's minimum OS version (iOS 17) | iOS | | `iapFirstDeclined` | `iap_first_declined` | An IAP-first layout ran its purchase before any UI and the user declined | Android | | `error` | `error` | Network, decoding, or integration failure. Read `errorType` and `errorMessage`. See [Errors](./errors) | Both | | `unknown` | `unknown` | A value this plugin version doesn't recognize, from a newer native SDK | Both | > [!NOTE] > > `EncoreNotPresented` is not a synonym for failure. `noOffers`, `experimentControl`, and `useCaseUnavailable` are healthy states that still need your original flow to continue. Run your fallback for every reason, and log only `error`. The three enums decode an unrecognized wire value to their explicit `unknown` case. The advertiser funnel has no `unknown` case: an advertiser outcome this plugin version doesn't recognize reads as `EncoreAdvertiserNotAttempted`. ## Related * [placement()](./placement): returns this record * [EncorePurchaseController](./purchase-controller): whose answer becomes `publisher` * [outcomes](./outcomes): carries this record for passive observers * [Errors](./errors): the `errorType` values # EncorePurchaseController Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/purchase-controller The controller your app registers so Encore offers purchase through your billing code Every purchase triggered by an Encore offer runs through an `EncorePurchaseController` your app registers with [`configure()`](./configure). The SDK has no built-in billing and never runs purchase code you did not write: your controller owns product lookup, receipt validation, restore handling, and entitlement bookkeeping, exactly as it does for every other purchase in your app. Encore controls *when* a purchase happens; you own *how*. ## Definition ```dart theme={null} abstract class EncorePurchaseController { // Called when a user accepts an offer that carries an in-app purchase. // Awaited: the offer flow waits for your answer. Throw for a real failure. Future purchase(EncorePurchaseRequest request); } enum EncorePurchaseResult { purchased, // the purchase completed cancelled, // the user backed out pending, // the store deferred the purchase; it may complete later } ``` Each native plugin owns the native conformance and forwards every request over the method channel, waiting until your Dart code answers. * **Throwing records a failure.** A throw lands on the result as `EncorePublisherOutcome.failed`, and the flow continues. Map your billing layer's "user cancelled" error to `cancelled` rather than throwing it. * **An unrecognized answer is a failure**, never `purchased`, because a phantom success would grant access nobody paid for. * **The controller survives [`reset()`](./reset).** It is app-level wiring, not user state. > [!WARNING] > > **`pending` is a first-class result, not a soft failure.** It means Ask to Buy (parental approval) on iOS, or SCA or a pending Play transaction on Android: the user has neither bought nor abandoned, and the store's eventual webhook is the source of truth. Returning `cancelled` for a deferred purchase records a sale still in flight as a decline. Route your billing library's deferred branch to `pending`. ## EncorePurchaseRequest What your controller receives when Encore needs a purchase. ```dart theme={null} class EncorePurchaseRequest { final String productId; // store product to purchase final String? placementId; // placement that triggered it final String? promoOfferId; // App Store promotional offer (iOS) final String? basePlanId; // Play base plan to select (Android) } ``` | Property | Type | Description | | - | - | - | | `productId` | `String` | The store product identifier to purchase, for example `com.app.monthly_premium` | | `placementId` | `String?` | Which placement triggered this purchase. On iOS the SDK generates an ID when the placement had none | | `promoOfferId` | `String?` | App Store Connect promotional offer identifier. iOS only; `null` for standard purchases and on Android | | `basePlanId` | `String?` | Google Play subscription base plan ID, when the product exposes several. Android only; `null` on iOS and for single-base-plan products | > [!NOTE] > > Android's native controller also hands over the foreground `Activity`. The plugin keeps it on the native side, since it is valid only for the duration of the call, so one Dart contract covers both platforms. ## Implementations > [tab] RevenueCat > > ```dart theme={null} > import 'package:encore_flutter/encore_flutter.dart'; > import 'package:flutter/services.dart'; > import 'package:purchases_flutter/purchases_flutter.dart'; > > class AppPurchases implements EncorePurchaseController { > @override > Future purchase(EncorePurchaseRequest request) async { > // Buys the product's default option. If your Play products expose several > // base plans, purchase the subscription option matching request.basePlanId. > final products = await Purchases.getProducts([request.productId]); > if (products.isEmpty) { > throw StateError('Unknown product ${request.productId}'); > } > try { > await Purchases.purchaseStoreProduct(products.first); > return EncorePurchaseResult.purchased; > } on PlatformException catch (e) { > final code = PurchasesErrorHelper.getErrorCode(e); > if (code == PurchasesErrorCode.purchaseCancelledError) { > return EncorePurchaseResult.cancelled; > } > if (code == PurchasesErrorCode.paymentPendingError) { > return EncorePurchaseResult.pending; > } > rethrow; // recorded as EncorePublisherOutcome.failed > } > } > } > ``` > [tab] Custom > > ```dart theme={null} > import 'package:encore_flutter/encore_flutter.dart'; > > class AppPurchases implements EncorePurchaseController { > AppPurchases(this.billing); > > final BillingService billing; // your app's existing billing layer > > @override > Future purchase(EncorePurchaseRequest request) async { > final outcome = await billing.purchase( > request.productId, > basePlanId: request.basePlanId, // Android, optional > promoOfferId: request.promoOfferId, // iOS, optional > ); > if (outcome.userCancelled) return EncorePurchaseResult.cancelled; > if (outcome.deferred) return EncorePurchaseResult.pending; > return EncorePurchaseResult.purchased; > } > } > ``` ## Related * [configure()](./configure): accepts the controller, and defines what happens when none is registered * [EncorePresentationResult](./presentation-result): where the controller's answer lands as `publisher` # reset() Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/reset Clear the user ID and attributes on logout, and start a new anonymous user Clears the current user ID, all user attributes, and any claim still waiting on strict verification. On iOS it also clears the SDK's cached entitlements. A new anonymous ID is generated automatically. > [!NOTE] > > The language set with [`setLanguage()`](./set-language) survives `reset()`. It is a preference of the device, like appearance, not user state, so a logout leaves it in place. Only [`clearLanguage()`](./clear-language) removes it. ## Signature ```dart theme={null} Future reset() ``` ## Parameters None. ## Usage ```dart theme={null} Future handleLogout() async { await Encore.shared.reset(); // Navigate to the login screen } ``` > [!TIP] > > You don't need to call `configure()` again after `reset()`. The SDK keeps running under the new anonymous ID. > [!NOTE] > > Your registered [purchase controller](./purchase-controller) **survives** `reset()`. It is app-level wiring, not user state, so logging a user out does not require registering it again. ## Related * [identify()](./identify): call it again when the next user logs in * [setUserAttributes()](./set-user-attributes): attributes start empty after a reset # setClaimEnabled() Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/set-claim-enabled Gray out and disable the claim button on offer cards at runtime Controls whether the claim button on offer cards is tappable. Set it to `false` to gray out and disable the claim button while leaving the rest of the presentation intact. ## Signature ```dart theme={null} Future setClaimEnabled(bool enabled) ``` Defaults to `true`. Call it any time after [`configure()`](./configure); the value applies from the next presentation, so a sheet already on screen keeps the state it opened with. There is no getter; track the value in your app if you need to read it back. ## Parameters | Name | Type | Description | | - | - | - | | `enabled` | `bool` | `true` makes the claim button tappable; `false` dims and disables it | ## Usage ```dart theme={null} // The user is in a state where claiming would be wrong (for example, // mid-checkout in your own flow). Dim the claim button without hiding the offer. await Encore.shared.setClaimEnabled(false); // Restore it when they leave that state. await Encore.shared.setClaimEnabled(true); ``` ## Related * [placement()](./placement): the sheet this setting applies to * [EncorePresentationResult](./presentation-result): a suppressed claim shows up as `EncoreAdvertiserNotAttempted` # setLanguage() Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/set-language Set the language Encore serves copy in, overriding the device language until you clear it Sets the language Encore serves its copy and offers in. It outranks the device language on every request the SDK makes. Use it when your app has its own language picker, or when the user's app language differs from their device language. > [!NOTE] > > New in the Flutter SDK release that pins native 2.3.0. ## Signature ```dart theme={null} Future setLanguage(String tag) ``` ## Parameters | Parameter | Type | Description | | - | - | - | | `tag` | `String` | A well-formed BCP-47 language tag, for example `es`, `es-MX`, or `pt-BR`. From a Flutter `Locale`, pass `locale.toLanguageTag()`, not `toString()`, which gives `pt_BR`. The SDK normalizes its case, so `PT-br` becomes `pt-BR`, and Encore keeps only the language part, so `es-MX` serves `es`. See [Language tags](/publishers/concepts/localization#language-tags) for what is accepted | ## Behavior * The SDK keeps the language on the device until you call [`clearLanguage()`](./clear-language), so it survives relaunches. Encore never stores it on its servers. * It is a preference of the device, not user state, so [`reset()`](./reset) and logout leave it in place. * When the language changes, the SDK fetches its configuration and offers again. * An invalid tag completes the returned `Future` with an `ArgumentError`, before anything reaches the native SDK. See [Errors](#errors). * The language is served only when your app has it enabled. Otherwise Encore falls back to the device languages, then your app's default language. See [Localization](/publishers/concepts/localization). * The device language is still sent as `Accept-Language`. This call adds the override that outranks it. ## Errors | Error | When | | - | - | | `ArgumentError` | `tag` is not a well-formed language tag, for example `'pt_BR'` or `'english'`. Use `'pt-BR'` and `'en'` | The error arrives through the returned `Future`, and nothing changes. Catch it where you await the call, or with `catchError`. A call you do not await still reports it, as an unhandled `Future` error. ## Replaces the `language` attribute Setting the language through `EncoreUserAttributes(language: ...)` is deprecated, on both the field and the constructor parameter. It still works and calls `setLanguage()` for you, logging a warning once, and it is removed at the next major release. A language saved through the attribute on an earlier release carries over the first time the new SDK starts. Unlike `setLanguage()`, the attribute and the carry-over still accept a locale identifier and turn it into a tag, so `pt_BR` becomes `pt-BR` and `de_DE@currency=EUR` becomes `de-DE`. See [the deprecated attribute](/publishers/concepts/localization#the-language-user-attribute-is-deprecated). A language set through the attribute is stored as the same override, so it also survives `reset()`. ## Usage Call it from your app's own language picker, and call `clearLanguage()` when the user picks "System default": ```dart theme={null} Future onLanguageChanged(String? code) async { if (code != null) { await Encore.shared.setLanguage(code); } else { await Encore.shared.clearLanguage(); } } ``` ## Related * [clearLanguage()](./clear-language): go back to the device language * [EncoreUserAttributes](./user-attributes): the deprecated `language` attribute * [Localization](/publishers/concepts/localization): how Encore picks the language it serves # setUserAttributes() Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/set-user-attributes Merge structured attributes into the current user's profile for targeting and analytics Stores structured attributes for the current user to power offer targeting, personalization, and analytics. Attributes are **merged** with the ones already stored; they do not replace them. ## Signature ```dart theme={null} Future setUserAttributes(EncoreUserAttributes attributes) ``` The `Future` completes once the call reaches the native SDK. It does not wait for the network. ## Parameters | Name | Type | Description | | - | - | - | | `attributes` | [`EncoreUserAttributes`](./user-attributes) | The attributes to merge. See [EncoreUserAttributes](./user-attributes) for every field | ## Merge rules > [!NOTE] > > Attributes are **merged**, not replaced. If you set `email` and `subscriptionTier`, then later set `monthsSubscribed`, all three are kept. * **A field you leave `null` is unchanged.** Passing only `countryCode` updates `countryCode` and nothing else. * **`custom` merges key by key.** A key you send overwrites the stored value for that key; keys you don't send are kept. * **You can't clear a single field.** `null` means "leave as is". To clear everything, call [`reset()`](./reset). * **An empty `EncoreUserAttributes()` does nothing.** [`identify()`](./identify) behaves differently: attributes passed there replace the stored set. ## Usage ### Basic attributes ```dart theme={null} await Encore.shared.setUserAttributes( EncoreUserAttributes( email: 'user@example.com', subscriptionTier: 'premium', monthsSubscribed: '6', ), ); ``` ### Custom attributes ```dart theme={null} await Encore.shared.setUserAttributes( EncoreUserAttributes(custom: {'cancelReason': 'too_expensive'}), ); ``` ### Location ```dart theme={null} await Encore.shared.setUserAttributes( EncoreUserAttributes(countryCode: 'US'), ); ``` > [!NOTE] > > Call `setUserAttributes()` after [`configure()`](./configure). Attributes set before the SDK is configured are not stored. ## Related * [EncoreUserAttributes](./user-attributes): every field, its format, and an example value * [identify()](./identify): sets a user ID and attributes in one call # EncoreUserAttributes Source: https://docs.encorekit.com/publishers/flutter/sdk-reference/user-attributes Every field of EncoreUserAttributes with its type, format, and an example value A class for storing user metadata used in offer targeting, personalization, and analytics. It carries the same fields as the native `UserAttributes` type on [iOS](/publishers/ios/sdk-reference/user-attributes) and [Android](/publishers/android/sdk-reference/user-attributes), and the plugin passes each one through to the native SDK unchanged. All fields are optional: pass only what you have. ## Structure ```dart theme={null} class EncoreUserAttributes { // Identity and basic info final String? email; final String? firstName; final String? lastName; final String? phoneNumber; // Location final String? postalCode; final String? city; final String? state; final String? countryCode; final String? latitude; final String? longitude; // Demographics final int? age; final String? dateOfBirth; final String? gender; final String? language; // Subscription and billing final String? subscriptionTier; final String? monthsSubscribed; final String? billingCycle; final String? lastPaymentAmount; // Engagement final String? lastActiveDate; final String? totalSessions; // Custom attributes final Map custom; const EncoreUserAttributes({ this.email, this.firstName, this.lastName, this.phoneNumber, this.postalCode, this.city, this.state, this.countryCode, this.latitude, this.longitude, this.age, this.dateOfBirth, this.gender, this.language, this.subscriptionTier, this.monthsSubscribed, this.billingCycle, this.lastPaymentAmount, this.lastActiveDate, this.totalSessions, this.custom = const {}, }); } ``` Every value is a `String`, including numbers and dates. Convert before you pass them, for example `months.toString()`. ## Field reference ### Identity and basic info | Field | Type | Format | Example | Description | | - | - | - | - | - | | `email` | `String?` | email address | `user@example.com` | User's email address | | `firstName` | `String?` | free-form string | `Jane` | User's first name | | `lastName` | `String?` | free-form string | `Doe` | User's last name | | `phoneNumber` | `String?` | E.164 or local, with country code for international numbers | `+442071838750` | User's phone number | ### Location | Field | Type | Format | Example | Description | | - | - | - | - | - | | `postalCode` | `String?` | postal/ZIP code | `SW1A 1AA` | Postal or ZIP code | | `city` | `String?` | free-form string | `San Francisco` | City name | | `state` | `String?` | abbr or full | `CA` | State or province | | `countryCode` | `String?` | ISO 3166-1 alpha-2, uppercase | `US` | Country code | | `latitude` | `String?` | decimal degrees | `37.7749` | Geographic latitude | | `longitude` | `String?` | decimal degrees | `-122.4194` | Geographic longitude | ### Demographics | Field | Type | Format | Example | Description | | - | - | - | - | - | | `age` | `int?` | whole years, 0 to 120 | `25` | The user's age. Send the lowest end of a range. A user under 18 is served age-appropriate offers with no per-user personalization. Not saved between launches: pass `dateOfBirth`, or set `age` on every launch | | `dateOfBirth` | `String?` | `YYYY-MM-DD` | `2001-04-18` | The user's date of birth. The SDK works the age out from it on the device and never sends the date. Given `age` too, the lower age is used. An unreadable or future date gives no age | | `gender` | `String?` | free-form string | `female` | User's gender. Common values: `male`, `female`, `non-binary`, `prefer_not_to_say`. Accepted only from an app rated 18+ in its store listing | | `language` | `String?` | BCP-47 tag | `es`, `es-MX` | **Deprecated.** Use [`setLanguage()`](./set-language) instead. From the release that adds `setLanguage()`, setting this field calls it for you and logs a warning once. Removed at the next major release. See [Localization](/publishers/concepts/localization) | ### Subscription and billing | Field | Type | Format | Example | Description | | - | - | - | - | - | | `subscriptionTier` | `String?` | plan name | `free`, `premium`, `pro` | Current subscription plan or tier | | `monthsSubscribed` | `String?` | integer string | `6` | Number of months subscribed | | `billingCycle` | `String?` | enum string | `monthly`, `annual` | Billing frequency | | `lastPaymentAmount` | `String?` | decimal as string | `9.99` | Amount of last payment | ### Engagement | Field | Type | Format | Example | Description | | - | - | - | - | - | | `lastActiveDate` | `String?` | ISO 8601 datetime | `2024-03-15T14:30:00Z` | Timestamp of last activity | | `totalSessions` | `String?` | integer string | `42` | Total number of app sessions | ### Custom attributes | Field | Type | Format | Example | Description | | - | - | - | - | - | | `custom` | `Map` | key-value pairs | `{'churnRisk': 'high'}` | Any additional attributes not covered above. Defaults to an empty map | ## Usage ```dart theme={null} await Encore.shared.setUserAttributes( EncoreUserAttributes( email: 'user@example.com', countryCode: 'US', subscriptionTier: 'premium', monthsSubscribed: '6', custom: {'favoritePosition': 'point_guard'}, ), ); ``` [`setUserAttributes()`](./set-user-attributes) merges these into the stored set; [`identify()`](./identify) replaces it; [`reset()`](./reset) clears it. ## Related * [setUserAttributes()](./set-user-attributes): merges these attributes into the current user's profile * [identify()](./identify): accepts the same attributes alongside your user ID * [UserAttributes on iOS](/publishers/ios/sdk-reference/user-attributes): the native type these fields map to # Send Users Back to an Unfinished Offer Source: https://docs.encorekit.com/publishers/guides/finish-later-links Fetch a claim's offer link from your backend with one HMAC-signed request, to email or message a user who started an offer but did not finish it. A user taps **Claim**, lands on the brand's site, and leaves before finishing. Your backend can fetch the link that user opened and send it back to them later, for example in a "finish this later" email. This needs no app update: it works for any claim your app already made, from its transaction id. The link carries the user's transaction id, so when they finish, the original claim gets the credit. > [!WARNING] > > Whoever opens the link completes the offer **as that user**. Send it only to the user who claimed, and keep it out of logs, analytics and any third-party tool. ## What you need * The claim's **transaction id**: `claim.transactionId` from the placement result in your app. Send it to your server when the user claims. It is null when Encore could not record the claim, and then there is nothing to look up. * If your app calls `identify()`, the **user id** you pass to it. It's optional: leave it out when your app never calls `identify()` and the SDK makes the id itself, and for claims made before `identify()`, which keep the pre-identify owner. * Your project's **publishable key** and its paired **secret key**, from the [dashboard](https://dashboard.encorekit.com). Call this endpoint only from your server. It never accepts a publishable key on its own. ## Request ```http theme={null} GET https://api.encorekit.com/encore/publisher/sdk/v1/transactions/{transactionId}/claim-url?userId=user-123 # userId is optional ``` | Parameter | In | Required | Description | | - | - | - | - | | `transactionId` | path | Yes | The claim's transaction id (a UUID). | | `userId` | query | No | Your user id for the user who made the claim. When you send it, a claim that belongs to another user returns `404`. Leave it out when the SDK makes the id, or for a claim made before `identify()`: that claim keeps its pre-identify owner, so sending the identified id returns `404`. The claim always has to be in your project. | > [!NOTE] > > Leaving out `userId` skips the check that the claim is that user's. The claim still has to be in your project, but making sure the link reaches the right person is then up to you: send it only to the user you stored the transaction id with. ### Authentication The request is HMAC-signed. Send these headers: | Header | Value | | - | - | | `X-API-Key` | Your publishable key (`pk_live_*` or `pk_test_*`). | | `X-Signature` | Hex HMAC-SHA256 of the base string, keyed with the secret key that pairs with your publishable key. | | `X-Timestamp` | Unix time in seconds. It is part of what you sign, and a skew over 5 minutes is rejected. | | `X-Platform` | Required when your project has more than one app: the platform of any app in it (`ios`, `android`, `web` or `api`). Whichever you name, the lookup covers claims from every app in the project. | The base string is `timestamp.METHOD.path.query`. Two details cause most signature failures: * **Sign the path without `/encore`.** You call `/encore/publisher/sdk/v1/...`, but Encore's gateway strips `/encore` before the API checks the signature, so sign `/publisher/sdk/v1/transactions/{transactionId}/claim-url`. * **Sign the query string, not a body.** With `userId`, that's `userId=` followed by the URI-encoded user id. Without it, the query is empty and the base string ends in a dot: `timestamp.GET.path.` ```javascript theme={null} // Your server (Node). Never call this from the app. import crypto from 'node:crypto'; async function fetchClaimUrl(transactionId, userId /* optional */) { const method = 'GET'; const path = `/publisher/sdk/v1/transactions/${transactionId}/claim-url`; // signed: no /encore const query = userId ? `userId=${encodeURIComponent(userId)}` : ''; const timestamp = Math.floor(Date.now() / 1000).toString(); const signature = crypto .createHmac('sha256', process.env.ENCORE_SECRET_KEY) .update(`${timestamp}.${method}.${path}.${query}`) .digest('hex'); const res = await fetch(`https://api.encorekit.com/encore${path}${query ? `?${query}` : ''}`, { method, headers: { 'X-API-Key': process.env.ENCORE_PUBLISHABLE_KEY, 'X-Signature': signature, 'X-Timestamp': timestamp, 'X-Platform': 'ios', // only when the project has more than one app }, }); if (res.status === 404) return null; // not this user's claim, or not in your project if (!res.ok) throw new Error(`claim-url lookup failed: ${res.status}`); const body = await res.json(); return body.claimUrl; // null when there is no link to send; body.reason says why } ``` ## Response ```typescript theme={null} interface ClaimUrlResponse { claimUrl: string | null; // the link to send, or null linkType: string; // "advertiser" today expiresAt: string | null; // ISO 8601 when Encore sets an expiry; null for "advertiser" links reason: string | null; // why claimUrl is null; null when there is a link campaignId: string; status: string; // "open", "completed" or "closed" isTestRequest: boolean; // the claim was made with a test key or a debug build } ``` Send the link when `claimUrl` is not null. Read it as the only signal: any `linkType` value means it is a link you can send. Encore may add values to `linkType`, `reason` and `status`, so treat a `reason` you do not recognize as "no link", and a `status` you do not recognize as closed. `advertiser` links are the brand's own link, and Encore sets no expiry on them. They keep crediting the claim for as long as the brand's network attributes it, often around 30 days. Send it within days of the claim, not weeks later. ### When there is no link | `reason` | Meaning | | - | - | | `completed` | The user already finished this offer. | | `revoked` | The claim's entitlement was revoked. | | `closed` | The claim can no longer be credited. | | `campaign_inactive` | The offer has ended or is paused. | | `not_per_user` | This offer's link credits your app, not a particular user (for example Amazon offers), so there is no per-user link to send. | | `no_destination` | The offer has no link configured. | | `demo` | A demo offer, which test keys see. It has no real brand link. | ### Test keys A test key (`pk_test_*` with its secret) reads only claims made in a development environment: with a test key, or from a debug build. It gets `404` for every live user's claim. Claims made from a debug build on a live key also read with `isTestRequest: true`, and their links are real, so test your email flow with your own account. ## Status codes | Code | Meaning | | - | - | | `200` | Found. Check `claimUrl`. It is null when `reason` explains why there is no link. | | `400` | `X-API-Key`, `X-Signature` or `X-Timestamp` is missing or malformed (a non-hex signature, a non-numeric timestamp), the transaction id is not a UUID, or `userId` is empty or over 256 characters. | | `401` | The signature does not verify, `X-Timestamp` is skewed over 5 minutes, the key does not resolve, or `X-Platform` is missing, not a supported value, or names a platform no app in a multi-app project uses. | | `404` | No such claim in your project, `userId` is not the user who made it, or the user's data was erased. | | `429` | Over 600 lookups per minute for your project, or Encore could not check the limit. Wait for `Retry-After` and retry. | | `5xx` | Encore-side failure. Retry with backoff. | ## Related * `placement()` result, where `claim.transactionId` comes from in your app: [iOS](/publishers/ios/sdk-reference/presentation-result), [Android](/publishers/android/sdk-reference/presentation-result), [React Native](/publishers/react-native/sdk-reference/presentation-result), [Flutter](/publishers/flutter/sdk-reference/presentation-result). # Reward Placements Source: https://docs.encorekit.com/publishers/guides/reward-placements Reward a user in your iOS, Android, React Native, Flutter, or Unity app the moment they finish something worth celebrating, with copy you set per call. Reward a user the moment they accomplish something: a completed purchase, a kept streak, a cleared milestone. Encore presents a reward sheet with premium brand offers (a real perk a brand funds to acquire customers), and it costs you nothing to give. This is the [Reward Users](/publishers/use-cases/post-action-reward) use case; *why* and *when* to use it live on that page. > [!NOTE] > > Requires **iOS SDK 2.0.0**, **Android SDK 2.0.2**, **React Native SDK 2.0.2**, **Flutter SDK 2.0.1**, or the **Unity package 2.5.0**. There is no setup step before this guide: your app is granted its use cases when the app is created, and a reward placement needs no subscription product and no purchase controller. ## The complete pattern Identify the user, then present the placement at the moment your app detects the achievement. Select the `rewardUsers` use case, and set `headline` and `subheadline` to name the moment: ```swift iOS theme={null} import Encore @MainActor func celebrateStreak(customerId: String) async { Encore.shared.identify(userId: customerId) // identity powers attribution let result = await Encore.shared.placement("streak_day_7") .useCase(.rewardUsers) .headline("Nice work, Sam!") // optional .subheadline("That is your fifth week running") // optional .show() if let claim = result.claim { // The user claimed an offer. Keep claim.transactionId; it carries the attribution. if let transactionId = claim.transactionId { persistClaim(transactionId) } } // Every other result: carry on with your own celebration screen. } ``` ```kotlin Android theme={null} import androidx.lifecycle.LifecycleCoroutineScope import com.encorekit.encore.Encore import com.encorekit.encore.UseCase import kotlinx.coroutines.launch fun celebrateStreak(scope: LifecycleCoroutineScope, customerId: String) { Encore.shared.identify(userId = customerId) // identity powers attribution scope.launch { val result = Encore.placement("streak_day_7") .useCase(UseCase.REWARD_USERS) .headline("Nice work, Sam!") // optional .subheadline("That is your fifth week running") // optional .show() result.claim?.let { claim -> // The user claimed an offer. Keep claim.transactionId; it carries the attribution. claim.transactionId?.let(::persistClaim) } // Every other result: carry on with your own celebration screen. } } ``` ```tsx React Native theme={null} import Encore, { UseCase } from '@encorekit/react-native'; async function celebrateStreak(customerId: string) { await Encore.identify(customerId); // identity powers attribution const result = await Encore.placement('streak_day_7') .useCase(UseCase.rewardUsers) .headline('Nice work, Sam!') // optional .subheadline('That is your fifth week running') // optional .show(); if (result.status === 'presented' && result.claim) { // The user claimed an offer. Keep claim.transactionId; it carries the attribution. if (result.claim.transactionId) persistClaim(result.claim.transactionId); } // Every other result: carry on with your own celebration screen. } ``` ```dart Flutter theme={null} import 'package:encore_flutter/encore_flutter.dart'; Future celebrateStreak(String customerId) async { await Encore.shared.identify(userId: customerId); // identity powers attribution final result = await Encore.placement('streak_day_7') .useCase(EncoreUseCase.rewardUsers) .headline('Nice work, Sam!') // optional .subheadline('That is your fifth week running') // optional .show(); final claim = result.claim; if (claim != null) { // The user claimed an offer. Keep claim.transactionId; it carries the attribution. final transactionId = claim.transactionId; if (transactionId != null) persistClaim(transactionId); } // Every other result: carry on with your own celebration screen. } ``` ```csharp Unity theme={null} using EncoreKit; using UnityEngine; public class StreakScreen : MonoBehaviour { public async void CelebrateStreak(string customerId) { Encore.Identify(customerId); // identity powers attribution var result = await Encore.Placement("streak_day_7") .UseCase(UseCase.RewardUsers) .Headline("Nice work, Sam!") // optional .Subheadline("That is your fifth week running") // optional .ShowAsync(); if (result.Claim?.TransactionId is string transactionId) { // The user claimed an offer. Keep the transaction ID; it carries the attribution. PersistClaim(transactionId); } // Every other result: carry on with your own celebration screen. } private void PersistClaim(string transactionId) { /* your storage */ } } ``` Contracts: `placement()` for [iOS](/publishers/ios/sdk-reference/placement), [Android](/publishers/android/sdk-reference/placement), [React Native](/publishers/react-native/sdk-reference/placement), and [Flutter](/publishers/flutter/sdk-reference/placement) · `PresentationResult` for [iOS](/publishers/ios/sdk-reference/presentation-result), [Android](/publishers/android/sdk-reference/presentation-result), [React Native](/publishers/react-native/sdk-reference/presentation-result), and [Flutter](/publishers/flutter/sdk-reference/presentation-result) · [`Placement()`](/publishers/unity/sdk-reference/placement) and [`PresentationResult`](/publishers/unity/sdk-reference/presentation-result) for Unity. `show()` never throws (on React Native, its promise never rejects) and resolves exactly once. On iOS call it from a main-actor context; on Android it is a suspend function, so call it from a coroutine such as `lifecycleScope`; on React Native and Flutter, await it; on Unity, await `ShowAsync()` from the main thread. iOS, Android, and Unity also take a callback form for call sites that can't await: `show(resume:)` on iOS, `show(onResult:)` on Android, and `Show(onResult)` on Unity, which throws only for a null callback. A reward placement is claim-only: it runs no in-app purchase, so your purchase controller is never called. ## Where the copy comes from `headline` and `subheadline` take the finished string for one presentation, and Encore never translates it, so localize it yourself. Pass nothing and the sheet still renders, with the copy Encore resolved for your app or the copy shipped with the screen. The full chain is on [Where the copy comes from](/publishers/use-cases/post-action-reward#where-the-copy-comes-from). ## Read the result `result.claim` (`result.Claim` on Unity) is the offer the user claimed, or empty when they didn't claim one. On React Native it exists only on a presented result, so check `result.status` first. It means the user tapped through to the brand, not that they finished the offer. Keep `claim.transactionId` when it is present; it carries the attribution. When no sheet appeared, the result says why. No offers matching this user, an error (which arrives as a value on the result), and `useCaseUnavailable` (`use_case_unavailable` on React Native) are the common reasons. `useCaseUnavailable` means nothing resolved for this use case, which includes a user in the holdout group of an Encore sheet experiment that shows its holdout group no sheet. A reward placement never returns `experimentControl` (`experiment_control` on React Native, `ExperimentControl` on Unity); that reason belongs to the Reduce Churn control cohort. Treat each of these as a normal outcome for a reward moment: show your own celebration without the offer and carry on. ## Gotchas * **You pass the finished string.** There is no streak-count or milestone-count parameter; Encore never assembles a sentence out of a count. * **A blank override is not an override.** An empty or whitespace-only value falls through to the next source rather than clearing the line. To show less, omit the call. * **A claim is not a conversion.** The bounty is earned only when the brand-side completion is verified on Encore's servers. Never pay out or grant access on a claim alone; the [offer\_completed webhook](/publishers/offers-api/guides/receive-completion-events) reports the verified completion, joined on `transactionId`. * **Omitting the use case selects Reduce Churn.** A placement without `useCase` presents the Reduce Churn sheet, which can run a purchase. Select `rewardUsers` on every reward placement. ## Related * [Reward Users](/publishers/use-cases/post-action-reward): the canonical description of this use case. * The `placement()` reference for [iOS](/publishers/ios/sdk-reference/placement), [Android](/publishers/android/sdk-reference/placement), [React Native](/publishers/react-native/sdk-reference/placement), and [Flutter](/publishers/flutter/sdk-reference/placement): every builder method, including the use case and copy overrides. On Unity, [`Placement()`](/publishers/unity/sdk-reference/placement). # Add Subscription Product Source: https://docs.encorekit.com/publishers/ios/guides/add-subscription-product Pick the App Store subscription Encore purchases when a user accepts an offer. ## Overview > [!NOTE] > > This step applies to **Reduce Churn** placements only. A [reward placement](/publishers/guides/reward-placements) never runs a purchase, so an app that presents only reward placements can skip it. Now that placements are presenting, choose the subscription product Encore offers. When a user accepts an offer, Encore hands the configured product id to your registered [`EncorePurchaseController`](../sdk-reference/purchase-controller), which performs the purchase through your billing code and owns the resulting entitlement state. > [!NOTE] > > **Using a third-party subscription manager?** How the purchase completes changes: see [Superwall](/publishers/ios/guides/managers/superwall/add-subscription-product), [RevenueCat](/publishers/ios/guides/managers/revenuecat/add-subscription-product), [Adapty](/publishers/ios/guides/managers/adapty/add-subscription-product), or [multiple managers](/publishers/ios/guides/managers/multiple-managers). The setup itself is store-console work, done once in App Store Connect and your app's **Entitlements** step: > [card] [App Store Subscription Product](/publishers/ios/platform-setup/subscription-product) > > Connect your App Store Connect catalog and pick the subscription Encore offers, let Encore create one for you, or enter a Product ID manually. *** ## What the SDK does with the Product ID at runtime You never hard-code the Product ID in your app; Encore delivers it to the SDK as **remote configuration**: * The SDK fetches your app's config (including the configured subscription Product ID) on `configure()` and again on each `identify()` that actually changes the user id or attributes. * That config is **disk-cached**, so it's available immediately on cold start; the SDK refreshes it in the background on the next launch. The very first launch (before the first fetch completes) is the only time the Product ID may be momentarily unavailable. * When a user accepts an offer, the SDK passes the configured Product ID to your registered [`EncorePurchaseController`](../sdk-reference/purchase-controller) as `request.productId`. Your controller performs the purchase; the SDK never purchases on its own. Because it's remote config, changing the product in the Encore Dashboard takes effect without an app update. *** ## Next Steps * [Configure Analytics](../quickstart/configure-analytics) - Forward App Store subscription events so Encore can measure offer impact # Integration Patterns Source: https://docs.encorekit.com/publishers/ios/guides/integration-patterns How to consume Encore offer results in Swift, at the call site and in passive observers. ## Overview `await Encore.shared.placement(_:).show()` returns a [`PresentationResult`](../sdk-reference/presentation-result): the factual record of the presentation. It never throws, and it resolves exactly once. Three rules cover almost every integration: 1. **Invoke `show()` from a main-actor context.** The facade and builder are `@MainActor`. 2. **Results are values: await inline for control flow.** Branch on the result where the context lives. 3. **`outcomes` is for passive observers.** Analytics, debug overlays, and cross-screen state consume the stream instead of owning a call site. *** ## Rule 1: Invoke show() from a main-actor context Call `show()` from a SwiftUI button action, a `.task`, or a UIKit handler; you are already on the main actor there, and the compiler enforces the rest. ```swift theme={null} Button("Upgrade") { Task { // inherits @MainActor from the button action let result = await Encore.placement("upgrade_button").show() handle(result) } } ``` Presentation mutates UI state; invoking it off-main would order the sheet arbitrarily against your progressing app UI. From nonisolated code, `await` hops you over: it compiles, and the result still resumes on main. *** ## Rule 2: Results are values, await inline for control flow Branch on the raw facts your flow cares about: ```swift theme={null} func cancelTapped() { Task { let result = await Encore.placement("cancel_flow").show() if result.claim != nil || result.publisher == .purchased { // The user claimed an offer or completed your purchase. // Read the concrete entitlement from isActive / isActivePublisher. navigateHome() } else { result.error.map(log) // presentation failures are values proceedWithCancellation() // dismissed, declined, nothing appeared, ... } // Code that runs in both branches lives here, written once analytics.track("cancel_flow_resolved") } } ``` There is no SDK-computed "unlocked" verdict: what a claim means is a property of the flow that served it, so the record reports what happened and your integration decides. When the mechanism matters (analytics, debugging), switch on the factual record: ```swift theme={null} switch result { case .presented(let outcome): // advertiser + publisher funnels, dismissal analytics.log(outcome.advertiser, outcome.publisher, outcome.dismissal) case .notPresented(let reason): // no offers, control cohort, error, ... analytics.log(reason) } ``` ### When the call site can't await `show(resume:)` delivers every outcome, including `.notPresented`, on the main actor: ```swift theme={null} Button("Cancel Subscription") { Encore.placement("cancel_flow").show { result in if result.claim == nil && result.publisher != .purchased { proceedWithCancellation() } } } ``` ### Sharing the result across the app When other parts of the app need the outcome, forward it into an app-owned `@Observable` state object distributed via `.environment(_:)`: ```swift theme={null} @Observable final class OfferState { var lastResult: PresentationResult? func apply(_ result: PresentationResult) { lastResult = result } } // at the call site Task { let result = await Encore.placement("paywall").show() offerState.apply(result) } ``` *** ## Rule 3: outcomes is for passive observers Anything that wants to watch results without owning a call site consumes the multicast [`outcomes`](../sdk-reference/outcomes) stream. Every resolution lands there, plus late events: ```swift theme={null} .task { for await outcome in Encore.shared.outcomes { switch outcome { case .presentation(let placementId, let result): analytics.log("encore", placementId, "\(result)") case .strictUnlockVerified(let transactionId): // A strict-unlock claim verified after its flow ended, possibly // on a later launch. Entitlements are already refreshed; gate on // isActive / isActivePublisher. print("late verification for \(transactionId)") } } } ``` Each access to `outcomes` returns an independent stream; any number of observers can listen concurrently. *** ## Recipe: paywall-delegate call sites (Superwall and friends) Delegate methods hand you a synchronous, nonisolated context. Bridge with a `Task`, forward the result into your state object: ```swift theme={null} extension PaywallService: SuperwallDelegate { func handleCustomPaywallAction(withName name: String) { guard name == "encore_offer" else { return } Task { @MainActor in let result = await Encore.placement("superwall_action").show() appState.apply(result) } } } ``` Register your purchase controller once at configure time, so purchases the sheet triggers run through your subscription manager: ```swift theme={null} Encore.shared.configure(apiKey: key, purchaseController: AppPurchases()) ``` *** ## Platform-specific notes * **`Task { }` wrapping**: `show()` is `async`; SwiftUI `Button` actions and UIKit `@IBAction` selectors are synchronous, so wrap the call in `Task { ... }`. * **`show()` never throws**: failures arrive as `.notPresented(.error(EncoreError))`, read via `result.error`. There is no `catch` block to forget. * **`Encore` is the entry point**: `Encore` is a `public final class`. Access it via `Encore.shared`; the static `Encore.placement(_:)` forwards to it. * **Purchases**: there are no purchase handlers to register per call site. The [`EncorePurchaseController`](../sdk-reference/purchase-controller) passed to `configure` owns every purchase. *** ## See also * [Presenting Offers](/publishers/ios/quickstart/present-offers): the quickstart walkthrough * [`placement()`](../sdk-reference/placement), [`PresentationResult`](../sdk-reference/presentation-result), and [`outcomes`](../sdk-reference/outcomes) in the SDK Reference # Add Subscription Product with Adapty Source: https://docs.encorekit.com/publishers/ios/guides/managers/adapty/add-subscription-product Route the purchase Encore requests through Adapty, or report a StoreKit 2 purchase to it. ## Overview You still pick the product in App Store Connect and the Encore Dashboard exactly as in [Add Subscription Product](/publishers/ios/guides/add-subscription-product). What changes with Adapty is which billing code your [`EncorePurchaseController`](/publishers/ios/sdk-reference/purchase-controller) calls and how Adapty learns about the purchase. Adapty ships no paywall component, so [Presenting Offers](/publishers/ios/quickstart/present-offers) needs no change: call `show()` from your own UI. *** ## Add the product to Adapty first Creating the product in App Store Connect is not enough. Adapty keeps its own product catalog, and the mapping from a product to an access level lives there rather than in the store. **1. Connect the store product** In the Adapty dashboard, add the product and connect it to the existing App Store product. This requires your App Store credentials to be connected, and it is a manual step per product. **2. Give it an access level** Assign the access level the product should unlock, from the **Access level ID** list. Adapty makes this mandatory: the field is marked required, and the form refuses to save a product without one. > [!NOTE] > > Adapty is stricter here than the other managers, in your favour. Because the access level is required at creation, you cannot end up with a purchasable product that grants nothing. And a product Adapty does not know about never reaches `makePurchase()`, so you get `Code-1000 noProductIDsFound` on your first test purchase rather than a support ticket months later. > [!WARNING] > > **Access levels only grant access in the first mode below.** If you run Adapty in observer mode, as the second mode does, Adapty does not respond to purchase events to grant or restrict paid access. Its own comparison table marks that unavailable in observer mode, and states: "You are tasked with managing access to the paid content in their app." Register the product either way, because otherwise the transaction is missing from your analytics, but gate your paid features on your own logic rather than on an Adapty access level. *** ## Route the purchase through Adapty Have your controller purchase through Adapty. Encore hands it the configured product id and Adapty performs the purchase, so a product you added in the preceding steps updates its access levels the way any other Adapty sale does: ```swift theme={null} final class AppPurchases: EncorePurchaseController { func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult { let products = try await Adapty.getPaywallProducts(paywall: paywall) guard let product = products.first(where: { $0.vendorProductId == request.productId }) else { throw PurchaseError.notFound } let result = try await Adapty.makePurchase(product: product) return result.isPurchaseCancelled ? .cancelled : .purchased } } Encore.shared.configure(apiKey: "pk_live_your_key", purchaseController: AppPurchases()) ``` *** ## Or purchase with StoreKit 2 and report to Adapty Alternatively, purchase through StoreKit 2 in your controller and report the transaction to Adapty from the same place. Adapty does not detect StoreKit 2 transactions on its own, so run it in observer mode: ```swift theme={null} try await Adapty.activate(with: .builder(withAPIKey: "YOUR_KEY") .with(observerMode: true) .build() ) final class AppPurchases: EncorePurchaseController { func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult { let products = try await Product.products(for: [request.productId]) guard let product = products.first else { throw PurchaseError.notFound } switch try await product.purchase() { case .success(let verification): if case .verified(let transaction) = verification { await transaction.finish() try? await Adapty.reportTransaction(transaction) } return .purchased case .userCancelled: return .cancelled case .pending: return .pending @unknown default: return .cancelled } } } ``` > [!NOTE] > > Adapty 3.3 and later require an explicit `reportTransaction()` call for StoreKit 2 transactions in observer mode. > [!WARNING] > > Observer mode is analytics only. Adapty does not grant or restrict paid access from a reported transaction, so your app owns that decision: gate your paid features on your own state, not on an Adapty access level. Report every transaction anyway, because Adapty's documentation warns that without `reportTransaction` it "won't recognize the transaction, it won't appear in analytics, and it won't be sent to integrations." *** ## Next * [Configure Analytics](./configure-analytics) - keep both Adapty and Encore receiving subscription events # Configure Analytics with Adapty Source: https://docs.encorekit.com/publishers/ios/guides/managers/adapty/configure-analytics Keep both Adapty and Encore receiving App Store Server Notifications when they compete for the same URL. ## Overview Adapty does not forward subscription events to Encore, so [Configure Analytics](/publishers/ios/quickstart/configure-analytics) applies unchanged: Encore reads Apple's App Store Server Notifications directly. The one thing Adapty changes is that two services now want the same notification URL, and App Store Connect holds one primary per environment. *** ## Give both services the notifications App Store Connect sends to whichever URL you set as primary. Whichever service loses the primary slot receives its events by forwarding. * **Encore primary:** set Encore's URL in App Store Connect and forward each notification on to the ASSN V2 URL from your Adapty dashboard. * **Adapty primary:** leave Adapty's URL in place and use the *forward from your own server* option on [App Store Server Notifications](/publishers/ios/platform-setup/server-notifications) to reach Encore. > [!NOTE] > > Forwarding matters most when Encore purchases through StoreKit rather than Adapty. See [Add Subscription Product](./add-subscription-product) for which path you are on. # Using Multiple Managers Source: https://docs.encorekit.com/publishers/ios/guides/managers/multiple-managers Route Encore purchase requests across several subscription managers and merge their entitlements into one flag. ## Overview When more than one subscription manager is live in your app, two things need a decision that a single-manager setup makes for you: which manager performs a given purchase, and how you combine each manager's entitlement state with Encore's grants. The rest of [Add Subscription Product](/publishers/ios/guides/add-subscription-product) is unchanged. > [!NOTE] > > Each product still needs registering in the manager that sells it, and attaching to that manager's entitlement, before the state merged below turns true: [RevenueCat](/publishers/ios/guides/managers/revenuecat/add-subscription-product), [Superwall](/publishers/ios/guides/managers/superwall/add-subscription-product), [Adapty](/publishers/ios/guides/managers/adapty/add-subscription-product), [Qonversion](/publishers/ios/guides/managers/qonversion/add-subscription-product). *** ## Route the purchase Branch inside your [`EncorePurchaseController`](/publishers/ios/sdk-reference/purchase-controller) on the product id Encore hands you: ```swift theme={null} final class AppPurchases: EncorePurchaseController { func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult { if request.productId.hasPrefix("rc_") { let products = try await Purchases.shared.products([request.productId]) guard let product = products.first else { throw PurchaseError.notFound } let result = try await Purchases.shared.purchase(product: product) return result.userCancelled ? .cancelled : .purchased } guard let product = try await Product.products(for: [request.productId]).first else { throw PurchaseError.notFound } switch try await product.purchase() { case .success(let verification): if case .verified(let transaction) = verification { await transaction.finish() } return .purchased case .userCancelled: return .cancelled case .pending: return .pending @unknown default: return .cancelled } } } Encore.shared.configure(apiKey: "pk_live_your_key", purchaseController: AppPurchases()) ``` *** ## Merge the entitlement state Each manager publishes its own subscription state, and Encore publishes its grants through [`isActivePublisher()`](/publishers/ios/sdk-reference/is-active-publisher). Combine them into the single flag your UI gates on: ```swift theme={null} import Combine import Encore import RevenueCat import SuperwallKit @MainActor final class EntitlementManager: ObservableObject { @Published var hasProAccess = false private var cancellables = Set() private let revenueCatActive = CurrentValueSubject(false) init() { Purchases.shared.delegate = self Publishers.CombineLatest3( revenueCatActive.eraseToAnyPublisher(), Superwall.shared.$subscriptionStatus, Encore.shared.isActivePublisher(for: .freeTrial()) ) .map { revenueCat, superwall, encore in revenueCat || superwall != .inactive || encore } .assign(to: \.hasProAccess, on: self) .store(in: &cancellables) } } extension EntitlementManager: PurchasesDelegate { nonisolated func purchases(_ purchases: Purchases, receivedUpdated customerInfo: CustomerInfo) { Task { @MainActor in revenueCatActive.send(!customerInfo.entitlements.active.isEmpty) } } } ``` Full contracts: [`isActivePublisher()`](/publishers/ios/sdk-reference/is-active-publisher) · [`isActive()`](/publishers/ios/sdk-reference/is-active) · [`EntitlementScope`](/publishers/ios/sdk-reference/entitlement-scope). # Add Subscription Product with Qonversion Source: https://docs.encorekit.com/publishers/ios/guides/managers/qonversion/add-subscription-product Route the purchase Encore requests through Qonversion, and give the product an entitlement so it unlocks something. ## Overview You still pick the product in App Store Connect and the Encore Dashboard exactly as in [Add Subscription Product](/publishers/ios/guides/add-subscription-product). What changes with Qonversion is which billing code your [`EncorePurchaseController`](/publishers/ios/sdk-reference/purchase-controller) calls. Qonversion ships no paywall component, so [Presenting Offers](/publishers/ios/quickstart/present-offers) needs no change: call `show()` from your own UI. *** ## Add the product to Qonversion first Creating the product in App Store Connect is not enough. Qonversion keeps its own product catalog, and the mapping from a product to an entitlement lives there rather than in the store. **1. Create the product** In the Qonversion dashboard, create a product whose store identifier matches the one in App Store Connect. **2. Attach it to an entitlement** Open the **entitlement** the product should unlock and add the product to it. The association is only editable from the entitlement side: Qonversion's `POST /products` has no entitlement field, and the API equivalent is the entitlement's `product_ids` list. > [!NOTE] > > Qonversion fails early when you skip the first step, which makes this easier to catch than the equivalent gap in other managers. A product Qonversion does not know about is rejected with a typed `QONErrorCodeProductNotFound (2)` on your first test purchase rather than in a support ticket months later. > [!WARNING] > > The second step fails quietly instead. A product that exists in Qonversion but belongs to no entitlement is purchasable, and the purchase completes, but it grants nothing. The snippet below guards against that by reading the returned entitlements. *** ## Route the purchase through Qonversion Qonversion's iOS purchase API is completion-based, so the controller bridges it with `withCheckedThrowingContinuation` before it can return the `EncorePurchaseResult` Encore expects: ```swift theme={null} import Qonversion final class AppPurchases: EncorePurchaseController { func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult { // Bridge Qonversion's completion into the result Encore expects. // A cancel is not a purchase: report .cancelled, never .purchased. return try await withCheckedThrowingContinuation { continuation in Qonversion.shared().purchase(request.productId) { entitlements, error, cancelled in if let error { continuation.resume(throwing: error) } else { continuation.resume(returning: cancelled || entitlements.isEmpty ? .cancelled : .purchased) } } } } } Encore.shared.configure(apiKey: "pk_live_your_key", purchaseController: AppPurchases()) ``` > [!NOTE] > > The `entitlements.isEmpty` check is deliberate. Qonversion hands you the granted entitlements in the same callback, so the controller can tell "bought and unlocked" from "bought and unlocked nothing" without a second call. Reporting `.purchased` for an empty set would record a conversion for a user who received no access. > [!WARNING] > > An empty entitlement set is also the correct state for a consumable, which is not meant to grant ongoing access. If you sell consumables through this controller, branch on the product id rather than treating every empty set as a cancel. *** ## Promotional offers A discount hangs off the product's `SKProduct`, so the promotional path needs the product object rather than the id. Signing is completion-based too, and a nil offer is not an error: it means this user buys at list price. ```swift theme={null} let products = try await Qonversion.shared().products() guard let product = products.first(where: { $0.value.storeID == request.productId })?.value else { throw PurchaseError.notFound } let options = Qonversion.PurchaseOptions() if let offerId = promoOfferId, let discount = product.skProduct?.discounts.first(where: { $0.identifier == offerId }) { options.promoOffer = await withCheckedContinuation { continuation in Qonversion.shared().getPromotionalOffer(for: product, discount: discount) { offer, _ in continuation.resume(returning: offer) } } } ``` Purchase with `Qonversion.shared().purchaseProduct(product, options: options)` and bridge the completion exactly as in the plain path. *** ## Next * [Configure Analytics](./configure-analytics) - keep both Qonversion and Encore receiving subscription events # Configure Analytics with Qonversion Source: https://docs.encorekit.com/publishers/ios/guides/managers/qonversion/configure-analytics Keep both Qonversion and Encore receiving App Store Server Notifications when they compete for the same URL. ## Overview Qonversion does not forward subscription events to Encore, so [Configure Analytics](/publishers/ios/quickstart/configure-analytics) applies unchanged: Encore reads Apple's App Store Server Notifications directly. The one thing Qonversion changes is that two services now want the same notification URL, and App Store Connect holds one primary per environment. *** ## Give both services the notifications App Store Connect sends to whichever URL you set as primary. Whichever service loses the primary slot receives its events by forwarding. * **Encore primary:** set Encore's URL in App Store Connect and forward each notification on to the notification URL from your Qonversion dashboard. * **Qonversion primary:** leave Qonversion's URL in place and use the *forward from your own server* option on [App Store Server Notifications](/publishers/ios/platform-setup/server-notifications) to reach Encore. > [!NOTE] > > Encore measures offer impact from the App Store notifications it receives, not from Qonversion's entitlements. The two are independent: a product that grants a Qonversion entitlement still needs Encore to see the notification before it appears in your offer reporting. # Add Subscription Product with RevenueCat Source: https://docs.encorekit.com/publishers/ios/guides/managers/revenuecat/add-subscription-product Route the purchase Encore requests through RevenueCat, or let RevenueCat observe a StoreKit 2 purchase. ## Overview You still pick the product in App Store Connect and the Encore Dashboard exactly as in [Add Subscription Product](/publishers/ios/guides/add-subscription-product). What changes with RevenueCat is which billing code your [`EncorePurchaseController`](/publishers/ios/sdk-reference/purchase-controller) calls and how RevenueCat learns about the purchase. *** ## Add the product to RevenueCat first Creating the product in App Store Connect is not enough. RevenueCat keeps its own product catalog, and the mapping from a product to an entitlement lives there rather than in the store. Complete both steps below before you ship the offer. **1. Connect your store, if you have not already** The import needs App Store credentials. Until they are connected, RevenueCat does not show an import option at all, so this step is easy to miss and looks like the feature is absent. **2. Import the product into RevenueCat** Go to **Product catalog → Products → + New**. The import block sits at the top of that page, before the manual fields. Import runs on demand: RevenueCat does not discover new App Store products in the background, so a product you added after your last import does not appear on its own. **3. Attach the product to an entitlement** Open the product and add it to the entitlement it should unlock. This is a separate action from importing, and it is the step that decides whether a purchase grants access. > [!WARNING] > > Skipping the entitlement step is the common failure. RevenueCat's [documentation](https://www.revenuecat.com/docs/getting-started/entitlements) warns that failing to add your products to an entitlement "could lead to your users making purchases that don't unlock access to the promised content." > > It does not fail loudly. RevenueCat [records the purchase either way](https://www.revenuecat.com/docs/offerings/products-overview): "If a user purchases a product that has not been set up in RevenueCat, the transaction will still be tracked in RevenueCat, and the product will be automatically created in RevenueCat." That auto-created product has no entitlement, so the sale looks healthy on your dashboard while the customer has nothing. > [!NOTE] > > Attaching an entitlement is retroactive: "Attaching an entitlement to a product will grant that entitlement to any customers that have previously purchased that product." So if you find a live product without one, attach it rather than refunding those purchases. The same is true in reverse, so detaching an entitlement removes access from people who already paid. *** ## Route the purchase through RevenueCat Have your controller purchase through RevenueCat. Encore hands it the configured product id and RevenueCat performs the purchase, so a product you registered in the preceding steps updates its entitlements the way any other RevenueCat sale does: ```swift theme={null} final class AppPurchases: EncorePurchaseController { func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult { let products = try await Purchases.shared.products([request.productId]) guard let product = products.first else { throw PurchaseError.notFound } let result = try await Purchases.shared.purchase(product: product) return result.userCancelled ? .cancelled : .purchased } } Encore.shared.configure(apiKey: "pk_live_your_key", purchaseController: AppPurchases()) ``` *** ## Or let RevenueCat observe a StoreKit 2 purchase Alternatively, keep the plain StoreKit 2 controller from [Presenting Offers](/publishers/ios/quickstart/present-offers#handle-purchases) and configure RevenueCat to observe purchases your app completes; it detects the transaction on its own: ```swift theme={null} Purchases.configure( with: .builder(withAPIKey: "YOUR_RC_KEY") .with(purchasesAreCompletedBy: .myApp, storeKitVersion: .storeKit2) .build() ) ``` > [!NOTE] > > No extra sync code is needed in this mode. RevenueCat detects the StoreKit transaction itself. > [!WARNING] > > Detecting the transaction is not the same as granting the entitlement. This mode still requires the product to be registered and attached to an entitlement, exactly as in the preceding steps. *** ## Next * [Configure Analytics](./configure-analytics) - forward RevenueCat's subscription events to Encore # Configure Analytics with RevenueCat Source: https://docs.encorekit.com/publishers/ios/guides/managers/revenuecat/configure-analytics Forward RevenueCat's subscription events to Encore instead of wiring App Store Server Notifications. ## Overview Encore measures offer impact from the subscription lifecycle events described in [Configure Analytics](/publishers/ios/quickstart/configure-analytics). When RevenueCat owns your subscriptions, it already receives those events, so you forward from RevenueCat instead of wiring App Store Server Notifications. Two paths do that; pick one. *** ## Forward events from RevenueCat The direct path. RevenueCat posts subscription lifecycle events straight to Encore. **1. Open your RevenueCat dashboard** Go to **Project Settings → Integrations → Webhooks**. **2. Create a webhook** Set the URL to `https://api.encorekit.com/encore/webhooks/revenuecat/` and save. > [!NOTE] > > Your RevenueCat webhook token (an `rcw_…` value) is issued by Encore and surfaced in your dashboard. Unlike your SDK API keys, which you retrieve yourself, this third-party webhook token is provisioned during onboarding, so share your RevenueCat project details with Encore to receive it. *** ## Forward from your own server The path for publishers who already operate a server that fans App Store Server Notifications out to several destinations. Add Encore as one of its destinations and leave RevenueCat's webhook configuration alone. The forwarding contract is on [App Store Server Notifications](/publishers/ios/platform-setup/server-notifications). # Present Offers with RevenueCat Source: https://docs.encorekit.com/publishers/ios/guides/managers/revenuecat/present-offers Trigger an Encore placement from a RevenueCat paywall dismissal. ## Overview RevenueCat owns the paywall, so the only thing that changes is *where* you call `show()`. Everything else in [Presenting Offers](/publishers/ios/quickstart/present-offers) applies unchanged: the same placement call, the same purchase controller, the same outcome model. Pick the hook that matches how you present the RevenueCat paywall. *** ## From `PaywallView` `onRequestDismiss` fires when the user closes the paywall without converting: ```swift theme={null} import RevenueCat import RevenueCatUI import Encore PaywallView( onRequestDismiss: { paywallInfo, paywallResult in Encore.shared.placement("paywall_decline").show { result in if result.claim == nil && result.publisher != .purchased { // Nothing claimed or purchased: resume your normal flow. } } } ) ``` *** ## From the `presentPaywallIfNeeded` modifier ```swift theme={null} import RevenueCat import RevenueCatUI import Encore YourView() .presentPaywallIfNeeded( presentationMode: .sheet, onDismiss: { Encore.shared.placement("paywall_decline").show { result in if result.claim == nil && result.publisher != .purchased { // Nothing claimed or purchased: resume your normal flow. } } } ) ``` Full contract: [`placement()`](/publishers/ios/sdk-reference/placement). *** ## Next * [Add Subscription Product](./add-subscription-product) - route the purchase through RevenueCat # Add Subscription Product with Superwall Source: https://docs.encorekit.com/publishers/ios/guides/managers/superwall/add-subscription-product Add the product to Superwall, then let Superwall observe the App Store purchase your controller makes. ## Overview You still pick the product in App Store Connect and the Encore Dashboard exactly as in [Add Subscription Product](/publishers/ios/guides/add-subscription-product). What changes with Superwall is how Superwall learns about the purchase your [`EncorePurchaseController`](/publishers/ios/sdk-reference/purchase-controller) makes. *** ## Add the product to Superwall first Creating the product in App Store Connect is not enough. Superwall keeps its own product list, and the mapping from a product to an entitlement lives there rather than in the store. **1. Add the product** In the Superwall dashboard, select your app, open **Products** in the sidebar, and choose **+ Add Product**. The form is manual, so copy the identifier from App Store Connect and fill in the fields yourself. Superwall does offer a store import, but it stays unavailable until you connect your store under **Integrations**, and for a single product the manual form is the shorter path. **2. Link it to an entitlement** Set the **Entitlements** field to the entitlement the product should unlock. Superwall states the requirement plainly: "Every subscription product must be linked to at least one entitlement." The field is optional in the form even though the rule is not, so nothing stops you from saving a product without one. > [!WARNING] > > Superwall derives access from entitlements, not from the transaction, and it [describes the failure directly](https://superwall.com/features/entitlements-and-products): a product with no entitlement "grants no access", and "the purchase succeeds, but the user's subscription status stays inactive." > > So this does not surface as an error. The customer is charged, your dashboard shows a sale, and the feature stays locked. > [!NOTE] > > Leaving **Entitlements** empty is correct for a consumable product, which is not meant to unlock ongoing access. Set **Period** to *None (Lifetime / Consumable)* and select no entitlement. A non-consumable product uses the same period but must be linked to the entitlement it unlocks. *** ## Purchase with StoreKit 2, let Superwall observe Superwall exposes no purchase API in observer mode, so register the StoreKit 2 controller from [Presenting Offers](/publishers/ios/quickstart/present-offers#handle-purchases) and turn on observer mode at Superwall configure time. Your controller purchases through StoreKit 2, and Superwall picks the transaction up on its own: ```swift theme={null} let options = SuperwallOptions() options.shouldObservePurchases = true Superwall.configure(apiKey: "YOUR_SW_KEY", options: options) Encore.shared.configure(apiKey: "pk_live_your_key", purchaseController: AppPurchases()) ``` > [!NOTE] > > No extra sync code is needed. Superwall detects the StoreKit transaction itself. > [!WARNING] > > Detecting the transaction is not the same as granting the entitlement. Observer mode leaves Superwall in charge of `subscriptionStatus`, and it computes that value from the entitlements attached to the product. A product you never added to Superwall still needs the preceding setup. > [!WARNING] > > Observer mode requires iOS 17.2 or later and disables `Superwall.shared.purchase()`. All purchases go through StoreKit directly. *** ## Next * [Configure Analytics](./configure-analytics) - point Superwall's webhook at Encore # Configure Analytics with Superwall Source: https://docs.encorekit.com/publishers/ios/guides/managers/superwall/configure-analytics Point Superwall's webhook at Encore so your subscription events reach it without App Store Server Notifications. ## Overview Encore measures offer impact from the subscription lifecycle events described in [Configure Analytics](/publishers/ios/quickstart/configure-analytics). When Superwall owns your subscriptions, its webhook already carries those events, so you forward from Superwall instead of wiring App Store Server Notifications. *** ## Add the Encore webhook in Superwall **1. Open your Superwall dashboard** Go to **Integrations → Webhooks → Create**. **2. Set the destination URL** Use `https://api.encorekit.com/encore/webhooks/superwall/`. **3. Share the signing secret** Copy the signing secret Superwall shows you and share it securely with Encore. Encore verifies the Svix HMAC signature on every inbound event with it. > [!NOTE] > > Your Superwall webhook token (a `swl_…` value) is issued by Encore and surfaced in your dashboard. Unlike your SDK API keys, which you retrieve yourself, this third-party webhook token is provisioned during onboarding, so share your Superwall project details with Encore to receive it. *** ## Forward from your own server instead If you already operate a server that fans App Store Server Notifications out to several destinations, add Encore as one of its destinations rather than pointing Superwall at Encore. The forwarding contract is on [App Store Server Notifications](/publishers/ios/platform-setup/server-notifications). # Present Offers with Superwall Source: https://docs.encorekit.com/publishers/ios/guides/managers/superwall/present-offers Trigger an Encore placement from a Superwall paywall dismissal or a custom paywall action. ## Overview Superwall owns the paywall, so the only thing that changes is *where* you call `show()`. Everything else in [Presenting Offers](/publishers/ios/quickstart/present-offers) applies unchanged: the same placement call, the same purchase controller, the same outcome model. > [!WARNING] > > **Type ambiguity with SuperwallKit.** Both Encore and SuperwallKit declare a type named `PresentationResult`. In any file that imports both, add a scoped import at the top: > > ```swift theme={null} > import enum Encore.PresentationResult > ``` > > Writing `Encore.PresentationResult` inline does **not** disambiguate, because `Encore` names both the module and the facade class, and Swift resolves the class first. The scoped enum import is the fix. *** ## Trigger on paywall dismissal Present an offer when a user closes your Superwall paywall without converting. Delegate methods are synchronous and nonisolated, so bridge with a `Task`: ```swift theme={null} import SuperwallKit import Encore import enum Encore.PresentationResult class SWDelegate: SuperwallDelegate { func willDismissPaywall(withInfo paywallInfo: PaywallInfo) { Task { @MainActor in let result = await Encore.shared.placement("paywall_decline").show() if result.claim == nil && result.publisher != .purchased { // Nothing claimed or purchased: resume your normal flow. } } } } ``` Full contract: [`placement()`](/publishers/ios/sdk-reference/placement). *** ## Trigger from a custom paywall action Superwall paywalls can emit named actions. Handle the name in your delegate and route it to a placement: ```swift theme={null} import SuperwallKit import Encore import enum Encore.PresentationResult class SWDelegate: SuperwallDelegate { func handleCustomPaywallAction(withName name: String) { if name == "EncoreTrigger" { Task { @MainActor in let result = await Encore.shared.placement("paywall_decline").show() appState.apply(result) } } } } ``` In the Superwall editor, add a custom action named `EncoreTrigger` to the button or element that should open the offer.