Skip to content

Commit 07cf58c

Browse files
authored
[in_app_purchase_storekit] Add SK2Transaction.currentEntitlements() (flutter#13373)
Exposes StoreKit 2's [`Transaction.currentEntitlements`](https://developer.apple.com/documentation/storekit/transaction/3851204-currententitlements) via `SK2Transaction.currentEntitlements()`. Previously, `SK2Transaction.transactions()` only wrapped `Transaction.all`, which returns the user's full transaction history rather than only their currently active entitlements (non-consumable purchases and active auto-renewable/non-renewing subscriptions). Adding `SK2Transaction.currentEntitlements()` allows callers to query active subscriptions and entitlements directly without invoking `restorePurchases()` or manually filtering historical transactions. Fixes flutter#61339 and flutter#118960 ## Pre-Review Checklist
1 parent 22fa2fc commit 07cf58c

10 files changed

Lines changed: 171 additions & 1 deletion

File tree

‎packages/in_app_purchase/in_app_purchase_storekit/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 0.4.16
2+
3+
* Adds `SK2Transaction.currentEntitlements()` to query active subscriptions and non-consumable entitlements.
4+
15
## 0.4.15
26

37
* Exposes `sk2Transaction` on `SK2PurchaseDetails`.

‎packages/in_app_purchase/in_app_purchase_storekit/darwin/in_app_purchase_storekit/Sources/in_app_purchase_storekit/StoreKit2/InAppPurchasePlugin+StoreKit2.swift‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,29 @@ extension InAppPurchasePlugin: InAppPurchase2API {
282282
}
283283
}
284284

285+
/// Wrapper method around StoreKit2's Transaction.currentEntitlements
286+
/// https://developer.apple.com/documentation/storekit/transaction/currententitlements
287+
func currentEntitlements(
288+
completion: @escaping (Result<[SK2TransactionMessage], Error>) -> Void
289+
) {
290+
Task {
291+
@MainActor in
292+
var transactionsMsgs: [SK2TransactionMessage] = []
293+
for await verificationResult in Transaction.currentEntitlements {
294+
switch verificationResult {
295+
case .verified(let transaction):
296+
transactionsMsgs.append(
297+
transaction.convertToPigeon(
298+
receipt: verificationResult.jwsRepresentation, status: .purchased)
299+
)
300+
case .unverified:
301+
break
302+
}
303+
}
304+
completion(.success(transactionsMsgs))
305+
}
306+
}
307+
285308
func restorePurchases(completion: @escaping (Result<Void, Error>) -> Void) {
286309
Task { [weak self] in
287310
guard let self = self else { return }

‎packages/in_app_purchase/in_app_purchase_storekit/darwin/in_app_purchase_storekit/Sources/in_app_purchase_storekit/StoreKit2/StoreKit2Messages.g.swift‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -997,6 +997,8 @@ protocol InAppPurchase2API {
997997
func transactions(completion: @escaping (Result<[SK2TransactionMessage], Error>) -> Void)
998998
func unfinishedTransactions(
999999
completion: @escaping (Result<[SK2TransactionMessage], Error>) -> Void)
1000+
func currentEntitlements(
1001+
completion: @escaping (Result<[SK2TransactionMessage], Error>) -> Void)
10001002
func finish(id: Int64, completion: @escaping (Result<Void, Error>) -> Void)
10011003
func startListeningToTransactions() throws
10021004
func stopListeningToTransactions() throws
@@ -1150,6 +1152,24 @@ class InAppPurchase2APISetup {
11501152
} else {
11511153
unfinishedTransactionsChannel.setMessageHandler(nil)
11521154
}
1155+
let currentEntitlementsChannel = FlutterBasicMessageChannel(
1156+
name:
1157+
"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchase2API.currentEntitlements\(channelSuffix)",
1158+
binaryMessenger: binaryMessenger, codec: codec)
1159+
if let api = api {
1160+
currentEntitlementsChannel.setMessageHandler { _, reply in
1161+
api.currentEntitlements { result in
1162+
switch result {
1163+
case .success(let res):
1164+
reply(wrapResult(res))
1165+
case .failure(let error):
1166+
reply(wrapError(error))
1167+
}
1168+
}
1169+
}
1170+
} else {
1171+
currentEntitlementsChannel.setMessageHandler(nil)
1172+
}
11531173
let finishChannel = FlutterBasicMessageChannel(
11541174
name: "dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchase2API.finish\(channelSuffix)",
11551175
binaryMessenger: binaryMessenger, codec: codec)

‎packages/in_app_purchase/in_app_purchase_storekit/example/shared/RunnerTests/InAppPurchaseStoreKit2PluginTests.swift‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,51 @@ final class InAppPurchase2PluginTests: XCTestCase {
134134
await fulfillment(of: [transactionExpectation], timeout: purchaseTimeout)
135135
}
136136

137+
func testGetCurrentEntitlements() async throws {
138+
let subscriptionExpectation = self.expectation(
139+
description: "Subscription purchase should succeed")
140+
let consumableExpectation = self.expectation(description: "Consumable purchase should succeed")
141+
let entitlementsExpectation = self.expectation(
142+
description: "Getting current entitlements should succeed")
143+
144+
plugin.purchase(id: "subscription_silver", options: nil) { result in
145+
switch result {
146+
case .success:
147+
subscriptionExpectation.fulfill()
148+
case .failure(let error):
149+
XCTFail("Subscription purchase should NOT fail. Failed with \(error)")
150+
subscriptionExpectation.fulfill()
151+
}
152+
}
153+
await fulfillment(of: [subscriptionExpectation], timeout: purchaseTimeout)
154+
155+
plugin.purchase(id: "consumable", options: nil) { result in
156+
switch result {
157+
case .success:
158+
consumableExpectation.fulfill()
159+
case .failure(let error):
160+
XCTFail("Consumable purchase should NOT fail. Failed with \(error)")
161+
consumableExpectation.fulfill()
162+
}
163+
}
164+
await fulfillment(of: [consumableExpectation], timeout: purchaseTimeout)
165+
166+
plugin.currentEntitlements { result in
167+
switch result {
168+
case .success(let transactions):
169+
XCTAssertEqual(transactions.count, 1)
170+
XCTAssertEqual(transactions.first?.productId, "subscription_silver")
171+
XCTAssertNotNil(transactions.first?.receiptData)
172+
XCTAssertEqual(transactions.first?.status, .purchased)
173+
entitlementsExpectation.fulfill()
174+
case .failure(let error):
175+
XCTFail("Getting current entitlements should NOT fail. Failed with \(error)")
176+
entitlementsExpectation.fulfill()
177+
}
178+
}
179+
await fulfillment(of: [entitlementsExpectation], timeout: purchaseTimeout)
180+
}
181+
137182
func testGetDiscountedProducts() async throws {
138183
let expectation = self.expectation(description: "products successfully fetched")
139184

‎packages/in_app_purchase/in_app_purchase_storekit/lib/src/sk2_pigeon.g.dart‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1070,6 +1070,25 @@ class InAppPurchase2API {
10701070
return (pigeonVar_replyValue! as List<Object?>).cast<SK2TransactionMessage>();
10711071
}
10721072

1073+
Future<List<SK2TransactionMessage>> currentEntitlements() async {
1074+
final pigeonVar_channelName =
1075+
'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchase2API.currentEntitlements$pigeonVar_messageChannelSuffix';
1076+
final pigeonVar_channel = BasicMessageChannel<Object?>(
1077+
pigeonVar_channelName,
1078+
pigeonChannelCodec,
1079+
binaryMessenger: pigeonVar_binaryMessenger,
1080+
);
1081+
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(null);
1082+
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
1083+
1084+
final Object? pigeonVar_replyValue = _extractReplyValueOrThrow(
1085+
pigeonVar_replyList,
1086+
pigeonVar_channelName,
1087+
isNullValid: false,
1088+
);
1089+
return (pigeonVar_replyValue! as List<Object?>).cast<SK2TransactionMessage>();
1090+
}
1091+
10731092
Future<void> finish(int id) async {
10741093
final pigeonVar_channelName =
10751094
'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchase2API.finish$pigeonVar_messageChannelSuffix';

‎packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_2_wrappers/sk2_transaction_wrapper.dart‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,17 @@ class SK2Transaction {
105105
return transactions;
106106
}
107107

108+
/// A wrapper around [Transaction.currentEntitlements]
109+
/// https://developer.apple.com/documentation/storekit/transaction/currententitlements
110+
/// A sequence that emits the latest transaction for each product the customer is currently entitled to.
111+
static Future<List<SK2Transaction>> currentEntitlements() async {
112+
final List<SK2TransactionMessage> msgs = await hostApi2.currentEntitlements();
113+
final List<SK2Transaction> transactions = msgs
114+
.map((SK2TransactionMessage e) => e.convertFromPigeon())
115+
.toList();
116+
return transactions;
117+
}
118+
108119
/// Start listening to transactions.
109120
/// Call this as soon as you can your app to avoid missing transactions.
110121
static void startListeningToTransactions() {

‎packages/in_app_purchase/in_app_purchase_storekit/pigeons/sk2_pigeon.dart‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,9 @@ abstract class InAppPurchase2API {
251251
@async
252252
List<SK2TransactionMessage> unfinishedTransactions();
253253

254+
@async
255+
List<SK2TransactionMessage> currentEntitlements();
256+
254257
@async
255258
void finish(int id);
256259

‎packages/in_app_purchase/in_app_purchase_storekit/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: in_app_purchase_storekit
22
description: An implementation for the iOS and macOS platforms of the Flutter `in_app_purchase` plugin. This uses the StoreKit Framework.
33
repository: https://github.com/flutter/packages/tree/main/packages/in_app_purchase/in_app_purchase_storekit
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22
5-
version: 0.4.15
5+
version: 0.4.16
66

77
environment:
88
sdk: ^3.11.0

‎packages/in_app_purchase/in_app_purchase_storekit/test/fakes/fake_storekit_platform.dart‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,7 @@ class FakeStoreKit2Platform implements InAppPurchase2API {
321321
late List<SK2Transaction> finishedTransactions;
322322
List<SK2TransactionMessage> transactionsList = <SK2TransactionMessage>[];
323323
List<SK2TransactionMessage> unfinishedTransactionsList = <SK2TransactionMessage>[];
324+
List<SK2TransactionMessage> currentEntitlementsList = <SK2TransactionMessage>[];
324325

325326
PlatformException? queryProductException;
326327
bool isListenerRegistered = false;
@@ -375,6 +376,18 @@ class FakeStoreKit2Platform implements InAppPurchase2API {
375376
status: SK2PurchaseStatusMessage.purchased,
376377
),
377378
];
379+
currentEntitlementsList = <SK2TransactionMessage>[
380+
SK2TransactionMessage(
381+
id: 123,
382+
originalId: 123,
383+
productId: 'product_id',
384+
purchaseDate: 123123.121,
385+
expirationDate: 321321.32,
386+
receiptData: 'fake_jws_representation',
387+
appAccountToken: 'fake_app_account_token',
388+
status: SK2PurchaseStatusMessage.purchased,
389+
),
390+
];
378391
}
379392

380393
SK2TransactionMessage createRestoredTransaction(
@@ -484,6 +497,11 @@ class FakeStoreKit2Platform implements InAppPurchase2API {
484497
return Future<List<SK2TransactionMessage>>.value(unfinishedTransactionsList);
485498
}
486499

500+
@override
501+
Future<List<SK2TransactionMessage>> currentEntitlements() {
502+
return Future<List<SK2TransactionMessage>>.value(currentEntitlementsList);
503+
}
504+
487505
@override
488506
Future<void> startListeningToTransactions() async {
489507
isListenerRegistered = true;

‎packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_2_platform_test.dart‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -774,4 +774,31 @@ void main() {
774774
expect(transactions.first.quantity, 2);
775775
});
776776
});
777+
778+
group('current entitlements', () {
779+
test('should return current entitlements', () async {
780+
final List<SK2Transaction> transactions = await SK2Transaction.currentEntitlements();
781+
782+
expect(transactions, isNotEmpty);
783+
expect(transactions.first.id, '123');
784+
expect(transactions.first.productId, 'product_id');
785+
expect(transactions.first.expirationDate, (321321.32 * 1000).round().toString());
786+
});
787+
788+
test('should expose receiptData (JWS) in current entitlements', () async {
789+
final List<SK2Transaction> transactions = await SK2Transaction.currentEntitlements();
790+
791+
expect(transactions, isNotEmpty);
792+
expect(transactions.first.receiptData, isNotNull);
793+
expect(transactions.first.receiptData, 'fake_jws_representation');
794+
});
795+
796+
test('should expose appAccountToken in current entitlements', () async {
797+
final List<SK2Transaction> transactions = await SK2Transaction.currentEntitlements();
798+
799+
expect(transactions, isNotEmpty);
800+
expect(transactions.first.appAccountToken, isNotNull);
801+
expect(transactions.first.appAccountToken, 'fake_app_account_token');
802+
});
803+
});
777804
}

0 commit comments

Comments
 (0)