Matthias Nott
2026-04-01 d54dc1eed8a7864bee407b8460156513b203e8a5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// Product ID for the one-time full-access purchase.
const String kFullAccessProductId = 'com.tekmidian.pailot.fullaccess';
/// Maximum sessions allowed on the free tier.
const int kFreeTierMaxSessions = 2;
/// Maximum message age for free-tier users (15 minutes).
const Duration kFreeTierMessageTtl = Duration(minutes: 15);
/// Shared preference key for caching purchase status locally.
const String _kProCacheKey = 'pailot_is_pro';
/// Service that manages the StoreKit 2 / in_app_purchase lifecycle.
///
/// Usage:
///   final svc = PurchaseService();
///   await svc.initialize();
///   svc.addListener(() { ... });
///   bool pro = svc.isPro;
///
/// Call [dispose] when done.
class PurchaseService extends ChangeNotifier {
  PurchaseService._();
  static final PurchaseService instance = PurchaseService._();
  bool _isPro = false;
  bool _isLoading = false;
  String? _errorMessage;
  StreamSubscription<List<PurchaseDetails>>? _subscription;
  /// Whether the user has purchased full access.
  bool get isPro => _isPro;
  /// True while a purchase or restore operation is in progress.
  bool get isLoading => _isLoading;
  /// Non-null if the last operation produced an error message.
  String? get errorMessage => _errorMessage;
  // ---------------------------------------------------------------------------
  // Lifecycle
  // ---------------------------------------------------------------------------
  /// Initialize the service. Call once at app startup.
  Future<void> initialize() async {
    // Restore cached value immediately so UI doesn't flicker.
    final prefs = await SharedPreferences.getInstance();
    _isPro = prefs.getBool(_kProCacheKey) ?? false;
    notifyListeners();
    // Listen for ongoing purchase updates.
    final purchaseUpdated = InAppPurchase.instance.purchaseStream;
    _subscription = purchaseUpdated.listen(
      _handlePurchaseUpdates,
      onError: (Object err) {
        _errorMessage = err.toString();
        notifyListeners();
      },
    );
    // Verify with StoreKit on each launch (catches refunds / family sharing).
    await restorePurchases(silent: true);
  }
  @override
  void dispose() {
    _subscription?.cancel();
    super.dispose();
  }
  // ---------------------------------------------------------------------------
  // Public API
  // ---------------------------------------------------------------------------
  /// Initiate the purchase flow for full access.
  Future<void> purchaseFullAccess() async {
    _errorMessage = null;
    _isLoading = true;
    notifyListeners();
    try {
      final bool available = await InAppPurchase.instance.isAvailable();
      if (!available) {
        _errorMessage = 'Store not available. Check your internet connection.';
        _isLoading = false;
        notifyListeners();
        return;
      }
      final ProductDetailsResponse response = await InAppPurchase.instance
          .queryProductDetails({kFullAccessProductId});
      if (response.error != null || response.productDetails.isEmpty) {
        _errorMessage =
            'Product not found. Please try again later.';
        _isLoading = false;
        notifyListeners();
        return;
      }
      final ProductDetails product = response.productDetails.first;
      final PurchaseParam param = PurchaseParam(productDetails: product);
      await InAppPurchase.instance.buyNonConsumable(purchaseParam: param);
      // Result arrives via purchaseStream — _isLoading cleared there.
    } catch (e) {
      _errorMessage = 'Purchase failed: $e';
      _isLoading = false;
      notifyListeners();
    }
  }
  /// Restore previously completed purchases (also called on app launch).
  Future<void> restorePurchases({bool silent = false}) async {
    if (!silent) {
      _errorMessage = null;
      _isLoading = true;
      notifyListeners();
    }
    try {
      await InAppPurchase.instance.restorePurchases();
      // Results arrive asynchronously via purchaseStream.
      // For non-silent restores _isLoading is cleared there.
      if (silent) {
        // Give the stream a moment to deliver any results.
        await Future<void>.delayed(const Duration(seconds: 2));
      }
    } catch (e) {
      if (!silent) {
        _errorMessage = 'Restore failed: $e';
        _isLoading = false;
        notifyListeners();
      }
    }
  }
  // ---------------------------------------------------------------------------
  // Internal
  // ---------------------------------------------------------------------------
  Future<void> _handlePurchaseUpdates(
      List<PurchaseDetails> purchases) async {
    for (final PurchaseDetails purchase in purchases) {
      if (purchase.productID != kFullAccessProductId) continue;
      switch (purchase.status) {
        case PurchaseStatus.purchased:
        case PurchaseStatus.restored:
          await _deliverPurchase(purchase);
          break;
        case PurchaseStatus.error:
          _errorMessage = purchase.error?.message ?? 'Purchase failed.';
          _isLoading = false;
          notifyListeners();
          break;
        case PurchaseStatus.canceled:
          _isLoading = false;
          notifyListeners();
          break;
        case PurchaseStatus.pending:
          // Show loading while pending (e.g. Ask to Buy).
          _isLoading = true;
          notifyListeners();
          break;
      }
      // Complete the transaction to prevent it from being re-delivered.
      if (purchase.pendingCompletePurchase) {
        await InAppPurchase.instance.completePurchase(purchase);
      }
    }
  }
  Future<void> _deliverPurchase(PurchaseDetails purchase) async {
    _isPro = true;
    _isLoading = false;
    _errorMessage = null;
    // Persist so the next app launch restores from cache quickly.
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_kProCacheKey, true);
    debugPrint('[Purchase] Full access granted for ${purchase.productID}');
    notifyListeners();
  }
}