From eac04bc348ebd2d4b9279fd3f8e76b91c0339d65 Mon Sep 17 00:00:00 2001 From: Jonas Acker Date: Wed, 25 Nov 2026 17:00:56 +0100 Subject: [PATCH] Microsoft Store: record a Base purchase on the account for the Black Friday deal After a Store purchase, and once per account at sign-in, the app asks the backend (ms-store-sync) for a service ticket, turns it into a collections ID key (new native getCustomerCollectionsIdKey, StoreContext .GetCustomerCollectionsIdAsync) and hands it back; the backend reads the Store's acquiredDate and records the Base. The deal is now offered on the Microsoft Store build too. Co-Authored-By: Claude Opus 5.5 --- lib/utils/iap/cross_platform_base_promo.dart | 13 ++-- lib/utils/iap/iap_manager.dart | 5 ++ lib/utils/iap/ms_store_collections_sync.dart | 64 +++++++++++++++ lib/utils/iap/windows_iap_service.dart | 33 ++++++++ test/paywall_layout_test.dart | 4 +- .../iap/cross_platform_base_promo_test.dart | 2 +- .../iap/ms_store_collections_sync_test.dart | 77 +++++++++++++++++++ windows_iap/lib/windows_iap.dart | 12 +++ .../lib/windows_iap_method_channel.dart | 15 ++++ .../lib/windows_iap_platform_interface.dart | 9 +++ windows_iap/windows/windows_iap_plugin.cpp | 57 ++++++++++++++ 11 files changed, 283 insertions(+), 8 deletions(-) create mode 100644 lib/utils/iap/ms_store_collections_sync.dart create mode 100644 test/utils/iap/ms_store_collections_sync_test.dart diff --git a/lib/utils/iap/cross_platform_base_promo.dart b/lib/utils/iap/cross_platform_base_promo.dart index e6b9eaa9..cfd4fc5b 100644 --- a/lib/utils/iap/cross_platform_base_promo.dart +++ b/lib/utils/iap/cross_platform_base_promo.dart @@ -21,12 +21,15 @@ class CrossPlatformBasePromo { } /// Where a Base bought now reaches the account, so the backend can carry it - /// to other platforms. The Microsoft Store licence never does, and Linux has - /// no Base to buy. + /// to other platforms (the Microsoft Store through MsStoreCollectionsSync). + /// Linux has no Base to buy. static bool appliesTo(PurchaseChannel channel) => switch (channel) { - PurchaseChannel.appStore || PurchaseChannel.macAppStore || PurchaseChannel.playStore || PurchaseChannel.windowsDirect => - true, - PurchaseChannel.microsoftStore || PurchaseChannel.linuxDirect || PurchaseChannel.none => false, + PurchaseChannel.appStore || + PurchaseChannel.macAppStore || + PurchaseChannel.playStore || + PurchaseChannel.windowsDirect || + PurchaseChannel.microsoftStore => true, + PurchaseChannel.linuxDirect || PurchaseChannel.none => false, }; static bool isOfferedOn(PurchaseChannel channel) => isRunning && appliesTo(channel); diff --git a/lib/utils/iap/iap_manager.dart b/lib/utils/iap/iap_manager.dart index 7ccce7d4..28ccd147 100644 --- a/lib/utils/iap/iap_manager.dart +++ b/lib/utils/iap/iap_manager.dart @@ -649,6 +649,11 @@ class IAPManager { await _revenueCatService?.setAttributes(); await entitlements.refresh(force: true); await _syncPurchaseFlagFromEntitlements(); + // A Base bought in the Microsoft Store reaches the account only + // through this sync (no store webhook), once per account. + if (purchaseChannel == PurchaseChannel.microsoftStore && isPurchased.value) { + unawaited(_windowsIapService?.storeCollections.syncOnce()); + } // A rider who tapped Buy on the Windows Stripe build while logged out was // sent to the login gate; a genuine `signedIn` is our cue to finish the // checkout they started. Skip token refreshes / the initial session, diff --git a/lib/utils/iap/ms_store_collections_sync.dart b/lib/utils/iap/ms_store_collections_sync.dart new file mode 100644 index 00000000..d400313a --- /dev/null +++ b/lib/utils/iap/ms_store_collections_sync.dart @@ -0,0 +1,64 @@ +import 'package:bike_control/main.dart' show recordError; + +/// Records a Base bought in the Microsoft Store on the signed-in account, +/// dated by the Store, so cross-platform promotions can apply to it (see +/// `ms-store-sync` in the backend): +/// +/// 1. the backend issues a service ticket for this account, +/// 2. the Store turns it into a collections ID key +/// (`StoreContext.GetCustomerCollectionsIdAsync`), +/// 3. the backend reads the Store's record with that key and writes the +/// entitlement, then the app re-reads its entitlements. +/// +/// Every step is injected; WindowsIAPService wires the real ones. +class MsStoreCollectionsSync { + MsStoreCollectionsSync({ + required this.currentUserId, + required this.requestTicket, + required this.collectionsIdKey, + required this.submitKey, + required this.refreshEntitlements, + required this.readFlag, + required this.writeFlag, + void Function(Object error, StackTrace stack)? onError, + }) : _onError = onError ?? ((e, s) => recordError(e, s, context: 'Microsoft Store collections sync')); + + final String? Function() currentUserId; + final Future<({String serviceTicket, String publisherUserId})> Function() requestTicket; + final Future Function({required String serviceTicket, required String publisherUserId}) collectionsIdKey; + + /// Returns the backend's verdict: "active", "expired" or "none". + final Future Function(String collectionsIdKey) submitKey; + final Future Function() refreshEntitlements; + final Future Function(String key) readFlag; + final Future Function(String key, String value) writeFlag; + final void Function(Object error, StackTrace stack) _onError; + + static String _flagFor(String userId) => 'ms_store_base_synced_$userId'; + + /// After a Store purchase: always asks the Store. + Future sync() async { + final userId = currentUserId(); + if (userId == null) return; + try { + final ticket = await requestTicket(); + final key = await collectionsIdKey( + serviceTicket: ticket.serviceTicket, + publisherUserId: ticket.publisherUserId, + ); + final base = await submitKey(key); + if (base != 'none') await writeFlag(_flagFor(userId), base); + await refreshEntitlements(); + } catch (e, s) { + _onError(e, s); + } + } + + /// At launch and sign-in: only until the account has the Store purchase. + Future syncOnce() async { + final userId = currentUserId(); + if (userId == null) return; + if (await readFlag(_flagFor(userId)) != null) return; + await sync(); + } +} diff --git a/lib/utils/iap/windows_iap_service.dart b/lib/utils/iap/windows_iap_service.dart index b4c4c56b..39f1556a 100644 --- a/lib/utils/iap/windows_iap_service.dart +++ b/lib/utils/iap/windows_iap_service.dart @@ -3,13 +3,18 @@ import 'package:bike_control/gen/l10n.dart'; import 'package:bike_control/main.dart'; import 'package:bike_control/services/entitlements_service.dart'; import 'package:bike_control/utils/core.dart'; +import 'dart:async'; + +import 'package:bike_control/utils/auth/account_session.dart'; import 'package:bike_control/utils/iap/iap_manager.dart'; +import 'package:bike_control/utils/iap/ms_store_collections_sync.dart'; import 'package:bike_control/utils/iap/stripe_checkout_flow.dart'; import 'package:bike_control/utils/iap/windows_stripe_service.dart'; import 'package:bike_control/utils/windows_store_environment.dart'; import 'package:bike_control/widgets/ui/toast.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:shadcn_flutter/shadcn_flutter.dart'; +import 'package:supabase_flutter/supabase_flutter.dart' show HttpMethod; import 'package:windows_iap/windows_iap.dart'; /// Windows-specific IAP service for Microsoft Store purchases and server-side sync. @@ -33,6 +38,33 @@ class WindowsIAPService { storeId: _windowsIapPlugin.getStoreId, ); + /// Records a Base bought in the Microsoft Store on the account, dated by + /// the Store (Microsoft Store build only), for cross-platform promotions. + late final MsStoreCollectionsSync storeCollections = MsStoreCollectionsSync( + currentUserId: () { + final user = core.supabase.auth.currentSession?.user; + return hasAccount(user) ? user!.id : null; + }, + requestTicket: () async { + final data = await _invokeStoreSync({'action': 'ticket'}); + return (serviceTicket: data['serviceTicket'] as String, publisherUserId: data['publisherUserId'] as String); + }, + collectionsIdKey: _windowsIapPlugin.getCustomerCollectionsIdKey, + submitKey: (key) async { + final data = await _invokeStoreSync({'action': 'sync', 'collectionsIdKey': key}); + core.connection.signalNotification(LogNotification('Microsoft Store Base on account: ${data['base']}')); + return data['base'] as String? ?? 'none'; + }, + refreshEntitlements: () => _entitlementsService.refresh(force: true), + readFlag: (key) => _prefs.read(key: key), + writeFlag: (key, value) => _prefs.write(key: key, value: value), + ); + + Future> _invokeStoreSync(Map body) async { + final response = await core.supabase.functions.invoke('ms-store-sync', method: HttpMethod.post, body: body); + return Map.from(response.data as Map); + } + bool _isInitialized = false; String? _lastCommandDate; @@ -117,6 +149,7 @@ class WindowsIAPService { final status = await _windowsIapPlugin.makePurchase(productId); if (status == StorePurchaseStatus.succeeded || status == StorePurchaseStatus.alreadyPurchased) { IAPManager.instance.isPurchased.value = true; + if (!IAPManager.instance.isOutsideStoreWindowsBuild) unawaited(storeCollections.sync()); buildToast( title: AppLocalizations.current.purchaseSuccessfulTitle, subtitle: AppLocalizations.current.purchaseSuccessfulBody, diff --git a/test/paywall_layout_test.dart b/test/paywall_layout_test.dart index 635d6433..bc652540 100644 --- a/test/paywall_layout_test.dart +++ b/test/paywall_layout_test.dart @@ -310,8 +310,8 @@ Future main() async { expect(find.byKey(deal), findsNothing); }); - testWidgets('is not shown in the Microsoft Store build, whose purchase never reaches the account', (tester) async { - await pumpAt(tester, DateTime.utc(2026, 11, 27, 12), PurchaseChannel.microsoftStore); + testWidgets('is not shown on Linux, where Base is free', (tester) async { + await pumpAt(tester, DateTime.utc(2026, 11, 27, 12), PurchaseChannel.linuxDirect); expect(find.byKey(deal), findsNothing); }); }); diff --git a/test/utils/iap/cross_platform_base_promo_test.dart b/test/utils/iap/cross_platform_base_promo_test.dart index bbc752de..b618a894 100644 --- a/test/utils/iap/cross_platform_base_promo_test.dart +++ b/test/utils/iap/cross_platform_base_promo_test.dart @@ -24,7 +24,7 @@ void main() { expect(CrossPlatformBasePromo.isOfferedOn(PurchaseChannel.macAppStore), isTrue); expect(CrossPlatformBasePromo.isOfferedOn(PurchaseChannel.playStore), isTrue); expect(CrossPlatformBasePromo.isOfferedOn(PurchaseChannel.windowsDirect), isTrue); - expect(CrossPlatformBasePromo.isOfferedOn(PurchaseChannel.microsoftStore), isFalse); + expect(CrossPlatformBasePromo.isOfferedOn(PurchaseChannel.microsoftStore), isTrue); expect(CrossPlatformBasePromo.isOfferedOn(PurchaseChannel.linuxDirect), isFalse); }); } diff --git a/test/utils/iap/ms_store_collections_sync_test.dart b/test/utils/iap/ms_store_collections_sync_test.dart new file mode 100644 index 00000000..dd1074ef --- /dev/null +++ b/test/utils/iap/ms_store_collections_sync_test.dart @@ -0,0 +1,77 @@ +import 'package:bike_control/utils/iap/ms_store_collections_sync.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + late List calls; + late Map stored; + + MsStoreCollectionsSync build({String? userId = 'user-1', String base = 'active', Object? keyError}) { + return MsStoreCollectionsSync( + currentUserId: () => userId, + requestTicket: () async { + calls.add('ticket'); + return (serviceTicket: 'TICKET', publisherUserId: 'user-1'); + }, + collectionsIdKey: ({required serviceTicket, required publisherUserId}) async { + calls.add('key $serviceTicket $publisherUserId'); + if (keyError != null) throw keyError; + return 'KEY'; + }, + submitKey: (key) async { + calls.add('sync $key'); + return base; + }, + refreshEntitlements: () async => calls.add('refresh'), + readFlag: (k) async => stored[k], + writeFlag: (k, v) async => stored[k] = v, + ); + } + + setUp(() { + calls = []; + stored = {}; + }); + + test('ticket, Store key, backend sync, then the entitlements are re-read', () async { + await build().sync(); + expect(calls, ['ticket', 'key TICKET user-1', 'sync KEY', 'refresh']); + }); + + test('signed out: nothing to record the purchase on', () async { + await build(userId: null).sync(); + expect(calls, isEmpty); + }); + + test('once recorded for an account, the launch sync is skipped; after a purchase it runs again', () async { + await build().syncOnce(); + calls.clear(); + await build().syncOnce(); + expect(calls, isEmpty); + + await build().sync(); + expect(calls, contains('sync KEY')); + }); + + test('a Store without a Base purchase is checked again next time', () async { + await build(base: 'none').syncOnce(); + calls.clear(); + await build(base: 'none').syncOnce(); + expect(calls, contains('ticket')); + }); + + test('a failing Store key is reported, not thrown', () async { + final errors = []; + final sync = MsStoreCollectionsSync( + currentUserId: () => 'user-1', + requestTicket: () async => (serviceTicket: 'T', publisherUserId: 'user-1'), + collectionsIdKey: ({required serviceTicket, required publisherUserId}) async => throw StateError('store'), + submitKey: (_) async => 'active', + refreshEntitlements: () async {}, + readFlag: (_) async => null, + writeFlag: (_, _) async {}, + onError: (e, s) => errors.add(e), + ); + await sync.sync(); + expect(errors.single, isA()); + }); +} diff --git a/windows_iap/lib/windows_iap.dart b/windows_iap/lib/windows_iap.dart index 4e52a2bd..6a1f761e 100644 --- a/windows_iap/lib/windows_iap.dart +++ b/windows_iap/lib/windows_iap.dart @@ -79,6 +79,18 @@ class WindowsIap { ); } + /// A Microsoft Store ID key the publisher's server passes to the + /// collections API to read what this Store user owns. + Future getCustomerCollectionsIdKey({ + required String serviceTicket, + required String publisherUserId, + }) { + return WindowsIapPlatform.instance.getCustomerCollectionsIdKey( + serviceTicket: serviceTicket, + publisherUserId: publisherUserId, + ); + } + Future getStoreId() { return WindowsIapPlatform.instance.getStoreId(); } diff --git a/windows_iap/lib/windows_iap_method_channel.dart b/windows_iap/lib/windows_iap_method_channel.dart index 86653fd6..b18aaf78 100644 --- a/windows_iap/lib/windows_iap_method_channel.dart +++ b/windows_iap/lib/windows_iap_method_channel.dart @@ -130,6 +130,21 @@ class MethodChannelWindowsIap extends WindowsIapPlatform { return result ?? ''; } + @override + Future getCustomerCollectionsIdKey({ + required String serviceTicket, + required String publisherUserId, + }) async { + final result = await methodChannel.invokeMethod( + 'getCustomerCollectionsIdKey', + { + 'serviceTicket': serviceTicket, + 'publisherUserId': publisherUserId, + }, + ); + return result ?? ''; + } + @override Future getStoreId() async { final result = await methodChannel.invokeMethod('getStoreId'); diff --git a/windows_iap/lib/windows_iap_platform_interface.dart b/windows_iap/lib/windows_iap_platform_interface.dart index e5b25f2c..2182d3b5 100644 --- a/windows_iap/lib/windows_iap_platform_interface.dart +++ b/windows_iap/lib/windows_iap_platform_interface.dart @@ -54,6 +54,15 @@ abstract class WindowsIapPlatform extends PlatformInterface { throw UnimplementedError('getCustomerPurchaseIdKey() has not been implemented.'); } + /// A Microsoft Store ID key for the collections API, from a service ticket + /// the publisher's server issued (StoreContext.GetCustomerCollectionsIdAsync). + Future getCustomerCollectionsIdKey({ + required String serviceTicket, + required String publisherUserId, + }) { + throw UnimplementedError('getCustomerCollectionsIdKey() has not been implemented.'); + } + Future getStoreId() { throw UnimplementedError('getStoreId() has not been implemented.'); } diff --git a/windows_iap/windows/windows_iap_plugin.cpp b/windows_iap/windows/windows_iap_plugin.cpp index 00a4a7a2..1d739007 100644 --- a/windows_iap/windows/windows_iap_plugin.cpp +++ b/windows_iap/windows/windows_iap_plugin.cpp @@ -340,6 +340,38 @@ namespace windows_iap } } + foundation::IAsyncAction getCustomerCollectionsIdKey( + std::string serviceTicket, + std::string publisherUserId, + std::unique_ptr> resultCallback) + { + if (serviceTicket.empty()) + { + resultCallback->Error("invalid-args", "serviceTicket is required."); + co_return; + } + if (publisherUserId.empty()) + { + resultCallback->Error("invalid-args", "publisherUserId is required."); + co_return; + } + + try + { + auto collectionsId = co_await getStore().GetCustomerCollectionsIdAsync( + to_hstring(serviceTicket), + to_hstring(publisherUserId)); + + resultCallback->Success(flutter::EncodableValue(to_string(collectionsId))); + } + catch (const winrt::hresult_error &error) + { + resultCallback->Error( + std::to_string(error.code().value), + to_string(error.message())); + } + } + foundation::IAsyncAction getStoreId( std::unique_ptr> resultCallback) { @@ -438,6 +470,31 @@ namespace windows_iap auto publisherUserId = std::get(publisherUserIdIt->second); getCustomerPurchaseIdKey(serviceTicket, publisherUserId, std::move(result)); } + else if (method_call.method_name().compare("getCustomerCollectionsIdKey") == 0) + { + if (method_call.arguments() == nullptr) + { + result->Error("invalid-args", "Arguments are required."); + return; + } + auto args = std::get(*method_call.arguments()); + auto serviceTicketIt = args.find(flutter::EncodableValue("serviceTicket")); + auto publisherUserIdIt = args.find(flutter::EncodableValue("publisherUserId")); + if (serviceTicketIt == args.end() || !std::holds_alternative(serviceTicketIt->second)) + { + result->Error("invalid-args", "serviceTicket must be a string."); + return; + } + if (publisherUserIdIt == args.end() || !std::holds_alternative(publisherUserIdIt->second)) + { + result->Error("invalid-args", "publisherUserId must be a string."); + return; + } + getCustomerCollectionsIdKey( + std::get(serviceTicketIt->second), + std::get(publisherUserIdIt->second), + std::move(result)); + } else if (method_call.method_name().compare("getStoreId") == 0) { getStoreId(std::move(result));