Superwall

Using RevenueCat

Handle a deep link in your app and use the delegate methods to link web checkouts with RevenueCat.

After purchasing from a web paywall, the user will be redirected to your app by a deep link to redeem their purchase on device. Please follow our Post-Checkout Redirecting guide to handle this user experience.

If you're using Superwall to handle purchases, then you don't need to do anything here.

You only need to use a PurchaseController if you want end-to-end control of the purchasing pipeline. The recommended way to use RevenueCat with Superwall is by putting it in observer mode.

If you're using your own PurchaseController, you should follow our Redeeming In-App guide.

Using a PurchaseController with RevenueCat

If you're using RevenueCat, you'll need to follow steps 1 to 4 in their guide to set up Stripe with RevenueCat. Then, you'll need to associate the RevenueCat customer with the Stripe subscription IDs returned from redeeming the code. You can do this by extracting the ids from the RedemptionResult and sending them to RevenueCat's API by using the didRedeemLink(result:) delegate method:

import com.revenuecat.purchases.Purchases
import com.superwall.sdk.Superwall
import com.superwall.sdk.delegate.SuperwallDelegate
import com.superwall.sdk.models.redemption.RedemptionResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

class SWDelegate : SuperwallDelegate {
  private val client = OkHttpClient()
  private val coroutineScope = CoroutineScope(Dispatchers.IO)
  
  // The user tapped on a deep link to redeem a code
  override fun willRedeemLink() {
    Log.d("Superwall", "[!] willRedeemLink")
    // Optionally show a loading indicator here
  }

  // Superwall received a redemption result and validated the purchase with Stripe.
  override fun didRedeemLink(result: RedemptionResult) {
    Log.d("Superwall", "[!] didRedeemLink: $result")
    // Send Stripe IDs to RevenueCat to link purchases to the customer

    // Get a list of subscription ids tied to the customer.
    val stripeSubscriptionIds = when (result) {
      is RedemptionResult.Success -> result.stripeSubscriptionIds
      else -> null
    } ?: return

    val revenueCatStripePublicAPIKey = "strp....." // replace with your RevenueCat Stripe Public API Key
    val appUserId = Purchases.sharedInstance.appUserID

    // In the background using coroutines...
    coroutineScope.launch {
      // For each subscription id, link it to the user in RevenueCat
      stripeSubscriptionIds.forEach { stripeSubscriptionId ->
        try {
          val json = JSONObject().apply {
            put("app_user_id", appUserId)
            put("fetch_token", stripeSubscriptionId)
          }

          val requestBody = json.toString()
            .toRequestBody("application/json".toMediaType())

          val request = Request.Builder()
            .url("https://api.revenuecat.com/v1/receipts")
            .post(requestBody)
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .addHeader("X-Platform", "stripe")
            .addHeader("Authorization", "Bearer $revenueCatStripePublicAPIKey")
            .build()

          val response = client.newCall(request).execute()
          val responseBody = response.body?.string()
          
          if (response.isSuccessful) {
            Log.d("Superwall", "[!] Success: linked $stripeSubscriptionId to user $appUserId: $responseBody")
          } else {
            Log.e("Superwall", "[!] Error: unable to link $stripeSubscriptionId to user $appUserId. Response: $responseBody")
          }
        } catch (e: Exception) {
          Log.e("Superwall", "[!] Error: unable to link $stripeSubscriptionId to user $appUserId", e)
        }
      }

      /// After all network calls complete, invalidate the cache
      Purchases.sharedInstance.getCustomerInfo(
        onSuccess = { customerInfo ->
          /// If you're using RevenueCat's `UpdatedCustomerInfoListener`, or keeping Superwall Entitlements in sync
          /// via RevenueCat's listener methods, you don't need to do anything here. Those methods will be
          /// called automatically when this call fetches the most up to date customer info, ignoring any local caches.

          /// Otherwise, if you're manually calling `Purchases.sharedInstance.getCustomerInfo` to keep Superwall's entitlements
          /// in sync, you should use the newly updated customer info here to do so.
          
          /// You could always access web entitlements here as well
          /// val webEntitlements = Superwall.instance.entitlements.web
        },
        onError = { error ->
          Log.e("Superwall", "Error getting customer info", error)
        }
      )

      // After all network calls complete, update UI on the main thread
      withContext(Dispatchers.Main) {
        // Perform UI updates on the main thread, like letting the user know their subscription was redeemed
      }
    }
  }
}

If you call logIn from RevenueCat's SDK, then you need to call the logic you've implemented inside didRedeemLink(result:) again. For example, that means if logIn was invoked from RevenueCat, you'd either abstract out this logic above into a function to call again, or simply call this function directly.

The web entitlements will be returned along with other existing entitlements in the CustomerInfo object accessible via RevenueCat's SDK.

If you're logging in and out of RevenueCat, make sure to resend the Stripe subscription IDs to RevenueCat's endpoint after logging in.

How is this guide?