# 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}
>
>
>
> );
> }
> ```
> [!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.
***
## Next
* [Add Subscription Product](./add-subscription-product) - let Superwall observe the purchase Encore makes
# Routine updates
Source: https://docs.encorekit.com/publishers/ios/guides/updating-sdk
How to update the Encore SDK and how its versioning works.
## Overview
The Encore SDK is a **public Swift Package**. Updating is the standard Swift Package Manager flow, with no token or authenticated URL 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 rule set to **Up to Next Major Version** (the Xcode default). Patch and minor updates then arrive through a routine package update, and a major version never lands without you opting in.
> [!NOTE]
>
> Upgrading across a major version? See [Updating to 2.x](./updating-to-2-x) for the step-by-step migration guide.
***
## Update via Xcode
1. In Xcode's left sidebar, expand **Package Dependencies**
2. Find and right-click the **Encore** package (resolved from `https://github.com/EncoreKit/ios-sdk`)
3. Select **Update Package**
Alternatively, select **File → Packages → Update to Latest Package Versions** to update all packages at once.
> [!NOTE]
>
> If your project still points at an old `https://www.github.com/...` URL, update the package **Location** to `https://github.com/EncoreKit/ios-sdk` (Your Project → Package Dependencies → the Encore package → Location column). No token is needed.
***
## Verify the update
After updating, check the package version in Xcode's Package Dependencies to confirm you're on the latest release.
***
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/ios/guides/updating-to-2-x
Step-by-step migration guide for upgrading the Encore iOS 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 a result and never throws.** Errors arrive as values on the result instead of as thrown exceptions.
* **Purchases run through a registered `EncorePurchaseController`.** The SDK never runs purchase code you didn't write.
* **Global handler closures and delegates are retired.** Results are values at the call site; passive observation moves to the `Encore.shared.outcomes` stream.
* **The public API is `@MainActor`.** Results and callbacks always land on the main actor.
***
## Step 1: Update the package
In Xcode, select the Encore package under **Package Dependencies** and change its version requirement to **Up to Next Major Version** from `2.0.0`. In a `Package.swift` manifest:
```swift theme={null}
.package(url: "https://github.com/EncoreKit/ios-sdk", from: "2.0.0")
```
2.0 removes the 1.x legacy surface outright rather than deprecating it, so every call site that needs attention fails to compile. Build the project: the compile errors that appear are your migration worklist, and each one corresponds to a step below. Work through them 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 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 StoreKit and reported it via `onPurchaseComplete`. 2.0 removes the closure, the completion callback, and the built-in StoreKit 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.
Conform a small class to [`EncorePurchaseController`](/publishers/ios/sdk-reference/purchase-controller) and pass it to [`configure(...)`](/publishers/ios/sdk-reference/configure):
```swift RevenueCat 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.productNotFound }
let result = try await Purchases.shared.purchase(product: product)
return result.userCancelled ? .cancelled : .purchased
}
}
Encore.shared.configure(apiKey: "pk_...", purchaseController: AppPurchases())
```
```swift StoreKit 2 theme={null}
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.productNotFound }
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_...", purchaseController: AppPurchases())
```
Return `.purchased` on success, `.cancelled` when the user backs out, and `.pending` for deferred flows such as Ask to Buy; throw for real failures.
> [!NOTE]
>
> The controller registration is build-time wiring, not user state: it survives `reset()`, so logging a user out does not require re-registering.
If your app uses Encore offers without a subscription product, no controller is needed and no purchase is ever attempted. If a product is configured but no controller is registered, the claim completes with `publisher: .notAttempted`, the SDK logs a warning naming the product, and the `sdk_iap_no_purchase_controller` analytics event makes the misconfiguration visible.
***
## Step 3: Update show() call sites
`show()` no longer throws. Errors arrive as `.notPresented(.error(EncoreError))` on the [`PresentationResult`](/publishers/ios/sdk-reference/presentation-result), so `do`/`catch` blocks around it are dead code:
```swift theme={null}
// 1.x
do {
let result = try await Encore.placement("paywall").show()
if case .granted = result { unlock() } else { runOriginalFlow() }
} catch {
runOriginalFlow() // often forgotten, causing a silent hang
}
// 2.0
let result = await Encore.placement("paywall").show()
if result.claim != nil || result.publisher == .purchased { unlock() } else { runOriginalFlow() }
```
Fire-and-forget presentation becomes `show(resume:)`, which delivers **every** outcome (including `.notPresented`) on the main actor:
```swift theme={null}
// 1.x: every error and result discarded
Encore.placement("paywall").show()
// 2.0: every outcome delivered
Encore.placement("paywall").show { result in
if result.claim == nil && result.publisher != .purchased { runOriginalFlow() }
}
```
The public API is now `@MainActor`. Calls from a background queue or a nonisolated helper no longer compile; move them to the main actor. SwiftUI actions, `.task` blocks, and UIKit handlers are already there.
***
## Step 4: Update result handling
1.x modeled the result as a flat enum (`.purchased`, `.granted(...)`, `.notGranted(reason)`), which forced a claim and a purchase to compete for a single winning case. 2.0 splits the result into `.notPresented(reason)` and `.presented(Outcome)`; see [`PresentationResult`](/publishers/ios/sdk-reference/presentation-result) for the full shape.
The record carries **raw facts only**: 2.0 removes the SDK-computed "unlocked" verdict, so your integration decides what a claim means. Most 1.x switches collapse to a one-line check on the facts:
```swift theme={null}
let result = await Encore.placement("paywall").show()
if result.claim != nil || result.publisher == .purchased {
// The user claimed an offer or completed your purchase.
// Read the concrete entitlement from isActive / isActivePublisher.
} else {
result.error.map(log) // presentation failures are values
runOriginalFlow() // dismissed, declined, no offers, control cohort, ...
}
```
`result.claim` surfaces the claimed offer (`campaignId`, `advertiserName`, `transactionId`) whenever the claim funnel reached `.claimed` or `.verified`; read `result.advertiser` directly to distinguish the two. `result.publisher` reports what your purchase code returned.
When the mechanism detail matters, switch on the record:
```swift theme={null}
switch result {
case .presented(let outcome):
analytics.log(outcome.advertiser, outcome.publisher, outcome.dismissal)
case .notPresented(let reason):
analytics.log(reason)
}
```
> [!NOTE]
>
> The 1.x result never carried the entitlement payload correctly across modes, so 2.0 removes it from the result entirely. The granted entitlement is always read from `isActive` / `isActivePublisher`, the authoritative state.
***
## Step 5: Replace global callbacks with the outcomes stream
`onPassthrough`, `EncoreDelegate`, `encoreSheet(onGranted:)`, and the builder and manager `onGranted` / `onNotGranted` callbacks are removed. Handle fallback inline at the call site (Step 4), and move passive observation (analytics, logging, cross-cutting state) to the [`Encore.shared.outcomes`](/publishers/ios/sdk-reference/outcomes) stream:
```swift theme={null}
Task {
for await outcome in Encore.shared.outcomes {
switch outcome {
case .presentation(let placementId, let result):
analytics.log("encore_outcome", placementId, result)
case .strictUnlockVerified:
// Entitlements already refreshed. Re-check isActive / isActivePublisher.
break
}
}
}
```
***
## Removed APIs at a glance
| 1.x surface | 2.0 replacement |
| :- | :- |
| `show() async throws -> PresentationResult` | `show() async -> PresentationResult`; errors arrive as `.notPresented(.error(EncoreError))` |
| Fire-and-forget `show()` | `show(resume:)`, which delivers every outcome on the main actor |
| `onPurchaseRequest` (both overloads) | `EncorePurchaseController` registered via `configure(apiKey:purchaseController:options:)` |
| `onPurchaseComplete` + built-in StoreKit fallback | Removed; your controller owns the purchase, so you already have the result |
| `onPassthrough { }` | No claim and no purchase on the record (`result.claim == nil && result.publisher != .purchased`) handled inline at the call site |
| Builder `.onGranted { }` / `.onNotGranted { }` | `await show()` + the record's raw facts (`claim`, `advertiser`, `publisher`, `dismissal`) |
| `EncoreDelegate`, `entitlementsDelegate`, `encoreSheet(onGranted:)` | `Encore.shared.outcomes` stream + `isActivePublisher` |
| `.purchased` / `.granted(entitlement)` flat cases | `.presented(Outcome)` with independent `advertiser`, `publisher`, `dismissal` fields |
| `.notGranted(reason)` | `.presented(Outcome)` with `outcome.dismissal: DismissReason` |
| `.notGranted(.noOffersAvailable / .unsupportedOS / .experimentControl)` | `.notPresented(.noOffers / .unsupportedOS / .experimentControl)`: these describe a sheet that never appeared |
| `.notGranted(.userTappedOutside)` | Removed with no replacement; no SDK version ever produced it |
| Errors thrown from `show()` | `.notPresented(.error(...) / .notConfigured / .alreadyPresenting)` |
| `configure(apiKey:logLevel:unlock:)` | `configure(apiKey:options:)` or `configure(apiKey:purchaseController:options:)` |
The deprecated typealiases `NotGrantedReason` and `EncorePresentationResult` survive as zero-cost renames that Xcode fix-its resolve.
***
## Behavior changes to be aware of
These compile fine but behave differently at runtime:
* **Errors no longer throw from `show()`.** Old `catch` fallback blocks are dead code; run fallback off `.notPresented` instead.
* **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.** The record says `advertiser: .claimed(...)` immediately (and `result.claim` surfaces it); in-session verification upgrades it to `.verified(...)`, and late completion arrives as `.strictUnlockVerified` on `Encore.shared.outcomes`, surviving process death. Gate concrete access on `isActive` / `isActivePublisher`.
* **Callbacks and resumes always land on the main actor.** 1.x invoked them from arbitrary contexts.
***
## New in 2.0, with no migration required
Existing call sites keep working unchanged. These arrive on top:
* **A claim-only reward surface.** A placement can select [`.useCase(.rewardUsers)`](/publishers/ios/sdk-reference/placement#use-cases) to present *after* the user has already done something worth celebrating, such as a completed purchase, a milestone, or a streak. It never runs a purchase and never falls back to the paywall sheet. Placements that omit `useCase(_:)` keep the default `.reduceChurn` surface.
* **Per-presentation copy overrides.** `headline(_:)` and `subheadline(_:)` replace the sheet's shipped copy for one presentation. Encore never translates the string you pass, so localization and pluralization stay yours. The copy Encore resolves for your app is translated for you; see [Localization](/publishers/concepts/localization).
* **A runtime claim gate.** [`Encore.shared.isClaimEnabled`](/publishers/ios/sdk-reference/is-claim-enabled) dims the claim CTA and stops it responding to taps, leaving the rest of the presentation intact.
* **No more wedged presentations.** A dead flow can no longer brick presentation with `.alreadyPresenting`: every flow resolves on a real event.
* **Durable strict-mode claims.** A strict-mode claim that ends unverified persists across launches until verification completes.
```swift theme={null}
let result = await Encore.shared.placement("streak_complete")
.useCase(.rewardUsers)
.headline("That's three days in a row staying informed 🔥")
.subheadline("Here's a little thank you from us")
.show()
```
***
## 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 no-claim, no-purchase branch (`result.claim == nil && result.publisher != .purchased`), not a `catch` block.
4. 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).
# Create a Promotional Offer
Source: https://docs.encorekit.com/publishers/ios/platform-setup/create-promotional-offer
Create a promotional offer in App Store Connect and link it in Encore so churn-moment offers carry a discounted or free period.
## Overview
Promotional offers let you give existing or lapsed subscribers a discounted or free period when they accept an Encore offer at a churn moment. You create the offer in App Store Connect, link it through your [Encore dashboard](https://dashboard.encorekit.com), and apply it in your purchase controller when it runs the purchase.
> [!NOTE]
>
> A promotional offer is a targeted discount or free period you extend to a specific existing or lapsed subscriber at a moment you choose.
***
## Prerequisites
* An auto-renewable subscription product configured in Encore (see [App Store Subscription Product](./subscription-product): connect your App Store Connect catalog and pick the product)
* Access to App Store Connect with the Admin or App Manager role
***
## Step 1: Create the promotional offer
**1. Open your subscription**
Go to [App Store Connect](https://appstoreconnect.apple.com) → **Apps** → your app → **Subscriptions**. Select the subscription product you want to add a promotional offer to.
**2. Add a promotional offer**
Scroll down to the **Subscription Prices** section and click the **"+"** button. Then click **Create Promotional Offer**
**3. Configure the offer**
Fill in the following fields:
| Field | Description | Example |
| - | - | - |
| **Reference Name** | Internal label (not shown to users) | `Encore 3 Month Free` |
| **Promotional Offer Identifier** | Unique identifier you'll enter in the Encore dashboard | `com.yourapp.promo.3m.free` |
| **Offer Type** | Free, Pay As You Go, or Pay Up Front | `Free` |
| **Duration** | How long the offer lasts | `2 Months` |
> [!TIP]
>
> For churn moments, a **Free** period of a few months tends to perform best. This gives a churning user a compelling reason to stay without requiring immediate payment.
**4. Save**
Click **Create** to save the promotional offer. The **Promotional Offer Identifier** you entered above is the value you'll enter as the **Promotional Offer ID** in the Encore dashboard.
***
## Step 2: Generate an In-App Purchase key
Promotional offers require a server-generated signature. If you're using **StoreKit** directly (not a third-party manager), the signature is generated with a separate **In-App Purchase key**, which you upload to Encore.
> [!WARNING]
>
> **This is a different key from the one you uploaded to connect your store catalog.** The App Store Connect API key from [App Store Subscription Product](./subscription-product) (Key ID + Issuer ID + .p8, **App Manager** role) is **read-only for product setup and pricing display**: Encore uses it to sync your subscription catalog and show your products. It does **not** sign promotional offers.
>
> Promotional-offer signing uses a dedicated **In-App Purchase key**, generated on a different App Store Connect page (below) and uploaded separately under **Entitlements → Promotional Offer Setup**. Keep the two distinct: the catalog-sync key never signs offers, and the In-App Purchase key is only needed when you sign offers with StoreKit directly.
**1. Open the keys page**
Go to [App Store Connect → Users and Access → Integrations → In-App Purchase](https://appstoreconnect.apple.com/access/integrations/api/subs).
**2. Generate a key**
Click **"Generate In-App Purchase Key"** and give it a descriptive name (e.g., `Encore Signing Key`).
**3. Copy the Key ID**
Copy the **Key ID** shown in the table (e.g., `WHJ3V7RXNW`). You'll need this in the Encore dashboard.
**4. Download the .p8 file**
Click **Download** to save the `.p8` private key file. You can only download this file once, so store it securely.
> [!WARNING]
>
> The `.p8` key file can only be downloaded once. If you lose it, you'll need to generate a new key.
> [!NOTE]
>
> If you use a third-party subscription manager (RevenueCat, Adapty), it handles offer signing through its own SDK. You do **not** need to upload the `.p8` key to Encore, but you still need the promotional offer created in App Store Connect.
***
## Step 3: Link in the Encore Dashboard
1. Go to your app in the [Encore Dashboard](https://dashboard.encorekit.com)
2. Navigate to **Entitlements** → **Promotional Offer Setup**
3. Enter the **Promotional Offer ID** (the Promotional Offer Identifier from Step 1)
4. If using StoreKit directly, also provide your **Key ID** and upload the **.p8 file**
5. Select your **Subscription Manager** and follow the integration instructions shown
***
## Naming convention
Use a consistent naming pattern for your promotional offer IDs:
```
{bundle_id}.promo.{duration}.{type}
```
| Example | Meaning |
| - | - |
| `com.yourapp.promo.3m.free` | 3 months free |
| `com.yourapp.promo.1m.free` | 1 month free |
| `com.yourapp.promo.6m.payasyougo` | 6 months at a reduced price |
***
## Handling the offer in code
`PurchaseRequest.promoOfferId` is reserved and is always `nil` on iOS SDK 2.0, so Encore does not drive promotional-offer selection. Your [`EncorePurchaseController`](../sdk-reference/purchase-controller) decides when a promotional offer applies and signs it with your own billing code. How you apply it depends on your subscription manager:
> [!NOTE]
>
> Encore-driven promotional offers are not yet available in the iOS SDK. Until they are, keep the promotional offer id in your own code.
> [tab] StoreKit
>
> With StoreKit 2, applying a promotional offer requires a server-generated signature: sign the offer with the In-App Purchase key from [Step 2](#step-2-generate-an-in-app-purchase-key), then pass the signed offer to `product.purchase(options:)` via `Product.PurchaseOption.promotionalOffer`. See Apple's [Implementing promotional offers](https://developer.apple.com/documentation/storekit/implementing-promotional-offers-in-your-app) for the signing flow.
>
> ```swift theme={null}
> final class AppPurchases: EncorePurchaseController {
> func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult {
> guard let product = try await Product.products(for: [request.productId]).first else {
> throw PurchaseError.notFound
> }
> // Your own code decides when a promotional offer applies and fetches
> // the signature for promoOfferId from your signing endpoint.
> let options: Set = [
> .promotionalOffer(
> offerID: promoOfferId,
> keyID: keyID, nonce: nonce, signature: signature, timestamp: timestamp
> )
> ]
> switch try await product.purchase(options: options) {
> 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
> }
> }
> }
> ```
> [tab] RevenueCat
>
> Manually check for the promotional offer, sign it through RevenueCat, and fall back to a standard purchase if the user isn't eligible.
>
> ```swift theme={null}
> final class AppPurchases: EncorePurchaseController {
> func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult {
> guard let product = try await Purchases.shared.products([request.productId]).first else {
> throw PurchaseError.notFound
> }
> // promoOfferId is your own value; Encore does not supply it.
> if let promoDiscount = product.discounts.first(where: { $0.offerIdentifier == promoOfferId }) {
> do {
> let offer = try await Purchases.shared.promotionalOffer(
> forProductDiscount: promoDiscount, product: product
> )
> let result = try await Purchases.shared.purchase(product: product, promotionalOffer: offer)
> return result.userCancelled ? .cancelled : .purchased
> } catch {
> // Promo failed (ineligible, network error, etc.): fall back to standard purchase
> let result = try await Purchases.shared.purchase(product: product)
> return result.userCancelled ? .cancelled : .purchased
> }
> } else {
> let result = try await Purchases.shared.purchase(product: product)
> return result.userCancelled ? .cancelled : .purchased
> }
> }
> }
> ```
>
> > [!WARNING]
> >
> > Your local StoreKit configuration file must be synced with App Store Connect. Promotional offers will not work if it is out of sync.
> [tab] Adapty
>
> Adapty automatically presents the promotional offer if the user is eligible (when configured correctly in the Adapty dashboard). Falls back to a standard purchase with an introductory offer.
>
> ```swift theme={null}
> final class AppPurchases: EncorePurchaseController {
> func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult {
> let paywall = try await Adapty.getPaywall(placementId: "YOUR_PAYWALL_PLACEMENT_ID")
> 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
> }
> }
> ```
>
> > [!WARNING]
> >
> > Adapty does not fall back to StoreKit: products and offers must exist in Adapty. Sync products in the Adapty dashboard before use, and configure the promotional offer there (it does not sync from App Store Connect automatically).
See [EncorePurchaseController](../sdk-reference/purchase-controller) for the full controller contract.
***
## Next steps
* [App Store Subscription Product](./subscription-product): the base subscription product the offer discounts.
* [Reduce Churn](/publishers/use-cases/churn-intervention): the use case these offers serve.
# App Store Server Notifications
Source: https://docs.encorekit.com/publishers/ios/platform-setup/server-notifications
Point Apple's subscription lifecycle webhooks at Encore so your dashboard can track subscription events and measure offer impact.
## Overview
Encore uses Apple's **App Store Server Notifications** (webhooks) to track subscription lifecycle events: trial starts, renewals, expirations, and refunds. 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 URL in App Store Connect (Recommended)
>
> Point App Store Connect directly at Encore's webhook endpoint. This is the most reliable integration: Encore receives notifications directly from Apple with no intermediary.
>
> **1. Open App Store Connect**
>
> Go to [appstoreconnect.apple.com](https://appstoreconnect.apple.com) and navigate to **Your App → General → App Information**.
>
> **2. Find App Store Server Notifications**
>
> Scroll down to the **App Store Server Notifications** section.
>
> **3. Set Production Server URL**
>
> Enter the following URL as the **Production Server URL**:
>
> ```
> https://api.encorekit.com/encore/webhooks/apple
> ```
>
> **4. Set Sandbox Server URL**
>
> Enter the same URL as the **Sandbox Server URL**:
>
> ```
> https://api.encorekit.com/encore/webhooks/apple
> ```
>
> > [!TIP]
> >
> > Setting both Production and Sandbox URLs ensures Encore tracks subscription events during development testing as well as in production.
>
> **5. Save**
>
> Click **Save** at the top of the page.
>
> **6. Confirm the webhook is wired**
>
> Back in the [Encore Dashboard](https://dashboard.encorekit.com), open your app's **Analytics** (or **Integration Progress → Configure Analytics**) view. Once Apple delivers the first notification, the **App Store Server Notifications** status flips to **Connected** and a "last received" timestamp appears.
>
> To force an event immediately, complete a sandbox purchase (or trigger a renewal or refund) for a test user; the notification typically lands within a minute or two. If nothing appears after a few minutes, re-check the Production and Sandbox URLs in App Store Connect.
> [tab] Forward from Your Server
>
> If you already have an App Store Server Notifications URL configured and don't want to change it, forward each notification to Encore from your existing webhook handler. Your current flow is preserved; you just add a single forwarding call.
>
> ```javascript theme={null}
> app.post('/webhooks/apple', async (req, res) => {
> // Forward the raw signed payload to Encore
> await fetch('https://api.encorekit.com/encore/webhooks/apple', {
> method: 'POST',
> headers: { 'Content-Type': 'application/json' },
> body: JSON.stringify(req.body),
> });
>
> // Continue with your existing logic...
> res.sendStatus(200);
> });
> ```
>
> > [!NOTE]
> >
> > **How Encore attributes the notification to your app:** Apple's notification is a signed JWS that Encore verifies against the Apple Root CA - G3 certificate chain, then reads the **bundle ID** embedded in the verified payload. That bundle ID is matched to your registered app, so no shared secret or per-app token is needed. Just forward the raw request body **unmodified** (re-serializing or re-signing it will break verification).
> >
> > If you operate multiple apps under one forwarding handler, you can optionally disambiguate by appending your Encore app ID as a query param: `…/encore/webhooks/apple?app=`.
> [!NOTE]
>
> **Using a third-party subscription manager?** Its webhook carries your subscription events instead: see [Superwall](/publishers/ios/guides/managers/superwall/configure-analytics), [RevenueCat](/publishers/ios/guides/managers/revenuecat/configure-analytics), or [Adapty](/publishers/ios/guides/managers/adapty/configure-analytics).
***
## Need help?
If you have questions about configuring App Store Server Notifications or the forwarding setup, contact us at [admin@encorekit.com](mailto:admin@encorekit.com).
# App Store Subscription Product
Source: https://docs.encorekit.com/publishers/ios/platform-setup/subscription-product
Connect your App Store Connect catalog and pick, or create, the subscription product Encore offers.
## Overview
When a user accepts an offer, Encore starts a real App Store subscription purchase of the product you configure here, and the App Store owns entitlement state from then on. This page is the store-console half of that setup: connect your App Store Connect catalog so Encore can auto-sync your subscriptions, then pick the product from a dropdown (or let Encore create one for you).
> [!NOTE]
>
> Connect your App Store Connect API key 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 App Store Connect catalog (recommended)
Encore reads your subscription catalog and pricing through an **App Store Connect API key**. Generating the key takes three values: a **Key ID**, an **Issuer ID**, and a **.p8** private key file. You upload them in the **Entitlements** phase of the [Integration Progress](/quickstart#integration-progress) tracker (the step labelled **Connect store**).
**1. Link your App Store ID first**
Encore needs your app's numeric **App Store ID** before it will accept a credential. If you added your app by pasting its App Store URL during onboarding, this is already set. Otherwise, paste your App Store URL (e.g. `https://apps.apple.com/us/app/.../id123456789`) or the numeric ID when prompted.
**2. Generate an API key in App Store Connect**
Go to [App Store Connect → Users and Access → Integrations](https://appstoreconnect.apple.com/access/users) and generate a new API key.
Select the **App Manager** role with **single-app scope**, limited to the one app you're connecting. Encore only needs to read and manage that app's subscription catalog, so don't grant broader access than necessary.
**3. Copy the Key ID and Issuer ID**
After generating the key, copy:
* The **Key ID**: a 10-character identifier (e.g. `ABCD1234EF`).
* The **Issuer ID**: a UUID shown at the top of the Integrations page (e.g. `69a6de70-...`).
**4. Download the .p8 file**
Download the **.p8** private key file. Apple lets you download it **only once**, so store it securely.
**5. Upload to Encore**
In your app's **Entitlements** step, enter the **Key ID** and **Issuer ID**, choose the **.p8** file, and click **Upload and verify**. Encore verifies the key with Apple, then pulls your subscription catalog automatically and shows how many subscriptions and promotional offers it found. You can re-run the sync anytime with **Sync now**.
**6. Pick your subscription product**
Once the catalog syncs, the **Subscription product** section shows a picker. Choose the product that gates entitlements. Encore reads its price and intro-offer details automatically, so there's nothing else to type.
**7. 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 App Store Connect for you**. Review the auto-filled fields, confirm, and Encore writes the product as a draft.
> [!NOTE]
>
> Newly created products land in your App Store Connect catalog as a **draft**. Review the auto-filled display name, price tier, and introductory offer, then promote to **ACTIVE** before users can purchase.
***
## 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 App Store Connect, then enter its ID in the Encore Dashboard.
**1. Create the subscription in App Store Connect**
Go to [appstoreconnect.apple.com](https://appstoreconnect.apple.com) → **Your App → Subscriptions**.
| Field | Value |
| - | - |
| **Product Type** | Auto-renewable subscription |
| **Reference Name** | Encore Annual 1 Month Trial |
| **Subscription Duration** | 1 Year |
| **Introductory Offer** | Free Trial, 1 Month |
| **Product ID** | `com.yourapp.encore.annual.1m.trial` |
Create a subscription group if you don't have one, add the subscription, set its duration and availability, then add a **Free** introductory offer. Save and submit for review.
> [!TIP]
>
> Subscriptions can be approved independently of app updates.
**2. Enter the Product ID in Encore**
In your app's **Entitlements** step, type the **Product ID** (e.g. `com.yourapp.encore.annual.1m.trial`) into the fallback input and save.
***
## How Encore stores your credential
> [!NOTE]
>
> Uploaded credentials are **encrypted at rest**. The **.p8** is encrypted with a domain-separated master key and is only ever decrypted inside Encore's credential-accessor, used to refresh your catalog and to create products you explicitly ask for. You can **remove** the credential at any time from the same Entitlements step.
>
> This catalog credential is **separate** from the In-App Purchase signing key used for [promotional offers](/publishers/ios/platform-setup/create-promotional-offer): the catalog key never signs offers.
***
## Next step
> [card] [App Store Server Notifications](/publishers/ios/platform-setup/server-notifications)
>
> Forward Apple's subscription lifecycle events to Encore so your dashboard can measure offer impact.
# Configure the SDK
Source: https://docs.encorekit.com/publishers/ios/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
Edit your main `App` struct to configure Encore at launch:
```swift theme={null}
import SwiftUI
import Encore
@main
struct YourApp: App {
init() {
// Configure Encore with your API key
Encore.shared.configure(apiKey: "pk_live_your_key")
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
```
This configures a shared instance of `Encore`, the primary class for interacting with the SDK's API. Make sure to replace `pk_live_your_key` with your publishable API key.
***
## 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.
```swift theme={null}
Encore.shared.configure(
apiKey: "pk_live_your_key",
purchaseController: AppPurchases()
)
```
See [Presenting Offers](./present-offers#handle-purchases) for a StoreKit 2 controller implementation, and [EncorePurchaseController](../sdk-reference/purchase-controller) for RevenueCat, Adapty, and custom variants. Apps that use Encore offers without anything to unlock can skip the controller: with no product configured, no purchase is ever attempted.
> [!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 `pk_live_…` (or the **Test** key `pk_test_…` for non-production builds).
***
## Options: Logging and Unlock Mode
`configure(apiKey:purchaseController:options:)` accepts an `Options` value for runtime behavior:
```swift theme={null}
Encore.shared.configure(
apiKey: "pk_live_your_key",
options: .init(
logLevel: .info, // .none (default), .error, .warn, .info, .debug
unlock: .optimistic // .optimistic (default) or .strict
)
)
```
Both options have safe defaults (`logLevel: .none`, `unlock: .optimistic`). See [`configure()`](../sdk-reference/configure#options) for the full contract and [EntitlementScope](../sdk-reference/entitlement-scope#two-phase-entitlements-provisional-vs-verified) for the two-phase grant model.
***
## 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 handle purchase results
# Configure Analytics
Source: https://docs.encorekit.com/publishers/ios/quickstart/configure-analytics
Forward App Store 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 refunds. Until Apple's **App Store Server Notifications** reach Encore, the Analytics section of your dashboard shows no data.
> [!NOTE]
>
> **Using a third-party subscription manager?** It can carry these events for you: see [Superwall](/publishers/ios/guides/managers/superwall/configure-analytics), [RevenueCat](/publishers/ios/guides/managers/revenuecat/configure-analytics), or [Adapty](/publishers/ios/guides/managers/adapty/configure-analytics).
Wiring them up is console work, done once in App Store Connect (or your own webhook handler):
> [card] [App Store Server Notifications](/publishers/ios/platform-setup/server-notifications)
>
> Set Encore's webhook URL in App Store Connect, 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/ios/quickstart/install
Add the Encore Swift SDK to your iOS project via Swift Package Manager.
## Overview
The Encore iOS SDK lets your app present premium brand offers, real perks funded by brands, at the moments you choose. It is distributed as a **public Swift Package**: no access token or authentication is required, and you add it straight from GitHub via Swift Package Manager.
The repository URL is:
```bash theme={null}
https://github.com/EncoreKit/ios-sdk
```
***
## Requirements
| Requirement | Minimum |
| - | - |
| **iOS deployment target** | iOS 15.0+ |
| **Xcode** | 15.3+ (Swift 5.10+) |
> [!NOTE]
>
> The SDK installs and runs on iOS 15+. The offer sheet UI is built with SwiftUI sheets and renders on **iOS 17+**. On iOS 15–16, calls to `placement(_:).show()` resolve immediately with `.notPresented(.unsupportedOS)` instead of presenting UI, so your fallback branch still runs and the user is never blocked.
***
## Install via Swift Package Manager
Swift Package Manager is Apple's official dependency manager, integrated into Xcode.
### Option A: Add in Xcode
**1. Open Add Package Dependencies**
In **Xcode**, select **File ▸ Add Package Dependencies…**
**2. Paste the repository URL**
Paste the public repository URL into the search field:
```bash theme={null}
https://github.com/EncoreKit/ios-sdk
```
Press Return. The package resolves automatically.
**3. Set the dependency rule**
Set **Dependency Rule** to **Up to Next Major Version** with a lower bound of **2.4.0**, then click **Add Package**. Trigger components and `Encore.claim` need 2.4.0 or later.
**4. Add to your target**
Ensure the **Encore** library is added to your app's target, then click **Add Package**.
### Option B: `Package.swift`
If you manage dependencies in a `Package.swift` manifest, add Encore to your `dependencies` and to your target:
```swift theme={null}
dependencies: [
.package(url: "https://github.com/EncoreKit/ios-sdk", from: "2.4.0"),
],
targets: [
.target(
name: "YourApp",
dependencies: [
.product(name: "Encore", package: "ios-sdk"),
]
),
]
```
### Verify Installation
You should now be able to import the SDK:
```swift theme={null}
import Encore
```
**Installation complete.**
***
## Next Steps
Now that the SDK is installed, continue with the integration:
* **[Configure the SDK](/publishers/ios/quickstart/configure)** - Set up your API key and initialize Encore
* **[Identify Users](/publishers/ios/quickstart/user-management)** - Learn how to identify users for offer tracking
For advanced features and complete API documentation, see the [SDK Reference](/publishers/ios/sdk-reference/overview).
***
## Already Installed?
If you've already installed the SDK and need to update to a newer version, see [Updating the SDK](/publishers/ios/guides/updating-sdk).
# Presenting Offers
Source: https://docs.encorekit.com/publishers/ios/quickstart/present-offers
Present Encore's reward sheet at a moment your user just earned, or a Reduce Churn sheet in a cancel flow, and branch on the result.
## 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 Offers
The facade is `@MainActor`, so call `show()` from a main-actor context: a SwiftUI button action, a `.task`, or a UIKit handler. `show()` never throws and always resolves; a SwiftUI `Button` action is synchronous, so wrap the `await` in a `Task`:
> [tab] Reward Users
>
> ```swift theme={null}
> @MainActor
> func celebrateStreak() {
> Task {
> let result = await Encore.shared.placement("streak_day_7")
> .useCase(.rewardUsers)
> .headline("Nice work, Sam!") // optional; falls back to the copy resolved for your app
> .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.
> }
> }
> ```
>
> Select `.useCase(.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
>
> ```swift theme={null}
> Button("Cancel Subscription") {
> Task {
> let result = await Encore.shared.placement("cancellation_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.
> } else {
> result.error.map(log) // presentation failures are values
> proceedWithCancellation() // dismissed, declined, nothing appeared, ...
> }
> }
> }
> ```
>
> A placement that omits `useCase(_:)` is a Reduce Churn placement. Always run your original flow in the non-success branch. Every presentation resolves exactly once, so this branch is guaranteed to run whenever the user should continue: dismissals, no offers, control cohorts, and errors all land here.
>
> If Superwall or RevenueCat owns your paywall, the trigger point changes: see [Superwall](/publishers/ios/guides/managers/superwall/present-offers) or [RevenueCat](/publishers/ios/guides/managers/revenuecat/present-offers).
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
When the call site can't await, `show(resume:)` delivers every outcome (including `.notPresented`) on the main actor:
```swift theme={null}
Encore.shared.placement("streak_day_7").useCase(.rewardUsers).show { result in
if let claim = result.claim {
// The user claimed an offer.
}
}
```
> [!NOTE]
>
> `show()` never throws. Failures arrive as `.notPresented(.error(EncoreError))` on the [`PresentationResult`](../sdk-reference/presentation-result), so there is no `catch` block to forget.
***
## 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.
When a user accepts an offer that requires a purchase, the SDK calls the [`EncorePurchaseController`](../sdk-reference/purchase-controller) you registered at configure time. It performs the purchase through your billing code (StoreKit 2, RevenueCat, Adapty, or your own) and reports what happened:
```swift theme={null}
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() }
return .purchased
case .userCancelled: return .cancelled
case .pending: return .pending
@unknown default: return .cancelled
}
}
}
Encore.shared.configure(apiKey: "pk_live_your_key", purchaseController: AppPurchases())
```
> [!TIP]
>
> The example above uses StoreKit 2. See [EncorePurchaseController](../sdk-reference/purchase-controller) for RevenueCat, Adapty, and custom subscription manager implementations.
> [!NOTE]
>
> If your app uses Encore offers without a subscription product, no controller is needed and no purchase is ever attempted. If a product is configured but no controller is registered, the SDK never attempts a purchase: the claim completes with `publisher: .notAttempted` and the `sdk_iap_no_purchase_controller` analytics event flags the misconfiguration.
***
## Observe Outcomes Passively
Anything that wants to watch results without owning a call site (analytics forwarding, a debug overlay, cross-screen state) consumes the [`outcomes`](../sdk-reference/outcomes) stream:
```swift theme={null}
.task {
for await outcome in Encore.shared.outcomes {
switch outcome {
case .presentation(let placementId, let result):
analytics.log("encore_outcome", placementId, "\(result)")
case .strictUnlockVerified:
// Entitlements already refreshed; re-check isActive / isActivePublisher.
break
}
}
}
```
***
## What a Grant Looks Like
The result of `show()` records the raw facts of the flow; read the granted entitlement itself from [`isActive`](../sdk-reference/is-active) / [`isActivePublisher`](../sdk-reference/is-active-publisher), the authoritative state. See [Two-phase entitlements in EntitlementScope](../sdk-reference/entitlement-scope#two-phase-entitlements-provisional-vs-verified) for how provisional and verified grants differ and which scope to gate on.
***
## 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: pick the App Store subscription Encore purchases when a user accepts an offer
# User Management
Source: https://docs.encorekit.com/publishers/ios/quickstart/user-management
Identifying users, setting attributes, and managing identity in your iOS 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 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 entitlement data.
***
## Identified Users
If you use your own user management system, call `identify(userId:)` when you have a user's identity:
```swift theme={null}
// After retrieving a user's ID from login or account creation
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
***
## Resetting User Identity
When a user logs out, call `reset()`:
```swift 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 entitlement data
* Clear all user attributes
***
## 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.
```swift theme={null}
let attributes = UserAttributes(
countryCode: "US",
age: 25,
custom: ["signupSource": "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` struct. Every value is a string except `age`, a whole number of years; `dateOfBirth` is a `YYYY-MM-DD` string. Use the `custom` dictionary, which takes strings, for app-specific fields:
```swift theme={null}
Encore.shared.setUserAttributes(
UserAttributes(
email: "user@example.com",
subscriptionTier: "premium",
monthsSubscribed: "6",
custom: [
"cancelReason": "too_expensive"
]
)
)
```
You can also set user attributes when identifying:
```swift 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.
> [!TIP]
>
> See the SDK Reference for details: [identify()](../sdk-reference/identify), [setUserAttributes()](../sdk-reference/set-user-attributes), and the full [UserAttributes](../sdk-reference/user-attributes) field list and formats.
***
## Implementation Examples
### SwiftUI with Login
```swift theme={null}
import SwiftUI
import Encore
@main
struct YourApp: App {
@StateObject private var authManager = AuthManager()
init() {
Encore.shared.configure(apiKey: "pk_live_your_key")
}
var body: some Scene {
WindowGroup {
MainAppView()
.onAppear {
if authManager.isAuthenticated {
Encore.shared.identify(
userId: authManager.userId,
attributes: UserAttributes(
email: authManager.email,
subscriptionTier: authManager.tier
)
)
}
}
}
}
}
struct SettingsView: View {
@EnvironmentObject var authManager: AuthManager
var body: some View {
Button("Log Out") {
Encore.shared.reset()
authManager.logout()
}
}
}
```
### UIKit with Login
```swift theme={null}
class LoginViewController: UIViewController {
func handleSuccessfulLogin(user: User) {
Encore.shared.identify(
userId: user.id,
attributes: UserAttributes(
email: user.email,
subscriptionTier: user.subscriptionTier
)
)
navigateToMainApp()
}
}
class SettingsViewController: UIViewController {
func handleLogout() {
Encore.shared.reset()
authManager.logout()
navigateToLogin()
}
}
```
### Apps Without Login
If your app doesn't require users to log in, you don't need to do anything special:
```swift theme={null}
@main
struct YourApp: App {
init() {
Encore.shared.configure(apiKey: "pk_live_your_key")
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
// You can still set attributes for anonymous users
Button("Cancel Subscription") {
Encore.shared.setUserAttributes(
UserAttributes(
custom: ["cancelReason": "too_expensive"]
)
)
Encore.placement().show { result in
if result.claim == nil && result.publisher != .purchased {
proceedWithCancellation()
}
}
}
```
***
## 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 an App Store subscription product and connect it to Encore
# clearLanguage()
Source: https://docs.encorekit.com/publishers/ios/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 iOS SDK 2.3.0. React Native and Flutter forward it from the release that pins native 2.3.0.
## Signature
```swift theme={null}
public func 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:
```swift theme={null}
func languageChanged(to code: String?) {
if let code {
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/ios/sdk-reference/configure
Initialize the Encore SDK with your public API key
Configures the shared Encore instance for use throughout your app. This must be called once, typically in your `AppDelegate` or SwiftUI `App` initializer, before using any other SDK methods.
> [!WARNING]
>
> Call `configure()` before using any other SDK methods. Failure to do so makes `show()` resolve with `.notPresented(.notConfigured)` and other APIs report `EncoreError.integration(.notConfigured)`.
## Signature
```swift theme={null}
@MainActor
public func configure(
apiKey: String,
purchaseController: EncorePurchaseController? = nil,
options: Encore.Options = .init()
)
```
`Options` bundles the SDK's runtime settings:
```swift theme={null}
extension Encore {
public struct Options: Sendable {
public var logLevel: LogLevel // default .none
public var unlock: UnlockMode // default .optimistic
public init(logLevel: LogLevel = .none, unlock: UnlockMode = .optimistic)
}
}
```
## Parameters
| Name | Type | Default | Description |
| - | - | - | - |
| `apiKey` | `String` | - | Your Live Key (`pk_live_…`) or Test Key (`pk_test_…`) from the Encore Dashboard |
| `purchaseController` | [`EncorePurchaseController?`](./purchase-controller) | `nil` | The controller Encore offers purchase through. Required if your app sells a product through Encore offers; with no controller, the SDK never attempts a purchase. |
| `options` | [`Encore.Options`](#options) | `.init()` | Runtime options: log verbosity and unlock mode |
> [!WARNING]
>
> The SDK has no built-in billing. If a subscription product is configured for your app but no controller is registered, the claim completes with `publisher: .notAttempted`, a warning is logged naming the product, and the `sdk_iap_no_purchase_controller` analytics event is emitted. 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.
### Options
| Field | Type | Default | Description |
| - | - | - | - |
| `logLevel` | [`Encore.LogLevel`](#log-levels) | `.none` | Logging verbosity |
| `unlock` | [`UnlockMode`](#unlock-mode) | `.optimistic` | When entitlements are granted after an offer flow |
### Unlock mode
`UnlockMode` controls *when* the SDK grants an entitlement after the user returns from an offer:
```swift theme={null}
public enum UnlockMode: Sendable {
case optimistic // default: grant immediately on return from Safari
case strict // wait for advertiser postback verification before granting
}
```
| Mode | Behavior | Use when |
| - | - | - |
| `.optimistic` (default) | Grants the moment the user returns to the app. This is the **provisional** grant: instant UX, later confirmed (or revoked) by the backend. | You want the snappiest unlock and gate reversible UX on the `.all` scope (see [EntitlementScope](./entitlement-scope)). |
| `.strict` | Withholds the grant until the advertiser's postback verifies the conversion. | You only ever want verified grants and can tolerate a short delay before the reward appears. |
```swift theme={null}
Encore.shared.configure(
apiKey: "pk_live_",
options: .init(logLevel: .info, unlock: .strict)
)
```
### Log levels
```swift theme={null}
extension Encore {
public enum LogLevel: Int, Comparable, Sendable {
case none = 0 // No logging (recommended for production)
case error = 1 // Only errors
case warn = 2 // Warnings and errors
case info = 3 // Milestones, warnings, and errors
case debug = 4 // 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
```swift theme={null}
import Encore
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
Encore.shared.configure(apiKey: "pk_live_your_key")
return true
}
```
### With a purchase controller
If your app sells a product through Encore offers, register your [`EncorePurchaseController`](./purchase-controller) at configure time so purchases run through your billing code:
```swift theme={null}
Encore.shared.configure(
apiKey: "pk_live_your_key",
purchaseController: AppPurchases()
)
```
### SwiftUI
```swift theme={null}
@main
struct YourApp: App {
init() {
Encore.shared.configure(
apiKey: "pk_live_your_key",
purchaseController: AppPurchases()
)
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
```
### Development builds
Pair the test key with `logLevel: .debug` so development builds serve the demo catalog and log verbosely, while production builds keep the live key and stay silent:
```swift theme={null}
#if DEBUG
Encore.shared.configure(
apiKey: "pk_test_your_key", // Demo offers
purchaseController: AppPurchases(),
options: .init(logLevel: .debug) // Verbose SDK logs
)
#else
Encore.shared.configure(
apiKey: "pk_live_your_key",
purchaseController: AppPurchases()
)
#endif
```
# DismissReason
Source: https://docs.encorekit.com/publishers/ios/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(.error(EncoreError))`, never here.
`DismissReason` is a `String`-backed enum. The raw values are the analytics wire values: the same string lands in `decline_reason` on `sdk_offer_sheet_dismissed`, unmapped.
## Definition
```swift theme={null}
public enum DismissReason: String, CaseIterable, Equatable, Sendable {
case userTappedClose = "close_button"
case userSwipedDown = "swipe_dismiss"
case userCancelled = "user_cancelled"
case lastOfferDeclined = "last_offer_declined"
case dismissed = "dismissed"
case cooldown = "provisional_cooldown" // not produced since 2.3.0
case flowCompleted = "flow_completed"
case interrupted = "interrupted"
// Emission-only cases (never carried on Outcome.dismissal):
case offerClaimed = "offer_claimed"
case appBackgrounded = "app_backgrounded"
case appTerminated = "app_terminated"
}
```
## Cases
| Case | Description |
| - | - |
| `.userTappedClose` | User tapped the close / "No thanks" button on the sheet. |
| `.userSwipedDown` | User swiped down to dismiss the sheet. |
| `.userCancelled` | User cancelled mid-flow. |
| `.lastOfferDeclined` | Retained for analytics wire compatibility. The SDK currently emits it only when a strict-mode claim ends with no transaction id to verify. |
| `.dismissed` | Generic dismissal when the specific gesture is unknown. |
| `.cooldown` | Not produced since 2.3.0; kept for source and binary compatibility. Before 2.3.0 it meant a claim refused with an HTTP 409 cross-offer provisional cooldown, which the server doesn't send. From 2.3.0 a refused claim is an ordinary claim error and the sheet stays open, except an offer the user already completed: the sheet drops it and, when it was the last one, closes with `.flowCompleted`. |
| `.flowCompleted` | The flow finished on its own and the SDK closed the sheet. |
| `.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; 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`, `.unsupportedOS`, `.experimentControl`, `.notConfigured`, `.alreadyPresenting`, `.useCaseUnavailable`, `.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.
```swift theme={null}
let result = await Encore.shared.placement("cancel_flow").show()
if result.claim != nil || result.publisher == .purchased {
// Claimed or purchased: continue the unlocked path.
} else {
if let dismissal = result.dismissal {
analytics.track("offer_dismissed", ["reason": dismissal.rawValue])
}
// In every case, let the user continue.
proceedWithCancellation()
}
```
## Related Types
* [PresentationResult](./presentation-result), the record `dismissal` is one axis of.
* [Errors](./errors), genuine failures carried as values on `.notPresented(.error(...))`.
# EntitlementScope
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/entitlement-scope
Control which entitlements to check, and understand provisional vs verified grants
## Overview
`EntitlementScope` determines which set of entitlements [`isActive()`](./is-active) inspects. It exists because Encore grants entitlements in **two phases**: a fast provisional grant for instant UX, followed by a backend-verified grant for correctness.
## Definition
```swift theme={null}
public enum EntitlementScope: Sendable {
case verified
case all
}
```
## Two-phase entitlements (provisional vs verified)
When a user completes an offer, the entitlement doesn't appear all at once:
1. **Provisional**: granted immediately so the user sees their reward without waiting. With the default [`UnlockMode.optimistic`](./configure#unlock-mode), this happens the moment the user returns from the offer flow. **A provisional grant can later be revoked** if the backend can't verify the underlying transaction (e.g. the purchase was refunded, fraudulent, or never confirmed).
2. **Verified**: granted once the backend confirms the transaction (via the App Store Server Notification webhook). A verified grant is durable.
### How each scope reads the two phases
| Scope | What it inspects | Returns `true` for a provisional grant? |
| - | - | - |
| `.all` (default) | The merged set of everything currently granted to the user, provisional **and** verified. Broadest and fastest. | Yes |
| `.verified` | The provisional set **or** the verified set, triggering a smart refresh when a provisional grant nears expiry to pick up verification. | Yes |
> [!NOTE]
>
> Both scopes surface provisional grants; neither is "verified-only." The difference is that `.verified` actively refreshes against the backend's verified set as provisional grants age, making it the right scope to drive toward a confirmed outcome. Use it when you want the SDK to chase verification; use `.all` for the cheapest "did the user just earn something" check.
### Which scope should I gate on?
* **Reversible / instant UX**: unlocking a screen, flipping a "premium" badge, hiding an upsell. Gate on **`.all`**. If a provisional grant is later revoked, you simply re-lock the UI; nothing was lost.
```swift theme={null}
if await Encore.shared.isActive(.freeTrial(), in: .all) {
showPremiumTab() // safe to reverse later
}
```
* **Irreversible / expensive grants**: minting durable credits, shipping a physical reward, writing a permanent server-side flag. Prefer **`.verified`** so the SDK is driving toward (and refreshing against) the backend's confirmed state before you commit. For grants you can never take back, wait until verification actually lands rather than acting on the first provisional signal.
```swift theme={null}
if await Encore.shared.isActive(.credit(), in: .verified) {
grantDurableCredits() // only after verification
}
```
### When verification fails
A provisional grant that the backend can't verify is **revoked**: the entitlement disappears from both scopes. To react in real time, subscribe with [`isActivePublisher(for:in:)`](./is-active-publisher) and re-lock whatever you optimistically unlocked:
```swift theme={null}
Encore.shared
.isActivePublisher(for: .freeTrial(), in: .all)
.sink { isActive in
isActive ? showPremiumTab() : hidePremiumTab()
}
.store(in: &cancellables)
```
If you only ever want to act on confirmed grants, never on provisional ones that might be revoked, configure the SDK with [`UnlockMode.strict`](./configure#unlock-mode), which withholds the grant until the advertiser postback verifies the conversion.
## Related
* [`isActive()`](./is-active): query a scope once.
* [`isActivePublisher()`](./is-active-publisher): observe a scope reactively.
* [`configure()` → Unlock mode](./configure#unlock-mode): choose optimistic vs strict granting.
# Entitlements
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/entitlements
Types of rewards granted when users accept offers
Represents the types of entitlements that can be granted when a user accepts an offer. Each entitlement type includes optional value and unit fields for specificity. Entitlements are never carried on a [`PresentationResult`](./presentation-result); read them from [`isActive()`](./is-active) / [`isActivePublisher()`](./is-active-publisher), the authoritative state.
## Definition
```swift theme={null}
public enum Entitlement: Sendable {
case freeTrial(value: Double? = nil, unit: EntitlementUnit? = nil)
case discount(value: Double? = nil, unit: EntitlementUnit? = nil)
case credit(value: Double? = nil, unit: EntitlementUnit? = nil)
}
public enum EntitlementUnit: CustomStringConvertible, Sendable {
case months
case days
case percent
case dollars
}
```
> [!WARNING]
>
> Entitlements may expire over time. Use [`isActive()`](./is-active) or [`isActivePublisher()`](./is-active-publisher) to check current status rather than storing the entitlement object.
## Entitlement Types
| Case | Associated Values | Description |
| - | - | - |
| `.freeTrial` | `value: Double?`, `unit: EntitlementUnit?` | Time-limited free access to premium features. Common units: `.days`, `.months` |
| `.discount` | `value: Double?`, `unit: EntitlementUnit?` | Percentage or dollar-based discount. Common units: `.percent`, `.dollars` |
| `.credit` | `value: Double?`, `unit: EntitlementUnit?` | Account credits applied to user's balance. Common unit: `.dollars` |
## Entitlement Units
| Unit | Description | Typical Use |
| - | - | - |
| `.months` | Duration in months | Free trials (e.g., "3 months free") |
| `.days` | Duration in days | Free trials (e.g., "30 days free") |
| `.percent` | Percentage value | Discounts (e.g., "20% off") |
| `.dollars` | Dollar amount | Discounts or credits (e.g., "\$10 off") |
> [!NOTE]
>
> Entitlements are automatically tracked and synced across devices when you call [`identify()`](./identify).
# Errors
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/errors
EncoreError values carried on presentation results and thrown by throwing APIs
## EncoreError
`EncoreError` is a **sealed, nested enum**. `show()` never throws: presentation failures arrive **as values**, in `.notPresented(.error(EncoreError))` on the [`PresentationResult`](./presentation-result) (and claim failures as `AdvertiserOutcome.failed(EncoreError)`). Throwing APIs like `revokeEntitlements()` still throw an `EncoreError`. User dismissals and "no offers" are business outcomes, not errors; see [DismissReason](./dismiss-reason) and [`NotPresentedReason`](./presentation-result#notpresentedreason).
> [!WARNING]
>
> Never block user actions on an SDK error. Always provide a fallback path so the user can complete their intended action: every non-success result, error or not, should fall through to your original flow.
### Definition
```swift theme={null}
public enum EncoreError: Error, LocalizedError, Sendable {
case transport(TransportError) // "The road is broken" — connectivity
case `protocol`(ProtocolError) // "The language failed" — HTTP/API
case integration(IntegrationError) // "SDK misused" — config/programmer error
case domain(String) // Client business-rule violation (message only)
public enum TransportError: Error, LocalizedError, Sendable {
case network(Error) // No connectivity, timeout, connection failed
case persistence(Error) // Local storage read/write failure
}
public enum ProtocolError: Error, LocalizedError, Sendable {
case http(status: Int, message: String?) // Non-2xx, body unreadable
case api(status: Int, code: String?, message: String) // Structured server error
case decoding(Error) // 2xx body didn't match schema
}
public enum IntegrationError: Error, LocalizedError, Sendable {
case notConfigured // configure() not called before use
case invalidApiKey // Empty / malformed API key
case invalidURL // Failed to construct a request URL
}
}
```
### Top-level cases
| Case | Associated value | Meaning |
| - | - | - |
| `.transport(TransportError)` | nested | Connectivity layer failed (network or local persistence). |
| `.protocol(ProtocolError)` | nested | The request reached the server but the exchange failed (bad status, server error, or undecodable body). |
| `.integration(IntegrationError)` | nested | The SDK was misused or misconfigured. |
| `.domain(String)` | `String` | A client-side business-rule violation, carrying a human-readable message. |
### Nested cases
| Case | Associated values | Description |
| - | - | - |
| `.transport(.network(Error))` | underlying `Error` | No internet, timeout, or connection failure. |
| `.transport(.persistence(Error))` | underlying `Error` | Local storage (cache/outbox) read or write failed. |
| `.protocol(.http(status:message:))` | `Int`, `String?` | Non-2xx response with an unreadable/unexpected body. |
| `.protocol(.api(status:code:message:))` | `Int`, `String?`, `String` | Server returned a structured error (its own domain error). |
| `.protocol(.decoding(Error))` | underlying `Error` | A 2xx response body didn't match the expected schema. |
| `.integration(.notConfigured)` | none | `configure(apiKey:)` was not called before use. |
| `.integration(.invalidApiKey)` | none | The API key was empty or malformed. |
| `.integration(.invalidURL)` | none | The SDK could not build a valid request URL. |
| `.domain(String)` | `String` | Client business-rule violation; the string describes it. |
### Helpers
Every `EncoreError` conforms to `LocalizedError`, so `errorDescription` gives a developer-readable summary. `transport` and `protocol(.decoding)` errors also expose the wrapped system error via the `underlying` property:
```swift theme={null}
if let underlying = encoreError.underlying {
// The original URLSession / decoding error, when one exists.
}
```
## Handling errors
`show()` delivers errors as values on the result:
```swift theme={null}
func cancelTapped() {
Task {
let result = await Encore.placement("cancel_flow").show()
if result.claim != nil || result.publisher == .purchased {
// Read the concrete entitlement from isActive / isActivePublisher.
} else {
if let error = result.error {
switch error {
case .integration(.notConfigured):
assertionFailure("Call Encore.shared.configure(apiKey:) at launch")
case .transport(.network(let underlying)):
Logger.log("Network error: \(underlying.localizedDescription)")
case .protocol(.api(_, let code, let message)):
Logger.log("API error (\(code ?? "unknown")): \(message)")
default:
Logger.log(error.errorDescription ?? "Encore error")
}
}
// Always let the user proceed.
proceedWithCancellation()
}
}
}
```
Throwing APIs like `revokeEntitlements()` still use `do`/`catch`:
```swift theme={null}
do {
try await Encore.shared.revokeEntitlements()
} catch let error as EncoreError {
Logger.log(error.errorDescription ?? "Encore error")
}
```
## Related Types
* [DismissReason](./dismiss-reason) and [`NotPresentedReason`](./presentation-result#notpresentedreason): business outcomes (dismiss, no offers, experiment control, unsupported OS). These are **not** errors.
* [PresentationResult](./presentation-result): the value returned by `await show()`, which carries any error via `result.error`.
> [!TIP]
>
> The most common "failure" is not an error at all: it is the user declining an offer, recorded on the result's `dismissal` axis. Every non-success result should fall through to your original flow.
# identify()
Source: https://docs.encorekit.com/publishers/ios/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
```swift theme={null}
public func identify(
userId: String,
attributes: UserAttributes? = nil
)
```
## Parameters
| Name | Type | Description |
| - | - | - |
| `userId` | String | Your user's unique identifier from your auth system. |
| `attributes` | [UserAttributes](./user-attributes)? | Optional structured attributes to set for the user in one call. Defaults to `nil`. |
## Usage
### Basic identification
```swift theme={null}
// After successful login
Encore.shared.identify(userId: user.id)
```
### With attributes
```swift theme={null}
Encore.shared.identify(
userId: user.id,
attributes: UserAttributes(
email: user.email,
subscriptionTier: user.plan,
monthsSubscribed: String(user.monthsActive)
)
)
```
> [!TIP]
>
> Call `identify()` after a successful login. On logout, call [`reset()`](./reset) to clear the user ID and cached entitlements.
# isActive()
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/is-active
Asynchronously check if an entitlement is currently active with automatic smart refresh
Asynchronously queries whether a given entitlement type is currently active for the user. Use this to gate features or show conditional UI based on active entitlements. This method automatically performs a smart refresh to guarantee fresh entitlement data before returning the result.
## Signature
```swift theme={null}
public func isActive(
_ type: Entitlement,
in scope: EntitlementScope = .all
) async -> Bool
```
## Parameters
| Name | Type | Description |
| - | - | - |
| `type` | [Entitlement](./entitlements) | The entitlement type |
| `scope` | [EntitlementScope](./entitlement-scope) | The scope to check (`.all` includes provisional grants; `.verified` refreshes against the backend's verified set) |
## Returns
Returns `true` if the specified entitlement is currently active for the user, `false` otherwise.
## Usage
```swift theme={null}
Task {
let hasTrial = await Encore.shared.isActive(.freeTrial(), in: .all)
if hasTrial {
// User has an active free trial
showPremiumFeatures()
} else {
// User doesn't have a free trial
showUpgradePrompt()
}
}
```
> [!TIP]
>
> For reactive, real-time entitlement tracking in Combine-based apps, use [`isActivePublisher()`](./is-active-publisher) instead.
# isActivePublisher()
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/is-active-publisher
Reactive entitlement state updates using Combine
Returns a Combine publisher that emits changes to an entitlement's active state. Use this for reactive UI updates in SwiftUI or when you need automatic notifications when entitlement status changes.
## Signature
```swift theme={null}
public func isActivePublisher(
for type: Entitlement,
in scope: EntitlementScope = .all
) -> AnyPublisher
```
## Parameters
| Name | Type | Description |
| - | - | - |
| `type` | [Entitlement](./entitlements) | The entitlement type to observe |
| `scope` | [EntitlementScope](./entitlement-scope) | The scope to check |
## Returns
`AnyPublisher` - A publisher that emits `true` when the entitlement becomes active and `false` when it becomes inactive.
## Usage
```swift theme={null}
// Automatically update when state changes
Encore.shared
.isActivePublisher(for: .freeTrial(), in: .verified)
.sink { isActive in
// Called whenever the state changes
}
.store(in: &cancellables)
```
# isClaimEnabled
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/is-claim-enabled
Runtime switch that dims the claim CTA on offer cards and stops it responding to taps
`Encore.shared.isClaimEnabled` controls whether the claim call to action on offer cards responds to taps. Set it to `false` to dim the claim button and make it inert; set it back to `true` to restore it. It is a property on the facade rather than an [`Options`](./configure#options) field, so you can gate claims for a session, a cohort, or a screen without reconfiguring the SDK.
## Signature
```swift theme={null}
@MainActor
public var isClaimEnabled: Bool // default true
```
## Usage
Set it before you present, then present as usual:
```swift theme={null}
// A user whose account is under review can browse offers but not claim them.
Encore.shared.isClaimEnabled = !account.isUnderReview
let result = await Encore.shared.placement("cancellation_flow").show()
```
## Behavior
The offer sheet reads the value when it appears, so the flag applies from the next presentation onward. Changing it while a sheet is already on screen does not affect that sheet.
With `isClaimEnabled == false`, the claim button on every offer card renders dimmed and ignores taps. Nothing else about the presentation changes: offers are still fetched, the sheet still appears, impressions are still tracked, and every other control (including dismissal) behaves normally. A user who dismisses a sheet they could not claim from produces the same [`PresentationResult`](./presentation-result) they would produce with claiming enabled: `advertiser: .notAttempted` and the dismissal they performed.
> [!NOTE]
>
> Turning claims off leaves purchases untouched. If a variant offers an in-app purchase, your [`EncorePurchaseController`](./purchase-controller) is still invoked when the user buys.
## Related
* [placement()](./placement), the presentation this flag applies to.
* [PresentationResult](./presentation-result), where a non-claim gets recorded as `advertiser: .notAttempted`.
# outcomes
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/outcomes
AsyncStream of every placement resolution, for passive observers
`Encore.shared.outcomes` is an `AsyncStream` that every placement resolution lands on, plus late events. Use it for anything that wants to watch results without owning a call site: analytics forwarding, a debug overlay, cross-screen state. Control flow at the call site should use the result returned by [`show()`](./placement) instead.
## Signature
```swift theme={null}
@MainActor
public var outcomes: AsyncStream { get }
public enum PlacementOutcome: Sendable {
/// A placement resolved. Yielded for every show(), including .notPresented outcomes.
case presentation(placementId: String, result: PresentationResult)
/// A strict-unlock claim verified after its flow ended, possibly on a later launch.
case strictUnlockVerified(transactionId: String)
}
```
Each access to `outcomes` returns an independent stream; any number of observers can listen concurrently.
## Usage
```swift theme={null}
.task {
for await outcome in Encore.shared.outcomes {
switch outcome {
case .presentation(let placementId, let result):
analytics.log("encore_outcome", placementId, "\(result)")
case .strictUnlockVerified(let transactionId):
// Entitlements are already refreshed; gate on isActive / isActivePublisher.
print("late verification for \(transactionId)")
}
}
}
```
## Late strict-unlock verification
With `unlock: .strict`, a claim that ends unverified persists across process death. When verification completes later, possibly on a subsequent launch, entitlements are refreshed first and then `.strictUnlockVerified(transactionId:)` is emitted. The `transactionId` matches the `ClaimedOffer.transactionId` recorded on the original result, so you can join the two events.
## Related
* [PresentationResult](./presentation-result), the payload of `.presentation` events.
* [isActivePublisher()](./is-active-publisher), the reactive entitlement state to gate UI on.
# Overview
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/overview
Complete reference documentation for the Encore iOS SDK
Every public method, type, and enum in the Encore iOS SDK, with its full contract.
> [!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 [iOS Quickstart](/publishers/ios/quickstart/install) for detailed installation and configuration instructions
> * **Advanced setups:** This reference section is ideal for looking up specific methods, parameters, and advanced usage patterns
## Core Methods
> [card] [configure()](/publishers/ios/sdk-reference/configure)
>
> Initialize the SDK with your public API key and optional UI configuration
> [card] [identify()](/publishers/ios/sdk-reference/identify)
>
> Associate your user ID with Encore for cross-device tracking
> [card] [setUserAttributes()](/publishers/ios/sdk-reference/set-user-attributes)
>
> Set structured attributes for targeting and analytics
> [card] [setLanguage()](/publishers/ios/sdk-reference/set-language)
>
> Set the language Encore serves copy in, overriding the device language
> [card] [clearLanguage()](/publishers/ios/sdk-reference/clear-language)
>
> Drop a language override so copy follows the device language again
> [card] [reset()](/publishers/ios/sdk-reference/reset)
>
> Clear user identification and cached entitlements on logout
## Presenting Offers
> [card] [placement()](/publishers/ios/sdk-reference/placement)
>
> Fluent API for presenting offers with async/await or a callback
> [card] [EncorePurchaseController](/publishers/ios/sdk-reference/purchase-controller)
>
> The controller your app registers so purchases run through your billing code
> [card] [outcomes](/publishers/ios/sdk-reference/outcomes)
>
> AsyncStream of every placement resolution, for passive observers
> [card] [isClaimEnabled](/publishers/ios/sdk-reference/is-claim-enabled)
>
> Runtime switch that dims the claim CTA on offer cards and stops it responding to taps
> [card] [isActive()](/publishers/ios/sdk-reference/is-active)
>
> Check if an entitlement is currently active for the user
> [card] [isActivePublisher()](/publishers/ios/sdk-reference/is-active-publisher)
>
> Reactive Combine publisher for entitlement state changes
## Testing & Development
> [card] [revokeEntitlements()](/publishers/ios/sdk-reference/revoke-entitlements)
>
> Admin method to revoke all entitlements for testing offer flows end-to-end
## Types & Configuration
> [card] [UserAttributes](/publishers/ios/sdk-reference/user-attributes)
>
> Structured user attributes for targeting and personalization
> [card] [Entitlements](/publishers/ios/sdk-reference/entitlements)
>
> Types of rewards granted when users accept offers
> [card] [PresentationResult](/publishers/ios/sdk-reference/presentation-result)
>
> The factual record a presentation resolves to
> [card] [DismissReason](/publishers/ios/sdk-reference/dismiss-reason)
>
> How a presented offer sheet went away
## Error Handling
> [card] [Errors](/publishers/ios/sdk-reference/errors)
>
> Errors that can occur when using the SDK
## Basic Integration
```swift theme={null}
// 1. Configure at launch, registering your purchase controller if your
// app sells a product through Encore offers
Encore.shared.configure(apiKey: "pk_live_your_key", purchaseController: AppPurchases())
// 2. Identify user after login
Encore.shared.identify(userId: user.id)
// 3. Present an offer and branch on the result
Button("Cancel Subscription") {
Task {
let result = await Encore.shared.placement("cancellation_flow").show()
if result.claim != nil || result.publisher == .purchased {
// The user claimed an offer or completed your purchase.
} else {
proceedWithCancellation() // dismissed, declined, nothing appeared, ...
}
}
}
// 4. Check entitlements (async with automatic smart refresh)
Task {
if await Encore.shared.isActive(.freeTrial(), in: .verified) {
unlockPremiumFeatures()
}
}
```
> [!NOTE]
>
> `show()` never throws. Failures arrive as `.notPresented(.error(EncoreError))` on the [`PresentationResult`](./presentation-result), so fallback logic lives in one place.
> [!TIP]
>
> For reactive state, subscribe with [`isActivePublisher`](./is-active-publisher) to keep premium UI in sync as provisional grants are verified or revoked. For passive observation (analytics, debug overlays), consume the [`outcomes`](./outcomes) stream.
# placement()
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/placement
Create and present Encore offers with a fluent API
## Purpose
Create and present Encore offers using a fluent API that fits naturally in SwiftUI and UIKit. Purchases run through the [`EncorePurchaseController`](./purchase-controller) you register at [`configure()`](./configure) time.
## Signature
```swift theme={null}
@MainActor
public static func placement(_ id: String? = nil) -> any PlacementBuilderProtocol
```
`placement(_:)` returns a builder. Configure it with the optional builder methods, then call `show()`:
```swift theme={null}
@MainActor
public protocol PlacementBuilderProtocol {
var id: String { get }
/// Presents the offer sheet and returns the outcome. Never throws.
func show() async -> PresentationResult
/// Callback form: delivers every outcome (including .notPresented) on the main actor.
func show(resume: @escaping @Sendable (PresentationResult) -> Void)
/// Reports when the builder starts and stops loading.
func onLoadingStateChange(_ callback: @escaping @Sendable (Bool) -> Void) -> Self
/// Selects the surface to present. Defaults to .reduceChurn.
func useCase(_ useCase: UseCase) -> Self
/// Overrides the sheet's headline copy.
func headline(_ text: String) -> Self
/// Overrides the sheet's subheadline copy.
func subheadline(_ text: String) -> Self
/// 2.3.0+: the prize your app pays for trying an offer.
func publisherReward(_ reward: PublisherReward) -> Self
}
```
> [!NOTE]
>
> `Encore.shared.placement(_:)` and the static `Encore.placement(_:)` are equivalent; the static form forwards to the shared instance.
## Methods
| Method | Parameters | Description |
| - | - | - |
| `placement(_:)` | `id: String?` | Creates a placement builder with an optional identifier. If omitted, a unique ID is auto-generated. |
| `show() async` | None | Presents the offer sheet and returns a [`PresentationResult`](./presentation-result). Never throws; failures arrive as `.notPresented(.error(EncoreError))`. |
| `show(resume:)` | `(PresentationResult) -> Void` | Callback form. Delivers every outcome, including `.notPresented`, on the main actor. |
| `onLoadingStateChange(_:)` | `(Bool) -> Void` | Reports when the builder starts and stops loading, so you can show your own spinner. |
| `useCase(_:)` | [`UseCase`](#use-cases) | Selects the surface to present. Defaults to `.reduceChurn`. |
| `headline(_:)` | `String` | Overrides the sheet's headline copy for this presentation. |
| `subheadline(_:)` | `String` | Overrides the sheet's subheadline copy for this presentation. |
| `publisherReward(_:)` | `PublisherReward` | 2.3.0+. The prize your app pays for trying an offer. See [Reward for Trying](/publishers/guides/reward-for-trying). |
`.presented` means the interaction ran: the offer sheet, or on IAP-first variants the purchase sheet that stands in for it.
`headline(_:)` and `subheadline(_:)` pass the full string through as-is; the SDK never composes copy out of a count. Priority is this override, then the copy Encore resolved for your app, then the shipped template default, and an empty string is ignored so it can't blank the shipped copy. Encore never translates the string you pass, so localize it yourself. The copy Encore resolves for your app is translated into the user's language. See [Where the copy comes from](/publishers/use-cases/post-action-reward#where-the-copy-comes-from) and [Localization](/publishers/concepts/localization).
## Use cases
```swift theme={null}
public enum UseCase: String, Sendable, CaseIterable, Equatable {
case reduceChurn = "churn-intervention" // default
case rewardUsers = "post-action-reward"
}
```
The raw values are the wire format the backend stores and that analytics splits the funnel on. The case names are the API surface; the raw values are the contract.
`.reduceChurn` is the default surface for cancel flows and paywall declines. `.rewardUsers` presents the reward surface *after* the user has already done something worth celebrating (a completed purchase, a milestone, a streak); it is not a way to sell. It is claim-only: no in-app purchase runs anywhere in the path, and it never falls back to the paywall sheet. See [Reward Users](/publishers/use-cases/post-action-reward). If no enabled variant resolves for the requested use case, `show()` resolves with `.notPresented(.useCaseUnavailable)` and no UI appears.
## Usage Patterns
### Async/await (recommended)
The facade and builder are `@MainActor`, so call `show()` from a main-actor context: a SwiftUI button action, a `.task`, or a UIKit handler. A SwiftUI `Button` action is synchronous, so wrap the `await` in a `Task`:
```swift theme={null}
Button("Cancel Subscription") {
Task {
let result = await Encore.shared.placement("cancellation_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.
} else {
result.error.map(log) // presentation failures are values
proceedWithCancellation() // dismissed, declined, nothing appeared, ...
}
}
}
```
### Callback form
When the call site can't await, `show(resume:)` delivers every outcome on the main actor:
```swift theme={null}
Button("Cancel Subscription") {
Encore.shared.placement("cancellation_flow").show { result in
if result.claim == nil && result.publisher != .purchased {
proceedWithCancellation()
}
}
}
```
> [!WARNING]
>
> There is no fire-and-forget `show()` in 2.x. Every presentation resolves exactly once, and the resolution is always delivered, so fallback logic can never be silently skipped.
### Selecting a use case
```swift theme={null}
let result = await Encore.shared.placement("workout_complete")
.useCase(.rewardUsers)
.headline("Nice work!")
.show()
```
> [!NOTE]
>
> `show()` is `@MainActor`: presentation always happens on the main thread. From nonisolated code, `await` hops to the main actor automatically and the result still resumes there.
### 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(resume:)`), 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).
## 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 presentation window is left unspecified, so the sheet inherits your app's interface style and switches with it, with no work on your side.
## Related
* [PresentationResult](./presentation-result) describes everything `show()` can resolve to.
* [outcomes](./outcomes) is the passive stream every resolution also lands on.
* [isClaimEnabled](./is-claim-enabled) gates the claim CTA on the cards this presents.
# PresentationResult
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/presentation-result
The factual record a placement presentation resolves to
The value returned by `await Encore.shared.placement(_:).show()`. It is the complete factual record of the presentation: either nothing appeared (and why), or the interaction ran and the record carries what happened on each independent axis. `.presented` means the interaction ran: the offer sheet, or on IAP-first variants the purchase sheet that stands in for it. `show()` never throws; errors are values on the result.
## Definition
```swift theme={null}
public enum PresentationResult: Sendable, Equatable {
/// Nothing appeared; the reason says why (errors included, as values).
case notPresented(NotPresentedReason)
/// The interaction ran (offer sheet, or the purchase sheet on IAP-first
/// variants); both funnels plus how it ended.
case presented(Outcome)
public struct Outcome: Sendable, Equatable {
public let advertiser: AdvertiserOutcome // Encore's claim funnel
public let publisher: PublisherOutcome // your purchase funnel
public let dismissal: DismissReason // how the sheet ended
}
}
```
`Outcome`'s fields are independent axes. `.notAttempted` is a real value ("funnel open, nothing entered it"), never `nil`. A claim and a purchase are not rival cases: a flow where the user claims an offer and then completes a purchase records both, side by side.
## NotPresentedReason
```swift theme={null}
public enum NotPresentedReason: Equatable, Sendable {
case notConfigured // configure() was not called
case alreadyPresenting // another sheet is already up
case unsupportedOS // requires iOS 17+
case noOffers // no offers matched this user
case experimentControl // NCL control cohort: exposure logged, no UI by design
case useCaseUnavailable // no enabled variant for the requested use case
case error(EncoreError) // network, decoding, or integration failure
}
```
## AdvertiserOutcome
How far Encore's claim funnel got. The claim is staged the same way in both unlock modes, but `.verified` is only reachable under [`unlock: .strict`](./configure#unlock-mode), where an in-session verification poll upgrades the staged `.claimed`. In `.optimistic` the advertiser axis stops at `.claimed`.
```swift theme={null}
public enum AdvertiserOutcome: Sendable, Equatable {
case notAttempted
case claimed(ClaimedOffer) // claim completed on-device; server verification not (yet) observed
case verified(ClaimedOffer) // server-level confirmation observed in-session
case cooldown // not produced since 2.3.0; kept for source compatibility
case failed(EncoreError) // claim errored
}
```
### ClaimedOffer
```swift theme={null}
public struct ClaimedOffer: Sendable, Equatable {
public let offerId: String // equals campaignId on iOS; both exist so bridges line up
public let campaignId: String
public let advertiserName: String
public let transactionId: String? // joins to a later .strictUnlockVerified on outcomes
public let userConfirmedCompletion: Bool // 2.3.0+: the user said they finished, and the server granted the prize
}
```
The `transactionId` is the join key to a later `.strictUnlockVerified` event on [`outcomes`](./outcomes).
`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).
## PublisherOutcome
What your [`EncorePurchaseController`](./purchase-controller) reported back.
```swift theme={null}
public enum PublisherOutcome: Sendable, Equatable {
case notAttempted
case purchased
case cancelled
case pending // deferred (Ask to Buy / SCA); may complete later
case failed
}
```
## DismissReason
How the sheet went away. See [DismissReason](./dismiss-reason) for the full vocabulary (`.userTappedClose`, `.userSwipedDown`, `.flowCompleted`, `.interrupted`, and more).
## Fact readers
The record carries raw facts only; there is no SDK-computed "unlocked" verdict. What a claim means is a property of the flow that served it (some flows grant on claim, some gate on verification, some grant nothing), so the SDK reports what happened and your integration decides.
```swift theme={null}
public extension PresentationResult {
/// The offer the user claimed, when the advertiser funnel got that far.
var claim: ClaimedOffer? { get }
/// nil ⇔ never presented; .notAttempted ⇔ presented, funnel untouched.
var advertiser: AdvertiserOutcome? { get }
var publisher: PublisherOutcome? { get }
var dismissal: DismissReason? { get }
/// The presentation-level failure, when that is why nothing appeared.
var error: EncoreError? { get }
}
```
## Usage
The dominant pattern branches on the facts:
```swift theme={null}
let result = await Encore.shared.placement("paywall").show()
if result.claim != nil || result.publisher == .purchased {
// The user claimed an offer or completed your purchase: continue the
// unlocked path. The record is the decision; nothing else to consult.
} else {
result.error.map(log) // presentation failures are values
runOriginalFlow() // dismissed, declined, nothing appeared, ...
}
```
When the mechanism matters (analytics, debugging), switch on the record:
```swift theme={null}
switch result {
case .presented(let outcome):
analytics.log(outcome.advertiser, outcome.publisher, outcome.dismissal)
case .notPresented(let reason):
analytics.log(reason)
}
```
> [!NOTE]
>
> Branch this flow on the record itself. [`isActive`](./is-active) and [`isActivePublisher`](./is-active-publisher) are the durable entitlement state for gating UI elsewhere in your app, long after a presentation ends; they are not the check for what just happened here. Use `result.advertiser` directly to distinguish an unverified `.claimed` from a `.verified` one.
## Related Types
* [DismissReason](./dismiss-reason), the dismissal axis of the record.
* [Errors](./errors), the `EncoreError` values carried by `.notPresented(.error(...))` and `AdvertiserOutcome.failed`.
* [outcomes](./outcomes), the passive stream every resolution also lands on.
# EncorePurchaseController
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/purchase-controller
The purchase controller your app registers so Encore offers purchase through your billing code
All purchases triggered by Encore offers run through an `EncorePurchaseController` your app registers at [`configure()`](./configure) time. The SDK has no built-in billing and never runs purchase code you did not write: your controller owns receipt validation, restore handling, and entitlement bookkeeping, exactly as it does for every other purchase in your app.
## Definition
```swift theme={null}
@MainActor
public protocol EncorePurchaseController: AnyObject {
/// Called when Encore's offer flow needs a purchase. Perform it through
/// your subscription manager and report what happened.
func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult
}
public enum EncorePurchaseResult: Sendable {
case purchased
case cancelled
case pending // deferred (Ask to Buy / SCA); may complete later
}
```
Return `.purchased` on success, `.cancelled` when the user backs out, and `.pending` for deferred flows; throw for real failures. The result lands on the record as [`PublisherOutcome`](./presentation-result#publisheroutcome), and the controller is awaited inside the sheet lifetime, so the sheet reacts to the outcome, except on IAP-first variants, where the purchase runs before the sheet is presented.
## PurchaseRequest
What your controller receives when Encore needs a purchase.
```swift theme={null}
public struct PurchaseRequest: Sendable {
public let productId: String // IAP product to purchase
public let placementId: String? // the placement that triggered it, if any
public let promoOfferId: String? // reserved; always nil on iOS 2.0
}
```
| Property | Type | Description |
| - | - | - |
| `productId` | `String` | The IAP product identifier to purchase, for example `com.app.monthly_premium` |
| `placementId` | `String?` | Which placement triggered this purchase, if any |
| `promoOfferId` | `String?` | Reserved for Encore-driven promotional offers, which iOS SDK 2.0 does not yet support. Always `nil`; see [Create a Promotional Offer](../platform-setup/create-promotional-offer) |
## Implementations
> [tab] StoreKit 2
>
> ```swift theme={null}
> 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() }
> return .purchased
> case .userCancelled: return .cancelled
> case .pending: return .pending
> @unknown default: return .cancelled
> }
> }
> }
> ```
> [tab] RevenueCat
>
> ```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
> }
> }
> ```
> [tab] Adapty
>
> ```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
> }
> }
> ```
> [tab] Custom
>
> ```swift theme={null}
> final class AppPurchases: EncorePurchaseController {
> func purchase(_ request: PurchaseRequest) async throws -> EncorePurchaseResult {
> // request.productId - App Store product ID to purchase
> // request.placementId - which placement triggered this (optional)
> // request.promoOfferId - reserved; always nil on iOS 2.0
> let didSucceed = try await yourManager.purchase(request.productId)
> return didSucceed ? .purchased : .cancelled
> }
> }
> ```
## Related
* [configure()](./configure), which accepts the controller and defines what happens when none is registered.
* [PresentationResult](./presentation-result), where the controller's result lands as `PublisherOutcome`.
* [Configure the SDK](../quickstart/configure#register-a-purchase-controller) for the registration walkthrough.
# reset()
Source: https://docs.encorekit.com/publishers/ios/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
```swift theme={null}
public func reset()
```
## Parameters
This method takes no parameters.
## Usage
### Basic logout flow
```swift theme={null}
func 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.
# revokeEntitlements()
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/revoke-entitlements
Admin/testing method to expire all entitlements while preserving user identity
Expires all entitlements for the currently identified user while preserving their user ID and attributes. This is a convenience method designed for testing and development environments to simulate entitlement expiry and test offer flows repeatedly for the same user.
> [!NOTE]
>
> Unlike [`reset()`](./reset) which clears everything, `revokeEntitlements()` only expires entitlements - the user remains identified with their attributes intact. This allows you to test multiple offer cycles for the same user.
## Signature
```swift theme={null}
public func revokeEntitlements() async throws
```
## Returns
No return value. Completes normally on success and throws an [`EncoreError`](./errors) on failure.
## Usage
### Complete Testing Lifecycle for a User
Test the full entitlement lifecycle from offer presentation through expiry and re-testing for the same user:
```swift theme={null}
func testCompleteEntitlementLifecycle() async {
// User identity is preserved throughout this entire flow
Encore.shared.identify(userId: "test_user_123")
// 1. Verify no active entitlements at start
let hasTrialInitially = await Encore.shared.isActive(.freeTrial())
print("Has trial initially: \(hasTrialInitially)") // false
// 2. Present offer and claim it
let result = await Encore.shared.placement("test_flow").show()
if result.claim != nil || result.publisher == .purchased {
print("✅ User accepted offer")
// 3. Verify entitlement is now active
let hasTrialAfterGrant = await Encore.shared.isActive(.freeTrial())
print("Has trial after grant: \(hasTrialAfterGrant)") // true
} else {
result.error.map { print("Error presenting offer: \($0)") }
print("User declined (dismissal: \(String(describing: result.dismissal)))")
return
}
// 4. Simulate entitlement expiry using revokeEntitlements
// Note: User identity (test_user_123) is preserved
do {
try await Encore.shared.revokeEntitlements()
print("✅ Entitlements expired - user still identified as test_user_123")
// 5. Verify entitlement is no longer active
let hasTrialAfterRevoke = await Encore.shared.isActive(.freeTrial())
print("Has trial after revoke: \(hasTrialAfterRevoke)") // false
// Ready to test another offer cycle for the same user
} catch {
print("❌ Failed to revoke: \(error)")
}
}
```
## End-to-end sandbox test recipe
Use the **Test Key** together with `revokeEntitlements()` to run repeatable offer cycles for the same user from any location, and to watch the [two-phase entitlement flow](./entitlement-scope#two-phase-entitlements-provisional-vs-verified) (provisional → verified → revoked).
**1. Configure with your Test Key**
The Test Key (`pk_test_…`) serves demo offers rather than your inventory, and bypasses geo-filtering. See [what a test key serves](/publishers/offers-api/overview#what-a-test-key-serves).
```swift theme={null}
#if DEBUG
Encore.shared.configure(
apiKey: "pk_test_",
options: .init(logLevel: .debug) // verbose logs to follow the flow
)
Encore.shared.identify(userId: "test_user_456")
#endif
```
**2. Point App Store Connect at the sandbox webhook**
In App Store Connect, set the **Sandbox Server URL** for App Store Server Notifications to Encore's endpoint so sandbox transactions reach the backend and can be verified:
```
https://api.encorekit.com/encore/webhooks/apple
```
See [App Store Server Notifications](/publishers/ios/platform-setup/server-notifications) for the full walkthrough.
**3. Trigger an offer and observe provisional → verified**
Present an offer and complete the sandbox purchase. With `unlock: .optimistic` (the default), the entitlement is granted **provisionally** the moment the user returns, then flips to **verified** once the backend confirms the transaction.
```swift theme={null}
let result = await Encore.shared.placement("test_offer").show()
if result.claim != nil || result.publisher == .purchased {
// Provisional grant — visible in the .all scope immediately.
print("all:", await Encore.shared.isActive(.freeTrial(), in: .all)) // true (provisional)
// Verified grant lands shortly after, once the webhook is processed.
print("verified:", await Encore.shared.isActive(.freeTrial(), in: .verified)) // becomes true after verification
}
```
**4. Revoke and repeat**
Expire all entitlements while keeping the user identified, then run another cycle for the same `test_user_456`:
```swift theme={null}
try await Encore.shared.revokeEntitlements()
print("all after revoke:", await Encore.shared.isActive(.freeTrial(), in: .all)) // false
// Present again to the same user.
let next = await Encore.shared.placement("test_offer_2").show()
```
> [!TIP]
>
> The combination of the **Test Key** ([`configure()`](./configure#using-test-key-for-development)) and `revokeEntitlements()` lets you replay the full offer lifecycle for one user against the demo catalog, from any location and with no geo-filtering.
## Related Methods
* [`configure()`](./configure) - Configure SDK with admin API key
* [`isActive()`](./is-active) - Check entitlement status after revoking
* [`reset()`](./reset) - Clear user session and entitlements
* [`identify()`](./identify) - Set user ID for testing specific users
# setLanguage()
Source: https://docs.encorekit.com/publishers/ios/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 iOS SDK 2.3.0. React Native and Flutter forward it from the release that pins native 2.3.0.
## Signature
```swift theme={null}
public func 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: passing `language:` to the `UserAttributes` initializer calls `setLanguage(_:)` for you, logging a warning once per launch, and it is removed at the next major release. The language is no longer sent as an attribute, and `UserAttributes.language` is now read-only. 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":
```swift theme={null}
func languageChanged(to code: String?) {
if let code {
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/ios/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
```swift theme={null}
public func 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
```swift theme={null}
Encore.shared.setUserAttributes(
UserAttributes(
email: "user@example.com",
subscriptionTier: "premium",
monthsSubscribed: "6"
)
)
```
# UserAttributes
Source: https://docs.encorekit.com/publishers/ios/sdk-reference/user-attributes
Structured user attributes for targeting and analytics
A structured data type for storing user metadata used in offer targeting, personalization, and analytics. All fields are optional and will be merged with existing attributes when set.
## Structure
```swift theme={null}
public struct UserAttributes {
// Identity & Basic Info
public let email: String?
public let firstName: String?
public let lastName: String?
public let phoneNumber: String?
// Location
public let postalCode: String?
public let city: String?
public let state: String?
public let countryCode: String?
public let latitude: String?
public let longitude: String?
// Demographics
public let age: Int?
public let dateOfBirth: String?
public let gender: String?
@available(*, deprecated, message: "Use Encore.shared.setLanguage(_:). Removed in the next major version.")
public var language: String? { get }
// Subscription & Billing
public let subscriptionTier: String?
public let monthsSubscribed: String?
public let billingCycle: String?
public let lastPaymentAmount: String?
// Engagement
public let lastActiveDate: String?
public let totalSessions: String?
// Custom Attributes
public let custom: [String: String]
public init(
email: String? = nil,
firstName: String? = nil,
lastName: String? = nil,
phoneNumber: String? = nil,
postalCode: String? = nil,
city: String? = nil,
state: String? = nil,
countryCode: String? = nil,
latitude: String? = nil,
longitude: String? = nil,
age: Int? = nil,
dateOfBirth: String? = nil,
gender: String? = nil,
language: String? = nil,
subscriptionTier: String? = nil,
monthsSubscribed: String? = nil,
billingCycle: String? = nil,
lastPaymentAmount: String? = nil,
lastActiveDate: String? = nil,
totalSessions: String? = nil,
custom: [String: String] = [:]
)
}
```
## Field Reference
### Identity & 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` | Alternative phone number |
### Location
| Field | Type | Format | Example | Description |
| - | - | - | - | - |
| `postalCode` | String? | postal/ZIP code | `SW1A 1AA` | Alternative postal code key |
| `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()`, the property is read-only, and passing `language:` to the initializer calls `setLanguage(_:)` for you and logs a warning once per launch. Removed at the next major release. See [Localization](/publishers/concepts/localization) |
### Subscription & 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` | \[String: String] | JSON object (string:string) | `{ "churnRisk": "high" }` | For any additional attributes not covered above |
## Usage
```swift theme={null}
let attributes = UserAttributes(
email: "user@example.com",
subscriptionTier: "premium",
monthsSubscribed: "6"
)
Encore.shared.setUserAttributes(attributes)
```
# Receive Completion Events
Source: https://docs.encorekit.com/publishers/offers-api/guides/receive-completion-events
Wire your server to react when a user's offer completion is verified, via the offer_completed webhook.
When one of your users completes an offer and the completion is **verified**, Encore can `POST` an `offer_completed` event to a URL you own. Use it when your server needs to *react* to a completion: grant a reward, credit a balance, kick off an email. You host one HTTPS endpoint; nothing to poll.
This is the final stage of an offer's flow, and it fires on **verification** (the advertiser's conversion postback), not on the user tapping or claiming; a claim that never converts produces no webhook. The payload contract (headers, body fields, signature spec, delivery guarantees, URL requirements) is the [offer\_completed webhook reference](/publishers/offers-api/reference/offer-completed-webhook); this guide is the wiring.
> [!WARNING]
>
> A failed delivery is **retried up to five times over roughly nine hours**, so a brief outage on your side no longer costs the event. Read [Design for the guarantees](#design-for-the-guarantees) before you make anything financial depend on it.
## Set it up
Configuration lives in the [dashboard](https://dashboard.encorekit.com) under **Settings** for the app you want events for; there is no publishable-key API for webhook config.
**1. Enter your webhook URL**
Paste the HTTPS URL of your endpoint (for example `https://your-server.com/webhooks/encore`) and save. **One webhook per app**: to point somewhere else, edit the existing URL. It must be HTTPS, publicly resolvable, and redirect-free ([URL requirements](/publishers/offers-api/reference/offer-completed-webhook#url-requirements)).
**2. Copy your signing secret**
Creating the webhook generates a `whsec_...` signing secret. Store it as a server-side secret (an environment variable, never in client code). Rotating it invalidates the old one immediately: update your server first, or you'll reject deliveries in the gap.
**3. Send a test delivery**
**Send Test** POSTs a sample event to your live URL with a real signature from your current secret, exercising your verification path end to end. The sample's `transactionId` and `userId` are not real records, so make sure your handler tolerates an unknown user gracefully instead of throwing. If your app has per-offer rewards on, the sample carries the reward one of your offers really sends, in your own unit, under that offer's `campaignId` and `campaignName`. Use **Send test reward** in the **Rewards** section of **Settings** to pick the offer. Without per-offer rewards, `reward` is `null`, as on a real completion. Every test delivery carries `"test": true`: skip crediting when it is present.
**4. Enable or pause**
The status toggle turns delivery on and off. Retries cover a failing endpoint, not a paused one: **events that occur while paused are lost, not queued**, and pausing also stops retries already in flight.
## Verify the signature
Never trust an unverified delivery; the signature proves the request came from Encore. Recompute HMAC-SHA256 over `.` with your `whsec_...` secret and compare hex digests ([signature spec](/publishers/offers-api/reference/offer-completed-webhook#signature)).
> [!WARNING]
>
> Sign the **exact bytes Encore sent**, not a re-serialization. Body parsers can normalize whitespace or escaping in ways that are fatal to a byte-exact HMAC. Capture the raw body: in Express, `express.raw()` or the `verify` hook of `express.json()`.
```javascript theme={null}
import express from 'express';
import crypto from 'node:crypto';
const app = express();
const MAX_SKEW_SECONDS = 300; // 5 minutes
// Fail fast at boot rather than inside createHmac on the first delivery.
const SIGNING_SECRET = process.env.ENCORE_WEBHOOK_SECRET; // whsec_...
if (!SIGNING_SECRET) {
throw new Error(
'ENCORE_WEBHOOK_SECRET is not set: copy the signing secret from the dashboard under Settings.',
);
}
// Mount the RAW body parser on this route: the signature covers exact bytes.
app.post(
'/webhooks/encore',
express.raw({ type: 'application/json' }),
async (req, res) => {
const signature = req.get('X-Webhook-Signature');
const timestamp = req.get('X-Webhook-Timestamp');
const rawBody = req.body.toString('utf8');
if (!signature || !timestamp) {
return res.status(400).send('Missing signature headers');
}
// 1. Replay protection: reject stale (or future-dated) timestamps.
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
if (!Number.isFinite(age) || age > MAX_SKEW_SECONDS) {
return res.status(401).send('Timestamp outside tolerance');
}
// 2. Recompute the HMAC over `${timestamp}.${rawBody}`.
const expected = crypto
.createHmac('sha256', SIGNING_SECRET)
.update(`${timestamp}.${rawBody}`)
.digest('hex');
// 3. Constant-time compare: never `===`, which leaks timing information.
const a = Buffer.from(signature, 'utf8');
const b = Buffer.from(expected, 'utf8');
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return res.status(401).send('Invalid signature');
}
// 4. Verified. Commit the write BEFORE acknowledging: a 200 tells Encore
// the delivery landed, so acknowledging first makes a later failure in
// your own code invisible and unretryable.
const payload = JSON.parse(rawBody);
if (payload.event === 'offer_completed') {
// Credit the user once per transactionId: a retry, or a later paid action
// of a multi-step offer, carries one you have already credited. Key each
// payment on transactionId + actionId, or transactionId alone when
// actionId is absent (see "Design for the guarantees").
await grantReward({
transactionId: payload.transactionId,
userId: payload.userId,
campaignId: payload.campaignId, // the offer; match on this, never on a name
campaignName: payload.campaignName,
payout: payload.payout, // may be null
actionId: payload.actionId, // the paid action; absent when there is none
// { amount, unit } or null. Credit it once per transactionId, and only
// if your app doesn't already pay this prize on the device.
reward: payload.reward,
});
} else if (payload.event === 'offer_payout_booked') {
// Payout updates only (see "Payout updates"). Never credit a reward here.
// Store the booked payout on transactionId + actionId; it wins over the
// earlier offer_completed payout, whichever arrives first.
await recordPayoutUpdate({
transactionId: payload.transactionId,
actionId: payload.actionId, // always present on this event
payout: payload.payout, // USD
bookedAt: payload.bookedAt,
});
}
// 5. Only now. Keep steps 4 and 5 inside the 5s budget; if the credit is
// genuinely slow, write it to your own durable queue and treat THAT
// write as the commit.
res.status(200).send('OK');
},
);
app.listen(3000);
```
Full header and body contract for the delivery this handler verifies: [`offer_completed` webhook reference](/publishers/offers-api/reference/offer-completed-webhook#the-request-encore-sends).
> [!TIP]
>
> Three details are easy to get wrong, and all three are security- or correctness-relevant: use the **raw body**, use **`crypto.timingSafeEqual`** rather than `===`, and enforce a **timestamp freshness window** so a captured delivery can't be replayed at you later.
## Design for the guarantees
Encore retries a failed delivery up to five times over roughly nine hours, with a 5-second timeout per attempt and no ordering guarantee ([full table](/publishers/offers-api/reference/offer-completed-webhook#the-response-encore-expects)). Three consequences worth designing for:
1. **Commit everything the delivery records before you return `2xx`.** That is the user's credit and, if you keep one, the payment record for its `actionId`; on a later paid action the credit is already a no-op, but the payment record is still new. Your `2xx` is what tells Encore the delivery landed, and it is what stops the retries. Acknowledge on receipt and write afterwards, and any failure in that later step loses the credit or the payment with no signal to us and no retry. If the credit is genuinely too slow for the 5-second budget, write it to your own durable queue inside the request and treat that write as the commit.
2. **Handle duplicates idempotently.** Credit the user once per `transactionId`: record credited ids and make a second credit for the same id a no-op. A user can have several transactions, so the transaction is the unit, not the user. A multi-step offer can send one delivery per paid action, all with the same `transactionId` and each with its own `actionId`, so to record each payment, key on `transactionId` plus `actionId` (or `transactionId` alone when `actionId` is absent).
3. **Reconcile anything financial.** Retries narrow the gap but do not close it: a delivery can still exhaust its attempts if your endpoint is down for the whole window. **Do not treat this webhook as your ledger.** Reconcile periodically against your Encore dashboard analytics.
## Payout updates
If you turn on payout updates, the same URL can also receive [`offer_payout_booked`](/publishers/offers-api/reference/offer-payout-booked-webhook): the USD payout Encore booked for a paying action it already reported to you, usually a transaction that verified at `payout: 0` because the advertiser priced it in another currency. Usually you already have that `offer_completed`. It is never a completion. A paying action Encore never sent an `offer_completed` for gets no `offer_payout_booked`: its first `offer_completed` carries the booked figure, and your handler credits it as any other completion. Switch on `event` before anything else, as the preceding handler does, send `offer_payout_booked` to your payout records and never to your credit logic, and let its `payout` win over the earlier `offer_completed` figure for the same `transactionId` plus `actionId`, whichever arrives first. It is off until you ask Encore support to turn it on.
## Testing locally
The SSRF guard refuses private addresses, so `http://localhost:3000` can never be a webhook URL, including for test deliveries. Expose your local server through a tunnel with a public HTTPS hostname (ngrok, Cloudflare Tunnel, Tailscale Funnel), point the webhook at the tunnel URL, and use **Send Test**. On the demo campaign, a test-conversion call from your own integration simulates the advertiser postback, so you can exercise the full flow without a live advertiser.
## Troubleshooting
> [accordion] Signature never matches
>
> Almost always a body-bytes problem. Verify against the **raw** request body, not `JSON.stringify(req.body)`. Also confirm you're joining timestamp and body with a literal dot, hex-encoding (not base64), using the header timestamp rather than your own clock, and using the current secret if you recently rotated it.
> [accordion] Send Test reports a timeout or connection error
>
> A timeout means your endpoint took longer than 5 seconds: return `2xx` as soon as the signature verifies. A connection error means the URL isn't HTTPS, the host isn't publicly resolvable (use a tunnel), or the path redirects (redirects are rejected, not followed). **Send Test** is a single attempt and is never retried, unlike a real completion.
> [accordion] No events arriving in production
>
> Confirm the status toggle is enabled, and remember the event fires on **verified** completions, driven by the advertiser, not by claims. Run **Send Test** first to isolate reachability from event volume.
> [accordion] A completion appears in the dashboard but no webhook arrived
>
> Check whether it is still in flight before treating it as lost: a failed attempt is retried at +5 min, +10 min, +30 min, +2 hours and +6 hours, so a delivery can be up to roughly nine hours behind the dashboard. If nothing has arrived after that, every attempt failed (endpoint down, non-2xx, timeout, TLS error) and the delivery was abandoned. Abandoned deliveries are not self-serve replayable, so reconcile from dashboard analytics and contact support if you need the event resent.
## Related
* [offer\_completed webhook reference](/publishers/offers-api/reference/offer-completed-webhook): the payload contract, signature spec, and delivery guarantees.
* [offer\_payout\_booked webhook reference](/publishers/offers-api/reference/offer-payout-booked-webhook): payout updates, never a reward.
# GET /entitlements/server
Source: https://docs.encorekit.com/publishers/offers-api/reference/entitlements-server
Endpoint contract for GET /entitlements/server: verify a user's entitlements from your backend, over HMAC-signed server-to-server auth.
Returns one user's accumulated entitlements, split into verified and provisional, so your
server can decide what to unlock. This is the pull counterpart to the
[Offer Completed webhook](/publishers/offers-api/reference/offer-completed-webhook): the
webhook pushes each completion to you as it verifies, this endpoint answers "what does
this user hold right now" on demand. It is the one server-to-server read an API
integration needs, because entitlements are server-authoritative: never gate real access
on anything a client reports.
```http theme={null}
GET https://api.encorekit.com/encore/publisher/sdk/v1/entitlements/server?userId=user-123
```
## Authentication
Unlike the offer endpoints, this endpoint is HMAC-signed. Three headers are required,
plus `X-Platform` for multi-app projects:
| Header | Value |
| - | - |
| `X-API-Key` | Your publishable key (`pk_live_*` / `pk_test_*`). |
| `X-Signature` | Hex HMAC-SHA256 of the base string, keyed with the secret key that pairs with your publishable key in the [dashboard](https://dashboard.encorekit.com). |
| `X-Timestamp` | Unix timestamp in seconds. Part of what you sign; the server rejects a skew over 5 minutes. |
| `X-Platform` | Multi-app projects only, same rule as the [overview's Authentication section](/publishers/offers-api/overview#authentication). |
The base string is `timestamp.METHOD.path.query`, and two details cause most signature
failures:
* **The path you sign is not the URL you call.** Encore's gateway strips the `/encore`
prefix before the API sees the request, so you call
`/encore/publisher/sdk/v1/entitlements/server` but sign
`/publisher/sdk/v1/entitlements/server`. Signing the public path is a silent `401`.
* **A GET signs a canonical query string, not a body.** Sort the parameters by key,
URI-encode each key and value, and join with `&`. This endpoint has one parameter, so
the canonical string is just `userId=...`, encoded.
```javascript theme={null}
// Backend (Node). Verify the entitlement server-to-server before you unlock.
import crypto from 'node:crypto';
const method = 'GET';
const path = '/publisher/sdk/v1/entitlements/server'; // the signed path: no /encore
const query = `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}`, {
method,
headers: {
'X-API-Key': process.env.ENCORE_PUBLISHABLE_KEY, // pk_live_...
'X-Signature': signature,
'X-Timestamp': timestamp,
'X-Platform': 'api', // multi-app projects only
},
});
if (!res.ok) return; // 401 = bad signature, stale timestamp, or an unresolvable key
const { verified, provisional } = await res.json();
```
## Request
| Parameter | Type | Required | Description |
| - | - | - | - |
| `userId` | string | Yes | The end-user identifier your integration uses everywhere else: the `userId` you send on offer requests, and the `userId` the webhook echoes back. |
## Response
```typescript theme={null}
interface EntitlementsResponse {
success: boolean;
provisional: EntitlementDetails; // temporary, granted at claim time, awaiting verification
verified: EntitlementDetails; // permanent, earned through a verified completion
all: EntitlementDetails; // verified + provisional combined
executionTimeMs: number;
}
interface EntitlementDetails {
freeTrial?: { startedAt: string | null; expiresAt: string | null };
discounts?: Array<{ value: number; unit: 'percent' | 'dollars'; expiresAt: string | null }>;
credits?: { totalAmount: number; expiresAt: string | null };
}
```
Gate real access on **`verified`**. `provisional` exists for the immediate unlock a
client shows while the brand-side completion is still unverified; treat it as a UX
courtesy, never as proof. Timestamps are ISO 8601 and nullable.
## Status codes
| Code | Meaning |
| - | - |
| `200` | Success. A user with no entitlements returns the same shape with empty detail objects, never a 404. |
| `401` | Signature does not verify, `X-Timestamp` skew over 5 minutes, or the key does not resolve. Recompute the signature against the signed path, not the public URL. |
| `5xx` | Encore-side failure. Retry with backoff. |
## Related
* [Offer Completed Webhook](/publishers/offers-api/reference/offer-completed-webhook): the push counterpart, delivered as each completion verifies.
* [Receive Completion Events](/publishers/offers-api/guides/receive-completion-events): wiring the webhook end to end.
# offer_completed webhook
Source: https://docs.encorekit.com/publishers/offers-api/reference/offer-completed-webhook
Payload contract for the offer_completed webhook: the HTTPS POST Encore sends to your server when a completion is verified.
An outbound webhook is an endpoint **you** implement: this page is the contract of the request Encore sends when one of your users' offer completions is verified, the response Encore expects back, and the delivery semantics.
> [!NOTE]
>
> For wiring it up (dashboard setup, a runnable signature-verification handler, idempotency, and reconciliation), see the [Receive Completion Events guide](/publishers/offers-api/guides/receive-completion-events). For the *inbound* direction (you forward your own billing's subscription events into Encore), see [Webhook Ingestion](/publishers/web/sdk-reference/webhook-ingestion): an unrelated flow with different headers and signing.
## The request Encore sends
`POST`ed to the URL you configure at the moment a transaction is marked **verified** (driven by the advertiser's conversion postback, not by the user tapping or claiming). It is the only event that credits a user. If you turn on payout updates, Encore can also send [`offer_payout_booked`](/publishers/offers-api/reference/offer-payout-booked-webhook) to the same URL, which never credits one.
```http theme={null}
POST /webhooks/encore HTTP/1.1
Content-Type: application/json
X-Webhook-Signature: 5a4f2e8c1b3d9e7f6a0c8b2d4e6f1a3c5b7d9e0f...
X-Webhook-Timestamp: 1772044200
X-Webhook-Delivery-Id: d290f1ee-6c54-4b01-90e6-d701748f0851
X-Webhook-Attempt: 1
```
### Headers
| Header | Value |
| - | - |
| `Content-Type` | Always `application/json`. |
| `X-Webhook-Signature` | Hex-encoded HMAC-SHA256 over the [signature base string](#signature), keyed by your app's signing secret (`whsec_...`). |
| `X-Webhook-Timestamp` | Unix time in **seconds** at the moment Encore signed. This value goes into the signature base string; use it for a freshness check. Every retry is signed afresh, so this moves between attempts of the same delivery. |
| `X-Webhook-Delivery-Id` | UUID for this delivery, stable across every retry attempt. For correlating attempts in your logs and in support requests. |
| `X-Webhook-Attempt` | Which attempt this is, `1` through `6`. |
### Body
```json theme={null}
{
"event": "offer_completed",
"timestamp": "2026-02-25T18:30:00.000Z",
"transactionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"userId": "usr_9f8e7d6c-5b4a-3210-fedc-ba0987654321",
"campaignId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"campaignName": "Audible Premium Plus",
"payout": 10,
"reward": { "amount": 200, "unit": "tokens" },
"actionId": "3f2b8c1e-9d4a-4e7b-8a6f-1c2d3e4f5a6b"
}
```
| Field | Type | Description |
| - | - | - |
| `event` | string | Always `"offer_completed"` on this event. Switch on it: the same URL can also receive [`offer_payout_booked`](/publishers/offers-api/reference/offer-payout-booked-webhook) if you turn payout updates on, and that one must never credit a reward. |
| `timestamp` | ISO 8601 string | UTC, milliseconds, trailing `Z`: when Encore generated this delivery. A *different format* from the `X-Webhook-Timestamp` header (Unix seconds); the header is the one you sign and check for freshness. |
| `transactionId` | string (UUID) | The Encore transaction that completed. **Credit the user once per `transactionId`.** To record each paid action of a multi-step offer, key on `transactionId` plus `actionId`, or on `transactionId` alone when `actionId` is absent. |
| `userId` | string | The end-user identifier **as your app supplied it, verbatim**: the value you passed to `identify()` or as `userId` on an Encore API call. Encore stores it opaquely and echoes it back unchanged, so it's the key you look the user up by. If you never supplied an id, this is the SDK's anonymous per-device id. |
| `campaignId` | string (UUID) | **Stable identifier of the offer the user completed**, and the field you join a completion back to the offer you served. It is the same value returned as `offers[].campaignId` by [`POST /offers/feed`](/publishers/offers-api/reference/feed) and as `offers[].id` by [`POST /offers/catalog`](/publishers/offers-api/reference/catalog). Unaffected by renames, locales, and creative rotation. |
| `campaignName` | string | Human-readable name of the campaign the user completed. A display/logging value, **not a stable identifier**: campaign names are editable, are never translated, and are unrelated to the `title` returned by `/offers/feed` (which is the creative headline and *is* translated). Match on `campaignId`, not on either name. |
| `payout` | number \| `null` | The payout amount associated with this completion, when one was reported. **`null` is normal and common**: several completion paths carry no amount at delivery time, so code for `null` rather than treating it as an error. No currency field is delivered. A `0` can mean the advertiser priced the conversion in another currency; if you turn on payout updates, [`offer_payout_booked`](/publishers/offers-api/reference/offer-payout-booked-webhook) later sends its booked USD figure. Treat your dashboard analytics, not this field, as the source of truth for revenue. |
| `reward` | object \| `null` | What to credit the user, in your app's own currency, when your app gives each offer its own value: `{ "amount": integer, "unit": string }`. Per-offer values are turned on per app in the Encore portal, under **Settings**, in the **Rewards** section, where you also set the unit name ([how values are set](/publishers/guides/reward-for-trying#show-each-offers-own-value)). `amount` is a whole number from 0 to 2,147,483,647, and `unit` is the singular or plural unit name from your settings, matching the amount. Always present, and `null` when the transaction carries no value: per-offer values are off, the offer had no value, or the claim didn't come from a sheet that shows a per-offer reward (today, reward for trying). That last case covers a claim from another sheet, from an SDK before 2.3.1, from the Web SDK or the hosted `/offers` page, and through a click-through link or a redemption. A re-claim from such a source before the brand confirms clears an earlier value, because the latest sheet decides. The value was frozen on the transaction when the user claimed, so it's the number the card showed, never recomputed, and the same on every delivery for one `transactionId`. **When your app pays from the webhook, credit it once per `transactionId`.** If your app already paid this prize on the device from `userConfirmedCompletion`, don't credit it again here: pay each offer from one place, never both. Encore sends no event to take a reward back. |
| `actionId` | string (UUID) | Omitted when absent. Identifies the paying action this delivery reports, when the completion came from an advertiser conversion. A multi-step offer can pay more than once for one transaction: each paid action sends its own delivery, with the same `transactionId`, its own `actionId`, and its own `payout`. Retries of one delivery repeat its `actionId`. To count each payment, key on `transactionId` plus `actionId`, or on `transactionId` alone when `actionId` is absent; to credit the user, key on `transactionId` alone. |
| `test` | boolean | Present only on a test delivery sent from the portal, and always `true` there. Never sent on a real completion. When it is present, verify the signature and return `2xx`, but don't credit anyone. |
> [!NOTE]
>
> **That's the whole body.** The body is exactly the top-level fields in the table, with no app id, creative id, or event id. Only `reward` is an object; every other field is a plain value. `actionId` appears only when it has a value, and `test` only on a test delivery, so a handler must not require either. A handler written against a nested `req.body.data` won't work; read the fields off the top level. The `usr_...` shape above is only a placeholder from the test-delivery sample; Encore mints no user ids and adds no prefix.
## Signature
The signature base string is the timestamp header and the **raw request body**, joined by a single dot:
```
.
```
HMAC-SHA256 that string with your `whsec_...` signing secret and hex-encode it. The result must equal `X-Webhook-Signature`. Verify against the exact bytes Encore sent, not a re-serialization; a runnable handler is in the [guide](/publishers/offers-api/guides/receive-completion-events#verify-the-signature).
## The response Encore expects
Return any `2xx` within **5 seconds**. Anything else fails that attempt and Encore retries it.
| Behaviour | What happens |
| - | - |
| **Retries** | Up to **5 retries** after the first attempt, at +5 min, +10 min, +30 min, +2 hours and +6 hours. A delivery that has still not succeeded 8 hours 45 minutes after the conversion is abandoned. |
| **Timeout** | 5 seconds per attempt. A slower response fails that attempt and is retried. |
| **Non-2xx response** | Retried on the schedule above, `4xx` included. Every attempt and its status code is recorded. |
| **Redirects** | Deliveries are sent with redirects disabled; a `301`/`302` fails the attempt. Publish the final URL. |
| **Request body** | Byte-identical on every attempt. Only `X-Webhook-Timestamp` and the signature over it are recomputed, so verify each attempt against the timestamp it arrived with. |
| **Webhook disabled or deleted** | Nothing new is sent. Retries already in flight stop, and nothing is backfilled when you re-enable it. |
| **Ordering** | Not guaranteed, and retries make interleaving more likely. |
| **Event id** | `X-Webhook-Delivery-Id`, stable across attempts, for correlation only. Key on the body instead: `transactionId` for the user's credit, and `transactionId` plus `actionId` for each payment (`transactionId` alone when `actionId` is absent). |
### Delivery is at-least-once
A conversion may arrive more than once, including a delivery your system already processed. A timeout or a missing response tells us nothing about whether your side completed the work, so we retry. Two things protect you, and they cover opposite failures:
1. **Required: credit the user once per `transactionId`.** Take it from the signed request body. Every retry carries the same value, and so does every paid action of a multi-step offer. To record each payment rather than each credit, key on `transactionId` plus `actionId`, or on `transactionId` alone when `actionId` is absent; retries of one delivery repeat both. Do not key on `X-Webhook-Delivery-Id` or `X-Webhook-Attempt`. Both sit outside the [signature base string](#signature) and are not authenticated.
2. **Recommended: return `2xx` only once everything the delivery records is durably committed**, not on receipt. That is the user's credit and, if you keep one, the payment record for its `actionId`. On a later paid action the credit is already a no-op, so the payment record is the only work left to commit. If you acknowledge first and write asynchronously, a failure in that async step is invisible to us: we will not retry, because you already returned `2xx`, and the credit or the payment is silently lost.
## URL requirements
| Requirement | Why |
| - | - |
| **HTTPS** | Plain `http://` URLs are rejected. Payloads carry user identifiers. |
| **Publicly resolvable host** | An SSRF guard resolves the hostname before every delivery and refuses `localhost` plus private, loopback, and link-local addresses, including a public hostname that *resolves* to one. |
| **No redirects** | Deliveries are sent with redirects disabled. |
## Related
* [Receive Completion Events guide](/publishers/offers-api/guides/receive-completion-events): setup, verification handler, idempotency, reconciliation, local testing.
* [offer\_payout\_booked webhook reference](/publishers/offers-api/reference/offer-payout-booked-webhook): a corrected payout for a completion already sent, never a reward.
* [Webhook Ingestion](/publishers/web/sdk-reference/webhook-ingestion): the inbound direction, for forwarding your own subscription events into Encore.
# offer_payout_booked webhook
Source: https://docs.encorekit.com/publishers/offers-api/reference/offer-payout-booked-webhook
Payload contract for the offer_payout_booked webhook: the USD payout Encore booked for a paying action it already reported, usually one that verified at $0; never a new completion or a reward.
When the conversion that verifies a transaction is priced in a currency other than USD, Encore does not convert it automatically: the [`offer_completed`](/publishers/offers-api/reference/offer-completed-webhook) it sends carries `payout: 0`. When Encore later books the conversion at a USD figure, it can send you `offer_payout_booked`: that figure, for the same `transactionId` and paying action. The same event reports a booking for any other paying action Encore already sent an `offer_completed` for. A paying action Encore never sent an `offer_completed` for gets no `offer_payout_booked`: its first `offer_completed` carries the booked figure instead.
> [!WARNING]
>
> **Never credit a reward on this event.** Credit only on `offer_completed`, once per `transactionId`. This event only corrects a payout figure. A handler that credits on every request without reading `event` would pay the user twice, which is why this event is off until you ask for it.
## Turning it on
Encore sends it only to a webhook subscribed to it. Every webhook starts subscribed to `offer_completed` only. To subscribe, confirm to Encore support that your handler switches on `event` and never credits on `offer_payout_booked`, and ask for payout updates on your app. Without the subscription, Encore still books the figure; only the notice to your server is skipped.
To unsubscribe, ask Encore support. Payout updates still waiting for a retry are then dropped. An `offer_completed` is never dropped this way.
Deleting and re-creating your webhook also unsubscribes it: the new webhook starts at `offer_completed` only, and queued payout updates are dropped until you ask to subscribe again.
## When Encore sends it
When Encore books a USD figure for a conversion priced in another currency, what your webhook receives depends on which conversion it is:
| Conversion booked | Subscribed webhook | Webhook not subscribed |
| - | - | - |
| The one the transaction verified on at `payout: 0`, or any other paying action Encore already sent an `offer_completed` for | `offer_payout_booked` | Nothing |
| A paying action Encore never sent an `offer_completed` for | `offer_completed` with the booked figure, its first notice | `offer_completed` with the booked figure, its first notice |
The conversion the transaction verified on always counts as already sent, so Encore never sends a late first `offer_completed` for it, even if your webhook did not exist or was turned off when it verified. If your app has no webhook, or it is turned off, when the figure is booked, Encore sends nothing.
## The request Encore sends
Same URL, headers, signature and delivery guarantees as [`offer_completed`](/publishers/offers-api/reference/offer-completed-webhook#the-request-encore-sends): an HMAC-SHA256 signature over `.`, and the same `2xx` deadline and retry schedule.
```json theme={null}
{
"event": "offer_payout_booked",
"timestamp": "2026-10-20T14:03:11.000Z",
"transactionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"userId": "usr_9f8e7d6c-5b4a-3210-fedc-ba0987654321",
"campaignId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"campaignName": "Audible Premium Plus",
"actionId": "3f2b8c1e-9d4a-4e7b-8a6f-1c2d3e4f5a6b",
"payout": 32.55,
"payoutCurrency": "USD",
"previousPayout": 0,
"bookedAt": "2026-10-20T14:03:10.412Z"
}
```
| Field | Type | Description |
| - | - | - |
| `event` | string | Always `"offer_payout_booked"`. |
| `timestamp` | ISO 8601 string | UTC, milliseconds, trailing `Z`: when Encore generated this delivery, as on `offer_completed`. |
| `transactionId` | string (UUID) | The transaction whose payout changed. |
| `userId` | string | The end-user identifier your app supplied, verbatim, as on `offer_completed`. |
| `campaignId` | string (UUID) | The offer, as on `offer_completed`. |
| `campaignName` | string | Display name of the campaign; not a stable identifier. |
| `actionId` | string (UUID) | The paying action whose payout changed. Always present on this event. If the earlier `offer_completed` for it carried an `actionId`, this is the same value; an `offer_completed` sent without one was for this action. |
| `payout` | number | The booked payout, in USD. |
| `payoutCurrency` | string | Always `"USD"`. |
| `previousPayout` | number | The payout the earlier `offer_completed` for this action carried: `0` when the transaction verified on a conversion priced in another currency (the usual case). Also `0` when that delivery carried `null`, or when Encore never sent one for the action the transaction verified on. |
| `bookedAt` | ISO 8601 string | When Encore booked the figure. |
There is no `reward` field: this event never carries one.
## What to do with it
1. **Switch on `event`.** Route `offer_payout_booked` to your payout records, never to your credit logic.
2. **Update the payout for `transactionId` plus `actionId`.** If you hold no `offer_completed` with this `actionId`, but hold one for this `transactionId` without an `actionId`, update that one. Use `(transactionId, actionId, event)` from the signed body to deduplicate. Do not key on `X-Webhook-Delivery-Id`, which sits outside the signature.
3. **The booked payout wins.** Ordering is not guaranteed: the earlier `offer_completed` for the same action can still be retrying when this arrives. For one `transactionId` plus `actionId`, keep this event's `payout` whichever arrives first, and never overwrite it with the `payout` of an `offer_completed` that arrives later. This event only reaches you for an action Encore already sent an `offer_completed` for, or the one the transaction verified on. For any other paying action, the booked figure arrives as that action's first `offer_completed`, so do not wait for an `offer_payout_booked` there.
4. **A transaction you have no completion for:** this happens when the `offer_completed` never reached you, for example because your webhook did not exist or was turned off when the transaction verified, or your endpoint was down for the whole retry window. Record the payout and reconcile from your dashboard. Still never credit a reward.
## Related
* [offer\_completed webhook reference](/publishers/offers-api/reference/offer-completed-webhook): the completion event, its signature, and its guarantees.
* [Receive Completion Events guide](/publishers/offers-api/guides/receive-completion-events): verification handler, idempotency, reconciliation.
# POST /users/attributes
Source: https://docs.encorekit.com/publishers/offers-api/reference/user-attributes
Endpoint contract for POST /users/attributes: store targeting attributes against a user for later offer requests.
Stores a set of targeting attributes against one user so later offer requests are targeted on them without the values traveling in a link. Your [hosted offer page](/publishers/web/guides/hosted-offer-page) URL then carries no attributes at all, just `apiKey`, `userId`, and whichever presentation parameters you use.
```http theme={null}
POST https://api.encorekit.com/encore/publisher/sdk/v1/users/attributes
```
> [!NOTE]
>
> Call it before you open the offer page for a user, or ahead of your [`POST /offers/feed`](/publishers/offers-api/reference/feed), and again whenever what you know about that user changes. To attach attributes to a single request instead of storing them, put them in that request's own `attributes` object: a request attribute always wins over the stored one.
## Authentication
Pass your publishable key in the `X-API-Key` header (`pk_live_*` for production, `pk_test_*` for development). This is the same guard [`POST /offers/feed`](/publishers/offers-api/reference/feed#authentication) uses, so no new credential is involved. Multi-app projects also send `X-Platform`.
> [!WARNING]
>
> **Store against the app that serves the offers.** The set is keyed on the app your key resolves plus `userId`, so a set stored against one app in a multi-app project is invisible to another. The hosted offer page runs the Web SDK, which sends `X-Platform: web`, so a multi-app project storing attributes for that page sends `X-Platform: web` here too.
## How the stored set is used
* **Each call replaces the last one.** The write is idempotent on the app plus `userId`, and the newest set is the whole truth. Attributes are never merged into what was stored before, so send the complete set every time.
* **There is no expiry.** The last set stays authoritative until a newer one arrives, and a data-subject erasure request removes it.
* **A request attribute always wins.** [`POST /offers/feed`](/publishers/offers-api/reference/feed), and the `POST /offers/search` call the Web SDK makes on your behalf, read the stored set only to fill an attribute the request itself omitted. [`POST /offers/catalog`](/publishers/offers-api/reference/catalog) and [`POST /offers/message`](/publishers/offers-api/reference/message) do not read it.
* **Storing an attribute never makes it optional on a request.** `/offers/feed` still requires `countryCode` and `language` in its own body, and rejects a request that omits them before the stored set is read. What the store fills on that endpoint is everything else.
* **The user does not have to exist yet.** The first call for a `userId` creates the user, so there is no ordering requirement against any other endpoint.
## Request
### Structure
```typescript theme={null}
interface StoreUserAttributesRequest {
userId: string; // required: the same end-user id your offer requests use
attributes: { // required: replaces any previously stored set
// Accepted from any app
countryCode?: string; // ISO 3166-1 alpha-2, two uppercase letters
language?: string; // ignored: send the language per request
city?: string;
state?: string;
region?: string;
subscriptionTier?: string;
monthsSubscribed?: string;
billingCycle?: string;
lastPaymentAmount?: string;
lastActiveDate?: string;
totalSessions?: string;
custom?: Record;
age?: number; // whole years, integer 0-120; see Sending an age
// Accepted only from an app declared adults_only
email?: string;
firstName?: string;
lastName?: string;
mobile?: string;
phoneNumber?: string;
postalCode?: string; // prefer this spelling
postcode?: string; // a separate key, not an alias
latitude?: string; // decimal degrees as a string
longitude?: string; // decimal degrees as a string
gender?: string;
};
}
```
### Field Reference
| Field | Type | Required | Description |
| - | - | - | - |
| `userId` | string | Yes | Your stable end-user identifier, the same one your offer requests and your offer page URL carry. It is the key the stored set is filed under. |
| `attributes` | object | Yes | The complete set to store. **Replaces** any set stored earlier for this user. An empty object is valid and clears the stored set. |
| `attributes.countryCode` | string | No | ISO 3166-1 alpha-2, two uppercase letters (for example `"US"`, `"GB"`, `"CA"`). Drives geo-targeting and the country dimension on analytics. |
| `attributes.language` | string | No | **Ignored.** Accepted so existing callers keep working, but Encore no longer stores a user's language. Send the language on each request instead: `attributes.language` on `/offers/feed`, `/offers/message`, and `/offers/search`, or `language` on `/offers/catalog`. See [Localization](/publishers/concepts/localization). |
| `attributes.city` | string | No | Coarse geography, accepted from any app. |
| `attributes.state` | string | No | Coarse geography, accepted from any app. |
| `attributes.region` | string | No | Coarse geography, accepted from any app. |
| `attributes.subscriptionTier` | string | No | Your own tier label (for example `"premium"`). |
| `attributes.monthsSubscribed` | string | No | Months the user has been subscribed, as a string. |
| `attributes.billingCycle` | string | No | Your own cycle label (for example `"annual"`). |
| `attributes.lastPaymentAmount` | string | No | Last payment amount, as a string. |
| `attributes.lastActiveDate` | string | No | ISO 8601 datetime the user was last active (for example `2024-03-15T14:30:00Z`). |
| `attributes.totalSessions` | string | No | Session count, as a string. |
| `attributes.custom` | object | No | Free-form string map for app-specific values (for example `{ "plan": "gold" }`). Values are strings. |
| `attributes.age` | integer | No | Whole years, `0` to `120`. Accepted from **any** app. Read [Sending an age](#sending-an-age) and [What is stored for a user under 18](#what-is-stored-for-a-user-under-18) before you send it: the range rule and what an under-18 age does are both easy to get wrong. |
| `attributes.email` | string | No | **Adults-only apps only.** See [Attributes that need an adults-only app](#attributes-that-need-an-adults-only-app). |
| `attributes.firstName` | string | No | **Adults-only apps only.** |
| `attributes.lastName` | string | No | **Adults-only apps only.** |
| `attributes.mobile` | string | No | **Adults-only apps only.** |
| `attributes.phoneNumber` | string | No | **Adults-only apps only.** |
| `attributes.postalCode` | string | No | **Adults-only apps only.** Precise location, unlike `city` and `state`. **Prefer this one:** it is the spelling every Encore SDK and the offer page URL use. |
| `attributes.postcode` | string | No | **Adults-only apps only.** A separate key, not an alias of `postalCode`, and stored under its own name. Accepted for callers whose own schema uses this spelling. Send one or the other, not both. |
| `attributes.latitude` | string | No | **Adults-only apps only.** Decimal degrees as a string (for example `"37.7749"`). |
| `attributes.longitude` | string | No | **Adults-only apps only.** Decimal degrees as a string (for example `"-122.4194"`). |
| `attributes.gender` | string | No | **Adults-only apps only.** |
### Sending an age
`age` is an integer count of whole years. It is accepted from every app, whatever that app's audience declaration says, because it is what narrows which offers a user may be shown rather than something that identifies them.
> [!WARNING]
>
> **If you hold only a range, send its lowest end.** `"13-17"` is sent as `13`, never `15` and never `17`. Sending the middle of a range defeats the check silently: flooring can never mask a minor, and a midpoint can.
**An age under 18 does not switch offers off.** That user is still served. What changes is that the offers come from age-appropriate inventory only, ranked by the app-level bandit, with no per-user personalization. The response reports `minor: true` so you can see which branch a user took.
The instant you sent the set is recorded, and the age acted on is counted forward from it. A user stored at 17 becomes an adult on schedule rather than staying 17 forever. Counting forward is a cautious fallback, since Encore cannot know the birthday: keep the age current by sending the user's age as it is now each time.
Send `age`, never a date of birth. `dateOfBirth` is refused here: an age carries the same targeting value with far less identifying power. The SDKs do take a `dateOfBirth`, but they turn it into an age on the device and send only that, so the date never reaches Encore.
### What is stored for a user under 18
Only `age` and `countryCode` are kept. Everything else you sent is discarded, `custom` included, along with `city`, `state`, `region`, and every subscription and billing field.
Those two survive because of what they do. `age` narrows which offers the user may be shown, and `countryCode` decides where an offer may legally appear. Neither chooses an advertiser. Everything else exists to personalize the pick, and personalization is withheld for this user, so storing it would keep data that can never be acted on.
> [!WARNING]
>
> **This is silent, and it is not an error.** The call returns `200`, and the only sign is `minor: true` in the response. Send `subscriptionTier` for a 16-year-old and you get success, no warning, and no `subscriptionTier` in the stored set afterwards.
It is decided per request, from the age that request carried, so this is not a separate integration to build. The same set sent for an adult is stored whole. Once a user is 18, re-send their set and it is stored in full.
### Attributes that need an adults-only app
`email`, `firstName`, `lastName`, `mobile`, `phoneNumber`, `postcode`, `postalCode`, `latitude`, `longitude`, and `gender` are accepted only from an app whose audience is declared `adults_only`, meaning it is rated 18+ in its store listing. Every other status is refused with a `400`, including the default status an app carries before anyone has declared its audience.
The refusal names the keys it rejected and stores nothing at all, not even the attributes that would have been allowed:
```json theme={null}
{
"error": "These attributes are accepted only from an app rated 18+ in its store listing: email, gender. This app's child_audience_status is \"unknown\", not \"adults_only\". Re-send without them, or have the app's audience declaration corrected first."
}
```
Re-send without those keys, or have the app's audience declaration corrected in the [dashboard](https://dashboard.encorekit.com) first.
Neither `postalCode` nor `postcode` reaches offer selection today, so an app that cannot send them loses no targeting by leaving them out.
### Attributes that are refused
| Key | Why |
| - | - |
| `dateOfBirth` | Refused from every app, including adults-only ones. Send `age` instead. |
| `interests` | Not part of this vocabulary. There is no substitute key. |
| Anything else | Any key not listed in [Field Reference](#field-reference) is refused rather than ignored, so a typo surfaces as a `400` instead of as targeting that quietly does less. |
## Response
### Structure
```typescript theme={null}
interface StoreUserAttributesResponse {
success: true;
userId: string; // canonical user UUID, not the id you sent
storedAt: string; // ISO 8601 instant the set was recorded
minor: boolean; // true when the age you sent was under 18
}
```
### Field Reference
| Field | Type | Description |
| - | - | - |
| `success` | `true` | Always `true` on a 200. Non-success outcomes come back as 4xx/5xx; see [Status codes](#status-codes). |
| `userId` | UUID | Encore's canonical user id, which is **not** the `userId` you sent. Keep using your own id on every other endpoint. |
| `storedAt` | string | ISO 8601 instant the set was recorded. This is what a stored `age` is counted forward from. |
| `minor` | boolean | `true` when the `age` you sent was under 18, `false` otherwise (including when you sent no age). **Offers are still served either way.** A `true` means this user was served from age-appropriate inventory and that only three attributes were kept from the set you sent. See [What is stored for a user under 18](#what-is-stored-for-a-user-under-18). |
## Example
```bash theme={null}
curl --location --request POST 'https://api.encorekit.com/encore/publisher/sdk/v1/users/attributes' \
--header 'X-API-Key: YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{
"userId": "user-123",
"attributes": {
"countryCode": "US",
"subscriptionTier": "gold",
"monthsSubscribed": "14",
"age": 34,
"custom": { "machine": "kiosk-4471" }
}
}'
```
```json theme={null}
{
"success": true,
"userId": "550e8400-e29b-41d4-a716-446655440000",
"storedAt": "2026-09-02T10:14:07.412Z",
"minor": false
}
```
## Status codes
| Code | Meaning |
| - | - |
| `200` | The set was stored and replaces any previous one. |
| `400` | A gated key from an app that is not `adults_only`, a refused or unrecognized key, an `age` that is not a whole number between `0` and `120`, or a missing `userId`. Nothing was stored. Don't retry; fix the request. The gate returns the sentence shown under [Attributes that need an adults-only app](#attributes-that-need-an-adults-only-app); a schema failure returns the offending field in `details` instead. Both are `{ error, details? }`. |
| `401` | Missing or invalid `X-API-Key`, or an `X-Platform` value your project has no app for. |
| `503` | Server temporarily over capacity. Retry with backoff. |
| `5xx` (other) | Encore-side failure. |
### Retry guidance
* **Retrying is safe, but only useful for some failures.** The call is an idempotent replace, so sending the same set twice leaves exactly the state one call would have. This is unlike the offer-selection endpoints, where each call mints fresh links and analytics rows. A `400` or `401` is deterministic, so repeating it produces the same refusal: fix the request instead.
* Use exponential backoff with jitter (for example 200 ms, 1 s, 5 s, max 3 retries) for transient failures (503 / network).
* After exhausting retries, open the offer page anyway. A user with no stored set is served from what the request itself carries, so the worst case is less targeted, never nothing.
## Related
* [Hosted Offer Page](/publishers/web/guides/hosted-offer-page): the page these attributes target, and how to move off URL parameters.
# Add Subscription Product
Source: https://docs.encorekit.com/publishers/react-native/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 React Native 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
* [SDK Reference](../sdk-reference/configure): the complete API contract for the React Native SDK
# React Native Integration Patterns
Source: https://docs.encorekit.com/publishers/react-native/guides/integration-patterns
Where the purchase controller, the call site, and the outcomes stream each belong in a React Native 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 |
| :- | :- | :- |
| [Purchase controller](../sdk-reference/purchase-controller) | Runs a purchase when a user accepts an offer | Passed once to `configure()`, at the app root |
| [`show()`](../sdk-reference/placement) result | Drives control flow for *this* call site | At the call site, awaited |
| [`onOutcome`](../sdk-reference/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
One binding, at the root, as part of `configure()`. `EncoreProvider` forwards its `purchaseController` prop into the `configure()` call it makes on mount, so the provider prop and the option are the same binding.
```tsx theme={null}
import { EncoreProvider } from '@encorekit/react-native';
import type { PurchaseController } from '@encorekit/react-native';
const purchaseController: PurchaseController = async ({ productId, basePlanId }) => {
const outcome = await billing.purchase(productId, { basePlanId });
if (outcome.userCancelled) return 'cancelled';
if (outcome.deferred) return 'pending';
return 'purchased';
};
export default function App() {
return (
);
}
```
This is the shape that made the 1.x pair removable. In 1.x, `onPurchaseRequest` fired an event and you answered with a second call, `completePurchaseRequest(success)`; forgetting one code path left the SDK wedged, and the boolean could not express a deferred purchase at all. Now the answer is the return value, the bridge correlates requests by id, and there is nothing to forget.
> [!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, in the presentation record and everywhere downstream of it.
Registering none is a supported configuration: nothing is ever charged, and every presentation records `publisher: 'not_attempted'`.
***
## 2. Control flow at the call site
`show()` never rejects, so there is no `catch` to write and no case where your fallback silently fails to run.
```tsx theme={null}
function CancelScreen() {
const handleCancel = async () => {
const result = await Encore.placement('cancel_flow').show();
const converted =
result.status === 'presented' &&
(result.claim !== null || result.publisher === 'purchased');
if (converted) {
navigation.navigate('Home');
} else {
await proceedWithCancellation();
}
// Code that runs in both branches lives here, written once.
analytics.track('cancel_flow_resolved');
};
return ;
}
```
### When the call site 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, rather than handing the SDK a global callback:
```tsx theme={null}
async function presentThenContinue(placementId: string, onDeclined: () => Promise) {
const result = await Encore.placement(placementId).show();
const converted =
result.status === 'presented' &&
(result.claim !== null || result.publisher === '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
`onOutcome` appends, unlike the 1.x `on*` setters, which replaced the previous handler. Several observers can listen at once, matching the multicast streams both native SDKs expose.
```tsx theme={null}
function EncoreTelemetry() {
useEffect(
() =>
Encore.onOutcome((outcome) => {
if (outcome.type === 'presentation') {
analytics.track('encore_presentation', {
placementId: outcome.placementId,
result: outcome.result,
});
} else {
// strict_unlock_verified: entitlements already refreshed natively.
refreshEntitlements();
}
}),
[],
);
return null;
}
```
There is **no replay**: subscribe at startup, or you miss outcomes emitted before you subscribed. Mount this component inside `EncoreProvider`, above your navigator.
The stream is also the only way to see `strict_unlock_verified`, a strict-mode claim the server confirmed after its flow ended, possibly on a later launch. No `show()` return value can carry that.
***
## Reading the record
```tsx theme={null}
type PresentationResult =
| { status: 'not_presented'; reason: NotPresentedReason }
| {
status: 'presented';
advertiser: AdvertiserOutcome;
publisher: PublisherOutcome;
dismissal: DismissReason;
claim: ClaimedOffer | null;
};
```
Two funnels, recorded independently, because one presentation can do both. See [PresentationResult](../sdk-reference/presentation-result) for the full vocabulary of each axis.
> [!NOTE]
>
> `not_presented` is not a synonym for "something went wrong". It also covers `no_offer_available`, `experiment_control`, and `use_case_unavailable`, all of which are 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 branch.
***
## Platform-specific notes
* **The offer UI is native.** SwiftUI on iOS, Jetpack Compose on Android. The bridge triggers presentation and returns the record.
* **Some axis values are platform-specific.** `no_foreground` and `iap_first_declined` are Android-only; `unsupported_ios`, `user_cancelled`, `last_offer_declined`, and `dismissed` are iOS-only. Code written against the full union is portable.
* **Android's `Activity` is absorbed by the bridge**, not leaked to JavaScript. It has no JavaScript representation, and your billing library resolves the current Activity itself, so one controller contract covers both platforms.
* **`reset()` keeps the controller.** It is build-time wiring, not user state.
***
## See also
* [Quickstart: Present Offers](/publishers/react-native/quickstart/present-offers)
* [Updating to 2.x](./updating-to-2-x), if you are migrating an existing 1.x integration
* SDK Reference: [`placement()`](../sdk-reference/placement), [`PurchaseController`](../sdk-reference/purchase-controller), [`PresentationResult`](../sdk-reference/presentation-result), [`onOutcome()`](../sdk-reference/outcomes)
# Routine updates
Source: https://docs.encorekit.com/publishers/react-native/guides/updating-sdk
How to update the Encore React Native SDK and how its versioning works.
## Overview
The Encore React Native SDK is published as the public **`@encorekit/react-native`** package on [npm](https://www.npmjs.com/package/@encorekit/react-native). The package includes native bridges for both iOS and Android, so updating is a two-part flow: bump the npm package, then refresh the native iOS pods so the updated iOS SDK is picked up. Android is resolved automatically on the next build.
***
## 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.1.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:
```json theme={null}
"dependencies": {
"@encorekit/react-native": "^2.0.0"
}
```
The bridge pins the native SDKs it was built against, so a bridge update is also a native update on both platforms. That is why a bridge 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 installed version is recorded in `package.json` and locked in your lockfile (`package-lock.json` or `yarn.lock`). The latest published version is listed on the package's [npm page](https://www.npmjs.com/package/@encorekit/react-native).
You can also check from the command line:
```bash theme={null}
npm view @encorekit/react-native version
```
To see whether your project is behind:
```bash theme={null}
npm outdated @encorekit/react-native
```
***
## Update the package
**1. Update within your major version**
Install the newest release your constraint allows:
```bash npm theme={null}
npm update @encorekit/react-native
```
```bash yarn theme={null}
yarn upgrade @encorekit/react-native
```
**2. Refresh the native iOS pods**
Run `pod install` with `--repo-update` so CocoaPods fetches the newest spec and installs the updated native iOS dependency:
```bash theme={null}
cd ios && pod install --repo-update && cd ..
```
> [!NOTE]
>
> Android requires no separate step: React Native auto-links the updated native module, and Gradle resolves it automatically on your next build.
**3. Rebuild both platforms**
Build fresh so the updated JavaScript and native layers are compiled in:
```bash iOS theme={null}
npx react-native run-ios
```
```bash Android theme={null}
npx react-native run-android
```
***
## Verify the update
Confirm the installed version matches the latest release in your major:
```bash theme={null}
npm outdated @encorekit/react-native
```
***
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/react-native/guides/updating-to-2-x
Step-by-step migration guide for upgrading @encorekit/react-native from 1.x to 2.x.
## Overview
`@encorekit/react-native` 2.x tracks the native 2.0 SDKs (EncoreKit 2.0.0 on iOS, `com.encorekit:encore` 2.0.1 on Android). Both natives removed the global purchase and passthrough callbacks and replaced the placement result with a factual two-funnel record, so this is a breaking release of the bridge's public API:
* **Purchases run through a purchase controller you pass to `configure()`.** An async function returning `'purchased' | 'cancelled' | 'pending'`. The SDK never runs purchase code you didn't write.
* **`show()` never rejects.** Errors arrive as values on the result.
* **The result is a factual record**, not a single verdict: two independent funnels plus how the sheet ended.
* **Global `on*` setters are retired.** Control flow lives at the call site; passive observation moves to the `Encore.onOutcome` stream.
> [!WARNING]
>
> **There is no compatibility shim for `onPurchaseRequest`.** One could be written, since the old event maps onto the new controller, but the reply is now three-valued and the old `completePurchaseRequest(success: boolean)` has no way to say `'pending'`. A shim would have to guess, and every guess reports a deferred purchase (Ask to Buy, SCA) 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
```bash npm theme={null}
npm install @encorekit/react-native@^2.0.0
```
```bash yarn theme={null}
yarn add @encorekit/react-native@^2.0.0
```
Then refresh the native iOS pods and rebuild both platforms:
```bash theme={null}
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 typecheck. Run `npx tsc --noEmit`: the errors are your migration worklist, and each one corresponds to a step below. The [removed API table](#removed-apis-at-a-glance) maps every 1.x symbol to its replacement.
***
## Step 2: Move purchases to a purchase controller
This is the largest change. In 1.x, purchases ran through the `onPurchaseRequest` event and you acknowledged them with a second call, `completePurchaseRequest(success)`. 2.x replaces the pair with a single function, passed to `configure()`, whose **return value** is the answer.
**Before**
```tsx theme={null}
Encore.onPurchaseRequest(async ({ productId }) => {
try {
await Purchases.purchaseProduct(productId);
await Encore.completePurchaseRequest(true);
} catch {
await Encore.completePurchaseRequest(false);
}
});
```
**After**
```tsx theme={null}
import type { PurchaseController } from '@encorekit/react-native';
const purchaseController: PurchaseController = async ({ productId }) => {
const outcome = await RevenueCat.purchase(productId);
if (outcome.userCancelled) return 'cancelled';
if (outcome.deferred) return 'pending';
return 'purchased';
};
// or, outside React:
await Encore.configure('pk_...', { purchaseController });
```
Three things changed:
1. **The answer is a return value, not a second call.** The bridge correlates each request by id internally, so a late reply can no longer land on a live flow. Nothing is left to forget, and the SDK can no longer be wedged by a missing acknowledgement.
2. **The result is three-valued.** See [`pending` is not a failure](#pending-is-not-a-failure) below, which is the whole reason the 1.x pair was removed rather than shimmed.
3. **Throwing is meaningful.** A thrown error records `publisher: 'failed'` with your message, and the flow continues. Map your billing layer's "user cancelled" error to `'cancelled'` rather than letting it throw.
### `pending` is not a failure
`'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 webhook is the source of truth.
The 1.x boolean handler could not express this state at all, so every deferred purchase was reported as a failure. When you map your billing layer onto `PurchaseResult`, returning `'cancelled'` for a deferred purchase silently misreports revenue: a sale that is still in flight is recorded as a decline, in the presentation record and in every analytics surface downstream. Route the deferred branch of your billing library to `'pending'`.
### Where the controller goes
The controller is a [`configure()`](../sdk-reference/configure) option, matching every other Encore SDK. Binding it *is* configuring, so there is no window in which the SDK is configured and your purchase path is not. `EncoreProvider` forwards its `purchaseController` prop into that same call.
If the controller genuinely has to change at runtime, swap it with [`Encore.setPurchaseController()`](../sdk-reference/purchase-controller#replacing-the-controller).
Registering no controller is a supported configuration, not a broken one: the SDK never attempts a purchase, keeps its own `not_attempted` record and `sdk_iap_no_purchase_controller` diagnostic, and every presentation resolves `publisher: 'not_attempted'`.
***
## Step 3: Update `show()` call sites
`show()` no longer rejects. Presentation failures arrive as `{ status: 'not_presented', reason: { type: 'error', error } }` on the [`PresentationResult`](../sdk-reference/presentation-result), so `try`/`catch` blocks around it are dead code:
```tsx theme={null}
// 1.x
try {
const result = await Encore.placement('cancel_flow').show();
if (result.status === 'granted') unlock();
else runOriginalFlow();
} catch {
runOriginalFlow(); // often forgotten, causing a silent hang
}
// 2.0
const result = await Encore.placement('cancel_flow').show();
if (result.status === 'presented' && (result.claim !== null || result.publisher === 'purchased')) {
unlock();
} else {
runOriginalFlow();
}
```
The deprecated `Encore.show(placementId)` is removed; use the builder. `Encore.placements.setClaimEnabled(bool)` flattened to [`Encore.setClaimEnabled(bool)`](../sdk-reference/set-claim-enabled), because both natives deleted the 1.x placements manager.
***
## Step 4: Update result handling
1.x modeled the result as a flat `status` string, which forced a claim, a purchase, and a dismissal to compete for one winning value. 2.0 keeps them apart; see [`PresentationResult`](../sdk-reference/presentation-result) for the full shape.
**Before**
```tsx theme={null}
if (result.status === 'granted') grantAccess();
```
**After**
```tsx theme={null}
if (result.status === 'presented') {
const converted = result.claim !== null || result.publisher === 'purchased';
if (converted) grantAccess();
}
```
The record carries **raw facts only**. There is deliberately no SDK-computed `unlocked` boolean, because what a claim means is a property of the variant flow that served it, and an SDK verdict computed over app-global config could contradict the flow that actually ran. Branch on the raw axes.
| 1.x `status` | Closest 2.0 reading |
| :- | :- |
| `granted` | `status === 'presented' && claim !== null` |
| `claimed` | `status === 'presented' && claim !== null` |
| `completed` | `status === 'presented'`; read `advertiser` / `publisher` for what happened |
| `dismissed` | `status === 'presented'` with `claim === null` and `publisher === 'not_attempted'`; `dismissal` says how |
| `no_offers` | `status === 'not_presented'` with `reason.type === 'no_offer_available'` |
| `not_granted` | Depends on which of the above it stood for; read `reason` or the two funnels |
| `result.entitlement` | Removed. The 1.x result never carried it correctly across platforms; read entitlement state from your own store |
***
## Step 5: Replace global callbacks with the outcomes stream
`onPassthrough`, `onPurchaseComplete` and `registerCallbacks()` are removed.
`onPurchaseComplete` has no native counterpart in 2.0: the SDK no longer runs purchases itself, so there is no native purchase to report, and your controller is the code that ran the one that happened.
`onPassthrough` becomes a reading of the presentation record rather than an event:
```tsx theme={null}
const result = await Encore.placement('cancel_flow').show();
const passedThrough =
result.status !== 'presented' ||
(result.claim === null && result.publisher !== 'purchased');
```
For cross-cutting observation (analytics forwarding, app-owned state, debug overlays), subscribe to [`Encore.onOutcome`](../sdk-reference/outcomes):
```tsx theme={null}
useEffect(
() =>
Encore.onOutcome((outcome) => {
if (outcome.type === 'presentation') {
analytics.track('encore_presentation', outcome.result);
} else {
refreshEntitlements(); // strict_unlock_verified
}
}),
[],
);
```
Two differences from the 1.x `on*` setters:
* **It appends.** The 1.x setters replaced the previous handler; this is a real subscription, and several observers can listen at once, matching the multicast streams both natives expose.
* **There is no replay.** Subscribe at startup, or you miss outcomes emitted before you subscribed.
The stream also carries `strict_unlock_verified`, which has no 1.x equivalent: a strict claim the server confirmed *after* its flow ended, possibly on a later launch, so it can never be a `show()` return value.
***
## Removed APIs at a glance
| 1.x surface | 2.x replacement |
| :- | :- |
| `Encore.onPurchaseRequest(handler)` + `Encore.completePurchaseRequest(bool)` | The `purchaseController` option on [`configure()`](../sdk-reference/configure), a [controller](../sdk-reference/purchase-controller) returning `'purchased' \| 'cancelled' \| 'pending'` |
| `Encore.onPurchaseComplete(handler)` | Removed; no native counterpart. Your controller already sees every purchase it runs |
| `Encore.onPassthrough(handler)` | Read the record at the call site, or subscribe to [`Encore.onOutcome`](../sdk-reference/outcomes) |
| `Encore.registerCallbacks()` | Removed; the controller is bound at [`configure()`](../sdk-reference/configure) and `onOutcome` starts the stream |
| `Encore.placements.setClaimEnabled(bool)` | [`Encore.setClaimEnabled(bool)`](../sdk-reference/set-claim-enabled) |
| `Encore.show(placementId)` (deprecated in 1.x) | `Encore.placement(placementId).show()` |
| `PlacementResult` (`status: 'granted' \| 'claimed' \| …`) | [`PresentationResult`](../sdk-reference/presentation-result): two funnels plus a dismissal |
| `result.entitlement` | Removed from the result; read entitlement state from your own store |
| A rejected `show()` promise | `{ status: 'not_presented', reason: { type: 'error', error: { type, message } } }` |
| *(no 1.x equivalent)* | `Encore.onOutcome(handler)`, the outcomes stream |
| *(no 1.x equivalent)* | `options.unlock: 'optimistic' \| 'strict'` |
***
## Behavior changes to be aware of
These typecheck fine but behave differently at runtime:
* **Errors no longer reject.** Old `catch` fallback blocks are dead code; run fallback off `not_presented` instead.
* **Claim-then-purchase records both funnels.** 1.x collapsed the flow to a single winner. 2.0 carries `advertiser: { type: 'claimed', … }` and `publisher: 'purchased'` side by side, and the result resolves once, after the purchase settles.
* **A deferred purchase is now visible.** Flows that previously recorded a failure for Ask to Buy or SCA now record `publisher: 'pending'`, provided your controller returns `'pending'` for them.
* **`useCase`, `headline` and `subheadline` now actually work.** The JS builder already exposed them in 1.x, but the bridge had no native method behind them, so the values were dropped with a warning and `rewardUsers` could never present. Both bridges now forward all three on every `show()`.
* **`reset()` does not clear the controller.** It is build-time wiring, not user state, so logging a user out does not require re-registering.
***
## New in 2.0
* **The outcomes stream**, including late `strict_unlock_verified` events that survive process death.
* **Unlock mode.** `options.unlock: 'strict'` verifies claims server-side, persisting unverified claims and re-checking them across launches. `'optimistic'` (the default, and 1.x's behavior) records the claim and finishes.
* **A working reward surface.** `.useCase(UseCase.rewardUsers)` presents the claim-only [reward](/publishers/use-cases/post-action-reward) sheet instead of the churn-intervention sheet, with `.headline()` / `.subheadline()` copy overrides.
* **`basePlanId` on the purchase request**, naming the Google Play base plan to select when a product exposes several.
```tsx theme={null}
const result = await Encore.placement('milestone_reached')
.useCase(UseCase.rewardUsers)
.headline("That's three days in a row staying informed 🔥")
.subheadline("Here's a little thank you from us")
.show();
```
***
## Verify the migration
> [!TIP]
>
> Confirm each of these before shipping:
1. `npx tsc --noEmit` is clean, with no references to removed 1.x APIs.
2. If your Encore flows include an in-app purchase, a purchase controller is passed to `configure()`, either directly or as the `EncoreProvider` prop.
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 branch, 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/react-native/quickstart/configure
Initialize the Encore React Native SDK with your API key and purchase controller.
## Overview
As soon as your app launches, 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).
If your Encore flows include an in-app purchase, you pass a **purchase controller** to `configure()` as well. The SDK has no built-in billing: it never runs purchase code you did not write.
***
## Option A: EncoreProvider (recommended)
Wrap your app with `EncoreProvider`. It calls `configure()` once, on mount, with your purchase controller bound as part of that call.
```tsx theme={null}
import { EncoreProvider } from '@encorekit/react-native';
import type { PurchaseController } from '@encorekit/react-native';
// Encore decides *when* a purchase happens; your app decides *how*.
const purchaseController: PurchaseController = async ({ productId }) => {
const outcome = await yourBilling.purchase(productId);
if (outcome.userCancelled) return 'cancelled';
if (outcome.deferred) return 'pending';
return 'purchased';
};
export default function App() {
return (
);
}
```
> [!NOTE]
>
> The provider configures once, so the controller from the first render is the one that is bound. If yours genuinely has to change at runtime, swap it with [`Encore.setPurchaseController()`](../sdk-reference/purchase-controller#replacing-the-controller).
If your Encore flows have no in-app purchase, omit the prop. The SDK then never attempts a purchase and every presentation records `publisher: 'not_attempted'`.
***
## Option B: Configure directly
Outside a React tree, or when you need to configure at a precise point in your startup sequence, call `configure()` yourself.
```tsx theme={null}
import Encore from '@encorekit/react-native';
// At app startup
await Encore.configure('pk_your_api_key_here', { purchaseController });
```
***
## Return `pending` for deferred purchases
`PurchaseResult` is three-valued for a reason:
```tsx theme={null}
type PurchaseResult = '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, and the store's eventual webhook is the source of truth.
Returning `'cancelled'` for a deferred purchase silently misreports revenue, recording a sale that is still in flight as a decline. Map the deferred branch of your billing library to `'pending'`. Throw only for a real failure, which is recorded as `publisher: 'failed'` with your message.
See [PurchaseController](../sdk-reference/purchase-controller) for RevenueCat, react-native-iap, and custom implementations.
***
## Configuration options
```tsx theme={null}
await Encore.configure('pk_your_api_key_here', {
purchaseController, // your billing code; omit if your flows have no purchase
logLevel: 'debug', // 'none' | 'error' | 'warn' | 'info' | 'debug'
unlock: 'optimistic' // 'optimistic' | 'strict'
});
```
| Option | Type | Default | Description |
| - | - | - | - |
| `purchaseController` | function | *(none)* | Your billing code, bound as the SDK's single purchase path. See [PurchaseController](../sdk-reference/purchase-controller) |
| `logLevel` | string | `'none'` | Logging verbosity level |
| `unlock` | string | `'optimistic'` | How a claim grants access. `'strict'` verifies server-side and persists unverified claims across launches, surfacing late confirmations on [`Encore.onOutcome`](../sdk-reference/outcomes) |
> [!TIP]
>
> Use `logLevel: 'debug'` during development, then remove it for production builds.
> [!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).
***
## 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/react-native/quickstart/install
Add the Encore React Native SDK to your project.
## Overview
The Encore React Native SDK lets your app present premium brand offers, real perks funded by brands, at the moments you choose. It is distributed via **npm** and includes native bridges for both iOS and Android.
***
## Requirements
* **iOS 15.0** or later, and **Android API 26** or later.
* **Node 16** or later to install the package.
***
## Install via npm
```bash theme={null}
npm install @encorekit/react-native
```
Trigger components need 2.4.0 or later; to upgrade an existing install, run `npm install @encorekit/react-native@latest`. This documentation describes the **2.x** surface. The package pins the native SDKs it was built against (EncoreKit 2.x on iOS, `com.encorekit:encore` 2.x on Android), so a bridge major tracks a native major.
> [!NOTE]
>
> Migrating an existing 1.x integration? 2.0 is a breaking release. [Updating to 2.x](/publishers/react-native/guides/updating-to-2-x) walks the migration step by step.
### iOS: Install CocoaPods
After installing the npm package, install the native iOS dependencies:
```bash theme={null}
cd ios && pod install
```
### Android: Auto-linking
React Native auto-links the native Android module, so no additional setup is needed.
***
## Verify Installation
You should now be able to import the SDK:
```tsx theme={null}
import Encore from '@encorekit/react-native';
```
**Installation complete!**
***
## Next Steps
Now that the SDK is installed, continue with the integration:
* **[Configure the SDK](/publishers/react-native/quickstart/configure)**: set up your API key and initialize Encore
* **[Identify Users](/publishers/react-native/quickstart/user-management)**: identify users 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/react-native/guides/updating-sdk).
# Presenting Offers
Source: https://docs.encorekit.com/publishers/react-native/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 React Native 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()` resolves with the complete factual record of what happened, and it **never rejects**. Every failure, including "nothing was presented", arrives as a value on the result, so there is no `catch` block to forget:
> [tab] Reward Users
>
> ```tsx theme={null}
> import Encore, { UseCase } from '@encorekit/react-native';
>
> async function onStreakKept() {
> const result = await Encore.placement('streak_day_7')
> .useCase(UseCase.rewardUsers)
> .headline('Nice work, Sam!') // optional; falls back to the copy resolved for your app
> .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.
> }
> ```
>
> Select `UseCase.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
>
> ```tsx theme={null}
> async function onCancelTapped() {
> const result = await Encore.placement('cancel_flow').show();
>
> if (result.status === 'presented' && (result.claim !== null || result.publisher === 'purchased')) {
> // The user claimed an offer or completed your purchase.
> navigation.navigate('Home');
> } 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) · [`PresentationResult`](../sdk-reference/presentation-result).
> [!TIP]
>
> `result.claim` means the user tapped through to an offer, not that they finished it.
***
## Read the result
A presented record carries **two independent funnels** plus how the sheet went away:
| Field | What it reports |
| - | - |
| `advertiser` | Encore's funnel: `not_attempted`, `claimed`, `verified`, `cooldown`, or `failed` |
| `publisher` | Your funnel: what your purchase controller returned |
| `dismissal` | How the sheet went away |
| `claim` | Shorthand for the offer behind a `claimed` or `verified` advertiser outcome, else `null` |
A single presentation can claim an offer **and** run a purchase, so the two funnels are recorded side by side rather than competing for one winning value.
> [!NOTE]
>
> There is deliberately no `unlocked` boolean. What a claim means is a property of the variant flow that served it, so an SDK-computed verdict could contradict the flow that actually ran. Branch on the raw axes, as above. See [PresentationResult](../sdk-reference/presentation-result).
***
## 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 [purchase controller](../sdk-reference/purchase-controller). Pass it to `configure()`; see [Configure the SDK](./configure).
```tsx theme={null}
const purchaseController: PurchaseController = async ({ productId }) => {
const outcome = await yourBilling.purchase(productId);
if (outcome.userCancelled) return 'cancelled';
if (outcome.deferred) return 'pending';
return 'purchased';
};
```
> [!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, subscribe to the outcomes stream. It appends rather than replacing, so several observers can listen at once.
```tsx theme={null}
useEffect(
() =>
Encore.onOutcome((outcome) => {
if (outcome.type === 'presentation') {
analytics.track('encore_presentation', outcome.result);
} else {
refreshEntitlements(); // strict_unlock_verified
}
}),
[],
);
```
There is no replay, so subscribe at startup. See [onOutcome()](../sdk-reference/outcomes).
***
## Full example: cancel flow
```tsx theme={null}
import { useEffect } from 'react';
import Encore, { EncoreProvider } from '@encorekit/react-native';
import type { PurchaseController } from '@encorekit/react-native';
const purchaseController: PurchaseController = async ({ productId }) => {
const outcome = await billingService.purchase(productId);
if (outcome.userCancelled) return 'cancelled';
if (outcome.deferred) return 'pending';
return 'purchased';
};
export default function App() {
return (
);
}
function SubscriptionScreen() {
useEffect(
() => Encore.onOutcome((outcome) => analytics.track('encore_outcome', outcome)),
[],
);
const handleCancel = async () => {
const result = await Encore.placement('cancel_flow').show();
if (result.status === 'presented' && (result.claim !== null || result.publisher === 'purchased')) {
showRetentionConfirmation();
} else {
await proceedWithCancellation();
}
};
return ;
}
```
***
## 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: set up the store subscriptions your controller purchases
* [Integration Patterns](/publishers/react-native/guides/integration-patterns) - Where to put the call site, the controller, and the stream
* [SDK Reference](../sdk-reference/configure) - Complete API documentation
# User Management
Source: https://docs.encorekit.com/publishers/react-native/quickstart/user-management
Identifying users, setting attributes, and managing identity in your React Native 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 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:
```tsx theme={null}
await Encore.identify(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
***
## Resetting User Identity
When a user logs out, call `reset()`:
```tsx theme={null}
await Encore.reset();
```
This will:
* Reset the user ID to a new auto-generated anonymous ID
* Clear cached entitlement data
* Clear all user attributes
Your registered [purchase controller](../sdk-reference/purchase-controller) **survives** `reset()`. It is build-time wiring, 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.
```typescript theme={null}
import Encore, { type UserAttributes } from '@encorekit/react-native';
const attributes: UserAttributes = {
countryCode: 'US',
age: 25,
custom: { signupSource: 'referral' },
};
await Encore.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.
### Usage
```tsx theme={null}
await Encore.setUserAttributes({
email: 'user@example.com',
subscriptionTier: 'premium',
monthsSubscribed: '6',
custom: {
cancelReason: 'too_expensive',
},
});
```
You can also set attributes when identifying:
```tsx theme={null}
await Encore.identify(user.id, {
email: user.email,
subscriptionTier: user.plan,
monthsSubscribed: String(user.monthsActive),
});
```
**Important:** `setUserAttributes()` **merges** with existing attributes. It does not replace them.
> [!TIP]
>
> See the SDK Reference for details: [identify()](../sdk-reference/identify), [setUserAttributes()](../sdk-reference/set-user-attributes), and the full [UserAttributes](../sdk-reference/user-attributes) field list.
***
## Implementation Examples
### With useEncoreContext Hook
```tsx theme={null}
import { useEncoreContext } from '@encorekit/react-native';
function ProfileScreen() {
const encore = useEncoreContext();
const handleLogin = async (user) => {
await encore.identify(user.id, {
email: user.email,
subscriptionTier: user.plan,
});
};
const handleLogout = async () => {
await encore.reset();
};
return (
// ...
);
}
```
### Apps Without Login
If your app doesn't require users to log in, no additional setup is needed:
```tsx theme={null}
// Anonymous users work automatically — just set attributes if needed
await Encore.setUserAttributes({
custom: { cancelReason: 'too_expensive' },
});
```
***
## Next Steps
* **[Present Offers](./present-offers)**: present a reward sheet at a moment your user just earned, and read the result
# clearLanguage()
Source: https://docs.encorekit.com/publishers/react-native/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 React Native SDK release that pins native 2.3.0.
## Signature
```typescript theme={null}
clearLanguage(): Promise<{ success: boolean }>
```
## 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:
```typescript theme={null}
import Encore from '@encorekit/react-native';
async function onLanguageChanged(code: string | null) {
if (code) {
await Encore.setLanguage(code);
} else {
await Encore.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/react-native/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. Binding it is part of configuring, so the SDK is never configured without the purchase path it was meant to have.
## Signature
```tsx theme={null}
configure(apiKey: string, options?: ConfigureOptions): Promise<{ success: boolean }>
```
## Parameters
| Name | Type | Default | Description |
| - | - | - | - |
| `apiKey` | string | *(required)* | Your Live Key or Test Key from the Encore Dashboard settings |
| `options` | [ConfigureOptions](#options) | `{}` | Optional configuration |
### Options
```tsx theme={null}
interface ConfigureOptions {
purchaseController?: PurchaseController;
logLevel?: 'none' | 'error' | 'warn' | 'info' | 'debug';
unlock?: 'optimistic' | 'strict';
}
```
| Option | Type | Default | Description |
| - | - | - | - |
| `purchaseController` | [PurchaseController](./purchase-controller) | *(none)* | 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` | `'none' \| 'error' \| 'warn' \| 'info' \| 'debug'` | `'none'` | Logging verbosity level |
| `unlock` | `'optimistic' \| 'strict'` | `'optimistic'` | How a claim grants access. See [Unlock mode](#unlock-mode) |
### Unlock mode
`'optimistic'` records the claim and finishes. `'strict'` verifies the claim server-side, persisting unverified claims and re-checking them across launches; those settle later as a `strict_unlock_verified` event on [`Encore.onOutcome`](./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
### EncoreProvider (recommended)
```tsx theme={null}
import { EncoreProvider } from '@encorekit/react-native';
import type { PurchaseController } from '@encorekit/react-native';
const purchaseController: PurchaseController = async ({ productId }) => {
const outcome = await yourBilling.purchase(productId);
if (outcome.userCancelled) return 'cancelled';
if (outcome.deferred) return 'pending';
return 'purchased';
};
export default function App() {
return (
);
}
```
The provider forwards the `purchaseController` prop into `configure`, which it calls once, on mount. Only the value from the first render is bound; swap it later with [`Encore.setPurchaseController()`](./purchase-controller#replacing-the-controller) if it genuinely needs to change at runtime.
### Direct configuration
```tsx theme={null}
import Encore from '@encorekit/react-native';
await Encore.configure('pk_your_api_key', {
purchaseController,
logLevel: 'debug',
unlock: 'strict',
});
```
## Configuring without a purchase controller
If your Encore flows include no in-app purchase, omit the option. The SDK then never attempts a purchase, logs its own `sdk_iap_no_purchase_controller` diagnostic, and every presentation records `publisher: 'not_attempted'`. That is a supported configuration and a more accurate record than a failure your app never caused.
> [!TIP]
>
> Use `logLevel: 'debug'` during development to see detailed SDK logs, then `'none'` for production builds.
## Related
* [PurchaseController](./purchase-controller), the shape of the `purchaseController` option.
* [onOutcome()](./outcomes), which `unlock: 'strict'` feeds late verifications into.
# Errors
Source: https://docs.encorekit.com/publishers/react-native/sdk-reference/errors
Error handling in the Encore React Native SDK: errors as values, not rejections
In 2.0 the SDK reports failures as **values**, not rejected promises. `show()` never rejects, and the bridge methods resolve with `{ success: false }` rather than throwing, so a missing `catch` can no longer wedge an integration.
## EncoreErrorInfo
A native failure, flattened for the bridge.
```tsx theme={null}
interface EncoreErrorInfo {
type: string; // frozen error-type vocabulary
message: string; // human-readable description
}
```
`type` is the stable identifier string. The two native `EncoreError` hierarchies differ in shape, so the bridge sends the identifier rather than reconstructing a JavaScript class from it.
| `type` | 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 |
| `bridge_error` | The native bridge did not return a result. React Native only |
## Where errors arrive
### Presentation failures
A failure that stopped the sheet appearing lands on the [`PresentationResult`](./presentation-result) as `not_presented` with `reason.type === 'error'`:
```tsx theme={null}
const result = await Encore.placement('cancel_flow').show();
if (result.status === 'not_presented') {
if (result.reason.type === 'error') {
console.warn('Encore:', result.reason.error.type, result.reason.error.message);
}
proceedWithCancellation(); // run your fallback either way
}
```
> [!WARNING]
>
> Do not gate your fallback on the error branch. `not_presented` also covers `no_offer_available`, `experiment_control`, and `use_case_unavailable`, 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 axis instead, as `advertiser: { type: 'failed', error }`. The user never saw it.
### Purchase failures
Throwing from your [purchase controller](./purchase-controller) records `publisher: 'failed'` with your error message, and the flow continues. Return `'cancelled'` for a user cancellation and `'pending'` for a deferred purchase rather than throwing either.
## Bridge-level failures
Every bridge method is wrapped: a native call that fails logs a `[Encore]` warning and resolves with a fallback rather than rejecting, so a bridge fault can never crash the host app.
```tsx theme={null}
const { success } = await Encore.setPurchaseController(replacementController);
if (!success) {
// configure() ran without a purchase path, so there is no controller to
// replace, or the native module rejected the call.
}
```
For `show()`, that fallback is a `not_presented` result carrying `error.type === 'bridge_error'`.
## Related
* [PresentationResult](./presentation-result), where presentation and claim failures land.
* [PurchaseController](./purchase-controller) for 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/react-native/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
```tsx theme={null}
identify(userId: string, attributes?: UserAttributes): Promise<{ success: boolean }>
```
## Parameters
| Name | Type | Description |
| - | - | - |
| `userId` | string | Your user's unique identifier from your auth system |
| `attributes` | [UserAttributes](./user-attributes) | Optional structured attributes to set in one call |
## Usage
### Basic identification
```tsx theme={null}
await Encore.identify(user.id);
```
### With attributes
```tsx theme={null}
await Encore.identify(user.id, {
email: user.email,
subscriptionTier: user.plan,
monthsSubscribed: String(user.monthsActive),
});
```
> [!TIP]
>
> Call `identify()` after a successful login. On logout, call [`reset()`](./reset) to clear the user ID and cached entitlements.
# onOutcome()
Source: https://docs.encorekit.com/publishers/react-native/sdk-reference/outcomes
Subscribe to the outcomes stream: every placement resolution, plus late strict-unlock verifications
`Encore.onOutcome(handler)` subscribes to the outcomes stream, the passive observation channel. It mirrors Swift's `AsyncStream` and Kotlin's `SharedFlow`.
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
```tsx theme={null}
onOutcome(handler: (outcome: PlacementOutcome) => void): () => void
```
Returns an unsubscribe function.
```tsx theme={null}
type PlacementOutcome = PresentationOutcome | StrictUnlockVerifiedOutcome;
interface PresentationOutcome {
type: 'presentation';
placementId: string;
result: PresentationResult;
}
interface StrictUnlockVerifiedOutcome {
type: 'strict_unlock_verified';
transactionId: string;
}
```
## Usage
```tsx theme={null}
import { useEffect } from 'react';
import Encore from '@encorekit/react-native';
useEffect(
() =>
Encore.onOutcome((outcome) => {
if (outcome.type === 'presentation') {
analytics.track('encore_presentation', {
placementId: outcome.placementId,
result: outcome.result,
});
} else {
// Entitlements are already refreshed natively by the time this lands.
refreshEntitlements();
}
}),
[],
);
```
The effect returns the unsubscribe function directly, so React tears the listener down on unmount.
## Behavior
* **It appends.** Unlike the 1.x `on*` setters, which replaced the previous handler, this is a real subscription: several observers can listen at once, matching the multicast streams both native SDKs expose.
* **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.
* **Every `show()` the SDK resolves emits**, including the ones that presented nothing. A `not_presented` resolution is still a `presentation` event, carrying the same [`PresentationResult`](./presentation-result) the call site received. A call the bridge rejects before it reaches the SDK resolves at the call site without reaching the stream.
## Late strict-unlock verification
`strict_unlock_verified` 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: 'strict'` on [`configure()`](./configure), a claim that ends unverified persists across process death and is re-checked on subsequent launches. When verification completes, entitlements are refreshed natively first, then the event is emitted. Its `transactionId` matches the [`ClaimedOffer.transactionId`](./presentation-result#claimedoffer) recorded on the original result, so you can join the two.
Under the default `unlock: 'optimistic'`, this event never fires.
## Related
* [PresentationResult](./presentation-result), the payload of `presentation` events.
* [configure()](./configure) for the `unlock` option that makes `strict_unlock_verified` reachable.
# placement()
Source: https://docs.encorekit.com/publishers/react-native/sdk-reference/placement
Present Encore offers via a fluent builder API
Creates a placement builder for presenting offers. This is the only way to present in 2.0, and it matches the builder across every Encore SDK.
## Signature
```tsx theme={null}
placement(placementId: string): PlacementBuilder
interface PlacementBuilder {
useCase(useCase: UseCase): PlacementBuilder;
headline(text: string): PlacementBuilder;
subheadline(text: string): PlacementBuilder;
publisherReward(reward: PublisherReward): PlacementBuilder; // 2.3.0+
show(): Promise;
}
interface PublisherReward {
id: string;
title: string;
detail?: string;
iconUrl?: string;
}
```
Each option returns a **new** builder, so a builder can be reused or shared without one call site mutating the configuration of another.
## Parameters
| Name | Type | Description |
| - | - | - |
| `placementId` | string | The placement identifier configured in the Encore Dashboard |
## show()
```tsx theme={null}
const result = await Encore.placement('cancel_flow').show();
```
`show()` **never rejects**. Every failure, including "nothing was presented", is a value on the returned [`PresentationResult`](./presentation-result):
```tsx theme={null}
const result = await Encore.placement('cancel_flow').show();
if (result.status === 'presented' && (result.claim !== null || result.publisher === 'purchased')) {
grantAccess();
} else {
proceedWithCancellation();
}
```
> [!NOTE]
>
> Pass a [purchase controller](./purchase-controller) to [`configure()`](./configure) if your flows include an in-app purchase. Without one the SDK never attempts a purchase, and every presentation records `publisher: 'not_attempted'`.
## Use cases
`useCase()` selects which Encore surface the placement presents. It defaults to `UseCase.reduceChurn`.
```tsx theme={null}
import Encore, { UseCase } from '@encorekit/react-native';
await Encore.placement('milestone_reached')
.useCase(UseCase.rewardUsers)
.headline("That's three days in a row staying informed 🔥")
.subheadline("Here's a little thank you from us")
.show();
```
| Case | Wire value | Surface |
| - | - | - |
| `UseCase.reduceChurn` | `churn-intervention` | Second-chance monetization after a paywall decline. The default |
| `UseCase.rewardUsers` | `post-action-reward` | A brand-funded reward at a moment the user just accomplished something. Claim-only; never presents IAP |
The keys name the capability; the values are the `sdui_use_case` labels the backend stores. They are pinned explicitly rather than derived from the keys, so renaming a key can never silently change what goes over the wire. `UseCase` is declaration-merged, so it is both the value you reach through and the type you annotate with.
> [!NOTE]
>
> A use case with no enabled variant resolves `not_presented` with `reason.type === 'use_case_unavailable'` rather than falling back to the churn-intervention sheet. An in-app-purchase screen at a moment the user was meant to be rewarded is worse than presenting nothing.
## 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, so the chain falls through rather than rendering an empty line.
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()` 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()` resolves to, and your app grants the prize from that result only. De-duplicate on your own user ID plus `campaignId`, because `transactionId` can be missing. Setup, the daily limit, and when the flag stays false: [Reward for Trying](/publishers/guides/reward-for-trying).
## Related
* [PresentationResult](./presentation-result), what `show()` resolves to.
* [PurchaseController](./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.
# PresentationResult
Source: https://docs.encorekit.com/publishers/react-native/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 rejects. Presentation-level failures arrive here as values.
## Structure
```tsx theme={null}
type PresentationResult =
| { status: 'not_presented'; reason: NotPresentedReason }
| {
status: 'presented';
advertiser: AdvertiserOutcome; // Encore's funnel: how far the claim got
publisher: PublisherOutcome; // your funnel: what your controller reported
dismissal: DismissReason; // how the sheet went away
claim: ClaimedOffer | null; // shorthand for a claimed/verified offer
};
```
The two funnels are independent axes, not competing cases: a single presentation can claim an offer **and** run a purchase, and 2.0 records both. `not_attempted` is a real value, meaning "the funnel was open and nothing entered it", never a missing one.
> [!NOTE]
>
> **There is no `unlocked` boolean, on purpose.** What a claim means is a property of the variant flow that served it, so an SDK-computed verdict over app-global config could contradict the flow that actually ran. The record is facts; the policy is yours.
## Reading it
```tsx theme={null}
const result = await Encore.placement('cancel_flow').show();
if (result.status === 'presented') {
const converted = result.claim !== null || result.publisher === 'purchased';
if (converted) grantAccess();
else proceedWithCancellation();
} else {
proceedWithCancellation(); // nothing was shown; result.reason says why
}
```
When the mechanism matters, branch on the axes directly:
```tsx theme={null}
if (result.status === 'presented') {
analytics.track('encore_presentation', {
advertiser: result.advertiser.type,
publisher: result.publisher,
dismissal: result.dismissal,
});
}
```
## PublisherOutcome
Your funnel: what your [purchase controller](./purchase-controller) reported back.
```tsx theme={null}
type PublisherOutcome =
| 'not_attempted'
| 'purchased'
| 'cancelled'
| 'pending'
| 'failed';
```
| Value | Meaning |
| - | - |
| `not_attempted` | No purchase was attempted. Also what a presentation records when no purchase controller is registered |
| `purchased` | Your controller returned `'purchased'` |
| `cancelled` | Your controller returned `'cancelled'` |
| `pending` | Your controller returned `'pending'`: the store deferred the purchase and it may settle later |
| `failed` | Your controller threw |
> [!WARNING]
>
> Treat `pending` as neither a conversion nor an abandonment. It is Ask to Buy (parental approval) on iOS, or SCA or a pending Play transaction on Android: the user has not been charged and has not walked away, and the store's webhook is the source of truth. Folding it into `cancelled` in your own reporting reproduces exactly the misreporting the 1.x boolean handler caused.
## AdvertiserOutcome
Encore's funnel: how far the offer claim got.
```tsx theme={null}
type AdvertiserOutcome =
| { type: 'not_attempted' }
| { type: 'claimed'; offer: ClaimedOffer }
| { type: 'verified'; offer: ClaimedOffer }
| { type: 'cooldown' }
| { type: 'failed'; error: EncoreErrorInfo };
```
| Case | Meaning |
| - | - |
| `not_attempted` | The claim funnel was open and nothing entered it |
| `claimed` | The claim completed on-device; server verification not (yet) observed |
| `verified` | Server-level confirmation was observed in-session |
| `cooldown` | 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 |
| `failed` | The claim errored. An SDK-side failure the user never saw |
`result.claim` is shorthand for the offer behind a `claimed` or `verified` outcome, and `null` otherwise. Read `result.advertiser` directly when you need to tell the two apart.
### ClaimedOffer
```tsx theme={null}
interface ClaimedOffer {
offerId: string;
campaignId: string;
advertiserName: string;
transactionId?: string;
userConfirmedCompletion: boolean; // 2.3.0+
}
```
On iOS an offer *is* a campaign, so `offerId` equals `campaignId` there. `transactionId` joins this record to a later [`strict_unlock_verified`](./outcomes) outcome and to the server-side completion event that can land days afterwards; it is nullable, because the transaction write can fail while the claim still happened. `userConfirmedCompletion` is 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).
## DismissReason
How a presented sheet went away. These strings are the frozen cross-platform vocabulary, and the same values land in `decline_reason` on `sdk_offer_sheet_dismissed`.
```tsx theme={null}
type DismissReason =
| 'close_button'
| 'swipe_dismiss'
| 'user_cancelled'
| 'last_offer_declined'
| 'dismissed'
| 'provisional_cooldown'
| 'flow_completed'
| 'interrupted';
```
| Value | Meaning | Platform |
| - | - | - |
| `close_button` | The user tapped the close control | Both |
| `swipe_dismiss` | The user swiped the sheet away | Both |
| `user_cancelled` | The user cancelled out of the flow | iOS |
| `last_offer_declined` | The user declined the final offer in the flow | iOS |
| `dismissed` | Generic dismissal | iOS |
| `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 `flow_completed` when it was the last one | Android (iOS before 2.3.0) |
| `flow_completed` | The flow finished on its own and the SDK closed the sheet | Both |
| `interrupted` | The SDK force-ended a dead flow, not the user | Both |
## NotPresentedReason
Why no sheet ever appeared.
```tsx theme={null}
type NotPresentedReason =
| {
type:
| 'not_configured'
| 'already_presenting'
| 'unsupported_ios'
| 'no_offer_available'
| 'experiment_control'
| 'use_case_unavailable'
| 'no_foreground'
| 'iap_first_declined';
}
| { type: 'error'; error: EncoreErrorInfo };
```
| Value | Meaning | Platform |
| - | - | - |
| `not_configured` | A method was called before `configure()` | Both |
| `already_presenting` | A presentation is already on screen | Both |
| `unsupported_ios` | The device is below the SDK's minimum OS version | iOS |
| `no_offer_available` | No offers matched this user. Don't retry immediately | Both |
| `experiment_control` | Control cohort: exposure logged, no UI by design | Both |
| `use_case_unavailable` | The requested use case resolved no layout for this app | Both |
| `no_foreground` | No foreground Activity was available when the SDK needed one | Android |
| `iap_first_declined` | An IAP-first layout ran its purchase before any UI and the user declined | Android |
| `error` | Network, decoding, or integration failure. See [Errors](./errors) | Both |
> [!NOTE]
>
> `use_case_unavailable` is a correct no-op, not an error. It never falls back to the churn-intervention sheet, because putting an in-app-purchase screen in front of a user who was meant to be rewarded is worse than presenting nothing.
## Related
* [placement()](./placement), which returns this record.
* [PurchaseController](./purchase-controller), whose answer becomes `publisher`.
* [outcomes](./outcomes), which carries this record for passive observers.
* [Errors](./errors) for the `EncoreErrorInfo` shape.
# PurchaseController
Source: https://docs.encorekit.com/publishers/react-native/sdk-reference/purchase-controller
The purchase function your app registers so Encore offers purchase through your billing code
Every purchase triggered by an Encore offer runs through a `PurchaseController` your app registers. 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
```tsx theme={null}
type PurchaseResult = 'purchased' | 'cancelled' | 'pending';
type PurchaseController = (
request: PurchaseRequest,
) => Promise | PurchaseResult;
```
JavaScript can't implement a native protocol, so the bridge owns the native controller conformance and forwards each request to your function, correlating requests by id so a late reply can never land on a live flow.
## Binding a controller
Pass your controller to [`configure()`](./configure). Binding it is part of configuring, so the SDK is never configured without the purchase path it was meant to have.
```tsx Direct theme={null}
await Encore.configure('pk_...', { purchaseController });
```
```tsx EncoreProvider theme={null}
```
`EncoreProvider` forwards its `purchaseController` prop into the `configure()` call it makes on mount, so these are one binding written two ways. Pick whichever matches where your app starts up.
> [!NOTE]
>
> Binding is build-time wiring, not user state. It survives [`reset()`](./reset), so logging a user out does not require binding again.
### Omitting the controller
Omitting the controller is a supported configuration, not a broken one. The SDK passes no controller to the native layer, never attempts a purchase, keeps its own `not_attempted` record and `sdk_iap_no_purchase_controller` diagnostic, and every presentation resolves `publisher: 'not_attempted'`. That is a different and more accurate fact than a `failed` the publisher never caused.
### Replacing the controller
`Encore.setPurchaseController()` swaps the controller bound at `configure()`. The controller the native SDK holds is the bridge itself, and the bridge always forwards to whichever handler is currently bound, so the swap is a JavaScript-side concern that takes effect on the next purchase request.
```tsx theme={null}
await Encore.setPurchaseController(controllerForSignedInUser);
```
Reach for it when the controller genuinely has to change at runtime, such as a billing stack that only exists once a user signs in. The bridge keeps exactly one native listener across swaps, so a replacement can never run a single purchase request through both handlers.
It resolves `{ success: false }`, and logs why, when `configure()` ran without a purchase path: the native SDKs take the controller as a `configure()` argument and Android has no setter, so no controller can be added to an SDK that is already configured. Pass yours to `configure()` instead.
## PurchaseResult
| Value | Meaning |
| - | - |
| `'purchased'` | The purchase completed |
| `'cancelled'` | The user backed out. Map your billing layer's "user cancelled" error to this rather than throwing it |
| `'pending'` | The store **deferred** the purchase and it may complete later |
Throw for a real failure. A throw is recorded as `publisher: 'failed'` with your error message, and the flow continues.
> [!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. When you map your billing layer onto `PurchaseResult`, 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 `'pending'`.
Returning anything else, including a bare `true` (the 1.x shape) or forgetting to return, is rejected rather than guessed at: the bridge fails that request with a message naming what it received. Failing loudly beats silently reporting a purchase that never happened.
## PurchaseRequest
What your controller receives when Encore needs a purchase.
```tsx theme={null}
interface PurchaseRequest {
productId: string;
placementId?: string;
promoOfferId?: string;
basePlanId?: string;
}
```
| Property | Type | Description |
| - | - | - |
| `productId` | `string` | The store product identifier to purchase, for example `com.app.monthly_premium` |
| `placementId` | `string?` | Which placement triggered this purchase, if any |
| `promoOfferId` | `string?` | App Store Connect promotional offer identifier. iOS only; `undefined` elsewhere |
| `basePlanId` | `string?` | Google Play subscription base plan id, when the product exposes several. Android only; `undefined` on iOS and for single-base-plan products |
> [!NOTE]
>
> Android's native controller also hands over the foreground `Activity`. The bridge **absorbs** it rather than leaking it to JavaScript: it has no JavaScript representation, it is valid only for the duration of the call, and a React Native host's billing library resolves the current Activity itself. One contract therefore covers both platforms.
## Implementations
> [tab] RevenueCat
>
> ```tsx theme={null}
> import Purchases from 'react-native-purchases';
> import type { PurchaseController } from '@encorekit/react-native';
>
> const purchaseController: PurchaseController = async ({ productId }) => {
> try {
> await Purchases.purchaseProduct(productId);
> return 'purchased';
> } catch (error) {
> if (error.userCancelled) return 'cancelled';
> // RevenueCat surfaces a deferred store transaction as its
> // payment-pending error code. Check the constant your version exports.
> if (isPaymentPending(error)) return 'pending';
> throw error; // a real failure — Encore records it as publisher: 'failed'
> }
> };
> ```
> [tab] react-native-iap
>
> ```tsx theme={null}
> import * as RNIap from 'react-native-iap';
> import type { PurchaseController } from '@encorekit/react-native';
>
> const purchaseController: PurchaseController = async ({ productId, basePlanId }) => {
> try {
> const purchase = await RNIap.requestSubscription({
> sku: productId,
> ...(basePlanId ? { subscriptionOffers: [{ sku: productId, offerToken: basePlanId }] } : {}),
> });
> // Play returns a deferred transaction in the pending purchase state
> // rather than a completed one; it settles through the store later.
> if (isPending(purchase)) return 'pending';
> return 'purchased';
> } catch (error) {
> if (isUserCancelled(error)) return 'cancelled';
> if (isDeferredPayment(error)) return 'pending';
> throw error;
> }
> };
> ```
> [tab] Custom
>
> ```tsx theme={null}
> import type { PurchaseController } from '@encorekit/react-native';
>
> const purchaseController: PurchaseController = async (request) => {
> // request.productId - store product to purchase
> // request.placementId - which placement triggered this (optional)
> // request.promoOfferId - iOS promotional offer (optional)
> // request.basePlanId - Play base plan to select (optional)
> const outcome = await yourBilling.purchase(request.productId);
>
> if (outcome.userCancelled) return 'cancelled';
> if (outcome.deferred) return 'pending';
> return 'purchased';
> };
> ```
## Related
* [configure()](./configure), which binds the controller.
* [PresentationResult](./presentation-result), where the controller's answer lands as `publisher`.
* [Present offers](../quickstart/present-offers) for the end-to-end walkthrough.
# reset()
Source: https://docs.encorekit.com/publishers/react-native/sdk-reference/reset
Clear user identity and cached entitlements
Clears the current user ID, cached entitlements, and all user attributes. A new anonymous ID is automatically generated.
> [!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
```tsx theme={null}
reset(): Promise<{ success: boolean }>
```
## Parameters
None.
## Usage
```tsx theme={null}
const handleLogout = async () => {
await Encore.reset();
// Navigate to login screen
};
```
> [!TIP]
>
> A new anonymous user ID is auto-generated after `reset()`. You don't need to call `configure()` again.
> [!NOTE]
>
> Your registered [purchase controller](./purchase-controller) **survives** `reset()`. It is build-time wiring, not user state, so logging a user out does not require re-registering it.
# setClaimEnabled()
Source: https://docs.encorekit.com/publishers/react-native/sdk-reference/set-claim-enabled
Gray out and disable the claim CTA on offer cards at runtime
Controls whether the claim call to action 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
```tsx theme={null}
setClaimEnabled(enabled: boolean): Promise<{ success: boolean }>
```
Defaults to `true`, and is runtime-mutable by design: call it any time after [`configure()`](./configure), including while a sheet is on screen.
## Usage
```tsx theme={null}
// The user is in a state where claiming would be wrong (for example,
// mid-checkout in your own flow). Dim the claim CTA without hiding the offer.
await Encore.setClaimEnabled(false);
// Restore it when they leave that state.
await Encore.setClaimEnabled(true);
```
> [!NOTE]
>
> In 1.x this lived on `Encore.placements`. Both native SDKs deleted the 1.x placements manager in 2.0 and folded its one surviving concern onto the facade, so the bridge did the same. See [Updating to 2.x](../guides/updating-to-2-x).
## Related
* [placement()](./placement), the sheet this gate applies to.
* [PresentationResult](./presentation-result), where a suppressed claim shows up as `advertiser: { type: 'not_attempted' }`.
# setLanguage()
Source: https://docs.encorekit.com/publishers/react-native/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 React Native SDK release that pins native 2.3.0.
## Signature
```typescript theme={null}
setLanguage(tag: string): Promise
```
## 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.
* An invalid tag rejects the returned `Promise` before anything reaches the native SDK. See [Errors](#errors).
* A failure inside the native SDK logs a warning, and the `Promise` still resolves, like every other Encore call. The same happens when a newer JavaScript bundle runs on an app binary built before this release, for example after an over-the-air update. When the native module is not linked, for example in Expo Go, the call resolves 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.
## Errors
| Error | When |
| - | - |
| `RangeError` | `tag` is not a well-formed language tag, for example `'pt_BR'` or `'english'`. Use `'pt-BR'` and `'en'` |
| `TypeError` | `tag` is not a string |
Both reject before the call reaches the native SDK, so nothing changes.
## Replaces the `language` attribute
Setting the language through the `language` attribute is deprecated. 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":
```typescript theme={null}
import Encore from '@encorekit/react-native';
async function onLanguageChanged(code: string | null) {
if (code) {
await Encore.setLanguage(code);
} else {
await Encore.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/react-native/sdk-reference/set-user-attributes
Store structured user attributes for targeting and analytics
Sets structured user attributes used for offer targeting, personalization, and analytics. Attributes are merged with any existing values, not replaced.
## Signature
```tsx theme={null}
setUserAttributes(attributes: UserAttributes): Promise<{ success: boolean }>
```
## Parameters
| Name | Type | Description |
| - | - | - |
| `attributes` | [UserAttributes](./user-attributes) | Structured attributes to set for the current user |
> [!NOTE]
>
> `setUserAttributes()` **merges** with existing attributes. To clear attributes, call [`reset()`](./reset).
## Usage
```tsx theme={null}
await Encore.setUserAttributes({
email: 'user@example.com',
subscriptionTier: 'premium',
monthsSubscribed: '6',
custom: {
cancelReason: 'too_expensive',
},
});
```
# UserAttributes
Source: https://docs.encorekit.com/publishers/react-native/sdk-reference/user-attributes
Structured user attributes for targeting and analytics
A structured type for storing user metadata used in offer targeting, personalization, and analytics. All fields are optional and will be merged with existing attributes when set.
## Structure
```tsx theme={null}
interface UserAttributes {
// Identity & Basic Info
email?: string;
firstName?: string;
lastName?: string;
phoneNumber?: string;
// Location
postalCode?: string;
city?: string;
state?: string;
countryCode?: string;
latitude?: string;
longitude?: string;
// Demographics
age?: number;
dateOfBirth?: string;
gender?: string;
language?: string;
// Subscription & Billing
subscriptionTier?: string;
monthsSubscribed?: string;
billingCycle?: string;
lastPaymentAmount?: string;
// Engagement
lastActiveDate?: string;
totalSessions?: string;
// Custom Attributes
custom?: Record;
}
```
## Field Reference
### Identity & 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` | Phone number |
### Location
| Field | Type | Format | Example | Description |
| - | - | - | - | - |
| `postalCode` | string? | postal/ZIP code | `SW1A 1AA` | Postal 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` | number? | 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` | 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 & Billing
| Field | Type | Format | Example | Description |
| - | - | - | - | - |
| `subscriptionTier` | string? | plan name | `free`, `premium`, `pro` | Current subscription tier |
| `monthsSubscribed` | string? | integer string | `6` | Months subscribed |
| `billingCycle` | string? | enum string | `monthly`, `annual` | Billing frequency |
| `lastPaymentAmount` | string? | decimal as string | `9.99` | Last payment amount |
### Engagement
| Field | Type | Format | Example | Description |
| - | - | - | - | - |
| `lastActiveDate` | string? | ISO 8601 datetime | `2024-03-15T14:30:00Z` | Last activity timestamp |
| `totalSessions` | string? | integer string | `42` | Total sessions |
### Custom Attributes
| Field | Type | Format | Example | Description |
| - | - | - | - | - |
| `custom` | `Record` | key-value pairs | `{ churnRisk: 'high' }` | Additional custom attributes |
## Usage
```tsx theme={null}
await Encore.setUserAttributes({
email: 'user@example.com',
subscriptionTier: 'premium',
monthsSubscribed: '6',
});
```
# Claim Reminder
Source: https://docs.encorekit.com/publishers/triggers/claim-reminder
A trigger component that reminds users of the newest premium brand offer they claimed but haven't finished, and opens the reward sheet that lists it.
> [!NOTE]
>
> **Requires SDK 2.4.0+** on every platform. See [Minimum SDK versions](/publishers/triggers/overview#minimum-sdk-versions).
Claim Reminder is a [trigger component](/publishers/triggers/overview): a small card you place inside your own screen. It shows the user the newest premium brand offer (a real perk a brand funds to acquire customers) that they claimed but haven't finished yet, with that brand's name and logo. Tapping it opens the reward sheet, where that offer is listed, so the user can get back to it.
Many users claim an offer, leave your app to sign up with the brand, and never come back to finish. The reminder brings them back to the sheet, inside a screen they already visit.
Its trigger ID is `claimReminder`. Everything on [Trigger components](/publishers/triggers/overview) applies to it: how it sizes itself, when it renders nothing, and its color order. This page covers only what is specific to Claim Reminder.
> [!NOTE]
>
> Claim Reminder shows the claims the user made in your app on this device. A claim made elsewhere, such as on another device, doesn't show.
## When to use it
Use Claim Reminder on a screen users return to on their own, such as your home screen, feed, or profile. It fits where a card can sit in the normal flow of the layout.
You don't need it where a Gifts Button sits: Gifts Button turns into the reminder after a claim by itself (see [After a claim](/publishers/triggers/gifts-button#after-a-claim)).
Its use case defaults to the reward use case, so leave `useCase` out. Churn isn't supported yet: with the churn use case, Claim Reminder renders nothing.
## What the user sees
The card names one brand and shows a countdown. Encore picks the claim to show:
* **One claim, the newest the sheet lists.** Among the user's open claims whose offer the reward sheet lists, the card shows the one claimed most recently.
* **Only claims the user can still finish.** A claim the brand already confirmed as completed, or one the user already reported finishing, is never shown.
* **Only inside the reminder window.** The reminder shows for a set number of hours after the claim (24 by default, set by Encore). After that, the card hides. The device remembers the window it was last served at each placement, across launches; until one is served there, it uses 24 hours.
* **Only when the sheet has offers.** The card shows only when the reward sheet for its use case and placement has offers to list.
**The countdown is a reminder window, not an offer deadline.** It counts down to the moment the card hides. When it reaches zero, nothing happens to the claim: it stays open, and the user can still finish the offer.
**A tap opens the reward sheet** for Claim Reminder's use case and placement, as if your app had called `show()` there. The claimed offer is in the sheet, though not always first. Picking it again there continues the same claim rather than starting a second one. If the card is dismissible, the user can also close it. A dismissed reminder stays hidden for that claim on that device for good. The claim itself is untouched.
Claim Reminder checks the user's claims again each time your app returns to the foreground, and when the sheet it opened closes. When the brand confirms the user finished, the card hides, or shows a thanks look in its place (see [After a completion](#after-a-completion)).
## Place it in your layout
Use the `ClaimReminder` shorthand for your platform. Give it a placement ID and, optionally, your `appearance`, which colors the entry and never the sheet it opens. Encore picks the look:
```swift iOS (SwiftUI) theme={null}
import Encore
import SwiftUI
struct HomeView: View {
var body: some View {
ScrollView {
VStack(spacing: 16) {
ClaimReminder(
placement: "home",
appearance: AppearanceConfig(accentColor: "#5671FF")
)
// The rest of your home screen.
}
.padding()
}
}
}
```
```swift iOS (UIKit) theme={null}
import Encore
import UIKit
final class HomeViewController: UIViewController {
private let stack = UIStackView()
override func viewDidLoad() {
super.viewDidLoad()
stack.axis = .vertical
stack.spacing = 16
stack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stack)
NSLayoutConstraint.activate([
stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
stack.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
stack.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
])
let reminder = ClaimReminderView(
placement: "home",
appearance: AppearanceConfig(accentColor: "#5671FF")
)
stack.addArrangedSubview(reminder)
// Add the rest of your home screen to the stack.
}
}
```
```kotlin Android (Compose) theme={null}
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import com.encorekit.encore.AppearanceConfig
import com.encorekit.encore.ClaimReminder
@Composable
fun HomeScreen() {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
ClaimReminder(
placement = "home",
appearance = AppearanceConfig(accentColor = "#5671FF"),
)
// The rest of your home screen.
}
}
```
```kotlin Android (View) theme={null}
import android.os.Bundle
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import com.encorekit.encore.AppearanceConfig
import com.encorekit.encore.ClaimReminderView
class HomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val column = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
setContentView(column)
val reminder = ClaimReminderView(
context = this,
placement = "home",
appearance = AppearanceConfig(accentColor = "#5671FF"),
)
column.addView(reminder)
// Add the rest of your home screen to the column.
}
}
```
```tsx React Native theme={null}
import { ScrollView } from 'react-native';
import { EncoreClaimReminder } from '@encorekit/react-native';
export function HomeScreen() {
return (
{/* The rest of your home screen. */}
);
}
```
```dart Flutter theme={null}
import 'package:flutter/material.dart';
import 'package:encore_flutter/encore_flutter.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return ListView(
children: [
EncoreClaimReminder(
placement: 'home',
appearance: AppearanceConfig(accentColor: '#5671FF'),
),
// The rest of your home screen.
],
);
}
}
```
```javascript Web SDK theme={null}
import Encore from '@encorekit/web-sdk';
// Call configure() first, as in the Web quickstart.
const handle = Encore.triggers.claimReminder.mount(document.getElementById('claim-reminder'), {
placement: 'home',
appearance: { accentColor: '#5671FF' },
});
// Call this from your own teardown, when you remove the element.
export function removeCard() {
handle.unmount();
}
```
```tsx Web SDK (React) theme={null}
import { ClaimReminder } from '@encorekit/web-sdk/react';
// Render inside your EncoreProvider.
export function Home() {
return (
{/* The rest of your home screen. */}
);
}
```
```csharp Unity theme={null}
using EncoreKit;
using UnityEngine;
// Or add EncoreClaimReminderView to an empty RectTransform in your Canvas, and it follows that element.
public class HomeScreen : MonoBehaviour
{
private ClaimReminder _reminder;
private void Start()
{
_reminder = ClaimReminder.Create("home", new TriggerOptions
{
Appearance = new AppearanceConfig { AccentColor = "#5671FF" },
});
_reminder.SetFrame(new Rect(40, Screen.height - 200, Screen.width - 80, 0)); // Unity screen space; the card sets its own height
}
private void OnDestroy() => _reminder?.Dispose();
}
```
### Or use the trigger host
Each shorthand is the [trigger host](/publishers/triggers/quickstart#the-trigger-host) with the ID `claimReminder` built in, and renders the same view. Use the host instead when your app places several trigger components through one code path. Both take `useCase`, `appearance`, `publisherReward`, `onResult`, and `alignment`.
| Platform | Shorthand | Same view through the host |
| - | - | - |
| iOS (SwiftUI) | `ClaimReminder(placement:useCase:icon:appearance:publisherReward:onResult:alignment:)` | `EncoreTrigger("claimReminder", placement:useCase:autoOpen:icon:appearance:publisherReward:onResult:alignment:)` |
| iOS (UIKit) | `ClaimReminderView(placement:useCase:icon:appearance:publisherReward:onResult:alignment:)`, each also settable as a property | `EncoreTriggerView(id: "claimReminder", placement:useCase:autoOpen:icon:appearance:alignment:)`, with the same properties |
| Android (Compose) | `ClaimReminder(placement, useCase, icon, appearance, publisherReward, onResult, alignment)` | `EncoreTrigger(id, placement, useCase, autoOpen, icon, appearance, publisherReward, onResult, alignment)` with `id = "claimReminder"` |
| Android (View) | `ClaimReminderView(context, placement, useCase, icon, appearance, publisherReward, onResult)` with `alignment` set as a property, or `` in XML | `EncoreTriggerView(context, id, placement, useCase, autoOpen, icon, appearance)` with `id = "claimReminder"` and the rest set as properties, or `app:encoreTriggerId="claimReminder"` in XML |
| React Native | `` | `` |
| Flutter | `EncoreClaimReminder(placement:, useCase:, icon:, appearance:, publisherReward:, onResult:, alignment:)` | `EncoreTrigger(id: 'claimReminder', placement:, useCase:, autoOpen:, icon:, appearance:, publisherReward:, onResult:, alignment:)` |
| Web SDK | `Encore.triggers.claimReminder.mount(element, options)` | `Encore.triggers.mount('claimReminder', element, options)` |
| Web SDK (React) | `` | `` |
| Unity | `ClaimReminder.Create(placement, options)`, or `EncoreClaimReminderView` in the Inspector. See [`ClaimReminder`](/publishers/unity/sdk-reference/claim-reminder) | `EncoreTrigger.Create("claimReminder", placement, options)`, or `EncoreTriggerView` with `triggerId` set to `claimReminder`. See [`EncoreTrigger`](/publishers/unity/sdk-reference/encore-trigger) |
## Your text
Pass `headline` to replace the card's title, and `cta` to relabel its button, the same way you set them on [Gifts Button](/publishers/triggers/gifts-button#your-text). Leave either out and the look's own copy shows, in the user's language. Only the `featured` look draws a button, and no look draws a subheadline today, so a `cta` or `subheadline` that a look has no place for leaves its copy as it is. Screen readers still read the brand's name when your headline replaces the title. See [Your text](/publishers/triggers/overview#your-text) for the rules on length and line breaks.
## Looks
Encore picks the look, and can test several against each other. These are the looks it serves today, each 76 tall except `featured`, which is 85 (points on iOS, `dp` on Android, CSS pixels on the web). The whole card is one control that opens the sheet, named for assistive technology by its title and the brand. The arrow is its own control, and so is the × when the look is dismissible.
| Look | What it shows |
| - | - |
| `progressBar` | A gift icon, the title, and a bar that drains as the reminder window runs out, with the time left |
| `logoProgress` | The brand's logo (or its first letter when there's no logo), a two-step progress line, the title, and a countdown |
| `countdownHero` | A large hours, minutes, and seconds countdown over the title, with an arrow |
| `featured` | A taller card with rounder corners: the brand's logo (or its first letter), the title, and the hours and minutes left, such as "23:32 left", beside a Continue button. Its background runs from `backgroundColor` to `backgroundEndColor` when you set both, else it is solid |
| `logoMarquee` | The title and countdown beside two columns of logos that scroll slowly, one logo per brand the user has an open claim with inside the reminder window, up to 8. They move only when there are at least 3 logos, stop while the card is off screen, and stay still when the user has reduced motion turned on. The card still names only the newest claim |
Encore can change these looks, or add new ones, without an app update.
## Pass your prize and read the result
Claim Reminder opens a reward sheet, so it takes `publisherReward` and `onResult` with the same rules as Gifts Button. It hands your prize to every sheet it opens and calls `onResult` once per sheet, after it closes. See [Pass your prize and read the result](/publishers/triggers/gifts-button#pass-your-prize-and-read-the-result) for the grant rules, the web caveat, and samples for every platform; swap in the `ClaimReminder` shorthand for your platform.
## After a completion
When the user finishes the offer they were reminded about, Encore decides what the spot shows for the rest of their day, and can test the choices against each other:
* **Nothing** (the usual choice), until the user claims another offer.
* **A thanks look**: "Nice work, you finished it" with a button that opens the reward sheet. A tap opens the sheet and ends the thanks look, and so do a new claim and midnight on the user's device. Its events carry the layout `thanks`.
There is nothing to set: the behavior comes with the look Encore serves.
## When it renders nothing
On top of the cases every trigger component shares (see [Troubleshooting](/publishers/triggers/troubleshooting#it-isnt-showing)), Claim Reminder renders nothing when:
* The user has no open claim, or none inside the reminder window.
* The user's open claims are all completed, either confirmed by the brand or reported finished by the user.
* The reward sheet for its use case and placement doesn't list the claimed offer, for example because the user has an open claim but the sheet has no offers to show.
* The user dismissed the reminder for that claim on this device.
## What Encore controls
The served look sets these, not your code:
* **Look.** One of the [looks](#looks), including its height.
* **Copy.** The card's text, in the user's language, for each line you don't [set yourself](/publishers/triggers/overview#your-text).
* **Reminder window.** How many hours after the claim the card shows, from 1 to 720. 24 by default.
* **Dismissible.** Whether the user can close the card.
* **Default colors.** The look's colors in the [color order](/publishers/triggers/overview#colors). Yours always win.
The card's copy never says the offer expires or that the user loses it, because neither happens.
## Analytics
Claim Reminder reports its own impressions, taps, and dismissals to Encore's analytics. You don't send any events.
## Related
* [Trigger components](/publishers/triggers/overview): how trigger components work, heights, and colors.
* [Quickstart](/publishers/triggers/quickstart) and [Experiments and looks](/publishers/triggers/experiments).
* [Gifts Button](/publishers/triggers/gifts-button): the other trigger component, and the full prize and result samples.
* [Localization](/publishers/concepts/localization): how the card's copy reaches the user's language.
* `AppearanceConfig` on the web: [Advanced UI](/publishers/web/guides/advanced-ui).
# Build your own button
Source: https://docs.encorekit.com/publishers/triggers/custom-ui
Draw your own gifts button or claim reminder while Encore decides what it shows, counts its views and taps, and opens the reward sheet.
> [!NOTE]
>
> **Requires SDK 2.4.0+** on every platform. See [Minimum SDK versions](/publishers/triggers/overview#minimum-sdk-versions).
[Gifts Button](/publishers/triggers/gifts-button) and [Claim Reminder](/publishers/triggers/claim-reminder) are the recommended way in: one line each, and Encore can change and test their looks without an app update. When your design needs the entry drawn in your app's own style, draw it yourself instead of skipping the entry. Encore still does everything behind it: it decides when the entry should show and what it shows, counts each view and tap, opens the reward sheet, and hands you the result. After a claim, your entry can turn into a reminder for that claim (it does by default), as [Gifts Button does](/publishers/triggers/gifts-button#after-a-claim).
Everything on [Trigger components](/publishers/triggers/overview) about the reward sheet, claims, and analytics applies. What differs: you draw it, so Encore's looks, heights, copy, and colors don't apply.
## How it works
You create one claim handle per placement and read its state. The state says what to draw:
| State | When | What it carries |
| - | - | - |
| `hidden` | The reward sheet has no offers for this user at this placement (its own holdout included), the offers could not be read, the SDK isn't configured yet, the use case is the churn one, or Encore's rules hide the entry after a completion | Nothing. Draw nothing |
| `gifts` | The reward sheet has offers | The number of offers, and up to eight of their brands' logos |
| `reminder` | The user claimed an offer this placement's sheet still lists, and hasn't finished it | The brand's name and logo, the offer's perk, when it was claimed, when the reminder ends (24 hours after the claim), and how many claims are open |
| `thanks` | When Encore shows a thank you: the user finished an offer today, hasn't claimed another or tapped your entry since, and the sheet has more offers | The number of offers, and up to eight of their brands' logos, as for `gifts`. A tap opens the sheet and ends it |
You attach your view to the handle. Encore then counts a view when at least half of it is on screen for one second with no sheet over it. On iOS, Android, React Native and the web, a tap on the attached view opens the reward sheet for that placement; on Flutter, call `claim.tap()` from your view. A tap while the state is `hidden` does nothing.
The state changes on its own: by default it turns into the reminder after the user claims an offer and back into gifts when the claim is finished, its 24 hours end, or the user dismisses it, and to hidden when the offers run out. Encore can change what follows a claim and a completion (below). Redraw whenever it changes.
## Add it
```swift iOS theme={null}
@StateObject var claim = Encore.claim(placement: "streak")
var body: some View {
switch claim.state {
case .hidden:
EmptyView()
case .gifts(let gifts):
StreakGiftRow(count: gifts.offerCount, logos: gifts.logoURLs)
.encoreClaim(claim)
case .reminder(let reminder):
MyReminder(name: reminder.advertiserName, until: reminder.deadline,
onOpen: { Task { await claim.tap() } },
onClose: { claim.dismiss() })
.encoreClaim(claim, handlesTap: false)
case .thanks(let gifts):
MyThanksRow(count: gifts.offerCount)
.encoreClaim(claim)
}
}
```
```kotlin Android theme={null}
val claim = rememberEncoreClaim(placement = "streak")
when (val state = claim.state) {
is ClaimState.Hidden -> Unit
is ClaimState.Gifts -> StreakGiftRow(state.offerCount, state.logoUrls,
Modifier.encoreClaim(claim))
is ClaimState.Reminder -> MyReminder(state.advertiserName, state.deadline,
onOpen = { claim.tap() },
onClose = claim::dismiss,
modifier = Modifier.encoreClaim(claim, handlesTap = false))
is ClaimState.Thanks -> MyThanksRow(state.offerCount, Modifier.encoreClaim(claim))
}
```
```tsx React Native theme={null}
const { claim, state, tap, dismiss } = useEncoreClaim({ placement: 'streak' });
if (state.kind === 'hidden') return null;
return (
{state.kind === 'reminder' ? (
tap()} onClose={dismiss} />
) : state.kind === 'thanks' ? (
) : (
)}
);
```
```dart Flutter theme={null}
EncoreClaim(
placement: 'streak',
builder: (context, state, claim) => switch (state) {
EncoreClaimHiddenState() => const SizedBox.shrink(),
EncoreClaimGiftsState(:final offerCount) => MyGiftRow(count: offerCount, onTap: claim.tap),
EncoreClaimReminderState(:final advertiserName, :final deadline) =>
MyReminder(name: advertiserName, until: deadline,
onTap: () => claim.tap(target: EncoreClaimTarget.card), onClose: claim.dismiss),
EncoreClaimThanksState(:final offerCount) => MyThanksRow(count: offerCount, onTap: claim.tap),
},
)
```
```javascript Web SDK theme={null}
const claim = Encore.claim({ placement: 'streak', onResult: (result) => {} });
const row = document.querySelector('#my-gift-row');
const unsubscribe = claim.subscribe((state) => {
row.hidden = state.kind === 'hidden';
if (state.kind === 'gifts') row.textContent = `${state.offerCount} gifts waiting`;
if (state.kind === 'reminder') row.textContent = `Finish your ${state.advertiserName} gift`;
if (state.kind === 'thanks') row.textContent = 'Thanks! More gifts are waiting';
});
const unbind = claim.bind(row);
// When you remove the row, let go of everything above.
function removeRow() {
unsubscribe();
unbind();
claim.destroy();
row.remove();
}
```
```tsx Web SDK (React) theme={null}
const { state, ref } = useEncoreClaim({ placement: 'streak' });
if (state.kind === 'hidden') return null;
return (
);
```
The options are `placement` (required), `useCase`, `autoOpen`, `publisherReward`, and `onResult`.
**Encore decides what comes next.** As with Gifts Button, Encore sets what your entry shows after a claim and after a completion, and can test it, without an app update. After a claim the state can turn into `reminder` or stay `gifts`; after a completed claim it can be `gifts`, `hidden`, or `thanks`. Draw every state and your entry follows. When Encore's rules can't be read, a claim turns the state into `reminder` and a completion turns it back into `gifts`, as by default, so a failed rules request never hides your entry. If the offers themselves can't be read, the state is `hidden`, as for the drop-in trigger components.
**Opening by itself.** Encore may open the reward sheet by itself when a test calls for it: at most once a day per placement, only after your view was really on screen, only while your app is in the foreground, and never over another Encore sheet. Set `autoOpen` to off to never: `autoOpen: .off` on iOS, `AutoOpen.OFF` on Android, `AutoOpen.off` on React Native, `EncoreAutoOpen.off` on Flutter, and `'off'` on the web.
On Android, `claim.state` is a Compose state, so a Compose view that reads it redraws on every change; outside Compose, collect `claim.stateFlow`. For Views or code outside Compose, make the handle with `Encore.claim(placement = "streak")`, attach a view with `claim.bind(view)`, and call `claim.close()` when you no longer need it. `rememberEncoreClaim` closes its handle when it leaves the composition. The reminder state also carries `perk`, the offer's perk as the sheet showed it.
## Show your entry only when there are offers
A user should never keep seeing an empty entry. Some users have no offers: for example, when your app passed the user's age as under 18 and every offer at the placement is rated 18+, because Encore serves a user known to be under 18 only offers rated for their age. Encore's own trigger components hide themselves then. An entry you draw must hide too.
**Recommended: use `Encore.claim`.** It loads the offers in the background without opening anything, so you draw your entry only while the claim has offers. From 2.5.0, `claim.hasOffers` says so in one value. On 2.4.0, draw while `claim.state` isn't `hidden`, as [Add it](#add-it) does on every platform.
From 2.5.0, one rule covers every entry:
* **A button you draw: `Encore.claim`.** Draw the button only while `claim.hasOffers` is true.
* **A sheet from your own flow: `Encore.placement`.** Ask `hasOffers()` before you show the item that opens the sheet, such as a "Get a gift" row at the end of a level.
A button that stays on screen should use the claim, because a placement answers once, at the moment you ask.
### With `hasOffers`, from 2.5.0
> [!NOTE]
>
> `hasOffers` is available from 2.5.0 of the iOS, Android, and web SDKs. On 2.4.0, draw while `claim.state` isn't `hidden`, as [Add it](#add-it) does. On earlier versions, use [the pattern for those versions](#without-an-sdk-update).
On a claim, `claim.hasOffers` is true when the last check found at least one offer. It is false while the state is `hidden`: before the first check, after a failed check, and when no offer fits the user. On iOS, `hasOffersPublisher` sends the same value for UIKit and Combine. On Android, `hasOffersFlow` is the same value as a `StateFlow` for Views. On the web with React, `claimHasOffers(state)` reads it from the state of `useEncoreClaim`.
```swift iOS theme={null}
@StateObject var claim = Encore.claim(placement: "streak")
var body: some View {
if claim.hasOffers {
MyGiftButton().encoreClaim(claim)
}
}
```
```swift iOS (UIKit) theme={null}
let claim = Encore.claim(placement: "streak") // keep it on self
unbind = claim.bind(giftButton) // counts the view and opens the sheet on a tap; call unbind() to undo
claim.hasOffersPublisher
.sink { [weak self] hasOffers in self?.giftButton.isHidden = !hasOffers } // use the value, not claim.hasOffers
.store(in: &cancellables)
```
```kotlin Android theme={null}
val claim = rememberEncoreClaim(placement = "streak")
if (claim.hasOffers) MyGiftButton(Modifier.encoreClaim(claim))
```
```kotlin Android (Views) theme={null}
val claim = Encore.claim(placement = "streak")
claim.bind(giftButton)
lifecycleScope.launch { claim.hasOffersFlow.collect { giftButton.isVisible = it } }
```
```javascript Web SDK theme={null}
const claim = Encore.claim({ placement: 'streak' });
const button = document.querySelector('#gifts');
claim.bind(button);
claim.subscribe(() => {
button.hidden = !claim.hasOffers;
});
```
```tsx Web SDK (React) theme={null}
import { claimHasOffers, useEncoreClaim } from '@encorekit/web-sdk/react';
const { state, ref } = useEncoreClaim({ placement: 'streak' });
return claimHasOffers(state) ? : null;
```
On a placement, `await placement(id).useCase(rewardUsers).hasOffers()` answers whether `show()` would find reward offers for this user now. Chain the reward use case: the builder's default is the churn use case, and on it `hasOffers()` always answers false. Any failure also answers false. It never throws. Ask when you decide to show the item, not once at app start.
```swift iOS theme={null}
let reward = Encore.placement("level_end").useCase(.rewardUsers)
showGiftRow = await reward.hasOffers() // starts false; the row's tap calls: await reward.show()
```
```kotlin Android theme={null}
val reward = Encore.placement("level_end").useCase(UseCase.REWARD_USERS)
giftRow.isVisible = false
lifecycleScope.launch {
if (reward.hasOffers()) {
giftRow.setOnClickListener { lifecycleScope.launch { reward.show() } }
giftRow.isVisible = true
}
}
```
```javascript Web SDK theme={null}
const reward = Encore.placement('level_end').useCase('rewardUsers');
button.hidden = true;
if (await reward.hasOffers()) {
button.addEventListener('click', () => void reward.show());
button.hidden = false;
}
```
On Android, `hasOffers { result -> }` is the callback form. It calls you once, on the main thread.
Keep the item hidden until `hasOffers()` answers, as the samples do, so no tap opens the sheet before the check. After `true`, the next `show()` usually uses the same offers and makes no second search. A `false` stays for up to 5 minutes, so asking often sends no extra requests; a new user, new user attributes, or a new language ask again.
React Native and Flutter don't have `hasOffers` yet. Use the claim state, as in [Add it](#add-it).
### Without an SDK update
On 2.3.1 and earlier (2.3.0 and earlier on the web), there's no way to check for offers without opening the sheet: `show()` opens it right away whenever there are offers. So never call `show()` at launch or when a screen appears to check for offers. Draw your button, call `show()` only from its tap, and when that tap comes back with no offers, hide the button for the rest of the session. The user still sees one empty tap.
Keep the flag in state that lasts for the session, not in a view that is rebuilt. Clear it when the app restarts and when the user changes, on `identify()` or `reset()`, because offers are per user.
```swift iOS theme={null}
let result = await Encore.placement("level_end").useCase(.rewardUsers).show()
if case .notPresented(.noOffers) = result {
rewardEntryHidden = true // until restart, identify() or reset()
}
```
```kotlin Android theme={null}
val result = Encore.placement("level_end").useCase(UseCase.REWARD_USERS).show()
if (result is PresentationResult.NotPresented && result.reason == NotPresentedReason.NoOffers) {
rewardEntryHidden = true // until restart, identify() or reset()
}
```
```javascript Web SDK theme={null}
const result = await Encore.placement('level_end').useCase('rewardUsers').show();
if (result.status === 'unavailable') {
rewardEntryHidden = true; // until reload, identify() or reset()
}
```
On the web, `unavailable` also means a measurement control cohort, no sheet for the use case, or a failed request for the sheet's settings. So on the web, one network error can also hide the button until the flag clears. On React Native, the result is `not_presented` and `reason.type` is `no_offer_available`. On Flutter, it is `EncoreNotPresented` with reason `noOffers`.
The result types are in each SDK's reference: [iOS](/publishers/ios/sdk-reference/presentation-result), [Android](/publishers/android/sdk-reference/presentation-result), [web](/publishers/web/sdk-reference/placement), [React Native](/publishers/react-native/sdk-reference/presentation-result), [Flutter](/publishers/flutter/sdk-reference/presentation-result).
## A view with its own buttons
When your view has buttons of its own, such as a close button on your reminder, don't let the whole view open the sheet. Report what's visible and call the tap yourself:
* **iOS and Android:** pass `handlesTap: false` to the modifier (on an Android View, `claim.bind(view, handlesTap = false)`), and call `claim.tap()` from your own button. On iOS, `tap()` returns the sheet's result; on Android, pass `onDone` to get it, as in `claim.tap(onDone = { result -> })`. To grant a prize, use `onResult` instead (see [Pass your prize and read the result](#pass-your-prize-and-read-the-result)).
* **React Native:** pass `handlesTap={false}` to `EncoreClaimView`, and call `tap()` from `useEncoreClaim` in your own button.
* **Flutter:** `EncoreClaim` never opens the sheet from a tap by itself; call `claim.tap()` from your own buttons, with `target: EncoreClaimTarget.card` for a reminder card. It returns the sheet's result.
* **Web:** `bind(element, { tap: false })` counts the whole element's visibility and leaves taps to you; call `claim.tap()` from your button. In React, pass `tap: false` to `useEncoreClaim` and put `ref` on the element. Even with taps on, a click that starts on a control inside the bound element, such as your close button, never opens the sheet.
Keep your own buttons inside the same check as the entry, so they never show while the claim has no offers. See [Show your entry only when there are offers](#show-your-entry-only-when-there-are-offers).
`claim.dismiss()` hides the reminder, every claim it was showing, on this device. Call it from your close button. It does nothing while the state isn't `reminder`.
## Pass your prize and read the result
Pass `publisherReward` and `onResult` when you create the handle, as for [Gifts Button](/publishers/triggers/gifts-button#pass-your-prize-and-read-the-result). `onResult` is called once per sheet the handle opens, after the sheet closes, whether the tap came from your attached view or from your own `claim.tap()`. The result `tap()` returns is the same one, so grant your prize in `onResult` only, or an app that grants from both pays twice.
The grant rule is the same as for Gifts Button. Everywhere but the web, grant when `userConfirmedCompletion` is true on the result's claim, keyed on the transaction ID. On the web, keep the claim's `transactionId` and grant when the `offer_completed` webhook confirms it.
```swift iOS theme={null}
@StateObject var claim = Encore.claim(
placement: "streak",
publisherReward: PublisherReward(id: "coins_100", title: "100 coins"),
onResult: { result in
if let claim = result.claim, claim.userConfirmedCompletion {
// Grant once per claim: key on the transaction, else on this user and campaign.
grantCoins(100, dedupeKey: claim.transactionId ?? "\(userId):\(claim.campaignId)")
}
}
)
```
```kotlin Android theme={null}
val claim = rememberEncoreClaim(
placement = "streak",
publisherReward = PublisherReward(id = "coins_100", title = "100 coins"),
onResult = { result ->
val done = result.claim
if (done != null && done.userConfirmedCompletion) {
// Grant once per claim: key on the transaction, else on this user and campaign.
grantCoins(100, dedupeKey = done.transactionId ?: "$userId:${done.campaignId}")
}
},
)
```
```tsx React Native theme={null}
const { claim, state, tap, dismiss } = useEncoreClaim({
placement: 'streak',
publisherReward: { id: 'coins_100', title: '100 coins' },
onResult: (result) => {
if (result.status === 'presented' && result.claim?.userConfirmedCompletion) {
// Grant once per claim: key on the transaction, else on this user and campaign.
grantCoins(100, result.claim.transactionId ?? `${userId}:${result.claim.campaignId}`);
}
},
});
```
```dart Flutter theme={null}
EncoreClaim(
placement: 'streak',
publisherReward: const EncorePublisherReward(id: 'coins_100', title: '100 coins'),
onResult: (result) {
final claim = result.claim;
if (claim != null && claim.userConfirmedCompletion) {
// Grant once per claim: key on the transaction, else on this user and campaign.
grantCoins(100, claim.transactionId ?? '$userId:${claim.campaignId}');
}
},
builder: (context, state, claim) => MyEntry(state: state, claim: claim),
)
```
```javascript Web SDK theme={null}
const claim = Encore.claim({
placement: 'streak',
publisherReward: { id: 'coins_100', title: '100 coins' },
onResult: (result) => {
// A claim isn't a completion: keep its transaction ID and grant on the offer_completed webhook.
if (result.status === 'claimed' && result.transactionId) saveClaim(result.transactionId);
},
});
```
## Accessibility
You own the labels. When the handle takes the tap, each platform makes your view one control, and you give it a label that says what a tap does:
* **iOS:** `.encoreClaim(claim)` adds the button trait to the view it modifies. On a stack with several children, SwiftUI passes that trait to each child, so VoiceOver reads every text and image as a separate button. Combine the children into one element and label it, before the modifier:
```swift theme={null}
StreakGiftRow(count: gifts.offerCount, logos: gifts.logoURLs)
.accessibilityElement(children: .combine)
.accessibilityLabel("\(gifts.offerCount) gifts waiting")
.encoreClaim(claim)
```
With `handlesTap: false` the modifier adds no trait, so your own buttons, such as a close button, stay separate elements.
* **Android:** `Modifier.encoreClaim(claim)` makes the view one clickable element with the button role, and TalkBack reads its children's text as one label. When that text doesn't say what a tap does, add a `contentDescription` with `Modifier.semantics`. On an Android View, `claim.bind(view)` only sets a click listener, so set the view's `contentDescription` yourself.
* **React Native:** `EncoreClaimView` wraps your children in one `Pressable` with the button role. Pass it `accessibilityLabel`.
* **Flutter:** `EncoreClaim` adds no semantics, because your own widgets call `claim.tap()`. Wrap an entry made of several widgets in `MergeSemantics`, or in `Semantics(button: true, label: ...)`.
* **Web:** `bind(element)` makes an element that isn't already a button or link behave like one: it adds `role="button"`, lets it take keyboard focus, and opens the sheet on Enter and Space. Give it an `aria-label` when its text isn't enough.
## Testing your states
Draw every state, then check each one on a debug build with your test API key (`pk_test_…`), which serves a demo catalog:
* **`gifts`:** shows once the reward sheet at your placement has offers. On the test key it does.
* **`hidden`:** shows at a placement whose sheet has no offers, and before `configure()`. Check that your screen looks right without the entry.
* **`reminder`:** open the sheet from your entry and claim an offer. The test key lets the claim go through without a live campaign. Back in your app, the state turns into `reminder` for 24 hours. Your close button's `claim.dismiss()` turns it back into `gifts`.
* **`thanks`:** opt-in on Encore's side. After a completion the default is `gifts`, so you see `thanks` only once Encore turns it on for your app. Ask your Encore contact to turn it on for your test app if you want to check it.
Claims are kept per user on the device. To start over, `identify()` a new test user. The SDKs have no public hooks for adding or clearing claims.
## Experiments and analytics
Encore can test what your entry does after a claim and after a completion, as it tests the drop-in trigger components. The reward sheet it opens takes part in its own experiments too: when the sheet's experiment holds a user out, the state is `hidden`.
Encore reports your entry's views, taps, and dismissals as it does for its own trigger components, marked as your own button. You don't send any events.
> [!WARNING]
>
> Don't also mount a Gifts Button or Claim Reminder at the same placement and screen as your own entry: the user would see two entries for one sheet.
## Related
* [Gifts Button](/publishers/triggers/gifts-button): Encore's own gifts entry, and what happens after a claim.
* [Claim Reminder](/publishers/triggers/claim-reminder): what the reminder shows, and when.
* [Trigger components](/publishers/triggers/overview): what every trigger component shares.
# Experiments and looks
Source: https://docs.encorekit.com/publishers/triggers/experiments
How Encore picks and tests a trigger component's look, and what that means for your screens and your numbers.
A trigger component's look comes from Encore. This page explains how Encore picks and tests looks, and what you can expect to see while a test runs.
> [!NOTE]
>
> **Requires SDK 2.4.0+** on every platform. See [Minimum SDK versions](/publishers/triggers/overview#minimum-sdk-versions).
## How Encore picks a look
When Encore runs an experiment for a trigger component in your app, the user gets that experiment's look; otherwise they get the trigger component's default look. Encore can change or retest the look without an app update, and there is nothing to set in code. The looks Encore serves today are listed on each trigger component's page: [Gifts Button](/publishers/triggers/gifts-button#looks) and [Claim Reminder](/publishers/triggers/claim-reminder#looks).
## How Encore tests looks
Encore tests the looks of one trigger component for one use case: for example, the Gifts Button's card against its banner at reward moments.
* **One assignment per user.** Encore assigns each user once, and every entry of that trigger component, on every placement, uses the same look for that user.
* **Only users who could see it are counted.** A trigger component checks that the reward sheet has offers before it asks Encore which look to show. A user with nothing to show is never assigned, so they don't dilute the results.
* **What's measured.** Encore compares what users do after seeing each look, such as how many of them claim and finish an offer, not only how many tap.
* **What you do.** Nothing in code. Encore sets up and reads the experiment. Ask your Encore contact about the looks you would like tested.
### The holdout group
An experiment can hold some users out on purpose: either they see nothing even when the entry would show, or they see the default look. Encore compares them with the users who see the experiment's looks, which is how it measures whether the trigger component changes what users do. So expect the entry to be missing for some users at times. That is the holdout working, not a bug. A Claim Reminder's holdout always sees the default look, never nothing, because it shows a gift the user already claimed.
## Turning a trigger component on
Encore sets a default look for each trigger component when it turns it on in your app, and runs experiments on top of it. Until then, the entry renders nothing, so you can ship your screens with trigger components in them before they're switched on. To turn one on, ask your Encore contact or write to [admin@encorekit.com](mailto:admin@encorekit.com).
## Looks and SDK versions
A new look Encore adds later may use something an older SDK can't draw. Encore only serves a user a look their SDK version supports. If an older SDK ever receives a look it can't draw, it renders nothing instead of drawing it wrong, and logs a warning.
## Related
* [Trigger components](/publishers/triggers/overview)
* [Gifts Button](/publishers/triggers/gifts-button) and [Claim Reminder](/publishers/triggers/claim-reminder)
* [Troubleshooting](/publishers/triggers/troubleshooting)
# Gifts Button
Source: https://docs.encorekit.com/publishers/triggers/gifts-button
A trigger component that shows a gift entry at a reward moment and opens the reward sheet when the user taps it.
Gifts Button is a [trigger component](/publishers/triggers/overview): a "you have a gift" entry you place at a reward moment in your app, for example right after the user finishes a streak. Instead of your app opening the reward sheet on its own, the user sees the entry and opens the sheet when they choose to. Tapping it opens the same reward sheet that `show()` presents for that placement, with the same premium brand offers, each one a real perk a brand funds to acquire customers.
Its trigger ID is `giftsButton`. Everything on [Trigger components](/publishers/triggers/overview) applies to it. This page covers only what is specific to Gifts Button.
> [!NOTE]
>
> **Requires SDK 2.4.0+** on every platform. See [Minimum SDK versions](/publishers/triggers/overview#minimum-sdk-versions).
## When to use it
Use Gifts Button on the screen where you would otherwise call `show()` for a [reward](/publishers/use-cases/post-action-reward), for example the screen that celebrates a finished streak. Mount it there **in place of** your own `show()` call for that moment, not as well as it. Keeping both can present the sheet twice.
Its use case defaults to the reward use case, so leave `useCase` out. Churn isn't supported yet: with the churn use case, Gifts Button renders nothing.
## What the user sees
* **An entry, only when there's a gift.** Gifts Button checks for offers for its use case and placement, the same check `show()` makes before it presents. With no offers, it renders nothing. If you draw your own button, it must hide too: see [Show your entry only when there are offers](/publishers/triggers/custom-ui#show-your-entry-only-when-there-are-offers).
* **A tap opens the reward sheet.** The sheet is the normal one for that use case and placement, as if your app had presented it.
* **It stays while offers remain.** When the sheet closes, Gifts Button checks again and hides only when no offers are left. The user can't dismiss it.
* **It may open the sheet once by itself.** When an Encore test calls for it, Gifts Button can open its sheet on its own: at most once a day at each placement, only while your app is in the foreground, and never over another Encore sheet. Set `autoOpen` to off to stop it.
## Place it in your layout
Use the `GiftsButton` shorthand for your platform. Give it a placement ID and, optionally, your `appearance`, which colors the entry and never the sheet it opens. Encore picks the look:
```swift iOS (SwiftUI) theme={null}
import Encore
import SwiftUI
struct StreakCompleteView: View {
var body: some View {
VStack(spacing: 16) {
Text("Streak complete")
GiftsButton(
placement: "milestone_reached",
appearance: AppearanceConfig(accentColor: "#5671FF")
)
}
.padding()
}
}
```
```swift iOS (UIKit) theme={null}
import Encore
import UIKit
final class StreakCompleteViewController: UIViewController {
private let stack = UIStackView()
override func viewDidLoad() {
super.viewDidLoad()
stack.axis = .vertical
stack.spacing = 16
stack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stack)
NSLayoutConstraint.activate([
stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
stack.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
stack.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
])
let gift = GiftsButtonView(
placement: "milestone_reached",
appearance: AppearanceConfig(accentColor: "#5671FF")
)
stack.addArrangedSubview(gift)
}
}
```
```kotlin Android (Compose) theme={null}
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import com.encorekit.encore.AppearanceConfig
import com.encorekit.encore.GiftsButton
@Composable
fun StreakCompleteScreen() {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text("Streak complete")
GiftsButton(
placement = "milestone_reached",
appearance = AppearanceConfig(accentColor = "#5671FF"),
)
}
}
```
```kotlin Android (View) theme={null}
import android.os.Bundle
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import com.encorekit.encore.AppearanceConfig
import com.encorekit.encore.GiftsButtonView
class StreakCompleteActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val column = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
setContentView(column)
val gift = GiftsButtonView(
context = this,
placement = "milestone_reached",
appearance = AppearanceConfig(accentColor = "#5671FF"),
)
column.addView(gift)
}
}
```
```tsx React Native theme={null}
import { View } from 'react-native';
import { EncoreGiftsButton } from '@encorekit/react-native';
export function StreakCompleteScreen() {
return (
);
}
```
```dart Flutter theme={null}
import 'package:flutter/material.dart';
import 'package:encore_flutter/encore_flutter.dart';
class StreakCompleteScreen extends StatelessWidget {
const StreakCompleteScreen({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
const Text('Streak complete'),
EncoreGiftsButton(
placement: 'milestone_reached',
appearance: AppearanceConfig(accentColor: '#5671FF'),
),
],
);
}
}
```
```javascript Web SDK theme={null}
import Encore from '@encorekit/web-sdk';
// Call configure() first, as in the Web quickstart.
const handle = Encore.triggers.giftsButton.mount(document.getElementById('gifts-button'), {
placement: 'milestone_reached',
appearance: { accentColor: '#5671FF' },
});
// Call this from your own teardown, when you remove the element.
export function removeCard() {
handle.unmount();
}
```
```tsx Web SDK (React) theme={null}
import { GiftsButton } from '@encorekit/web-sdk/react';
// Render inside your EncoreProvider.
export function StreakComplete() {
return (
Streak complete
);
}
```
```csharp Unity theme={null}
using EncoreKit;
using UnityEngine;
// Or add EncoreGiftsButtonView to an empty RectTransform in your Canvas, and it follows that element.
public class StreakComplete : MonoBehaviour
{
private GiftsButton _gifts;
private void Start()
{
_gifts = GiftsButton.Create("milestone_reached");
_gifts.SetFrame(new Rect(40, Screen.height - 200, Screen.width - 80, 0)); // Unity screen space; the button sets its own height
}
private void OnDestroy() => _gifts?.Dispose();
}
```
| Platform | Shorthand |
| - | - |
| iOS | `GiftsButton(placement:useCase:autoOpen:icon:appearance:publisherReward:onResult:alignment:)` (SwiftUI), `GiftsButtonView(placement:useCase:autoOpen:icon:appearance:publisherReward:onResult:alignment:)` (UIKit), each also settable as a property |
| Android | `GiftsButton(placement, useCase, autoOpen, icon, appearance, publisherReward, onResult, alignment)` (Compose), `GiftsButtonView(context, placement, useCase, autoOpen, icon, appearance, publisherReward, onResult)` (View, with `alignment` set as a property), or `` in XML |
| React Native | `` |
| Flutter | `EncoreGiftsButton(placement:, useCase:, autoOpen:, icon:, appearance:, publisherReward:, onResult:, alignment:)` |
| Web SDK | `Encore.triggers.giftsButton.mount(element, options)`, where `options` holds `placement`, `useCase`, `autoOpen`, `icon`, `appearance`, `publisherReward`, `onResult`, and `alignment` |
| Web SDK (React) | `` |
| Unity | `GiftsButton.Create(placement, options)`, where `options` holds `UseCase`, `AutoOpenOff`, `Icon`, `Alignment`, `Appearance`, `Headline`, `Subheadline`, `Cta`, and `Values`, or `EncoreGiftsButtonView` in the Inspector. See [`GiftsButton`](/publishers/unity/sdk-reference/gifts-button) |
Each shorthand is the [trigger host](/publishers/triggers/quickstart#the-trigger-host) with the ID `giftsButton`. The [parameters table](/publishers/triggers/quickstart#parameters) gives every default.
## Your text
Pass `headline`, `subheadline` and `cta` to put your own words on the entry, such as the name of the moment the user just reached:
```swift iOS theme={null}
GiftsButton(placement: "milestone_reached")
.headline("7 day streak!")
.subheadline("Pick a gift from our partners")
```
```kotlin Android theme={null}
GiftsButton(placement = "milestone_reached", headline = "7 day streak!", subheadline = "Pick a gift from our partners")
```
```tsx React Native theme={null}
```
```dart Flutter theme={null}
EncoreGiftsButton(placement: 'milestone_reached', headline: '7 day streak!', subheadline: 'Pick a gift from our partners')
```
```javascript Web SDK theme={null}
Encore.triggers.giftsButton.mount(element, { placement: 'milestone_reached', headline: '7 day streak!', subheadline: 'Pick a gift from our partners' });
```
```tsx Web SDK (React) theme={null}
```
Any line you leave out shows the look's own copy, in the user's language, and every look Encore tests falls back to its own words. A look shows your `cta` only when it draws a button or a label, as `banner` and `pill` do. See [Your text](/publishers/triggers/overview#your-text) for the rules on length and line breaks.
## Looks
Encore picks the look, and can test several against each other. These are the looks it serves today. It draws each one from a look file it can change without an app update, so treat the heights as defaults rather than constants.
| Look | What it looks like | Height |
| - | - | - |
| `card` | An inline gift card with a gift icon, a title, a subtitle, and a chevron | 76 |
| `banner` | A wider banner with a title, a subtitle, a button, and a soft glow | 88 |
| `pulse` | An animated gift box with rings and a title | 112 |
| `pill` | A compact capsule with a gift icon and a label | 48 |
| `offerMarquee` | The card with a strip of the logos of the brands in the reward sheet, scrolling sideways under "Pick a gift, on us". With fewer than three logos to show, it is the plain card | 76 |
| `offerColumns` | The card with the same logos in two short columns scrolling in opposite directions, beside "Pick a gift, on us". With fewer than three logos to show, it is the plain card | 76 |
| `giftCard` | The card with a gift card face in place of the icon, under "Your gift card" | 76 |
| `stillWaiting` | A plain card titled "Your gift is still waiting", with no timer | 76 |
Heights are in points on iOS, `dp` on Android, and CSS pixels on the web. Each look is one control, named for assistive technology by its copy. The `pulse` animation and the scrolling logos of `offerMarquee` and `offerColumns` pause while the entry is off screen and stay still when the user has reduced motion turned on.
## Pass your prize and read the result
When your app pays its own prize for trying an offer, pass it to Gifts Button as `publisherReward`. It is the same value you would pass to `placement(id).publisherReward(...)` before `show()`, with the same rules: a `PublisherReward` on iOS, Android, and React Native, and an `EncorePublisherReward` on Flutter. On the web it is a `PublisherReward` with the same fields: `id`, `title`, and the optional `detail` and `iconUrl`. Gifts Button hands it to every sheet it opens. Pass `onResult` to receive the result of each sheet Gifts Button opens. It is called once per sheet, after the sheet closes, with the same result `show()` returns. Both are optional; without them Gifts Button behaves exactly as described earlier on this page.
On iOS, Android, React Native, and Flutter, grant the prize from `onResult` only, when `userConfirmedCompletion` is true on the result's claim, with this grant key: the transaction ID, or your user ID plus `campaignId` when it is missing.
> [!WARNING]
>
> **On the web, the sheet doesn't show or grant your prize yet.** Gifts Button accepts `publisherReward` and passes it to the sheet, but the web sheet doesn't draw the promise or ask whether the user finished, and its result (a `ShowResult`) has no `userConfirmedCompletion` flag. A `claimed` result only means the user went to the brand, so never grant from it. Keep the claim's `transactionId` from `onResult`, as the web sample does, and grant from your server when the [offer\_completed webhook](/publishers/offers-api/guides/receive-completion-events) with that transaction ID confirms the completion.
### Other ways to learn about a claim
`onResult` is the main path, because it belongs to this one entry. Two other channels see the same claims:
* **The outcomes stream.** Every sheet Gifts Button opens resolves onto the same stream as your own `show()` calls: [`Encore.shared.outcomes`](/publishers/ios/sdk-reference/outcomes) on iOS, [`Encore.outcomes`](/publishers/android/sdk-reference/outcomes) on Android, [`Encore.shared.outcomes`](/publishers/flutter/sdk-reference/outcomes) on Flutter, [`Encore.onOutcome()`](/publishers/react-native/sdk-reference/outcomes) on React Native, and [`Encore.Outcomes`](/publishers/unity/sdk-reference/outcomes) on Unity. If your app already watches it, for analytics or entitlement sync, it sees Gifts Button's claims with no extra code. On the web, [`onStrictUnlockVerified()`](/publishers/web/sdk-reference/on-strict-unlock-verified) reports a claim the brand later confirms, in strict unlock mode.
* **The `offer_completed` webhook.** Your server hears about a completion the brand confirms, whichever surface the claim came from. See [Receive completion events](/publishers/offers-api/guides/receive-completion-events).
Pay the prize from one place only. The outcomes stream carries the same result `onResult` receives, so an app that grants from both pays twice.
```swift iOS (SwiftUI) theme={null}
GiftsButton(
placement: "milestone_reached",
publisherReward: PublisherReward(id: "coins_100", title: "100 coins"),
onResult: { result in
if let claim = result.claim, claim.userConfirmedCompletion {
// Grant once per claim: key on the transaction, else on this user and campaign.
grantCoins(100, dedupeKey: claim.transactionId ?? "\(userId):\(claim.campaignId)")
}
}
)
```
```swift iOS (UIKit) theme={null}
let gift = GiftsButtonView(placement: "milestone_reached")
gift.publisherReward = PublisherReward(id: "coins_100", title: "100 coins")
gift.onResult = { result in
if let claim = result.claim, claim.userConfirmedCompletion {
// Grant once per claim: key on the transaction, else on this user and campaign.
grantCoins(100, dedupeKey: claim.transactionId ?? "\(userId):\(claim.campaignId)")
}
}
```
```kotlin Android (Compose) theme={null}
import com.encorekit.encore.features.offers.PublisherReward
GiftsButton(
placement = "milestone_reached",
publisherReward = PublisherReward(id = "coins_100", title = "100 coins"),
onResult = { result ->
val claim = result.claim
if (claim != null && claim.userConfirmedCompletion) {
// Grant once per claim: key on the transaction, else on this user and campaign.
grantCoins(100, dedupeKey = claim.transactionId ?: "$userId:${claim.campaignId}")
}
},
)
```
```kotlin Android (View) theme={null}
import com.encorekit.encore.features.offers.PublisherReward
val gift = GiftsButtonView(context = this, placement = "milestone_reached")
gift.publisherReward = PublisherReward(id = "coins_100", title = "100 coins")
gift.onResult = { result ->
val claim = result.claim
if (claim != null && claim.userConfirmedCompletion) {
// Grant once per claim: key on the transaction, else on this user and campaign.
grantCoins(100, dedupeKey = claim.transactionId ?: "$userId:${claim.campaignId}")
}
}
```
```tsx React Native theme={null}
{
if (result.status === 'presented' && result.claim?.userConfirmedCompletion) {
// Grant once per claim: key on the transaction, else on this user and campaign.
const claim = result.claim;
grantCoins(100, claim.transactionId ?? `${userId}:${claim.campaignId}`);
}
}}
/>
```
```dart Flutter theme={null}
EncoreGiftsButton(
placement: 'milestone_reached',
publisherReward: const EncorePublisherReward(id: 'coins_100', title: '100 coins'),
onResult: (result) {
final claim = result.claim;
if (claim != null && claim.userConfirmedCompletion) {
// Grant once per claim: key on the transaction, else on this user and campaign.
grantCoins(100, claim.transactionId ?? '$userId:${claim.campaignId}');
}
},
)
```
```javascript Web SDK theme={null}
const handle = Encore.triggers.giftsButton.mount(document.getElementById('gifts-button'), {
placement: 'milestone_reached',
publisherReward: { id: 'coins_100', title: '100 coins' },
onResult: (result) => {
// The same result placement(id).show() resolves to. A claim isn't a completion:
// keep its transaction ID and grant when the offer_completed webhook confirms it.
if (result.status === 'claimed' && result.transactionId) {
saveClaim(result.transactionId);
}
},
});
```
```tsx Web SDK (React) theme={null}
{
if (result.status === 'claimed' && result.transactionId) saveClaim(result.transactionId);
}}
/>
```
Changing `publisherReward` on a mounted Gifts Button applies to the next sheet it opens.
## After a claim
Encore decides what the spot shows after the user claims an offer, and can test the choices against each other. Usually Gifts Button turns into a [Claim Reminder](/publishers/triggers/claim-reminder): the same spot reminds the user to finish that claim, with a countdown, and a tap opens the reward sheet with that offer in it. It turns back into Gifts Button when any of these happens:
* **The claim is completed.** Encore confirms the user finished it.
* **The reminder window ends.** That is 24 hours after the claim by default; Encore sets it with the look.
* **The user taps ×.** Every claim it was reminding about is hidden on this device. A claim made later brings the reminder back.
* **The offer leaves the sheet.** For example, the brand paused the campaign, or the campaign reached its cap.
Any claim the user makes in an Encore sheet counts, including one from your own `show()` call, as long as this placement's sheet still lists that offer. The SDK keeps the user's claims on the device, so the reminder also shows after the app reopens, until one of those four things ends it. The spot's request for its look includes whether a claim is open, so Gifts Button doesn't flash first. A claim counts as open while it's inside the reminder window last served at this placement, which the device remembers across launches; until one is served there, that's 24 hours.
The reminder in the spot keeps its own look and analytics. Don't also mount a Claim Reminder at the same spot: the user could see the reminder twice.
**The height changes.** Reminder looks are 76 points tall (pixels on the web), and the `featured` look is 85. Gifts Button's looks are 48 to 112. The entry takes its new height at once while the content fades across, so leave room in your layout for it to grow or shrink.
## After a completion
A claim is completed when Encore confirms the user finished the offer. On iOS and Android, a user telling the sheet they finished it counts too. An expired or failed claim is not a completion. The entry asks Encore about the user's newest open claims when the screen opens and when the app comes back to the foreground, so a completed claim stops showing as a reminder.
After a completion, Encore decides what the spot shows for the rest of the user's day, and can test the choices against each other:
* **Gifts Button** while its sheet has offers, as before.
* **Nothing**, until midnight on the user's device or until they claim another offer, whichever comes first.
* **A thanks look**: "Nice work, you finished it" with "More gifts are waiting" and a "See gifts" button, and no logos. A tap opens the reward sheet as Gifts Button does, and the spot goes back to Gifts Button. So do a new claim and midnight on the user's device. Its events carry the layout `thanks`.
There is nothing to set: the behavior comes with the look Encore serves.
## What Encore controls
The served look sets the layout, the height, the copy (in the user's language) for each line you don't [set yourself](/publishers/triggers/overview#your-text), the default colors, and what the spot shows [after a claim](#after-a-claim) and [after a completion](#after-a-completion). Encore can test several looks against each other, so different users can see a different entry. Your `appearance` colors always win, in the [color order](/publishers/triggers/overview#colors).
The entry never names the reward.
## Analytics
Gifts Button reports its own impressions and taps to Encore's analytics. You don't send any events.
## Related
* [Trigger components](/publishers/triggers/overview): how trigger components work, heights, and colors.
* [Quickstart](/publishers/triggers/quickstart) and [Experiments and looks](/publishers/triggers/experiments).
* [Reward Users](/publishers/use-cases/post-action-reward): the use case whose sheet Gifts Button opens.
* [Localization](/publishers/concepts/localization): how the entry's copy reaches the user's language.
# Trigger components
Source: https://docs.encorekit.com/publishers/triggers/overview
Small Encore entries you place in your own screens that open the reward sheet, with looks Encore changes and tests without an app update.
A trigger component is a small Encore entry that sits inside one of your own screens, in the normal flow of your layout. When the user taps it, it opens the reward sheet for its placement: the same sheet `show()` presents, with the same premium brand offers, each one a real perk a brand funds to acquire customers.
Instead of deciding in code when to interrupt the user with the sheet, you place an entry where the reward makes sense and let the user open it when they choose to. You add it with one line and a placement ID. Encore decides how it looks.
> [!NOTE]
>
> **Requires SDK 2.4.0+** on every platform. See [Minimum SDK versions](#minimum-sdk-versions).
## Minimum SDK versions
Trigger components first shipped in 2.4.0 of each SDK, and in 2.5.0 of the Unity package:
| Platform | Package | Minimum |
| - | - | - |
| iOS | `EncoreKit` ([install](/publishers/ios/quickstart/install)) | 2.4.0 |
| Android | `com.encorekit:encore` ([install](/publishers/android/quickstart/install)) | 2.4.0 |
| React Native | `@encorekit/react-native` ([install](/publishers/react-native/quickstart/install)) | 2.4.0 |
| Flutter | `encore_flutter` ([install](/publishers/flutter/quickstart/install)) | 2.4.0 |
| Web | `@encorekit/web-sdk` ([install](/publishers/web/quickstart/install)) | 2.4.0 |
| Unity | `com.encorekit.unity` ([install](/publishers/unity/quickstart/install)) | 2.5.0 |
The React Native and Flutter 2.4.0 packages bring the native 2.4.0 SDKs with them, and the Unity 2.5.0 package brings the native 2.5.0 SDKs.
## The two trigger components
| Trigger component | What it is | Where it goes |
| - | - | - |
| [Gifts Button](/publishers/triggers/gifts-button) | A "you have a gift" entry: a card, an animated gift box, a thank you banner, or a compact pill. | A reward moment, such as the screen after a finished streak, in place of your own `show()` call |
| [Claim Reminder](/publishers/triggers/claim-reminder) | A card that reminds the user of an offer they claimed but haven't finished, with a countdown | A screen users return to on their own, such as your home screen |
Start with the [quickstart](/publishers/triggers/quickstart): it adds both in a few lines on iOS, Android, React Native, Flutter, and the web.
Prefer to draw the entry in your own style? [Build your own button](/publishers/triggers/custom-ui): Encore still decides what it shows, counts its views and taps, and opens the reward sheet.
## Looks come from Encore
Each trigger component's look (its layout, copy, colors, and height) is served by Encore, not built into your app. Encore draws it with the same engine that draws the reward sheet. That means:
* **No app update to change a look.** Encore can switch the Gifts Button from the card to the banner, or reword the Claim Reminder, for every user on a version that supports trigger components.
* **Encore can test looks.** Encore picks each trigger component's look, and can run an experiment comparing looks across your users. See [Experiments and looks](/publishers/triggers/experiments).
* **Copy arrives in the user's language.** See [Localization](/publishers/concepts/localization).
Your code never builds the entry's views. You place it and give it a placement. If you like, you also give it your own [text](#your-text) and [colors](#colors).
## Your text
Write the entry's words yourself with `headline`, `subheadline` and `cta`, the same names the reward sheet uses. Anything you leave out, or pass blank, shows the look's own copy, so you can set just the line you care about:
```swift iOS theme={null}
GiftsButton(placement: "streak")
.headline("You kept your streak!")
.subheadline("A gift from us, on the house")
.cta("Open")
```
```kotlin Android theme={null}
GiftsButton(
placement = "streak",
headline = "You kept your streak!",
subheadline = "A gift from us, on the house",
cta = "Open",
)
```
```tsx React Native theme={null}
```
```dart Flutter theme={null}
EncoreGiftsButton(
placement: 'streak',
headline: 'You kept your streak!',
subheadline: 'A gift from us, on the house',
cta: 'Open',
)
```
```javascript Web SDK theme={null}
Encore.triggers.giftsButton.mount(element, {
placement: 'streak',
headline: 'You kept your streak!',
subheadline: 'A gift from us, on the house',
cta: 'Open',
});
```
```tsx Web SDK (React) theme={null}
```
Claim Reminder takes the same three. On UIKit and Android Views, set the `headline`, `subheadline` and `cta` properties.
| Option | What it replaces |
| - | - |
| `headline` | The entry's main line |
| `subheadline` | The line under it |
| `cta` | The button's label |
How your text is shown:
* **Each look has its own default.** The copy you fall back to belongs to the look Encore serves, in the user's language. If Encore tests two looks, each falls back to its own words.
* **A look shows only the lines it has.** Your `cta` appears on looks that draw a button, and your `subheadline` on looks that draw a second line. No Claim Reminder look draws a subheadline today. A look with no place for a line keeps its own copy there.
* **Your text is shown as you pass it.** Encore doesn't translate it, so pass the user's language yourself if your app has more than one.
* **One line each, up to 120 characters.** Line breaks and invisible control characters are removed. Text with nothing visible left counts as blank.
* **The thanks look keeps Encore's words.** After a completion, the thanks look shows its own copy even when you pass text.
* **Screen readers keep the brand.** When your headline replaces a Claim Reminder's title, VoiceOver and TalkBack still read the advertiser's name.
## How it relates to the reward sheet
A trigger component is a way in to the reward sheet, not a second sheet:
* It shows only when the reward sheet it opens has offers for this user at this placement. It checks first, so a tap never opens an empty sheet.
* A tap opens that sheet exactly as `show()` would, with the offers it already checked.
* `publisherReward` and `onResult` work on that sheet as they do for `show()`. See [Pass your prize and read the result](/publishers/triggers/gifts-button#pass-your-prize-and-read-the-result).
* When the sheet closes, the entry checks again. It stays while offers remain and hides when none are left.
## What you can count on
These hold for every trigger component on every platform.
### It takes no space when there's nothing to show
A trigger component is zero height, and never shows an empty or broken entry, until it has something to show. Design every screen that holds one so it looks right both with and without it. [Troubleshooting](/publishers/triggers/troubleshooting#it-isnt-showing) lists every reason it can be empty.
### It never crashes your app
A trigger component never throws into your code. A network error, an unknown ID, or a look the SDK can't draw all end the same way: it renders nothing. A look that uses something your SDK version can't draw is never drawn partly or wrongly; the entry stays empty instead.
### It sizes itself
Its height comes from the look Encore serves, and it reports that height to your layout. Give it the width of your content and leave the height to the trigger component: put it in a stack, column, or list, and use `wrap_content` on Android Views. See [Heights](#heights) and [Width and alignment](#width-and-alignment).
### Its text follows the user's text size
The entry's text grows with the user's larger text setting, up to a limit set by the look, so the entry keeps its height. A long line shrinks to fit before it's cut off.
### It keeps itself current
It checks again when your app returns to the foreground and when the sheet it opened closes, and hides when what it showed no longer applies. It reloads when you call `identify()`, `reset()`, or `setLanguage()`, so a new user never sees the previous user's entry.
### Dismissals stay on the device
When a look lets the user dismiss the entry (the Claim Reminder's ×), the dismissal is stored on that device only. It hides that item on every screen showing the same trigger component. Nothing is sent to your server or changed on the user's account.
## Heights
These are the heights Encore serves today, in points on iOS, `dp` on Android, and CSS pixels on the web. React Native and Flutter take the iOS or Android value of the device. They're set by the look, so Encore can change them without an app update.
| Trigger component | Look | Height |
| - | - | - |
| Gifts Button | `card` | 76 |
| Gifts Button | `banner` | 88 |
| Gifts Button | `pulse` | 112 |
| Gifts Button | `pill` | 48 |
| Gifts Button | `offerMarquee`, `offerColumns`, `giftCard` and `stillWaiting` | 76 |
| Claim Reminder | `featured` | 85 |
| Claim Reminder | Every other look | 76 |
Looks in one experiment can have different heights, so a Gifts Button can change height between users. Leave the height flexible.
## Colors
Each trigger component reads these fields from the `appearance` you pass. That `appearance` styles only the trigger component, never the sheet it opens: set the sheet's look where you style your sheets, as you do when you present the sheet yourself.
| Field | What it colors | When you leave it out |
| - | - | - |
| `backgroundColor` | The entry's surface | The color order below |
| `textColor` | Titles and the countdown | The color order below |
| `accentColor` | Buttons, progress, and highlights | The color order below |
| `secondaryTextColor` | Subtitles, the countdown's units, and the close button | Your text color, faded by the look |
| `trackColor` | The unfilled part of a progress bar | Your text color, faded by the look |
| `onAccentColor` | Text and icons drawn on the accent | Black or white, whichever reads on the accent. Some looks draw button text in the entry's background color when that reads too |
| `backgroundEndColor` | The second color of a look's background gradient, such as the featured Claim Reminder's | Your background color, so the entry is solid |
For each color on its own, the first one set wins:
1. **Your `appearance`.**
2. **Your app's theme in the Encore portal.** Today this is the accent color you saved for the app.
3. **The look's own colors**, set by Encore.
4. **The built-in default**: a dark surface with a gold accent.
A color you set is drawn exactly as you set it. A look can fade its secondary text or its track, but only when you haven't set that color yourself.
Your `textColor` applies on its own, with or without a `backgroundColor`. When a background is set without a text color at the same step, the text is black or white, whichever reads on that background. Hex formats are `#RGB`, `#RRGGBB`, and `#RRGGBBAA`. A value that isn't a hex color is ignored, and the next step in the order applies. On the web, the reward sheet's other `AppearanceConfig` fields (`headline`, `claimButton`, and the rest) don't apply to the entry. To change the entry's words, use [`headline`, `subheadline` and `cta`](#your-text).
### Light and dark
`colorScheme` sets the look's mode: `light`, `dark`, or `system`, which follows the device. Leave it out and the entry follows the mode you saved for your app in the Encore portal, where `auto` follows the device. With neither set, the entry is dark.
In light mode, the order is your `appearance`, then your app's portal theme, then the look's light colors, then a light default: a white surface with dark text and a gold accent. A look's dark colors never apply in light mode.
## Icon
The `icon` option picks the icon the look draws. It goes on the trigger component itself, next to `placement`, not inside `appearance`:
* `gift`, the default: Encore's gift.
* `appIcon`: your app's store icon, from your app's settings in the Encore portal. When your app has no store icon, the look draws the gift.
* `none`: no icon.
Looks that show the advertiser's logo keep it whatever you set here.
## Width and alignment
A trigger component is never wider than its look. Encore sets that width for each look. In a container narrower than the look, such as a phone screen, it fills the container. In a wider one, such as a large screen or a desktop page, it keeps the look's width and sits where `alignment` puts it:
* `center`, the default.
* `leading`: the start of the line in your app's writing direction (left in English, right in Arabic).
* `trailing`: the end of the line.
`alignment` goes on the trigger component, next to `placement`. Gifts Button, Claim Reminder and the trigger host all take it:
```swift iOS theme={null}
ClaimReminder(placement: "home", alignment: .leading)
```
```kotlin Android theme={null}
ClaimReminder(placement = "home", alignment = EncoreAlignment.LEADING)
```
```tsx React Native theme={null}
import { EncoreClaimReminder, EncoreAlignment } from '@encorekit/react-native';
```
```dart Flutter theme={null}
EncoreClaimReminder(placement: 'home', alignment: EncoreAlignment.leading)
```
```javascript Web SDK theme={null}
Encore.triggers.claimReminder.mount(element, { placement: 'home', alignment: 'leading' });
```
```tsx Web SDK (React) theme={null}
```
Changing `alignment` only moves the trigger component. It makes no new request and keeps the look already on screen. On Android Views set the `alignment` property, or `app:encoreAlignment` in XML; on the web call `setAlignment()` on the handle `mount()` returns.
## Analytics
Every trigger component reports its own impressions, taps, and dismissals to Encore's analytics. You don't send or handle any events.
## Related
* [Quickstart](/publishers/triggers/quickstart): add both trigger components.
* [Gifts Button](/publishers/triggers/gifts-button) and [Claim Reminder](/publishers/triggers/claim-reminder).
* [Build your own button](/publishers/triggers/custom-ui): draw the entry yourself; Encore still decides what it shows and opens the sheet.
* [Experiments and looks](/publishers/triggers/experiments): how Encore picks and tests looks.
* [Troubleshooting](/publishers/triggers/troubleshooting): when a trigger component isn't showing.
# Trigger components quickstart
Source: https://docs.encorekit.com/publishers/triggers/quickstart
Add a Gifts Button and a Claim Reminder to your app on iOS, Android, React Native, Flutter, or the web.
This page adds both trigger components to your app in a few lines each: a [Gifts Button](/publishers/triggers/gifts-button) at a reward moment and a [Claim Reminder](/publishers/triggers/claim-reminder) on a screen users come back to. Read [Trigger components](/publishers/triggers/overview) first if you want the picture before the code.
> [!NOTE]
>
> **Requires SDK 2.4.0+** on every platform. See [Minimum SDK versions](/publishers/triggers/overview#minimum-sdk-versions).
## Before you start
* Install the Encore SDK 2.4.0 or later for your platform and call `configure()`, as in its quickstart: [iOS](/publishers/ios/quickstart/install), [Android](/publishers/android/quickstart/install), [React Native](/publishers/react-native/quickstart/install), [Flutter](/publishers/flutter/quickstart/install), or [Web](/publishers/web/quickstart/install).
* Identify your user with `identify()` once you know who they are, as for `show()`.
* Pick a placement ID for each spot, such as `milestone_reached` for the end of a streak and `home` for your home screen. A trigger component opens the same reward sheet `show()` presents at that placement, so the placement works exactly as it does there.
A trigger component only appears when the reward sheet it opens has offers for this user. Until then it takes up no space, so you can add it to a screen and ship it before anything shows.
## Add a Gifts Button
Put it on the screen where you would otherwise call `show()` for a reward, in place of that call:
```swift iOS (SwiftUI) theme={null}
import Encore
import SwiftUI
struct StreakDoneView: View {
var body: some View {
VStack(spacing: 16) {
Text("7 day streak")
GiftsButton(placement: "milestone_reached")
}
.padding()
}
}
```
```swift iOS (UIKit) theme={null}
import Encore
import UIKit
final class StreakDoneViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let stack = UIStackView()
stack.axis = .vertical
stack.spacing = 16
stack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stack)
NSLayoutConstraint.activate([
stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
stack.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
stack.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
])
stack.addArrangedSubview(GiftsButtonView(placement: "milestone_reached"))
}
}
```
```kotlin Android (Compose) theme={null}
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import com.encorekit.encore.GiftsButton
@Composable
fun StreakDoneScreen() {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text("7 day streak")
GiftsButton(placement = "milestone_reached")
}
}
```
```xml Android (XML layout) theme={null}
```
```tsx React Native theme={null}
import { View, Text } from 'react-native';
import { EncoreGiftsButton } from '@encorekit/react-native';
export function StreakDoneScreen() {
return (
7 day streak
);
}
```
```dart Flutter theme={null}
import 'package:flutter/material.dart';
import 'package:encore_flutter/encore_flutter.dart';
class StreakDoneScreen extends StatelessWidget {
const StreakDoneScreen({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: const [
Text('7 day streak'),
EncoreGiftsButton(placement: 'milestone_reached'),
],
);
}
}
```
```javascript Web SDK theme={null}
import Encore from '@encorekit/web-sdk';
// Call configure() first, as in the Web quickstart.
const giftsButton = Encore.triggers.giftsButton.mount(
document.getElementById('streak-gift'),
{ placement: 'milestone_reached' }
);
// When you remove the element from the page:
// giftsButton.unmount();
```
```tsx Web SDK (React) theme={null}
import { GiftsButton } from '@encorekit/web-sdk/react';
// Render inside your EncoreProvider.
export function StreakDone() {
return (
7 day streak
);
}
```
That's the whole setup. Encore picks the look, the copy, and the colors, and can change them without an app update. A tap opens the reward sheet for that placement.
## Add a Claim Reminder
Put it on a screen users return to on their own, such as your home screen:
```swift iOS (SwiftUI) theme={null}
import Encore
import SwiftUI
struct HomeView: View {
var body: some View {
ScrollView {
VStack(spacing: 16) {
ClaimReminder(placement: "home")
// The rest of your home screen.
}
.padding()
}
}
}
```
```swift iOS (UIKit) theme={null}
// In your view controller, next to your other arranged subviews.
stack.addArrangedSubview(ClaimReminderView(placement: "home"))
```
```kotlin Android (Compose) theme={null}
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import com.encorekit.encore.ClaimReminder
@Composable
fun HomeScreen() {
Column {
ClaimReminder(placement = "home")
// The rest of your home screen.
}
}
```
```xml Android (XML layout) theme={null}
```
```tsx React Native theme={null}
import { ScrollView } from 'react-native';
import { EncoreClaimReminder } from '@encorekit/react-native';
export function HomeScreen() {
return (
{/* The rest of your home screen. */}
);
}
```
```dart Flutter theme={null}
import 'package:flutter/material.dart';
import 'package:encore_flutter/encore_flutter.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return ListView(
children: const [
EncoreClaimReminder(placement: 'home'),
// The rest of your home screen.
],
);
}
}
```
```javascript Web SDK theme={null}
import Encore from '@encorekit/web-sdk';
const reminder = Encore.triggers.claimReminder.mount(
document.getElementById('claim-reminder'),
{ placement: 'home' }
);
```
```tsx Web SDK (React) theme={null}
import { ClaimReminder } from '@encorekit/web-sdk/react';
export function Home() {
return (
{/* The rest of your home screen. */}
);
}
```
> [!NOTE]
>
> Claim Reminder shows a claim the user started but hasn't finished. Until the SDKs can read the user's open claims from Encore, which ships after the first trigger release, it shows only claims made in your app on this device. Adding it now is safe: with no claim to show, it takes no space and sends nothing.
## Use your own words (optional)
Set the entry's text with `headline`, `subheadline` and `cta`, as you do for the reward sheet. Leave any of them out and that line keeps the look's own copy, in the user's language:
```swift iOS theme={null}
GiftsButton(placement: "milestone_reached")
.headline("Level complete!")
.cta("Claim")
```
```kotlin Android theme={null}
GiftsButton(placement = "milestone_reached", headline = "Level complete!", cta = "Claim")
```
```tsx React Native theme={null}
```
```dart Flutter theme={null}
EncoreGiftsButton(placement: 'milestone_reached', headline: 'Level complete!', cta: 'Claim')
```
```javascript Web SDK theme={null}
Encore.triggers.giftsButton.mount(element, { placement: 'milestone_reached', headline: 'Level complete!', cta: 'Claim' });
```
```tsx Web SDK (React) theme={null}
```
Claim Reminder takes the same options. [Your text](/publishers/triggers/overview#your-text) says which looks show which line.
## Pay your prize (optional)
If your app pays its own prize for trying an offer, pass it as `publisherReward` and read the result in `onResult`. See [Pass your prize and read the result](/publishers/triggers/gifts-button#pass-your-prize-and-read-the-result).
## The trigger host
Each shorthand on this page is the trigger host with its ID built in. Use the host when your app places trigger components through one code path, for example from your own server-driven layout. It takes the trigger ID as a string:
```swift iOS (SwiftUI) theme={null}
EncoreTrigger("giftsButton", placement: "milestone_reached")
```
```swift iOS (UIKit) theme={null}
let trigger = EncoreTriggerView(id: "giftsButton", placement: "milestone_reached")
```
```kotlin Android (Compose) theme={null}
EncoreTrigger(id = "giftsButton", placement = "milestone_reached")
```
```kotlin Android (View) theme={null}
val trigger = EncoreTriggerView(context = this, id = "giftsButton", placement = "milestone_reached")
```
```xml Android (XML layout) theme={null}
```
```tsx React Native theme={null}
```
```dart Flutter theme={null}
EncoreTrigger(id: 'giftsButton', placement: 'milestone_reached')
```
```javascript Web SDK theme={null}
const handle = Encore.triggers.mount('giftsButton', element, { placement: 'milestone_reached' });
```
```tsx Web SDK (React) theme={null}
```
An ID the SDK doesn't know renders nothing, so a server that names a future trigger component can't break an older app.
## Parameters
The host and every shorthand take these by name. Every one except `placement` (and `id` on the host) is optional.
| Parameter | Default | Meaning |
| - | - | - |
| `id` | Built into each shorthand | Host only. The trigger ID: `giftsButton` or `claimReminder` |
| `placement` | Required | The placement ID for this spot, as for `show()` |
| `useCase` | The reward use case | The use case of the sheet it opens. Only the reward use case is supported today; the churn use case renders nothing |
| `autoOpen` | None | Gifts Button and the host only. When an Encore test calls for it, the sheet can open by itself: at most once a day at each placement, in the foreground, never over another Encore sheet. Set it to off to stop that |
| `icon` | `gift` | The icon the look draws: `gift`, `appIcon`, or `none`. See [Icon](/publishers/triggers/overview#icon) |
| `alignment` | `center` | Where it sits when its container is wider than its look: `leading`, `center` or `trailing`, in your app's writing direction. Changing it only moves it. See [Width and alignment](/publishers/triggers/overview#width-and-alignment) |
| `appearance` | None | Your colors and `colorScheme` for the trigger component only, never the sheet it opens. See [Colors](/publishers/triggers/overview#colors) |
| `publisherReward` | None | Your prize for trying an offer, handed to every sheet it opens |
| `onResult` | None | Called once per sheet it opens, after the sheet closes, with that sheet's result |
| `headline`, `subheadline`, `cta` | The look's own copy | Your words for the entry's main line, second line, and button. Blank falls back to the look's copy. On iOS they're modifiers: `.headline("…")`. See [Your text](/publishers/triggers/overview#your-text) |
The names of the typed values differ by platform:
| | iOS | Android | React Native | Flutter | Web | Unity |
| - | - | - | - | - | - | - |
| Use case | `UseCase.rewardUsers` | `UseCase.REWARD_USERS` (XML `reward`) | `UseCase.rewardUsers` | `EncoreUseCase.rewardUsers` | `'rewardUsers'` | `UseCase.RewardUsers` |
| `autoOpen` | `.off` | `AutoOpen.OFF` (XML `off`) | `AutoOpen.off` | `EncoreAutoOpen.off` | `'off'` | `AutoOpenOff = true` |
| `icon` | `TriggerIcon.appIcon` | `TriggerIcon.APP_ICON` | `TriggerIcon.appIcon` | `EncoreTriggerIcon.appIcon` | `'appIcon'` | `TriggerIcon.AppIcon` |
| `alignment` | `EncoreAlignment.leading` | `EncoreAlignment.LEADING` (XML `leading`) | `EncoreAlignment.leading` | `EncoreAlignment.leading` | `'leading'` | `EncoreAlignment.Leading` |
| `appearance.colorScheme` | `AppearanceConfig.ColorScheme.dark` | `AppearanceConfig.ColorScheme.DARK` | `'dark'` | `EncoreColorScheme.dark` | `'dark'` | `ColorScheme.Dark` |
| Prize | `PublisherReward` | `PublisherReward` | `PublisherReward` | `EncorePublisherReward` | `PublisherReward` | |
| `onResult` gets | `PresentationResult` | `PresentationResult` | `PresentationResult` | `EncorePresentationResult` | `ShowResult` | `PresentationResult` (the `Result` event) |
On the web, `publisherReward`, `onResult` and `alignment` go inside the options object you pass to `mount()`, and the handle's `setAlignment()` moves a mounted trigger component.
## Platform notes
* **iOS.** The SDK installs on iOS 15, but trigger components draw only on iOS 17 or later. Below that they render nothing. `EncoreTriggerView` (UIKit) takes `publisherReward` and `onResult` as properties you set after creating it; `GiftsButtonView(placement:)` and `ClaimReminderView(placement:)` take them directly when you create them. Pin a UIKit view's leading and trailing edges, not its height.
* **Android.** Android 7.0 (API 24) or later. `EncoreTriggerView`'s constructor doesn't take `publisherReward`, `onResult` or `alignment`; set them as properties. On `GiftsButtonView` and `ClaimReminderView`, `alignment` is a property too. On `EncoreTriggerView` the ID property is `triggerId`, because `View.id` is already the view's integer ID. XML attributes carry an `encore` prefix: `app:encoreTriggerId`, `app:encorePlacement`, `app:encoreUseCase`, `app:encoreIcon`, `app:encoreAlignment`, and `app:encoreAutoOpen`. Use `wrap_content` for the height.
* **React Native.** React Native 0.72 or later. The trigger components render the native trigger view, so they need the native module linked: in Expo Go, or with React Native for web, they render nothing and log one warning. A `style` sets the width and margins; the height always comes from the trigger component. When you read `onResult`, check `result.status === 'presented'` before reading `result.claim`.
* **Flutter.** iOS 17 or later (the plugin installs on iOS 15), and Android API 26 or later. Android and iOS only: on the web and desktop the widgets render nothing. Give them a bounded width, as inside a `Column` or `ListView`.
* **Unity.** Unity can't embed a native view in its UI, so a trigger component floats above the Unity view at a rect you set with `SetFrame`, or over a `RectTransform` with `EncoreGiftsButtonView`, `EncoreClaimReminderView`, or `EncoreTriggerView` (the host). It draws above all Unity content: call `SetVisible(false)` while your game shows its own modal or pause screen. Its height arrives through `HeightChanged`. `onResult` is the `Result` event, and `autoOpen` is the `AutoOpenOff` flag. `SetAlignment` and `SetAppearance` change a placed trigger component. See [`GiftsButton`](/publishers/unity/sdk-reference/gifts-button), [`ClaimReminder`](/publishers/unity/sdk-reference/claim-reminder), and [`EncoreTrigger`](/publishers/unity/sdk-reference/encore-trigger).
* **Web.** `mount()` returns a handle; call `unmount()` when you remove the element. The React components clean up for you and render inside the `EncoreProvider` from [React](/publishers/web/frameworks/react). If you serve the SDK's ES module build yourself, serve the whole `dist/esm` folder: trigger components load from its `chunks` folder on first use, so a page without them never downloads them.
## Next steps
* [Gifts Button](/publishers/triggers/gifts-button): what it shows and paying your prize.
* [Claim Reminder](/publishers/triggers/claim-reminder): what it shows and when.
* [Experiments and looks](/publishers/triggers/experiments): how Encore picks and tests looks.
* [Troubleshooting](/publishers/triggers/troubleshooting): why a trigger component isn't showing.
# Release checklist
Source: https://docs.encorekit.com/publishers/triggers/release-checklist
Everything to set up before you ship a Gifts Button and a Claim Reminder, in order, with a list to check before release.
> [!NOTE]
>
> **Requires SDK 2.4.0+** on every platform. See [Minimum SDK versions](/publishers/triggers/overview#minimum-sdk-versions).
Use this page to plan the release of both trigger components and to check it before you ship. You add a [Gifts Button](/publishers/triggers/gifts-button) at your reward moment and a [Claim Reminder](/publishers/triggers/claim-reminder) on a screen users come back to, then identify your user. Each step links to the page that holds its code for every platform.
It takes one app release. After that, Encore can change the looks and test them without another release from you.
## Update the Encore SDK
Update every SDK you ship to 2.4.0 or later: trigger components first shipped in 2.4.0 on every platform. [Minimum SDK versions](/publishers/triggers/overview#minimum-sdk-versions) lists each package.
No migration is needed. Your existing `show()` calls keep working as they do today.
## Identify your user and share what you know
Call `identify()` once you know who the user is, as for `show()`. Encore matches claims and completions to that ID.
Then send the attributes your app already has. Country has its own field, and anything of your own goes in `custom`. Gender is accepted only from an app rated 18+. This is strongly recommended: country and language already shape which offers a user is shown. Each platform's user management page has the call:
| Platform | Page |
| - | - |
| iOS | [User management](/publishers/ios/quickstart/user-management) |
| Android | [User management](/publishers/android/quickstart/user-management) |
| React Native | [User management](/publishers/react-native/quickstart/user-management) |
| Flutter | [User management](/publishers/flutter/quickstart/user-management) |
| Web | [User management](/publishers/web/quickstart/user-management) |
| Unity | [User management](/publishers/unity/quickstart/user-management) |
* Pass the user's age as `age` (whole years) or their date of birth as `dateOfBirth`, whichever your app has. Every SDK takes both, works the age out on the device, and never sends the date. If you hold only a range, send its lowest end as `age`. See [Sending an age](/publishers/offers-api/reference/user-attributes#sending-an-age).
* A user under 18 is still served offers, from age-appropriate inventory only and with no per-user personalization.
* Only send what you have a lawful basis to share, such as the user's consent.
## Place a Gifts Button at your reward moment
Use the screen that celebrates something the user did: a finished streak, for example. The entry shows only when the reward sheet has offers for this user; until then it takes up no space. See [Add a Gifts Button](/publishers/triggers/quickstart#add-a-gifts-button).
* Use it **in place of** your `show()` call at that moment, not as well as it.
* Keep it clear of controls people tap without looking, such as a send button, so every tap on it is meant.
## Place a Claim Reminder on a screen users return to
When a user claims an offer and leaves before finishing it, this card brings them back with a countdown. Add it as its own view on a screen people open on their own, such as your home tab, rather than one they rarely reach. See [Add a Claim Reminder](/publishers/triggers/quickstart#add-a-claim-reminder).
* With no open claim it draws nothing and leaves no gap, so place it inline.
* A tap opens the reward sheet with that offer in it. When the look is dismissible, × hides that reminder on this device.
* Don't also mount a Claim Reminder where a Gifts Button sits: the Gifts Button turns into the reminder after a claim by itself.
## Make it look like your app
Pass `appearance` on the trigger component to set its colors; yours always win over Encore's. It styles only the trigger component, never the sheet it opens: the sheet keeps the look you give your sheets. See [Colors](/publishers/triggers/overview#colors).
* `headline`, `subheadline` and `cta` put your own words on it; each line you leave out keeps the look's copy. See [Your text](/publishers/triggers/overview#your-text).
* `icon`, next to `placement`, picks the icon: `gift` (the default), `appIcon` or `none`. See [Icon](/publishers/triggers/overview#icon).
* `alignment`, next to `placement`, sets where it sits when the screen is wider than its look: `center` (the default), `leading` or `trailing`. See [Width and alignment](/publishers/triggers/overview#width-and-alignment).
## Who controls what
| Encore, from its side with no app update | Your app |
| - | - |
| Which look shows, and its default copy in the user's language | Which screens each trigger component goes on |
| What the spot shows after a claim and after a completion | The trigger component's text (`headline`, `subheadline`, `cta`), colors, and icon |
| Which offers the reward sheet lists | Where it sits on a wide screen |
| Experiments on each of these, with a [holdout group](/publishers/triggers/experiments#the-holdout-group) | Whether Encore may open the gifts by itself (`autoOpen` set to off to never) |
| Counting views and taps, so you send no events | Who the user is, and the attributes you choose to share |
## Before you ship
Check each of these on a test build:
* Every SDK you ship is 2.4.0 or later.
* `identify()` runs once you know who the user is.
* Attributes are sent, with `age` or `dateOfBirth`, and no gender unless your app is rated 18+.
* The Gifts Button replaces your `show()` call on the reward screen, not both.
* The Claim Reminder sits inline on a screen users return to, as its own view.
* Colors are set on the trigger components.
* You claimed a test offer and left without finishing it. When you came back, the reminder showed.
## Related
* [Quickstart](/publishers/triggers/quickstart): the code for both trigger components on every platform.
* [Troubleshooting](/publishers/triggers/troubleshooting): why a trigger component isn't showing.
# Troubleshooting trigger components
Source: https://docs.encorekit.com/publishers/triggers/troubleshooting
Find out why a Gifts Button or Claim Reminder isn't showing, why users can tap and see no offers, how to test trigger components while you build, and answers to common questions.
A trigger component is designed to stay empty, and take no space, whenever it has nothing good to show. That makes "it isn't showing" the most common question. Work through the list below in order.
> [!NOTE]
>
> **Requires SDK 2.4.0+** on every platform. See [Minimum SDK versions](/publishers/triggers/overview#minimum-sdk-versions).
## It isn't showing
### Check your setup first
* **The SDK is configured.** A trigger component mounted before `configure()` waits and starts once the SDK is configured.
* **The trigger component is turned on for your app.** Encore turns each trigger component on per app and sets its default look. Until then the entry renders nothing. Ask your Encore contact or write to [admin@encorekit.com](mailto:admin@encorekit.com).
* **The reward sheet has offers at that placement.** A trigger component only shows when the reward sheet it opens has offers for this user at this placement. Try `show()` at the same placement: if the sheet doesn't present, the entry won't show either.
* **The SDK is 2.4.0 or later.** See [Minimum SDK versions](/publishers/triggers/overview#minimum-sdk-versions).
* **For Claim Reminder: there is a claim to show.** Claim Reminder shows only claims the user made in your app on this device. See [Claim Reminder](/publishers/triggers/claim-reminder).
### Every reason it can be empty
A trigger component renders nothing, at zero height, when:
| Situation | Logged once? |
| - | - |
| The trigger ID isn't one this SDK knows | Yes |
| `useCase` is the churn use case, which isn't supported yet | Yes |
| The reward sheet has no offers for this user at this placement | No |
| Encore serves no reward sheet to this user at this placement | No |
| The user is in a Gifts Button experiment's holdout group that sees nothing | No |
| Encore served a look this SDK version can't draw | Yes |
| Managed, and Encore has set no default look and runs no experiment | No |
| It's still loading, or the request failed (for example, offline) | No |
| React Native without the native module linked: Expo Go, or React Native for web | Yes |
| Flutter on the web or desktop | No |
| The Unity Editor, which shows no trigger components | No |
| iOS below 17 | No |
| Claim Reminder: no open claim inside the reminder window, the sheet doesn't list the claimed offer, or the user dismissed it | No |
A failed request is asked again the next time your app returns to the foreground, so a trigger component that was empty while offline can appear later without any code from you.
### It was showing, then disappeared
That's expected in these cases:
* **The offers ran out.** After the sheet closes, the entry checks again and hides when no offers are left.
* **The user claimed the offer.** Claim Reminder hides when the brand confirms the user finished, and Gifts Button checks the offers afresh after a claim.
* **The reminder window ended.** Claim Reminder hides when its countdown reaches zero. The claim itself stays open.
* **The user changed.** After `identify()` or `reset()`, it reloads for the new user, who may have nothing to show.
* **The user dismissed it.** A dismissed Claim Reminder stays hidden for that claim on that device.
## Users tap and see no offers
Encore's own trigger components hide when there are no offers, so this comes from an entry your app draws or opens itself. Check these causes:
* **Your button shows while there are no offers.** Draw your entry from `Encore.claim`, so it shows only while the claim has offers. From 2.5.0, ask `placement(id).useCase(rewardUsers).hasOffers()` before you show an item that calls `show()`. On SDKs before 2.4.0, call `show()` only from the tap, and hide the button after its first no-offers result. See [Show your entry only when there are offers](/publishers/triggers/custom-ui#show-your-entry-only-when-there-are-offers).
* **No offer fits the user.** One cause is the age rating. When your app passes a user's age as under 18, Encore serves that user only offers rated for their age. Many offers are rated 18+, so such a user can have far fewer offers than an adult, or none at a placement. Your app's audience setting can also limit offers for every user. Ask your Encore contact to check it.
## Testing while you build
* **Use your test API key** in debug builds, as for the rest of Encore. Ask your Encore contact to turn trigger components on for your test app, so the entries have a look to show.
* **Make sure the reward sheet has offers** for your test user at the placement you're testing. Calling `show()` at the same placement is the quickest check.
* **Test both states of every screen.** Each screen with a trigger component should look right with and without it, because some users never see it: those with no offers, and those in a holdout group.
* **Watch your console.** The cases marked "Logged once?" in the preceding table each log one warning per run of your app: in the Xcode console on iOS, the Android Studio log on Android, Metro or the native console on React Native, the debug console on Flutter, the browser console on the web, and on Unity the native console (Xcode or Android Studio), or the browser console on WebGL. On the web the SDK logs nothing by default: pass `logLevel: 'warn'` (or `'debug'`) to `configure()` to see these.
## Common questions
### Why does the Gifts Button sometimes have a different height?
Its height comes from the look Encore serves, and looks in one experiment can differ (the card is 76, the banner 88, the pulse 112). Leave the height flexible. See [Heights](/publishers/triggers/overview#heights).
### Can the copy or colors change?
Pass `appearance` to set the trigger component's own colors and light or dark mode; your colors win over your app's portal theme and the look's colors. It never styles the sheet the trigger component opens. See [Colors](/publishers/triggers/overview#colors). Pass `icon` to choose the icon; see [Icon](/publishers/triggers/overview#icon). The copy comes with the look, in the user's language. To use your own words, pass `headline`, `subheadline` and `cta`; see [Your text](/publishers/triggers/overview#your-text). Encore can also change the look's own copy without an app update.
### Can the app keep its own `show()` call next to a Gifts Button?
Use the Gifts Button **in place of** your own `show()` call at that moment, not as well as it. Both would open the sheet.
### Does the app need to send any events?
No. Every trigger component reports its own impressions, taps, and dismissals to Encore's analytics.
### Can a trigger component crash the app?
No. Whatever goes wrong (a network error, an unknown ID, a look the SDK can't draw) ends the same way: the entry renders nothing.
## Related
* [Trigger components](/publishers/triggers/overview)
* [Quickstart](/publishers/triggers/quickstart)
* [Experiments and looks](/publishers/triggers/experiments)
# Build Compatibility
Source: https://docs.encorekit.com/publishers/unity/guides/build-compatibility
Which Unity versions and billing packages build with the Encore Unity package, and the one Gradle fix Unity 2022.3 needs on Android.
The Encore Unity package brings the native Android SDK (`com.encorekit:encore`, at the version [Install the SDK](/publishers/unity/quickstart/install#step-2-add-the-package) names) into your Gradle build, with its own AndroidX and Google Play Billing dependencies. Most projects need nothing extra. This page lists what was measured on 2026-10-29 and what to do where a build fails.
## At a glance
| Setup | Result | What to do |
| - | - | - |
| Unity 2022.3 (2022.3.62f3), Android | Build fails in D8 | Add the [Gradle template fix](#the-d8-crash-on-android) |
| Unity 6.3 (6000.3.27f1), Android | Builds | Nothing beyond the [`Assets/Plugins/Android` folder](/publishers/unity/quickstart/install#step-3-platform-setup). The classic Activity and GameActivity both build |
| Unity 2022.3 and 6.3, iOS | Builds | Nothing. The package adds the pod to every target |
| Unity IAP 4.x | Build fails on a manifest merge | [Move to Unity IAP 5.x](#unity-iap) |
| Unity IAP 5.4.4 | Builds | Nothing |
| RevenueCat `purchases-unity` 10.0.0 | Builds | Nothing |
## The D8 crash on Android
Unity 2022.3 builds Android with Android Gradle Plugin 7.4.2. Its D8 crashes with a `NullPointerException` on `androidx.lifecycle:lifecycle-livedata-core:2.8.7`, which the native SDK brings in, and the build fails.
The fix is a newer D8 and R8 for the build, with no change to the Android Gradle Plugin version:
1. Open **Project Settings → Player → Android → Publishing Settings** and turn on **Custom Base Gradle Template**. Unity creates `Assets/Plugins/Android/baseProjectTemplate.gradle`.
2. Add this `buildscript` block at the top of that file, above the `plugins` block:
```groovy theme={null}
buildscript {
repositories { google() }
dependencies { classpath 'com.android.tools:r8:8.2.47' }
}
```
Leave the rest of the template as Unity wrote it.
## Unity IAP
Unity IAP 4.11 bundles Google Play Billing 5.2.1 (older 4.x ships older Billing, same conflict), and the native SDK needs Billing 8.0.0. The Android manifest merge fails on the two `com.google.android.play.billingclient.version` values (measured with Unity IAP 4.11.0):
```text theme={null}
Manifest merger failed with multiple errors, see logs
```
Unity IAP 4.x can't be made to work with the package. Move to Unity IAP 5.x first: 5.4.4 builds with it. RevenueCat `purchases-unity` 10.0.0 also builds with it.
A reward placement never runs a purchase, so the package doesn't call your billing stack. The conflict is only about which Billing library the build includes.
## iOS
There is no publisher step. The package lists the `EncoreKit` pod for every target of the exported Xcode project, so the app target embeds the framework the game links.
## Related
* [Install the SDK](/publishers/unity/quickstart/install)
# Configure the SDK
Source: https://docs.encorekit.com/publishers/unity/quickstart/configure
Initialize the Encore Unity package with your API key when your game starts.
## Overview
Configure the package with your **API Key** when your game starts. This initializes the Encore SDK on the device: the native SDK on Android and iOS, and the web SDK on WebGL. A reward placement needs no purchase controller, so the API key is all it needs. A `ReduceChurn` placement whose offers sell a product also needs an `IEncorePurchaseController`, passed to `Configure`.
***
## Initialize Encore
Call `Encore.Configure` once, from the Unity main thread, before you identify the player or present anything. A `MonoBehaviour` in your first scene is a good place:
```csharp theme={null}
using EncoreKit;
using UnityEngine;
public class EncoreBootstrap : MonoBehaviour
{
private void Awake()
{
Encore.Configure("pk_your_api_key_here");
}
}
```
Replace `pk_your_api_key_here` with your publishable **Live** key from the Dashboard under **Settings → Project API Keys**. Use the **Test** key for development builds.
`Configure` throws `ArgumentException` when the key is null or empty. The full contract is on [`Configure()`](/publishers/unity/sdk-reference/configure).
### Log level
Pass a `LogLevel` to see Encore's logs. The default is `LogLevel.None`:
```csharp theme={null}
Encore.Configure("pk_your_api_key_here", LogLevel.Debug);
```
The levels are `None`, `Error`, `Warn`, `Info`, and `Debug`. The package's own messages go to the Unity log, and the native SDKs' logs to Xcode or Android Studio. On WebGL they go to the browser console. Details: [`Configure()` notes](/publishers/unity/sdk-reference/configure#notes).
***
## Threading
Call every `Encore` method from the Unity main thread. Every callback, `Task` continuation, and event the package raises also arrives on the main thread, so you can use Unity objects in them directly.
***
## Next steps
> [card] [User management](/publishers/unity/quickstart/user-management)
>
> Identify the player and set attributes
> [card] [Present offers](/publishers/unity/quickstart/present-offers)
>
> Show the reward sheet at a moment the player earned
# Install the SDK
Source: https://docs.encorekit.com/publishers/unity/quickstart/install
Add the Encore Unity package to your project, so your game presents Encore's reward sheet from C#.
## Overview
The Encore Unity package lets your game present premium brand offers, real perks a brand funds to acquire customers, at the moments you choose. It is a C# API over the native iOS (`EncoreKit`) and Android (`com.encorekit:encore`) SDKs, and over the Encore web SDK in a WebGL build: the SDK draws the reward sheet and trigger components above your game, and runs the analytics.
You'll add External Dependency Manager for Unity, which brings in the native SDKs at build time, then add the package.
***
## Prerequisites
* **Unity 2022.3** or later.
* **Android:** minimum API level 24, target API level 35.
* **iOS:** deployment target 15.0. Offers show on **iOS 17** and later. On iOS 15 and 16, `ShowAsync()` returns not presented with the reason [`UnsupportedOS`](/publishers/unity/sdk-reference/presentation-result), and trigger components draw nothing.
* **WebGL:** read the WebGL warning below first. The package bundles the Encore web SDK, so the WebGL template needs no change.
* 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.
The package supports Android, iOS, and WebGL builds. Where the platforms differ, each reference page names the ones that read a setting. In the Unity Editor every placement returns a not-presented result and trigger components stay empty, so your game still runs there.
> [!WARNING]
>
> **WebGL is tested on Unity 6.3 only**, in desktop Chrome, iOS Safari, and Android Chrome, and in a cross-origin iframe on iOS Safari. Unity 2022.3 does not support mobile browsers. When a sheet opens while the game is in full-screen mode, the game leaves full-screen mode so the sheet can show. On a phone in landscape, the sheet opens as a column in the middle of the screen.
Some Unity versions and billing packages need a step before an Android build succeeds. Read [Build compatibility](/publishers/unity/guides/build-compatibility) before your first device build.
***
## Step 1: Add External Dependency Manager for Unity
The package lists the native SDKs in `Editor/EncoreDependencies.xml`. [External Dependency Manager for Unity](https://openupm.com/packages/com.google.external-dependency-manager/) (EDM4U) reads that file and adds the native SDKs to your Android Gradle build and the CocoaPods file of your iOS build. **Without EDM4U, the native SDKs are not in your build.**
If your project doesn't have EDM4U yet, add the OpenUPM registry and the package to `Packages/manifest.json`:
```json theme={null}
{
"scopedRegistries": [
{
"name": "package.openupm.com",
"url": "https://package.openupm.com",
"scopes": ["com.google.external-dependency-manager"]
}
],
"dependencies": {
"com.google.external-dependency-manager": "1.2.190"
}
}
```
Many ad and analytics SDKs already bring EDM4U. Keep one copy.
***
## Step 2: Add the package
Pick a version from the [Encore Unity SDK releases](https://github.com/EncoreKit/unity-sdk/releases). In Unity, open **Window → Package Manager**, select **+ → Add package from git URL**, and enter the URL with that version's tag in place of `vX.Y.Z`:
```text theme={null}
https://github.com/EncoreKit/unity-sdk.git#vX.Y.Z
```
Or add it to `Packages/manifest.json`:
```json theme={null}
{
"dependencies": {
"com.encorekit.unity": "https://github.com/EncoreKit/unity-sdk.git#vX.Y.Z"
}
}
```
The tag pins the version, so the package changes only when you change the tag. The package is `com.encorekit.unity`. It pins the native SDKs it was built against to exact versions. Version 2.5.0 pins `com.encorekit:encore` 2.5.0 on Android and `EncoreKit` 2.5.0 on iOS, and bundles `@encorekit/web-sdk` 2.5.0 for a WebGL build.
***
## Step 3: Platform setup
**Android:** set **Minimum API Level** to 24 or higher under **Project Settings → Player → Android → Other Settings**. If your project has no `Assets/Plugins/Android` folder, create it. EDM4U writes its Gradle templates there and adds `com.encorekit:encore` to them when you build.
> [!NOTE]
>
> Without that folder, EDM4U falls back to a resolver that fails on Unity 6, and the build log shows `Resolution failed` for `com.encorekit:encore`.
**iOS:** nothing to set beyond the deployment target. EDM4U adds the `EncoreKit` pod to every target of the Xcode project Unity exports, including the app target, which must embed the framework.
***
## Next steps
> [card] [Configure the SDK](/publishers/unity/quickstart/configure)
>
> Initialize Encore with your API key
> [card] [Build compatibility](/publishers/unity/guides/build-compatibility)
>
> Unity versions and billing packages, measured
# Presenting Offers
Source: https://docs.encorekit.com/publishers/unity/quickstart/present-offers
Present Encore's reward sheet at a moment the player just earned, such as a cleared level or a kept streak, in your Unity game.
## 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. In a game, that is a moment the player just earned: a cleared level, a daily streak, a completed purchase. This is the [Reward Users](/publishers/use-cases/post-action-reward) use case, and it costs you nothing to give.
Call `.UseCase(UseCase.RewardUsers)` for this. A placement with no `UseCase` call is `UseCase.ReduceChurn`, the [Reduce Churn](/publishers/use-cases/churn-intervention) use case.
***
## Present an offer
Build a placement with an ID that names the moment, set the copy, and await `ShowAsync()`. The Encore SDK draws the sheet above your game. `ShowAsync()` **never throws**: every outcome, including "nothing was presented", is a value on the returned `PresentationResult`.
```csharp theme={null}
using EncoreKit;
using UnityEngine;
public class LevelComplete : MonoBehaviour
{
public async void OnLevelCleared(int level)
{
var result = await Encore.Placement("level_complete")
.UseCase(UseCase.RewardUsers)
.Headline($"Level {level} cleared!") // optional
.Subheadline("Here is a thank you from us") // optional
.ShowAsync();
if (result.Claim?.TransactionId is string transactionId)
{
// The player claimed an offer. Keep the transaction ID; it carries the attribution.
SaveClaim(transactionId);
}
// Every other result: carry on with your own celebration screen.
}
private void SaveClaim(string transactionId) { /* your storage */ }
}
```
For a call site that can't await, `Show(Action)` takes a callback instead. The result, from either form, arrives on the Unity main thread. Contract: [`Placement()`](/publishers/unity/sdk-reference/placement).
Your game keeps running under the sheet on every platform. On Android the sheet draws in your game's own window, so `OnApplicationPause` does not fire while it is open. If your game stops timers or audio on pause, stop them yourself while a sheet is open, for example from [`OnLoadingStateChange`](/publishers/unity/sdk-reference/placement) and the result.
***
## Read the result
`result.Claim` is the offer the player claimed, or null. It means the player went to the brand, not that they finished the offer. Keep `Claim.TransactionId`: it carries the attribution. When no sheet appeared, `result.Reason` says why; `NoOffers`, `UseCaseUnavailable`, and `Error` are the common reasons. Treat each as a normal outcome for a reward moment: show your own celebration and carry on. Every field is on [`PresentationResult`](/publishers/unity/sdk-reference/presentation-result).
> [!WARNING]
>
> **A claim is not a conversion.** Never pay out or grant access on a claim alone. Encore's servers confirm the completion later, joined on the transaction ID.
To see every result in one place, for analytics, subscribe to [`Encore.Outcomes`](/publishers/unity/sdk-reference/outcomes).
***
## Next steps
> [card] [Reward placements](/publishers/guides/reward-placements)
>
> Where the copy comes from, and the gotchas
> [card] [Gifts Button](/publishers/triggers/gifts-button)
>
> Let the player open the sheet when they choose
# User Management
Source: https://docs.encorekit.com/publishers/unity/quickstart/user-management
Identify the player, set attributes for offer targeting, set the language, and reset on logout in the Encore Unity package.
## Overview
Identify the player so Encore can trace a claim back to them, and set attributes so it can pick offers that suit them.
***
## Identify the player
Call `Identify` with your own stable player ID once you know it, for example after sign-in. Identity powers attribution: a claim is traced back to this player through it.
```csharp theme={null}
using EncoreKit;
Encore.Identify(playerId);
```
Call it after `Encore.Configure`. A call made before `Configure` is ignored. Contract: [`Identify()`](/publishers/unity/sdk-reference/identify).
***
## Set attributes
Attributes help Encore pick offers that suit the player. Pass them with `Identify`, or later with `SetUserAttributes`:
```csharp theme={null}
Encore.Identify(playerId, new UserAttributes
{
CountryCode = "US",
Age = 29,
});
// Later, for example after the player picks a plan:
Encore.SetUserAttributes(new UserAttributes { SubscriptionTier = "pro" });
```
Gender is accepted only from a game rated 18+ in its store listing, so leave `Gender` out otherwise.
> [!WARNING]
>
> Only pass what you have a lawful basis to share, such as the player's consent. Pass the player's age in whole years as `Age`, or their date of birth as `DateOfBirth` (`YYYY-MM-DD`), whichever your game has. The package 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 player under 18 is still served offers, from age-appropriate inventory only and with no per-user personalization. Encore's servers do this filtering, so your game doesn't filter offers itself. See [Sending an age](/publishers/offers-api/reference/user-attributes#sending-an-age).
Contract: [`SetUserAttributes()`](/publishers/unity/sdk-reference/set-user-attributes), and every field is on [`UserAttributes`](/publishers/unity/sdk-reference/user-attributes).
***
## Set the language
Encore's copy follows the device language. To match a language the player picked in your game, pass a BCP 47 tag such as `es` or `pt-BR`, and clear it to go back to the device language:
```csharp theme={null}
Encore.SetLanguage("pt-BR");
Encore.ClearLanguage();
```
Contract: [`SetLanguage()`](/publishers/unity/sdk-reference/set-language) and [`ClearLanguage()`](/publishers/unity/sdk-reference/clear-language). How Encore picks a language is on [Localization](/publishers/concepts/localization).
***
## Reset on logout
Call `Reset` when the player signs out, so the next player doesn't inherit their identity:
```csharp theme={null}
Encore.Reset();
```
Contract: [`Reset()`](/publishers/unity/sdk-reference/reset).
***
## Next steps
> [card] [Present offers](/publishers/unity/quickstart/present-offers)
>
> Show the reward sheet at a moment the player earned
> [card] [Gifts Button](/publishers/triggers/gifts-button)
>
> Put a gift entry on a game screen
# AppearanceConfig
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/appearance-config
Your brand colors and light or dark mode for the reward sheet and trigger components in a Unity game.
Colors you pass to [`Placement().Appearance()`](/publishers/unity/sdk-reference/placement) for the sheet, or to a trigger component's [`TriggerOptions.Appearance`](/publishers/unity/sdk-reference/encore-trigger) and `SetAppearance()` for the entry. Every field is optional, and a field you leave null keeps the look's own color.
## Structure
```csharp theme={null}
public sealed class AppearanceConfig
{
public string AccentColor; // sheet and trigger components
public string BackgroundColor; // sheet and trigger components
public string TextColor; // sheet and trigger components
public string SecondaryTextColor; // trigger components
public string TrackColor; // trigger components
public string OnAccentColor; // trigger components
public ColorScheme? ColorScheme; // trigger components; null follows the app's setting in the Encore portal
public string BackgroundEndColor; // trigger components
}
public enum ColorScheme { System, Light, Dark }
```
Colors are hex strings: `#RGB`, `#RRGGBB`, or `#RRGGBBAA`. The sheet reads `AccentColor`, `BackgroundColor`, and `TextColor`, and applies `TextColor` only together with `BackgroundColor`. A trigger component reads every field; what each one colors on the entry is in [Colors](/publishers/triggers/overview#colors).
## Example
```csharp theme={null}
var brand = new AppearanceConfig
{
AccentColor = "#5671FF",
BackgroundColor = "#101827",
TextColor = "#FFFFFF",
ColorScheme = ColorScheme.Dark,
};
```
## Notes
* Read on Android, iOS, and WebGL builds.
* An appearance on a placement styles that sheet. An appearance on a trigger component styles the entry only, never the sheet it opens.
# ClaimReminder
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/claim-reminder
The Unity API for the Claim Reminder trigger component: a banner for an offer the player claimed and hasn't finished, from code or with EncoreClaimReminderView.
The Unity form of the [Claim Reminder](/publishers/triggers/claim-reminder) trigger component. The native banner floats above the Unity view at a rect your game sets. It reminds the player of an offer they claimed but haven't finished, and a tap opens the sheet that holds that offer. Its height stays 0 while there is no claim to show.
## Signature
```csharp theme={null}
public sealed class ClaimReminder : EncoreTrigger
{
public static ClaimReminder Create(string placement, TriggerOptions options = null);
}
```
`ClaimReminder` is an [`EncoreTrigger`](/publishers/unity/sdk-reference/encore-trigger) with the trigger ID `claimReminder` built in. Placing it, its height, its live setters, its `Result` event, and `Dispose()` are on [`EncoreTrigger`](/publishers/unity/sdk-reference/encore-trigger#members), and every option is on [`TriggerOptions`](/publishers/unity/sdk-reference/encore-trigger#signature).
`Create` throws `ArgumentException` for a blank placement.
## Example
```csharp theme={null}
using EncoreKit;
using UnityEngine;
public class HomeScreen : MonoBehaviour
{
private ClaimReminder _reminder;
private void Start()
{
_reminder = ClaimReminder.Create("home", new TriggerOptions
{
Appearance = new AppearanceConfig { AccentColor = "#5671FF" },
});
_reminder.HeightChanged += height => LayoutAround(height); // 0 while there is no claim
_reminder.SetFrame(new Rect(40, Screen.height - 200, Screen.width - 80, 0));
}
private void OnDestroy() => _reminder?.Dispose();
private void LayoutAround(float height) { /* move your own UI */ }
}
```
## EncoreClaimReminderView
A `MonoBehaviour`, under **Add Component → Encore → Claim Reminder**, that keeps the banner over an empty `RectTransform` in your Canvas and follows it every frame as the layout moves or scales. It waits for `Encore.Configure`, then creates the banner in its first `LateUpdate` after that. With `resizeToContent` on, the element has no height while there is no claim.
```csharp theme={null}
public sealed class EncoreClaimReminderView : EncoreTriggerViewBase
{
public ClaimReminder Reminder { get; } // null until the banner exists
}
```
Its Inspector fields, `Placement`, and `Result` are those of [`EncoreTriggerView`](/publishers/unity/sdk-reference/encore-trigger#encoretriggerview), without `triggerId` and `autoOpenOff`.
## Notes
* What the banner shows, and when it renders nothing, is on [Claim Reminder](/publishers/triggers/claim-reminder#what-the-user-sees).
* The rules every trigger component shares, such as drawing order, are in [`EncoreTrigger` notes](/publishers/unity/sdk-reference/encore-trigger#notes).
# ClearLanguage()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/clear-language
Go back to the device language for Encore copy after SetLanguage().
Removes the override that [`SetLanguage()`](/publishers/unity/sdk-reference/set-language) set.
## Signature
```csharp theme={null}
public static void ClearLanguage()
```
## Example
```csharp theme={null}
Encore.ClearLanguage();
```
# ClearOfferCache()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/clear-offer-cache
Testing only, Android only: drop the offers and images Encore loaded ahead of time, without resetting the player.
Drops the offers and images Encore loaded ahead of time, and keeps the player's identity. Use it in test builds to compare a presentation with and without those cached offers for the same player. Android only: elsewhere it does nothing.
## Signature
```csharp theme={null}
public static void ClearOfferCache()
```
## Example
```csharp theme={null}
#if DEVELOPMENT_BUILD
Encore.ClearOfferCache(); // the next Show fetches offers again
#endif
```
## Notes
* A call before [`Configure()`](/publishers/unity/sdk-reference/configure) is ignored.
* To clear the player's identity instead, call [`Reset()`](/publishers/unity/sdk-reference/reset).
# Configure()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/configure
Initialize the Encore Unity package with your API key, options, and purchase controller, once, when your game starts.
Initializes Encore on the device. Call it once, from the Unity main thread, before you identify the player or present anything. Pass an [`IEncorePurchaseController`](/publishers/unity/sdk-reference/purchase-controller) here if your offers sell a product: `Configure` is the only place to set one.
## Signature
```csharp theme={null}
public static void Configure(string apiKey, LogLevel logLevel = LogLevel.None)
public static void Configure(string apiKey, EncoreOptions options)
public static void Configure(string apiKey, IEncorePurchaseController purchaseController, EncoreOptions options = null)
public static bool IsConfigured { get; }
```
## Parameters
| Name | Type | Default | Description |
| - | - | - | - |
| `apiKey` | `string` | required | Your publishable key from the Dashboard, starting with `pk_` |
| `logLevel` | `LogLevel` | `LogLevel.None` | Sets `EncoreOptions.LogLevel` and leaves every other option at its default |
| `options` | [`EncoreOptions`](#encoreoptions) | `null`, read as `new EncoreOptions()` | Log level, unlock mode, and transaction linking |
| `purchaseController` | [`IEncorePurchaseController`](/publishers/unity/sdk-reference/purchase-controller) | none | Your billing code. With no controller, Encore never asks for a purchase |
## EncoreOptions
```csharp theme={null}
public sealed class EncoreOptions
{
public LogLevel LogLevel = LogLevel.None; // native SDK logs, and this package's own logs
public UnlockMode Unlock = UnlockMode.Optimistic; // when access is granted after an offer flow
public bool TransactionLinking = true; // links store purchases to the player for lift measurement
}
public enum LogLevel { None, Error, Warn, Info, Debug }
public enum UnlockMode
{
Optimistic, // grant when the player comes back from the offer
Strict, // wait for the advertiser's postback
}
```
| Field | Type | Default | Description |
| - | - | - | - |
| `LogLevel` | `LogLevel` | `None` | How much the native SDK logs, and the level from which the package logs its own messages. At `None` the package logs nothing of its own, except the one error a trigger view logs for a blank ID or placement in the Inspector ([`EncoreTriggerView`](/publishers/unity/sdk-reference/encore-trigger#encoretriggerview)). Android, iOS, and WebGL |
| `Unlock` | `UnlockMode` | `Optimistic` | `Strict` waits for the advertiser's postback; a verification that lands after the flow arrives on [`Outcomes`](/publishers/unity/sdk-reference/outcomes) with `Kind = StrictUnlockVerified`. Android, iOS, and WebGL |
| `TransactionLinking` | `bool` | `true` | Links the store's purchases to the player for lift measurement. Android and iOS; WebGL has no store |
## Example
```csharp theme={null}
using EncoreKit;
using UnityEngine;
public class EncoreBootstrap : MonoBehaviour
{
private void Awake()
{
Encore.Configure(
"pk_your_api_key_here",
new GamePurchases(), // your IEncorePurchaseController
new EncoreOptions { LogLevel = Debug.isDebugBuild ? LogLevel.Debug : LogLevel.None });
}
}
```
For reward placements only, `Encore.Configure("pk_your_api_key_here")` is enough.
## Notes
* Throws `ArgumentException` when `apiKey` is null or empty. It throws nothing else.
* A failure inside the native layer is caught and logged at `LogLevel.Warn`. Encore stays unconfigured, `IsConfigured` stays `false`, and you can call `Configure` again.
* `IsConfigured` is `true` once a `Configure` call succeeded. A later `Configure` is ignored and logged at `LogLevel.Warn`, so the purchase controller and the options can't change after that.
* [`IsClaimEnabled`](/publishers/unity/sdk-reference/is-claim-enabled) can be set before `Configure`, which sends it.
* The package's own messages go to the Unity log. Failures inside the native bridges go to the iOS subsystem `com.encorekit.unity`, the Android tag `EncoreUnity`, or the browser console on WebGL.
# CurrentEntitlement()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/current-entitlement
Android only: read the in-app purchase product Encore's remote config offers now.
Returns the in-app purchase product Encore's remote config offers now. Android only.
## Signature
```csharp theme={null}
public static IapEntitlement CurrentEntitlement()
public sealed class IapEntitlement
{
public string ProductId;
public string OfferId;
public string BasePlanId;
}
```
## Example
```csharp theme={null}
var product = Encore.CurrentEntitlement();
if (product != null) Debug.Log($"Encore offers {product.ProductId} ({product.BasePlanId})");
```
## Notes
* Returns null on iOS and WebGL, before [`Configure()`](/publishers/unity/sdk-reference/configure), and when no product is set.
* It never throws: a native failure is logged at `LogLevel.Warn` and returns null.
# EncoreTrigger
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/encore-trigger
The Unity trigger host: place any trigger component by its ID above your game, and the members every trigger component shares.
The Unity form of the [trigger host](/publishers/triggers/quickstart#the-trigger-host). An `EncoreTrigger` is a trigger view the SDK draws above the Unity view, at a screen rect your game sets. [`GiftsButton`](/publishers/unity/sdk-reference/gifts-button) and [`ClaimReminder`](/publishers/unity/sdk-reference/claim-reminder) derive from it, so the members on this page are theirs too.
## Signature
```csharp theme={null}
public class EncoreTrigger : IDisposable
{
public static EncoreTrigger Create(string triggerId, string placement, TriggerOptions options = null);
public float Height { get; }
public event Action HeightChanged;
public event Action Result;
public void SetFrame(Rect screenRect);
public void SetVisible(bool visible);
public void SetText(string headline, string subheadline = null, string cta = null);
public void SetValues(IDictionary values);
public void SetAlignment(EncoreAlignment alignment);
public void SetAppearance(AppearanceConfig appearance);
public void Dispose();
}
public class TriggerOptions
{
public UseCase UseCase = UseCase.RewardUsers;
public bool AutoOpenOff; // forbids a look that opens its sheet by itself
public string Headline; // null keeps the look's own text
public string Subheadline;
public string Cta;
public Dictionary Values; // your words and numbers, by the names the look uses
public TriggerIcon Icon = TriggerIcon.Gift;
public EncoreAlignment Alignment = EncoreAlignment.Center; // across the width SetFrame gives
public AppearanceConfig Appearance; // the entry's colors, never the sheet's
}
public enum TriggerIcon { Gift, AppIcon, None }
public enum EncoreAlignment { Leading, Center, Trailing }
```
`Icon`, `Alignment`, and `Appearance` mean what they mean on every platform: see [Icon](/publishers/triggers/overview#icon), [Width and alignment](/publishers/triggers/overview#width-and-alignment), and [Colors](/publishers/triggers/overview#colors). The types are [`AppearanceConfig`](/publishers/unity/sdk-reference/appearance-config) and [`PresentationResult`](/publishers/unity/sdk-reference/presentation-result).
## Members
| Member | Description |
| - | - |
| `Create(triggerId, placement, options)` | Creates the trigger with the ID you give, such as `giftsButton` or `claimReminder`. An ID the native SDK doesn't know shows nothing. Throws `ArgumentException` for a blank ID or placement. Created before `Encore.Configure`, it shows nothing |
| `SetFrame(screenRect)` | Places the trigger. The rect is in Unity screen space (origin bottom-left, as `Screen` and `RectTransformUtility` use). Only `x`, `y`, and `width` are used: the top sits at the top edge of the rect and the trigger takes its own height, so pass a height of 0 to put the top at `y` |
| `Height`, `HeightChanged` | The trigger's height in Unity screen pixels, and the event when it changes. Zero while there is nothing to show: no offers, a holdout, or an error |
| `SetVisible(visible)` | Hides or shows the trigger without removing it |
| `SetText(headline, subheadline, cta)` | Redraws the text in place. A null line falls back to the look's own text |
| `SetValues(values)` | Replaces the look's values, such as a countdown, and redraws. The text stays as it is |
| `SetAlignment(alignment)` | Moves the card across the width `SetFrame` gives |
| `SetAppearance(appearance)` | Redraws the entry in your colors. Null goes back to the look's own colors |
| `Result` | The result of each sheet the trigger opens, from a tap or an automatic open |
| `Dispose()` | Removes the trigger. Safe to call more than once |
`TriggerOptions.UseCase` defaults to `RewardUsers`, the use case trigger components support.
## Example
```csharp theme={null}
using EncoreKit;
using UnityEngine;
public class HomeScreen : MonoBehaviour
{
private EncoreTrigger _trigger;
private void Start()
{
_trigger = EncoreTrigger.Create("giftsButton", "home");
_trigger.HeightChanged += height => Debug.Log($"Trigger height: {height}");
_trigger.SetFrame(new Rect(40, Screen.height - 200, Screen.width - 80, 0));
}
private void OnDestroy() => _trigger?.Dispose();
}
```
## EncoreTriggerView
A `MonoBehaviour`, under **Add Component → Encore → Trigger**, that keeps the trigger with the ID you give over an empty `RectTransform` in your Canvas, and follows it every frame as the layout moves or scales. It waits for `Encore.Configure`, then creates the trigger in its first `LateUpdate` after that. [`EncoreGiftsButtonView`](/publishers/unity/sdk-reference/gifts-button#encoregiftsbuttonview) and [`EncoreClaimReminderView`](/publishers/unity/sdk-reference/claim-reminder#encoreclaimreminderview) work the same way, with the ID built in.
```csharp theme={null}
public sealed class EncoreTriggerView : EncoreTriggerViewBase
{
public string TriggerId { get; set; } // read once, when the trigger is created
}
public abstract class EncoreTriggerViewBase : MonoBehaviour
{
public EncoreTrigger Trigger { get; } // null until the trigger exists
public string Placement { get; set; } // read once, when the trigger is created
public event Action Result;
}
```
| Inspector field | Default | Description |
| - | - | - |
| `triggerId` | `giftsButton` | `EncoreTriggerView` only. The trigger ID |
| `autoOpenOff` | off | `EncoreTriggerView` and `EncoreGiftsButtonView` only. Stops the trigger opening its sheet by itself |
| `placement` | `home` | The placement ID |
| `headline`, `subheadline`, `cta` | empty | Your text in place of the look's. Empty keeps the look's text |
| `icon` | `Gift` | The icon the look draws |
| `alignment` | `Center` | Where the card sits across the element's width. `SetAlignment` on the trigger changes it later |
| `resizeToContent` | on | Sets the element's height to the trigger's, and to zero when there is nothing to show |
Leave the element empty: the native trigger draws over it. Disabling the view hides the trigger, enabling it shows the trigger again, and destroying it removes the trigger. A blank ID or placement in the Inspector logs one error and disables the view.
## Notes
* The trigger draws above all Unity content. Hide it with `SetVisible(false)` while your game shows its own modal or pause screen.
* On iOS, trigger components draw only on iOS 17 or later. Below that the height stays 0.
* In the Unity Editor the trigger reports a height of 0 and draws nothing.
* On WebGL, `SetValues` and `SetAppearance` mount the trigger again instead of redrawing it in place.
# Entitlement
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/entitlements
The entitlement types and scopes you pass to IsActive and IsActivePublisher to check what an offer granted.
Describes an entitlement an offer can grant: a free trial, a discount, or a credit. Pass it to [`IsActive()`](/publishers/unity/sdk-reference/is-active) or [`IsActivePublisher()`](/publishers/unity/sdk-reference/is-active-publisher) to check whether the player has one now.
## Structure
```csharp theme={null}
public sealed class Entitlement
{
public EntitlementType Type;
public double? Value; // iOS ignores it and matches on Type only
public EntitlementUnit? Unit; // iOS ignores it and matches on Type only
public static Entitlement FreeTrial(double? value = null, EntitlementUnit? unit = null);
public static Entitlement Discount(double? value = null, EntitlementUnit? unit = null);
public static Entitlement Credit(double? value = null, EntitlementUnit? unit = null);
}
public enum EntitlementType { FreeTrial, Discount, Credit }
public enum EntitlementUnit { Months, Days, Percent, Dollars }
public enum EntitlementScope
{
All,
Verified, // on iOS, this also counts provisional grants
}
```
## Example
```csharp theme={null}
bool hasTrial = await Encore.IsActiveAsync(Entitlement.FreeTrial(), EntitlementScope.Verified);
```
## Notes
* Entitlement checks answer on iOS only. On Android and WebGL they answer `false`.
# GiftsButton
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/gifts-button
The Unity API for the Gifts Button trigger component: create it from code or with EncoreGiftsButtonView, place it, and read its results.
The Unity form of the [Gifts Button](/publishers/triggers/gifts-button) trigger component. The native button floats above the Unity view at a rect your game sets, and takes its height from the look Encore serves. After a claim it usually turns into the reminder look, so its height changes: listen to `HeightChanged`, or use `EncoreGiftsButtonView`, which resizes its element. Tapping it opens the reward sheet.
## Signature
```csharp theme={null}
public sealed class GiftsButton : EncoreTrigger
{
public static GiftsButton Create(string placement, GiftsButtonOptions options = null);
}
public sealed class GiftsButtonOptions : TriggerOptions
{
}
```
`GiftsButton` is an [`EncoreTrigger`](/publishers/unity/sdk-reference/encore-trigger) with the trigger ID `giftsButton` built in. Placing it, its height, its live setters, its `Result` event, and `Dispose()` are on [`EncoreTrigger`](/publishers/unity/sdk-reference/encore-trigger#members), and every option is on [`TriggerOptions`](/publishers/unity/sdk-reference/encore-trigger#signature).
`Create` throws `ArgumentException` for a blank placement.
## Example
```csharp theme={null}
using EncoreKit;
using UnityEngine;
public class DailyRewardsScreen : MonoBehaviour
{
private GiftsButton _gifts;
private void Start()
{
_gifts = GiftsButton.Create("daily_rewards", new GiftsButtonOptions { Headline = "You've got a gift" });
_gifts.Result += result =>
{
if (result.Claim?.TransactionId is string transactionId) SaveClaim(transactionId);
};
_gifts.SetFrame(new Rect(40, Screen.height - 200, Screen.width - 80, 0));
}
public void OnPauseMenuShown() => _gifts.SetVisible(false);
public void OnPauseMenuHidden() => _gifts.SetVisible(true);
private void OnDestroy() => _gifts?.Dispose();
private void SaveClaim(string transactionId) { /* your storage */ }
}
```
## EncoreGiftsButtonView
A `MonoBehaviour`, under **Add Component → Encore → Gifts Button**, that keeps the button over an empty `RectTransform` in your Canvas and follows it every frame as the layout moves or scales. It waits for `Encore.Configure`, then creates the button in its first `LateUpdate` after that.
```csharp theme={null}
public sealed class EncoreGiftsButtonView : EncoreTriggerViewBase
{
public GiftsButton Button { get; } // null until the button exists
}
```
Its Inspector fields, `Placement`, and `Result` are those of [`EncoreTriggerView`](/publishers/unity/sdk-reference/encore-trigger#encoretriggerview), without `triggerId`.
## Notes
* After a claim, the button can turn into a Claim Reminder; see [After a claim](/publishers/triggers/gifts-button#after-a-claim). It turns back after a later check of the claim confirms the completion (see [After a completion](/publishers/triggers/gifts-button#after-a-completion)), which can take a few minutes.
* The rules every trigger component shares, such as drawing order, are in [`EncoreTrigger` notes](/publishers/unity/sdk-reference/encore-trigger#notes).
# Identify()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/identify
Tie Encore's attribution to your own stable player ID, with optional attributes.
Sets the player's identity. A claim is traced back to this player through it.
## Signature
```csharp theme={null}
public static void Identify(string userId, UserAttributes attributes = null)
```
## Parameters
| Name | Type | Default | Description |
| - | - | - | - |
| `userId` | `string` | required | Your stable player ID, for example after sign-in |
| `attributes` | [`UserAttributes`](/publishers/unity/sdk-reference/user-attributes) | `null` | Attributes that help Encore pick offers |
## Example
```csharp theme={null}
Encore.Identify(playerId, new UserAttributes { CountryCode = "US" });
```
## Notes
* Throws `ArgumentException` when `userId` is null or empty.
* A call before [`Configure()`](/publishers/unity/sdk-reference/configure) is ignored.
# IsActive()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/is-active
Check once whether the player has an active entitlement, with a callback or a Task.
Asks whether an [`Entitlement`](/publishers/unity/sdk-reference/entitlements) is active for the player now. Answers on iOS only: on Android and WebGL it answers `false`.
## Signature
```csharp theme={null}
public static void IsActive(Entitlement entitlement, EntitlementScope scope, Action onResult)
public static void IsActive(Entitlement entitlement, Action onResult) // EntitlementScope.All
public static Task IsActiveAsync(Entitlement entitlement, EntitlementScope scope = EntitlementScope.All)
```
## Parameters
| Name | Type | Default | Description |
| - | - | - | - |
| `entitlement` | [`Entitlement`](/publishers/unity/sdk-reference/entitlements) | required | The entitlement to check |
| `scope` | [`EntitlementScope`](/publishers/unity/sdk-reference/entitlements) | `All` | Which grants count |
| `onResult` | `Action` | required | Called once with the answer |
## Example
```csharp theme={null}
if (await Encore.IsActiveAsync(Entitlement.FreeTrial()))
{
UnlockPremiumLevels();
}
```
## Notes
* The answer arrives once, on the Unity main thread.
* Before [`Configure()`](/publishers/unity/sdk-reference/configure), or when the native call fails, it answers `false`.
* Throws `ArgumentNullException` when `entitlement` or `onResult` is null.
* To follow changes, use [`IsActivePublisher()`](/publishers/unity/sdk-reference/is-active-publisher).
# IsActivePublisher()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/is-active-publisher
Follow whether the player has an active entitlement, with a callback on every change until you dispose the handle.
Calls `onChange` with the current state of an [`Entitlement`](/publishers/unity/sdk-reference/entitlements), then again on each change, until you dispose the handle it returns. Follows changes on iOS only: on Android and WebGL it calls `onChange(false)` once.
## Signature
```csharp theme={null}
public static IDisposable IsActivePublisher(Entitlement entitlement, EntitlementScope scope, Action onChange)
public static IDisposable IsActivePublisher(Entitlement entitlement, Action onChange) // EntitlementScope.All
```
## Parameters
| Name | Type | Default | Description |
| - | - | - | - |
| `entitlement` | [`Entitlement`](/publishers/unity/sdk-reference/entitlements) | required | The entitlement to follow |
| `scope` | [`EntitlementScope`](/publishers/unity/sdk-reference/entitlements) | `All` | Which grants count |
| `onChange` | `Action` | required | Called with the current state, then on each change |
## Example
```csharp theme={null}
using System;
using EncoreKit;
using UnityEngine;
public class PremiumBadge : MonoBehaviour
{
[SerializeField] private GameObject badge;
private IDisposable _subscription;
private void OnEnable() =>
_subscription = Encore.IsActivePublisher(Entitlement.FreeTrial(), active => badge.SetActive(active));
private void OnDisable() => _subscription?.Dispose();
}
```
## Notes
* `onChange` runs on the Unity main thread, and never after you dispose the handle.
* Before [`Configure()`](/publishers/unity/sdk-reference/configure), or when the native subscribe fails before any answer, it calls `onChange(false)` once.
* Throws `ArgumentNullException` when `entitlement` or `onChange` is null.
# IsClaimEnabled
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/is-claim-enabled
Turn the claim button on offer cards on or off at runtime, without reconfiguring Encore.
Whether the claim button on offer cards is tappable. Set it to `false` to turn the claim button off, and back to `true` to turn it on.
## Signature
```csharp theme={null}
public static bool IsClaimEnabled { get; set; } // default true
```
## Example
```csharp theme={null}
// A player in your own checkout flow can see offers but not claim them.
Encore.IsClaimEnabled = !checkout.IsOpen;
var result = await Encore.Placement("level_complete").UseCase(UseCase.RewardUsers).ShowAsync();
```
## Notes
* Android and iOS apply a change to a sheet that is already open. WebGL applies it from the next `Show`.
* You can set it before [`Configure()`](/publishers/unity/sdk-reference/configure), which sends it.
* It survives [`Reset()`](/publishers/unity/sdk-reference/reset).
* A native failure is logged at `LogLevel.Warn` and never thrown into your game.
# LinkPurchase()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/link-purchase
Android only: link a Google Play purchase your game made outside Encore's flow to the player, at once.
Links a Google Play purchase made outside Encore's offer flow to the player, at once. Android only: elsewhere it does nothing.
## Signature
```csharp theme={null}
public static void LinkPurchase(string purchaseToken)
```
## Parameters
| Name | Type | Description |
| - | - | - |
| `purchaseToken` | `string` | The Google Play purchase token |
## Example
```csharp theme={null}
Encore.LinkPurchase(purchase.PurchaseToken); // from your billing library's purchase
```
## Notes
* Throws `ArgumentException` when `purchaseToken` is null or empty.
* A call before [`Configure()`](/publishers/unity/sdk-reference/configure) is ignored.
# Outcomes
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/outcomes
An event that reports each presentation result the native SDK sends, wherever the placement was shown from, and each late strict unlock verification.
Raised once for each presentation result the native SDK reports, including the sheets trigger components open, and once for each claim that verifies after its flow ended under `UnlockMode.Strict`.
## Signature
```csharp theme={null}
public static event Action Outcomes;
public sealed class PlacementOutcome
{
public PlacementOutcomeKind Kind;
public string PlacementId; // Presentation only
public PresentationResult Result; // Presentation only
public string TransactionId; // StrictUnlockVerified only; matches the claim's ClaimedOffer.TransactionId
}
public enum PlacementOutcomeKind
{
Presentation, // a placement resolved
StrictUnlockVerified, // UnlockMode.Strict only; entitlements are already refreshed
}
```
| Field | Type | Description |
| - | - | - |
| `Kind` | `PlacementOutcomeKind` | Which of the two outcomes this is. Read it before the other fields |
| `PlacementId` | `string` | `Presentation` only. The placement that resolved |
| `Result` | [`PresentationResult`](/publishers/unity/sdk-reference/presentation-result) | `Presentation` only. What the presentation did |
| `TransactionId` | `string` | `StrictUnlockVerified` only. Matches `ClaimedOffer.TransactionId` on the claim's original result, so you can join the two |
## Example
```csharp theme={null}
Encore.Outcomes += outcome =>
{
if (outcome.Kind == PlacementOutcomeKind.Presentation)
{
Debug.Log($"{outcome.PlacementId}: presented={outcome.Result.Presented}");
}
else
{
Debug.Log($"Verified late: {outcome.TransactionId}");
}
};
```
## Notes
* Raised on the Unity main thread.
* `StrictUnlockVerified` arrives only when [`EncoreOptions.Unlock`](/publishers/unity/sdk-reference/configure#encoreoptions) is `UnlockMode.Strict`.
* Results the package builds itself, before the native SDK is reached, are not raised: `NotConfigured`, a bridge failure returned as `Error`, and `UseCaseUnavailable` from the builder. In the Unity Editor it never fires.
* It carries the same results your own call and a trigger component's `Result` event receive, so grant from one place only.
# Overview
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/overview
Every method, interface, trigger component, and type in the Encore Unity package, with C# signatures and platform differences.
Contracts for the Encore Unity package: the methods you call, the interface you implement, the trigger components you place, and the types they exchange. Every symbol on these pages is in the `EncoreKit` namespace.
> [!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 [Unity Quickstart](/publishers/unity/quickstart/install) for installation and configuration
> * **Build problems:** See [Build compatibility](/publishers/unity/guides/build-compatibility)
## Core methods
> [card] [Configure()](/publishers/unity/sdk-reference/configure)
>
> Initialize Encore with your API key, options, and purchase controller
> [card] [Identify()](/publishers/unity/sdk-reference/identify)
>
> Tie attribution to your own stable player ID
> [card] [SetUserAttributes()](/publishers/unity/sdk-reference/set-user-attributes)
>
> Update the attributes Encore uses to pick offers
> [card] [SetLanguage()](/publishers/unity/sdk-reference/set-language)
>
> Show Encore's copy in a language the player picked
> [card] [ClearLanguage()](/publishers/unity/sdk-reference/clear-language)
>
> Go back to the device language
> [card] [Reset()](/publishers/unity/sdk-reference/reset)
>
> Clear the identified player on logout
## Presenting offers
> [card] [Placement()](/publishers/unity/sdk-reference/placement)
>
> Build a placement and present Encore's sheet
> [card] [IEncorePurchaseController](/publishers/unity/sdk-reference/purchase-controller)
>
> The interface your game implements so purchases run through your billing code
> [card] [Outcomes](/publishers/unity/sdk-reference/outcomes)
>
> An event for every presentation result and late strict unlock verification
> [card] [IsClaimEnabled](/publishers/unity/sdk-reference/is-claim-enabled)
>
> Turn the claim button on offer cards on or off
## Trigger components
> [card] [GiftsButton](/publishers/unity/sdk-reference/gifts-button)
>
> The gift entry, from code or with EncoreGiftsButtonView
> [card] [ClaimReminder](/publishers/unity/sdk-reference/claim-reminder)
>
> A banner for an offer the player claimed and hasn't finished
> [card] [EncoreTrigger](/publishers/unity/sdk-reference/encore-trigger)
>
> Any trigger component by its ID, and the members every one shares
## Entitlements
> [card] [IsActive()](/publishers/unity/sdk-reference/is-active)
>
> Check once whether an entitlement is active
> [card] [IsActivePublisher()](/publishers/unity/sdk-reference/is-active-publisher)
>
> Follow an entitlement's state until you dispose the handle
> [card] [LinkPurchase()](/publishers/unity/sdk-reference/link-purchase)
>
> Android only: link a Play purchase made outside Encore's flow
> [card] [CurrentEntitlement()](/publishers/unity/sdk-reference/current-entitlement)
>
> Android only: the in-app purchase product Encore offers now
> [card] [RevokeEntitlements()](/publishers/unity/sdk-reference/revoke-entitlements)
>
> Testing only: expire the player's entitlements and keep the player identified
> [card] [ClearOfferCache()](/publishers/unity/sdk-reference/clear-offer-cache)
>
> Testing only, Android only: drop the offers and images loaded ahead of time
## Types
> [card] [PresentationResult](/publishers/unity/sdk-reference/presentation-result)
>
> What one presentation did
> [card] [UserAttributes](/publishers/unity/sdk-reference/user-attributes)
>
> The player attributes Encore uses to pick offers
> [card] [AppearanceConfig](/publishers/unity/sdk-reference/appearance-config)
>
> Your colors for the sheet and trigger components
> [card] [Entitlement](/publishers/unity/sdk-reference/entitlements)
>
> The entitlement types and scopes you check
> [card] [EncoreCallResult](/publishers/unity/sdk-reference/revoke-entitlements#encorecallresult)
>
> The success or failure of a call that returns no value
## Basic integration
```csharp theme={null}
using EncoreKit;
// 1. Configure once when the game starts.
Encore.Configure("pk_your_api_key_here");
// 2. Identify the player once you know them.
Encore.Identify(playerId);
// 3. Present an offer at a moment the player earned, and read the result.
var result = await Encore.Placement("level_complete")
.UseCase(UseCase.RewardUsers)
.ShowAsync();
if (result.Claim?.TransactionId is string transactionId)
{
SaveClaim(transactionId); // the player claimed an offer
}
```
> [!NOTE]
>
> `ShowAsync()` never throws. Every outcome, including "nothing was presented", is a value on the [`PresentationResult`](/publishers/unity/sdk-reference/presentation-result).
## Platform support
The package supports Android, iOS, and WebGL builds. WebGL is tested in one setup only, so read the [WebGL warning](/publishers/unity/quickstart/install#prerequisites) before you ship a WebGL build. Where the platforms differ, each entry names the ones that read it. In the Unity Editor, Encore configures but presents nothing: every placement returns a not-presented result and trigger components stay at height 0.
# Placement()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/placement
Build a placement for a moment in your game and present Encore's sheet.
Creates a placement builder. `ShowAsync()` presents Encore's sheet above your game and completes with a [`PresentationResult`](/publishers/unity/sdk-reference/presentation-result).
## Signature
```csharp theme={null}
public static Placement Placement(string placementId)
public sealed class Placement
{
public Placement UseCase(UseCase useCase);
public Placement Headline(string headline);
public Placement Subheadline(string subheadline);
public Placement Cta(string cta);
public Placement Decline(string decline);
public Placement Badge(string badge);
public Placement Appearance(AppearanceConfig appearance);
public event Action OnLoadingStateChange;
public void Prefetch();
public Task HasOffersAsync();
public void HasOffers(Action onResult);
public Task ShowAsync();
public void Show(Action onResult);
}
public enum UseCase { RewardUsers, ReduceChurn }
```
Each step sets a value on the same builder and returns it.
## Parameters
| Name | Type | Platforms | Description |
| - | - | - | - |
| `placementId` | `string` | All | Names the moment, such as `level_complete`. Results and analytics carry it |
| `UseCase` | `UseCase` | All | `RewardUsers` for a moment the player earned, or `ReduceChurn` for a paywall decline. `ReduceChurn` is the default, so a reward placement must set `RewardUsers`. Offers that sell a product need an [`IEncorePurchaseController`](/publishers/unity/sdk-reference/purchase-controller) in `Configure` |
| `Headline`, `Subheadline` | `string` | All | Your copy for this presentation. Null or empty falls back to the copy Encore resolved for your app |
| `Cta` | `string` | Android, iOS | The primary button's label. Read by the reward use case only. An empty string keeps the served copy |
| `Decline` | `string` | Android, iOS | The decline button's label, with the same rules as `Cta` |
| `Badge` | `string` | Android, iOS | The badge on the highlighted offer, with the same rules as `Cta` |
| `Appearance` | [`AppearanceConfig`](/publishers/unity/sdk-reference/appearance-config) | Android, iOS, WebGL | Your colors for this sheet. The sheet reads `AccentColor`, `BackgroundColor`, and `TextColor` (`TextColor` only together with `BackgroundColor`) |
| `OnLoadingStateChange` | `event Action` | All | `true` when `Show` starts and `false` when its result arrives, before the result callback. Raised on the main thread |
| `Prefetch()` | | iOS | Warms this placement's offers so `Show` opens without a network round trip. Call it when the screen comes into view. Elsewhere it does nothing |
| `HasOffersAsync()`, `HasOffers()` | `Task`, `Action` | All | Whether `Show` would find offers for this player now. See [Show your entry only when it opens something](#show-your-entry-only-when-it-opens-something) |
## Example
```csharp theme={null}
var reward = Encore.Placement("level_complete").UseCase(UseCase.RewardUsers);
reward.Prefetch(); // when the level-complete screen opens
reward.OnLoadingStateChange += loading => spinner.SetActive(loading);
var result = await reward
.Headline("Level 3 cleared!")
.Cta("Claim my gift")
.Decline("Maybe later")
.ShowAsync();
```
## Show your entry only when it opens something
`HasOffersAsync()` asks whether `Show` would find offers for this player now, so a button you draw yourself can stay hidden when no offer fits:
```csharp theme={null}
var reward = Encore.Placement("level_complete").UseCase(UseCase.RewardUsers);
giftButton.SetActive(await reward.HasOffersAsync());
```
It answers `false` for `ReduceChurn`, so set `RewardUsers` first. It also answers `false` before [`Configure()`](/publishers/unity/sdk-reference/configure), in the Unity Editor, and on any failure. `HasOffers(onResult)` gives the same answer through a callback.
## Notes
* The last call to each setter wins.
* Subscribe to `OnLoadingStateChange` before you call `Show` or `ShowAsync`: each call reads the handlers it has then.
* `ShowAsync()` never throws: every outcome, including "nothing was presented", is a value on the result. `Show()` throws `ArgumentNullException` only when `onResult` is null.
* The result arrives on the Unity main thread, and so does the `HasOffers` answer.
* The reward use case, the copy rules, and the gotchas are in [Reward placements](/publishers/guides/reward-placements).
# PresentationResult
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/presentation-result
What one presentation did: whether a sheet appeared, the offer the player claimed, and why nothing appeared.
Every placement and every sheet a trigger component opens completes with one `PresentationResult`.
## Structure
```csharp theme={null}
public sealed class PresentationResult
{
public bool Presented; // a sheet appeared
public NotPresentedReason Reason; // why not, when Presented is false
public string ErrorType; // the error, when there was one
public string ErrorMessage;
public AdvertiserOutcomeType Advertiser;
public ClaimedOffer Offer;
public string Publisher;
public string Dismissal; // how the sheet closed, such as "close_button"
public ClaimedOffer Claim { get; } // Offer when the player claimed, else null
}
public sealed class ClaimedOffer
{
public string OfferId; // null on Android
public string CampaignId;
public string AdvertiserName;
public string TransactionId; // keep it: it carries the attribution
}
public enum AdvertiserOutcomeType { NotAttempted, Claimed, Verified, Cooldown, Failed, Unknown }
public enum NotPresentedReason
{
None, NotConfigured, AlreadyPresenting, NoOffers, ExperimentControl, UseCaseUnavailable, Error,
NoForegroundActivity, // Android only
IapFirstDeclined, // Android only
UnsupportedOS, // iOS only
Unknown, // a value this package version does not know
}
```
## Example
```csharp theme={null}
if (result.Claim?.TransactionId is string transactionId) SaveClaim(transactionId);
else if (!result.Presented) Debug.Log($"No sheet: {result.Reason}");
```
## Notes
* `Claim` is set when `Advertiser` is `Claimed` or `Verified`. A claim means the player went to the brand, not that they finished the offer.
* In the Unity Editor every placement returns `Presented = false` with `Reason = Error`, because the package has no native SDK to call there.
# IEncorePurchaseController
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/purchase-controller
The interface your game implements so a product an Encore offer sells is bought through your own billing code.
When a `ReduceChurn` offer sells a product, Encore asks your game to buy it through an `IEncorePurchaseController` you pass to [`Configure()`](/publishers/unity/sdk-reference/configure). Encore decides when; your code buys it, through your own store or billing library. Encore owns the sheet, the analytics, and the attribution around the call. A reward placement never asks for a purchase.
## Definition
```csharp theme={null}
public interface IEncorePurchaseController
{
// Called on the Unity main thread. Throw, or fault the task, for a real failure.
Task Purchase(PurchaseRequest request);
}
public enum PurchaseResult
{
Purchased, // the purchase completed
Cancelled, // the player backed out
Pending, // the store deferred the purchase
}
```
* **A throw is a failed purchase**, never a cancelled one. So are a faulted task, a null task, and a result the package doesn't know.
* **The controller lives for the process.** `Configure` takes it once; a second `Configure` is ignored.
## PurchaseRequest
```csharp theme={null}
public sealed class PurchaseRequest
{
public string ProductId; // the store product to buy
public string PlacementId; // null when the purchase did not come from a named placement
public string PromoOfferId; // the offer to apply: an App Store promotional offer on iOS, a Google Play offer on Android
public string BasePlanId; // Android only: the Google Play base plan to buy
}
```
| Field | Type | Description |
| - | - | - |
| `ProductId` | `string` | The store product identifier to buy |
| `PlacementId` | `string` | The placement the purchase came from, or null when it came from no named placement |
| `PromoOfferId` | `string` | The offer to apply, when the offer has one. On iOS, an App Store promotional offer. On Android, a Google Play offer ID. The package sends no `offerToken`, so your billing code picks the offer whose base plan is `BasePlanId` and whose offer ID is this one, and buys with that offer's `offerToken` |
| `BasePlanId` | `string` | Android only. The Google Play base plan to buy, when the offer has one |
## Example
Implement the controller over your own billing code:
```csharp GamePurchases.cs theme={null}
using System.Threading.Tasks;
using EncoreKit;
public sealed class GamePurchases : IEncorePurchaseController
{
public async Task Purchase(PurchaseRequest request)
{
// Pass PromoOfferId when it is set: a promotional offer on iOS, a Play offer ID with BasePlanId on Android.
var outcome = await MyStore.Buy(request.ProductId, request.BasePlanId, request.PromoOfferId);
if (outcome.Cancelled) return PurchaseResult.Cancelled;
if (outcome.Deferred) return PurchaseResult.Pending;
return PurchaseResult.Purchased;
// Throw for a real failure.
}
}
```
`MyStore` stands for your own billing code, such as Unity IAP or RevenueCat. Then pass the controller to `Configure` in place of the plain call, and show a Reduce Churn placement:
```csharp theme={null}
// In your bootstrap's Awake():
Encore.Configure("pk_your_api_key_here", new GamePurchases());
// Later, in an async method, when the player turns down your paywall:
var result = await Encore.Placement("paywall_decline").UseCase(UseCase.ReduceChurn).ShowAsync();
```
## Notes
* **Android:** the sheet draws in your game's own window, so Unity keeps running and your controller is called while the sheet is open. If your game sets `com.encorekit.offerSheetInHostWindow` to `false` in its manifest, the sheet opens as its own Activity, Unity pauses, and a purchase runs only after the sheet closes.
* **WebGL:** the web SDK sells nothing, so Encore never calls the controller.
# Reset()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/reset
Clear the identified player when they sign out, so the next player starts fresh.
Clears the identity that [`Identify()`](/publishers/unity/sdk-reference/identify) set. Call it on logout.
## Signature
```csharp theme={null}
public static void Reset()
```
## Example
```csharp theme={null}
Encore.Reset();
```
# RevokeEntitlements()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/revoke-entitlements
Testing only: expire every entitlement for the current player on iOS and WebGL, keeping the player's ID and attributes, so you can run the same offer flow again.
On iOS and WebGL, expires every entitlement Encore granted the current player, and keeps the player's ID and attributes. Use it in test and development builds to run an offer flow again for the same player. Don't call it in a release build.
[`Reset()`](/publishers/unity/sdk-reference/reset) clears the player's identity. `RevokeEntitlements()` keeps it.
## Signature
```csharp theme={null}
public static void RevokeEntitlements(Action onComplete)
public static Task RevokeEntitlementsAsync()
```
## Parameters
| Name | Type | Description |
| - | - | - |
| `onComplete` | `Action` | Called once with the result, on the Unity main thread |
## Returns
`RevokeEntitlementsAsync()` returns a task that completes with an [`EncoreCallResult`](#encorecallresult). The task never faults: a failure is a result with `Success = false`.
## Example
```csharp theme={null}
#if DEVELOPMENT_BUILD
var result = await Encore.RevokeEntitlementsAsync();
if (!result.Success) Debug.LogWarning($"Revoke failed: {result.ErrorType} {result.ErrorMessage}");
var active = await Encore.IsActiveAsync(Entitlement.FreeTrial()); // false after a successful revoke
#endif
```
## EncoreCallResult
The result of a call that returns no value.
```csharp theme={null}
public sealed class EncoreCallResult
{
public bool Success;
public string ErrorType; // null on success
public string ErrorMessage; // null on success
}
```
| Field | Type | Description |
| - | - | - |
| `Success` | `bool` | `true` when the call succeeded |
| `ErrorType` | `string` | A short code for the failure, such as `not_configured`, `network_error`, or `domain_error` |
| `ErrorMessage` | `string` | A readable description of the failure, for your logs |
## Notes
* iOS and WebGL revoke. Android has no revoke in its native SDK, so on Android the result is always a failure with `ErrorType = "domain_error"`. In the Unity Editor the result is also a failure.
* Before [`Configure()`](/publishers/unity/sdk-reference/configure), the result is a failure with `ErrorType = "not_configured"`.
* `RevokeEntitlements` throws `ArgumentNullException` when `onComplete` is null.
# SetLanguage()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/set-language
Show Encore's copy in a language the player picked in your game, instead of the device language.
Overrides the device language for Encore copy.
## Signature
```csharp theme={null}
public static void SetLanguage(string tag)
```
## Parameters
| Name | Type | Description |
| - | - | - |
| `tag` | `string` | A BCP 47 language tag, such as `es` or `pt-BR` |
## Example
```csharp theme={null}
Encore.SetLanguage("pt-BR");
```
## Notes
* Throws `ArgumentException` when `tag` is null or empty. Any other invalid tag is logged and ignored, and the language already in effect stays.
* [`ClearLanguage()`](/publishers/unity/sdk-reference/clear-language) goes back to the device language.
* How Encore picks the language, and what it translates, is on [Localization](/publishers/concepts/localization).
# SetUserAttributes()
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/set-user-attributes
Update the attributes Encore uses to pick offers for the identified player.
Merges attributes for the current player. Every field is on [`UserAttributes`](/publishers/unity/sdk-reference/user-attributes).
## Signature
```csharp theme={null}
public static void SetUserAttributes(UserAttributes attributes)
```
## Parameters
| Name | Type | Description |
| - | - | - |
| `attributes` | [`UserAttributes`](/publishers/unity/sdk-reference/user-attributes) | The fields to set. An object with no fields set changes nothing |
## Example
```csharp theme={null}
Encore.SetUserAttributes(new UserAttributes { SubscriptionTier = "pro" });
```
## Notes
* Throws `ArgumentNullException` when `attributes` is null.
# UserAttributes
Source: https://docs.encorekit.com/publishers/unity/sdk-reference/user-attributes
The player attributes Encore uses to pick offers, passed when you identify the player or later.
Every field is optional and defaults to null, and an object with no fields set changes nothing. To set the language, call [`SetLanguage()`](/publishers/unity/sdk-reference/set-language). `DateOfBirth` is used on the device to work out `Age`, and the date is never sent.
> [!WARNING]
>
> Only pass what you have a lawful basis to share, such as the player's consent. A player under 18 is still served offers, from age-appropriate inventory only and with no per-user personalization. Encore's servers do this filtering, so your game doesn't filter offers itself. See [Sending an age](/publishers/offers-api/reference/user-attributes#sending-an-age).
## Structure
```csharp theme={null}
public sealed class UserAttributes
{
public string Email;
public string FirstName;
public string LastName;
public string PhoneNumber;
public string PostalCode;
public string City;
public string State;
public string CountryCode; // ISO country code, such as "US"
public string Latitude;
public string Longitude;
public int? Age; // whole years, 0 to 120
public string DateOfBirth; // "YYYY-MM-DD" or an ISO 8601 date-time with a zone; used on the device to work out Age, never sent
public string Gender;
public string SubscriptionTier;
public string MonthsSubscribed;
public string BillingCycle;
public string LastPaymentAmount;
public string LastActiveDate;
public string TotalSessions;
public Dictionary Custom = new Dictionary(); // your own keys
}
```
## Field reference
| Field | Type | Description |
| - | - | - |
| `Email`, `FirstName`, `LastName`, `PhoneNumber` | `string` | The player's contact details |
| `PostalCode`, `City`, `State` | `string` | The player's address |
| `CountryCode` | `string` | ISO 3166-1 alpha-2 country code, such as `US` |
| `Latitude`, `Longitude` | `string` | Decimal degrees, such as `37.7749` |
| `Age` | `int?` | Whole years, 0 to 120. Any other value is dropped with a warning. If you hold only a range, pass its lowest end. A player under 18 is served age-appropriate offers with no per-user personalization. Sent only in the launch you set it (on WebGL, the page load) and not saved, so pass `DateOfBirth`, or set `Age` on every launch |
| `DateOfBirth` | `string` | `YYYY-MM-DD`, or an ISO 8601 date-time with a zone. Anything else is dropped with a warning. Used on the device to work out `Age`, and the date is never sent. With `Age` set too, the lower age is sent |
| `Gender` | `string` | The player's gender. Accepted only from a game rated 18+ in its store listing |
| `SubscriptionTier`, `MonthsSubscribed`, `BillingCycle`, `LastPaymentAmount` | `string` | The player's plan in your game, such as `pro` and `monthly` |
| `LastActiveDate` | `string` | ISO 8601, such as `2026-01-15T10:30:00Z` |
| `TotalSessions` | `string` | How many sessions the player has had |
| `Custom` | `Dictionary` | Your own keys, for attributes no other field covers |
## Example
```csharp theme={null}
Encore.Identify(playerId, new UserAttributes
{
CountryCode = "US",
Age = 29,
Custom = { ["favorite_mode"] = "arcade" },
});
```
Used by [`Identify()`](/publishers/unity/sdk-reference/identify) and [`SetUserAttributes()`](/publishers/unity/sdk-reference/set-user-attributes).
# Reduce Churn
Source: https://docs.encorekit.com/publishers/use-cases/churn-intervention
Recover revenue from users about to walk away: a premium brand offer offsets their subscription cost, funded by the brand.
A churn intervention turns a leaving moment into a save. The user has decided your subscription no longer clears the bar (they declined your paywall, or they're walking through your cancel flow), and instead of letting them go your app presents a **premium brand offer**: a real perk a brand funds to acquire customers. Because the offer offsets the user's subscription cost, and the brand pays for it rather than you, staying subscribed suddenly costs the user less than leaving. This page is the canonical description of the use case; the integration walkthroughs are the SDK quickstarts in [Integration surfaces](#integration-surfaces).
## The paywall decline
The highest-intent moment. The user has seen your paywall, knows your pricing, and is about to leave without purchasing. They've already shown purchase intent by getting this far, so an offer that changes the math feels like a personalized win rather than an interruption. Present it as the last screen between them and the exit, triggered when the user:
* Taps "X" or swipes to dismiss the paywall.
* Taps "Not now" or "Maybe later".
* Navigates back from a pricing screen.
> [!TIP]
>
> This is the recommended starting point for a new integration: get this one moment working, measure, then expand to the cancel flow.
## The cancel flow
The user is an existing subscriber actively trying to cancel. They've already paid before, so the willingness to stay is high if the math changes before the cancellation completes. Trigger the offer when the user:
* Taps a cancel or unsubscribe button in your settings.
* Opens subscription management with cancel intent.
* Is about to be redirected to the store's subscription-management page.
> [!WARNING]
>
> Never block the cancel flow. When the user dismisses the offer, your own fallback path must let the cancellation proceed: branch on `result.claim == null && result.publisher != PublisherOutcome.Purchased` at the call site.
## The mechanic
The save is a premium brand offer, **paid for by the brand, never by you**. A brand funds the perk (a free trial, a discount) as its cost of acquiring a customer; your app supplies the moment and the audience. This use case is SDK-led: your code detects the moment and calls the SDK, Encore renders the offer sheet, and your existing subscription plumbing (native StoreKit or Play Billing, or your subscription manager) completes any subscription purchase the offer leads to. On iOS you can pair the moment with an App Store promotional offer so the save also carries a discounted or free period; see [Create a Promotional Offer](/publishers/ios/platform-setup/create-promotional-offer).
### Nothing to set in the SDK
This use case is the SDK default. A placement that does not name a use case resolves to `churn-intervention`, which is exactly what every Encore integration does today, so existing code is unaffected and no call site needs changing:
```swift theme={null}
// Unchanged. Resolves to the churn-intervention use case.
Encore.shared.placement("cancel_flow").show()
```
If you do name it, note that the symbol you type and the value Encore sends are deliberately unrelated. Every SDK names what the use case does: `.reduceChurn` on iOS, `UseCase.REDUCE_CHURN` on Android, `EncoreUseCase.reduceChurn` on Flutter, `UseCase.reduceChurn` on React Native, `UseCase.ReduceChurn` on Unity, and `'reduceChurn'` on web. The value Encore sends and stores is the hyphenated `churn-intervention`, naming the surface it resolves. Keeping them independent is what stops a rename changing the wire: `churn-intervention` is a frozen label the backend rejects anything else for, and no SDK accepts it as an input. The same split applies to the other use case; see [Reward Users](/publishers/use-cases/post-action-reward).
To override the screen's copy, set the headline and subheadline at the call site and they take priority over the copy Encore resolved for your app. Every SDK exposes them: `.headline()` and `.subheadline()` on the placement builder on iOS, Android, React Native, and Flutter, `.Headline()` and `.Subheadline()` on Unity, and the flat `headline` / `subheadline` placement options on web. Encore translates the copy it resolves into the user's language but never translates a per-call value. The resolution order is the same for both use cases and is spelled out under [where the copy comes from](/publishers/use-cases/post-action-reward#where-the-copy-comes-from). Languages are covered in [Localization](/publishers/concepts/localization).
## The economics
Revenue from this use case lands in the **`paywallUplift`** metric: subscription revenue recovered from users who were about to leave. Two rules govern how it's counted:
* **The lift is measured, never assumed.** Encore compares exposed users against a holdout, so the subscription ARPU lift you see is incremental, not correlation.
* **The value compounds.** A saved subscriber keeps renewing, so each save pays out over the subscriber's remaining lifetime rather than once.
## Integration surfaces
| Surface | When to use it | Start here |
| - | - | - |
| **iOS SDK** (recommended start) | Native Swift apps; the SDK renders the offer and drives StoreKit or your subscription manager | [iOS quickstart](/publishers/ios/quickstart/install) |
| **Android SDK** | Native Kotlin apps; the SDK renders the offer and routes any subscription purchase through your registered purchase controller (RevenueCat, Play Billing, or your own stack) | [Android quickstart](/publishers/android/quickstart/install) |
| **Web SDK** | Web paywalls and cancel flows; a claim is saved, and the user is handed off after your own step | [Reduce Churn at the Paywall guide](/publishers/web/guides/intercept-paywall-abandonment) |
| **Neither: this isn't your use case** | The user just accomplished something (a purchase, a streak, a milestone) and you want to celebrate it, not save it | [Reward Users](/publishers/use-cases/post-action-reward) |
React Native, Flutter, and Unity apps use the bridge SDKs over the same native trees (Unity WebGL builds use the web SDK): start from the [React Native quickstart](/publishers/react-native/quickstart/install), the [Flutter quickstart](/publishers/flutter/quickstart/install), or the [Unity quickstart](/publishers/unity/quickstart/install).
The SDK is the lead surface for this use case: the moments live inside your app's paywall and settings flows, and rendering the offer plus driving the subscription purchase is exactly what the SDK manages for you.
## Related
* [Create a Promotional Offer](/publishers/ios/platform-setup/create-promotional-offer): pair the save with a discounted or free period on iOS.
* [Reduce Churn at the Paywall](/publishers/web/guides/intercept-paywall-abandonment): the Web SDK flow end to end.
* [Integration Patterns](/publishers/ios/guides/integration-patterns): how to wire offer results into your paywall and cancel flows on iOS.
* [Reward Users](/publishers/use-cases/post-action-reward): the other use case, for celebrating a win rather than saving a leaver.
# Reward Users
Source: https://docs.encorekit.com/publishers/use-cases/post-action-reward
Congratulate a user who just completed a purchase, streak, or milestone with a brand-funded reward, at a moment your app already owns.
A post-action reward turns a moment of accomplishment into a gift. The user just did something worth celebrating (finished a purchase, kept a streak alive, hit a level), and your app says congratulations with a **premium brand offer**: a real perk a brand funds to acquire customers, presented as part of your celebration screen, and you earn a bounty on each server-verified activation. This page is the canonical description of the use case; [Integration surfaces](#integration-surfaces) routes you to the walkthrough for the surface you build on.
## The moment
The trigger is an *achievement your app already detects*:
* **A completed purchase**: the checkout success or thank-you screen.
* **A milestone or streak**: the user's seventh consecutive day, a finished course, a cleared level, a savings goal reached.
These moments share three properties that make them ideal reward surfaces: the user is in a positive state, the screen is one your app fully controls, and your own code already fires at exactly the right instant, with no detection machinery needed from Encore.
## The mechanic
The reward is a premium brand offer, **paid for by the brand, never by you**. A brand funds the perk (a free trial, a discount) as its cost of acquiring a customer; your app supplies the moment and the audience. You render the offer as part of your congratulations UI ("You did it, here's something on us"), the user claims it by tapping through, and the brand fulfills it on their side. There is no coupon inventory for you to buy and no reward budget for you to hold.
**One use case, room for more than one screen.** `post-action-reward` names the moment, not the layout. Encore renders the celebration screen suited to the moment, and further layouts, such as one tuned for a purchase thank-you, can be added inside the same use case later. Your call site does not change when that happens: you keep naming the moment, and Encore keeps choosing what to draw.
## The economics
Revenue from this use case lands in the **`brandOfferRevenue`** metric: a **CPA bounty**, paid per verified activation. Two rules govern how it's counted:
* **A claim is not a conversion.** A claim means the user tapped through to the brand. Nothing pays out on a claim.
* **Activation is server-verified.** The bounty is earned only when the brand-side completion is verified on Encore's servers. Your app never attests to a conversion, which is why the economics survive scrutiny.
## Integration surfaces
> [!NOTE]
>
> **There is nothing to turn on.** Your app is granted its use cases when the app is created, so `post-action-reward` is available to every surface below from your first call. If a request resolves as unavailable, there are no eligible offers right now, or the user is in the holdout group of an Encore experiment that shows its holdout group nothing. It never falls back to a paywall screen, because a purchase ask on a "you did it!" moment is exactly what this use case exists to avoid.
| Surface | When to use it | Start here |
| - | - | - |
| **Web SDK** | A web checkout or success page where you want Encore's managed rendering, with the celebration copy set at the call site | [Post-Purchase Placements guide](/publishers/web/guides/post-purchase-placements) |
| **iOS SDK** | Reward a user in-app the moment they finish something worth celebrating, using Encore's managed reward sheet | [Reward Placements guide](/publishers/guides/reward-placements) |
| **Android SDK** | The same managed reward sheet presented from a coroutine or from a callback | [Reward Placements guide](/publishers/guides/reward-placements) |
| **React Native SDK** | The same sheet, selected on the bridge's placement builder | [Reward Placements guide](/publishers/guides/reward-placements) |
| **Flutter SDK** | The same sheet, selected on the plugin's placement builder | [Reward Placements guide](/publishers/guides/reward-placements) |
| **Unity package** | The same sheet in a game, at a moment the player earned | [Reward Placements guide](/publishers/guides/reward-placements) |
| **Neither: this isn't your use case** | The user is about to *leave* (a declined paywall, a cancel flow), not celebrating a win | [Reduce Churn](/publishers/use-cases/churn-intervention) |
Every surface in the preceding table hands rendering to Encore, native SDKs and Web SDK alike: you tell it the moment happened and it presents the celebration screen, so there is no UI for you to build or maintain. Handing over the rendering doesn't mean handing over the words: every SDK, web and native alike, lets you set the headline and subheadline at the call site, so the sheet can name the moment that triggered it. [Where the copy comes from](#where-the-copy-comes-from) has the resolution order.
## Where the copy comes from
**Presentation time is where you set the copy.** You supply the finished string for one presentation, on every SDK and on both use cases. On the native and bridge SDKs that is `.headline()` and `.subheadline()` on the placement builder:
```typescript theme={null}
await Encore.placement('milestone_reached')
.useCase(UseCase.rewardUsers)
.headline('Nice work, Sam!')
.subheadline('That is your fifth week running')
.show();
```
On the **Web SDK** the same two slots are flat placement options rather than builder methods:
```javascript theme={null}
await Encore.placement('milestone_reached', {
useCase: 'rewardUsers',
headline: 'Nice work, Sam!',
subheadline: 'That is your fifth week running',
}).show();
```
> [!NOTE]
>
> The flat web options require the current **`@encorekit/web-sdk` 2.x** release; upgrading an existing integration: [Updating to 2.x](/publishers/web/guides/updating-to-2-x).
Beneath that override the sheet falls back to copy Encore resolves for your app, and beneath that to the copy shipped with the screen. Three sources, strict priority order, first one set wins, and each field resolves on its own, so setting only the headline leaves the subheadline to fall through:
| Priority | Source | Set where |
| - | - | - |
| 1 | Per-call override | Set at the call site on every SDK: the `headline` / `subheadline` placement options on web, and `.headline()` / `.subheadline()` on the placement builder on iOS, Android, React Native, and Flutter (`.Headline()` / `.Subheadline()` on Unity) |
| 2 | Encore-resolved copy | The copy Encore has configured for this use case on your app, translated into the user's language |
| 3 | Encore's default | Shipped with the screen |
You pass the finished string, so the wording, the tone, the pluralization, and any emoji are yours to decide. Encore never translates it, so an English override shows English to every user. See [Localization](/publishers/concepts/localization). 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 string falls *through* to the next source rather than clearing the line, so it is never a way to render a headless sheet. That is deliberate: it keeps a `` `Nice work, ${name}!` `` template from collapsing into a blank heading when `name` comes back empty. To deliberately show less, omit the override rather than passing `''`.
Leave both unset and Encore's shipped default renders: headline `Congrats! We got a *gift* for you both to celebrate your 30-days streak!`, subheadline `Choose one of our partner offers below`. Both render even unconfigured, so don't assume an unconfigured app shows nothing. The default is streak-shaped even though this use case also covers purchases, milestones, and levels, which is one good reason to set your own.
> [!WARNING]
>
> **Watch for accent markup in copy you didn't write, especially on web.** The shipped default uses the SDKs' inline accent syntax (asterisks around the run to emphasize, as in `*gift*`), and support for it is uneven right now:
>
> | Surface | Renders `*gift*` as an accent run? |
> | - | - |
> | iOS | From 1.5.0, which hasn't shipped yet |
> | Android | Not yet; its equivalent hasn't shipped |
> | Web SDK | From 2.4.0, in a [served variant](/publishers/web/concepts/sheet-variants) that styles its headline accent. The built-in web sheets render plain text, so there the asterisks stay literal |
>
> Until that evens out, a surface that doesn't support the syntax shows the asterisks on screen. Passing your own headline and subheadline sidesteps the question everywhere, since you control every character that reaches the sheet. On web the built-in sheet has no accent-run rendering to wait for, so there your own copy is the fix rather than a stopgap.
> [!WARNING]
>
> **A per-call override outranks the copy Encore resolved for your app.** If a screen shows something other than the copy configured for the app, check whether the call site sets a headline or subheadline. The per-call value wins every time. That is deliberate, so a single placement can speak to the moment that triggered it, but it does mean a stray override at one call site keeps winning after the app's configured copy changes.
## Related
* [Post-Purchase Placements](/publishers/web/guides/post-purchase-placements): the Web SDK surface for purchase moments.
* [Reward Placements](/publishers/guides/reward-placements): the iOS, Android, React Native, Flutter, and Unity walkthrough for this use case.
* What a claim resolves to, field by field: [iOS](/publishers/ios/sdk-reference/presentation-result#claimedoffer), [Android](/publishers/android/sdk-reference/presentation-result), [React Native](/publishers/react-native/sdk-reference/presentation-result#claimedoffer), [Flutter](/publishers/flutter/sdk-reference/presentation-result#encoreclaimedoffer), and [Unity](/publishers/unity/sdk-reference/presentation-result).
* [Receive Completion Events](/publishers/offers-api/guides/receive-completion-events): the webhook that reports the verified activation a claim can turn into, joined on `transactionId`.
# The Claim Flow
Source: https://docs.encorekit.com/publishers/web/concepts/claim-flow
When the advertiser opens after a Web SDK claim, by use case, and what the claimed result carries.
Presenting an offer is one call. When the user taps **Claim**, the use case decides when
the advertiser opens:
| `useCase` | On **Claim** | [`show()`](/publishers/web/sdk-reference/show) resolves `claimed` | The advertiser opens |
| - | - | - | - |
| `'rewardUsers'` | The SDK opens the advertiser in a new tab, inside the tap. | When the sheet closes | At the claim |
| `'reduceChurn'` (default) | The SDK saves the claim and shows its primer, a screen that leads into your own offer. | When the user taps the primer's button or closes it | When your site calls [`redeem()`](/publishers/web/sdk-reference/redeem) and the user taps the redemption screen's button |
A `'rewardUsers'` claim goes straight through, because the user already did the thing you
reward. A `'reduceChurn'` claim waits so the user can finish your own step first,
such as starting a trial or completing a cancel, before Encore sends them to the advertiser.
On `'reduceChurn'`, [optimistic mode](/publishers/web/sdk-reference/configure#unlock-mode)'s
provisional grant lands at `redeem()`, not at the claim.
## Redeem a saved `'reduceChurn'` claim
```javascript theme={null}
const result = await Encore.placement('cancel_flow').show();
if (result.status === 'claimed') {
// Saved, not handed off yet. Keep result.transactionId.
await runYourOwnStep();
// Shows the SDK's redemption screen; its button opens the advertiser.
await Encore.placement('cancel_flow').redeem();
}
```
`redeem()` can also run on a later page, and
[`getPendingTransaction()`](/publishers/web/sdk-reference/redeem#getpendingtransaction)
returns the saved claim without showing anything. How long it lasts and where it is stored:
[`redeem()` gotchas](/publishers/web/sdk-reference/redeem#gotchas).
> [!NOTE]
>
> Requires the current **`@encorekit/web-sdk` 2.x** release. Upgrading an existing integration:
> [Updating to 2.x](/publishers/web/guides/updating-to-2-x).
## What a claimed result carries
```typescript theme={null}
{
status: 'claimed';
offerId: string;
campaignId: string;
advertiserName: string;
transactionId?: string;
}
```
| Field | What it is |
| - | - |
| `offerId` / `campaignId` | Identify what was claimed. On web these are distinct values and both are reported. |
| `advertiserName` | The merchant's display name, for a confirmation message you render yourself. |
| `transactionId` | The claim's durable handle: the id Encore keys on. It is how a completion that lands days later is traced back to this user and app. |
The payload mirrors the iOS and Android `ClaimedOffer` field for field, so a
cross-platform integration reads one shape everywhere.
> [!WARNING]
>
> **`transactionId` is optional, and that is deliberate.** The transaction write can fail
> while the claim itself genuinely happened. When that occurs the SDK logs a warning naming
> the attribution consequence rather than fabricating a placeholder id, and the result still
> resolves `claimed`: a failed write must never retroactively turn a real claim into a
> decline. Persist `transactionId` when it is present, and treat its absence as a claim you
> cannot later join on, not as a failure.
## Use cases
The [`useCase`](/publishers/web/sdk-reference/placement) option names the use case, which
decides the sheet, and it defaults to `'reduceChurn'`. The sheet is the served variant for that use case, or the
SDK's built-in sheet for it; see [Sheet Variants](/publishers/web/concepts/sheet-variants#which-sheet-draws).
A use case with nothing to present is not an error. `show()` resolves
`{ status: 'unavailable' }`, the same result no eligible offers produce, and it never falls
back to another use case's offers or copy.
> [!NOTE]
>
> These symbols match the native SDKs verbatim (iOS `.reduceChurn` / `.rewardUsers`, Android
> `REDUCE_CHURN` / `REWARD_USERS`), so a cross-platform integration reads one vocabulary. The
> values Encore sends and stores are separate frozen labels, which is what keeps a rename from
> ever changing the wire. You never type a wire value: passing one is rejected as an
> unrecognized use case.
## Where the sheet's copy comes from
`headline` and `subheadline` on the
[placement options](/publishers/web/sdk-reference/placement) set the copy for one
presentation, ahead of the copy Encore resolved for your app. The full resolution order,
and how blank values behave, are on
[Where the copy comes from](/publishers/use-cases/post-action-reward#where-the-copy-comes-from).
## Identify before you present
Call [`identify()`](/publishers/web/sdk-reference/identify) with your stable user id before
presenting, so the claim binds to an account id that survives reloads, navigations, and
device switches. Exposures recorded before `identify()` are keyed to the auto-generated
anonymous id and are not retro-linked, so a late identify leaves them unattributed. See
[Configure Analytics](/publishers/web/quickstart/configure-analytics).
## A claim is not a conversion
`claimed` reports a **presentation fact**: the user tapped Claim. Nothing has been earned or
verified at that moment.
Advertiser completion happens later, is asynchronous, and is server-authoritative. Verify
real access from your backend through Encore's HMAC-authenticated server-side entitlements
API, by user, never from this result and never from the client.
## Gotchas
* **Your confirmation is yours to render.** Apart from the primer, the redemption screen, and
a served variant's post-claim screen, the SDK shows nothing after a claim. Render your own
moment when the result is `claimed`.
* **A post-claim screen keeps the sheet up.** `claimed` arrives when the user closes it, and
a second `show()` before then resolves `dismissed` with the reason
[`'alreadyPresenting'`](/publishers/web/sdk-reference/show#showresult).
* **`unavailable` is overloaded on purpose.** It means no eligible offers, a measurement
control cohort, or nothing to present for the requested use case, and the SDK keeps them
indistinguishable so incrementality experiments aren't contaminated. Show your normal
fallback; don't branch on a suspected control assignment.
* **You don't need a click handler for `show()` or `redeem()`.** Every advertiser tab opens
inside a tap on a button in the SDK's own sheet (Claim, or the redemption screen's
button). Present offers and call `redeem()` from whatever moment makes sense in your app.
* **`reset()` drops a saved claim.** It clears local SDK state, including a claim waiting
for `redeem()`, and generates a fresh anonymous id. It revokes nothing: claims already
recorded belong to the user id they were made under.
## Related
* [`show()`](/publishers/web/sdk-reference/show): the full `ShowResult` contract.
* [`redeem()`](/publishers/web/sdk-reference/redeem): the `RedeemResult` contract and `getPendingTransaction()`.
* [Sheet Variants](/publishers/web/concepts/sheet-variants): which sheet draws, and which appearance options it reads.
* [`placement()`](/publishers/web/sdk-reference/placement): the `PlacementOptions` contract, including `headline` and `subheadline`.
* [Updating to 2.x](/publishers/web/guides/updating-to-2-x): moving a 1.x integration onto 2.x.
* [Reduce Churn at the Paywall](/publishers/web/guides/intercept-paywall-abandonment) · [Post-Purchase Placements](/publishers/web/guides/post-purchase-placements): the two use cases end to end.
# Sheet Variants
Source: https://docs.encorekit.com/publishers/web/concepts/sheet-variants
Which sheet a Web SDK placement draws when Encore serves a variant, and which of your appearance and copy options it honors.
> [!NOTE]
>
> New in `2.4.0`.
The sheet a placement presents can be a variant Encore serves for your app (the served
variant), so Encore can change the sheet or test variants against each other without a
release of your site. When Encore serves no variant, or the served one can't run on the web,
the SDK draws its built-in sheet instead.
## When to use this
* An `appearance` option has no visible effect on the sheet.
* You need to know when the sheet turns dark, or how it fits a phone and a desktop.
* Your `headline` or `subheadline` doesn't appear, or the sheet isn't the one you expected.
For the claim result and when it arrives, see
[The Claim Flow](/publishers/web/concepts/claim-flow).
## Which sheet draws
| What Encore serves for the use case | What draws |
| - | - |
| A variant that runs on the web | That variant |
| A reward variant Encore maps to one of the SDK's own reward screens | That screen, a built-in sheet |
| A variant this SDK can't read, or one that needs an in-app purchase or a lead form | The built-in sheet for the use case |
| No variant | The built-in sheet for the use case |
The built-in sheet for each [`useCase`](/publishers/web/sdk-reference/placement#field-reference):
| `useCase` | Built-in sheet |
| - | - |
| `'reduceChurn'` (default) | The offer carousel: a save attempt at a moment the user is leaving. |
| `'rewardUsers'` | Its own headline chrome around a paged carousel, for a moment the user just accomplished something. Claim-only, with no purchase ask anywhere in it. |
## Your appearance options
A served variant brings its own layout and colors, and reads four of your
[`appearance`](/publishers/web/guides/advanced-ui) options. Three of them apply wherever the
variant uses the matching theme color, and a color the variant fixes for itself stays as
designed.
```javascript theme={null}
const result = await Encore.placement('cancel_flow', {
appearance: {
accentColor: '#6743F5',
backgroundColor: '#101014',
},
}).show();
```
The full `appearance` contract: [Advanced UI](/publishers/web/guides/advanced-ui#the-two-tiers).
| Option | What it moves on a served variant |
| - | - |
| `accentColor` | The variant's accent color. |
| `backgroundColor` | The variant's canvas. A `#`-prefixed 3- or 6-digit hex value (such as `#101014`) also re-derives the surfaces, borders, and text from it. |
| `textColor` | The variant's text. |
| `modalBackgroundColor` | The sheet's frame, behind the variant, in place of the variant's own frame color. |
The [reward sheet overrides](/publishers/web/guides/advanced-ui#the-two-tiers) in
`appearance` (the slot fields and the dot colors) and the
[`statusIcon`](/publishers/web/sdk-reference/placement#field-reference) option style the
built-in sheets only, never a served variant.
## Your copy options
The `headline` and `subheadline` options on
[`placement()`](/publishers/web/sdk-reference/placement#field-reference) apply to the built-in
sheets, and to a served variant wherever it shows your headline. A variant with fixed copy
keeps it.
## Dark mode
A served variant renders in light, dark, or automatic appearance, following the appearance
mode Encore sets for your app. To change it for a web app, contact Encore.
| Appearance mode | The sheet |
| - | - |
| Light | Light on every page. |
| Dark | Dark on every page. |
| Automatic (the default) | Dark only when your page declares dark support and the device prefers dark. |
The SDK picks light or dark when the sheet opens, and an open sheet keeps it. A hex
`backgroundColor` sets the palette in either mode.
A page declares dark support with a `color-scheme` that includes `dark`, set in a meta tag or
in CSS on the root or `body` element:
```html theme={null}
```
A page that declares none keeps the light sheet, so a light-only site never shows a dark one
by surprise. The built-in sheets stay light.
## Screen size
* **Narrower than 768px:** a full-screen variant fills the screen. A variant made for part of
the screen opens as a bottom sheet. The user can drag it between its heights, or down to
close it, the same as the close button.
* **768px wide or wider:** a full-screen variant draws in a square of up to 720px, smaller in
a short or narrow window, on a backdrop in the variant's canvas color, not a dimmed page.
A variant made for part of the screen keeps the square's width and takes
the height of its content, and keeps the square when its content doesn't fit.
## Related
* [`placement()`](/publishers/web/sdk-reference/placement): the options a presentation takes.
* [Advanced UI](/publishers/web/guides/advanced-ui): the full `appearance` contract.
* [The Claim Flow](/publishers/web/concepts/claim-flow): what happens when the user claims.
# Angular
Source: https://docs.encorekit.com/publishers/web/frameworks/angular
Integrate the Encore Web SDK in an Angular app: a root-provided service that wraps configure()/identify()/show(), initialized once at startup.
The SDK is framework-agnostic; in Angular, wrap it in a root-provided service so
configuration happens once and components stay free of SDK plumbing.
## Install
```bash theme={null}
npm install @encorekit/web-sdk
```
## A root-provided service
```typescript theme={null}
// encore.service.ts
import { Injectable } from '@angular/core';
import Encore, { type PlacementOptions } from '@encorekit/web-sdk';
import { environment } from '../environments/environment';
@Injectable({ providedIn: 'root' })
export class EncoreService {
constructor() {
Encore.configure({ apiKey: environment.encoreApiKey });
}
identify(userId: string): void {
Encore.identify(userId); // replaces the auto-generated anonymous UUID
}
show(placementId: string, options?: PlacementOptions) {
return Encore.placement(placementId, options).show(); // never rejects; branch on result.status
}
}
```
Full configuration options: [`configure()`](/publishers/web/sdk-reference/configure).
## Present offers from a component
```typescript theme={null}
export class FinishLessonComponent {
constructor(private encore: EncoreService) {}
// saveLessonProgress(), persistClaim() and goToNextLesson() are your own methods.
async onFinishClicked() {
await this.saveLessonProgress();
const result = await this.encore.show('milestone_reached', { useCase: 'rewardUsers' });
if (result.status === 'claimed') {
// The SDK has opened the advertiser. transactionId is absent if its write failed.
if (result.transactionId) await this.persistClaim(result.transactionId);
}
this.goToNextLesson(); // whatever the result, continue your flow
}
}
```
Contracts: [`placement()`](/publishers/web/sdk-reference/placement) ·
[`show()`](/publishers/web/sdk-reference/show).
Pass `useCase: 'rewardUsers'` on a reward placement. Without it the placement is a
`'reduceChurn'` one, the default, whose claim waits for
[`redeem()`](/publishers/web/sdk-reference/redeem).
## Next steps
* [Post-Purchase Placements](/publishers/web/guides/post-purchase-placements): per-call headline and subheadline copy for a reward moment
* [The Claim Flow](/publishers/web/concepts/claim-flow): what happens when a user claims an offer
* [`show()`](/publishers/web/sdk-reference/show): the full `ShowResult` contract
* [Reduce Churn at the Paywall](/publishers/web/guides/intercept-paywall-abandonment): the other use case, whose claim waits for [`redeem()`](/publishers/web/sdk-reference/redeem)
# React
Source: https://docs.encorekit.com/publishers/web/frameworks/react
Integrate the Encore Web SDK in a React app with EncoreProvider and useEncore().
The SDK ships a React entry point, `@encorekit/web-sdk/react`, with an `EncoreProvider`
that calls [`configure()`](/publishers/web/sdk-reference/configure) exactly once (StrictMode-safe)
and a `useEncore()` hook that returns the SDK instance.
## Install
```bash theme={null}
npm install @encorekit/web-sdk
```
## Configure at the root
```tsx theme={null}
// main.tsx
import ReactDOM from 'react-dom/client';
import { EncoreProvider } from '@encorekit/web-sdk/react';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render(
);
```
The provider takes the same props as [`EncoreConfig`](/publishers/web/sdk-reference/configure)
(`apiKey`, `logLevel`, …).
## Identify and present offers
```tsx theme={null}
import { useEncore } from '@encorekit/web-sdk/react';
function FinishLessonButton() {
const Encore = useEncore();
const onFinish = async () => {
await saveLessonProgress();
Encore.identify(currentUser.id); // once you know the real user (see identify())
const result = await Encore.placement('milestone_reached', {
useCase: 'rewardUsers',
}).show(); // never rejects
if (result.status === 'claimed') {
// The SDK has opened the advertiser. transactionId is absent if its write failed.
if (result.transactionId) await persistClaim(result.transactionId);
}
goToNextLesson(); // whatever the result, continue your flow
};
return ;
}
```
Contracts: [`placement()`](/publishers/web/sdk-reference/placement) ·
[`show()`](/publishers/web/sdk-reference/show).
Pass `useCase: 'rewardUsers'` on a reward placement. Without it the placement is a
`'reduceChurn'` one, the default, whose claim waits for
[`redeem()`](/publishers/web/sdk-reference/redeem).
## Next steps
* [Post-Purchase Placements](/publishers/web/guides/post-purchase-placements): per-call headline and subheadline copy for a reward moment
* [The Claim Flow](/publishers/web/concepts/claim-flow): what happens when a user claims an offer
* [`show()`](/publishers/web/sdk-reference/show): the full `ShowResult` contract
* [Reduce Churn at the Paywall](/publishers/web/guides/intercept-paywall-abandonment): the other use case, whose claim waits for [`redeem()`](/publishers/web/sdk-reference/redeem)
# Svelte
Source: https://docs.encorekit.com/publishers/web/frameworks/svelte
Integrate the Encore Web SDK in a Svelte app: configure() in the root component's onMount, identify() on login, show() from event handlers.
The SDK is framework-agnostic; in Svelte you call it directly. Configure once in the root
component's `onMount`, then present offers from event handlers.
## Install
```bash theme={null}
npm install @encorekit/web-sdk
```
## Configure on mount
```svelte theme={null}
```
`configure()` honors only its first successful call; full options are in the
[`configure()` reference](/publishers/web/sdk-reference/configure).
## Identify and present offers
```svelte theme={null}
```
Contracts: [`placement()`](/publishers/web/sdk-reference/placement) ·
[`show()`](/publishers/web/sdk-reference/show).
Pass `useCase: 'rewardUsers'` on a reward placement. Without it the placement is a
`'reduceChurn'` one, the default, whose claim waits for
[`redeem()`](/publishers/web/sdk-reference/redeem).
## Next steps
* [Post-Purchase Placements](/publishers/web/guides/post-purchase-placements): per-call headline and subheadline copy for a reward moment
* [The Claim Flow](/publishers/web/concepts/claim-flow): what happens when a user claims an offer
* [`show()`](/publishers/web/sdk-reference/show): the full `ShowResult` contract
* [Reduce Churn at the Paywall](/publishers/web/guides/intercept-paywall-abandonment): the other use case, whose claim waits for [`redeem()`](/publishers/web/sdk-reference/redeem)
# Vanilla JavaScript
Source: https://docs.encorekit.com/publishers/web/frameworks/vanilla-js
Integrate the Encore Web SDK without a build system: load the UMD bundle via a script tag (global Encore, unwrap with Encore.default), then configure()/identify()/show().
For pages without a bundler, load the UMD build via a script tag. The bundle exposes a
global `Encore`; the SDK instance lives on `.default`, so unwrap it once.
## Load the script
Self-host `dist/umd/encore.min.js` from the npm package with your own assets (see
[Install](/publishers/web/quickstart/install) for the hosted-CDN note):
```html theme={null}
```
## Configure, identify, show
```html theme={null}
```
Full configuration options: [`configure()`](/publishers/web/sdk-reference/configure).
Contracts: [`placement()`](/publishers/web/sdk-reference/placement) ·
[`show()`](/publishers/web/sdk-reference/show).
Pass `useCase: 'rewardUsers'` on a reward placement. Without it the placement is a
`'reduceChurn'` one, the default, whose claim waits for
[`redeem()`](/publishers/web/sdk-reference/redeem).
## Next steps
* [Post-Purchase Placements](/publishers/web/guides/post-purchase-placements): per-call headline and subheadline copy for a reward moment
* [The Claim Flow](/publishers/web/concepts/claim-flow): what happens when a user claims an offer
* [`show()`](/publishers/web/sdk-reference/show): the full `ShowResult` contract
* [Reduce Churn at the Paywall](/publishers/web/guides/intercept-paywall-abandonment): the other use case, whose claim waits for [`redeem()`](/publishers/web/sdk-reference/redeem)
# Vue
Source: https://docs.encorekit.com/publishers/web/frameworks/vue
Integrate the Encore Web SDK in a Vue 3 app: configure() in the root component's onMounted, identify() on login, show() from event handlers.
The SDK is framework-agnostic; in Vue you call it directly. Configure once when the root
component mounts, then present offers from event handlers.
## Install
```bash theme={null}
npm install @encorekit/web-sdk
```
## Configure on mount
```vue theme={null}
```
`configure()` honors only its first successful call; full options are in the
[`configure()` reference](/publishers/web/sdk-reference/configure).
## Identify and present offers
```vue theme={null}
```
Contracts: [`placement()`](/publishers/web/sdk-reference/placement) ·
[`show()`](/publishers/web/sdk-reference/show).
Pass `useCase: 'rewardUsers'` on a reward placement. Without it the placement is a
`'reduceChurn'` one, the default, whose claim waits for
[`redeem()`](/publishers/web/sdk-reference/redeem).
## Next steps
* [Post-Purchase Placements](/publishers/web/guides/post-purchase-placements): per-call headline and subheadline copy for a reward moment
* [The Claim Flow](/publishers/web/concepts/claim-flow): what happens when a user claims an offer
* [`show()`](/publishers/web/sdk-reference/show): the full `ShowResult` contract
* [Reduce Churn at the Paywall](/publishers/web/guides/intercept-paywall-abandonment): the other use case, whose claim waits for [`redeem()`](/publishers/web/sdk-reference/redeem)
# Advanced UI
Source: https://docs.encorekit.com/publishers/web/guides/advanced-ui
Restyle the offer sheet with theme colors, or replace the reward sheet's headline and buttons with your own elements: the full appearance contract on PlacementOptions.
The sheet ships styled, responsive, and accessible, and most integrations never change it.
Reach for `appearance` when the sheet has to sit inside your brand: your palette on the
surfaces, your typography on the headline, or your own element where the SDK's button was.
Every field is optional, and **omitting `appearance` entirely renders exactly the default
sheet**. Nothing on this page is required for a working integration.
`appearance` is a per-presentation option on
[`PlacementOptions`](/publishers/web/sdk-reference/placement#placementoptions):
```javascript theme={null}
import Encore from '@encorekit/web-sdk';
const result = await Encore.placement('milestone_reached', {
useCase: 'rewardUsers',
appearance: { accentColor: '#0A6' },
}).show();
```
## The two tiers
The config has two tiers, and they compose.
**Theme colors** set the SDK's CSS custom properties, so one value repaints everything
derived from it: muted text, secondary surfaces, focus rings.
| Field | What it moves |
| - | - |
| `backgroundColor` | The sheet's canvas, and every surface derived from it. |
| `textColor` | The primary ink, from which muted and secondary text are derived. |
| `accentColor` | Focus rings, links, and the Reduce Churn CTA. |
| `modalBackgroundColor` | The modal container only. Narrower than `backgroundColor`: use it to repaint the sheet and nothing else. |
**Reward sheet overrides** replace or restyle one element each. They are read by the
built-in `'rewardUsers'` sheet, the one with a headline block, a CTA pair, and page dots.
The built-in `'reduceChurn'` carousel honors the theme colors and
`modalBackgroundColor` only. For a served variant, see
[Sheet Variants](/publishers/web/concepts/sheet-variants#your-appearance-options).
| Field | Kind | What it fills |
| - | - | - |
| `headline` | slot | The reward sheet's primary heading. |
| `subheadline` | slot | The line under it. |
| `claimButton` | slot | The "Claim gift" CTA. The SDK keeps the action. |
| `declineButton` | slot | The "No thanks" button. The SDK keeps the action. |
| `dotColor` | color | The page indicator's inactive dots. |
| `dotActiveColor` | color | The page indicator's active dot. |
## The three slot forms
Each slot (`headline`, `subheadline`, `claimButton`, `declineButton`) takes one of three
forms. Pick the cheapest one that does the job.
```typescript theme={null}
type TextSlot = TextAppearance | HTMLElement | AppearanceRenderer;
type ButtonSlot = ButtonAppearance | HTMLElement | AppearanceRenderer;
type AppearanceRenderer = (context: AppearanceSlotContext) => HTMLElement | null | undefined;
```
All of these are exported from `@encorekit/web-sdk`, so a TypeScript integration can type
against them directly.
### A styled config object
The most common case: custom copy, font, and color, with no DOM knowledge required. The
SDK keeps its own element, and with it every default style and accessibility attribute, and
applies your values on top.
```javascript theme={null}
import Encore from '@encorekit/web-sdk';
await Encore.placement('milestone_reached', {
useCase: 'rewardUsers',
appearance: {
modalBackgroundColor: '#101014',
dotColor: '#3A3A44',
dotActiveColor: '#FFD166',
headline: {
text: 'Nice work, Sam!',
color: '#FFD166',
fontFamily: '"Helvetica Neue", Arial, sans-serif',
fontSize: '28px',
fontWeight: 700,
},
claimButton: {
backgroundColor: '#FFD166',
color: '#101014',
borderRadius: '999px',
},
},
}).show();
```
Text slots accept `text`, `color`, `fontFamily`, `fontSize`, `fontWeight`,
`letterSpacing`, and `textAlign`. Button slots accept the same fields plus
`backgroundColor`, `borderColor`, and `borderRadius`. A `text` value that is blank or
whitespace-only falls **through** to the copy Encore resolved rather than blanking the
slot, the same rule `PlacementOptions.headline` follows; a non-blank `text` beats it.
### A ready element
Hand the slot an `HTMLElement` to render something that is not text at all. The SDK mounts
your element inside its own semantic element, which keeps the heading's id and the
sheet's accessible name intact.
```javascript theme={null}
import Encore from '@encorekit/web-sdk';
const badge = document.createElement('div');
badge.className = 'streak-badge';
badge.append('🔥 5-week streak');
await Encore.placement('milestone_reached', {
useCase: 'rewardUsers',
appearance: { subheadline: badge },
}).show();
```
Build a fresh element per slot and per presentation. One element can fill only one slot:
supplying the same element twice keeps the SDK's default for the second one.
### A renderer
A `(context) => HTMLElement` function runs per presentation with the SDK's context in
hand:
| Context field | What it carries |
| - | - |
| `text` | The copy the SDK resolved for this slot, after its full fallback chain. |
| `useCase` | Why the sheet is presenting. |
| `defaultElement` | The element the SDK would have rendered. |
Return an element to replace the default, return `defaultElement` (mutated) to decorate
it, or return `null` to keep the default as is.
```javascript theme={null}
import Encore from '@encorekit/web-sdk';
await Encore.placement('milestone_reached', {
useCase: 'rewardUsers',
appearance: {
// Replace: build your own CTA around the copy the SDK resolved.
claimButton: ({ text }) => {
const el = document.createElement('span');
el.className = 'my-cta';
el.textContent = text;
return el;
},
// Decorate: keep the SDK's element, styles, and accessibility wiring.
declineButton: ({ defaultElement }) => {
defaultElement.classList.add('my-ghost-button');
return defaultElement;
},
},
}).show();
```
## What you can rely on
* **Omitting `appearance` changes nothing.** The sheet renders exactly what it rendered
before this config existed, byte for byte.
* **The SDK keeps the action.** On `claimButton` and `declineButton` you supply appearance
only. Your element is mounted inside an SDK-owned control that carries the role, the tab
stop, and the listener; the listener runs in the capture phase, so the SDK's
claim or decline behavior runs first and a handler you attached to your own element does
not run at all. React to the outcome through `show()`'s resolved
[`ShowResult`](/publishers/web/sdk-reference/show), never through your own click
handlers.
* **The SDK also keeps the gate.** Because the claim is the SDK's, so is whether it is
available: turning
[`Encore.isClaimEnabled`](/publishers/web/sdk-reference/is-claim-enabled) off makes your
claim button unavailable along with everything else. Your element's host carries
`aria-disabled="true"` rather than the native `disabled` attribute, which means nothing
outside a `