Using RevenueCat (Legacy)
If you want to use RevenueCat to handle your subscription-related logic with Superwall, follow this guide.
Not using RevenueCat? No problem! Superwall works out of the box without any additional SDKs.
Integrate RevenueCat with Superwall in one of two ways:
- Using a purchase controller: Use this route if you want to maintain control over purchasing logic and code.
- Using PurchasesAreCompletedBy: Here, you don't use a purchase controller and you tell RevenueCat that purchases are completed by your app using StoreKit 1. In this mode, RevenueCat will observe the purchases that the Superwall SDK makes. For more info see here.
1. Create a PurchaseController
Create a new file called RCPurchaseController.swift or RCPurchaseController.kt, then copy and paste the following:
import SuperwallKit
import RevenueCat
import StoreKit
enum PurchasingError: Error {
case productNotFound
}
final class RCPurchaseController: PurchaseController {
// MARK: Sync Subscription Status
/// Makes sure that Superwall knows the customers subscription status by
/// changing `Superwall.shared.subscriptionStatus`
func syncSubscriptionStatus() {
assert(Purchases.isConfigured, "You must configure RevenueCat before calling this method.")
Task {
for await customerInfo in Purchases.shared.customerInfoStream {
// Gets called whenever new CustomerInfo is available
let hasActiveSubscription = !customerInfo.entitlements.activeInCurrentEnvironment.isEmpty // Why? -> https://www.revenuecat.com/docs/entitlements#entitlements
if hasActiveSubscription {
Superwall.shared.subscriptionStatus = .active
} else {
Superwall.shared.subscriptionStatus = .inactive
}
}
}
}
// MARK: Handle Purchases
/// Makes a purchase with RevenueCat and returns its result. This gets called when
/// someone tries to purchase a product on one of your paywalls.
func purchase(product: SKProduct) async -> PurchaseResult {
do {
guard let storeProduct = await Purchases.shared.products([product.productIdentifier]).first else {
throw PurchasingError.productNotFound
}
// This must be initialized before initiating the purchase.
let purchaseDate = Date()
let revenueCatResult = try await Purchases.shared.purchase(product: storeProduct)
if revenueCatResult.userCancelled {
return .cancelled
} else {
if let transaction = revenueCatResult.transaction,
purchaseDate > transaction.purchaseDate {
return .restored
} else {
return .purchased
}
}
} catch let error as ErrorCode {
if error == .paymentPendingError {
return .pending
} else {
return .failed(error)
}
} catch {
return .failed(error)
}
}
// MARK: Handle Restores
/// Makes a restore with RevenueCat and returns `.restored`, unless an error is thrown.
/// This gets called when someone tries to restore purchases on one of your paywalls.
func restorePurchases() async -> RestorationResult {
do {
_ = try await Purchases.shared.restorePurchases()
return .restored
} catch let error {
return .failed(error)
}
}
}// RCPurchaseController.kt
import android.app.Activity
import android.content.Context
import com.android.billingclient.api.ProductDetails
import com.revenuecat.purchases.*
import com.revenuecat.purchases.interfaces.GetStoreProductsCallback
import com.revenuecat.purchases.interfaces.PurchaseCallback
import com.revenuecat.purchases.interfaces.ReceiveCustomerInfoCallback
import com.revenuecat.purchases.interfaces.UpdatedCustomerInfoListener
import com.revenuecat.purchases.models.StoreProduct
import com.revenuecat.purchases.models.StoreTransaction
import com.revenuecat.purchases.models.SubscriptionOption
import com.revenuecat.purchases.models.googleProduct
import com.superwall.sdk.Superwall
import com.superwall.sdk.delegate.PurchaseResult
import com.superwall.sdk.delegate.RestorationResult
import com.superwall.sdk.delegate.SubscriptionStatus
import com.superwall.sdk.delegate.subscription_controller.PurchaseController
import kotlinx.coroutines.CompletableDeferred
// Extension function to convert callback to suspend function
suspend fun Purchases.awaitProducts(productIds: List<String>): List<StoreProduct> {
val deferred = CompletableDeferred<List<StoreProduct>>()
getProducts(productIds, object : GetStoreProductsCallback {
override fun onReceived(storeProducts: List<StoreProduct>) {
deferred.complete(storeProducts)
}
override fun onError(error: PurchasesError) {
// Not sure about this cast...
deferred.completeExceptionally(Exception(error.message))
}
})
return deferred.await()
}
interface PurchaseCompletion {
var storeTransaction: StoreTransaction
var customerInfo: CustomerInfo
}
// Create a custom exception class that wraps PurchasesError
private class PurchasesException(val purchasesError: PurchasesError) : Exception(purchasesError.toString())
suspend fun Purchases.awaitPurchase(activity: Activity, storeProduct: StoreProduct): PurchaseCompletion {
val deferred = CompletableDeferred<PurchaseCompletion>()
purchase(PurchaseParams.Builder(activity, storeProduct).build(), object : PurchaseCallback {
override fun onCompleted(storeTransaction: StoreTransaction, customerInfo: CustomerInfo) {
deferred.complete(object : PurchaseCompletion {
override var storeTransaction: StoreTransaction = storeTransaction
override var customerInfo: CustomerInfo = customerInfo
})
}
override fun onError(error: PurchasesError, p1: Boolean) {
deferred.completeExceptionally(PurchasesException(error))
}
})
return deferred.await()
}
suspend fun Purchases.awaitRestoration(): CustomerInfo {
val deferred = CompletableDeferred<CustomerInfo>()
restorePurchases(object : ReceiveCustomerInfoCallback {
override fun onReceived(purchaserInfo: CustomerInfo) {
deferred.complete(purchaserInfo)
}
override fun onError(error: PurchasesError) {
deferred.completeExceptionally(error as Throwable)
}
})
return deferred.await()
}
class RCPurchaseController(val context: Context): PurchaseController, UpdatedCustomerInfoListener {
init {
Purchases.logLevel = LogLevel.DEBUG
Purchases.configure(PurchasesConfiguration.Builder(context, "MY_ANDROID_API_KEY").build())
// Make sure we get the updates
Purchases.sharedInstance.updatedCustomerInfoListener = this
}
fun syncSubscriptionStatus() {
// Refetch the customer info on load
Purchases.sharedInstance.getCustomerInfoWith {
if (hasAnyActiveEntitlements(it)) {
setSubscriptionStatus(SubscriptionStatus.ACTIVE)
} else {
setSubscriptionStatus(SubscriptionStatus.INACTIVE)
}
}
}
/**
* Callback for RC customer updated info
*/
override fun onReceived(customerInfo: CustomerInfo) {
if (hasAnyActiveEntitlements(customerInfo)) {
setSubscriptionStatus(SubscriptionStatus.ACTIVE)
} else {
setSubscriptionStatus(SubscriptionStatus.INACTIVE)
}
}
/**
* Initiate a purchase
*/
override suspend fun purchase(
activity: Activity,
productDetails: ProductDetails,
basePlanId: String?,
offerId: String?
): PurchaseResult {
// Find products matching productId from RevenueCat
val products = Purchases.sharedInstance.awaitProducts(listOf(productDetails.productId))
// Choose the product which matches the given base plan.
// If no base plan set, select first product or fail.
val product = products.firstOrNull { it.googleProduct?.basePlanId == basePlanId }
?: products.firstOrNull()
?: return PurchaseResult.Failed("Product not found")
return when (product.type) {
ProductType.SUBS, ProductType.UNKNOWN -> handleSubscription(activity, product, basePlanId, offerId)
ProductType.INAPP -> handleInAppPurchase(activity, product)
}
}
private fun buildSubscriptionOptionId(basePlanId: String?, offerId: String?): String =
buildString {
basePlanId?.let { append("$it") }
offerId?.let { append(":$it") }
}
private suspend fun handleSubscription(
activity: Activity,
storeProduct: StoreProduct,
basePlanId: String?,
offerId: String?
): PurchaseResult {
storeProduct.subscriptionOptions?.let { subscriptionOptions ->
// If subscription option exists, concatenate base + offer ID.
val subscriptionOptionId = buildSubscriptionOptionId(basePlanId, offerId)
// Find first subscription option that matches the subscription option ID or default
// to letting revenuecat choose.
val subscriptionOption = subscriptionOptions.firstOrNull { it.id == subscriptionOptionId }
?: subscriptionOptions.defaultOffer
// Purchase subscription option, otherwise fail.
if (subscriptionOption != null) {
return purchaseSubscription(activity, subscriptionOption)
}
}
return PurchaseResult.Failed("Valid subscription option not found for product.")
}
private suspend fun purchaseSubscription(activity: Activity, subscriptionOption: SubscriptionOption): PurchaseResult {
val deferred = CompletableDeferred<PurchaseResult>()
Purchases.sharedInstance.purchaseWith(
PurchaseParams.Builder(activity, subscriptionOption).build(),
onError = { error, userCancelled ->
deferred.complete(if (userCancelled) PurchaseResult.Cancelled() else PurchaseResult.Failed(error.message))
},
onSuccess = { _, _ ->
deferred.complete(PurchaseResult.Purchased())
}
)
return deferred.await()
}
private suspend fun handleInAppPurchase(activity: Activity, storeProduct: StoreProduct): PurchaseResult =
try {
Purchases.sharedInstance.awaitPurchase(activity, storeProduct)
PurchaseResult.Purchased()
} catch (e: PurchasesException) {
when (e.purchasesError.code) {
PurchasesErrorCode.PurchaseCancelledError -> PurchaseResult.Cancelled()
else -> PurchaseResult.Failed(e.message ?: "Purchase failed due to an unknown error")
}
}
/**
* Restore purchases
*/
override suspend fun restorePurchases(): RestorationResult {
try {
if (hasAnyActiveEntitlements(Purchases.sharedInstance.awaitRestoration())) {
return RestorationResult.Restored()
} else {
return RestorationResult.Failed(Exception("No active entitlements"))
}
} catch (e: Throwable) {
return RestorationResult.Failed(e)
}
}
/**
* Check if the customer has any active entitlements
*/
private fun hasAnyActiveEntitlements(customerInfo: CustomerInfo): Boolean {
val entitlements = customerInfo.entitlements.active.values.map { it.identifier }
return entitlements.isNotEmpty()
}
private fun setSubscriptionStatus(subscriptionStatus: SubscriptionStatus) {
if (Superwall.initialized) {
Superwall.instance.setSubscriptionStatus(subscriptionStatus)
}
}
}import 'package:flutter/services.dart';
import 'package:purchases_flutter/purchases_flutter.dart';
import 'package:superwallkit_flutter/superwallkit_flutter.dart' hide LogLevel;
class RCPurchaseController extends PurchaseController {
// MARK: Configure and sync subscription Status
/// Makes sure that Superwall knows the customers subscription status by
/// changing `Superwall.shared.subscriptionStatus`
Future<void> syncSubscriptionStatus() async {
// Configure RevenueCat
await Purchases.setLogLevel(LogLevel.debug);
PurchasesConfiguration configuration = Platform.isIOS ? PurchasesConfiguration("MY_IOS_API_KEY") : PurchasesConfiguration("MY_ANDROID_API_KEY");
await Purchases.configure(configuration);
// Listen for changes
Purchases.addCustomerInfoUpdateListener((customerInfo) {
// Gets called whenever new CustomerInfo is available
bool hasActiveEntitlementOrSubscription = customerInfo.hasActiveEntitlementOrSubscription(); // Why? -> https://www.revenuecat.com/docs/entitlements#entitlements
if (hasActiveEntitlementOrSubscription) {
Superwall.shared.setSubscriptionStatus(SubscriptionStatus.active);
} else {
Superwall.shared.setSubscriptionStatus(SubscriptionStatus.inactive);
}
});
}
// MARK: Handle Purchases
/// Makes a purchase from App Store with RevenueCat and returns its
/// result. This gets called when someone tries to purchase a product on
/// one of your paywalls from iOS.
@override
Future<PurchaseResult> purchaseFromAppStore(String productId) async {
// Find products matching productId from RevenueCat
List<StoreProduct> products = await PurchasesAdditions.getAllProducts([productId]);
// Get first product for product ID (this will properly throw if empty)
StoreProduct? storeProduct = products.firstOrNull;
if (storeProduct == null) {
return PurchaseResult.failed("Failed to find store product for $productId");
}
PurchaseResult purchaseResult = await _purchaseStoreProduct(storeProduct);
return purchaseResult;
}
/// Makes a purchase from Google Play with RevenueCat and returns its
/// result. This gets called when someone tries to purchase a product on
/// one of your paywalls from Android.
@override
Future<PurchaseResult> purchaseFromGooglePlay(String productId, String? basePlanId, String? offerId) async {
// Find products matching productId from RevenueCat
List<StoreProduct> products = await PurchasesAdditions.getAllProducts([productId]);
// Choose the product which matches the given base plan.
// If no base plan set, select first product or fail.
String storeProductId = "$productId:$basePlanId";
// Try to find the first product where the googleProduct's basePlanId matches the given basePlanId.
StoreProduct? matchingProduct;
// Loop through each product in the products list.
for (final product in products) {
// Check if the current product's basePlanId matches the given basePlanId.
if (product.identifier == storeProductId) {
// If a match is found, assign this product to matchingProduct.
matchingProduct = product;
// Break the loop as we found our matching product.
break;
}
}
// If a matching product is not found, then try to get the first product from the list.
StoreProduct? storeProduct = matchingProduct ?? (products.isNotEmpty ? products.first : null);
// If no product is found (either matching or the first one), return a failed purchase result.
if (storeProduct == null) {
return PurchaseResult.failed("Product not found");
}
switch (storeProduct.productCategory) {
case ProductCategory.subscription:
SubscriptionOption? subscriptionOption = await _fetchGooglePlaySubscriptionOption(storeProduct, basePlanId, offerId);
if (subscriptionOption == null) {
return PurchaseResult.failed("Valid subscription option not found for product.");
}
return await _purchaseSubscriptionOption(subscriptionOption);
case ProductCategory.nonSubscription:
return await _purchaseStoreProduct(storeProduct);
case null:
return PurchaseResult.failed("Unable to determine product category");
}
}
Future<SubscriptionOption?> _fetchGooglePlaySubscriptionOption(
StoreProduct storeProduct,
String? basePlanId,
String? offerId,
) async {
final subscriptionOptions = storeProduct.subscriptionOptions;
if (subscriptionOptions != null && subscriptionOptions.isNotEmpty) {
// Concatenate base + offer ID
final subscriptionOptionId = _buildSubscriptionOptionId(basePlanId, offerId);
// Find first subscription option that matches the subscription option ID or use the default offer
SubscriptionOption? subscriptionOption;
// Search for the subscription option with the matching ID
for (final option in subscriptionOptions) {
if (option.id == subscriptionOptionId) {
subscriptionOption = option;
break;
}
}
// If no matching subscription option is found, use the default option
subscriptionOption ??= storeProduct.defaultOption;
// Return the subscription option
return subscriptionOption;
}
return null;
}
Future<PurchaseResult> _purchaseSubscriptionOption(SubscriptionOption subscriptionOption) async {
// Define the async perform purchase function
Future<CustomerInfo> performPurchase() async {
// Attempt to purchase product
CustomerInfo customerInfo = await Purchases.purchaseSubscriptionOption(subscriptionOption);
return customerInfo;
}
PurchaseResult purchaseResult = await _handleSharedPurchase(performPurchase);
return purchaseResult;
}
Future<PurchaseResult> _purchaseStoreProduct(StoreProduct storeProduct) async {
// Define the async perform purchase function
Future<CustomerInfo> performPurchase() async {
// Attempt to purchase product
CustomerInfo customerInfo = await Purchases.purchaseStoreProduct(storeProduct);
return customerInfo;
}
PurchaseResult purchaseResult = await _handleSharedPurchase(performPurchase);
return purchaseResult;
}
// MARK: Shared purchase
Future<PurchaseResult> _handleSharedPurchase(Future<CustomerInfo> Function() performPurchase) async {
try {
// Store the current purchase date to later determine if this is a new purchase or restore
DateTime purchaseDate = DateTime.now();
// Perform the purchase using the function provided
CustomerInfo customerInfo = await performPurchase();
// Handle the results
if (customerInfo.hasActiveEntitlementOrSubscription()) {
DateTime? latestTransactionPurchaseDate = customerInfo.getLatestTransactionPurchaseDate();
// If no latest transaction date is found, consider it as a new purchase.
bool isNewPurchase = (latestTransactionPurchaseDate == null);
// If the current date (`purchaseDate`) is after the latestTransactionPurchaseDate,
bool purchaseHappenedInThePast = latestTransactionPurchaseDate?.isBefore(purchaseDate) ?? false;
if (!isNewPurchase && purchaseHappenedInThePast) {
return PurchaseResult.restored;
} else {
return PurchaseResult.purchased;
}
} else {
return PurchaseResult.failed("No active subscriptions found.");
}
} on PlatformException catch (e) {
var errorCode = PurchasesErrorHelper.getErrorCode(e);
if (errorCode == PurchasesErrorCode.paymentPendingError) {
return PurchaseResult.pending;
} else if (errorCode == PurchasesErrorCode.purchaseCancelledError) {
return PurchaseResult.cancelled;
} else {
return PurchaseResult.failed(e.message ?? "Purchase failed in RCPurchaseController");
}
}
}
// MARK: Handle Restores
/// Makes a restore with RevenueCat and returns `.restored`, unless an error is thrown.
/// This gets called when someone tries to restore purchases on one of your paywalls.
@override
Future<RestorationResult> restorePurchases() async {
try {
await Purchases.restorePurchases();
return RestorationResult.restored;
} on PlatformException catch (e) {
// Error restoring purchases
return RestorationResult.failed(e.message ?? "Restore failed in RCPurchaseController");
}
}
}
// MARK: Helpers
String _buildSubscriptionOptionId(String? basePlanId, String? offerId) {
String result = '';
if (basePlanId != null) {
result += basePlanId;
}
if (offerId != null) {
if (basePlanId != null) {
result += ':';
}
result += offerId;
}
return result;
}
extension CustomerInfoAdditions on CustomerInfo {
bool hasActiveEntitlementOrSubscription() {
return (activeSubscriptions.isNotEmpty || entitlements.active.isNotEmpty);
}
DateTime? getLatestTransactionPurchaseDate() {
Map<String, String> allPurchaseDates = this.allPurchaseDates;
if (allPurchaseDates.entries.isEmpty) {
return null;
}
DateTime latestDate = DateTime.fromMillisecondsSinceEpoch(0);
allPurchaseDates.forEach((key, value) {
DateTime date = DateTime.parse(value);
if (date.isAfter(latestDate)) {
latestDate = date;
}
});
return latestDate;
}
}
extension PurchasesAdditions on Purchases {
static Future<List<StoreProduct>> getAllProducts(List<String> productIdentifiers) async {
final subscriptionProducts = await Purchases.getProducts(productIdentifiers, productCategory: ProductCategory.subscription);
final nonSubscriptionProducts = await Purchases.getProducts(productIdentifiers, productCategory: ProductCategory.nonSubscription);
final combinedProducts = [...subscriptionProducts, ...nonSubscriptionProducts];
return combinedProducts;
}
}import { Platform } from "react-native"
import Superwall, {
PurchaseController,
PurchaseResult,
RestorationResult,
SubscriptionStatus,
PurchaseResultCancelled,
PurchaseResultFailed,
PurchaseResultPending,
PurchaseResultPurchased,
PurchaseResultRestored,
} from "@superwall/react-native-superwall"
import Purchases, {
type CustomerInfo,
PRODUCT_CATEGORY,
type PurchasesStoreProduct,
type SubscriptionOption,
PURCHASES_ERROR_CODE,
type MakePurchaseResult,
} from "react-native-purchases"
export class RCPurchaseController extends PurchaseController {
configureAndSyncSubscriptionStatus() {
// Configure RevenueCat
Purchases.setLogLevel(Purchases.LOG_LEVEL.DEBUG)
const apiKey =
Platform.OS === "ios" ? "MY_REVENUECAT_IOS_API_KEY" : "MY_REVENUECAT_ANDROID_API_KEY"
Purchases.configure({ apiKey })
// Listen for changes
Purchases.addCustomerInfoUpdateListener((customerInfo) => {
const hasActiveEntitlementOrSubscription =
this.hasActiveEntitlementOrSubscription(customerInfo)
Superwall.shared.setSubscriptionStatus(
hasActiveEntitlementOrSubscription ? SubscriptionStatus.ACTIVE : SubscriptionStatus.INACTIVE
)
})
}
async purchaseFromAppStore(productId: string): Promise<PurchaseResult> {
const products = await Promise.all([
Purchases.getProducts([productId], PRODUCT_CATEGORY.SUBSCRIPTION),
Purchases.getProducts([productId], PRODUCT_CATEGORY.NON_SUBSCRIPTION),
]).then((results) => results.flat())
// Assuming an equivalent for Dart's firstOrNull is not directly available in TypeScript,
// so using a simple conditional check
const storeProduct = products.length > 0 ? products[0] : null
if (!storeProduct) {
return new PurchaseResultFailed("Failed to find store product for $productId")
}
return await this._purchaseStoreProduct(storeProduct)
}
async purchaseFromGooglePlay(
productId: string,
basePlanId?: string,
offerId?: string
): Promise<PurchaseResult> {
// Find products matching productId from RevenueCat
const products = await Promise.all([
Purchases.getProducts([productId], PRODUCT_CATEGORY.SUBSCRIPTION),
Purchases.getProducts([productId], PRODUCT_CATEGORY.NON_SUBSCRIPTION),
]).then((results) => results.flat())
// Choose the product which matches the given base plan.
// If no base plan set, select first product or fail.
const storeProductId = `${productId}:${basePlanId}`
// Initialize matchingProduct as null explicitly
let matchingProduct: PurchasesStoreProduct | null = null
// Loop through each product in the products array
for (const product of products) {
// Check if the current product's identifier matches the given storeProductId
if (product.identifier === storeProductId) {
// If a match is found, assign this product to matchingProduct
matchingProduct = product
// Break the loop as we found our matching product
break
}
}
let storeProduct: PurchasesStoreProduct | null =
matchingProduct ??
(products.length > 0 && typeof products[0] !== "undefined" ? products[0] : null)
// If no product is found (either matching or the first one), return a failed purchase result.
if (storeProduct === null) {
return new PurchaseResultFailed("Product not found")
}
switch (storeProduct.productCategory) {
case PRODUCT_CATEGORY.SUBSCRIPTION:
const subscriptionOption = await this._fetchGooglePlaySubscriptionOption(
storeProduct,
basePlanId,
offerId
)
if (subscriptionOption === null) {
return new PurchaseResultFailed("Valid subscription option not found for product.")
}
return await this._purchaseSubscriptionOption(subscriptionOption)
case PRODUCT_CATEGORY.NON_SUBSCRIPTION:
return await this._purchaseStoreProduct(storeProduct)
default:
return new PurchaseResultFailed("Unable to determine product category")
}
}
private async _purchaseStoreProduct(
storeProduct: PurchasesStoreProduct
): Promise<PurchaseResult> {
const performPurchase = async (): Promise<MakePurchaseResult> => {
// Attempt to purchase product
const makePurchaseResult = await Purchases.purchaseStoreProduct(storeProduct)
return makePurchaseResult
}
return await this.handleSharedPurchase(performPurchase)
}
private async _fetchGooglePlaySubscriptionOption(
storeProduct: PurchasesStoreProduct,
basePlanId?: string,
offerId?: string
): Promise<SubscriptionOption | null> {
const subscriptionOptions = storeProduct.subscriptionOptions
if (subscriptionOptions && subscriptionOptions.length > 0) {
// Concatenate base + offer ID
const subscriptionOptionId = this.buildSubscriptionOptionId(basePlanId, offerId)
// Find first subscription option that matches the subscription option ID or use the default offer
let subscriptionOption: SubscriptionOption | null = null
// Search for the subscription option with the matching ID
for (const option of subscriptionOptions) {
if (option.id === subscriptionOptionId) {
subscriptionOption = option
break
}
}
// If no matching subscription option is found, use the default option
subscriptionOption = subscriptionOption ?? storeProduct.defaultOption
// Return the subscription option
return subscriptionOption
}
return null
}
private buildSubscriptionOptionId(basePlanId?: string, offerId?: string): string {
let result = ""
if (basePlanId !== null) {
result += basePlanId
}
if (offerId !== null) {
if (basePlanId !== null) {
result += ":"
}
result += offerId
}
return result
}
private async _purchaseSubscriptionOption(
subscriptionOption: SubscriptionOption
): Promise<PurchaseResult> {
// Define the async perform purchase function
const performPurchase = async (): Promise<MakePurchaseResult> => {
// Attempt to purchase product
const purchaseResult = await Purchases.purchaseSubscriptionOption(subscriptionOption)
return purchaseResult
}
const purchaseResult: PurchaseResult = await this.handleSharedPurchase(performPurchase)
return purchaseResult
}
private async handleSharedPurchase(
performPurchase: () => Promise<MakePurchaseResult>
): Promise<PurchaseResult> {
try {
// Store the current purchase date to later determine if this is a new purchase or restore
const purchaseDate = new Date()
// Perform the purchase using the function provided
const makePurchaseResult = await performPurchase()
// Handle the results
if (this.hasActiveEntitlementOrSubscription(makePurchaseResult.customerInfo)) {
const latestTransactionPurchaseDate = new Date(makePurchaseResult.transaction.purchaseDate)
// If no latest transaction date is found, consider it as a new purchase.
const isNewPurchase = latestTransactionPurchaseDate === null
// If the current date (`purchaseDate`) is after the latestTransactionPurchaseDate,
const purchaseHappenedInThePast = latestTransactionPurchaseDate
? purchaseDate > latestTransactionPurchaseDate
: false
if (!isNewPurchase && purchaseHappenedInThePast) {
return new PurchaseResultRestored()
} else {
return new PurchaseResultPurchased()
}
} else {
return new PurchaseResultFailed("No active subscriptions found.")
}
} catch (e: any) {
// Catch block to handle exceptions, adjusted for TypeScript
if (e.userCancelled) {
return new PurchaseResultCancelled()
}
if (e.code === PURCHASES_ERROR_CODE.PAYMENT_PENDING_ERROR) {
return new PurchaseResultPending()
} else {
return new PurchaseResultFailed(e.message)
}
}
}
async restorePurchases(): Promise<RestorationResult> {
try {
await Purchases.restorePurchases()
return RestorationResult.restored()
} catch (e: any) {
return RestorationResult.failed(e.message)
}
}
private hasActiveEntitlementOrSubscription(customerInfo: CustomerInfo): Boolean {
return (
customerInfo.activeSubscriptions.length > 0 ||
Object.keys(customerInfo.entitlements.active).length > 0
)
}
}As discussed in Purchases and Subscription Status, this PurchaseController is responsible for handling the subscription-related logic. Take a few moments to look through the code to understand how it does this.
2. Configure Superwall
Initialize an instance of RCPurchaseController and pass it in to Superwall.configure(apiKey:purchaseController):
let purchaseController = RCPurchaseController()
Superwall.configure(
apiKey: "MY_API_KEY",
purchaseController: purchaseController
)RCPurchaseController *purchaseController = [RCPurchaseController alloc] init];
[Superwall
configureWithApiKey:@"MY_API_KEY"
purchaseController:purchaseController
options:options
completion:nil
];val purchaseController = RCPurchaseController(this)
Superwall.configure(
this,
"MY_API_KEY",
purchaseController
)
// Make sure we sync the subscription status
// on first load and whenever it changes
purchaseController.syncSubscriptionStatus()RCPurchaseController purchaseController = RCPurchaseController();
Superwall.configure(
apiKey,
purchaseController: purchaseController
);
await purchaseController.syncSubscriptionStatus();React.useEffect(() => {
const apiKey = Platform.OS === "ios" ? "MY_SUPERWALL_IOS_API_KEY" : "MY_SUPERWALL_ANDROID_API_KEY"
const purchaseController = new RCPurchaseController()
Superwall.configure(apiKey, null, purchaseController)
purchaseController.configureAndSyncSubscriptionStatus()
}, [])3. Sync the subscription status
Then, call purchaseController.syncSubscriptionStatus() to keep Superwall's subscription status up to date with RevenueCat.
That's it! Check out our RevenueCat iOS example app for a working example of this integration.
Using PurchasesAreCompletedBy
If you're using RevenueCat's PurchasesAreCompletedBy, you don't need to create a purchase controller. Register your placements, present a paywall — and Superwall will take care of completing any purchase the user starts. However, there are a few things to note if you use this setup:
- Here, you aren't using RevenueCat's entitlements as a source of truth. If your app is multiplatform, you'll need to consider how to link up pro features or purchased products for users.
- If you require custom logic when purchases occur, then you'll want to add a purchase controller. In that case, Superwall handles purchasing flows and RevenueCat will still observe transactions to power their analytics and charts.
- Be sure that user identifiers are set the same way across Superwall and RevenueCat.
- Finally, make sure that RevenueCat is using StoreKit 1.
Example:
Superwall.configure(apiKey: "superwall_public_key")
Superwall.shared.identify(userId: user.identifier)
Purchases.configure(with:
.builder(withAPIKey: "revcat_public_key")
.with(purchasesAreCompletedBy: .myApp, storeKitVersion: .storeKit1)
.with(appUserID: user.identifier)
.build()
)For more information on observer mode, visit RevenueCat's docs.
How is this guide?
Edit on GitHub