A photographer bought the yearly plan as the train entered a tunnel. The App Store completed the transaction. The system then reclaimed the app, and the await on product.purchase() never returned to update the paywall. On the next launch the screen consulted a UserDefaults flag, found nothing, and asked her to buy again.

Nothing failed. StoreKit had the transaction, verified and ready. The app had simply decided that access was something it remembered rather than something it derived.

Two contracts meet in every purchase, and they have different owners. The App Store supplies signed evidence that a transaction happened. The app turns verified evidence into access or into delivered content. Most StoreKit bugs come from letting one entry point, the purchase sheet, act as if it were the only one.

There are four ways a transaction reaches you

A transaction can arrive through:

  • the result of product.purchase() on this device, in this process;
  • Transaction.updates, for purchases made on another device, renewals, Ask to Buy approvals, refunds, and purchases whose callback this process never saw;
  • Transaction.unfinished, for transactions a previous process received but never finished;
  • Transaction.currentEntitlements, the App Store’s current answer to “what does this customer own?”

The purchase callback is the least reliable of the four, because it depends on the process surviving the purchase. So access is never set from the callback alone. Every path feeds the same derivation, and the derivation reads the evidence.

Derive access from evidence

One owner, created at app launch, outliving every window:

SwiftGitHub
import Foundation
import Observation
import StoreKit

enum Access: Equatable, Sendable {
    case checking
    case subscribed(expires: Date?, inGrace: Bool)
    case notSubscribed
}

@MainActor
@Observable
final class EntitlementStore {
    private(set) var access: Access = .checking
    private let productIDs: Set<String>
    private var updates: Task<Void, Never>?

    init(productIDs: Set<String>) {
        self.productIDs = productIDs
    }

    func start() {
        guard updates == nil else { return }
        updates = Task { [weak self] in
            for await result in Transaction.updates {
                await self?.handle(result)
            }
        }
        Task {
            for await result in Transaction.unfinished {
                await handle(result)
            }
            await refresh()
        }
    }

    func refresh() async {
        var best: Access = .notSubscribed
        var latestExpiry = Date.distantPast
        for await result in Transaction.currentEntitlements {
            guard case .verified(let transaction) = result,
                  productIDs.contains(transaction.productID),
                  transaction.revocationDate == nil else { continue }
            let expiry = transaction.expirationDate ?? .distantFuture   // nil: never expires
            guard expiry >= latestExpiry else { continue }
            latestExpiry = expiry
            let inGrace = transaction.expirationDate.map { $0 < .now } ?? false
            best = .subscribed(expires: transaction.expirationDate, inGrace: inGrace)
        }
        access = best
    }

    func handle(_ result: VerificationResult<Transaction>) async {
        guard case .verified(let transaction) = result else {
            return          // never grant from unverified evidence; log and move on
        }
        await refresh()
        await transaction.finish()
    }
}

The interface starts in .checking, not .notSubscribed. A paywall shown during the first few hundred milliseconds of launch, before the evidence has been read, is the original bug with a faster train.

Unverified results take an error path and grant nothing. A revoked transaction (a refund, a family-sharing change) disappears from the derivation the next time it runs, because Transaction.updates delivers the revocation and handle re-derives. There is no separate “remove access” code to forget.

Grace is evidence too. For auto-renewable subscriptions, Billing Grace Period keeps the entitlement in currentEntitlements while Apple retries the payment. When a product needs a precise answer (which level in a subscription group, whether the customer is in grace or retry), read Product.SubscriptionInfo.Status for the group and pick the status that grants the highest access. The first element of that array may belong to a family member’s entitlement or another level.

Finish after delivery, never before

finish() tells the App Store that the app has delivered what was bought. Until then, StoreKit will keep presenting the transaction through Transaction.unfinished and Transaction.updates. That redelivery is the recovery mechanism, and finishing early switches it off.

For subscriptions and non-consumables, delivery is the derivation above. For consumables, delivery is a credit, and redelivery is a threat: a crash after crediting and before finishing will present the same transaction again. The transaction ID is the deduplication key, committed in the same durable write as the credit:

SwiftGitHub
actor CreditLedger {
    private var processed: Set<UInt64> = []
    private(set) var balance = 0

    /// Credits the transaction once. Returns the balance either way.
    func credit(transactionID: UInt64, amount: Int) -> Int {
        if processed.insert(transactionID).inserted {
            balance += amount
        }
        return balance
    }
}

func deliverCredits(
    _ result: VerificationResult<Transaction>,
    ledger: CreditLedger,
    amount: Int
) async throws {
    let transaction = try result.payloadValue
    _ = await ledger.credit(transactionID: transaction.id, amount: amount)
    await transaction.finish()
}

Every path that can deliver a consumable, including updates and unfinished, routes it here by productType. The handle method above is for subscriptions; given a consumable, it would finish the transaction without crediting anything.

The actor stands in for the durable store. In the real app the processed ID and the credit are one transaction in the database, or one request to your server, which then owns the deduplication. Persisting them separately reopens the gap the actor closes.

If delivery fails because your server is unavailable, do not finish. The transaction is valid; your system is not ready. Leaving it unfinished means StoreKit will hand it back, and the customer will not have paid for nothing.

Let pending, grace, and restore look different

SwiftGitHub
func buy(_ product: Product, store: EntitlementStore) async throws -> String {
    switch try await product.purchase() {
    case .success(let verification):
        await store.handle(verification)
        return "Purchase complete."
    case .pending:
        return "Waiting for approval. You’ll get access as soon as it’s approved."
    case .userCancelled:
        return ""
    @unknown default:
        return ""
    }
}

A pending purchase, under Ask to Buy or a payment that needs action, is not a failure, and the screen should not treat it as one. The approval arrives later through Transaction.updates, possibly when this screen no longer exists, which is precisely why the owner listens at app scope.

A renewal in billing retry, with grace, may justify a quiet message about the payment method while the customer keeps access. Losing access the moment a card expires is a policy decision, and Billing Grace Period exists so you do not have to make it.

Restore is an explicit action. AppStore.sync() may ask the customer to authenticate. When it returns, run the same refresh() that launch runs, and say what was found: “Your yearly plan is active,” or “No purchases found for this Apple Account.” A permanent spinner, or a second purchase prompt, teaches the customer that restore does not work. With universal purchase configured, the iPhone and Mac apps share one entitlement, and both deserve a test under the same Apple Account.

Verify the interrupted path

StoreKit Testing in Xcode makes the tunnel reproducible:

  • complete a purchase, terminate the app before finish(), relaunch, and assert that access resolves from unfinished without a second purchase;
  • for a consumable, deliver, crash before finishing, relaunch, and assert the balance was credited once;
  • approve an Ask to Buy purchase while the paywall is closed;
  • refund a transaction and assert access disappears without a relaunch;
  • expire a subscription into grace, then into expiry;
  • restore on a second device.

Then repeat the account and cross-device cases in Sandbox, where the timing is real.

What to ask of your own code

  • Is there any place where access is stored as a flag rather than derived from currentEntitlements?
  • Does a single app-scoped owner listen to Transaction.updates from launch, independent of any window?
  • Is finish() called only after delivery has been committed?
  • Is consumable delivery idempotent on the transaction ID?
  • What does the paywall show before the first derivation completes?

The photographer does not care which of the four paths brought her purchase home. She cares that the app, opened after the tunnel, already knows. That knowledge was never the app’s to remember. It was the App Store’s to prove.

References

If this edition sharpened your next review, you can buy me a coffee.