Skip to content
Commitwise
Menu
iOS Development

In-app purchases and subscriptions with StoreKit 2

Load products, buy and verify transactions, finish them, listen for transactions that happen outside your purchase flow, derive what the user has access to from current entitlements, test with StoreKit configuration files, and connect it to your server with App Store Server Notifications and appAccountToken.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The recipe app’s Pro subscription launches. In the first week support gets three kinds of email: “I paid but the app still says Free”, “my kid bought it with my approval yesterday and nothing happened”, and, from finance, a list of users who got refunds but still have Pro. Each one is a different mistake in how the app handles transactions.

StoreKit 2 is Apple’s Swift API for in-app purchases: products are loaded with async calls, transactions come signed by the App Store, and the current entitlements are one loop away. The API is small. What makes or breaks a subscription business is the model around it: what counts as “the user has Pro”, when it’s checked, and what happens when money moves outside your purchase button.

New to some of these? Open what you need, or skip ahead.

Basics:Kinds of in-app purchases
  • Consumable: used up and bought again, like game coins.
  • Non-consumable: bought once, kept forever, like “remove ads”.
  • Auto-renewable subscription: renews every period until cancelled, like a monthly Pro plan. Subscriptions are grouped in a subscription group; a user has at most one active subscription per group.
  • Non-renewing subscription: access for a fixed time that the user renews manually.

Apple’s rules require in-app purchase for most digital goods sold in iOS apps; the exact rules differ by region and change over time.

Basics:What is a transaction?

A transaction is the App Store’s record of one purchase or renewal: which product, when, when it expires, and whether it was refunded. In StoreKit 2 it arrives signed by Apple, so the app (and your server) can check it’s genuine. See JWT (JSON Web Token)JWT (JSON Web Token)A signed token that carries claims (who the user is, what they may do, when it expires), so a server can verify a request without a database lookup.Open in glossary →, the same signing idea used for tokens.

Part Not started

Buying and verifying

A purchase has four steps:

  1. Load the products by their ids (set up in App Store Connect). You get names and localized prices, never hard-coded “€4.99”.
  2. Call purchase(). Apple shows its own payment sheet. You get a result: success, pending or cancelled.
  3. Check the transaction is verified (signed by Apple), then give the user access.
  4. Call finish() on the transaction, which tells the App Store you delivered what was bought.

There’s a fifth thing that’s easy to forget: some transactions don’t come from your Buy button. A renewal next month, a parent approving a child’s request (Ask to Buy), a purchase made on the user’s iPad, a refund. All of these arrive in Transaction.updates, a stream you start listening to when the app launches and keep for its whole life.

Product.products(for:) returns localized products (displayPrice, subscription info including introductory offers and the group id). purchase(options:) returns .success(VerificationResult<Transaction>), .pending (Ask to Buy, Strong Customer Authentication, payment issues) or .userCancelled; a .success can still be .unverified, in which case you don’t grant access. Pass .appAccountToken(UUID) tied to your user so your server can link App Store transactions to accounts. After granting access, finish() the transaction; unfinished transactions are redelivered through Transaction.updates on every launch. That listener must start at launch (not on the paywall screen), since it carries renewals, approved Ask to Buy, purchases on other devices, revocations (refunds, Family Sharing removal) and offer-code redemptions. Test with a StoreKit configuration file (local, instant renewals, failure injection, Transaction Manager in Xcode), SKTestSession in unit tests, then sandbox accounts and TestFlight. SwiftUI’s SubscriptionStoreView and StoreView give a compliant paywall with little code.

import StoreKit

@MainActor @Observable
final class Store {
    private(set) var products: [Product] = []
    private(set) var hasPro = false
    private var updates: Task<Void, Never>?

    static let productIDs = ["com.example.recipes.pro.monthly", "com.example.recipes.pro.yearly"]

    init() {
        // Renewals, Ask to Buy approvals, refunds and purchases on other devices arrive here
        updates = Task {
            for await update in Transaction.updates {
                if case .verified(let transaction) = update {
                    await self.refreshEntitlements()
                    await transaction.finish()
                }
            }
        }
    }

    func loadProducts() async {
        products = (try? await Product.products(for: Self.productIDs))?
            .sorted { $0.price < $1.price } ?? []
    }

    enum PurchaseOutcome { case purchased, pending, cancelled }

    func buy(_ product: Product, accountID: UUID) async throws -> PurchaseOutcome {
        let result = try await product.purchase(options: [.appAccountToken(accountID)])
        switch result {
        case .success(.verified(let transaction)):
            await refreshEntitlements()
            await transaction.finish()                    // after access is granted
            return .purchased
        case .success(.unverified(_, let error)):
            throw error                                   // signed data didn't check out: no access
        case .pending:
            return .pending                               // e.g. Ask to Buy; the result comes via updates
        case .userCancelled:
            return .cancelled
        @unknown default:
            return .cancelled
        }
    }

    /// What the user has right now, computed from the App Store's signed data.
    func refreshEntitlements() async {
        var pro = false
        for await entitlement in Transaction.currentEntitlements {
            if case .verified(let transaction) = entitlement,
               Self.productIDs.contains(transaction.productID),
               transaction.revocationDate == nil {
                pro = true
            }
        }
        hasPro = pro
    }

    func restore() async throws {
        try await AppStore.sync()                         // only from an explicit "Restore Purchases" tap
        await refreshEntitlements()
    }
}
  • Transaction.updates is started in init, so it runs from app launch. Without it, the parent’s approval (and next month’s renewal) would be missed.
  • .success(.verified(...)): only verified transactions unlock Pro. An unverified one means the signature didn’t check out.
  • .pending isn’t a failure: tell the user “Waiting for approval”, and the result will arrive later through updates.
  • refreshEntitlements asks StoreKit “what does this user own right now?” instead of remembering a flag. Expired, cancelled-and-ended or refunded subscriptions simply aren’t in the list.
  • AppStore.sync() is for a Restore Purchases button. It may ask the user to sign in, so never call it automatically.
Spot the bugPro for everyone who taps Buy

Tap the line with the bug.

func buy(_ product: Product) async {
    let result = try? await product.purchase()
    switch result {
    case .success:
        UserDefaults.standard.set(true, forKey: "isPro")
    default:
        break
    }
}

Predict the output

A 12-year-old taps Subscribe in a family with Ask to Buy turned on. product.purchase() returns .pending. The app shows 'Waiting for approval' and the child closes it. An hour later the parent approves. The app only handles purchases in its buy function and has no Transaction.updates listener. What does the child see when they open the app?

Practice: a paywall with SwiftUI

StoreKit has ready-made views. SubscriptionStoreView shows the plans of a subscription group with localized prices and a subscribe button, and handles the purchase flow.

struct PaywallView: View {
    @Environment(Store.self) private var store

    var body: some View {
        SubscriptionStoreView(groupID: "21482763") {
            VStack {
                Image(systemName: "fork.knife.circle.fill").font(.system(size: 60))
                Text("Recipes Pro").font(.largeTitle.bold())
                Text("Meal plans, shopping lists and every recipe.")
            }
        }
        .storeButton(.visible, for: .restorePurchases)
        .onInAppPurchaseCompletion { _, _ in
            await store.refreshEntitlements()
        }
    }
}

Before the app is in App Store Connect, add a StoreKit Configuration File (File → New → StoreKit Configuration File), create the products there, and select it in the scheme’s Run → Options. Purchases then work in the simulator, renewals happen in minutes, and Debug → StoreKit → Manage Transactions lets you refund or expire them to test the app’s reaction.

Details that cost money

  • Prices: always displayPrice; never compare price across storefronts or build your own currency strings.
  • Introductory offers: check eligibility with product.subscription?.isEligibleForIntroOffer before advertising “1 week free”.
  • Upgrades and downgrades within a group: upgrades take effect immediately with a prorated refund, downgrades at the next renewal. The app sees the new product in entitlements; don’t grant both.
  • Family Sharing: transaction.ownershipType == .familyShared; revocations arrive when the family changes.
  • Manage and refund: .manageSubscriptionsSheet(isPresented:) and Transaction.beginRefundRequest keep users in the app instead of searching Settings.
  • Product.products(for:) → purchase(options: [.appAccountToken(userUUID)]) → .success(.verified) grant, then finish(); .unverified no access; .pending (Ask to Buy, SCA) resolves via updates.
  • Transaction.updates listener from launch: renewals, approvals, other devices, revocations, offer codes, unfinished transactions.
  • Access = Transaction.currentEntitlements (verified, not revoked), recomputed at launch and on updates; never a permanent flag.
  • AppStore.sync() only from an explicit Restore button. displayPrice, intro-offer eligibility, SubscriptionStoreView.
  • Test: StoreKit configuration file + Transaction Manager, SKTestSession, then sandbox and TestFlight.

Check this part

  1. Where does a parent’s Ask to Buy approval reach the app?

  2. Why compute Pro from Transaction.currentEntitlements instead of saving isPro = true?

  3. What happens to a transaction you never finish()?

  4. Why pass .appAccountToken(userUUID) to purchase?

Load products with Product.products(for:), buy with product.purchase(), and handle success, pending (Ask to Buy, extra authentication) and cancelled. Only trust verified transactions, update access, then call finish(). Start a Transaction.updates listener at launch, because renewals, approvals, refunds and purchases on other devices arrive there. Test with a StoreKit configuration file before the sandbox.

Part Not started

The server and the subscription lifecycle

A subscription keeps changing after the purchase, often while the app is closed:

  • It renews every month, or fails to renew because the card expired.
  • During billing retry, Apple keeps trying to charge for up to 60 days. If you turn on the grace period, the user keeps access for a few days while Apple retries.
  • The user cancels (access continues until the period ends), upgrades to yearly, or asks Apple for a refund (access should end).

If your app has accounts, for example the same Pro on iPhone and on the web, the server must know about all of this. Apple tells your server directly with App Store Server NotificationsApp Store Server NotificationsSigned messages the App Store sends to your server when a purchase or subscription changes: renewals, failures, refunds and more.Open in glossary →: a message for every renewal, failure, refund and change. The server checks Apple’s signature, finds the user by the appAccountToken you attached to the purchase, and updates their plan.

For apps with accounts or cross-platform access, the server is the source of truth. Configure App Store Server Notifications V2 (signed JWS payloads: SUBSCRIBED, DID_RENEW, DID_FAIL_TO_RENEW with GRACE_PERIOD subtype, GRACE_PERIOD_EXPIRED, EXPIRED, DID_CHANGE_RENEWAL_PREF, REFUND, REVOKE, CONSUMPTION_REQUEST and more), verify the signature chain to Apple’s root (Apple’s App Store Server Library does this), and map appAccountToken or originalTransactionId to your user. Notifications can arrive late, twice or out of order: process them idempotently, keyed by notificationUUID, and reconcile periodically with the App Store Server API (Get All Subscription Statuses, Get Transaction History), which is also how you backfill after outages. Business logic by state: subscribed → access; in grace period → access plus an in-app nudge to fix payment; billing retry without grace → no access, show the update-payment path (.manageSubscriptionsSheet); expired → no access, win-back offers; revoked (refund, family removal) → remove access immediately. The client still verifies locally (StoreKit validates JWS on device) and shows state from Product.SubscriptionInfo.status for UI, but entitlement decisions for server-side features rest on server-verified data, never on a transaction id the client sends.

// App: show the right message for the user's current state
func subscriptionMessage(for product: Product) async -> String? {
    guard let statuses = try? await product.subscription?.status else { return nil }
    for status in statuses {
        guard case .verified(let renewal) = status.renewalInfo else { continue }
        switch status.state {
        case .inGracePeriod:
            return "There’s a problem with your payment. Update it to keep Pro."
        case .inBillingRetryPeriod:
            return "Pro is paused until your payment method is updated."
        case .subscribed where renewal.willAutoRenew == false:
            return "Pro ends at the end of this period."
        default:
            continue
        }
    }
    return nil
}
// Server (Kotlin/Spring sketch): App Store Server Notifications V2
@PostMapping("/webhooks/app-store")
fun appStoreNotification(@RequestBody body: SignedPayload): ResponseEntity<Unit> {
    val notification = verifier.verifyAndDecodeNotification(body.signedPayload)   // checks Apple's signature
    if (!processed.markIfNew(notification.notificationUUID)) return ResponseEntity.ok().build()   // duplicates

    val transaction = verifier.verifyAndDecodeTransaction(notification.data.signedTransactionInfo)
    val user = users.byAppAccountToken(transaction.appAccountToken)
        ?: users.byOriginalTransactionId(transaction.originalTransactionId)

    when (notification.notificationType) {
        SUBSCRIBED, DID_RENEW -> entitlements.grant(user, until = transaction.expiresDate)
        DID_FAIL_TO_RENEW ->
            if (notification.subtype == GRACE_PERIOD) entitlements.markGracePeriod(user)
            else entitlements.markBillingRetry(user)
        EXPIRED, GRACE_PERIOD_EXPIRED -> entitlements.expire(user)
        REFUND, REVOKE -> entitlements.revoke(user, at = transaction.revocationDate)
        else -> Unit
    }
    return ResponseEntity.ok().build()
}
  • status.state tells the app where the subscription is in its lifecycle, so it can show a helpful message instead of silently locking features.
  • willAutoRenew == false means the user cancelled: they keep Pro until the period ends.
  • On the server, verifyAndDecodeNotification checks the message really comes from Apple. Without it, anyone could send “user X subscribed” to your webhook.
  • markIfNew(notificationUUID) ignores duplicates: Apple retries notifications that weren’t acknowledged.

Production puzzles

Predict the output

The server grants Pro when the app sends POST /pro { transactionId: '2000000123456789' } after a purchase, looking the id up in its own database of ids it has seen. Someone shares a valid transaction id on a forum. What happens?

Spot the bugRefunds that keep Pro

Tap the line with the bug.

func refreshEntitlements() async {
    var pro = false
    for await entitlement in Transaction.currentEntitlements {
        if case .verified(let transaction) = entitlement {
            pro = true
        }
    }
    hasPro = pro
    UserDefaults.standard.set(pro, forKey: "hasPro")
}

// At launch
hasPro = UserDefaults.standard.bool(forKey: "hasPro")

Exercisehard

Design subscription state for a cross-platform app

Recipes Pro is sold on iOS (StoreKit), Android (Google Play Billing) and the web (a payment provider). A user may subscribe on one platform and sign in on the others. Design the entitlement model and the main flows.

›

Separate where a subscription was bought from what the user is entitled to, and decide which system is the source of truth for each.

SolutionTry it yourself first
  • Model: subscriptions rows per store (store, store_subscription_id, user_id, status, expires_at, in_grace, revoked_at), and an entitlement computed per user: Pro if any subscription is active or in grace. Features check the entitlement only.
  • Linking: iOS purchases carry appAccountToken = user.uuid; Android uses obfuscatedAccountId; the web stores user_id in checkout metadata. An originalTransactionId already bound to another user is a conflict to resolve (support flow), not silently moved.
  • Updates: App Store Server Notifications V2, Google Real-time Developer Notifications and the web provider’s webhooks all go through verified, idempotent handlers that update rows; a nightly reconciliation job calls each store’s API.
  • Clients: apps ask the server for the entitlement (a signed token works offline for a while); iOS still runs a Transaction.updates listener and reports new signed transactions to the server for faster updates.
  • Double subscriptions: if a user subscribes on a second platform while active elsewhere, warn before purchase, and explain where to manage each one.
  • Refunds and revocations remove access immediately on the next entitlement check.
Exerciseeasy

Messages for every state

For each situation, say whether the user should have Pro and what the app should show: (1) the user cancelled yesterday, the period ends in 20 days; (2) the card failed and the grace period is active; (3) the card failed, no grace period, Apple is retrying; (4) Apple refunded the purchase.

›

Cancelling stops the next renewal; it doesn’t end the current period.

SolutionTry it yourself first
  1. Pro, yes. Show “Pro ends on” with the end date, and maybe a gentle reason to stay.
  2. Pro, yes. Show a banner asking to update the payment method, with a button that opens the subscription management sheet.
  3. No Pro. Explain that Pro is paused until payment is updated, with the same button. When Apple’s retry succeeds, access returns automatically through Transaction.updates.
  4. No Pro. Remove access; no special message is needed beyond the normal Free state.
  • Server is the source of truth for account-based or cross-platform access: ASSN V2 (signed JWS), verified with Apple’s chain (App Store Server Library), idempotent by notificationUUID, reconciled with the App Store Server API.
  • Link with appAccountToken (or originalTransactionId); never trust a bare transaction id from the client.
  • States: subscribed → access; grace period → access + fix-payment nudge; billing retry → no access + manage sheet; expired → win-back; revoked → remove now.
  • Client UI from Product.SubscriptionInfo.status (state, renewalInfo.willAutoRenew); recompute entitlements at launch and on updates.

Check this part

  1. A user cancels their monthly subscription today. When do they lose Pro?

  2. Why does the server verify the signature on App Store notifications?

  3. Notifications arrive twice and out of order. How should the handler behave?

  4. What should a server do when an app sends just a transaction id to unlock Pro?

Subscriptions change without the app: renewals, billing retry and grace periods, refunds, upgrades. Apps with accounts keep the truth on the server: App Store Server Notifications V2 (signed JWS) and the App Store Server API, linked to users with appAccountToken. Grant access during a grace period, prompt for payment during billing retry, revoke on refunds, and never trust a client claim without verifying Apple's signature.

Key takeaways

  • Load products for localized prices; buy, verify, grant access, then finish().
  • Listen to Transaction.updates from launch: approvals, renewals and refunds arrive there.
  • Compute access from Transaction.currentEntitlements, not a saved flag.
  • Restore only from a Restore Purchases button; test with a StoreKit configuration file.
  • Handle .pending and .unverified deliberately; attach appAccountToken.
  • For accounts, the server owns entitlements: verified, idempotent notifications plus reconciliation.
  • Map lifecycle states to access and UI: grace period, billing retry, expiry, revocation.
  • Never grant access from an unverified client claim.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.