Rovenue SDKBeta
Guides

Processing Purchases

Use the SDK to fetch offerings and drive the purchase flow end-to-end.

The SDK drives the full purchase lifecycle — fetching products from the store, presenting them, triggering StoreKit 2 (iOS) or Play Billing 6 (Android), and validating the receipt server-side — all in a single purchase(pkg) call. Your app only decides which package to present.

To let the dashboard decide which offering a subscriber sees at a given location — per audience, with A/B tests — see Placements.

Rovenue handles receipt validation server-side before resolving the purchase promise. Your app receives verified entitlements and updated virtual-currency balances in the result — no additional polling or webhook listener is needed on the client. See Methods — Purchases.

Types on this page

type Offerings = {
  current: Offering | null;           // default offering; null if none configured
  all: Record<string, Offering>;      // all offerings by identifier
};

type Offering = {
  identifier: string;    // e.g. "default" or "annual_promo"
  isDefault: boolean;    // true for the offering marked default in the dashboard
  packages: Package[];   // ordered list of packages in this offering
};

type Package = {
  identifier: string;    // e.g. "$rc_monthly", "$rc_annual"
  product: StoreProduct; // localised product from the store
};

type StoreProduct = {
  id: string;                      // store product ID
  type: ProductType;               // "subscription" | "consumable" | "non_consumable" | "non_renewing_subscription"
  displayName: string;             // localised product name
  priceString: string | null;      // localised price string, e.g. "$4.99"
  price: number | null;            // raw price in the account currency
  currencyCode: string | null;     // ISO 4217 currency code, e.g. "USD"
};

type ProductType = 'subscription' | 'consumable' | 'non_consumable' | 'non_renewing_subscription';

type PurchaseResult = {
  entitlements: Entitlement[];              // entitlements after the purchase; for a verification deferral, temporary ones included
  virtualCurrencies: Record<string, number>; // updated virtual-currency balances (code → amount)
  productId: string;                        // store product ID that was purchased
  storeTransactionId: string;               // store-issued transaction identifier; empty for a storeApproval deferral
  isDeferred: boolean;                      // true when nothing could be granted yet — not an error
  pendingReason?: 'storeApproval' | 'verification' | null; // why: Ask-to-Buy, or paid but server verification pending (SDK retries)
};
TypeKey fieldsDescription
Offeringscurrent, allContainer returned by getOfferings().
Offeringidentifier, packagesA named group of packages configured in the dashboard.
Packageidentifier, productA purchasable unit wrapping a StoreProduct.
StoreProducttype, priceString, priceLive pricing data from the store; localised automatically.
PurchaseResultentitlements, virtualCurrencies, isDeferredReturned after server-validated purchase.

See Types for the full Entitlement shape included in PurchaseResult.


Purchase flow

Fetch offerings

Offerings are configured in the Rovenue dashboard and cached locally after the first fetch. Fetch them at app launch or when your paywall opens so pricing is always available instantly.

import { Rovenue } from '@rovenue/react-native-sdk';

const offerings = await Rovenue.getOfferings();
// offerings.current — the default Offering (or null if none configured)
// offerings.all     — Record<string, Offering> for all named offerings
let offerings = try await Rovenue.shared.getOfferings()
// offerings.current — the default Offering? 
// offerings.all     — [String: Offering]
val offerings = Rovenue.shared.getOfferings()
// offerings.current — the default Offering?
// offerings.all     — Map<String, Offering>

Present packages to the user

Iterate over offering.packages to build your paywall UI. Each Package exposes a StoreProduct with localised pricing directly from the store — use priceString for display and price for analytics.

import { Rovenue } from '@rovenue/react-native-sdk';

const offerings = await Rovenue.getOfferings();
const packages = offerings.current?.packages ?? [];

function Paywall() {
  return (
    <View>
      {packages.map((pkg) => (
        <TouchableOpacity key={pkg.identifier} onPress={() => handlePurchase(pkg)}>
          <Text>{pkg.product.displayName}</Text>
          <Text>{pkg.product.priceString}</Text>
        </TouchableOpacity>
      ))}
    </View>
  );
}
let offerings = try await Rovenue.shared.getOfferings()
let packages = offerings.current?.packages ?? []

for pkg in packages {
  print("\(pkg.product.displayName) — \(pkg.product.priceString ?? "?")")
}
val offerings = Rovenue.shared.getOfferings()
val packages = offerings.current?.packages ?: emptyList()

for (pkg in packages) {
  println("${pkg.product.displayName} — ${pkg.product.priceString}")
}

priceString and price are fetched live from the store at runtime, so they reflect the user's locale and currency without any extra work on your part.

Call purchase(pkg) on selection

Pass the chosen Package to Rovenue.purchase(). The SDK presents the native store sheet (StoreKit 2 on iOS, Play Billing on Android), waits for the transaction to complete, and validates the receipt server-side before resolving. The resolved PurchaseResult carries verified entitlements and updated virtual-currency balances — no additional polling needed.

Rovenue decides server-side — based on your product configuration in the dashboard — whether a purchase grants an entitlement (subscriptions, one-time unlocks) or adds credits (consumables). Both product types go through the same purchase(pkg) call.

import { Rovenue, RovenueError } from '@rovenue/react-native-sdk';

async function handlePurchase(pkg) {
  try {
    const result = await Rovenue.purchase(pkg);

    if (result.isDeferred) {
      // Not an error. pendingReason 'storeApproval' = Ask-to-Buy;
      // 'verification' = paid, the SDK is still verifying it with the
      // server. Wait for 'ENTITLEMENTS_CHANGED' via addChangeListener.
      showPendingMessage();
      return;
    }

    // result.entitlements — verified, up-to-date array
    // result.virtualCurrencies — updated balances (for currency-pack products)
    console.log('Purchase succeeded:', result.productId);
    console.log('Transaction ID:', result.storeTransactionId);

    navigateToSuccess();
  } catch (e) {
    if (!(e instanceof RovenueError)) throw e; // not an SDK error — re-throw
    switch (e.kind) {
      case 'PurchaseCanceled':
        // User dismissed the store sheet — no action needed
        break;
      case 'ProductNotAvailable':
        // Product ID not available in this store environment
        showError('This product is not available. Please try again later.');
        break;
      case 'StoreProblem':
        // Unexpected StoreKit / Play Billing error
        showError('Store error. Please try again.');
        break;
      default:
        throw e; // unexpected — re-throw
    }
  }
}
func handlePurchase(pkg: Package) async {
  do {
    let result = try await Rovenue.shared.purchase(pkg)

    if result.isDeferred {
      // Ask-to-Buy / deferred — inform the user and wait for a change event
      showPendingMessage()
      return
    }

    // result.entitlements — verified, up-to-date array
    // result.virtualCurrencies — updated balances (for currency-pack products)
    print("Purchase succeeded: \(result.productId)")
    print("Transaction ID: \(result.storeTransactionId)")

    navigateToSuccess()
  } catch let e as RovenueError {
    switch e.kind {
    case .purchaseCanceled:
      break // User dismissed the store sheet — no action needed
    case .productNotAvailable:
      showError("This product is not available. Please try again later.")
    case .storeProblem:
      showError("Store error. Please try again.")
    default:
      throw e
    }
  }
}
// `activity` is your current Activity — Play Billing requires it.
suspend fun handlePurchase(activity: Activity, pkg: Package) {
  try {
    val result = Rovenue.shared.purchase(activity, pkg)

    if (result.isDeferred) {
      // Deferred payment — inform the user and wait for a change event
      showPendingMessage()
      return
    }

    // result.entitlements — verified, up-to-date list
    // result.virtualCurrencies — updated balances (for currency-pack products)
    println("Purchase succeeded: ${result.productId}")
    println("Transaction ID: ${result.storeTransactionId}")

    navigateToSuccess()
  } catch (e: RovenueException) {
    when (e.kind) {
      ErrorKind.PURCHASE_CANCELED -> { /* User dismissed the store sheet — no action needed */ }
      ErrorKind.PRODUCT_NOT_AVAILABLE -> showError("This product is not available. Please try again later.")
      ErrorKind.STORE_PROBLEM -> showError("Store error. Please try again.")
      else -> throw e
    }
  }
}

Errors to handle explicitly

  • RovenueError/RovenueException with kind === 'PurchaseCanceled' — the user dismissed the store sheet. Safe to ignore; do not show an error.
  • result.isDeferred (not an error) — Ask-to-Buy (iOS) or a pending Play Billing transaction. Show a "waiting for approval" message and listen for an ENTITLEMENTS_CHANGED event via addChangeListener.
  • result.isDeferred with pendingReason 'verification' — the store charged the user but the server could not be reached to verify it. The bought product's access is granted temporarily meanwhile (see Paid but not verified yet); its credits are not. The SDK keeps posting the purchase (a retry loop, then every launch and foreground) until it lands. It stays with the user who bought it: if the app calls logOut() or identify() meanwhile, the purchase is still recorded on the buyer, not on whoever is signed in by then. A buyer who was identified sees it after signing in again. Any other identity on the device — including the anonymous one a logOut() creates — gets it only through an explicit restorePurchases(), per the project's transfer behavior.
  • kind === 'ProductNotAvailable' — the product ID is not available in this store environment. Check your dashboard configuration.
  • kind === 'StoreProblem' — an unexpected StoreKit / Play Billing error. Retry or surface to the user.

See Errors for the full error reference.

Restore purchases

Apple's App Store guidelines require a Restore Purchases button in your paywall UI. Call restorePurchases() to re-validate all prior transactions for the current user — for example, after a reinstall or when a user switches devices.

import { Rovenue } from '@rovenue/react-native-sdk';

// Triggered by a "Restore Purchases" button
await Rovenue.restorePurchases();

// Entitlements are refreshed; read from cache
const pro = Rovenue.entitlement('pro');
console.log('pro restored:', pro?.isActive);
// Triggered by a "Restore Purchases" button
try await Rovenue.shared.restorePurchases()

// Entitlements are refreshed; read from cache
let pro = await Rovenue.shared.entitlement("pro")
print("pro restored:", pro?.isActive ?? false)
// Triggered by a "Restore Purchases" button (needs the current Activity)
Rovenue.shared.restorePurchases(activity)

// Entitlements are refreshed; read from cache
val pro = Rovenue.shared.entitlement("pro")
println("pro restored: ${pro?.isActive}")

On completion, the SDK emits an ENTITLEMENTS_CHANGED change event with the refreshed entitlement state. If you have a listener attached via addChangeListener, it fires automatically — you do not need to poll. See Reacting to changes.

When a restore fails

restorePurchases() throws when a receipt could not be submitted and no entitlement is active afterwards. It used to return an empty result in that case, which read as "nothing to restore". With nothing owned, or with an active entitlement after the refresh, it returns normally.

What was thrownWhat to show
isRetryable is true (NetworkUnavailable, Timeout, RateLimited, ServerError, StoreServiceUnavailable)"Couldn't reach the store. Check your connection and try again." with a retry button
kind Conflict with serverCode RECEIPT_IN_USE"This purchase belongs to another account. Sign in to that account to use it." The project's transfer behavior is "keep with original", so a retry will not help
Anything elseA generic "Restore failed" with the option to contact support
No error, and no active entitlement"No purchases to restore"
import { Rovenue, RovenueError } from '@rovenue/react-native-sdk';

try {
  await Rovenue.restorePurchases();
  const pro = Rovenue.entitlement('pro');
  showMessage(pro?.isActive ? 'Purchases restored' : 'No purchases to restore');
} catch (e) {
  if (!(e instanceof RovenueError)) throw e;
  if (e.isRetryable) showRetry("Couldn't reach the store. Try again.");
  else if (e.serverCode === 'RECEIPT_IN_USE') showMessage('This purchase belongs to another account.');
  else showMessage('Restore failed.');
}
do {
  try await Rovenue.shared.restorePurchases()
  let pro = await Rovenue.shared.entitlement("pro")
  showMessage(pro?.isActive == true ? "Purchases restored" : "No purchases to restore")
} catch let e as RovenueError {
  if e.isRetryable { showRetry("Couldn't reach the store. Try again.") }
  else if e.serverCode == "RECEIPT_IN_USE" { showMessage("This purchase belongs to another account.") }
  else { showMessage("Restore failed.") }
}
try {
  Rovenue.shared.restorePurchases(activity)
  val pro = Rovenue.shared.entitlement("pro")
  showMessage(if (pro?.isActive == true) "Purchases restored" else "No purchases to restore")
} catch (e: RovenueException) {
  when {
    e.isRetryable -> showRetry("Couldn't reach the store. Try again.")
    e.serverCode == "RECEIPT_IN_USE" -> showMessage("This purchase belongs to another account.")
    else -> showMessage("Restore failed.")
  }
}

On Android, restorePurchases asks Google Play for the purchases the account owns and posts them, so it also brings access back after a reinstall or on a new device. Also on Android, a second purchase() while the Play purchase sheet is up throws STORE_PROBLEM ("another purchase is already in progress") before Play is asked: disable the buy button while a purchase is pending, and do not present this error as a failed payment.


When the store has charged the user — a verified StoreKit 2 transaction, a Play purchase in PURCHASED — and the SDK cannot post the receipt to Rovenue because the request failed without an answer (offline, timeout, HTTP 429 or 5xx after its own retries), purchase() returns a verification deferral and the SDK keeps retrying. Meanwhile the bought product's access is granted temporarily on the device: the entitlements the product grants (as the last offering or funnel the app read says) read active, with isTemporary: true.

  • When it is granted. Only for the purchase's own first receipt post, and only for a transient failure. A definitive refusal (an HTTP 4xx: receipt invalid, product not in the project, sandbox key in a release build, a purchase owned by another customer) grants nothing and throws as before. An Ask-to-Buy / Play pending purchase and an unverified StoreKit transaction are never posted, so they grant nothing either. A consumable grants no access, and a product the device has not seen in an offering or funnel grants none.
  • How long it lasts. Until the first of: the receipt is verified (the server's answer replaces it — normally the same access, now with isTemporary: false); the receipt is refused (the access is removed); logOut() or identify() as another user; 24 hours after the failure. A non-renewing subscription (a pass) is granted like a lifetime purchase, but never past one day after it was bought (the shortest pass; on iOS from the transaction's purchase date, on Android from the first post), so it cannot outlast what the pass itself would grant. It survives a relaunch. Each change emits ENTITLEMENTS_CHANGED.
  • Credits are never granted on the device. The balance does not move, and nothing a spend can use exists until the server verifies the purchase; the server then grants them once, whatever retried, relaunched or restored in between. While a purchase is pending, pendingVerificationProductIds() lists its store product id: show "your credits are on the way", not a final balance of 0.
  • Server-side gates. Your own backend asks Rovenue, which has not seen the purchase yet: content your server gates stays locked until the receipt lands. Treat isTemporary access as "unlocked on this device, confirming".
const result = await Rovenue.purchase(pkg);
if (result.pendingReason === 'verification') {
  const pro = result.entitlements.find((e) => e.id === 'pro' && e.active);
  showBanner(pro?.isTemporary ? 'Payment received — confirming your purchase' : 'Payment received');
}
// Anywhere: products whose credits are still on the way.
const pending = await Rovenue.pendingVerificationProductIds();
let result = try await Rovenue.shared.purchase(pkg)
if result.pendingReason == .verification,
   let pro = result.entitlements.first(where: { $0.id == "pro" && $0.isActive }) {
    showBanner(pro.isTemporary ? "Payment received — confirming your purchase" : "Payment received")
}
let pending = await Rovenue.shared.pendingVerificationProductIds()
val result = Rovenue.shared.purchase(activity, pkg)
if (result.pendingReason == PurchasePendingReason.VERIFICATION) {
    val pro = result.entitlements.firstOrNull { it.id == "pro" && it.isActive }
    showBanner(if (pro?.isTemporary == true) "Payment received — confirming your purchase" else "Payment received")
}
val pending = Rovenue.shared.pendingVerificationProductIds()
final result = await Rovenue.instance.purchase(pkg.product);
if (result.pendingReason == PurchasePendingReason.verification) {
  final pro = result.entitlements.where((e) => e.id == 'pro' && e.active).firstOrNull;
  showBanner(pro?.isTemporary == true ? 'Payment received — confirming your purchase' : 'Payment received');
}
final pending = await Rovenue.instance.pendingVerificationProductIds();

Web checkout needs none of this: a Stripe payment is granted by Stripe's webhook on the server, and the browser never posts a receipt that could fail after the charge.


Redeeming promotional offers (iOS)

iOS lets you offer promotional discounts on subscriptions. They appear in StoreProduct.discounts and can be passed to purchase() to apply the discount at the moment of purchase. The SDK asks your Rovenue server to sign the offer right before the purchase — no extra setup beyond the In-App Purchase key.

Overview

  • Promotional offers come from StoreProduct.discounts with type = 'promotional'.
  • Win-back offers (type: 'winBack') are not promotional offers: StoreKit redeems them with its own win-back purchase option and no signature. Buy them with purchase(…, winBackOffer:) — see Win-back offers. Passing one to the promotional path throws (Swift: kind .invalidArgument, serverCode WIN_BACK_OFFER_UNSUPPORTED; the message names the win-back API).
  • Introductory offers (type: 'introductory') are applied automatically by the App Store and must NOT be passed to purchase() — doing so throws.
  • The server signs with your project's Apple In-App Purchase key and issuer id (never the App Store Connect API key) and only for a product that is an auto-renewable subscription in your Rovenue catalog under its App Store id; any other product id is refused with APPLE_OFFER_PRODUCT_INVALID. The JWS and the legacy signature route apply the same check.
  • Signature form. A Swift SDK built with Xcode 26 or later asks for a JWS (POST /v1/purchases/apple-offer-jws) and passes it to StoreKit's promotionalOffer(_:compactJWS:), which Apple back-deploys to iOS 15 and macOS 12 — so it covers every OS the SDK supports. Built with an older Xcode the API is not in the SDK, and the SDK uses the legacy signature (POST /v1/purchases/apple-offer-signature, deprecated by Apple in the 26 SDKs). It also falls back to the legacy signature when your server is older than the JWS route. React Native and Flutter apps inherit this from the Swift SDK they bundle.
  • The JWS carries Apple's claims (aud: "promotional-offer", productId, offerIdentifier, the customer's app transaction id when StoreKit has one) and no expiry claim: Apple expires it from its iat, the server's clock. Keep the server's clock in sync (NTP); the SDK fetches a new JWS for every purchase and never caches one.
  • If StoreKit refuses the offer (bad signature, unknown offer id, ineligible price), the purchase throws — Swift: kind .storeProblem, serverCode APPLE_PROMOTIONAL_OFFER_REJECTED — and nothing is charged. The SDK does not retry with the other signature form: it would be refused for the same reason (usually the wrong key in the In-App Purchase slot, a wrong issuer id, or an offer id that does not exist for this product in App Store Connect).
  • iOS: redeem via purchase(..., promotionalOffer:) or purchase(..., promotionalOfferId:).
  • Android: Google Play has no signed offers — see the Kotlin tab.

Introductory offers are automatic

Do not pass offers with type: 'introductory' to purchase(). The App Store applies them automatically based on eligibility. Attempting to pass one results in an error.

// ❌ Wrong
const intro = product.discounts.find(d => d.type === 'introductory');
await purchase(pkg, { promotionalOfferId: intro?.identifier });

// ✅ Correct
const promo = product.discounts.find(d => d.type === 'promotional');
await purchase(pkg, { promotionalOfferId: promo?.identifier });

Usage by platform

Pass the offer's identifier in the options object:

import { Rovenue } from '@rovenue/react-native-sdk';

const offerings = await Rovenue.getOfferings();
const pkg = offerings.current?.packages[0];
const product = pkg?.product;

// Promotional offers only: skip 'introductory' (automatic) and 'winBack' (use winBackOffer)
const promoOffer = product?.discounts?.find(d => d.type === 'promotional');

if (promoOffer) {
  try {
    const result = await Rovenue.purchase(pkg, {
      promotionalOfferId: promoOffer.identifier,
    });
    console.log('Purchase with promo succeeded:', result.productId);
  } catch (e) {
    // Handle errors (see [Errors](/docs/reference/errors))
  }
} else {
  // No promotional offer available; purchase at full price
  const result = await Rovenue.purchase(pkg);
}

promotionalOfferId is sent to StoreKit as a promotional offer id, so do not pass a win-back offer's identifier: it is refused with WIN_BACK_OFFER_UNSUPPORTED. Use the winBackOffer option instead (Win-back offers).

Note: On Android, the promotionalOfferId parameter is present but ignored; the purchase proceeds at the standard price.

Pass a Discount object (or use the id-based overload):

let offerings = try await Rovenue.shared.getOfferings()
let pkg = offerings.current?.packages.first
let product = pkg?.product

// Promotional offers only: skip .introductory (automatic) and .winBack (use winBackOffer:)
let promoOffer = product?.discounts.first { $0.type == .promotional }

if let offer = promoOffer {
  do {
    // Pass the Discount object directly
    let result = try await Rovenue.shared.purchase(product!, promotionalOffer: offer)
    print("Purchase with promo succeeded: \(result.productId)")

    // Or use the id-based overload:
    // let result = try await Rovenue.shared.purchase(product!, promotionalOfferId: offer.identifier!)
  } catch let error as RovenueError where error.serverCode == RovenueError.promotionalOfferRejectedCode {
    // StoreKit refused the signed offer; nothing was charged
  } catch {
    // Handle errors (see [Errors](/docs/reference/errors))
  }
} else {
  // No promotional offer available; purchase at full price
  let result = try await Rovenue.shared.purchase(product!)
}

Important: Passing a .introductory offer throws an error with code .ineligible and message "Introductory offers are applied automatically; do not pass them as a promotional offer." Passing a .winBack offer throws .invalidArgument with serverCode RovenueError.winBackOfferUnsupportedCode: buy it with purchase(_:winBackOffer:) (Win-back offers).

Google Play has no signed promotional offers. Its equivalent is a developer-determined offer: an offer on a base plan whose eligibility in the Play Console is Developer determined, so Play does not check eligibility and your app decides who sees it. Select it at purchase time with subscriptionOption — see Selecting a subscription offer. Nothing is signed on the server.

val offerings = Rovenue.shared.getOfferings()
val pkg = offerings.current?.packages?.firstOrNull()

if (pkg != null) {
  try {
    val result = Rovenue.shared.purchase(activity, pkg)
    println("Purchase succeeded: ${result.productId}")
  } catch (e: Exception) {
    // Handle errors (see [Errors](/docs/reference/errors))
  }
}

React Native apps on Android accept the promotionalOfferId option but ignore it, falling back to standard pricing.

Overriding introductory-offer eligibility (server)

The App Store decides who gets a subscription's introductory offer. Your server can override that per purchase with a JWS for StoreKit's introductoryOfferEligibility(compactJWS:) (back-deployed to iOS 15): POST /v1/purchases/apple-intro-eligibility-jws with productId, allowIntroductoryOffer and the customer's transactionId (required by Apple — any transaction id of the customer, including the app transaction id). It requires your secret key: a public key in a shipped app could otherwise grant itself the trial on every purchase.

curl -X POST https://api.example.com/v1/purchases/apple-intro-eligibility-jws \
  -H "Authorization: Bearer rov_sk_live_…" -H "Content-Type: application/json" \
  -d '{"productId":"premium_monthly","allowIntroductoryOffer":false,"transactionId":"2000000123456789"}'
# → { "data": { "jws": "eyJhbGciOiJFUzI1NiIs…" } }

The SDK's purchase() does not take this JWS yet; it is for apps that run the StoreKit purchase themselves.

Server prerequisites

Your project needs the Apple In-App Purchase key (.p8, from App Store Connect → Users and Access → Integrations → In-App Purchase) and its issuer id, saved in the Rovenue dashboard under Stores → App Store. The App Store Connect API key is never used for offers.

Error codeMeaning
APPLE_OFFER_PRODUCT_INVALIDThe product id is not an App Store subscription in this project's catalog.
apple_offer_signing_unavailableNo In-App Purchase key or issuer id is stored.
apple_offer_signing_failedThe stored key cannot sign (corrupted, or not an EC P-256 .p8).

A key that is a valid .p8 but the wrong one (for example the App Store Connect key saved in the In-App Purchase slot) signs fine and is only refused by StoreKit at purchase time (APPLE_PROMOTIONAL_OFFER_REJECTED).


Win-back offers

A win-back offer is a discount for someone whose subscription has lapsed. Both stores support it, differently:

App StoreGoogle Play
Where it is set upApp Store Connect → the subscription → Win-Back OffersPlay Console → base plan → offer with eligibility Developer determined, tagged rovenue-winback
Who is eligibleApple decides (the rules you set: time subscribed, time since it lapsed); StoreKit reports it on the devicePlay returns developer-determined offers to everyone and keeps no purchase history, so Rovenue decides: the SDK lists them only when the server saw the user hold that Play subscription and no longer hold it (any of its base plans), and the user has no active entitlement from it. A user who never subscribed sees none
OS / SDKiOS 18 / macOS 15, SDK built with Xcode 16 or laterany
Signaturenonenone

On both stores the offer is a Discount with type winBack in StoreProduct.discounts (catalog: every win-back offer of the product, eligible or not). Ask the SDK which ones the user can take now — on iOS from StoreKit's renewal info (eligibleWinBackOfferIDs, best offer first) — and buy one with purchase(…, winBackOffer:). The purchase lands on the server like any other: its offerKind is win_back on the App Store (see Which offer produced a purchase), and a Play purchase records its offer id with offerKind developer.

import { Rovenue } from '@rovenue/react-native-sdk';

const offers = await Rovenue.eligibleWinBackOffers(pkg);
if (offers.length > 0) {
  const result = await Rovenue.purchase(pkg, { winBackOffer: offers[0] });
}

winBackOffer cannot be combined with promotionalOfferId or subscriptionOption (InvalidArgument); a discount that is not a win-back offer rejects with Ineligible / WIN_BACK_OFFER_UNAVAILABLE. On Android, StoreProduct.discounts now lists the product's win-back offers too.

let offers = await Rovenue.shared.eligibleWinBackOffers(for: package)
if let best = offers.first {
  let result = try await Rovenue.shared.purchase(package, winBackOffer: best)
}
// Or by id (what the React Native and Flutter bridges call):
// try await Rovenue.shared.purchase(product, winBackOfferId: "winback_3m")
val offers = Rovenue.shared.eligibleWinBackOffers(product)
if (offers.isNotEmpty()) {
  val result = Rovenue.shared.purchase(activity, product, winBackOffer = offers.first())
}
// Or by id ("<basePlanId>:<offerId>"):
// Rovenue.shared.purchase(activity, product, winBackOfferId = "monthly:comeback")

A rovenue-winback offer is never the product's default offer, so a plain purchase() does not redeem it. A dashboard Offer ID that names one still wins: you chose it explicitly. Do not also tag it rovenue-ignore-offer.

final offers = await Rovenue.instance.eligibleWinBackOffers(product);
if (offers.isNotEmpty) {
  final result = await Rovenue.instance.purchase(product, winBackOffer: offers.first);
}

Lapsed subscriptions (Android). The SDK learns "held it before" from the server: GET /v1/me/entitlements (and GET /v1/me) carry lapsedSubscriptions, the App Store and Play subscriptions the customer held and no longer holds, as { store, productId } (Play: the subscription id, every base plan of it one entry; App Store: the product id — a crossgrade on the same subscription is not a lapse). Only store and product id are sent: no dates, prices or transaction ids. A subscription still held in any state — trial, grace period, account hold, paused — is not lapsed. The SDK caches the set with the entitlements, replaced on every refresh; it is conservative: before the first entitlements refresh, and once the cache is past the seven-day offline grace, nothing is lapsed and no win-back offer is listed. A restore of an expired App Store transaction can read "held" until the expiry sweep closes it again.

Errors. A discount that is not a win-back offer, an offer the store does not list for the product, or (iOS) an OS older than iOS 18 throws before the store sheet opens: kind ineligible, serverCode WIN_BACK_OFFER_UNAVAILABLE. A win-back offer passed to the promotional path throws WIN_BACK_OFFER_UNSUPPORTED. StoreKit refusing an offer the user is no longer eligible for is the usual ineligible purchase error.

Offers Apple presents itself. Apple also shows win-back offers outside your app: in the App Store, in Settings, and as a StoreKit message (winBackOffer, iOS 18; see Store messages). With Streamlined Purchasing on (the default in App Store Connect) the purchase completes in the App Store and reaches the SDK's transaction listener like any purchase made outside the app — nothing to do. With it off, the App Store opens your app with a purchase intent that the app must complete:

// iOS 16.4+ / macOS 14.4+
Task {
  for await intent in PurchaseIntent.intents {
    _ = try? await Rovenue.shared.purchase(intent)  // applies the intent's win-back offer, if any
  }
}

Funnels. A native funnel can show and sell the offer: {{product.winback_price}} prints the selected package's win-back price and the condition product.has_winback is true while the visitor is eligible (on Android, the rule above). A purchase_selected action or a purchase button with "offer": "win_back" buys the package with its best eligible win-back offer, or at the regular price when there is none. Web funnels have no win-back offers. See Purchases and effects.

Server. For App Store subscriptions the server keeps the eligible offer ids Apple last reported in renewal info (eligibleWinBackOfferIds, best first) on the subscription's latest purchase, with the time Apple signed that renewal info (eligibleWinBackOfferIdsAt): [] once Apple lists none, null for Google Play, Stripe and rows never reported. Every App Store notification that carries renewal info updates it (an older, out-of-order one does not), and so does the reconciliation sweep while it still checks the subscription. Neither reaches a subscription that has already ended: Apple sends no notification when a lapsed customer becomes eligible, and the sweep does not re-poll expired subscriptions. Nothing on the server decides on this list — the SDKs read eligibility from StoreKit on the device — so it is shown as last known: the dashboard's subscription drawer reads Win-back eligible "<offers> · last known <date>" (or "None · last known <date>"), and the dashboard subscriptions list and customer purchases carry eligibleWinBackOfferIds with eligibleWinBackOfferIdsAt.

Selecting a subscription offer (Android)

Android products can expose multiple subscription offers through subscriptionOptions — for example, a monthly base plan and a monthly-with-free-trial offer. You can select a specific offer at purchase time to redeem the user's chosen variant.

Overview

  • Subscription offers come from product.subscriptionOptions, a list of SubscriptionOption objects available on the product.
  • Each SubscriptionOption has a stable identity (basePlanId and offerId) that the SDK uses to resolve the live Play offer at purchase time.
  • When no option is passed to purchase(), the SDK buys the default option (product.defaultOption, see Default offer). If Play no longer returns that offer at purchase time, its base plan is bought.
  • If an option you pass explicitly is no longer available on Google Play, purchase fails with RovenueException (Kotlin) or RovenueError (React Native) — refresh offerings and retry.
  • iOS: the subscriptionOption parameter is ignored on iOS (iOS uses promotional offers instead).

Default offer (Android)

Google Play returns, for each base plan, only the offers the current user is eligible for. The SDK picks product.defaultOption from those, the way RevenueCat's defaultOption does:

  1. The product's base plan: the dashboard's Base plan ID, else the cheapest base plan.
  2. Among that base plan's offers, skipping any tagged rovenue-ignore-offer: the longest free trial, else the cheapest introductory price, else the base plan itself. An offer of another base plan is never chosen.

introPrice, isEligibleForIntroOffer and the funnel's trial variables (has_trial, trial_days, offer_price) describe that option, and a purchase without an explicit option (including a funnel's purchase button, and React Native / Flutter without subscriptionOption) redeems it. Introductory phases map to PaymentMode.FREE_TRIAL (free), PAY_UP_FRONT (one payment for the whole intro period) or PAY_AS_YOU_GO (a discounted price over several billing periods).

To keep an offer out of the default, add the tag rovenue-ignore-offer to it in the Play Console. Do this for offers whose eligibility is Developer determined — Play returns those to every user — and for upgrade offers you present yourself. Tag win-back offers rovenue-winback instead: that also keeps them out of the default and lists them as win-back discounts (Win-back offers). Offers inherit their base plan's tags, so tagging the base plan opts out all of its offers.

Server-configured default

The default offer (product.defaultOption) can be configured server-side in the Rovenue dashboard:

  • Per-product configuration in the Android section: set a Base plan ID (and optionally an Offer ID).
  • A Base plan ID alone picks that base plan; the SDK still chooses that plan's best eligible offer as above.
  • A Base plan ID with an Offer ID picks that offer, ahead of the automatic choice.
  • This ensures the advertised default price in your UI matches the actual plan the SDK purchases when the user selects a package without explicitly choosing an offer variant.
  • When left blank, the SDK uses the default offer of the cheapest base plan.
  • Important: an offer ID cannot be configured without a base plan ID — the API rejects orphaned offers.
  • If Play does not return the configured offer (the user is not eligible, or it ended), the SDK uses its base plan; if Play does not return the configured base plan, the automatic default. Neither fails the purchase.
  • Android-only: iOS has no base-plan concept; these configuration fields are ignored on iOS.

Free trials and introductory prices

Rovenue labels each Google Play charge from the order Google actually billed. A free-trial start is recorded as a $0 INITIAL event, the first paid order after the trial as TRIAL_CONVERSION at the amount the buyer paid, and an introductory period at its introductory price. While a free trial runs, the subscription's status is TRIAL.

To read each order, grant the service account you saved under Stores → Google Play the Play Console permission View financial data, orders, and cancellation survey responses (Users and permissions → the service account → App permissions). Without it, Rovenue falls back to the live subscription state only when that state provably describes the order, and otherwise records no revenue event for it (the server log names the reason). Saving the credentials shows a warning on the Stores card while the permission is missing.

Server-side acknowledgement (safety net)

Google Play refunds and revokes a purchase that nobody acknowledges within three days. The Android SDK acknowledges (or consumes) every purchase on the device right after Rovenue verified it. As a safety net, the Rovenue server also acknowledges a Google purchase it has verified and recorded, a few minutes later (10 by default, GOOGLE_SERVER_ACK_DELAY_MS on self-host; GOOGLE_SERVER_ACK_ENABLED=false turns it off). It reads Play first and does nothing when the app already acknowledged, so in the normal flow it never calls Play's acknowledge at all. It covers a user who pays and does not open the app again for three days, and a subscription that reaches Rovenue only through Real-time Developer Notifications (bought outside the app).

  • It acknowledges, never consumes. A consumable stays owned until the app consumes it (the SDK does on its next launch or foreground), because only the app knows it delivered the item.
  • It acknowledges only purchases Rovenue recorded. A one-time purchase that only arrived as a notification, with no receipt from the app, granted nothing in Rovenue, so it is left for Play to refund.
  • It needs the Play Console permission Manage orders and subscriptions on the service account (Users and permissions → the service account → App permissions). When Play refuses with 401/403, Rovenue stops trying for that app and the Stores card shows a warning on the service account step. Grant the permission and press Re-check (or save a new key): the next purchase is acknowledged again. Until then only the app acknowledges.

Usage by platform

Pass the chosen SubscriptionOption in the options object:

import { Rovenue, RovenueError } from '@rovenue/react-native-sdk';

const offerings = await Rovenue.getOfferings();
const pkg = offerings.current?.packages[0];
const product = pkg?.product;

// Get available subscription offers for this product
const options = product?.subscriptionOptions ?? [];

// Select the offer (e.g., the free-trial variant)
const selectedOption = options.find(opt => opt.tags.includes('free_trial'));

if (selectedOption && pkg) {
  try {
    const result = await Rovenue.purchase(pkg, {
      subscriptionOption: selectedOption,
    });
    console.log('Purchase with offer succeeded:', result.productId);
  } catch (e) {
    if (e instanceof RovenueError && e.kind === 'ProductNotAvailable') {
      // The selected offer is no longer available; refresh offerings and retry
      showError('This offer is no longer available. Please try again.');
    } else {
      // Handle other errors (see [Errors](/docs/reference/errors))
    }
  }
} else if (pkg) {
  // No specific offer selected; purchase the default option
  const result = await Rovenue.purchase(pkg);
}

Note: On iOS, the subscriptionOption parameter is present but ignored; the purchase proceeds with the standard iOS flow.

Subscription offer selection is not directly supported on native Swift. The native Kotlin SDK exposes this feature for Android; React Native apps can use the feature cross-platform.

let offerings = try await Rovenue.shared.getOfferings()
let pkg = offerings.current?.packages.first
let product = pkg?.product

if let product = product {
  do {
    // Native Swift does not expose subscriptionOptions
    // Use the standard purchase flow; the selected offer is an Android-only feature
    let result = try await Rovenue.shared.purchase(product)
    print("Purchase succeeded: \(result.productId)")
  } catch {
    // Handle errors (see [Errors](/docs/reference/errors))
  }
}

Note: Subscription offer selection is Android-only (Play Billing feature). If you need this functionality on iOS, use React Native instead.

Pass the chosen SubscriptionOption to purchase():

import dev.rovenue.sdk.RovenueException
import dev.rovenue.sdk.ErrorKind

val offerings = Rovenue.shared.getOfferings()
val pkg = offerings.current?.packages?.firstOrNull()
val product = pkg?.product

if (product != null) {
  // Get available subscription offers for this product
  val options = product.subscriptionOptions ?: emptyList()

  // Select the offer (e.g., the free-trial variant)
  val selectedOption = options.find { opt -> opt.tags.contains("free_trial") }

  if (selectedOption != null) {
    try {
      // Pass the chosen option to purchase
      val result = Rovenue.shared.purchase(activity, product, selectedOption)
      println("Purchase with offer succeeded: ${result.productId}")
    } catch (e: RovenueException) {
      if (e.kind == ErrorKind.PRODUCT_NOT_AVAILABLE) {
        // The selected offer is no longer available; refresh offerings and retry
        showError("This offer is no longer available. Please try again.")
      } else {
        // Handle other errors (see [Errors](/docs/reference/errors))
      }
    }
  } else {
    // No specific offer selected; purchase the default option
    val result = Rovenue.shared.purchase(activity, product)
    println("Purchase with default offer succeeded: ${result.productId}")
  }
}

You can also pass the option when purchasing a Package:

val pkg = offerings.current?.packages?.firstOrNull()
if (pkg != null && selectedOption != null) {
  val result = Rovenue.shared.purchase(activity, pkg, selectedOption)
}

Handling stale or unavailable offers

If the SubscriptionOption you selected is no longer available on Google Play (e.g., because the offer was removed or expired), the SDK will raise RovenueException with kind == ErrorKind.PRODUCT_NOT_AVAILABLE at purchase time. The error is raised only at the moment of purchase — not when building the UI.

What to do:

  1. Catch RovenueException and check kind == ErrorKind.PRODUCT_NOT_AVAILABLE in your purchase handler.
  2. Call Rovenue.getOfferings() again to refresh the product list.
  3. Show the user a message like "This offer is no longer available" and let them select another.
import dev.rovenue.sdk.RovenueException
import dev.rovenue.sdk.ErrorKind

try {
  val result = Rovenue.shared.purchase(activity, product, selectedOption)
} catch (e: RovenueException) {
  if (e.kind == ErrorKind.PRODUCT_NOT_AVAILABLE) {
    // Refresh offerings
    val refreshed = Rovenue.shared.getOfferings()
    showError("This offer is no longer available. Please select another.")
  } else {
    // Handle other errors
  }
}

Which offer produced a purchase

Every App Store and Google Play purchase records which store offer it came from, whichever path saw it first (the receipt your app posts, a store notification, or the reconciliation sweep). The dashboard's Subscriptions table shows it as a pill beside the renewal mode, and the row's drawer shows the kind and the store's id for the offer.

offerKindApp StoreGoogle Play
introofferType 1: introductory offer (free trial, pay as you go, pay up front)the purchase was seen in an offer's free-trial or introductory-price phase
promotionalofferType 2: promotional offer—
offer_codeofferType 3: subscription offer code—
win_backofferType 4: win-back offer—
retentionofferType 5: retention offer—
promo_code—a one-time or vanity promo code applied at sign-up (signupPromotion)
developer—any other offer (offerDetails.offerId), e.g. a developer-determined offer

Beside the kind, a purchase keeps the store's own facts: offerIdentifier (Apple's offer identifier; on Google Play the offerId, or the vanity code when Play names no offer), Apple's raw offerType, offerPeriod (ISO 8601, e.g. P1M) and offerDiscountType (FREE_TRIAL, PAY_AS_YOU_GO, PAY_UP_FRONT, ONE_TIME), and Google Play's basePlanId. Google Play does not say which eligibility rule an offer used, so a developer-determined offer bought straight into its free trial reads intro; a token keeps the kind it was first seen with while Play names the same offer, so a trial that converts stays intro. When a later delivery omits the offer, nothing recorded is erased.

"Intro" means introductory offers only. The subscriptions Intro filter, the intro pill and isIntroOffer in the subscriptions API used to count every App Store purchase made with any offer. Since v0.13.1 they count introductory offers only (offerKind intro), and Google Play free trials and introductory prices count too. Migration 0263 corrected the stored App Store rows, so the intro count drops by the promotional, offer-code and win-back purchases it used to include. App Store purchases recorded before Rovenue stored the offer type (migration 0118) keep their old flag and have no kind.

Trials follow the price, not the offer kind. A free period is a trial (status TRIAL, subscription.trial.started, and its first paid renewal is a trial conversion) whichever offer produced it: an App Store offer code, promotional or win-back offer whose payment mode is FREE_TRIAL, or a Google Play promo code redeemed into a free-trial phase. offerKind still says offer_code / promo_code and isIntroOffer stays false for them: kind is attribution, the trial state comes from the price and phase (the same split RevenueCat makes between period_type and offer_code).

The subscription.offer_redeemed webhook carries offerKind beside Apple's offerType (see outbound webhooks).


On this page