The problem
Most subscription bugs come from the same few mistakes: a purchase that completes on another device and never unlocks this one, a renewal the app misses because nothing was listening, a isPro flag in UserDefaults that survives a refund. StoreKit 2 removes most of the reasons for these bugs, but only if you wire it the way Apple’s documentation expects. This guide builds a small, complete subscription layer for an iOS 17 app in Swift 6, then covers the parts that live outside the app: StoreKit testing, App Store Server Notifications V2 and the App Store Server API.
Set up the products first
Everything starts in App Store Connect. Every auto-renewable subscription must belong to a subscription group, and a person can hold only one subscription per group at a time. Apple’s subscriptions page recommends a single group for most apps. Inside the group you rank subscriptions by level, which decides what counts as an upgrade (immediate, prorated refund), a downgrade (takes effect at the next renewal) or a crossgrade.
Keep product identifiers boring and stable, such as pro.monthly and pro.yearly. Josh Holtz at RevenueCat points out in his StoreKit 2 tutorial that hard-coded identifiers mean an app update every time you change your catalog, so serving the list from a remote config is worth considering once you start experimenting with prices.
One store object, owned by the app
The store below is an @Observable class isolated to the main actor. It loads products, listens for transactions, and publishes the set of product IDs the person is currently entitled to. Views read from it; nothing else stores purchase state.
import StoreKit
import Observation
@MainActor
@Observable
final class SubscriptionStore {
static let productIDs = ["pro.monthly", "pro.yearly"]
private(set) var products: [Product] = []
private(set) var entitledProductIDs: Set<Product.ID> = []
private var updatesTask: Task<Void, Never>?
var isSubscribed: Bool { !entitledProductIDs.isEmpty }
init() {
updatesTask = Task { [weak self] in
for await result in Transaction.updates {
await self?.handle(result)
}
}
}
func loadProducts() async throws {
products = try await Product.products(for: Self.productIDs)
.sorted { $0.price < $1.price }
}
func refreshEntitlements() async {
var entitled: Set<Product.ID> = []
for await result in Transaction.currentEntitlements {
guard case .verified(let transaction) = result,
transaction.revocationDate == nil else { continue }
entitled.insert(transaction.productID)
}
entitledProductIDs = entitled
}
func process(_ result: Product.PurchaseResult) async {
if case .success(let verification) = result {
await handle(verification)
}
}
private func handle(_ result: VerificationResult<Transaction>) async {
guard case .verified(let transaction) = result else { return }
await refreshEntitlements()
await transaction.finish()
}
}
The store is created once in the App struct and lives as long as the process, so it does not need a deinit that cancels the task. Create it and kick off the initial load like this:
import SwiftUI
@main
struct ExampleApp: App {
@State private var store = SubscriptionStore()
var body: some Scene {
WindowGroup {
ContentView()
.environment(store)
.task {
await store.refreshEntitlements()
try? await store.loadProducts()
}
}
}
}
In a real app, surface the loadProducts() error in the paywall instead of discarding it with try?; a paywall with no products and no message is the most common App Review complaint about subscription apps.
Why the listener starts in init
Apple’s updates documentation is explicit: create the task that iterates Transaction.updates as soon as the app launches. The sequence delivers Ask to Buy approvals, offer code redemptions, App Store purchases, renewals and purchases made on the person’s other devices. If the app has unfinished transactions, the listener receives them once, right after launch. Start the task late and you can miss them for that session.
Purchases made inside the app on the same device do not arrive through updates. They come back as the result of the purchase call, which is why process(_:) exists.
Why access comes from currentEntitlements
Transaction.currentEntitlements (iOS 15 and later) emits the latest transaction for each non-consumable, each auto-renewable subscription whose renewal state is subscribed or inGracePeriod, and each non-renewing subscription. Refunded and revoked products drop out of it by themselves. Holtz makes the point that you do not need your own offline cache for this: StoreKit keeps the signed data on the device.
That property is the whole reason to avoid a persisted isPro flag. Recompute entitlements at launch, after every handled transaction, and when the app returns to the foreground. If you need the state in a widget or extension, write the result to an App Group container after you recompute it, and treat that copy as a cache, never as the source of truth.
Finish transactions after you unlock
Call finish() only after the content is available to the person. An unfinished transaction is redelivered at the next launch, which is the safety net you want if the app crashes between payment and unlock. In the store above, entitlements are refreshed first and the transaction is finished second.
Buying from SwiftUI
On iOS 17 and later, read the purchase environment value instead of calling product.purchase() directly. SwiftUI then knows which scene presents the payment sheet, which matters on iPad with several windows open.
import StoreKit
import SwiftUI
struct PlanButton: View {
@Environment(SubscriptionStore.self) private var store
@Environment(\.purchase) private var purchase
@State private var errorMessage: String?
let product: Product
var body: some View {
Button {
Task {
do {
let result = try await purchase(product)
await store.process(result)
} catch {
errorMessage = error.localizedDescription
}
}
} label: {
VStack(alignment: .leading) {
Text(product.displayName)
Text(product.displayPrice).font(.headline)
}
}
.alert("Purchase failed", isPresented: Binding(
get: { errorMessage != nil },
set: { if !$0 { errorMessage = nil } }
)) {
Button("OK", role: .cancel) {}
} message: {
Text(errorMessage ?? "")
}
}
}
Product.PurchaseResult has three cases you care about. .success carries a VerificationResult<Transaction>. .pending means the purchase needs approval, for example Ask to Buy or Strong Customer Authentication, and the eventual transaction will arrive through updates. .userCancelled needs no UI at all; do not show an error for it.
Restore
Give people a visible way to restore. With StoreKit 2 the entitlements are already on the device, so the button only needs to call AppStore.sync() and then refresh entitlements. Holtz recommends keeping the button even though most restores now happen automatically, because people expect it and Apple’s sign-up screen requirements mention it.
Reading subscription status
Entitlement tells you whether to unlock. Status tells you why, and what to say. Product.SubscriptionInfo.Status exposes a state (subscribed, expired, inBillingRetryPeriod, inGracePeriod, revoked) and signed renewalInfo with willAutoRenew and the product the person will renew into.
import StoreKit
enum RenewalSummary: Sendable {
case renewing(Product.ID)
case cancelled(expires: Date?)
case billingProblem
case none
}
func renewalSummary(for product: Product) async throws -> RenewalSummary {
guard let statuses = try await product.subscription?.status else { return .none }
for status in statuses {
guard case .verified(let renewal) = status.renewalInfo,
case .verified(let transaction) = status.transaction else { continue }
switch status.state {
case .inBillingRetryPeriod, .inGracePeriod:
return .billingProblem
case .subscribed:
return renewal.willAutoRenew
? .renewing(renewal.autoRenewPreference ?? transaction.productID)
: .cancelled(expires: transaction.expirationDate)
default:
continue
}
}
return .none
}
Use this for the account screen: “Renews as Pro Yearly”, “Ends on 12 January” or “There’s a problem with your payment method”. Apple’s subscriptions page recommends turning on Billing Grace Period (3, 16 or 28 days) so people keep access while the App Store retries a failed charge; billing retry itself runs for up to 60 days.
SubscriptionStoreView when you want less code
SubscriptionStoreView (iOS 17 and later) renders a complete, localized subscription store from a group ID. It orders options by their rank in the group, shows the eligible introductory offer, and adds Terms of Service and Privacy Policy buttons from your App Store Connect metadata.
import StoreKit
import SwiftUI
struct ProStoreView: View {
@Environment(SubscriptionStore.self) private var store
let groupID: String
var body: some View {
SubscriptionStoreView(groupID: groupID) {
VStack(spacing: 8) {
Image(systemName: "sparkles")
.font(.largeTitle)
.accessibilityHidden(true)
Text("Example Pro")
.font(.title.bold())
Text("Unlimited projects, sync and export.")
.foregroundStyle(.secondary)
}
.padding()
}
.subscriptionStoreControlStyle(.picker)
.storeButton(.visible, for: .restorePurchases)
.subscriptionStorePolicyDestination(
url: URL(string: "https://example.com/terms")!,
for: .termsOfService
)
.subscriptionStorePolicyDestination(
url: URL(string: "https://example.com/privacy")!,
for: .privacyPolicy
)
.onInAppPurchaseCompletion { _, result in
if case .success(let purchaseResult) = result {
await store.process(purchaseResult)
}
}
}
}
The view still needs your transaction listener; it does not replace the store object. It is a good default for a first release. Many teams move to a custom paywall later because they want to test layouts and copy, which SubscriptionStoreView restricts by design.
Testing with a StoreKit configuration file
You can exercise almost all of the above without App Store Connect. A StoreKit configuration file (File > New > File, then StoreKit Configuration File) describes products, groups, prices and offers locally. Select it in the scheme’s Run options and the app talks to Xcode’s local store instead of the sandbox.
Antoine van der Lee recommends creating the file with the “Sync this file with an app in App Store Connect” option, which pulls your real products, as he explains in Faster StoreKit testing. His main caveat: you cannot turn syncing on for an existing file, so create a new synced file and keep older hand-made files only for scenarios they cover.
Once the file is active, open Debug > StoreKit > Manage Transactions to see each purchase. From there you can refund a transaction, expire a subscription, approve or decline Ask to Buy, and trigger billing retry. The editor’s settings let you speed up renewals so a monthly plan renews every few seconds, and enable failure simulation for specific StoreKit calls. Walk through, at minimum: first purchase, renewal while the app is running, renewal while it is closed, refund, billing failure into grace period, and upgrade from monthly to yearly. Each should change what refreshEntitlements() returns without a relaunch.
Before release, repeat the important paths in the sandbox with a Sandbox Apple Account, because only the sandbox exercises the real App Store payment sheet and server notifications.
The server side
An app with no account system and a single platform can run entirely on the device. You need a server when access must follow the person to the web or Android, when you want revenue analytics you control, or when you send offers based on churn.
App Store Server Notifications V2
Set a production and a sandbox URL in App Store Connect under App Information. The App Store then POSTs a signed payload for each event. The notificationType values you will handle first:
| Event | Type and subtype |
|---|---|
| First subscription in a group | SUBSCRIBED / INITIAL_BUY |
| Resubscribe after expiry | SUBSCRIBED / RESUBSCRIBE |
| Successful renewal | DID_RENEW |
| Auto-renew turned off | DID_CHANGE_RENEWAL_STATUS / AUTO_RENEW_DISABLED |
| Renewal failed, grace period on | DID_FAIL_TO_RENEW / GRACE_PERIOD |
| Expired after cancelling | EXPIRED / VOLUNTARY |
| Refund | REFUND |
| Offer redeemed on an active subscription | OFFER_REDEEMED |
Verify every payload before you trust it. Apple’s App Store Server Library is open source in Swift, Java, Python and Node, and includes verifyAndDecodeTransaction and verifyAndDecodeRenewalInfo along with an API client that creates the JWT for you.
Holtz lists two traps worth designing for. The same purchase can reach your server twice, once from the app and once from a notification, so make the handler idempotent on transactionId. And Apple retries failed deliveries only a limited number of times, so keep a periodic job that calls the notification history endpoint to fill gaps.
App Store Server API basics
The App Store Server API is a REST API authorized with a JWT signed by an in-app purchase key from App Store Connect. The calls most apps need:
- Get Transaction Info to look up one transaction by ID, for example the ID your app sends after a purchase.
- Get All Subscription Statuses to read the current state of every subscription in the person’s groups, including
eligibleWinBackOfferIdsin the renewal info. - Get Transaction History to rebuild a customer’s full record.
- Request a Test Notification to check your endpoint, which arrives as type
TEST.
Send the transaction’s appAccountToken from the app if you have your own user accounts. Set it as a purchase option with a UUID you store against the user, and it comes back in every signed transaction and notification, which makes matching purchases to accounts trivial.
Traps
- Starting the listener in a view. If the
Transaction.updatestask lives in a view’s.task, it stops when that view disappears. Own it in an object created by theApp. - Showing errors for cancellations.
.userCancelledis a normal outcome. - Unlocking on unverified transactions. StoreKit verifies the JWS for you; treat
.unverifiedas no access. - Forgetting Family Sharing. If you enable it, and Apple notes the choice cannot be undone, family members appear in
currentEntitlementswith anownershipTypeof.familyShared. Decide whether your copy should say “your subscription” to them. - Leaving the StoreKit configuration file selected in a release scheme. It only applies when running from Xcode, but a shared scheme with a stale file confuses the next developer. Keep it in a Debug-only scheme.
- Trusting local time. Compare
expirationDateonly for display. Access decisions come fromcurrentEntitlements, which already accounts for the App Store’s clock.
Checklist
| Step | Done when |
|---|---|
| Group and levels | Monthly and yearly in one group, ranked deliberately |
| Listener | Transaction.updates task starts in the app’s root object |
| Entitlements | Access derived from currentEntitlements at launch, after transactions and on foreground |
| Finish | Every verified transaction finished after unlock |
| Purchase | Uses @Environment(\.purchase), handles .pending and .userCancelled |
| Restore | Visible button calling AppStore.sync() |
| Status | Account screen explains renewal, cancellation and billing problems |
| Testing | Synced StoreKit file plus Transaction Manager scenarios, then sandbox |
| Server | Notifications V2 verified with the App Store Server Library, idempotent on transaction ID |
Sources and further reading
- updates Apple Developer Documentation
- currentEntitlements Apple Developer Documentation
- SubscriptionStoreView Apple Developer Documentation
- purchase (EnvironmentValues) Apple Developer Documentation
- notificationType Apple Developer Documentation
- Simplifying your implementation by using the App Store Server Library Apple Developer Documentation
- Auto-renewable subscriptions Apple Developer
- iOS in-app subscription tutorial with StoreKit 2 and Swift Josh Holtz, RevenueCat
- Faster StoreKit testing by syncing in-app purchase products Antoine van der Lee, SwiftLee