StoreKit 2 Subscriptions: Complete Implementation Guide
To build subscriptions with StoreKit 2: load products with Product.products(for:), buy with product.purchase(), start a Transaction.updates listener when the app launches, unlock features from Transaction.currentEntitlements, and call finish() on every verified transaction. Add a Restore button that calls AppStore.sync(), test locally with a StoreKit configuration file, then in the sandbox.
This guide builds each step in Swift and SwiftUI. The code was type-checked with Xcode 26.6 (iOS 26.5 SDK) in Swift 6 language mode, with an iOS 17 deployment target; APIs added or changed since are marked by version. It is part of the subscription app monetization guide.
Before you start
You need:
- An auto-renewable subscription group with one or more subscriptions in App Store Connect. A customer can be subscribed to only one product in a group at a time.
- For sandbox testing, an active Paid Applications Agreement, signed by your team's Account Holder.
- A StoreKit configuration file in Xcode for local testing (File > New > File from Template > StoreKit Configuration File), selected in your scheme under Run > Options > StoreKit Configuration. Xcode 14 and later can sync it from App Store Connect.
The examples use two product IDs, pro_monthly and pro_yearly, in one group.
Step 1: Load products
Product.products(for:) fetches products in one request. It doesn't throw for an unknown ID: Apple says the App Store leaves invalid identifiers out of the result, so an empty array usually means an ID mismatch.
import StoreKit
import SwiftUI
import Observation
@MainActor
@Observable
final class Store {
static let productIDs = ["pro_monthly", "pro_yearly"]
private(set) var products: [Product] = []
private(set) var isPro = false
private var updatesTask: Task<Void, Never>?
init() {
updatesTask = listenForTransactions()
Task {
await loadProducts()
await refreshEntitlements()
}
}
func loadProducts() async {
do {
products = try await Product.products(for: Self.productIDs)
.sorted { $0.price < $1.price }
} catch {
print("Failed to load products: \(error)")
}
}
}
Show product.displayPrice to customers; it is already localized. Use product.price only for arithmetic. For a subscription, product.subscription gives the group ID, the billing period and any introductory offer.
Step 2: Buy a subscription
purchase(options:) returns one of three results, and the success case carries a VerificationResult that you must check.
extension Store {
enum PurchaseError: Error { case failedVerification }
func purchase(_ product: Product, appAccountToken: UUID? = nil) async throws -> Bool {
var options: Set<Product.PurchaseOption> = []
if let appAccountToken {
options.insert(.appAccountToken(appAccountToken))
}
let result = try await product.purchase(options: options)
switch result {
case .success(let verification):
let transaction = try checkVerified(verification)
await refreshEntitlements()
await transaction.finish()
return true
case .userCancelled:
return false
case .pending:
// For example Ask to Buy: if it's approved, the transaction
// arrives later through Transaction.updates.
return false
@unknown default:
return false
}
}
nonisolated func checkVerified<T>(_ result: VerificationResult<T>) throws -> T {
switch result {
case .verified(let value):
return value
case .unverified(_, let error):
print("Verification failed: \(error)")
throw PurchaseError.failedVerification
}
}
}
What each part does:
.verified/.unverified. StoreKit checks the App Store's JWS signature on the device. Grant access only for.verified..pending. The purchase needs approval, for example from a parent through Ask to Buy. Apple delivers the transaction later throughTransaction.updates, which is why Step 3 matters.appAccountToken. A UUID you choose for the user. The App Store returns it on the transaction and on renewal info, so your server can match a purchase to an account. Use the same UUID for the same user every time.finish(). Call it after you unlock the content. Apple says a transaction stays unfinished until you do.
What a custom paywall must show. App Review Guideline 3.1.2(c) says to clearly describe what the user gets for the price before asking them to subscribe. In practice that means the subscription's name, length and price per period, plus working links to your terms of use and privacy policy. Apple's SubscriptionStoreView (Step 7) adds the links for you. Apple also requires the billed amount to be the most prominent price on the screen; paywall design patterns covers that rule and the rest of the layout.
Which purchase method to use:
| Your UI | Method | Available from |
|---|---|---|
| SwiftUI | @Environment(\.purchase) (a PurchaseAction) |
iOS 17 |
| UIKit, with a scene | purchase(confirmIn: scene, options:) |
iOS 17 |
| UIKit, with a view controller | purchase(confirmIn: viewController, options:) |
iOS 18.2 |
| watchOS, or no UI context | purchase(options:) |
iOS 15 |
Apple recommends PurchaseAction for SwiftUI, and the UI-context methods so the payment sheet appears over the right window. If you use StoreKit's own views (Step 7), they make the purchase for you.
Step 3: Listen for transactions from launch
Not every transaction comes back from purchase(). Apple lists what arrives through Transaction.updates instead: Ask to Buy approvals, offer-code redemptions, purchases made in the App Store, and purchases completed on another device. Apple says to start this listener as soon as your app launches, and that unfinished transactions are delivered to it once, right after launch.
extension Store {
func listenForTransactions() -> Task<Void, Never> {
Task.detached { [weak self] in
for await result in Transaction.updates {
guard let self else { return }
guard let transaction = try? self.checkVerified(result) else { continue }
await self.refreshEntitlements()
await transaction.finish()
}
}
}
}
The Store starts this task in its init, so create the store once, at the top of the app:
@main
struct ExampleApp: App {
@State private var store = Store()
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
PaywallView(groupID: "21482456")
.environment(store)
}
.onChange(of: scenePhase) { _, phase in
// An expiry creates no new transaction, so re-check when the app comes back.
if phase == .active {
Task { await store.refreshEntitlements() }
}
}
}
}
Step 4: Decide who has access
Transaction.currentEntitlements returns the latest transaction for each product the customer is entitled to. For auto-renewable subscriptions, that means a state of subscribed or in grace period. Refunded or revoked purchases don't appear.
extension Store {
func refreshEntitlements() async {
var hasPro = false
for await result in Transaction.currentEntitlements {
guard case .verified(let transaction) = result else { continue }
if transaction.productType == .autoRenewable,
transaction.revocationDate == nil,
Self.productIDs.contains(transaction.productID) {
hasPro = true
}
}
isPro = hasPro
}
}
Run this at launch, after each purchase and restore, and when the app returns to the foreground. A subscription that expires creates no new transaction, so nothing arrives on Transaction.updates; without the foreground check, isPro stays true until the next launch. Don't cache isPro as the only source of truth; StoreKit keeps the entitlements up to date and works offline.
On iOS 18.4 and later, Transaction.currentEntitlements(for:) returns the entitlements for one product ID. It replaces currentEntitlement(for:), which iOS 18.4 deprecated.
Upgrades, downgrades and crossgrades
Subscriptions in a group are ranked by level in App Store Connect, and the level decides what happens when a customer switches:
- Upgrade (to a higher level): takes effect immediately, and Apple refunds the unused part of the old subscription. The old transaction has
isUpgradedset totrue, so look for the newer transaction. - Downgrade (to a lower level): takes effect at the next renewal date. Until then,
RenewalInfo.autoRenewPreferenceshows the product it will renew to. - Crossgrade (same level): with the same duration it takes effect immediately, with a prorated refund; with a different duration it takes effect at the next renewal date.
currentEntitlements handles all three, so the refreshEntitlements() code above needs no changes.
Subscription states
For more detail than "has access or not", read the status of the subscription group:
RenewalState |
Meaning | Give access? |
|---|---|---|
subscribed |
Active | Yes |
inGracePeriod |
Payment failed; Apple is retrying, and Billing Grace Period is on | Yes, through the grace period |
inBillingRetryPeriod |
Payment failed; Apple is retrying | No, but ask the user to update their payment method |
expired |
Ended | No |
revoked |
Apple revoked access: a refund, removal from Family Sharing, or loss of access through an organization | No |
func subscriptionState(groupID: String) async throws -> Product.SubscriptionInfo.RenewalState? {
let statuses = try await Product.SubscriptionInfo.status(for: groupID).filter {
if case .verified = $0.transaction { return true }
return false
}
// With Family Sharing there can be several statuses; any entitled one wins.
if let entitled = statuses.first(where: { $0.state == .subscribed || $0.state == .inGracePeriod }) {
return entitled.state
}
if let retrying = statuses.first(where: { $0.state == .inBillingRetryPeriod }) {
// Payment failed and Apple is retrying: no access, but ask the user to update billing.
if case .verified(let renewal) = retrying.renewalInfo {
print("Retrying billing. Auto-renew on: \(renewal.willAutoRenew)")
}
return retrying.state
}
return statuses.first?.state
}
The array can hold more than one status when the subscription supports Family Sharing. RenewalInfo also tells you whether the subscription will renew (willAutoRenew), which product it will renew to (autoRenewPreference), and why it expired (expirationReason). Billing Grace Period is off by default; you turn it on in App Store Connect. It doesn't apply to monthly subscriptions with a 12-month commitment.
currentEntitlements also includes subscriptions shared through Family Sharing; check transaction.ownershipType if you need to tell them apart. Once you turn Family Sharing on for a product, you can't turn it off.
Step 5: Introductory offers, promotional offers and win-back
Introductory offers (free trial, pay as you go, pay up front) apply automatically to an eligible customer, and each customer gets one per subscription group. Show the offer only when introductoryOffer isn't nil and isEligibleForIntroOffer is true. Eligibility alone isn't enough: Apple notes it can be true even when no offer is set up.
func introOfferText(for product: Product) async -> String? {
guard let subscription = product.subscription,
let offer = subscription.introductoryOffer,
await subscription.isEligibleForIntroOffer else { return nil }
// Localized, for example "1 week" or "3 months".
let period = offer.period.formatted(product.subscriptionPeriodFormatStyle)
let renewal = subscription.subscriptionPeriod.formatted(product.subscriptionPeriodFormatStyle)
// Put these strings in your string catalog in a real app.
switch offer.paymentMode {
case .freeTrial:
return "Free for \(period), then \(product.displayPrice) every \(renewal)"
case .payAsYouGo:
return "\(offer.displayPrice) every \(period) for \(offer.periodCount) periods, then \(product.displayPrice)"
case .payUpFront:
return "\(offer.displayPrice) for \(period), then \(product.displayPrice) every \(renewal)"
default:
return nil
}
}
For which offer to choose, see free trial vs introductory offer.
Promotional offers are for existing or lapsed subscribers, and your server must sign them. iOS 26 deprecated the two older signature options. Use Product.PurchaseOption.promotionalOffer(_:compactJWS:) with a JWS your server creates, which Apple back-deployed to iOS 15. It returns an array of options, so add them with formUnion. The App Store Server Library (Swift, Java, Python and Node) can create the signature.
Your server can also decide intro-offer eligibility with introductoryOfferEligibility(compactJWS:), also back-deployed to iOS 15.
Win-back offers (iOS 18 and later) are for customers whose subscription has ended. subscription.winBackOffers lists every win-back offer without checking eligibility; the renewal info's eligibleWinBackOfferIDs says which the customer can redeem. Pass one with .winBackOffer(offer).
Step 6: Restore, manage, redeem and refund
Restore. App Review Guideline 3.1.1 says to have a restore mechanism for restorable purchases, and Apple's sync() documentation suggests a Restore Purchases button. AppStore.sync() fetches the latest transactions, but Apple says to call it only in response to an explicit user action, and that in regular operation there's no need, because StoreKit keeps transactions up to date.
struct RestoreButton: View {
let store: Store
@State private var isRestoring = false
var body: some View {
Button("Restore Purchases") {
Task {
isRestoring = true
defer { isRestoring = false }
try? await AppStore.sync()
await store.refreshEntitlements()
}
}
.disabled(isRestoring)
}
}
Manage and redeem. Let people change or cancel without leaving the app, and redeem offer codes in Apple's sheet. Apple says offer codes can be redeemed in the app only through that sheet, not a custom UI.
struct AccountView: View {
@State private var showManage = false
@State private var showRedeem = false
var body: some View {
List {
Button("Manage subscription") { showManage = true }
Button("Redeem offer code") { showRedeem = true }
}
.manageSubscriptionsSheet(isPresented: $showManage)
.offerCodeRedemption(isPresented: $showRedeem)
}
}
iOS 27 deprecates offerCodeRedemption(isPresented:onCompletion:) in favour of offerCodeRedemption(options:isPresented:onCompletion:), whose completion delivers the redeemed transaction as a VerificationResult. With it, verify the transaction, unlock the content and call finish() in the completion handler; if the app can't, StoreKit delivers the transaction through Transaction.updates at the next launch. If you build with the iOS 27 SDK, use the new modifier behind if #available(iOS 27, *). The code in this guide was compiled with the iOS 26.5 SDK, so it uses the older modifier.
Refunds. refundRequestSheet(for:isPresented:onDismiss:) (SwiftUI) or transaction.beginRefundRequest(in:) (UIKit, with a window scene) opens Apple's refund request. Apple says it takes up to 48 hours to approve or deny one. If it's approved, the purchase drops out of currentEntitlements and your server receives a REFUND notification.
Step 7 (optional): Use Apple's subscription store view
From iOS 17, SubscriptionStoreView shows a subscription group's plans, prices and purchase buttons, makes the purchase itself, and shows your terms of service and privacy policy links from App Store Connect.
struct PaywallView: View {
let groupID: String
var body: some View {
SubscriptionStoreView(groupID: groupID) {
VStack {
Text("Pro").font(.largeTitle.bold())
Text("Unlimited projects, sync and export.")
}
}
.storeButton(.visible, for: .restorePurchases)
.subscriptionStoreControlStyle(.prominentPicker)
}
}
struct GatedView: View {
let groupID: String
@State private var isPro = false
var body: some View {
Text(isPro ? "Pro" : "Free")
.subscriptionStatusTask(for: groupID) { taskState in
if let statuses = taskState.value {
isPro = statuses.contains { status in
guard case .verified = status.transaction else { return false }
return status.state == .subscribed || status.state == .inGracePeriod
}
}
}
}
}
Apple's store-view documentation says the app calls AppStore.sync() when people use the restore button, so you don't call it yourself. .subscriptionStatusTask(for:) runs again whenever the status changes. It is quick to ship, but changing its design needs a new app release; a server-driven paywall can change without one.
Step 8: Test it
Test in three places, in this order:
| Where | How it works | Renewal speed |
|---|---|---|
| Xcode (StoreKit configuration file) | Local, no App Store connection. Debug > StoreKit > Manage Transactions shows the test transactions and lets you change them. For unit tests, SKTestSession controls the same environment. |
Set in Editor > Subscription Renewal Rate (for example, monthly renewal every 30 seconds) or SKTestSession.timeRate |
| Sandbox | Real App Store Connect products with a sandbox Apple Account. Settings on the device can change the renewal rate, clear purchase history and test win-back offers. | By default 1 month = 5 minutes (1 week = 3 minutes, 1 year = 1 hour). Renews up to 12 times, then stops. |
| TestFlight | Runs in the sandbox environment. | Each subscription renews daily, up to 6 times in a week, whatever its length |
Things worth testing on every build:
- A first purchase, a cancelled purchase, and an Ask to Buy approval arriving later (pending).
- A renewal while the app is closed, then opening the app.
- A failed renewal: billing retry, then grace period if you use it.
- A refund (access should go).
- Restore on a second device or after reinstalling.
- Upgrades and downgrades within the group.
Server side: notifications and the App Store Server API
StoreKit is enough to unlock features on one device. A server is needed to share access with the web or Android, to react to renewals and refunds when the app isn't open, and to measure revenue.
- App Store Server Notifications V2 send your server a JWS-signed payload for each event, including
SUBSCRIBED,DID_RENEW,DID_FAIL_TO_RENEW,GRACE_PERIOD_EXPIRED,EXPIREDandREFUND. Enter your production and sandbox URLs (Version 2) in App Store Connect, under the app's App Information page. Without a sandbox URL, Apple sends sandbox notifications to the production URL. Respond with HTTP 200–206, or Apple retries; retries happen only in production, and in the sandbox Apple sends each notification once. - App Store Server API answers questions on demand. Get All Subscription Statuses returns every subscription's status for a customer, from any of their transaction IDs.
appAccountTokenlinks both back to your user, which is why Step 2 sets it.- Receipts are deprecated. Apple has deprecated the
verifyReceiptendpoint; verify signed transactions instead, for example with the App Store Server Library.
What changed in recent iOS versions
| iOS | Change |
|---|---|
| 17 | SwiftUI store views (SubscriptionStoreView, StoreView, ProductView), PurchaseAction, subscriptionStatusTask, purchase(confirmIn: scene) |
| 17.2 | Transaction.offer replaces offerType and offerID |
| 18 | Win-back offers |
| 18.2 | purchase(confirmIn: viewController) |
| 18.4 | currentEntitlements(for:), appTransactionID (back-deployed to iOS 15), the offer period on Transaction.offer, subscription status by transaction ID |
| 26 | Older promotional offer signatures deprecated; use promotionalOffer(_:compactJWS:) |
| 26.4 | billingPlanType and commitmentInfo, for monthly plans with a 12-month commitment |
| 27 | New offerCodeRedemption(options:isPresented:onCompletion:) returns the redeemed transaction |
Troubleshooting
| Symptom | Likely cause |
|---|---|
products(for:) returns nothing |
A product ID doesn't match exactly, no StoreKit configuration is selected in the scheme, or the Paid Applications Agreement isn't active (sandbox) |
| A purchase succeeds but access doesn't unlock | Entitlements weren't refreshed after the purchase, or the listener isn't running |
| Old purchases keep arriving at every launch | Transactions aren't being finished |
| Ask to Buy approvals, purchases on another device or refunds only show after a relaunch | Transaction.updates isn't started at launch |
| Access stays on after a subscription expires | Entitlements aren't re-checked when the app returns to the foreground |
| Free-trial text shows to people who already used a trial | Eligibility isn't checked before showing the offer |
| Restore shows an Apple sign-in prompt unexpectedly | AppStore.sync() is being called automatically instead of from a button |
How to do it with BillDog
BillDog's iOS SDK uses StoreKit 2 and does the steps above for you: it listens to Transaction.updates from launch, finishes transactions, sets appAccountToken from a token the BillDog server issues for the user, and applies promotional and win-back offers. The BillDog server checks each signed transaction against Apple's certificates (and with the App Store Server API once you add your In-App Purchase key) and receives App Store Server Notifications V2, so a signed-in user has the same entitlements on iOS, Android and the web.
import BillDogFull
BillDog.shared.configure(config: BillDogConfig(apiKey: "YOUR_API_KEY"))
let result = try await BillDog.shared.purchase(productId: "pro_monthly")
let customerInfo = try await BillDog.shared.getCustomerInfo()
let isPro = customerInfo.hasEntitlement("pro")
You can also show a paywall designed in the dashboard with presentPaywall(identifier:from:), and test its design without an app release. To keep your own StoreKit code, pass a purchase controller to configure and BillDog records the purchases it returns; your code then stays responsible for calling finish(). See the iOS SDK guide, App Store setup for server notifications, and commitment plans for 12-month commitment subscriptions.
Sources
- Apple: Product.products(for:), accessed 2026-11-14
- Apple: purchase(options:), accessed 2026-11-14
- Apple: PurchaseAction, accessed 2026-11-14
- Apple: Product.PurchaseResult.pending, accessed 2026-11-14
- Apple: appAccountToken(_:), accessed 2026-11-14
- Apple: Transaction.updates, accessed 2026-11-14
- Apple: Transaction.currentEntitlements, accessed 2026-11-14
- Apple: finish(), accessed 2026-11-14
- Apple: Product.SubscriptionInfo.RenewalState, accessed 2026-11-14
- Apple: status(for:), accessed 2026-11-14
- Apple: isEligibleForIntroOffer, accessed 2026-11-14
- Apple: promotionalOffer(_:compactJWS:), accessed 2026-11-14
- Apple: winBackOffers, accessed 2026-11-14
- Apple: AppStore.sync(), accessed 2026-11-14
- Apple: offerCodeRedemption(options:isPresented:onCompletion:), accessed 2026-11-14
- Apple: beginRefundRequest(in:), accessed 2026-11-14
- Apple: SubscriptionStoreView, accessed 2026-11-14
- Apple: Setting up StoreKit Testing in Xcode, accessed 2026-11-14
- Apple: Testing in-app purchases with sandbox, accessed 2026-11-14
- App Store Connect Help: Manage sandbox Apple Account settings, accessed 2026-11-14
- App Store Connect Help: Testing subscriptions in TestFlight, accessed 2026-11-14
- Apple: App Store Server Notifications V2, accessed 2026-11-14
- Apple: Get All Subscription Statuses, accessed 2026-11-14
- Apple: App Store Receipts (deprecated), accessed 2026-11-14
- Apple: App Review Guidelines (3.1.1, 3.1.2), accessed 2026-11-14
- Apple: Transaction.unfinished, accessed 2026-11-14
- Apple: StoreView, accessed 2026-11-14
- Apple: Responding to App Store Server Notifications, accessed 2026-11-14
- Apple: Supporting Family Sharing in your app, accessed 2026-11-14
- App Store Connect Help: Auto-renewable subscription information, accessed 2026-11-14
- App Store Connect Help: Enter server URLs for App Store Server Notifications, accessed 2026-11-14
- App Store Connect Help: Enable Billing Grace Period, accessed 2026-11-14
- WWDC25: What's new in StoreKit and In-App Purchase
- WWDC26: What's new in Apple In-App Purchase
Frequently asked questions
What is the difference between StoreKit 1 and StoreKit 2?
StoreKit 2 is Apple's Swift API for in-app purchases, available from iOS 15. It uses async/await, returns transactions signed by the App Store in JWS format, and verifies them for you, so the app no longer has to parse a receipt. The original StoreKit uses delegates and payment queues, and Apple has deprecated the receipt-based verifyReceipt endpoint.
Why does Product.products(for:) return an empty array?
StoreKit leaves out any product ID it can't find, so a typo, a product not yet set up, or the wrong StoreKit configuration file in your scheme all give an empty result without an error. For sandbox testing, the Account Holder must also have signed the Paid Applications Agreement in App Store Connect.
Do I still need to call finish() on transactions in StoreKit 2?
Yes. Apple says to call finish() after you deliver the content or turn on the service. A transaction stays unfinished until you do, and the updates listener delivers unfinished transactions again when the app launches.
When should I call AppStore.sync()?
Only when the user taps a Restore Purchases button. Apple says there's no need to call it in regular operation, because StoreKit keeps transactions up to date, and calling it can show an App Store sign-in prompt.
Do I need a server for StoreKit 2 subscriptions?
Not to unlock content on one device; StoreKit verifies transactions on the device. You need one to give access on other platforms such as the web or Android, to act on renewals and refunds when the app isn't running, or to send win-back messages. For that, use App Store Server Notifications V2 and the App Store Server API.
Get the BillDog newsletter
Practical guides on subscription pricing, paywalls and app growth, about twice a month. No spam.
