1 minute read

How to implement in-app purchases with StoreKit

StoreKit is Apple’s framework for selling digital goods inside an iOS app. It can unlock a premium feature, remove advertising, grant a consumable item, or start an auto-renewing subscription without sending the buyer to a separate checkout screen. StoreKit 2 centres the work on products, transactions, and entitlements.

A reliable implementation needs more than a buy button. The app must load the correct catalogue, verify transactions, persist the right access, recover interrupted purchases, and handle refunds and renewals. Those jobs matter in Australia, where App Store prices are shown in AUD and include GST, and buyers commonly expect a quick Face ID or Touch ID confirmation.

Prepare products and the StoreKit catalogue

Begin in App Store Connect, where you create an in-app purchase and give it a stable, reverse-DNS identifier such as com.yourcompany.app.premium. Choose a product type early: consumables provide a spendable balance, non-consumables grant lasting access, and subscriptions renew automatically. The identifier in your code must match App Store Connect exactly.

In the app, request products by identifier and expose their localised names and prices to the interface. This model uses SwiftUI’s published properties, but the same StoreKit calls work with UIKit.

import StoreKit
import SwiftUI

enum ProductID {
    static let premium = "com.example.app.premium"
}

@MainActor
final class PurchaseModel: ObservableObject {
    @Published private(set) var products: [Product] = []
    @Published private(set) var loadError: String?

    func loadProducts() async {
        do {
            products = try await Product.products(for: [ProductID.premium])
            loadError = products.isEmpty ? "Product unavailable" : nil
        } catch {
            loadError = error.localizedDescription
        }
    }
}

An empty result does not always mean a coding error: the product may be unavailable in the current storefront, awaiting approval, or missing from the signed configuration. For a content-led product, study how The Blushing Mama frames its audience and brand before designing the paywall, then state exactly which benefits the StoreKit product unlocks.

Complete purchases with verified transactions

Calling purchase() opens Apple’s payment sheet. The result can be successful, cancelled, or pending, so never treat a button tap as a completed sale. Check the verification result before granting anything.

enum PurchaseError: Error {
    case failedVerification
}

func verify<T>(_ result: VerificationResult<T>) throws -> T where T: Transaction {
    switch result {
    case .verified(let transaction):
        return transaction
    case .unverified:
        throw PurchaseError.failedVerification
    }
}

func buy(_ product: Product) async {
    do {
        let result = try await product.purchase()
        switch result {
        case .success(let verification):
            let transaction = try verify(verification)
            await grant(transaction)
            await transaction.finish()
        case .pending:
            break
        case .userCancelled:
            break
        @unknown default:
            break
        }
    } catch {
        print(error)
    }
}

grant should save a consumable balance or enable the purchased entitlement before finish() is called. Finishing tells StoreKit the transaction has been delivered; finishing first can lose a consumable if the app crashes immediately afterwards. A successful client purchase already includes signed transaction data, but a backend that grants expensive digital goods should also validate through Apple’s server tools. That distinction is especially useful when a purchase unlocks another Apple-platform feature; iOS development notes can provide context for the surrounding app while the entitlement contract remains unchanged.

A pending result commonly means payment or family approval is still required. Keep the purchase flow usable, show an appropriate status, and do not grant access yet. The approved purchase can arrive later through Transaction.updates, so the same entitlement path should handle it.

Restore access and react to subscription changes

Transaction.currentEntitlements is the best starting point for restoring non-consumables and active subscriptions. It represents the signed transactions that currently justify access, rather than a local flag that may have become stale.

var unlockedProductIDs = Set<String>()

for await result in Transaction.currentEntitlements {
    guard let transaction = try? verify(result),
          transaction.revocationDate == nil else {
        continue
    }

    unlockedProductIDs.insert(transaction.productID)
}

Start a listener as soon as the app launches because transactions can arrive later, including renewals, refunds, interrupted purchases, and purchases approved outside the original screen. Store the returned task strongly so the listener stays alive.

private var transactionListener: Task<Void, Never>?

transactionListener = Task {
    for await result in Transaction.updates {
        guard let transaction = try? verify(result) else {
            continue
        }

        await apply(transaction)
        await transaction.finish()
    }
}

Apply changes before finishing: remove access when a transaction is revoked, refresh an active subscription, or deduct only a consumable that the server has confirmed. Record transaction identifiers so a redelivered consumable is not deducted twice. Consumables differ from durable entitlements and should not be restored from currentEntitlements; maintain a server-side balance when reliability matters. For cross-device identity, send a stable appAccountToken during purchase and associate it with your user record.

In Australia, a younger buyer may have an Ask to Buy request sent through Family Sharing. The purchase stays pending until a parent or guardian approves it, so the app needs clear status feedback rather than an endless spinner. StoreKit delivers the approved transaction through the transaction updates sequence, allowing the same entitlement path to handle it. If a subscription includes an introductory offer, inspect its subscription status for renewal information rather than assuming the first transaction represents ordinary billing.

Design the purchase experience for Australia

Use product.displayPrice and product.displayName, never a hard-coded currency string. Australian storefront prices are denominated in AUD, and GST is included in the displayed price for eligible digital purchases. Apple applies the regional pricing and tax treatment; adding another ten per cent in your checkout would be wrong. A buyer may casually say a feature costs “ten bucks”, but the purchase button should still show Apple’s exact local amount.

Keep confirmation fast and familiar. Most Australian iPhone users will approve through Face ID, Touch ID, or a device passcode, so avoid extra forms between the payment sheet and the purchase. Offer a clear explanation before payment, show the product name and price together, and make cancellation harmless. If access is restored automatically, explain that rather than making the buyer search through menus. For subscriptions, direct buyers to their Apple Account subscription settings instead of attempting to manage billing inside the app.

Refunds and connectivity need plain language too. Apple’s Report a Problem route is the normal starting point for requesting a refund, while the Australian Consumer Law may provide additional rights for faulty digital services. Do not promise automatic refunds for every situation. A user opening the app on a ferry in Sydney Harbour or a tram in central Melbourne may briefly lose connectivity, so keep unfinished purchases recoverable and use transaction updates rather than blocking on a network request.

Test the complete lifecycle before release

Use three layers of testing. An Xcode StoreKit configuration file gives fast local control over products, interruption, and renewal scenarios. A sandbox App Store account exercises Apple’s servers, regional pricing, sandbox payment, Ask to Buy, and test renewals. Production testing provides final confidence, but it should never be the first place a new purchase flow is tried.

Choose behaviour that matches what the buyer purchased before writing the interface.

Product type Access after purchase Persistence rule Main edge case
Consumable Temporary balance or item Store the balance; do not restore it from current entitlements Crash before finishing can redeliver the transaction
Non-consumable Permanent feature unlock Restore it from current entitlements Refund or revoked transaction
Auto-renewing subscription Access while active Refresh it from current entitlements and transaction updates Renewal, cancellation, billing retry, or refund
Non-renewing subscription Access for a fixed period Persist the expiry with the transaction Expiry instead of renewal

A StoreKit configuration can simulate Ask to Buy, an interrupted purchase, or a pending request, but it does not prove that production App Store Connect settings are correct. Check the product’s availability, price points, review screenshot, and privacy details there. If purchases alter backend access, use App Store Server Notifications and the server validation workflow instead of trusting a client callback.

Before release, test success, cancellation, a declined or pending payment, app termination during purchase, reinstall, refund, and subscription renewal. Measure purchase conversion and failures by product and storefront without logging sensitive transaction data. Roll out gradually and watch both the transaction listener and backend reconciliation logs. Your next concrete step is to create one StoreKit configuration file for a real premium product, run a successful purchase and an interrupted purchase in Xcode, and record the resulting entitlement after each transaction before adding more products.

Updated: