import 'dart:io'; import 'package:flutter/services.dart'; import 'package:purchases_flutter/purchases_flutter.dart'; import 'package:cid_app/global_data.dart'; class SubscriptionService { static const _googleApiKey = 'test_xlLcZsCHGnotDSfUoDBmDCrjfaZ'; static const _appleApiKey = 'appl_dIdoPnRhnqwYwstFZSmoABcMJRW'; static const entitlementID = 'pro'; // Il nome dell'entitlement su RevenueCat static Future init() async { await Purchases.setLogLevel(LogLevel.debug); PurchasesConfiguration? configuration; if (Platform.isAndroid) { configuration = PurchasesConfiguration(_googleApiKey); } else if (Platform.isIOS) { configuration = PurchasesConfiguration(_appleApiKey); } if (configuration != null) { await Purchases.configure(configuration); await checkSubscriptionStatus(); // Ascolta i cambiamenti di stato (es. rinnovi in background) Purchases.addCustomerInfoUpdateListener((customerInfo) { _updateProStatus(customerInfo); }); } } static Future checkSubscriptionStatus() async { try { final customerInfo = await Purchases.getCustomerInfo(); _updateProStatus(customerInfo); } on PlatformException catch (e) { print('Errore controllo abbonamento: \${e.message}'); } } static void _updateProStatus(CustomerInfo customerInfo) { if (customerInfo.entitlements.all[entitlementID] != null && customerInfo.entitlements.all[entitlementID]!.isActive) { GlobalData.isPro = true; } else { GlobalData.isPro = false; } // TODO: Notifica l'interfaccia utente se necessario (es. tramite un Provider o ValueNotifier) } static Future fetchOfferings() async { try { final offerings = await Purchases.getOfferings(); return offerings; } on PlatformException catch (e) { print('Errore fetch offerte: \${e.message}'); return null; } } static Future purchasePackage(Package package) async { try { final customerInfo = await Purchases.purchasePackage(package); _updateProStatus(customerInfo); return GlobalData.isPro; } on PlatformException catch (e) { final errorCode = PurchasesErrorHelper.getErrorCode(e); if (errorCode != PurchasesErrorCode.purchaseCancelledError) { print('Errore acquisto: \${e.message}'); } return false; } } static Future restorePurchases() async { try { final customerInfo = await Purchases.restorePurchases(); _updateProStatus(customerInfo); return GlobalData.isPro; } on PlatformException catch (e) { print('Errore ripristino: \${e.message}'); return false; } } }