StoreKit 2 In-App Subscription Tutorial for Swift and SwiftUI
This guide walks through a working SwiftUI subscription flow built on StoreKit 2, from App Store Connect product setup to entitlement checks, restore behavior, and the server-side alternative. It is written for iOS developers who already know Swift and want a concrete path from a paywall button to a correctly unlocked feature.
What you are building
The sample app sells three products: a monthly subscription, a yearly subscription, and a lifetime unlock. The paywall lists them, a tap starts a purchase, and a successful verified transaction unlocks the pro experience. The same code listens for transactions that happen outside the app, keeps entitlements current when the device is offline, and exposes a Restore Purchases button.
Before writing any StoreKit code, decide which product types you need. Apple defines four in-app purchase categories:
- Consumables can be bought repeatedly and in quantity, such as lives, gems, boosts, or tips.
- Non-consumables are bought once and do not expire, such as a permanent feature unlock or a cosmetic item.
- Auto-renewable subscriptions charge on a recurring basis until the customer cancels or a billing problem occurs.
- Non-renewing subscriptions grant access for a limited period and require the customer to resubscribe manually.
That distinction drives both App Store Connect configuration and the entitlement logic you write later.
App Store Connect setup
Products must exist before the app can fetch them. App Store Connect separates the work into two areas: In-App Purchases for consumables and non-consumables, and Subscriptions for auto-renewable and non-renewing products. Subscriptions live in their own area because their configuration is more involved.
Two administrative items must be completed before selling anything: bank information must be set up, and the Paid App agreement must be signed.
For a subscription, the sequence is: open Subscriptions, create a Subscription Group, add a localization for that group, create the subscription with a reference name and product ID, then fill in duration, price, localization, and review information. For a consumable or non-consumable, open In-App Purchases, create the item, choose its type, set the reference name and product ID, then complete price, localization, and review details.
Local testing with a StoreKit configuration file
You do not need App Store Connect to develop locally. Since Xcode 13, a StoreKit configuration file can drive the whole in-app purchase workflow. That makes it possible to test purchase flows in the simulator, in unit and UI tests, without a network connection, and against edge cases that are hard to reproduce in the sandbox — failures, renewals, billing issues, promotional offers, and introductory offers.
To create one: choose File > New > File in Xcode, filter for storekit, select StoreKit Configuration File, name it, optionally check the box to sync with an app in App Store Connect, and save. Xcode 14 can sync the file with App Store Connect so products do not have to be added by hand; otherwise add products manually with the + button and supply a reference name, product ID, price, and at least one localization.
Creating the file is not enough. Select it in the Xcode scheme under Run > Options > StoreKit Configuration. Because switching between the configuration file and the sandbox environment is tedious, duplicating the scheme for StoreKit testing is a practical habit.
Step 1: List products
Fetching products takes very little code: import StoreKit, define the product identifiers, and call the product lookup API. The identifiers must match what exists in the StoreKit configuration file or App Store Connect. The result is an array of product objects that carry the display name and display price needed by the paywall buttons.
In the sample, the identifiers are pro_monthly, pro_yearly, and pro_lifetime. The SwiftUI view keeps the fetched products in state and renders a button per product inside a task that loads them when the view appears.
Hardcoding identifiers is fine for a demo but poor for production. Changing a hardcoded list requires an app update, and users who have not enabled automatic updates may keep seeing an outdated set of products. Serving the product list from a remote source avoids that.
Step 2: Purchase and read the result
Calling purchase on a product starts the transaction. A thrown error means the purchase did not go through, but the absence of an error does not mean it succeeded. The result is an enum with several cases, and each one needs a deliberate response.
The purchase result table below explains what each outcome means. Read it as a decision map: only a verified success should unlock content, a pending result needs to wait for later confirmation, and an unverified success should not be trusted blindly.
Step 3: Move purchase logic out of the view
Once the end-to-end flow works, the purchasing code should leave the SwiftUI view. A dedicated purchase manager object can own product loading and purchasing, and the app can create it once and pass it down as an environment object so every view shares the same instance. Because the manager is observable, views refresh automatically when its published properties change.
This refactor does not change behavior, but it creates the right place for entitlement logic, transaction observation, and extension sharing that follow.
Step 4: Unlock features from entitlements
Feature unlocking should be based on current entitlements, not on the memory of a single purchase. The current entitlements sequence returns active transactions: one per non-consumable, the latest transaction for each active auto-renewable subscription, the latest transaction for each non-renewing subscription, and any unfinished consumable.
The purchase manager iterates that sequence, skips unverified results, inserts product identifiers whose transaction has no revocation date, and removes identifiers that were revoked. The resulting set answers a simple question: does this user currently own pro?
Refresh that set at three moments: when the app starts, after a verified purchase, and whenever the transaction updates sequence emits a change. The last one covers renewals, cancellations, revocations, and purchases made on another device.
Step 5: Offline behavior
Current entitlements fetch the latest transactions when the device is online and fall back to locally cached data when it is not. Transactions are also pushed to the device while online, so a user who later goes offline still sees the correct state. No custom caching layer is required for this part of the flow.
Step 6: Restore purchases
StoreKit keeps subscription status and transaction history in sync, so a manual restore is rarely technically necessary. It is still expected: App Store Review Guidelines section 3.1.1 require a restore mechanism for restorable purchases, and a visible button gives users confidence that their purchase is recognized.
The restore action calls the App Store sync API. Place it on the paywall below the product list. If a user has purchased but the paywall is still showing, syncing updates the transactions, the paywall disappears, and the content becomes available.
Step 8: Renewals, cancellations, and billing issues
Current entitlements always reflect the latest transaction for each active subscription. When a subscription renews, the entitlement stays. When it is canceled or hits an unresolved billing issue, the entitlement goes away.
That keeps access correct, but it is not a great user experience on its own. Renewals and cancellations do not need to interrupt the user, while a billing issue usually does — the customer wants to fix it before losing access. On-device handling cannot reliably surface billing issues or grace periods in a timely way. A server that receives App Store notifications can detect those events sooner and let the app tell the user.
Step 9: Receipt validation
With StoreKit 1, parsing and validating the receipt was the primary way to determine what a user owned. StoreKit 2 removes that burden: current entitlements and the full transaction history encapsulate parsing and validation, so a purely on-device implementation does not need to handle the receipt directly.
If you do need to verify authenticity yourself, Apple describes two approaches: local on-device validation of the receipt signature, which suits apps with in-app purchases, and server-side validation with the App Store, which suits persisting and managing purchase records.
Step 10: Promoted purchases from the App Store
Promoted in-app purchases appear on the app's product page. When a user taps one, the app opens and should finish the purchase, but iOS does not continue the action automatically. As of iOS 16, StoreKit 2 has no listener for this flow, so it requires StoreKit 1 APIs: a payment transaction observer class that inherits from NSObject, an implementation of the should-add-store-payment delegate method, and registration of the observer on the default payment queue.
Returning true continues the transaction as soon as the user enters the app. Returning false defers it, letting you add the payment to the queue at a better moment.
When a server is worth it
A pure on-device implementation works well for apps that live only on Apple platforms and use Universal Purchases. It breaks down when subscription status must be shared with the web or other platforms, when the team wants insight into user behavior, or when users should be contacted outside the app about billing problems or win-back offers.
Apple's server-side tools are the App Store Server API, a REST interface for transaction history, subscription status, order lookup, refund history, and renewal extension, and App Store Server Notifications, which push real-time events to an HTTPS endpoint you register in App Store Connect. The API is authorized with a JSON Web Token generated from a secret key created in App Store Connect. Most endpoints need the original transaction identifier, which the app obtains from the transaction object after purchase.
Version 2 of App Store Server Notifications defines 15 notification types: CONSUMPTION_REQUEST, DID_CHANGE_RENEWAL_PREF, DID_CHANGE_RENEWAL_STATUS, DID_FAIL_TO_RENEW, DID_RENEW, EXPIRED, GRACE_PERIOD_EXPIRED, OFFER_REDEEMED, PRICE_INCREASE, REFUND, REFUND_DECLINED, RENEWAL_EXTENDED, REVOKE, SUBSCRIBED, and TEST. Each arrives as an HTTP POST whose payload is signed in JWS format, and the payload carries the notification type, subtype, UUID, and a data object with the app Apple ID, bundle ID, bundle version, environment, renewal info, and transaction info.
A test notification can be requested through the API to confirm the endpoint works end to end, which is easier than making a sandbox or production purchase just to test the connection.
Server design and tradeoffs
With a backend, the app still starts purchases through StoreKit 2, but stops relying on current entitlements to decide what is active. Instead it posts the transaction to the server, which uses the original transaction identifier to fetch history from the App Store Server API and to match incoming notifications. The app also posts transaction updates it observes, which matters for pending purchases that had no identifier at purchase time.
The server endpoint should confirm the user is signed in, validate and fetch the transaction from the App Store, store the important fields, and update entitlements. It must tolerate duplicate deliveries, because the same event can arrive from the app and from notifications.
Prices need care. The App Store Server does not include the product price or currency in transactions, so the app sends the product's numeric price and display price. As of iOS 16, StoreKit 2 has no direct way to obtain the purchase currency; parsing the display price string is one option, and StoreKit 1's product object is a more reliable but messier one. Storing price supports lifetime-value analysis.
For keeping status current, notifications are the best practice because Apple sends them when something changes. Retries occur at 1, 12, 24, 48, and 72 hours after a failed delivery, and notification history can be replayed through the API if retries are missed. Polling the API is a useful complement: schedule checks around renewal and expiration, re-check after a grace period, and poll non-renewing and non-consumable purchases for refunds. Polling alone becomes a complex scheduling problem, which is why notifications are preferred.
Serving the product list from the backend also lets the paywall change without an app update and enables A/B testing of product sets.
The benefits of a backend include real-time status and refund notifications, transaction and receipt validation, customer management with refunds and extensions, revenue and churn analysis outside App Store Connect, binding subscription status to backend features, and sharing purchases across web and other platforms. The cost is substantially more complexity than an on-device implementation.
| Case | Description |
|---|---|
| Success – verified | The in-app product was successfully purchased. |
| Success – unverified | The purchase was a success but failed StoreKit automatic verification checks. This could be due to a jailbroken device, but the StoreKit documentation is currently unclear on this. |
| Pending | This is caused by either Strong Customer Authentication (SCA) or Ask to Buy. SCA is an additional factor of authentication or approval by a financial authority before this purchase is made. This might be done through an app or through a text message. After approval, the transaction will be updated. Ask to Buy is a feature enabling a child to ask to purchase something from a parent or guardian. The purchase will be held in a pending state until the parent or guardian approves or denies the purchase. |
| User Canceled | This usually does not need to get handled as an error state, but it is sometimes good to know. |
| Error | This result is either Product.PurchaseError or StoreKitError and could be due to not having an internet connection, App Store being down, payment errors, among other causes. |
This table reflects the captured state of StoreKit 2 purchase results as described in the original tutorial; verify current Apple documentation for the latest enum cases.
Frequently asked questions
Does StoreKit 2 handle receipt validation automatically?
For the on-device flow, yes. Current entitlements and the full transaction history encapsulate parsing and validation, so you do not need to parse the receipt yourself. If you need to verify authenticity independently, Apple describes local on-device signature validation and server-side validation with the App Store.
Why does my purchase return pending instead of success?
Pending means the transaction is waiting on Strong Customer Authentication or an Ask to Buy approval. The transaction will be updated after approval, so listen for transaction updates rather than treating pending as a failure.
Do I need a Restore Purchases button if StoreKit keeps things in sync?
It is still expected. App Store Review Guidelines section 3.1.1 require a restore mechanism for restorable purchases, and a visible button reassures users that their purchase is recognized. The restore action calls the App Store sync API.
Can a watchOS app read the same entitlement flag as a widget extension?
No. A companion watch app is a separate platform and does not share transaction history or app-group defaults with the iOS app. It can request entitlement status from the iOS app through WatchConnectivity.
How do I support purchases started from the App Store product page?
As of iOS 16, StoreKit 2 has no listener for promoted purchases. Use StoreKit 1: implement a payment transaction observer that inherits from NSObject, handle the should-add-store-payment delegate method, and register the observer on the default payment queue. Returning true continues the transaction immediately; returning false defers it.