StoreKit 2 for a free app with a one-time unlock: entitlements, refunds and restore
Sell a single non-consumable unlock in a free iPhone app with StoreKit 2: derive access from entitlements, handle refunds and Ask to Buy, and restore.
· 7 min read
- StoreKit
- In-app purchase
- Swift
A common model for a small iPhone app is to give it away and sell one thing: a “Pro” unlock, paid for once. In StoreKit terms that is a single non-consumable in-app purchase. It is the simplest product type, and the code is short. It is also easy to get subtly wrong, usually by treating the purchase as an event instead of treating access as a fact the App Store can tell you at any time.
This article builds the whole flow with StoreKit 2: loading the product, buying it, deriving access, and handling refunds, Ask to Buy, Family Sharing and restore. We checked the signatures and availability against Apple’s documentation, but we could not compile or run this code for the article, so build and test it in Xcode before shipping.
The snippets assume iOS 17 or later for @Observable and SwiftUI’s purchase action. The core calls (Transaction.currentEntitlements, Transaction.updates, AppStore.sync()) date from iOS 15.
Treat access as state, not as an event
The tempting design is to save isPro = true when the purchase succeeds. It breaks in ordinary situations:
- The user buys on their iPad and opens the app on their iPhone.
- A parent approves an Ask to Buy request an hour after the child tapped Buy.
- The user reinstalls the app, or gets a new phone.
- Apple refunds the purchase.
In all of these the purchase call in your app never returns a success, or returned one long ago. What you need is a function that answers “does this person own the unlock right now?” from StoreKit’s own records, and a way to re-run it whenever something changes.
Transaction.currentEntitlements is that source. Apple describes it as the latest transaction for each product the customer is entitled to, including one for each non-consumable. Refunded and revoked products don’t appear in it. So the rule is: don’t treat a saved flag as the truth; recompute access from current entitlements. The state starts as locked, so use hasLoaded to show a neutral state until the first check finishes, or a paying user sees the locked screen for a moment.
The store object
One object owns the product, the entitlement state and the listener:
import StoreKit
import Observation
@MainActor
@Observable
final class Store {
static let unlockID = "com.example.app.pro" // your product ID from App Store Connect
private(set) var unlock: Product?
private(set) var isUnlocked = false
private(set) var hasLoaded = false // false until the first entitlement check finishes
@ObservationIgnored private var listener: Task<Void, Never>?
init() {
listener = Task { [weak self] in
for await result in Transaction.updates {
await self?.process(result)
}
}
Task {
await loadProduct()
await refreshEntitlements()
}
}
func loadProduct() async {
unlock = try? await Product.products(for: [Self.unlockID]).first
}
func refreshEntitlements() async {
var owned = false
for await result in Transaction.currentEntitlements {
guard case .verified(let transaction) = result,
transaction.productID == Self.unlockID,
transaction.revocationDate == nil
else { continue }
owned = true
}
isUnlocked = owned
hasLoaded = true
}
}
Product.products(for:) takes a collection of product IDs and returns the products that exist and are available. A nil result means either an error (such as no network) or a product ID that doesn’t exist or isn’t ready in App Store Connect, so show a retry state rather than a dead button. The revocationDate check is belt and braces: Apple’s documentation says revoked transactions don’t appear in current entitlements, and revocationDate is the date a transaction was refunded or revoked from Family Sharing.
Create one Store for the life of the app and share it through the SwiftUI environment, so the listener never needs cancelling.
Start the listener at launch
Transaction.updates emits transactions that happen outside a purchase you started in the app: Ask to Buy approvals, offer code redemptions, purchases made in the App Store, and purchases completed on another device. Apple notes that a purchase made in the app on the same device is returned from the purchase call instead, not from updates.
Apple also says the updates listener receives unfinished transactions once, at app launch. That is why the listener is created in init, before any view appears. Start it late and you can miss them; Apple’s Transaction.unfinished sequence is there if you need to fetch unfinished transactions at other times.
extension Store {
private func process(_ result: VerificationResult<Transaction>) async {
guard case .verified(let transaction) = result else { return }
await refreshEntitlements()
await transaction.finish()
}
}
The order matters. Apple’s guidance is to call finish() after you have delivered the content, so refresh access first and finish second. If the app is killed in between, the transaction is still unfinished and arrives again at the next launch, and refreshing twice does no harm. This is the same shape of problem as idempotent payment webhooks: events arrive at least once, so the handler must be safe to run again.
Because the handler recomputes state and doesn’t flip a flag, it also covers refunds without any extra code. When a refund or revocation arrives through updates, refreshEntitlements() runs, the transaction is no longer in the entitlements, and isUnlocked goes back to false.
Buying
In SwiftUI on iOS 17 and later, a view starts a purchase with the purchase action from the environment. It returns a Product.PurchaseResult, which has three cases you must handle: success, userCancelled and pending. Put the handling in the store, so there is one place that decides what each result means:
extension Store {
enum PurchaseError: Error { case unverified }
func handle(_ purchaseResult: Product.PurchaseResult) async throws {
switch purchaseResult {
case .success(let result):
guard case .verified(let transaction) = result else {
throw PurchaseError.unverified
}
await refreshEntitlements()
await transaction.finish()
case .pending, .userCancelled:
break
@unknown default:
break
}
}
}
pending is not an error. It means the purchase needs something from somebody else, such as a parent approving an Ask to Buy request. Show a calm “waiting for approval” message and leave the app locked. If the request is approved, the transaction arrives later through Transaction.updates, and your listener unlocks the app.
The button passes whatever the action returns to the store:
import SwiftUI
import StoreKit
struct UnlockButton: View {
@Environment(\.purchase) private var purchase
@Environment(Store.self) private var store
let product: Product
var body: some View {
Button("Unlock Pro for \(product.displayPrice)") {
Task {
do {
try await store.handle(purchase(product))
} catch {
// Show an error message.
}
}
}
}
}
Create the store once, in the App, and share it with @State private var store = Store() and .environment(store) on the root view. Creating it inside a view’s own state can build several stores, each with its own listener. StoreKit also provides ProductView if you would rather not write the button yourself.
Use displayPrice for the price, because it is already formatted for the user’s storefront and currency.
What to do with an unverified transaction
Every transaction comes wrapped in a VerificationResult, either .verified or .unverified with an error. StoreKit has checked the signature on the device. An unverified result means the check failed, and you should not unlock on it.
For a low-priced unlock the simple policy above is enough: ignore unverified transactions and, in the purchase path, tell the user something went wrong. If the unlock is expensive, or unlocks something your own server pays for, validate the signed transaction on your server. Apple’s App Store Server Library has functions for verifying and decoding signed transactions.
Restore, and why you still need the button
Apple’s documentation says that in normal operation you don’t need AppStore.sync(). After a reinstall or on a new device, a fresh launch can read current entitlements immediately, because StoreKit keeps transaction information up to date. The documented use of AppStore.sync() is for the rare case when a user suspects the app isn’t showing all their purchases.
You should still ship a Restore Purchases button. App Review Guideline 3.1.1 says you should make sure you have a restore mechanism for any restorable in-app purchases, and App Review expects one. The button is a few lines:
extension Store {
func restore() async throws {
try await AppStore.sync()
await refreshEntitlements()
}
}
AppStore.sync() throws. Show a message for a real failure, but ignore StoreKitError.userCancelled, which is what you get when the user dismisses the sign-in prompt. The call can ask the user to sign in to the App Store, so make it only from a button the user presses, never at launch.
Family Sharing and refunds
If you turn on Family Sharing for the product in App Store Connect, family members get their own transactions, and the code above needs no special case. If sharing was enabled after the original purchase, Apple says family members may have to use restore to get access, which is one more reason to ship the button. Apple’s documentation says you can’t turn Family Sharing off for a product once it is enabled, so decide before you ship. Product.isFamilyShareable tells you at runtime whether to mention it in your UI.
Access for family members lasts only while sharing is on. If the purchaser leaves the family group, stops sharing or gets a refund, the transaction is revoked. Because you derive access from currentEntitlements and refresh whenever Transaction.updates fires, revocation takes effect while the app is running, or at the next launch, without extra code. That is the payoff of the state-not-event design.
Testing
- StoreKit configuration file in Xcode. Add a
.storekitfile with your product and set it as the active configuration in the scheme. Purchases then run locally without the App Store. Use Xcode’s transaction manager (Debug > StoreKit > Manage Transactions) to refund a purchase, approve or decline an Ask to Buy request (turn Ask to Buy on in the.storekitfile’s settings first), and check your listener unlocks and re-locks the app. Menu names can change between Xcode versions. - Sandbox account. The local environment can’t prove your App Store Connect setup is right. Test once with a sandbox account on a real device, including a reinstall and the restore button.
Purchases, entitlements and review requirements are part of shipping an app, not an afterthought. We build and launch native apps, including App Store submission; see our iOS app development service.