Buying and verifying
A purchase has four steps:
- Load the products by their ids (set up in App Store Connect). You get names and localized prices, never hard-coded “€4.99”.
- Call
purchase(). Apple shows its own payment sheet. You get a result: success, pending or cancelled. - Check the transaction is verified (signed by Apple), then give the user access.
- 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.updatesis started ininit, 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..pendingisn’t a failure: tell the user “Waiting for approval”, and the result will arrive later throughupdates.refreshEntitlementsasks 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.
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
}
}Hint: What's inside .success, and what happens to the transaction afterwards?
Three problems:
.successcarries aVerificationResult, which can be.unverified. This code grants Pro without checking it.- The transaction is never finished, so StoreKit redelivers it on every launch, and there’s nothing listening.
isProinUserDefaultsnever turns off. When the subscription expires or is refunded, the flag staystrue.
Check verification, finish the transaction, and compute access from Transaction.currentEntitlements (as in the store above) rather than storing a flag forever.
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?
The approval creates a transaction after purchase() returned. StoreKit delivers it through Transaction.updates, and keeps it unfinished until someone handles it. With no listener, the family paid and the app doesn't know. currentEntitlements would include it, which is another reason to compute access from entitlements at launch and to start the listener there.
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 comparepriceacross storefronts or build your own currency strings. - Introductory offers: check eligibility with
product.subscription?.isEligibleForIntroOfferbefore 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:)andTransaction.beginRefundRequestkeep users in the app instead of searching Settings.
Product.products(for:)→purchase(options: [.appAccountToken(userUUID)])→.success(.verified)grant, thenfinish();.unverifiedno access;.pending(Ask to Buy, SCA) resolves via updates.Transaction.updateslistener 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
Where does a parent’s Ask to Buy approval reach the app?
Why compute Pro from Transaction.currentEntitlements instead of saving isPro = true?
What happens to a transaction you never finish()?
Why pass .appAccountToken(userUUID) to purchase?