@chipmobilesdk/rn-payment 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,660 +1,627 @@
1
- /**
2
- * Android adapter over `react-native-iap` (Play Billing).
3
- *
4
- * **The only file in this package that touches the billing library.** Everything
5
- * above it talks to `ProviderPort`, which is what keeps the binding replaceable
6
- * and lets an iOS adapter be added without changing a consumer call (FR-002,
7
- * FR-007). ESLint enforces that boundary.
8
- *
9
- * ## Verified against react-native-iap 16.7.3
10
- *
11
- * 0.3.0 was written before the binding was installed, from its documentation, and
12
- * no purchase could complete on a device. Checked against the installed 16.7.3
13
- * source for 0.3.1, two facts shape the purchase path:
14
- *
15
- * - The request is keyed by store: `google` / `apple`. 0.3.0 sent `android`, which
16
- * the binding rejects (`empty-sku-list`) before Play opens. The request type is
17
- * now the binding's own `RequestPurchaseProps`, so a renamed key fails to
18
- * typecheck here instead of failing on a user's device.
19
- * - On Android `requestPurchase` resolves with an **empty list** once the flow
20
- * ends, whatever happened. The outcome (bought, pending, cancelled, failed)
21
- * arrives only through `purchaseUpdatedListener` / `purchaseErrorListener`, so
22
- * `launchPurchase` waits for those events.
23
- *
24
- * The module is still required lazily, and `IapModule` still names exactly the
25
- * surface used. `__tests__/iap-adapter.test.ts` drives this file through a fake
26
- * binding that behaves as 16.7.3 does; the rest of the suite uses the fake store.
27
- *
28
- * ## Known upstream defect this guards against
29
- *
30
- * openiap#408: the Android bridge did not clear its internal `isInitialized` flag
31
- * on disconnect, so `connected` stayed true, later calls failed with
32
- * `E_NOT_PREPARED`, and `reconnect()` reported success without rebuilding
33
- * anything. This adapter therefore (a) tracks connection state itself rather than
34
- * trusting the binding's flag, and (b) always performs a full
35
- * `endConnection` + `initConnection` cycle instead of calling any reconnect
36
- * shortcut.
37
- */
38
-
39
- import type {
40
- RequestPurchaseProps,
41
- SubscriptionReplacementModeAndroid,
42
- } from 'react-native-iap';
43
-
44
- import type { ProductType, Unsubscribe } from '../config/types';
45
- import type {
46
- ProviderCapabilities,
47
- ProviderConnectOutcome,
48
- ProviderFailureReason,
49
- ProviderPort,
50
- ProviderPriceChangeOutcome,
51
- ProviderProduct,
52
- ProviderPurchase,
53
- ProviderPurchaseOutcome,
54
- ProviderPurchaseRequest,
55
- ProviderToken,
56
- StoreProductId,
57
- } from './port';
58
-
59
- /**
60
- * Exactly what this adapter needs from the binding.
61
- *
62
- * Declared narrowly on purpose: it documents the coupling, and it means a binding
63
- * upgrade that changes one of these shapes fails to typecheck here instead of
64
- * failing silently at runtime on a user's device.
65
- */
66
- interface IapModule {
67
- initConnection(): Promise<boolean>;
68
- endConnection(): Promise<void>;
69
- fetchProducts(params: {
70
- skus: string[];
71
- type: 'in-app' | 'subs';
72
- }): Promise<RawProduct[]>;
73
- getAvailablePurchases(): Promise<RawPurchase[]>;
74
- /** Typed by the binding itself, so a renamed request key fails to compile. */
75
- requestPurchase(params: RequestPurchaseProps): Promise<unknown>;
76
- finishTransaction(params: {
77
- purchase: unknown;
78
- isConsumable?: boolean;
79
- }): Promise<unknown>;
80
- purchaseUpdatedListener(
81
- listener: (purchase: RawPurchase) => void,
82
- ): { remove(): void };
83
- purchaseErrorListener(listener: (error: RawPurchaseError) => void): {
84
- remove(): void;
85
- };
86
- deepLinkToSubscriptions?(params: { skuAndroid?: string }): Promise<void>;
87
- }
88
-
89
- interface RawProduct {
90
- id?: string;
91
- productId?: string;
92
- title?: string;
93
- name?: string;
94
- description?: string;
95
- displayPrice?: string;
96
- localizedPrice?: string;
97
- currency?: string;
98
- currencyCode?: string;
99
- price?: string | number;
100
- oneTimePurchaseOfferDetails?: {
101
- formattedPrice?: string;
102
- priceAmountMicros?: string | number;
103
- priceCurrencyCode?: string;
104
- };
105
- subscriptionOfferDetails?: RawSubscriptionOffer[];
106
- }
107
-
108
- interface RawSubscriptionOffer {
109
- offerToken?: string;
110
- offerId?: string;
111
- basePlanId?: string;
112
- pricingPhases?: {
113
- pricingPhaseList?: Array<{
114
- formattedPrice?: string;
115
- priceAmountMicros?: string | number;
116
- priceCurrencyCode?: string;
117
- billingPeriod?: string;
118
- recurrenceMode?: number;
119
- billingCycleCount?: number;
120
- }>;
121
- };
122
- }
123
-
124
- interface RawPurchase {
125
- id?: string;
126
- transactionId?: string;
127
- productId?: string;
128
- ids?: string[];
129
- purchaseToken?: string;
130
- purchaseStateAndroid?: number | null;
131
- /** A string in the 16.x binding: `'pending' | 'purchased' | 'unknown'`. */
132
- purchaseState?: number | string;
133
- transactionDate?: number;
134
- isAcknowledgedAndroid?: boolean;
135
- isAcknowledged?: boolean;
136
- autoRenewingAndroid?: boolean;
137
- isAutoRenewing?: boolean;
138
- expirationDateAndroid?: number;
139
- transactionReceipt?: string;
140
- dataAndroid?: string;
141
- }
142
-
143
- /** What `purchaseErrorListener` delivers. */
144
- interface RawPurchaseError {
145
- code?: string;
146
- message?: string;
147
- productId?: string | null;
148
- }
149
-
150
- /**
151
- * How long to wait for the outcome event after `requestPurchase` has resolved.
152
- * The binding emits the event before or as it resolves, so this only bounds the
153
- * case where none ever comes; it never runs while the user is in Play's UI.
154
- */
155
- const RESULT_EVENT_GRACE_MS = 2_000;
156
-
157
- /** Play's replacement modes, by the codes the engine passes (`engine/subscriptions.ts`). */
158
- const REPLACEMENT_MODES: Record<string, SubscriptionReplacementModeAndroid> = {
159
- WITH_TIME_PRORATION: 'with-time-proration',
160
- CHARGE_FULL_PRICE: 'charge-full-price',
161
- CHARGE_PRORATED_PRICE: 'charge-prorated-price',
162
- DEFERRED: 'deferred',
163
- };
164
-
165
- /** The request in the binding's 16.7 shape: keyed `google`, not `android`. */
166
- export function toRequestProps(request: ProviderPurchaseRequest): RequestPurchaseProps {
167
- const google = {
168
- skus: [request.storeProductId],
169
- ...(request.obfuscatedAccountId
170
- ? { obfuscatedAccountId: request.obfuscatedAccountId }
171
- : {}),
172
- };
173
- if (request.productType !== 'subscription') {
174
- return { request: { google }, type: 'in-app' };
175
- }
176
-
177
- const replacementMode = request.prorationMode
178
- ? REPLACEMENT_MODES[request.prorationMode]
179
- : undefined;
180
- return {
181
- request: {
182
- google: {
183
- ...google,
184
- ...(request.offerKey
185
- ? {
186
- subscriptionOffers: [
187
- { sku: request.storeProductId, offerToken: request.offerKey },
188
- ],
189
- }
190
- : {}),
191
- // A plan change: the token of the purchase being replaced, and — for
192
- // the replacement mode to apply — its product id (Billing 8.1+).
193
- ...(request.replacePurchaseToken
194
- ? { purchaseToken: request.replacePurchaseToken }
195
- : {}),
196
- ...(request.replacePurchaseToken &&
197
- request.replaceStoreProductId &&
198
- replacementMode
199
- ? {
200
- subscriptionProductReplacementParams: {
201
- oldProductId: request.replaceStoreProductId,
202
- replacementMode,
203
- },
204
- }
205
- : {}),
206
- },
207
- },
208
- type: 'subs',
209
- };
210
- }
211
-
212
- /** Play's `PurchaseState`: 0 unspecified, 1 purchased, 2 pending. */
213
- const PLAY_STATE_PURCHASED = 1;
214
- const PLAY_STATE_PENDING = 2;
215
-
216
- function loadModule(): IapModule {
217
- // Required lazily so importing the package does not require the native module.
218
- const mod = require('react-native-iap') as IapModule;
219
- return mod;
220
- }
221
-
222
- function toMicros(value: string | number | undefined): number {
223
- if (typeof value === 'number') {
224
- return value;
225
- }
226
- if (typeof value === 'string') {
227
- const parsed = Number.parseInt(value, 10);
228
- return Number.isFinite(parsed) ? parsed : 0;
229
- }
230
- return 0;
231
- }
232
-
233
- function normalizeProduct(
234
- raw: RawProduct,
235
- productType: ProductType,
236
- ): ProviderProduct {
237
- const oneTime = raw.oneTimePurchaseOfferDetails;
238
- const currencyCode =
239
- oneTime?.priceCurrencyCode ?? raw.currencyCode ?? raw.currency ?? '';
240
-
241
- return {
242
- storeProductId: raw.id ?? raw.productId ?? '',
243
- productType,
244
- title: raw.title ?? raw.name ?? '',
245
- description: raw.description ?? '',
246
- // Store-formatted, never built here: only the store knows the right currency
247
- // symbol, separator, and placement for the user's locale (FR-028).
248
- formattedPrice:
249
- oneTime?.formattedPrice ?? raw.displayPrice ?? raw.localizedPrice ?? '',
250
- currencyCode,
251
- priceAmountMicros: toMicros(oneTime?.priceAmountMicros ?? raw.price),
252
- offers: (raw.subscriptionOfferDetails ?? []).map(offer =>
253
- normalizeOffer(offer, currencyCode),
254
- ),
255
- };
256
- }
257
-
258
- function normalizeOffer(
259
- offer: RawSubscriptionOffer,
260
- fallbackCurrency: string,
261
- ): ProviderProduct['offers'][number] {
262
- const phases = offer.pricingPhases?.pricingPhaseList ?? [];
263
- // The last phase is the recurring price; earlier ones are trial or
264
- // introductory. Play orders them that way.
265
- const recurring = phases[phases.length - 1];
266
- const intro = phases.length > 1 ? phases[0] : undefined;
267
- const isFreeTrial = intro !== undefined && toMicros(intro.priceAmountMicros) === 0;
268
-
269
- return {
270
- offerKey: offer.offerToken ?? offer.offerId ?? offer.basePlanId ?? '',
271
- billingPeriod: recurring?.billingPeriod ?? '',
272
- formattedPrice: recurring?.formattedPrice ?? '',
273
- priceAmountMicros: toMicros(recurring?.priceAmountMicros),
274
- currencyCode: recurring?.priceCurrencyCode ?? fallbackCurrency,
275
- trialPeriod: isFreeTrial ? intro?.billingPeriod : undefined,
276
- introductoryPrice:
277
- intro && !isFreeTrial
278
- ? {
279
- formattedPrice: intro.formattedPrice ?? '',
280
- period: intro.billingPeriod ?? '',
281
- cycles: intro.billingCycleCount ?? 1,
282
- }
283
- : undefined,
284
- // Play decides eligibility by only returning offers the user qualifies for,
285
- // so forwarding `true` reports the store's determination rather than
286
- // computing our own (FR-026).
287
- isEligible: true,
288
- };
289
- }
290
-
291
- /**
292
- * Reads the purchase state from whichever field the binding filled.
293
- *
294
- * Pending is preserved, never flattened to purchased: that distinction is what
295
- * stops an entitlement being granted for money that has not arrived (FR-037).
296
- * And an unrecognized or missing state is `unspecified`, never `purchased`.
297
- *
298
- * 0.1.0 read only Play's numeric state and treated anything else as purchased.
299
- * The 16.x binding hands JavaScript the *string* state and does not carry the
300
- * numeric one across, so on a device every pending purchase arrived as a string,
301
- * fell through to the default, and was granted. Unit tests could not see it: they
302
- * drive the fake store, which never passes through here.
303
- */
304
- export function toProviderPurchaseState(
305
- raw: Pick<RawPurchase, 'purchaseStateAndroid' | 'purchaseState'>,
306
- ): ProviderPurchase['state'] {
307
- let numeric: number | undefined;
308
- if (typeof raw.purchaseStateAndroid === 'number') {
309
- numeric = raw.purchaseStateAndroid;
310
- } else if (typeof raw.purchaseState === 'number') {
311
- numeric = raw.purchaseState;
312
- }
313
- if (numeric !== undefined) {
314
- if (numeric === PLAY_STATE_PENDING) {
315
- return 'pending';
316
- }
317
- return numeric === PLAY_STATE_PURCHASED ? 'purchased' : 'unspecified';
318
- }
319
-
320
- switch (typeof raw.purchaseState === 'string' ? raw.purchaseState.toLowerCase() : '') {
321
- case 'purchased':
322
- case 'restored':
323
- return 'purchased';
324
- case 'pending':
325
- case 'deferred':
326
- return 'pending';
327
- default:
328
- return 'unspecified';
329
- }
330
- }
331
-
332
- function normalizePurchase(raw: RawPurchase): ProviderPurchase {
333
- return {
334
- storeProductId: raw.productId ?? raw.ids?.[0] ?? '',
335
- transactionId: raw.id ?? raw.transactionId ?? raw.purchaseToken ?? '',
336
- token: raw.purchaseToken ?? '',
337
- state: toProviderPurchaseState(raw),
338
- purchasedAt: raw.transactionDate ?? Date.now(),
339
- isAcknowledged: raw.isAcknowledgedAndroid ?? raw.isAcknowledged ?? false,
340
- expiresAt: raw.expirationDateAndroid,
341
- willAutoRenew: raw.autoRenewingAndroid ?? raw.isAutoRenewing,
342
- // Opaque material for the app's backend. Carried here and handed to the
343
- // validation hook only — never logged or put in an event (FR-074).
344
- verificationPayload: raw.transactionReceipt ?? raw.dataAndroid,
345
- };
346
- }
347
-
348
- /** Maps a binding error code onto the port's vocabulary, so no store code escapes. */
349
- function mapErrorCode(code: string | undefined): ProviderFailureReason {
350
- switch (code) {
351
- case 'E_USER_CANCELLED':
352
- case 'user-cancelled':
353
- return 'user_cancelled';
354
- case 'E_ALREADY_OWNED':
355
- case 'already-owned':
356
- case 'item-already-owned':
357
- return 'already_owned';
358
- case 'E_ITEM_UNAVAILABLE':
359
- case 'item-unavailable':
360
- case 'sku-not-found':
361
- return 'unknown_product';
362
- case 'E_NOT_PREPARED':
363
- case 'not-prepared':
364
- return 'not_ready';
365
- case 'E_NETWORK_ERROR':
366
- case 'network-error':
367
- return 'network_error';
368
- case 'E_DEFERRED_PAYMENT':
369
- // Not a failure — a pending purchase. The caller resolves it from the
370
- // purchase update rather than from this error.
371
- return 'store_error';
372
- default:
373
- return 'store_error';
374
- }
375
- }
376
-
377
- const ANDROID_CAPABILITIES: ProviderCapabilities = {
378
- supportsSubscriptions: true,
379
- supportsPlanChange: true,
380
- supportsPriceChangeConfirmation: false,
381
- /**
382
- * False, and this is a platform fact rather than a gap in this adapter.
383
- *
384
- * Client-side Play Billing cannot separate grace period from account hold: a
385
- * grace-period subscription is still returned as active, and one in account
386
- * hold stops being returned at all — indistinguishable from expired, cancelled,
387
- * or refunded. The entitlement layer reads this flag and reports
388
- * `indeterminate` rather than inventing a distinction (research.md R5).
389
- */
390
- reportsGraceAndHoldDistinctly: false,
391
- supportsExternalTransactions: false,
392
- /** This one really does move money, which is what arms the environment guard. */
393
- createsRealTransactions: true,
394
- /** The outcome event comes only when the user leaves Play's purchase UI. */
395
- purchaseOutcomeIncludesStoreTime: true,
396
- };
397
-
398
- export interface IapAdapterOptions {
399
- /** Injected in tests that need to drive the mapping without the native module. */
400
- module?: IapModule;
401
- }
402
-
403
- export function createIapAdapter(options: IapAdapterOptions = {}): ProviderPort {
404
- let iap: IapModule | undefined = options.module;
405
-
406
- /** Tracked here, never read from the binding — see the openiap#408 note above. */
407
- let connected = false;
408
-
409
- const connectionListeners = new Set<
410
- (connected: boolean, reason?: string) => void
411
- >();
412
- const purchaseListeners = new Set<(purchase: ProviderPurchase) => void>();
413
- /** Only an in-flight `launchPurchase` listens here; see there. */
414
- const purchaseErrorListeners = new Set<(error: RawPurchaseError) => void>();
415
- let updateSub: { remove(): void } | undefined;
416
- let errorSub: { remove(): void } | undefined;
417
-
418
- const module = (): IapModule => {
419
- if (!iap) {
420
- iap = loadModule();
421
- }
422
- return iap;
423
- };
424
-
425
- const notifyConnection = (next: boolean, reason?: string): void => {
426
- if (connected === next) {
427
- return;
428
- }
429
- connected = next;
430
- for (const listener of connectionListeners) {
431
- listener(next, reason);
432
- }
433
- };
434
-
435
- const attachListeners = (): void => {
436
- // Every connect attaches, so whatever an earlier connect left must go first.
437
- // Overwriting the handles orphaned the old native listeners, which kept
438
- // firing — every purchase update reached the engine once per connect.
439
- detachListeners();
440
- const mod = module();
441
- updateSub = mod.purchaseUpdatedListener(raw => {
442
- const purchase = normalizePurchase(raw);
443
- for (const listener of purchaseListeners) {
444
- listener(purchase);
445
- }
446
- });
447
- errorSub = mod.purchaseErrorListener(error => {
448
- // A `not-prepared` error is the one signal the binding gives that the
449
- // service went away underneath us, so it is treated as a disconnect
450
- // rather than as a purchase failure.
451
- if (mapErrorCode(error.code) === 'not_ready') {
452
- notifyConnection(false, 'not_prepared');
453
- }
454
- for (const listener of purchaseErrorListeners) {
455
- listener(error);
456
- }
457
- });
458
- };
459
-
460
- const detachListeners = (): void => {
461
- updateSub?.remove();
462
- updateSub = undefined;
463
- errorSub?.remove();
464
- errorSub = undefined;
465
- };
466
-
467
- return {
468
- async connect(): Promise<ProviderConnectOutcome> {
469
- try {
470
- const mod = module();
471
- // Always a full cycle. The binding's own reconnect has reported success
472
- // without rebuilding anything, so we never rely on it (openiap#408).
473
- if (connected) {
474
- await mod.endConnection().catch(() => undefined);
475
- connected = false;
476
- }
477
- const ok = await mod.initConnection();
478
- if (!ok) {
479
- return {
480
- ok: false,
481
- reason: 'no_billing_service',
482
- retryable: true,
483
- };
484
- }
485
- attachListeners();
486
- notifyConnection(true);
487
- return { ok: true };
488
- } catch (error) {
489
- const code = (error as { code?: string }).code;
490
- // A missing or too-old Play Services install is not the same as a
491
- // transient error, and the app shows different things for each (FR-021).
492
- if (code === 'E_IAP_NOT_AVAILABLE' || code === 'iap-not-available') {
493
- return { ok: false, reason: 'no_billing_service', retryable: false };
494
- }
495
- if (code === 'E_SERVICE_ERROR') {
496
- return {
497
- ok: false,
498
- reason: 'billing_service_outdated',
499
- retryable: true,
500
- };
501
- }
502
- return { ok: false, reason: 'store_error', retryable: true };
503
- }
504
- },
505
-
506
- async disconnect(): Promise<void> {
507
- detachListeners();
508
- try {
509
- await module().endConnection();
510
- } catch {
511
- // Already down; nothing to tear down.
512
- }
513
- notifyConnection(false, 'disconnect');
514
- },
515
-
516
- observeConnection(listener): Unsubscribe {
517
- connectionListeners.add(listener);
518
- let removed = false;
519
- return () => {
520
- if (removed) {
521
- return;
522
- }
523
- removed = true;
524
- connectionListeners.delete(listener);
525
- };
526
- },
527
-
528
- async queryProducts(
529
- storeProductIds: StoreProductId[],
530
- productType: ProductType,
531
- ): Promise<ProviderProduct[]> {
532
- const raw = await module().fetchProducts({
533
- skus: storeProductIds,
534
- type: productType === 'subscription' ? 'subs' : 'in-app',
535
- });
536
- return raw.map(product => normalizeProduct(product, productType));
537
- },
538
-
539
- async queryOwned(): Promise<ProviderPurchase[]> {
540
- const raw = await module().getAvailablePurchases();
541
- // Pending purchases are mapped through, flagged rather than filtered: the
542
- // engine needs to see them to raise the pending signal (FR-038).
543
- return raw.map(normalizePurchase);
544
- },
545
-
546
- /**
547
- * Settles on the first outcome event for this product: a purchase update
548
- * (bought or pending) or a purchase error (cancelled, already owned, …).
549
- *
550
- * The binding's promise is not the outcome: on Android it resolves with an
551
- * empty list when the flow ends, whatever happened. Its listeners also feed
552
- * `observePurchases`, so the engine sees a bought purchase twice — here and
553
- * as a store update — and grants it once (FR-044).
554
- */
555
- launchPurchase(request: ProviderPurchaseRequest): Promise<ProviderPurchaseOutcome> {
556
- const sku = request.storeProductId;
557
- return new Promise<ProviderPurchaseOutcome>(resolve => {
558
- let settled = false;
559
- let grace: ReturnType<typeof setTimeout> | undefined;
560
-
561
- const onPurchase = (purchase: ProviderPurchase): void => {
562
- if (purchase.storeProductId === sku) {
563
- finish({ ok: true, purchase });
564
- }
565
- };
566
- const onError = (error: RawPurchaseError): void => {
567
- if (error.productId && error.productId !== sku) {
568
- return;
569
- }
570
- finish({ ok: false, reason: mapErrorCode(error.code), detail: error.code });
571
- };
572
- const fail = (error: unknown): void => {
573
- const code = (error as { code?: string } | undefined)?.code;
574
- finish({ ok: false, reason: mapErrorCode(code), detail: code });
575
- };
576
- function finish(outcome: ProviderPurchaseOutcome): void {
577
- if (settled) {
578
- return;
579
- }
580
- settled = true;
581
- clearTimeout(grace);
582
- purchaseListeners.delete(onPurchase);
583
- purchaseErrorListeners.delete(onError);
584
- resolve(outcome);
585
- }
586
-
587
- purchaseListeners.add(onPurchase);
588
- purchaseErrorListeners.add(onError);
589
- try {
590
- module()
591
- .requestPurchase(toRequestProps(request))
592
- .then(() => {
593
- if (!settled) {
594
- grace = setTimeout(
595
- () =>
596
- finish({
597
- ok: false,
598
- reason: 'store_error',
599
- detail: 'no purchase event',
600
- }),
601
- RESULT_EVENT_GRACE_MS,
602
- );
603
- }
604
- }, fail);
605
- } catch (error) {
606
- fail(error);
607
- }
608
- });
609
- },
610
-
611
- observePurchases(listener): Unsubscribe {
612
- purchaseListeners.add(listener);
613
- let removed = false;
614
- return () => {
615
- if (removed) {
616
- return;
617
- }
618
- removed = true;
619
- purchaseListeners.delete(listener);
620
- };
621
- },
622
-
623
- async acknowledge(token: ProviderToken): Promise<void> {
624
- // Idempotent at the store: acknowledging an already-acknowledged purchase
625
- // is accepted, which is what FR-044 relies on.
626
- await module().finishTransaction({
627
- purchase: { purchaseToken: token },
628
- isConsumable: false,
629
- });
630
- },
631
-
632
- async consume(token: ProviderToken): Promise<void> {
633
- await module().finishTransaction({
634
- purchase: { purchaseToken: token },
635
- isConsumable: true,
636
- });
637
- },
638
-
639
- async openSubscriptionManagement(
640
- storeProductId?: StoreProductId,
641
- ): Promise<void> {
642
- // The store's own screen. Platforms forbid a self-built cancellation
643
- // screen, so there is deliberately no alternative path here (FR-066).
644
- const mod = module();
645
- if (!mod.deepLinkToSubscriptions) {
646
- return;
647
- }
648
- await mod.deepLinkToSubscriptions({ skuAndroid: storeProductId });
649
- },
650
-
651
- async confirmPriceChange(): Promise<ProviderPriceChangeOutcome> {
652
- // Play has no client-side price-change confirmation flow; it notifies the
653
- // user itself. Reported as unsupported rather than faked, matching
654
- // `supportsPriceChangeConfirmation: false` (FR-067).
655
- return { ok: false, reason: 'store_error' };
656
- },
657
-
658
- capabilities: () => ANDROID_CAPABILITIES,
659
- };
660
- }
1
+ /**
2
+ * Android adapter over `react-native-iap` (Play Billing).
3
+ *
4
+ * **The only file in this package that touches the billing library.** Everything
5
+ * above it talks to `ProviderPort`, which is what keeps the binding replaceable
6
+ * and lets an iOS adapter be added without changing a consumer call (FR-002,
7
+ * FR-007). ESLint enforces that boundary.
8
+ *
9
+ * ## Verified against react-native-iap 16.7.3
10
+ *
11
+ * 0.3.0 was written before the binding was installed, from its documentation, and
12
+ * no purchase could complete on a device. Checked against the installed 16.7.3
13
+ * source for 0.3.1, two facts shape the purchase path:
14
+ *
15
+ * - The request is keyed by store: `google` / `apple`. 0.3.0 sent `android`, which
16
+ * the binding rejects (`empty-sku-list`) before Play opens. The request type is
17
+ * now the binding's own `RequestPurchaseProps`, so a renamed key fails to
18
+ * typecheck here instead of failing on a user's device.
19
+ * - On Android `requestPurchase` resolves with an **empty list** once the flow
20
+ * ends, whatever happened. The outcome (bought, pending, cancelled, failed)
21
+ * arrives only through `purchaseUpdatedListener` / `purchaseErrorListener`, so
22
+ * `launchPurchase` waits for those events.
23
+ *
24
+ * The module is still required lazily, and `IapModule` still names exactly the
25
+ * surface used. `__tests__/iap-adapter.test.ts` drives this file through a fake
26
+ * binding that behaves as 16.7.3 does; the rest of the suite uses the fake store.
27
+ *
28
+ * ## Known upstream defect this guards against
29
+ *
30
+ * openiap#408: the Android bridge did not clear its internal `isInitialized` flag
31
+ * on disconnect, so `connected` stayed true, later calls failed with
32
+ * `E_NOT_PREPARED`, and `reconnect()` reported success without rebuilding
33
+ * anything. This adapter therefore (a) tracks connection state itself rather than
34
+ * trusting the binding's flag, and (b) always performs a full
35
+ * `endConnection` + `initConnection` cycle instead of calling any reconnect
36
+ * shortcut.
37
+ */
38
+
39
+ import { createListenerSet, lazyPeer } from '@chipmobilesdk/rn-core';
40
+
41
+ import type { RequestPurchaseProps, SubscriptionReplacementModeAndroid } from 'react-native-iap';
42
+
43
+ import type { ProductType, Unsubscribe } from '../config/types';
44
+ import { PaymentError, redact } from '../diagnostics/errors';
45
+ import type {
46
+ ProviderCapabilities,
47
+ ProviderConnectOutcome,
48
+ ProviderFailureReason,
49
+ ProviderPort,
50
+ ProviderPriceChangeOutcome,
51
+ ProviderProduct,
52
+ ProviderPurchase,
53
+ ProviderPurchaseOutcome,
54
+ ProviderPurchaseRequest,
55
+ ProviderToken,
56
+ StoreProductId,
57
+ } from './port';
58
+
59
+ /**
60
+ * Exactly what this adapter needs from the binding.
61
+ *
62
+ * Declared narrowly on purpose: it documents the coupling, and it means a binding
63
+ * upgrade that changes one of these shapes fails to typecheck here instead of
64
+ * failing silently at runtime on a user's device.
65
+ */
66
+ interface IapModule {
67
+ initConnection(): Promise<boolean>;
68
+ endConnection(): Promise<void>;
69
+ fetchProducts(params: { skus: string[]; type: 'in-app' | 'subs' }): Promise<RawProduct[]>;
70
+ getAvailablePurchases(): Promise<RawPurchase[]>;
71
+ /** Typed by the binding itself, so a renamed request key fails to compile. */
72
+ requestPurchase(params: RequestPurchaseProps): Promise<unknown>;
73
+ finishTransaction(params: { purchase: unknown; isConsumable?: boolean }): Promise<unknown>;
74
+ purchaseUpdatedListener(listener: (purchase: RawPurchase) => void): { remove(): void };
75
+ purchaseErrorListener(listener: (error: RawPurchaseError) => void): {
76
+ remove(): void;
77
+ };
78
+ deepLinkToSubscriptions?(params: { skuAndroid?: string }): Promise<void>;
79
+ }
80
+
81
+ interface RawProduct {
82
+ id?: string;
83
+ productId?: string;
84
+ title?: string;
85
+ name?: string;
86
+ description?: string;
87
+ displayPrice?: string;
88
+ localizedPrice?: string;
89
+ currency?: string;
90
+ currencyCode?: string;
91
+ price?: string | number;
92
+ oneTimePurchaseOfferDetails?: {
93
+ formattedPrice?: string;
94
+ priceAmountMicros?: string | number;
95
+ priceCurrencyCode?: string;
96
+ };
97
+ subscriptionOfferDetails?: RawSubscriptionOffer[];
98
+ }
99
+
100
+ interface RawSubscriptionOffer {
101
+ offerToken?: string;
102
+ offerId?: string;
103
+ basePlanId?: string;
104
+ pricingPhases?: {
105
+ pricingPhaseList?: Array<{
106
+ formattedPrice?: string;
107
+ priceAmountMicros?: string | number;
108
+ priceCurrencyCode?: string;
109
+ billingPeriod?: string;
110
+ recurrenceMode?: number;
111
+ billingCycleCount?: number;
112
+ }>;
113
+ };
114
+ }
115
+
116
+ interface RawPurchase {
117
+ id?: string;
118
+ transactionId?: string;
119
+ productId?: string;
120
+ ids?: string[];
121
+ purchaseToken?: string;
122
+ purchaseStateAndroid?: number | null;
123
+ /** A string in the 16.x binding: `'pending' | 'purchased' | 'unknown'`. */
124
+ purchaseState?: number | string;
125
+ transactionDate?: number;
126
+ isAcknowledgedAndroid?: boolean;
127
+ isAcknowledged?: boolean;
128
+ autoRenewingAndroid?: boolean;
129
+ isAutoRenewing?: boolean;
130
+ expirationDateAndroid?: number;
131
+ transactionReceipt?: string;
132
+ dataAndroid?: string;
133
+ }
134
+
135
+ /** What `purchaseErrorListener` delivers. */
136
+ interface RawPurchaseError {
137
+ code?: string;
138
+ message?: string;
139
+ productId?: string | null;
140
+ }
141
+
142
+ /**
143
+ * How long to wait for the outcome event after `requestPurchase` has resolved.
144
+ * The binding emits the event before or as it resolves, so this only bounds the
145
+ * case where none ever comes; it never runs while the user is in Play's UI.
146
+ */
147
+ const RESULT_EVENT_GRACE_MS = 2_000;
148
+
149
+ /** Play's replacement modes, by the codes the engine passes (`engine/subscriptions.ts`). */
150
+ const REPLACEMENT_MODES: Record<string, SubscriptionReplacementModeAndroid> = {
151
+ WITH_TIME_PRORATION: 'with-time-proration',
152
+ CHARGE_FULL_PRICE: 'charge-full-price',
153
+ CHARGE_PRORATED_PRICE: 'charge-prorated-price',
154
+ DEFERRED: 'deferred',
155
+ };
156
+
157
+ /** The request in the binding's 16.7 shape: keyed `google`, not `android`. */
158
+ export function toRequestProps(request: ProviderPurchaseRequest): RequestPurchaseProps {
159
+ const google = {
160
+ skus: [request.storeProductId],
161
+ ...(request.obfuscatedAccountId ? { obfuscatedAccountId: request.obfuscatedAccountId } : {}),
162
+ };
163
+ if (request.productType !== 'subscription') {
164
+ return { request: { google }, type: 'in-app' };
165
+ }
166
+
167
+ const replacementMode = request.prorationMode
168
+ ? REPLACEMENT_MODES[request.prorationMode]
169
+ : undefined;
170
+ return {
171
+ request: {
172
+ google: {
173
+ ...google,
174
+ ...(request.offerKey
175
+ ? {
176
+ subscriptionOffers: [{ sku: request.storeProductId, offerToken: request.offerKey }],
177
+ }
178
+ : {}),
179
+ // A plan change: the token of the purchase being replaced, and — for
180
+ // the replacement mode to apply — its product id (Billing 8.1+).
181
+ ...(request.replacePurchaseToken ? { purchaseToken: request.replacePurchaseToken } : {}),
182
+ ...(request.replacePurchaseToken && request.replaceStoreProductId && replacementMode
183
+ ? {
184
+ subscriptionProductReplacementParams: {
185
+ oldProductId: request.replaceStoreProductId,
186
+ replacementMode,
187
+ },
188
+ }
189
+ : {}),
190
+ },
191
+ },
192
+ type: 'subs',
193
+ };
194
+ }
195
+
196
+ /** Play's `PurchaseState`: 0 unspecified, 1 purchased, 2 pending. */
197
+ const PLAY_STATE_PURCHASED = 1;
198
+ const PLAY_STATE_PENDING = 2;
199
+
200
+ // Required lazily (rn-core's lazy peer) so importing the package does not require
201
+ // the native module.
202
+ const iapPeer = lazyPeer('react-native-iap', () => {
203
+ // Inside `try`, so Metro bundles an app that leaves this optional peer out.
204
+ try {
205
+ return require('react-native-iap') as IapModule;
206
+ } catch (cause) {
207
+ throw cause;
208
+ }
209
+ });
210
+
211
+ function loadModule(): IapModule {
212
+ return iapPeer.require(
213
+ (peer, cause) =>
214
+ new PaymentError({
215
+ code: 'PAYMENT_UNAVAILABLE',
216
+ message: `${peer} is not installed or its native module is not linked`,
217
+ operation: 'initialize',
218
+ cause: redact(cause),
219
+ }),
220
+ );
221
+ }
222
+
223
+ function toMicros(value: string | number | undefined): number {
224
+ if (typeof value === 'number') {
225
+ return value;
226
+ }
227
+ if (typeof value === 'string') {
228
+ const parsed = Number.parseInt(value, 10);
229
+ return Number.isFinite(parsed) ? parsed : 0;
230
+ }
231
+ return 0;
232
+ }
233
+
234
+ function normalizeProduct(raw: RawProduct, productType: ProductType): ProviderProduct {
235
+ const oneTime = raw.oneTimePurchaseOfferDetails;
236
+ const currencyCode = oneTime?.priceCurrencyCode ?? raw.currencyCode ?? raw.currency ?? '';
237
+
238
+ return {
239
+ storeProductId: raw.id ?? raw.productId ?? '',
240
+ productType,
241
+ title: raw.title ?? raw.name ?? '',
242
+ description: raw.description ?? '',
243
+ // Store-formatted, never built here: only the store knows the right currency
244
+ // symbol, separator, and placement for the user's locale (FR-028).
245
+ formattedPrice: oneTime?.formattedPrice ?? raw.displayPrice ?? raw.localizedPrice ?? '',
246
+ currencyCode,
247
+ priceAmountMicros: toMicros(oneTime?.priceAmountMicros ?? raw.price),
248
+ offers: (raw.subscriptionOfferDetails ?? []).map(offer => normalizeOffer(offer, currencyCode)),
249
+ };
250
+ }
251
+
252
+ function normalizeOffer(
253
+ offer: RawSubscriptionOffer,
254
+ fallbackCurrency: string,
255
+ ): ProviderProduct['offers'][number] {
256
+ const phases = offer.pricingPhases?.pricingPhaseList ?? [];
257
+ // The last phase is the recurring price; earlier ones are trial or
258
+ // introductory. Play orders them that way.
259
+ const recurring = phases[phases.length - 1];
260
+ const intro = phases.length > 1 ? phases[0] : undefined;
261
+ const isFreeTrial = intro !== undefined && toMicros(intro.priceAmountMicros) === 0;
262
+
263
+ return {
264
+ offerKey: offer.offerToken ?? offer.offerId ?? offer.basePlanId ?? '',
265
+ billingPeriod: recurring?.billingPeriod ?? '',
266
+ formattedPrice: recurring?.formattedPrice ?? '',
267
+ priceAmountMicros: toMicros(recurring?.priceAmountMicros),
268
+ currencyCode: recurring?.priceCurrencyCode ?? fallbackCurrency,
269
+ trialPeriod: isFreeTrial ? intro?.billingPeriod : undefined,
270
+ introductoryPrice:
271
+ intro && !isFreeTrial
272
+ ? {
273
+ formattedPrice: intro.formattedPrice ?? '',
274
+ period: intro.billingPeriod ?? '',
275
+ cycles: intro.billingCycleCount ?? 1,
276
+ }
277
+ : undefined,
278
+ // Play decides eligibility by only returning offers the user qualifies for,
279
+ // so forwarding `true` reports the store's determination rather than
280
+ // computing our own (FR-026).
281
+ isEligible: true,
282
+ };
283
+ }
284
+
285
+ /**
286
+ * Reads the purchase state from whichever field the binding filled.
287
+ *
288
+ * Pending is preserved, never flattened to purchased: that distinction is what
289
+ * stops an entitlement being granted for money that has not arrived (FR-037).
290
+ * And an unrecognized or missing state is `unspecified`, never `purchased`.
291
+ *
292
+ * 0.1.0 read only Play's numeric state and treated anything else as purchased.
293
+ * The 16.x binding hands JavaScript the *string* state and does not carry the
294
+ * numeric one across, so on a device every pending purchase arrived as a string,
295
+ * fell through to the default, and was granted. Unit tests could not see it: they
296
+ * drive the fake store, which never passes through here.
297
+ */
298
+ export function toProviderPurchaseState(
299
+ raw: Pick<RawPurchase, 'purchaseStateAndroid' | 'purchaseState'>,
300
+ ): ProviderPurchase['state'] {
301
+ let numeric: number | undefined;
302
+ if (typeof raw.purchaseStateAndroid === 'number') {
303
+ numeric = raw.purchaseStateAndroid;
304
+ } else if (typeof raw.purchaseState === 'number') {
305
+ numeric = raw.purchaseState;
306
+ }
307
+ if (numeric !== undefined) {
308
+ if (numeric === PLAY_STATE_PENDING) {
309
+ return 'pending';
310
+ }
311
+ return numeric === PLAY_STATE_PURCHASED ? 'purchased' : 'unspecified';
312
+ }
313
+
314
+ switch (typeof raw.purchaseState === 'string' ? raw.purchaseState.toLowerCase() : '') {
315
+ case 'purchased':
316
+ case 'restored':
317
+ return 'purchased';
318
+ case 'pending':
319
+ case 'deferred':
320
+ return 'pending';
321
+ default:
322
+ return 'unspecified';
323
+ }
324
+ }
325
+
326
+ function normalizePurchase(raw: RawPurchase): ProviderPurchase {
327
+ return {
328
+ storeProductId: raw.productId ?? raw.ids?.[0] ?? '',
329
+ transactionId: raw.id ?? raw.transactionId ?? raw.purchaseToken ?? '',
330
+ token: raw.purchaseToken ?? '',
331
+ state: toProviderPurchaseState(raw),
332
+ purchasedAt: raw.transactionDate ?? Date.now(),
333
+ isAcknowledged: raw.isAcknowledgedAndroid ?? raw.isAcknowledged ?? false,
334
+ expiresAt: raw.expirationDateAndroid,
335
+ willAutoRenew: raw.autoRenewingAndroid ?? raw.isAutoRenewing,
336
+ // Opaque material for the app's backend. Carried here and handed to the
337
+ // validation hook only — never logged or put in an event (FR-074).
338
+ verificationPayload: raw.transactionReceipt ?? raw.dataAndroid,
339
+ };
340
+ }
341
+
342
+ /** Maps a binding error code onto the port's vocabulary, so no store code escapes. */
343
+ function mapErrorCode(code: string | undefined): ProviderFailureReason {
344
+ switch (code) {
345
+ case 'E_USER_CANCELLED':
346
+ case 'user-cancelled':
347
+ return 'user_cancelled';
348
+ case 'E_ALREADY_OWNED':
349
+ case 'already-owned':
350
+ case 'item-already-owned':
351
+ return 'already_owned';
352
+ case 'E_ITEM_UNAVAILABLE':
353
+ case 'item-unavailable':
354
+ case 'sku-not-found':
355
+ return 'unknown_product';
356
+ case 'E_NOT_PREPARED':
357
+ case 'not-prepared':
358
+ return 'not_ready';
359
+ case 'E_NETWORK_ERROR':
360
+ case 'network-error':
361
+ return 'network_error';
362
+ case 'E_DEFERRED_PAYMENT':
363
+ // Not a failure — a pending purchase. The caller resolves it from the
364
+ // purchase update rather than from this error.
365
+ return 'store_error';
366
+ default:
367
+ return 'store_error';
368
+ }
369
+ }
370
+
371
+ const ANDROID_CAPABILITIES: ProviderCapabilities = {
372
+ supportsSubscriptions: true,
373
+ supportsPlanChange: true,
374
+ supportsPriceChangeConfirmation: false,
375
+ /**
376
+ * False, and this is a platform fact rather than a gap in this adapter.
377
+ *
378
+ * Client-side Play Billing cannot separate grace period from account hold: a
379
+ * grace-period subscription is still returned as active, and one in account
380
+ * hold stops being returned at all — indistinguishable from expired, cancelled,
381
+ * or refunded. The entitlement layer reads this flag and reports
382
+ * `indeterminate` rather than inventing a distinction (research.md R5).
383
+ */
384
+ reportsGraceAndHoldDistinctly: false,
385
+ supportsExternalTransactions: false,
386
+ /** This one really does move money, which is what arms the environment guard. */
387
+ createsRealTransactions: true,
388
+ /** The outcome event comes only when the user leaves Play's purchase UI. */
389
+ purchaseOutcomeIncludesStoreTime: true,
390
+ };
391
+
392
+ export interface IapAdapterOptions {
393
+ /** Injected in tests that need to drive the mapping without the native module. */
394
+ module?: IapModule;
395
+ }
396
+
397
+ export function createIapAdapter(options: IapAdapterOptions = {}): ProviderPort {
398
+ let iap: IapModule | undefined = options.module;
399
+
400
+ /** Tracked here, never read from the binding — see the openiap#408 note above. */
401
+ let connected = false;
402
+
403
+ const connectionListeners = createListenerSet<[boolean, string | undefined]>();
404
+ const purchaseListeners = createListenerSet<[ProviderPurchase]>();
405
+ /** Only an in-flight `launchPurchase` listens here; see there. */
406
+ const purchaseErrorListeners = createListenerSet<[RawPurchaseError]>();
407
+ let updateSub: { remove(): void } | undefined;
408
+ let errorSub: { remove(): void } | undefined;
409
+
410
+ const module = (): IapModule => {
411
+ if (!iap) {
412
+ iap = loadModule();
413
+ }
414
+ return iap;
415
+ };
416
+
417
+ const notifyConnection = (next: boolean, reason?: string): void => {
418
+ if (connected === next) {
419
+ return;
420
+ }
421
+ connected = next;
422
+ connectionListeners.notify(next, reason);
423
+ };
424
+
425
+ const attachListeners = (): void => {
426
+ // Every connect attaches, so whatever an earlier connect left must go first.
427
+ // Overwriting the handles orphaned the old native listeners, which kept
428
+ // firing — every purchase update reached the engine once per connect.
429
+ detachListeners();
430
+ const mod = module();
431
+ updateSub = mod.purchaseUpdatedListener(raw => {
432
+ purchaseListeners.notify(normalizePurchase(raw));
433
+ });
434
+ errorSub = mod.purchaseErrorListener(error => {
435
+ // A `not-prepared` error is the one signal the binding gives that the
436
+ // service went away underneath us, so it is treated as a disconnect
437
+ // rather than as a purchase failure.
438
+ if (mapErrorCode(error.code) === 'not_ready') {
439
+ notifyConnection(false, 'not_prepared');
440
+ }
441
+ purchaseErrorListeners.notify(error);
442
+ });
443
+ };
444
+
445
+ const detachListeners = (): void => {
446
+ updateSub?.remove();
447
+ updateSub = undefined;
448
+ errorSub?.remove();
449
+ errorSub = undefined;
450
+ };
451
+
452
+ return {
453
+ async connect(): Promise<ProviderConnectOutcome> {
454
+ try {
455
+ const mod = module();
456
+ // Always a full cycle. The binding's own reconnect has reported success
457
+ // without rebuilding anything, so we never rely on it (openiap#408).
458
+ if (connected) {
459
+ await mod.endConnection().catch(() => undefined);
460
+ connected = false;
461
+ }
462
+ const ok = await mod.initConnection();
463
+ if (!ok) {
464
+ return {
465
+ ok: false,
466
+ reason: 'no_billing_service',
467
+ retryable: true,
468
+ };
469
+ }
470
+ attachListeners();
471
+ notifyConnection(true);
472
+ return { ok: true };
473
+ } catch (error) {
474
+ const code = (error as { code?: string }).code;
475
+ // A missing or too-old Play Services install is not the same as a
476
+ // transient error, and the app shows different things for each (FR-021).
477
+ if (code === 'E_IAP_NOT_AVAILABLE' || code === 'iap-not-available') {
478
+ return { ok: false, reason: 'no_billing_service', retryable: false };
479
+ }
480
+ if (code === 'E_SERVICE_ERROR') {
481
+ return {
482
+ ok: false,
483
+ reason: 'billing_service_outdated',
484
+ retryable: true,
485
+ };
486
+ }
487
+ return { ok: false, reason: 'store_error', retryable: true };
488
+ }
489
+ },
490
+
491
+ async disconnect(): Promise<void> {
492
+ detachListeners();
493
+ try {
494
+ await module().endConnection();
495
+ } catch {
496
+ // Already down; nothing to tear down.
497
+ }
498
+ notifyConnection(false, 'disconnect');
499
+ },
500
+
501
+ observeConnection(listener): Unsubscribe {
502
+ return connectionListeners.add(listener);
503
+ },
504
+
505
+ async queryProducts(
506
+ storeProductIds: StoreProductId[],
507
+ productType: ProductType,
508
+ ): Promise<ProviderProduct[]> {
509
+ const raw = await module().fetchProducts({
510
+ skus: storeProductIds,
511
+ type: productType === 'subscription' ? 'subs' : 'in-app',
512
+ });
513
+ return raw.map(product => normalizeProduct(product, productType));
514
+ },
515
+
516
+ async queryOwned(): Promise<ProviderPurchase[]> {
517
+ const raw = await module().getAvailablePurchases();
518
+ // Pending purchases are mapped through, flagged rather than filtered: the
519
+ // engine needs to see them to raise the pending signal (FR-038).
520
+ return raw.map(normalizePurchase);
521
+ },
522
+
523
+ /**
524
+ * Settles on the first outcome event for this product: a purchase update
525
+ * (bought or pending) or a purchase error (cancelled, already owned, …).
526
+ *
527
+ * The binding's promise is not the outcome: on Android it resolves with an
528
+ * empty list when the flow ends, whatever happened. Its listeners also feed
529
+ * `observePurchases`, so the engine sees a bought purchase twice — here and
530
+ * as a store update — and grants it once (FR-044).
531
+ */
532
+ launchPurchase(request: ProviderPurchaseRequest): Promise<ProviderPurchaseOutcome> {
533
+ const sku = request.storeProductId;
534
+ return new Promise<ProviderPurchaseOutcome>(resolve => {
535
+ let settled = false;
536
+ let grace: ReturnType<typeof setTimeout> | undefined;
537
+
538
+ const onPurchase = (purchase: ProviderPurchase): void => {
539
+ if (purchase.storeProductId === sku) {
540
+ finish({ ok: true, purchase });
541
+ }
542
+ };
543
+ const onError = (error: RawPurchaseError): void => {
544
+ if (error.productId && error.productId !== sku) {
545
+ return;
546
+ }
547
+ finish({ ok: false, reason: mapErrorCode(error.code), detail: error.code });
548
+ };
549
+ const fail = (error: unknown): void => {
550
+ const code = (error as { code?: string } | undefined)?.code;
551
+ finish({ ok: false, reason: mapErrorCode(code), detail: code });
552
+ };
553
+ function finish(outcome: ProviderPurchaseOutcome): void {
554
+ if (settled) {
555
+ return;
556
+ }
557
+ settled = true;
558
+ clearTimeout(grace);
559
+ stopPurchase();
560
+ stopError();
561
+ resolve(outcome);
562
+ }
563
+
564
+ const stopPurchase = purchaseListeners.add(onPurchase);
565
+ const stopError = purchaseErrorListeners.add(onError);
566
+ try {
567
+ module()
568
+ .requestPurchase(toRequestProps(request))
569
+ .then(() => {
570
+ if (!settled) {
571
+ grace = setTimeout(
572
+ () =>
573
+ finish({
574
+ ok: false,
575
+ reason: 'store_error',
576
+ detail: 'no purchase event',
577
+ }),
578
+ RESULT_EVENT_GRACE_MS,
579
+ );
580
+ }
581
+ }, fail);
582
+ } catch (error) {
583
+ fail(error);
584
+ }
585
+ });
586
+ },
587
+
588
+ observePurchases(listener): Unsubscribe {
589
+ return purchaseListeners.add(listener);
590
+ },
591
+
592
+ async acknowledge(token: ProviderToken): Promise<void> {
593
+ // Idempotent at the store: acknowledging an already-acknowledged purchase
594
+ // is accepted, which is what FR-044 relies on.
595
+ await module().finishTransaction({
596
+ purchase: { purchaseToken: token },
597
+ isConsumable: false,
598
+ });
599
+ },
600
+
601
+ async consume(token: ProviderToken): Promise<void> {
602
+ await module().finishTransaction({
603
+ purchase: { purchaseToken: token },
604
+ isConsumable: true,
605
+ });
606
+ },
607
+
608
+ async openSubscriptionManagement(storeProductId?: StoreProductId): Promise<void> {
609
+ // The store's own screen. Platforms forbid a self-built cancellation
610
+ // screen, so there is deliberately no alternative path here (FR-066).
611
+ const mod = module();
612
+ if (!mod.deepLinkToSubscriptions) {
613
+ return;
614
+ }
615
+ await mod.deepLinkToSubscriptions({ skuAndroid: storeProductId });
616
+ },
617
+
618
+ async confirmPriceChange(): Promise<ProviderPriceChangeOutcome> {
619
+ // Play has no client-side price-change confirmation flow; it notifies the
620
+ // user itself. Reported as unsupported rather than faked, matching
621
+ // `supportsPriceChangeConfirmation: false` (FR-067).
622
+ return { ok: false, reason: 'store_error' };
623
+ },
624
+
625
+ capabilities: () => ANDROID_CAPABILITIES,
626
+ };
627
+ }