[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6E6C407733F4EYV8B0XH45A":3,"skill-same:01M6E6C407733F4EYV8B0XH45A":74},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":34,"linkOnly":35,"markdownContent":36,"markdownBody":37,"frontMatter":38,"refName":41,"commitSha":42,"skillDirectory":43,"forksCount":44,"repositoryHtmlUrl":45,"repositoryHomepageUrl":46,"ownerHtmlUrl":47,"ownerBlogUrl":6,"ownerDescription":48,"updatedAt":49,"install":50,"resources":63},"01M6E6C407733F4EYV8B0XH45A","axiom-in-app-purchases",null,"Use when implementing in-app purchases, StoreKit 2, subscriptions, or transaction handling - testing-first workflow with .storekit configuration, StoreManager architecture, transaction verification, subscription management, and restore purchases for consumables, non-consumables, and auto-renewable subscriptions","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-in-app-purchases\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33],"app","axiom in app purchases","testing","workflow","architecture","verification","first","management","use","auto","restore","subscriptions","configuration","transaction","subscription management","2026-11-10 10:12:30",false,"---\nname: axiom-in-app-purchases\ndescription: Use when implementing in-app purchases, StoreKit 2, subscriptions, or transaction handling - testing-first workflow with .storekit configuration, StoreManager architecture, transaction verification, subscription management, and restore purchases for consumables, non-consumables, and auto-renewable subscriptions\nlicense: MIT\nmetadata:\n  version: \"1.0\"\n---\n\n# StoreKit 2 In-App Purchase Implementation\n\n**Purpose**: Guide robust, testable in-app purchase implementation\n**StoreKit Version**: StoreKit 2\n**iOS Version**: iOS 15+ (iOS 18.4+ for latest features)\n**Xcode**: Xcode 13+ (Xcode 16+ recommended)\n**Context**: WWDC 2025-241, 2025-249, 2023-10013, 2021-10114\n\n## When to Use This Skill\n\n✅ **Use this skill when**:\n- Implementing any in-app purchase functionality (new or existing)\n- Adding consumable products (coins, hints, boosts)\n- Adding non-consumable products (premium features, level packs)\n- Adding auto-renewable subscriptions (monthly\u002Fannual plans)\n- Debugging purchase failures, missing transactions, or restore issues\n- Setting up StoreKit testing configuration\n- Implementing subscription status tracking\n- Adding promotional offers or introductory offers\n- Server-side receipt validation\n- Family Sharing support\n\n❌ **Do NOT use this skill for**:\n- StoreKit 1 (legacy API) - this skill focuses on StoreKit 2\n- App Store Connect product configuration (separate documentation)\n- Pricing strategy or business model decisions\n\n---\n\n## ⚠️ Already Wrote Code Before Creating .storekit Config?\n\nIf you wrote purchase code before creating `.storekit` configuration, you have three options:\n\n### Option A: Delete and Start Over (Strongly Recommended)\n\nDelete all IAP code and follow the testing-first workflow below. This reinforces correct habits and ensures you experience the full benefit of .storekit-first development.\n\n**Why this is best**:\n- Validates that you understand the workflow\n- Catches product ID issues you might have missed\n- Builds muscle memory for future IAP implementations\n- Takes only 15-30 minutes for experienced developers\n\n### Option B: Create .storekit Config Now (Acceptable with Caution)\n\nCreate the `.storekit` file now with your existing product IDs. Test everything works locally. Document in your PR that you tested in sandbox first.\n\n**Trade-offs**:\n- ✅ Keeps working code\n- ✅ Adds local testing capability\n- ❌ Misses product ID validation benefit\n- ❌ Reinforces testing-after pattern\n- ❌ Requires extra vigilance in code review\n\n**If choosing this path**: Create .storekit immediately, verify locally, and commit a note explaining the approach.\n\n### Option C: Skip .storekit Entirely (Not Recommended)\n\nCommit without `.storekit` configuration, test only in sandbox.\n\n**Why this is problematic**:\n- Teammates can't test purchases locally\n- No validation of product IDs before runtime\n- Harder iteration (requires App Store Connect)\n- Missing documentation of product structure\n\n**Bottom line**: Choose Option A if possible, Option B if pragmatic, never Option C.\n\n---\n\n## Core Philosophy: Testing-First Workflow\n\n> **Best Practice**: Create and test StoreKit configuration BEFORE writing production purchase code.\n\n### Why .storekit-First Matters\n\nThe recommended workflow is to create `.storekit` configuration before writing any purchase code. This isn't arbitrary - it provides concrete benefits:\n\n**Immediate product ID validation**:\n- Typos caught in Xcode, not at runtime\n- Product configuration visible in project\n- No App Store Connect dependency for testing\n\n**Faster iteration**:\n- Test purchases in simulator instantly\n- No network requests during development\n- Accelerated subscription renewal for testing\n\n**Team benefits**:\n- Anyone can test purchase flows locally\n- Product catalog documented in code\n- Code review includes purchase testing\n\n**Common objections addressed**:\n\n❓ **\"I already tested in sandbox\"** - Sandbox testing is valuable but comes later. Local testing with .storekit is faster and enables true TDD.\n\n❓ **\"My code works\"** - Working code is great! Adding .storekit makes it easier for teammates to verify and maintain.\n\n❓ **\"I've done this before\"** - Experience is valuable. The .storekit-first workflow makes experienced developers even more productive.\n\n❓ **\"Time pressure\"** - Creating .storekit takes 10-15 minutes. The time saved in iteration pays back immediately.\n\n### The Recommended Workflow\n\n```\nStoreKit Config → Local Testing → Production Code → Unit Tests → Sandbox Testing\n      ↓               ↓                ↓               ↓              ↓\n   .storekit      Test purchases   StoreManager    Mock store    Integration test\n```\n\n**Why this order helps**:\n1. **StoreKit Config First**: Defines products without App Store Connect dependency\n2. **Local Testing**: Validates product IDs and purchase flows immediately\n3. **Production Code**: Implements against validated product configuration\n4. **Unit Tests**: Verifies business logic with mocked store responses\n5. **Sandbox Testing**: Final validation in App Store environment\n\n**Benefits of following this workflow**:\n- Product IDs validated before writing code\n- Faster development iteration\n- Easier team collaboration\n- Better test coverage\n\n---\n\n## Mandatory Checklist\n\nBefore marking IAP implementation complete, **ALL** items must be verified:\n\n### Phase 1: Testing Foundation\n- [ ] Created `.storekit` configuration file with all products\n- [ ] Verified each product type renders correctly in StoreKit preview\n- [ ] Tested successful purchase flow for each product in Xcode\n- [ ] Tested purchase failure scenarios (insufficient funds, cancelled)\n- [ ] Tested restore purchases flow\n- [ ] For subscriptions: tested renewal, expiration, and upgrade\u002Fdowngrade\n\n### Phase 2: Architecture\n- [ ] Centralized StoreManager class exists (single source of truth)\n- [ ] StoreManager is ObservableObject (SwiftUI) or uses NotificationCenter\n- [ ] Transaction observer listens for updates via `Transaction.updates`\n- [ ] All transaction verification uses `VerificationResult`\n- [ ] All transactions call `.finish()` after entitlement granted\n- [ ] Product loading happens at app launch or before displaying store\n\n### Phase 3: Purchase Flow\n- [ ] Purchase uses new `purchase(confirmIn:options:)` with UI context (iOS 18.2+)\n- [ ] Purchase handles all `PurchaseResult` cases (success, userCancelled, pending)\n- [ ] Purchase verifies transaction signature before granting entitlement\n- [ ] Purchase stores transaction receipt\u002Fidentifier for support\n- [ ] appAccountToken set for all purchases (if using server backend)\n\n### Phase 4: Subscription Management (if applicable)\n- [ ] Subscription status tracked via `Product.SubscriptionInfo.Status`\n- [ ] Current entitlements checked via `Transaction.currentEntitlements(for:)`\n- [ ] Renewal info accessed for expiration, renewal date, offer status\n- [ ] Subscription views use ProductView or SubscriptionStoreView\n- [ ] Win-back offers implemented for expired subscriptions\n- [ ] Grace period and billing retry states handled\n\n### Phase 5: Restore & Sync\n- [ ] Restore purchases implemented (required by App Store Review)\n- [ ] Restore uses `Transaction.currentEntitlements` or `Transaction.all`\n- [ ] Family Sharing transactions identified (if supported)\n- [ ] Server sync implemented (if using backend)\n- [ ] Cross-device entitlement sync tested\n\n### Phase 6: Error Handling\n- [ ] Network errors handled gracefully (retries, user messaging)\n- [ ] Invalid product IDs detected and logged\n- [ ] Purchase failures show user-friendly error messages\n- [ ] Transaction verification failures logged and reported\n- [ ] Refund notifications handled (via App Store Server Notifications)\n\n### Phase 7: Testing & Validation\n- [ ] Unit tests verify purchase logic with mocked Product\u002FTransaction\n- [ ] Unit tests verify subscription status determination\n- [ ] Integration tests with StoreKit configuration pass\n- [ ] Sandbox testing with real Apple ID completed\n- [ ] TestFlight testing completed before production release\n\n---\n\n## Step 1: Create StoreKit Configuration (FIRST!)\n\n**DO THIS BEFORE WRITING ANY PURCHASE CODE.**\n\n### Create Configuration File\n\n1. **Xcode → File → New → File → StoreKit Configuration File**\n2. **Save as**: `Products.storekit` (or your app name)\n3. **Add to target**: ✅ (include in app bundle for testing)\n\n### Add Products\n\nClick \"+\" and add each product type:\n\n#### Consumable\n```\nProduct ID: com.yourapp.coins_100\nReference Name: 100 Coins\nPrice: $0.99\n```\n\n#### Non-Consumable\n```\nProduct ID: com.yourapp.premium\nReference Name: Premium Upgrade\nPrice: $4.99\n```\n\n#### Auto-Renewable Subscription\n```\nProduct ID: com.yourapp.pro_monthly\nReference Name: Pro Monthly\nPrice: $9.99\u002Fmonth\nSubscription Group ID: pro_tier\n```\n\n### Test Immediately\n\n1. **Run app in simulator**\n2. **Scheme → Edit Scheme → Run → Options**\n3. **StoreKit Configuration**: Select `Products.storekit`\n4. **Verify**: Products load, purchases complete, transactions appear\n\n---\n\n## Step 2: Implement StoreManager Architecture\n\n### Required Pattern: Centralized StoreManager\n\n**All purchase logic must go through a single StoreManager.** No scattered `Product.purchase()` calls throughout app.\n\n```swift\nimport StoreKit\n\n@MainActor\nfinal class StoreManager: ObservableObject {\n    \u002F\u002F Published state for UI\n    @Published private(set) var products: [Product] = []\n    @Published private(set) var purchasedProductIDs: Set\u003CString> = []\n\n    \u002F\u002F Product IDs from StoreKit configuration\n    private let productIDs = [\n        \"com.yourapp.coins_100\",\n        \"com.yourapp.premium\",\n        \"com.yourapp.pro_monthly\"\n    ]\n\n    private var transactionListener: Task\u003CVoid, Never>?\n\n    init() {\n        \u002F\u002F Start transaction listener immediately\n        transactionListener = listenForTransactions()\n\n        Task {\n            await loadProducts()\n            await updatePurchasedProducts()\n        }\n    }\n\n    deinit {\n        transactionListener?.cancel()\n    }\n}\n```\n\n**Why @MainActor**: Published properties must update on main thread for UI binding.\n\n### Load Products (At Launch)\n\n```swift\nextension StoreManager {\n    func loadProducts() async {\n        do {\n            \u002F\u002F Load products from App Store\n            let loadedProducts = try await Product.products(for: productIDs)\n\n            \u002F\u002F Update published property on main thread\n            self.products = loadedProducts\n\n        } catch {\n            print(\"Failed to load products: \\(error)\")\n            \u002F\u002F Show error to user\n        }\n    }\n}\n```\n\n**Call from**: `App.init()` or first view's `.task` modifier\n\n### Listen for Transactions (REQUIRED)\n\n```swift\nextension StoreManager {\n    func listenForTransactions() -> Task\u003CVoid, Never> {\n        Task.detached { [weak self] in\n            \u002F\u002F Listen for ALL transaction updates\n            for await verificationResult in Transaction.updates {\n                await self?.handleTransaction(verificationResult)\n            }\n        }\n    }\n\n    @MainActor\n    private func handleTransaction(_ result: VerificationResult\u003CTransaction>) async {\n        \u002F\u002F Verify transaction signature\n        guard let transaction = try? result.payloadValue else {\n            print(\"Transaction verification failed\")\n            return\n        }\n\n        \u002F\u002F Grant entitlement to user\n        await grantEntitlement(for: transaction)\n\n        \u002F\u002F CRITICAL: Always finish transaction\n        await transaction.finish()\n\n        \u002F\u002F Update purchased products\n        await updatePurchasedProducts()\n    }\n}\n```\n\n**Why detached**: Transaction listener runs independently of view lifecycle\n\n---\n\n## Step 3: Implement Purchase Flow\n\n### Purchase with UI Context (iOS 18.2+)\n\n```swift\nextension StoreManager {\n    func purchase(_ product: Product, confirmIn scene: UIWindowScene) async throws -> Bool {\n        \u002F\u002F Perform purchase with UI context for payment sheet\n        let result = try await product.purchase(confirmIn: scene)\n\n        switch result {\n        case .success(let verificationResult):\n            \u002F\u002F Verify the transaction\n            guard let transaction = try? verificationResult.payloadValue else {\n                print(\"Transaction verification failed\")\n                return false\n            }\n\n            \u002F\u002F Grant entitlement\n            await grantEntitlement(for: transaction)\n\n            \u002F\u002F CRITICAL: Finish transaction\n            await transaction.finish()\n\n            \u002F\u002F Update state\n            await updatePurchasedProducts()\n\n            return true\n\n        case .userCancelled:\n            \u002F\u002F User tapped \"Cancel\" in payment sheet\n            return false\n\n        case .pending:\n            \u002F\u002F Purchase requires action (Ask to Buy, payment issue)\n            \u002F\u002F Will be delivered via Transaction.updates when approved\n            return false\n\n        @unknown default:\n            return false\n        }\n    }\n}\n```\n\n### SwiftUI Purchase (Using Environment)\n\n```swift\nstruct ProductRow: View {\n    let product: Product\n    @Environment(\\.purchase) private var purchase\n\n    var body: some View {\n        Button(\"Buy \\(product.displayPrice)\") {\n            Task {\n                do {\n                    let result = try await purchase(product)\n                    \u002F\u002F Handle result\n                } catch {\n                    print(\"Purchase failed: \\(error)\")\n                }\n            }\n        }\n    }\n}\n```\n\n### Set appAccountToken (If Using Backend)\n\n```swift\nfunc purchase(\n    _ product: Product,\n    confirmIn scene: UIWindowScene,\n    accountToken: UUID\n) async throws -> Bool {\n    \u002F\u002F Purchase with appAccountToken for server-side association\n    let result = try await product.purchase(\n        confirmIn: scene,\n        options: [\n            .appAccountToken(accountToken)\n        ]\n    )\n\n    \u002F\u002F ... handle result\n}\n```\n\n**When to use**: When your backend needs to associate purchases with user accounts\n\n---\n\n## Step 4: Verify Transactions (MANDATORY)\n\n### Always Use VerificationResult\n\n```swift\nfunc handleTransaction(_ result: VerificationResult\u003CTransaction>) async {\n    switch result {\n    case .verified(let transaction):\n        \u002F\u002F ✅ Transaction signed by App Store\n        await grantEntitlement(for: transaction)\n        await transaction.finish()\n\n    case .unverified(let transaction, let error):\n        \u002F\u002F ❌ Transaction signature invalid\n        print(\"Unverified transaction: \\(error)\")\n        \u002F\u002F DO NOT grant entitlement\n        \u002F\u002F DO finish transaction to clear from queue\n        await transaction.finish()\n    }\n}\n```\n\n**Why verify**: Prevents granting entitlements for:\n- Fraudulent receipts\n- Jailbroken device receipts\n- Man-in-the-middle attacks\n\n### Check Transaction Fields\n\n```swift\nfunc grantEntitlement(for transaction: Transaction) async {\n    \u002F\u002F Check transaction hasn't been revoked\n    guard transaction.revocationDate == nil else {\n        print(\"Transaction was refunded\")\n        await revokeEntitlement(for: transaction.productID)\n        return\n    }\n\n    \u002F\u002F Grant based on product type\n    switch transaction.productType {\n    case .consumable:\n        await addConsumable(productID: transaction.productID)\n\n    case .nonConsumable:\n        await unlockFeature(productID: transaction.productID)\n\n    case .autoRenewable:\n        await activateSubscription(productID: transaction.productID)\n\n    default:\n        break\n    }\n}\n```\n\n---\n\n## Step 5: Track Current Entitlements\n\n### Check What User Owns\n\n```swift\nextension StoreManager {\n    func updatePurchasedProducts() async {\n        var purchased: Set\u003CString> = []\n\n        \u002F\u002F Iterate through all current entitlements\n        for await result in Transaction.currentEntitlements {\n            guard let transaction = try? result.payloadValue else {\n                continue\n            }\n\n            \u002F\u002F Only include active entitlements (not revoked)\n            if transaction.revocationDate == nil {\n                purchased.insert(transaction.productID)\n            }\n        }\n\n        self.purchasedProductIDs = purchased\n    }\n}\n```\n\n### Check Specific Product\n\n```swift\nfunc isEntitled(to productID: String) async -> Bool {\n    \u002F\u002F Check current entitlements for specific product\n    for await result in Transaction.currentEntitlements(for: productID) {\n        if let transaction = try? result.payloadValue,\n           transaction.revocationDate == nil {\n            return true\n        }\n    }\n\n    return false\n}\n```\n\n---\n\n## Step 6: Implement Subscription Management\n\n### Track Subscription Status\n\n```swift\nextension StoreManager {\n    func checkSubscriptionStatus(for groupID: String) async -> Product.SubscriptionInfo.Status? {\n        \u002F\u002F Get subscription statuses for group\n        guard let result = try? await Product.SubscriptionInfo.status(for: groupID),\n              let status = result.first else {\n            return nil\n        }\n\n        return status.state\n    }\n}\n```\n\n### Handle Subscription States\n\n```swift\nfunc updateSubscriptionUI(for status: Product.SubscriptionInfo.Status) {\n    switch status.state {\n    case .subscribed:\n        \u002F\u002F User has active subscription\n        showSubscribedContent()\n\n    case .expired:\n        \u002F\u002F Subscription expired - show win-back offer\n        showResubscribeOffer()\n\n    case .inGracePeriod:\n        \u002F\u002F Billing issue - show payment update prompt\n        showUpdatePaymentPrompt()\n\n    case .inBillingRetryPeriod:\n        \u002F\u002F Apple retrying payment - maintain access\n        showBillingRetryMessage()\n\n    case .revoked:\n        \u002F\u002F Family Sharing access removed\n        removeAccess()\n\n    @unknown default:\n        break\n    }\n}\n```\n\n### Use StoreKit Views (iOS 17+)\n\n```swift\nstruct SubscriptionView: View {\n    var body: some View {\n        SubscriptionStoreView(groupID: \"pro_tier\") {\n            \u002F\u002F Marketing content\n            VStack {\n                Image(\"premium-icon\")\n                Text(\"Unlock all features\")\n            }\n        }\n        .subscriptionStoreControlStyle(.prominentPicker)\n    }\n}\n```\n\n---\n\n## Step 7: Implement Restore Purchases (REQUIRED)\n\n### Restore Flow\n\n```swift\nextension StoreManager {\n    func restorePurchases() async {\n        \u002F\u002F Sync all transactions from App Store\n        try? await AppStore.sync()\n\n        \u002F\u002F Update current entitlements\n        await updatePurchasedProducts()\n    }\n}\n```\n\n### UI Button\n\n```swift\nstruct SettingsView: View {\n    @StateObject private var store = StoreManager()\n\n    var body: some View {\n        Button(\"Restore Purchases\") {\n            Task {\n                await store.restorePurchases()\n            }\n        }\n    }\n}\n```\n\n**App Store Requirement**: Apps with IAP must provide restore functionality for non-consumables and subscriptions.\n\n---\n\n## Step 8: Handle Refunds\n\n### Listen for Refund Notifications\n\n```swift\nextension StoreManager {\n    func listenForTransactions() -> Task\u003CVoid, Never> {\n        Task.detached { [weak self] in\n            for await verificationResult in Transaction.updates {\n                await self?.handleTransaction(verificationResult)\n            }\n        }\n    }\n\n    @MainActor\n    private func handleTransaction(_ result: VerificationResult\u003CTransaction>) async {\n        guard let transaction = try? result.payloadValue else {\n            return\n        }\n\n        \u002F\u002F Check if transaction was refunded\n        if let revocationDate = transaction.revocationDate {\n            print(\"Transaction refunded on \\(revocationDate)\")\n            await revokeEntitlement(for: transaction.productID)\n        } else {\n            await grantEntitlement(for: transaction)\n        }\n\n        await transaction.finish()\n    }\n}\n```\n\n---\n\n## Step 9: Unit Testing\n\n### Mock Store Responses\n\n```swift\nprotocol StoreProtocol {\n    func products(for ids: [String]) async throws -> [Product]\n    func purchase(_ product: Product) async throws -> PurchaseResult\n}\n\n\u002F\u002F Production\nfinal class StoreManager: StoreProtocol {\n    func products(for ids: [String]) async throws -> [Product] {\n        try await Product.products(for: ids)\n    }\n}\n\n\u002F\u002F Testing\nfinal class MockStore: StoreProtocol {\n    var mockProducts: [Product] = []\n    var mockPurchaseResult: PurchaseResult?\n\n    func products(for ids: [String]) async throws -> [Product] {\n        mockProducts\n    }\n\n    func purchase(_ product: Product) async throws -> PurchaseResult {\n        mockPurchaseResult ?? .userCancelled\n    }\n}\n```\n\n### Test Purchase Logic\n\n```swift\n@Test func testSuccessfulPurchase() async {\n    let mockStore = MockStore()\n    let manager = StoreManager(store: mockStore)\n\n    \u002F\u002F Given: Mock successful purchase\n    mockStore.mockPurchaseResult = .success(.verified(mockTransaction))\n\n    \u002F\u002F When: Purchase product\n    let result = await manager.purchase(mockProduct)\n\n    \u002F\u002F Then: Entitlement granted\n    #expect(result == true)\n    #expect(manager.purchasedProductIDs.contains(\"com.app.premium\"))\n}\n\n@Test func testCancelledPurchase() async {\n    let mockStore = MockStore()\n    let manager = StoreManager(store: mockStore)\n\n    \u002F\u002F Given: User cancels\n    mockStore.mockPurchaseResult = .userCancelled\n\n    \u002F\u002F When: Purchase product\n    let result = await manager.purchase(mockProduct)\n\n    \u002F\u002F Then: No entitlement granted\n    #expect(result == false)\n    #expect(manager.purchasedProductIDs.isEmpty)\n}\n```\n\n---\n\n## Common Anti-Patterns (NEVER DO THIS)\n\n### ❌ No StoreKit Configuration\n\n```swift\n\u002F\u002F ❌ WRONG: Writing purchase code without .storekit file\nlet products = try await Product.products(for: productIDs)\n\u002F\u002F Can't test this without App Store Connect setup!\n```\n\n✅ **Correct**: Create `.storekit` file FIRST, test in Xcode, THEN implement.\n\n### ❌ Code Before .storekit Config\n\n```swift\n\u002F\u002F ❌ Less ideal: Write code, test in sandbox, add .storekit later\nlet products = try await Product.products(for: productIDs)\nlet result = try await product.purchase(confirmIn: scene)\n\u002F\u002F \"I tested this in sandbox, it works! I'll add .storekit config later.\"\n```\n\n✅ **Recommended**: Create `.storekit` config first, then write code.\n\n**If you're in this situation**: See \"Already Wrote Code Before Creating .storekit Config?\" section above for your options (A, B, or C).\n\n**Why .storekit-first is better**:\n- Product ID typos caught in Xcode, not at runtime\n- Faster iteration without network requests\n- Teammates can test locally\n- Documents product structure in code\n\n**Sandbox testing is valuable** - it validates against real App Store infrastructure. But starting with .storekit makes sandbox testing easier because you've already validated product IDs locally.\n\n### ❌ Scattered Purchase Calls\n\n```swift\n\u002F\u002F ❌ WRONG: Purchase calls scattered throughout app\nButton(\"Buy\") {\n    try await product.purchase()  \u002F\u002F In view 1\n}\n\nButton(\"Subscribe\") {\n    try await subscriptionProduct.purchase()  \u002F\u002F In view 2\n}\n```\n\n✅ **Correct**: All purchases through centralized StoreManager.\n\n### ❌ Forgetting to Finish Transactions\n\n```swift\n\u002F\u002F ❌ WRONG: Never calling finish()\nfunc handleTransaction(_ transaction: Transaction) {\n    grantEntitlement(for: transaction)\n    \u002F\u002F Missing: await transaction.finish()\n}\n```\n\n✅ **Correct**: ALWAYS call `transaction.finish()` after granting entitlement.\n\n### ❌ Not Verifying Transactions\n\n```swift\n\u002F\u002F ❌ WRONG: Using unverified transaction\nfor await transaction in Transaction.all {\n    grantEntitlement(for: transaction)  \u002F\u002F Unsafe!\n}\n```\n\n✅ **Correct**: Always check `VerificationResult` before granting.\n\n### ❌ Ignoring Transaction Listener\n\n```swift\n\u002F\u002F ❌ WRONG: Only handling purchases in purchase() method\nfunc purchase() {\n    let result = try await product.purchase()\n    \u002F\u002F What about pending purchases, family sharing, restore?\n}\n```\n\n✅ **Correct**: Listen to `Transaction.updates` for ALL transaction sources.\n\n### ❌ Not Implementing Restore\n\n```swift\n\u002F\u002F ❌ WRONG: No restore button\n\u002F\u002F App Store will REJECT your app!\n```\n\n✅ **Correct**: Provide visible \"Restore Purchases\" button in settings.\n\n---\n\n## Validation\n\nBefore marking IAP implementation complete, verify:\n\n### Code Inspection\n\nRun these searches to verify compliance:\n\n```bash\n# Check StoreKit configuration exists\nfind . -name \"*.storekit\"\n\n# Check transaction.finish() is called\nrg \"transaction\\.finish\\(\\)\" --type swift\n\n# Check VerificationResult usage\nrg \"VerificationResult\" --type swift\n\n# Check Transaction.updates listener\nrg \"Transaction\\.updates\" --type swift\n\n# Check restore implementation\nrg \"AppStore\\.sync|Transaction\\.all\" --type swift\n```\n\n### Functional Testing\n\n- [ ] Can purchase each product type in StoreKit configuration\n- [ ] Can cancel purchase and state remains consistent\n- [ ] Can restore purchases and regain access\n- [ ] Subscription renewal\u002Fexpiration works as expected\n- [ ] Refunded transactions revoke access\n- [ ] Family Sharing transactions identified (if supported)\n\n### Sandbox Testing\n\n- [ ] Real Apple ID sandbox purchases complete\n- [ ] TestFlight beta testers confirm purchase flows work\n- [ ] Server-side validation works (if using backend)\n\n---\n\n## Resources\n\n**WWDC**: 2025-241, 2025-249, 2023-10013, 2021-10114\n\n**Docs**: \u002Fstorekit, \u002Fappstoreserverapi\n\n**Skills**: axiom-storekit-ref\n\n","# StoreKit 2 In-App Purchase Implementation\n\n**Purpose**: Guide robust, testable in-app purchase implementation\n**StoreKit Version**: StoreKit 2\n**iOS Version**: iOS 15+ (iOS 18.4+ for latest features)\n**Xcode**: Xcode 13+ (Xcode 16+ recommended)\n**Context**: WWDC 2025-241, 2025-249, 2023-10013, 2021-10114\n\n## When to Use This Skill\n\n✅ **Use this skill when**:\n- Implementing any in-app purchase functionality (new or existing)\n- Adding consumable products (coins, hints, boosts)\n- Adding non-consumable products (premium features, level packs)\n- Adding auto-renewable subscriptions (monthly\u002Fannual plans)\n- Debugging purchase failures, missing transactions, or restore issues\n- Setting up StoreKit testing configuration\n- Implementing subscription status tracking\n- Adding promotional offers or introductory offers\n- Server-side receipt validation\n- Family Sharing support\n\n❌ **Do NOT use this skill for**:\n- StoreKit 1 (legacy API) - this skill focuses on StoreKit 2\n- App Store Connect product configuration (separate documentation)\n- Pricing strategy or business model decisions\n\n---\n\n## ⚠️ Already Wrote Code Before Creating .storekit Config?\n\nIf you wrote purchase code before creating `.storekit` configuration, you have three options:\n\n### Option A: Delete and Start Over (Strongly Recommended)\n\nDelete all IAP code and follow the testing-first workflow below. This reinforces correct habits and ensures you experience the full benefit of .storekit-first development.\n\n**Why this is best**:\n- Validates that you understand the workflow\n- Catches product ID issues you might have missed\n- Builds muscle memory for future IAP implementations\n- Takes only 15-30 minutes for experienced developers\n\n### Option B: Create .storekit Config Now (Acceptable with Caution)\n\nCreate the `.storekit` file now with your existing product IDs. Test everything works locally. Document in your PR that you tested in sandbox first.\n\n**Trade-offs**:\n- ✅ Keeps working code\n- ✅ Adds local testing capability\n- ❌ Misses product ID validation benefit\n- ❌ Reinforces testing-after pattern\n- ❌ Requires extra vigilance in code review\n\n**If choosing this path**: Create .storekit immediately, verify locally, and commit a note explaining the approach.\n\n### Option C: Skip .storekit Entirely (Not Recommended)\n\nCommit without `.storekit` configuration, test only in sandbox.\n\n**Why this is problematic**:\n- Teammates can't test purchases locally\n- No validation of product IDs before runtime\n- Harder iteration (requires App Store Connect)\n- Missing documentation of product structure\n\n**Bottom line**: Choose Option A if possible, Option B if pragmatic, never Option C.\n\n---\n\n## Core Philosophy: Testing-First Workflow\n\n> **Best Practice**: Create and test StoreKit configuration BEFORE writing production purchase code.\n\n### Why .storekit-First Matters\n\nThe recommended workflow is to create `.storekit` configuration before writing any purchase code. This isn't arbitrary - it provides concrete benefits:\n\n**Immediate product ID validation**:\n- Typos caught in Xcode, not at runtime\n- Product configuration visible in project\n- No App Store Connect dependency for testing\n\n**Faster iteration**:\n- Test purchases in simulator instantly\n- No network requests during development\n- Accelerated subscription renewal for testing\n\n**Team benefits**:\n- Anyone can test purchase flows locally\n- Product catalog documented in code\n- Code review includes purchase testing\n\n**Common objections addressed**:\n\n❓ **\"I already tested in sandbox\"** - Sandbox testing is valuable but comes later. Local testing with .storekit is faster and enables true TDD.\n\n❓ **\"My code works\"** - Working code is great! Adding .storekit makes it easier for teammates to verify and maintain.\n\n❓ **\"I've done this before\"** - Experience is valuable. The .storekit-first workflow makes experienced developers even more productive.\n\n❓ **\"Time pressure\"** - Creating .storekit takes 10-15 minutes. The time saved in iteration pays back immediately.\n\n### The Recommended Workflow\n\n```\nStoreKit Config → Local Testing → Production Code → Unit Tests → Sandbox Testing\n      ↓               ↓                ↓               ↓              ↓\n   .storekit      Test purchases   StoreManager    Mock store    Integration test\n```\n\n**Why this order helps**:\n1. **StoreKit Config First**: Defines products without App Store Connect dependency\n2. **Local Testing**: Validates product IDs and purchase flows immediately\n3. **Production Code**: Implements against validated product configuration\n4. **Unit Tests**: Verifies business logic with mocked store responses\n5. **Sandbox Testing**: Final validation in App Store environment\n\n**Benefits of following this workflow**:\n- Product IDs validated before writing code\n- Faster development iteration\n- Easier team collaboration\n- Better test coverage\n\n---\n\n## Mandatory Checklist\n\nBefore marking IAP implementation complete, **ALL** items must be verified:\n\n### Phase 1: Testing Foundation\n- [ ] Created `.storekit` configuration file with all products\n- [ ] Verified each product type renders correctly in StoreKit preview\n- [ ] Tested successful purchase flow for each product in Xcode\n- [ ] Tested purchase failure scenarios (insufficient funds, cancelled)\n- [ ] Tested restore purchases flow\n- [ ] For subscriptions: tested renewal, expiration, and upgrade\u002Fdowngrade\n\n### Phase 2: Architecture\n- [ ] Centralized StoreManager class exists (single source of truth)\n- [ ] StoreManager is ObservableObject (SwiftUI) or uses NotificationCenter\n- [ ] Transaction observer listens for updates via `Transaction.updates`\n- [ ] All transaction verification uses `VerificationResult`\n- [ ] All transactions call `.finish()` after entitlement granted\n- [ ] Product loading happens at app launch or before displaying store\n\n### Phase 3: Purchase Flow\n- [ ] Purchase uses new `purchase(confirmIn:options:)` with UI context (iOS 18.2+)\n- [ ] Purchase handles all `PurchaseResult` cases (success, userCancelled, pending)\n- [ ] Purchase verifies transaction signature before granting entitlement\n- [ ] Purchase stores transaction receipt\u002Fidentifier for support\n- [ ] appAccountToken set for all purchases (if using server backend)\n\n### Phase 4: Subscription Management (if applicable)\n- [ ] Subscription status tracked via `Product.SubscriptionInfo.Status`\n- [ ] Current entitlements checked via `Transaction.currentEntitlements(for:)`\n- [ ] Renewal info accessed for expiration, renewal date, offer status\n- [ ] Subscription views use ProductView or SubscriptionStoreView\n- [ ] Win-back offers implemented for expired subscriptions\n- [ ] Grace period and billing retry states handled\n\n### Phase 5: Restore & Sync\n- [ ] Restore purchases implemented (required by App Store Review)\n- [ ] Restore uses `Transaction.currentEntitlements` or `Transaction.all`\n- [ ] Family Sharing transactions identified (if supported)\n- [ ] Server sync implemented (if using backend)\n- [ ] Cross-device entitlement sync tested\n\n### Phase 6: Error Handling\n- [ ] Network errors handled gracefully (retries, user messaging)\n- [ ] Invalid product IDs detected and logged\n- [ ] Purchase failures show user-friendly error messages\n- [ ] Transaction verification failures logged and reported\n- [ ] Refund notifications handled (via App Store Server Notifications)\n\n### Phase 7: Testing & Validation\n- [ ] Unit tests verify purchase logic with mocked Product\u002FTransaction\n- [ ] Unit tests verify subscription status determination\n- [ ] Integration tests with StoreKit configuration pass\n- [ ] Sandbox testing with real Apple ID completed\n- [ ] TestFlight testing completed before production release\n\n---\n\n## Step 1: Create StoreKit Configuration (FIRST!)\n\n**DO THIS BEFORE WRITING ANY PURCHASE CODE.**\n\n### Create Configuration File\n\n1. **Xcode → File → New → File → StoreKit Configuration File**\n2. **Save as**: `Products.storekit` (or your app name)\n3. **Add to target**: ✅ (include in app bundle for testing)\n\n### Add Products\n\nClick \"+\" and add each product type:\n\n#### Consumable\n```\nProduct ID: com.yourapp.coins_100\nReference Name: 100 Coins\nPrice: $0.99\n```\n\n#### Non-Consumable\n```\nProduct ID: com.yourapp.premium\nReference Name: Premium Upgrade\nPrice: $4.99\n```\n\n#### Auto-Renewable Subscription\n```\nProduct ID: com.yourapp.pro_monthly\nReference Name: Pro Monthly\nPrice: $9.99\u002Fmonth\nSubscription Group ID: pro_tier\n```\n\n### Test Immediately\n\n1. **Run app in simulator**\n2. **Scheme → Edit Scheme → Run → Options**\n3. **StoreKit Configuration**: Select `Products.storekit`\n4. **Verify**: Products load, purchases complete, transactions appear\n\n---\n\n## Step 2: Implement StoreManager Architecture\n\n### Required Pattern: Centralized StoreManager\n\n**All purchase logic must go through a single StoreManager.** No scattered `Product.purchase()` calls throughout app.\n\n```swift\nimport StoreKit\n\n@MainActor\nfinal class StoreManager: ObservableObject {\n    \u002F\u002F Published state for UI\n    @Published private(set) var products: [Product] = []\n    @Published private(set) var purchasedProductIDs: Set\u003CString> = []\n\n    \u002F\u002F Product IDs from StoreKit configuration\n    private let productIDs = [\n        \"com.yourapp.coins_100\",\n        \"com.yourapp.premium\",\n        \"com.yourapp.pro_monthly\"\n    ]\n\n    private var transactionListener: Task\u003CVoid, Never>?\n\n    init() {\n        \u002F\u002F Start transaction listener immediately\n        transactionListener = listenForTransactions()\n\n        Task {\n            await loadProducts()\n            await updatePurchasedProducts()\n        }\n    }\n\n    deinit {\n        transactionListener?.cancel()\n    }\n}\n```\n\n**Why @MainActor**: Published properties must update on main thread for UI binding.\n\n### Load Products (At Launch)\n\n```swift\nextension StoreManager {\n    func loadProducts() async {\n        do {\n            \u002F\u002F Load products from App Store\n            let loadedProducts = try await Product.products(for: productIDs)\n\n            \u002F\u002F Update published property on main thread\n            self.products = loadedProducts\n\n        } catch {\n            print(\"Failed to load products: \\(error)\")\n            \u002F\u002F Show error to user\n        }\n    }\n}\n```\n\n**Call from**: `App.init()` or first view's `.task` modifier\n\n### Listen for Transactions (REQUIRED)\n\n```swift\nextension StoreManager {\n    func listenForTransactions() -> Task\u003CVoid, Never> {\n        Task.detached { [weak self] in\n            \u002F\u002F Listen for ALL transaction updates\n            for await verificationResult in Transaction.updates {\n                await self?.handleTransaction(verificationResult)\n            }\n        }\n    }\n\n    @MainActor\n    private func handleTransaction(_ result: VerificationResult\u003CTransaction>) async {\n        \u002F\u002F Verify transaction signature\n        guard let transaction = try? result.payloadValue else {\n            print(\"Transaction verification failed\")\n            return\n        }\n\n        \u002F\u002F Grant entitlement to user\n        await grantEntitlement(for: transaction)\n\n        \u002F\u002F CRITICAL: Always finish transaction\n        await transaction.finish()\n\n        \u002F\u002F Update purchased products\n        await updatePurchasedProducts()\n    }\n}\n```\n\n**Why detached**: Transaction listener runs independently of view lifecycle\n\n---\n\n## Step 3: Implement Purchase Flow\n\n### Purchase with UI Context (iOS 18.2+)\n\n```swift\nextension StoreManager {\n    func purchase(_ product: Product, confirmIn scene: UIWindowScene) async throws -> Bool {\n        \u002F\u002F Perform purchase with UI context for payment sheet\n        let result = try await product.purchase(confirmIn: scene)\n\n        switch result {\n        case .success(let verificationResult):\n            \u002F\u002F Verify the transaction\n            guard let transaction = try? verificationResult.payloadValue else {\n                print(\"Transaction verification failed\")\n                return false\n            }\n\n            \u002F\u002F Grant entitlement\n            await grantEntitlement(for: transaction)\n\n            \u002F\u002F CRITICAL: Finish transaction\n            await transaction.finish()\n\n            \u002F\u002F Update state\n            await updatePurchasedProducts()\n\n            return true\n\n        case .userCancelled:\n            \u002F\u002F User tapped \"Cancel\" in payment sheet\n            return false\n\n        case .pending:\n            \u002F\u002F Purchase requires action (Ask to Buy, payment issue)\n            \u002F\u002F Will be delivered via Transaction.updates when approved\n            return false\n\n        @unknown default:\n            return false\n        }\n    }\n}\n```\n\n### SwiftUI Purchase (Using Environment)\n\n```swift\nstruct ProductRow: View {\n    let product: Product\n    @Environment(\\.purchase) private var purchase\n\n    var body: some View {\n        Button(\"Buy \\(product.displayPrice)\") {\n            Task {\n                do {\n                    let result = try await purchase(product)\n                    \u002F\u002F Handle result\n                } catch {\n                    print(\"Purchase failed: \\(error)\")\n                }\n            }\n        }\n    }\n}\n```\n\n### Set appAccountToken (If Using Backend)\n\n```swift\nfunc purchase(\n    _ product: Product,\n    confirmIn scene: UIWindowScene,\n    accountToken: UUID\n) async throws -> Bool {\n    \u002F\u002F Purchase with appAccountToken for server-side association\n    let result = try await product.purchase(\n        confirmIn: scene,\n        options: [\n            .appAccountToken(accountToken)\n        ]\n    )\n\n    \u002F\u002F ... handle result\n}\n```\n\n**When to use**: When your backend needs to associate purchases with user accounts\n\n---\n\n## Step 4: Verify Transactions (MANDATORY)\n\n### Always Use VerificationResult\n\n```swift\nfunc handleTransaction(_ result: VerificationResult\u003CTransaction>) async {\n    switch result {\n    case .verified(let transaction):\n        \u002F\u002F ✅ Transaction signed by App Store\n        await grantEntitlement(for: transaction)\n        await transaction.finish()\n\n    case .unverified(let transaction, let error):\n        \u002F\u002F ❌ Transaction signature invalid\n        print(\"Unverified transaction: \\(error)\")\n        \u002F\u002F DO NOT grant entitlement\n        \u002F\u002F DO finish transaction to clear from queue\n        await transaction.finish()\n    }\n}\n```\n\n**Why verify**: Prevents granting entitlements for:\n- Fraudulent receipts\n- Jailbroken device receipts\n- Man-in-the-middle attacks\n\n### Check Transaction Fields\n\n```swift\nfunc grantEntitlement(for transaction: Transaction) async {\n    \u002F\u002F Check transaction hasn't been revoked\n    guard transaction.revocationDate == nil else {\n        print(\"Transaction was refunded\")\n        await revokeEntitlement(for: transaction.productID)\n        return\n    }\n\n    \u002F\u002F Grant based on product type\n    switch transaction.productType {\n    case .consumable:\n        await addConsumable(productID: transaction.productID)\n\n    case .nonConsumable:\n        await unlockFeature(productID: transaction.productID)\n\n    case .autoRenewable:\n        await activateSubscription(productID: transaction.productID)\n\n    default:\n        break\n    }\n}\n```\n\n---\n\n## Step 5: Track Current Entitlements\n\n### Check What User Owns\n\n```swift\nextension StoreManager {\n    func updatePurchasedProducts() async {\n        var purchased: Set\u003CString> = []\n\n        \u002F\u002F Iterate through all current entitlements\n        for await result in Transaction.currentEntitlements {\n            guard let transaction = try? result.payloadValue else {\n                continue\n            }\n\n            \u002F\u002F Only include active entitlements (not revoked)\n            if transaction.revocationDate == nil {\n                purchased.insert(transaction.productID)\n            }\n        }\n\n        self.purchasedProductIDs = purchased\n    }\n}\n```\n\n### Check Specific Product\n\n```swift\nfunc isEntitled(to productID: String) async -> Bool {\n    \u002F\u002F Check current entitlements for specific product\n    for await result in Transaction.currentEntitlements(for: productID) {\n        if let transaction = try? result.payloadValue,\n           transaction.revocationDate == nil {\n            return true\n        }\n    }\n\n    return false\n}\n```\n\n---\n\n## Step 6: Implement Subscription Management\n\n### Track Subscription Status\n\n```swift\nextension StoreManager {\n    func checkSubscriptionStatus(for groupID: String) async -> Product.SubscriptionInfo.Status? {\n        \u002F\u002F Get subscription statuses for group\n        guard let result = try? await Product.SubscriptionInfo.status(for: groupID),\n              let status = result.first else {\n            return nil\n        }\n\n        return status.state\n    }\n}\n```\n\n### Handle Subscription States\n\n```swift\nfunc updateSubscriptionUI(for status: Product.SubscriptionInfo.Status) {\n    switch status.state {\n    case .subscribed:\n        \u002F\u002F User has active subscription\n        showSubscribedContent()\n\n    case .expired:\n        \u002F\u002F Subscription expired - show win-back offer\n        showResubscribeOffer()\n\n    case .inGracePeriod:\n        \u002F\u002F Billing issue - show payment update prompt\n        showUpdatePaymentPrompt()\n\n    case .inBillingRetryPeriod:\n        \u002F\u002F Apple retrying payment - maintain access\n        showBillingRetryMessage()\n\n    case .revoked:\n        \u002F\u002F Family Sharing access removed\n        removeAccess()\n\n    @unknown default:\n        break\n    }\n}\n```\n\n### Use StoreKit Views (iOS 17+)\n\n```swift\nstruct SubscriptionView: View {\n    var body: some View {\n        SubscriptionStoreView(groupID: \"pro_tier\") {\n            \u002F\u002F Marketing content\n            VStack {\n                Image(\"premium-icon\")\n                Text(\"Unlock all features\")\n            }\n        }\n        .subscriptionStoreControlStyle(.prominentPicker)\n    }\n}\n```\n\n---\n\n## Step 7: Implement Restore Purchases (REQUIRED)\n\n### Restore Flow\n\n```swift\nextension StoreManager {\n    func restorePurchases() async {\n        \u002F\u002F Sync all transactions from App Store\n        try? await AppStore.sync()\n\n        \u002F\u002F Update current entitlements\n        await updatePurchasedProducts()\n    }\n}\n```\n\n### UI Button\n\n```swift\nstruct SettingsView: View {\n    @StateObject private var store = StoreManager()\n\n    var body: some View {\n        Button(\"Restore Purchases\") {\n            Task {\n                await store.restorePurchases()\n            }\n        }\n    }\n}\n```\n\n**App Store Requirement**: Apps with IAP must provide restore functionality for non-consumables and subscriptions.\n\n---\n\n## Step 8: Handle Refunds\n\n### Listen for Refund Notifications\n\n```swift\nextension StoreManager {\n    func listenForTransactions() -> Task\u003CVoid, Never> {\n        Task.detached { [weak self] in\n            for await verificationResult in Transaction.updates {\n                await self?.handleTransaction(verificationResult)\n            }\n        }\n    }\n\n    @MainActor\n    private func handleTransaction(_ result: VerificationResult\u003CTransaction>) async {\n        guard let transaction = try? result.payloadValue else {\n            return\n        }\n\n        \u002F\u002F Check if transaction was refunded\n        if let revocationDate = transaction.revocationDate {\n            print(\"Transaction refunded on \\(revocationDate)\")\n            await revokeEntitlement(for: transaction.productID)\n        } else {\n            await grantEntitlement(for: transaction)\n        }\n\n        await transaction.finish()\n    }\n}\n```\n\n---\n\n## Step 9: Unit Testing\n\n### Mock Store Responses\n\n```swift\nprotocol StoreProtocol {\n    func products(for ids: [String]) async throws -> [Product]\n    func purchase(_ product: Product) async throws -> PurchaseResult\n}\n\n\u002F\u002F Production\nfinal class StoreManager: StoreProtocol {\n    func products(for ids: [String]) async throws -> [Product] {\n        try await Product.products(for: ids)\n    }\n}\n\n\u002F\u002F Testing\nfinal class MockStore: StoreProtocol {\n    var mockProducts: [Product] = []\n    var mockPurchaseResult: PurchaseResult?\n\n    func products(for ids: [String]) async throws -> [Product] {\n        mockProducts\n    }\n\n    func purchase(_ product: Product) async throws -> PurchaseResult {\n        mockPurchaseResult ?? .userCancelled\n    }\n}\n```\n\n### Test Purchase Logic\n\n```swift\n@Test func testSuccessfulPurchase() async {\n    let mockStore = MockStore()\n    let manager = StoreManager(store: mockStore)\n\n    \u002F\u002F Given: Mock successful purchase\n    mockStore.mockPurchaseResult = .success(.verified(mockTransaction))\n\n    \u002F\u002F When: Purchase product\n    let result = await manager.purchase(mockProduct)\n\n    \u002F\u002F Then: Entitlement granted\n    #expect(result == true)\n    #expect(manager.purchasedProductIDs.contains(\"com.app.premium\"))\n}\n\n@Test func testCancelledPurchase() async {\n    let mockStore = MockStore()\n    let manager = StoreManager(store: mockStore)\n\n    \u002F\u002F Given: User cancels\n    mockStore.mockPurchaseResult = .userCancelled\n\n    \u002F\u002F When: Purchase product\n    let result = await manager.purchase(mockProduct)\n\n    \u002F\u002F Then: No entitlement granted\n    #expect(result == false)\n    #expect(manager.purchasedProductIDs.isEmpty)\n}\n```\n\n---\n\n## Common Anti-Patterns (NEVER DO THIS)\n\n### ❌ No StoreKit Configuration\n\n```swift\n\u002F\u002F ❌ WRONG: Writing purchase code without .storekit file\nlet products = try await Product.products(for: productIDs)\n\u002F\u002F Can't test this without App Store Connect setup!\n```\n\n✅ **Correct**: Create `.storekit` file FIRST, test in Xcode, THEN implement.\n\n### ❌ Code Before .storekit Config\n\n```swift\n\u002F\u002F ❌ Less ideal: Write code, test in sandbox, add .storekit later\nlet products = try await Product.products(for: productIDs)\nlet result = try await product.purchase(confirmIn: scene)\n\u002F\u002F \"I tested this in sandbox, it works! I'll add .storekit config later.\"\n```\n\n✅ **Recommended**: Create `.storekit` config first, then write code.\n\n**If you're in this situation**: See \"Already Wrote Code Before Creating .storekit Config?\" section above for your options (A, B, or C).\n\n**Why .storekit-first is better**:\n- Product ID typos caught in Xcode, not at runtime\n- Faster iteration without network requests\n- Teammates can test locally\n- Documents product structure in code\n\n**Sandbox testing is valuable** - it validates against real App Store infrastructure. But starting with .storekit makes sandbox testing easier because you've already validated product IDs locally.\n\n### ❌ Scattered Purchase Calls\n\n```swift\n\u002F\u002F ❌ WRONG: Purchase calls scattered throughout app\nButton(\"Buy\") {\n    try await product.purchase()  \u002F\u002F In view 1\n}\n\nButton(\"Subscribe\") {\n    try await subscriptionProduct.purchase()  \u002F\u002F In view 2\n}\n```\n\n✅ **Correct**: All purchases through centralized StoreManager.\n\n### ❌ Forgetting to Finish Transactions\n\n```swift\n\u002F\u002F ❌ WRONG: Never calling finish()\nfunc handleTransaction(_ transaction: Transaction) {\n    grantEntitlement(for: transaction)\n    \u002F\u002F Missing: await transaction.finish()\n}\n```\n\n✅ **Correct**: ALWAYS call `transaction.finish()` after granting entitlement.\n\n### ❌ Not Verifying Transactions\n\n```swift\n\u002F\u002F ❌ WRONG: Using unverified transaction\nfor await transaction in Transaction.all {\n    grantEntitlement(for: transaction)  \u002F\u002F Unsafe!\n}\n```\n\n✅ **Correct**: Always check `VerificationResult` before granting.\n\n### ❌ Ignoring Transaction Listener\n\n```swift\n\u002F\u002F ❌ WRONG: Only handling purchases in purchase() method\nfunc purchase() {\n    let result = try await product.purchase()\n    \u002F\u002F What about pending purchases, family sharing, restore?\n}\n```\n\n✅ **Correct**: Listen to `Transaction.updates` for ALL transaction sources.\n\n### ❌ Not Implementing Restore\n\n```swift\n\u002F\u002F ❌ WRONG: No restore button\n\u002F\u002F App Store will REJECT your app!\n```\n\n✅ **Correct**: Provide visible \"Restore Purchases\" button in settings.\n\n---\n\n## Validation\n\nBefore marking IAP implementation complete, verify:\n\n### Code Inspection\n\nRun these searches to verify compliance:\n\n```bash\n# Check StoreKit configuration exists\nfind . -name \"*.storekit\"\n\n# Check transaction.finish() is called\nrg \"transaction\\.finish\\(\\)\" --type swift\n\n# Check VerificationResult usage\nrg \"VerificationResult\" --type swift\n\n# Check Transaction.updates listener\nrg \"Transaction\\.updates\" --type swift\n\n# Check restore implementation\nrg \"AppStore\\.sync|Transaction\\.all\" --type swift\n```\n\n### Functional Testing\n\n- [ ] Can purchase each product type in StoreKit configuration\n- [ ] Can cancel purchase and state remains consistent\n- [ ] Can restore purchases and regain access\n- [ ] Subscription renewal\u002Fexpiration works as expected\n- [ ] Refunded transactions revoke access\n- [ ] Family Sharing transactions identified (if supported)\n\n### Sandbox Testing\n\n- [ ] Real Apple ID sandbox purchases complete\n- [ ] TestFlight beta testers confirm purchase flows work\n- [ ] Server-side validation works (if using backend)\n\n---\n\n## Resources\n\n**WWDC**: 2025-241, 2025-249, 2023-10013, 2021-10114\n\n**Docs**: \u002Fstorekit, \u002Fappstoreserverapi\n\n**Skills**: axiom-storekit-ref\n\n",{"name":5,"license":15,"metadata":39,"description":7},{"version":40},"1.0","main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-in-app-purchases",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":51,"prompt":61,"zipAvailable":62},[52,55,58],{"tool":53,"command":54},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill axiom-in-app-purchases",{"tool":56,"command":57},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill axiom-in-app-purchases",{"tool":59,"command":60},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill axiom-in-app-purchases","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-in-app-purchases\u002FSKILL.md",true,[64,70],{"path":65,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":68,"sourceHtmlUrl":69},"references\u002Fdoubles.md","REFERENCE","参考文档",2069,"https:\u002F\u002Fgithub.com\u002Fhaxorize\u002Fskills\u002Fblob\u002Fmain\u002Fsrc\u002Ftdd\u002Freferences\u002Fdoubles.md",{"path":71,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":72,"sourceHtmlUrl":73},"references\u002Funtested-at-close.md",1205,"https:\u002F\u002Fgithub.com\u002Fhaxorize\u002Fskills\u002Fblob\u002Fmain\u002Fsrc\u002Ftdd\u002Freferences\u002Funtested-at-close.md",[75,84,93,102,108,114],{"skillNo":76,"name":77,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":34},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[81,82,83],"model","model hierarchy","model hierarchy skill",{"skillNo":85,"name":86,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":34},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[90,91,92],"MCP","zoom","zoom mcp",{"skillNo":94,"name":95,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":34},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[99,100,101,91],"sdk","zoom apps sdk","apps",{"skillNo":103,"name":104,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":34},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[104],{"skillNo":109,"name":110,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":34},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[110],{"skillNo":115,"name":116,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":34},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[116]]