mirror of
https://github.com/jonasbark/swiftcontrol.git
synced 2026-11-28 16:58:41 +01:00
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
64
lib/utils/iap/ms_store_collections_sync.dart
Normal file
64
lib/utils/iap/ms_store_collections_sync.dart
Normal file
@@ -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<String> Function({required String serviceTicket, required String publisherUserId}) collectionsIdKey;
|
||||
|
||||
/// Returns the backend's verdict: "active", "expired" or "none".
|
||||
final Future<String> Function(String collectionsIdKey) submitKey;
|
||||
final Future<void> Function() refreshEntitlements;
|
||||
final Future<String?> Function(String key) readFlag;
|
||||
final Future<void> 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<void> 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<void> syncOnce() async {
|
||||
final userId = currentUserId();
|
||||
if (userId == null) return;
|
||||
if (await readFlag(_flagFor(userId)) != null) return;
|
||||
await sync();
|
||||
}
|
||||
}
|
||||
@@ -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<Map<String, dynamic>> _invokeStoreSync(Map<String, dynamic> body) async {
|
||||
final response = await core.supabase.functions.invoke('ms-store-sync', method: HttpMethod.post, body: body);
|
||||
return Map<String, dynamic>.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,
|
||||
|
||||
@@ -310,8 +310,8 @@ Future<void> 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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
|
||||
77
test/utils/iap/ms_store_collections_sync_test.dart
Normal file
77
test/utils/iap/ms_store_collections_sync_test.dart
Normal file
@@ -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<String> calls;
|
||||
late Map<String, String> 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 = <Object>[];
|
||||
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<StateError>());
|
||||
});
|
||||
}
|
||||
@@ -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<String> getCustomerCollectionsIdKey({
|
||||
required String serviceTicket,
|
||||
required String publisherUserId,
|
||||
}) {
|
||||
return WindowsIapPlatform.instance.getCustomerCollectionsIdKey(
|
||||
serviceTicket: serviceTicket,
|
||||
publisherUserId: publisherUserId,
|
||||
);
|
||||
}
|
||||
|
||||
Future<String?> getStoreId() {
|
||||
return WindowsIapPlatform.instance.getStoreId();
|
||||
}
|
||||
|
||||
@@ -130,6 +130,21 @@ class MethodChannelWindowsIap extends WindowsIapPlatform {
|
||||
return result ?? '';
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String> getCustomerCollectionsIdKey({
|
||||
required String serviceTicket,
|
||||
required String publisherUserId,
|
||||
}) async {
|
||||
final result = await methodChannel.invokeMethod<String>(
|
||||
'getCustomerCollectionsIdKey',
|
||||
{
|
||||
'serviceTicket': serviceTicket,
|
||||
'publisherUserId': publisherUserId,
|
||||
},
|
||||
);
|
||||
return result ?? '';
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> getStoreId() async {
|
||||
final result = await methodChannel.invokeMethod<String>('getStoreId');
|
||||
|
||||
@@ -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<String> getCustomerCollectionsIdKey({
|
||||
required String serviceTicket,
|
||||
required String publisherUserId,
|
||||
}) {
|
||||
throw UnimplementedError('getCustomerCollectionsIdKey() has not been implemented.');
|
||||
}
|
||||
|
||||
Future<String?> getStoreId() {
|
||||
throw UnimplementedError('getStoreId() has not been implemented.');
|
||||
}
|
||||
|
||||
@@ -340,6 +340,38 @@ namespace windows_iap
|
||||
}
|
||||
}
|
||||
|
||||
foundation::IAsyncAction getCustomerCollectionsIdKey(
|
||||
std::string serviceTicket,
|
||||
std::string publisherUserId,
|
||||
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> 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<flutter::MethodResult<flutter::EncodableValue>> resultCallback)
|
||||
{
|
||||
@@ -438,6 +470,31 @@ namespace windows_iap
|
||||
auto publisherUserId = std::get<std::string>(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<flutter::EncodableMap>(*method_call.arguments());
|
||||
auto serviceTicketIt = args.find(flutter::EncodableValue("serviceTicket"));
|
||||
auto publisherUserIdIt = args.find(flutter::EncodableValue("publisherUserId"));
|
||||
if (serviceTicketIt == args.end() || !std::holds_alternative<std::string>(serviceTicketIt->second))
|
||||
{
|
||||
result->Error("invalid-args", "serviceTicket must be a string.");
|
||||
return;
|
||||
}
|
||||
if (publisherUserIdIt == args.end() || !std::holds_alternative<std::string>(publisherUserIdIt->second))
|
||||
{
|
||||
result->Error("invalid-args", "publisherUserId must be a string.");
|
||||
return;
|
||||
}
|
||||
getCustomerCollectionsIdKey(
|
||||
std::get<std::string>(serviceTicketIt->second),
|
||||
std::get<std::string>(publisherUserIdIt->second),
|
||||
std::move(result));
|
||||
}
|
||||
else if (method_call.method_name().compare("getStoreId") == 0)
|
||||
{
|
||||
getStoreId(std::move(result));
|
||||
|
||||
Reference in New Issue
Block a user