Custom Stores

Paddle

Sell Paddle Billing subscriptions on Superwall paywalls with a custom store: Paddle runs the checkout, and Superwall grants access and reports the revenue.

This guide connects Paddle Billing to Superwall through a custom store. When you're done:

  • A paywall sells your Paddle prices. Paddle's checkout takes the payment.
  • Paddle's webhooks reach a small server you run. It reports each purchase, renewal, cancellation and refund to Superwall.
  • Superwall grants and revokes the user's entitlements, sends your webhooks, and shows the revenue in your charts, attributed to the paywall that sold it.

You don't write the server from scratch. superwall/custom-store-paddle is a reference implementation: one Node server with no dependencies and a test suite. Run it as is, or copy it into your own backend.

How it works

  1. 1

    The app opens a Paddle checkout

    The user taps a Paddle product on a paywall. The server creates a Paddle transaction for that product's price, with the user's ID in its custom_data, and the app opens its checkout.

  2. 2

    The customer pays

    Paddle's overlay checkout takes the payment and sends the customer back to the app.

  3. 3

    Paddle notifies the server

    Paddle sends transaction.completed to the server. Paddle copies the transaction's custom_data to the subscription and to every renewal, so every later webhook names the same user.

  4. 4

    The server reports it to Superwall

    The server verifies the webhook and sends an initial_purchase event to the custom store. Superwall grants the product's entitlements, and the app unlocks.

Before you start

  • A Paddle Billing account. Start with a sandbox account: test purchases there never charge a card, and Superwall keeps them out of your production revenue.
  • A Superwall project with an iOS or Android app.
  • Node.js 22.18 or later, and a public https:// URL for the server. While testing, a tunnel such as cloudflared tunnel --url http://localhost:8788 works.

1. Set up Superwall

  1. 1

    Create a Paddle custom store

    Go to Integrations › Custom stores and click Create custom store. Name it Paddle. Note its custom store ID. You can also use the API.

  2. 2

    Add a product for each Paddle price

    Paddle sells prices, not products: one Paddle product can have a monthly and a yearly price, each with its own pri_... ID. Add one product to the store per Paddle price, and attach it to an entitlement such as pro. Use the same price, billing period and trial as the Paddle price, because that's what the paywall shows.

    Write down each Paddle price ID with its Superwall product identifier. You'll need them in step 3:

    { "pri_01k6x9...": "pro_monthly", "pri_01k6xa...": "pro_yearly" }
  3. 3

    Create an API key

    Go to Settings › API Keys and create a key with the custom_store_events:write scope, restricted to this project. This is SUPERWALL_API_KEY.

2. Set up Paddle

  1. 1

    Create an API key

    In Paddle, go to Paddle › My account › Settings › Authentication, open API keys, and create a key with these permissions: transaction.read, transaction.write, subscription.read and subscription.write. The server cancels a subscription in Paddle when it's refunded, so it needs write access. This is PADDLE_API_KEY (pdl_sdbx_apikey_... in sandbox).

  2. 2

    Create a client-side token

    Go to Paddle › My account › Settings › Authentication, open Client-side tokens, and create one. This is PADDLE_CLIENT_TOKEN (test_... in sandbox). The payment page uses it to open Paddle's checkout.

  3. 3

    Set the default payment link

    Go to Paddle › Checkout › Checkout configuration and set Default payment link to https://<your server>/paddle/pay. Paddle builds every checkout URL from this link, so it must point at the server's payment page. Paddle doesn't accept localhost, so use your tunnel's URL while testing. A live account needs the domain approved first under Paddle › My account › Settings › Website approval.

  4. 4

    Add a notification destination

    Go to Paddle › Events › Notifications and click New destination:

    • URL: https://<your server>/paddle/webhooks
    • Events: transaction.completed, subscription.created, subscription.updated, subscription.past_due, subscription.canceled, subscription.paused, adjustment.created and adjustment.updated

    Copy its secret key. This is PADDLE_WEBHOOK_SECRET (pdl_ntfset_...).

3. Run the server

git clone https://github.com/superwall/custom-store-paddle
cd custom-store-paddle

PADDLE_API_KEY=pdl_sdbx_apikey_... \
PADDLE_CLIENT_TOKEN=test_... \
PADDLE_WEBHOOK_SECRET=pdl_ntfset_... \
PADDLE_PRODUCTS='{"pri_01k6x9...":"pro_monthly"}' \
SUPERWALL_API_KEY=... \
SUPERWALL_CUSTOM_STORE_ID=4821 \
npm start

It listens on port 8788. Add the checkout settings from the next step before you sell anything.

The keys decide the environment. A sandbox API key and client token send events with environment: "sandbox", and live keys send production. The server refuses to start if the two don't match, so a test purchase can never be reported as real revenue.

To check your mapping before you send anything, start it with DRY_RUN=1: it logs each event it would send instead of sending it.

4. Open the checkout from the app

Pick how your app opens Paddle's checkout.

Checkout endpointPurchaseController
Purchase code in your appNoneA PurchaseController that opens the checkout
Who decides the user is subscribedThe SDK, from Superwall's entitlementsYour app, through subscriptionStatus
Works oniOS SDK 4.19.0+iOS SDK 4.15.0+, Android SDK 2.8.0+

Use the checkout endpoint unless you sell on Android or need the older iOS versions.

Option A: Checkout endpoint

  1. 1

    Point the store at the server

    Open the Paddle custom store in the dashboard. In its Checkout section, set the endpoint to https://<your server>/paddle/checkout. Superwall shows a signing secret (whsec_...) once. Restart the server with it as SUPERWALL_CHECKOUT_SECRET.

  2. 2

    Set up your app's URL scheme

    The customer comes back to the app through its URL scheme. Give your app a URL scheme, pass incoming links to Superwall.handleDeepLink(_:), and enter the scheme as the app's Apple custom URL scheme in the dashboard's app settings.

When the user taps a Paddle product, Superwall sends the server a signed checkout.create request. The server creates a Paddle transaction with the user's ID and the purchase's custom_transaction_id in custom_data, and answers with its checkout URL. The paywall opens it and waits for the customer to come back. When Paddle's webhook arrives, the server reports the initial_purchase with that custom_transaction_id, and the paywall closes as purchased. You don't need a PurchaseController.

Option B: PurchaseController

Your app's PurchaseController asks the server for a checkout and opens it.

  1. 1

    Tell the server who is buying

    POST /paddle/app-checkout creates a checkout for the signed-in user. Open app-auth.ts and replace authenticateAppUser with your app's own authentication. It must return the ID your app passes to Superwall.shared.identify(userId:), read from a credential your server checks, such as a session token:

    export const authenticateAppUser: AuthenticateAppUser = async (request) => {
      const token = request.headers.authorization?.replace(/^Bearer /, "")
      const session = token ? await sessions.verify(token) : undefined
      return session?.userId
    }

    Never take the user ID from the request body. Anyone could then attach their purchase to another user's account. Until you implement this function, the route answers 501.

  2. 2

    Set the return URL

    Restart the server with APP_RETURN_URL set to a URL that opens your app, such as myapp://paddle-checkout. The route answers 501 without it. After the customer pays, the payment page goes to myapp://paddle-checkout?status=completed&transaction_id=txn_.... If they close the checkout, it goes to ...?status=closed.

  3. 3

    Open the checkout from the PurchaseController

    For a custom store product, ask the server for a checkout and open it in an ASWebAuthenticationSession, which ends when the payment page opens your return URL. Its callbackURLScheme must be the scheme of APP_RETURN_URL:

    import AuthenticationServices
    import UIKit
    import SuperwallKit
    
    final class PaddlePurchaseController: NSObject, PurchaseController {
      let server = URL(string: "https://billing.example.com")!
      // The session must stay alive while the checkout is open.
      private var session: ASWebAuthenticationSession?
    
      func purchase(product: StoreProduct) async -> PurchaseResult {
        // App Store products: let Superwall purchase them with StoreKit.
        if product.sk1Product != nil {
          return await Superwall.shared.purchase(product)
        }
        if #available(iOS 15.0, *), product.sk2Product != nil {
          return await Superwall.shared.purchase(product)
        }
        do {
          let checkout = try await createCheckout(productId: product.productIdentifier)
          let returned = try await open(checkout)
          guard returned.queryItem("status") == "completed" else { return .cancelled }
          await refreshSubscriptionStatus()
          return .purchased
        } catch let error as ASWebAuthenticationSessionError where error.code == .canceledLogin {
          return .cancelled
        } catch {
          return .failed(error)
        }
      }
    
      func restorePurchases() async -> RestorationResult {
        await refreshSubscriptionStatus()
        return .restored
      }
    
      private func createCheckout(productId: String) async throws -> URL {
        var request = URLRequest(url: server.appendingPathComponent("paddle/app-checkout"))
        request.httpMethod = "POST"
        request.setValue("Bearer \(Session.current.token)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try JSONEncoder().encode(["product_id": productId])
        let (data, response) = try await URLSession.shared.data(for: request)
        guard (response as? HTTPURLResponse)?.statusCode == 200 else {
          throw URLError(.badServerResponse)
        }
        struct Checkout: Decodable { let url: URL }
        return try JSONDecoder().decode(Checkout.self, from: data).url
      }
    
      @MainActor
      private func open(_ url: URL) async throws -> URL {
        try await withCheckedThrowingContinuation { continuation in
          let session = ASWebAuthenticationSession(url: url, callbackURLScheme: "myapp") { [weak self] url, error in
            self?.session = nil
            if let url { continuation.resume(returning: url) }
            else { continuation.resume(throwing: error ?? URLError(.cancelled)) }
          }
          session.presentationContextProvider = self
          self.session = session
          session.start()
        }
      }
    }
    
    extension PaddlePurchaseController: ASWebAuthenticationPresentationContextProviding {
      func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        UIApplication.shared.connectedScenes
          .compactMap { ($0 as? UIWindowScene)?.keyWindow }
          .first ?? ASPresentationAnchor()
      }
    }
    
    private extension URL {
      func queryItem(_ name: String) -> String? {
        URLComponents(url: self, resolvingAgainstBaseURL: false)?
          .queryItems?.first { $0.name == name }?.value
      }
    }

    Session.current.token stands for your app's own credential, and refreshSubscriptionStatus() for your code that sets Superwall.shared.subscriptionStatus. With a PurchaseController, your app owns the subscription status. Set it from the entitlements Superwall holds for the user, as Custom Store Products describes, on launch and after every purchase. The customer can be back in the app a few seconds before Paddle's webhook reaches your server, so retry for a short while before you treat the purchase as not yet active.

To credit revenue to the paywall that sold it, also send the SDK's StoreProduct.customTransactionId as custom_transaction_id in the app-checkout body. It's available in the iOS SDK 4.19.0 and later and the Android SDK 2.8.0 and later. See Paywall attribution.

5. Test a purchase

  1. Start the server with sandbox keys, behind your tunnel.
  2. In the app, identify a test user, open the paywall and buy the Paddle product.
  3. In Paddle's checkout, pay with the test card 4242 4242 4242 4242, any cardholder name and any future expiry date.
  4. The server logs transaction.completed -> initial_purchase: accepted, and the app unlocks.
  5. In Paddle, refund the transaction in full. The server logs a refund, cancels the subscription in Paddle, and the user loses access the next time the app refreshes its entitlements, such as when it comes to the foreground.

Sandbox purchases appear in revenue charts when you filter to the Sandbox environment.

Go live

  1. Get your website approved in Paddle, then repeat step 2 in your live Paddle account. You need a live API key (pdl_live_apikey_...), client token (live_...), default payment link and notification destination.
  2. Map the live price IDs in PADDLE_PRODUCTS.
  3. Deploy the server on your own domain and restart it with the live keys.

The first live purchase starts the store's reporting_since. From then on, revenue charts count Paddle revenue from the server's events.

What the server reports

PaddleSuperwall event
transaction.completed for a new subscriptioninitial_purchase, priced at what the customer paid before tax
subscription.created in a free trialinitial_purchase with period_type: trial and a price of 0
transaction.completed for a renewalrenewal, with is_trial_conversion on the first charge after a free trial
transaction.completed for a plan changerenewal of the new product if it charged, otherwise product_change
transaction.completed for a one-time pricenon_renewing_purchase with no expiry
subscription.updated with a scheduled cancellationcancellation. Access continues until the period ends.
subscription.past_duebilling_issue
subscription.canceled or subscription.pausedexpiration
A full, approved refund or chargeback of the current periodrefund, and the server cancels the subscription in Paddle

Every event uses Paddle's event ID as its event_id, so Paddle's retries never apply a change twice. The repository's README explains each rule.

Limitations

  • Partial refunds aren't reported. Superwall supports only full refunds, and a refund ends the subscription for good. A customer who subscribes again gets a new Paddle subscription.
  • A removed cancellation isn't reported. Paddle's subscription.updated doesn't say what changed, so the server can't tell when a customer turns auto-renew back on. Superwall shows auto-renew off until the next renewal turns it back on. Access is never affected.
  • Refunding an earlier period is ignored. Refunding January's renewal in February leaves February, which the customer paid for, active in both Paddle and Superwall.
  • Prices are assumed to be one per transaction. Add-ons on the same transaction count toward the subscription's price.

Troubleshooting

Server logWhat to do
ignored (no app_user_id ...)The transaction was created without custom_data.superwall_app_user_id. Start checkouts through the server, not with Paddle.js on another page.
ignored (no mapped Paddle price among ...)Add the price ID to PADDLE_PRODUCTS.
rejected unknown_productThe product identifier in PADDLE_PRODUCTS doesn't exist on the custom store.
rejected unsupported_currencySuperwall has no exchange rate for the currency. Contact Superwall support.
Superwall responded 401; Paddle will retryCheck SUPERWALL_API_KEY and its custom_store_events:write scope. Paddle retries for about two days in live mode, so fixing it in time recovers every event. Sandbox retries only three times within about two minutes, so replay missed sandbox notifications from Paddle's dashboard.
CANCEL FAILEDA refunded subscription couldn't be canceled in Paddle. Paddle retries the webhook, and the cancel runs again. Alert on this line.

How is this guide?

On this page