Subscription lifecycle

From gustavscirulis/snapgrid · View interactive version

Subscription lifecycle is an AI agent skill from the GitHub repository gustavscirulis/snapgrid. Generates StoreKit 2 subscription lifecycle management — grace periods, billing retry, offer codes, win-back offers, upgrade/downgrade paths, and subscription status monitoring. Use when user needs post-purchase subscription state handling beyond the initial paywall.

How to use this skill

Skill file

Subscription Lifecycle Generator

Generate production StoreKit 2 subscription lifecycle management with real-time status monitoring, grace period handling, billing retry detection, offer code redemption, win-back offers, and upgrade/downgrade path support.

Different from paywall-generator: The paywall generator handles the purchase UI and initial transaction. This skill handles everything that happens after purchase — monitoring subscription state changes, handling payment failures, retaining churning users, and managing tier transitions.

When This Skill Activates

Use this skill when the user:

Pre-Generation Checks

1. Project Context Detection

2. Existing StoreKit Detection

Search for existing subscription code:

Glob: **/*Store*.swift, **/*Subscription*.swift, **/*Entitlement*.swift
Grep: "import StoreKit" or "Transaction.updates" or "Product.SubscriptionInfo"

If paywall-generator output found:

If no existing StoreKit code found:

3. Entitlement Check

Grep: "In-App Purchase" or "StoreKit" in *.entitlements

If missing, warn user to add the In-App Purchase capability in Xcode.

Configuration Questions

Ask user via AskUserQuestion:

  1. Subscription tiers?
  1. Lifecycle features? (multi-select)
  1. Include subscription dashboard UI?
  1. Server-side verification?

Generation Process

Step 1: Read Templates and Patterns

Read patterns.md for lifecycle state diagrams and StoreKit 2 behavior reference.

Read templates.md for production Swift code templates.

Step 2: Create Core Files

Generate these files:

  1. SubscriptionState.swift — Comprehensive enum for all lifecycle states
  2. SubscriptionMonitor.swift — @Observable class monitoring real-time status via Transaction.updates and Product.SubscriptionInfo
  3. SubscriptionEntitlement.swift — Maps product IDs to feature access levels

Step 3: Create Lifecycle Handlers

Based on configuration:

  1. GracePeriodHandler.swift — If grace period selected
  2. OfferManager.swift — If offer codes or win-back selected

Step 4: Create UI Files

If dashboard UI selected:

  1. SubscriptionDashboardView.swift — SwiftUI view for plan management

Step 5: Determine File Location

Check project structure:

Output Format

After generation, provide:

Files Created

SubscriptionLifecycle/
├── SubscriptionState.swift           # All lifecycle states enum
├── SubscriptionMonitor.swift         # Real-time status monitoring
├── SubscriptionEntitlement.swift     # Product ID → feature mapping
├── GracePeriodHandler.swift          # Grace period detection & UI (optional)
├── OfferManager.swift                # Offers, codes, win-back (optional)
└── SubscriptionDashboardView.swift   # Plan management UI (optional)

Integration with Existing Paywall

If paywall-generator was already used:

// In your existing StoreKitManager, add lifecycle monitoring
@Observable
final class StoreKitManager {
    // ... existing product loading and purchase code ...

    let lifecycleMonitor = SubscriptionMonitor()

    func startMonitoring() async {
        await lifecycleMonitor.start(
            groupID: "your.subscription.group",
            entitlements: SubscriptionEntitlement.default
        )
    }
}

App Entry Point:

@main
struct MyApp: App {
    @State private var monitor = SubscriptionMonitor()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(monitor)
                .task { await monitor.start(groupID: "your.group.id") }
        }
    }
}

Check Access Anywhere:

struct PremiumFeatureView: View {
    @Environment(SubscriptionMonitor.self) private var monitor

    var body: some View {
        if monitor.hasAccess {
            // Full feature
            PremiumContent()
        } else if monitor.state == .inGracePeriod {
            // Feature still accessible, but show payment warning
            VStack {
                PaymentWarningBanner()
                PremiumContent()
            }
        } else {
            // Show paywall
            PaywallView()
        }
    }
}

Grace Period Notification:

struct ContentView: View {
    @Environment(SubscriptionMonitor.self) private var monitor

    var body: some View {
        NavigationStack {
            MainContent()
                .overlay(alignment: .top) {
                    if monitor.state == .inGracePeriod {
                        GracePeriodBanner(
                            daysRemaining: monitor.gracePeriodDaysRemaining,
                            onFixPayment: { /* open manage subscriptions */ }
                        )
                    }
                }
        }
    }
}

Win-Back Offer:

struct ExpiredUserView: View {
    @State private var offerManager = OfferManager()

    var body: some View {
        if let winBackOffer = offerManager.availableWinBackOffer {
            WinBackOfferCard(offer: winBackOffer) {
                try await offerManager.redeemWinBackOffer(winBackOffer)
            }
        } else {
            StandardPaywallView()
        }
    }
}

Testing

@Test
func gracePeriodGrantsAccess() async throws {
    let monitor = SubscriptionMonitor()
    monitor.updateState(.inGracePeriod(expiresIn: 3))

    #expect(monitor.hasAccess == true)
    #expect(monitor.gracePeriodDaysRemaining == 3)
}

@Test
func billingRetryGrantsAccess() async throws {
    let monitor = SubscriptionMonitor()
    monitor.updateState(.inBillingRetry)

    #expect(monitor.hasAccess == true)
    #expect(monitor.shouldShowPaymentWarning == true)
}

@Test
func expiredRevokesAccess() async throws {
    let monitor = SubscriptionMonitor()
    monitor.updateState(.expired(reason: .autoRenewDisabled))

    #expect(monitor.hasAccess == false)
}

@Test
func upgradeChangesEntitlementLevel() async throws {
    let entitlements = SubscriptionEntitlement.default
    let basicLevel = entitlements.accessLevel(for: "com.app.basic.monthly")
    let proLevel = entitlements.accessLevel(for: "com.app.pro.monthly")

    #expect(proLevel > basicLevel)
}

Common Patterns

Status Checking

// Check current subscription state
let state = monitor.state
switch state {
case .active(let renewalDate):
    print("Active until \(renewalDate)")
case .inGracePeriod(let expiresIn):
    print("Payment issue — \(expiresIn) days to fix")
case .inBillingRetry:
    print("Apple retrying payment")
case .expired(let reason):
    print("Expired: \(reason)")
case .revoked:
    print("Refunded or revoked")
default:
    break
}

Grace Period Notification

// Show in-app banner during grace period
if case .inGracePeriod(let days) = monitor.state {
    Banner(
        message: "Payment issue. Update payment method within \(days) days.",
        action: "Fix Now",
        onTap: { await openSubscriptionManagement() }
    )
}

Offer Code Redemption

// Present the system offer code redemption sheet
try await AppStore.presentOfferCodeRedeemSheet(in: windowScene)

Tier Upgrade

// Upgrade from Basic to Pro (takes effect immediately)
let proProduct = try await Product.products(for: ["com.app.pro.monthly"]).first!
let result = try await proProduct.purchase()
// StoreKit handles prorating automatically

Gotchas

Transaction.currentEntitlements vs Product.SubscriptionInfo.status

Grace Period vs Billing Retry Period

Sandbox vs Production Testing

Offer Eligibility

Transaction.finish() is Critical

Never forget to call transaction.finish(). Unfinished transactions will be re-delivered on every app launch, causing duplicate processing and potential UI glitches.

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.