@chipmobilesdk/rn-payment 0.1.0 → 0.2.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,516 +1,547 @@
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
- * ## Verification status
10
- *
11
- * The binding is **not yet installed** — the root `react-native-nitro-modules`
12
- * bump it requires is held pending approval (see specs/013-rn-payment-sdk/plan.md,
13
- * Post-Implementation Notes). So the call shapes below are written against
14
- * `react-native-iap` 16.x as documented, and **every one must be verified against
15
- * the installed package** before this adapter is trusted on a device. The module
16
- * is required lazily and the surface it needs is declared explicitly in
17
- * `IapModule`, so a mismatch surfaces here rather than deep in the engine.
18
- *
19
- * No test exercises this file: the whole suite runs against the fake store, and
20
- * the IAP test double throws on every call precisely so that reaching this code in
21
- * a test fails loudly instead of passing against a stub.
22
- *
23
- * ## Known upstream defect this guards against
24
- *
25
- * openiap#408: the Android bridge did not clear its internal `isInitialized` flag
26
- * on disconnect, so `connected` stayed true, later calls failed with
27
- * `E_NOT_PREPARED`, and `reconnect()` reported success without rebuilding
28
- * anything. This adapter therefore (a) tracks connection state itself rather than
29
- * trusting the binding's flag, and (b) always performs a full
30
- * `endConnection` + `initConnection` cycle instead of calling any reconnect
31
- * shortcut.
32
- */
33
-
34
- import type { ProductType, Unsubscribe } from '../config/types';
35
- import type {
36
- ProviderCapabilities,
37
- ProviderConnectOutcome,
38
- ProviderFailureReason,
39
- ProviderPort,
40
- ProviderPriceChangeOutcome,
41
- ProviderProduct,
42
- ProviderPurchase,
43
- ProviderPurchaseOutcome,
44
- ProviderPurchaseRequest,
45
- ProviderToken,
46
- StoreProductId,
47
- } from './port';
48
-
49
- /**
50
- * Exactly what this adapter needs from the binding.
51
- *
52
- * Declared narrowly on purpose: it documents the coupling, and it means a binding
53
- * upgrade that changes one of these shapes fails to typecheck here instead of
54
- * failing silently at runtime on a user's device.
55
- */
56
- interface IapModule {
57
- initConnection(): Promise<boolean>;
58
- endConnection(): Promise<void>;
59
- fetchProducts(params: {
60
- skus: string[];
61
- type: 'in-app' | 'subs';
62
- }): Promise<RawProduct[]>;
63
- getAvailablePurchases(): Promise<RawPurchase[]>;
64
- requestPurchase(params: unknown): Promise<unknown>;
65
- finishTransaction(params: {
66
- purchase: unknown;
67
- isConsumable?: boolean;
68
- }): Promise<unknown>;
69
- purchaseUpdatedListener(
70
- listener: (purchase: RawPurchase) => void,
71
- ): { remove(): void };
72
- purchaseErrorListener(
73
- listener: (error: { code?: string; message?: string }) => void,
74
- ): { remove(): void };
75
- deepLinkToSubscriptions?(params: { skuAndroid?: string }): Promise<void>;
76
- }
77
-
78
- interface RawProduct {
79
- id?: string;
80
- productId?: string;
81
- title?: string;
82
- name?: string;
83
- description?: string;
84
- displayPrice?: string;
85
- localizedPrice?: string;
86
- currency?: string;
87
- currencyCode?: string;
88
- price?: string | number;
89
- oneTimePurchaseOfferDetails?: {
90
- formattedPrice?: string;
91
- priceAmountMicros?: string | number;
92
- priceCurrencyCode?: string;
93
- };
94
- subscriptionOfferDetails?: RawSubscriptionOffer[];
95
- }
96
-
97
- interface RawSubscriptionOffer {
98
- offerToken?: string;
99
- offerId?: string;
100
- basePlanId?: string;
101
- pricingPhases?: {
102
- pricingPhaseList?: Array<{
103
- formattedPrice?: string;
104
- priceAmountMicros?: string | number;
105
- priceCurrencyCode?: string;
106
- billingPeriod?: string;
107
- recurrenceMode?: number;
108
- billingCycleCount?: number;
109
- }>;
110
- };
111
- }
112
-
113
- interface RawPurchase {
114
- id?: string;
115
- transactionId?: string;
116
- productId?: string;
117
- ids?: string[];
118
- purchaseToken?: string;
119
- purchaseStateAndroid?: number;
120
- purchaseState?: number | string;
121
- transactionDate?: number;
122
- isAcknowledgedAndroid?: boolean;
123
- isAcknowledged?: boolean;
124
- autoRenewingAndroid?: boolean;
125
- isAutoRenewing?: boolean;
126
- expirationDateAndroid?: number;
127
- transactionReceipt?: string;
128
- dataAndroid?: string;
129
- }
130
-
131
- /** Play's `PurchaseState`: 0 unspecified, 1 purchased, 2 pending. */
132
- const PLAY_STATE_PURCHASED = 1;
133
- const PLAY_STATE_PENDING = 2;
134
-
135
- function loadModule(): IapModule {
136
- // Required lazily so importing the package does not require the native module.
137
- const mod = require('react-native-iap') as IapModule;
138
- return mod;
139
- }
140
-
141
- function toMicros(value: string | number | undefined): number {
142
- if (typeof value === 'number') {
143
- return value;
144
- }
145
- if (typeof value === 'string') {
146
- const parsed = Number.parseInt(value, 10);
147
- return Number.isFinite(parsed) ? parsed : 0;
148
- }
149
- return 0;
150
- }
151
-
152
- function normalizeProduct(
153
- raw: RawProduct,
154
- productType: ProductType,
155
- ): ProviderProduct {
156
- const oneTime = raw.oneTimePurchaseOfferDetails;
157
- const currencyCode =
158
- oneTime?.priceCurrencyCode ?? raw.currencyCode ?? raw.currency ?? '';
159
-
160
- return {
161
- storeProductId: raw.id ?? raw.productId ?? '',
162
- productType,
163
- title: raw.title ?? raw.name ?? '',
164
- description: raw.description ?? '',
165
- // Store-formatted, never built here: only the store knows the right currency
166
- // symbol, separator, and placement for the user's locale (FR-028).
167
- formattedPrice:
168
- oneTime?.formattedPrice ?? raw.displayPrice ?? raw.localizedPrice ?? '',
169
- currencyCode,
170
- priceAmountMicros: toMicros(oneTime?.priceAmountMicros ?? raw.price),
171
- offers: (raw.subscriptionOfferDetails ?? []).map(offer =>
172
- normalizeOffer(offer, currencyCode),
173
- ),
174
- };
175
- }
176
-
177
- function normalizeOffer(
178
- offer: RawSubscriptionOffer,
179
- fallbackCurrency: string,
180
- ): ProviderProduct['offers'][number] {
181
- const phases = offer.pricingPhases?.pricingPhaseList ?? [];
182
- // The last phase is the recurring price; earlier ones are trial or
183
- // introductory. Play orders them that way.
184
- const recurring = phases[phases.length - 1];
185
- const intro = phases.length > 1 ? phases[0] : undefined;
186
- const isFreeTrial = intro !== undefined && toMicros(intro.priceAmountMicros) === 0;
187
-
188
- return {
189
- offerKey: offer.offerToken ?? offer.offerId ?? offer.basePlanId ?? '',
190
- billingPeriod: recurring?.billingPeriod ?? '',
191
- formattedPrice: recurring?.formattedPrice ?? '',
192
- priceAmountMicros: toMicros(recurring?.priceAmountMicros),
193
- currencyCode: recurring?.priceCurrencyCode ?? fallbackCurrency,
194
- trialPeriod: isFreeTrial ? intro?.billingPeriod : undefined,
195
- introductoryPrice:
196
- intro && !isFreeTrial
197
- ? {
198
- formattedPrice: intro.formattedPrice ?? '',
199
- period: intro.billingPeriod ?? '',
200
- cycles: intro.billingCycleCount ?? 1,
201
- }
202
- : undefined,
203
- // Play decides eligibility by only returning offers the user qualifies for,
204
- // so forwarding `true` reports the store's determination rather than
205
- // computing our own (FR-026).
206
- isEligible: true,
207
- };
208
- }
209
-
210
- function normalizePurchase(raw: RawPurchase): ProviderPurchase {
211
- const state = raw.purchaseStateAndroid ?? raw.purchaseState;
212
- const numericState = typeof state === 'number' ? state : PLAY_STATE_PURCHASED;
213
-
214
- return {
215
- storeProductId: raw.productId ?? raw.ids?.[0] ?? '',
216
- transactionId: raw.id ?? raw.transactionId ?? raw.purchaseToken ?? '',
217
- token: raw.purchaseToken ?? '',
218
- // Pending is preserved, never flattened to purchased: that distinction is
219
- // what stops an entitlement being granted for money that has not arrived
220
- // (FR-037).
221
- state:
222
- numericState === PLAY_STATE_PENDING
223
- ? 'pending'
224
- : numericState === PLAY_STATE_PURCHASED
225
- ? 'purchased'
226
- : 'unspecified',
227
- purchasedAt: raw.transactionDate ?? Date.now(),
228
- isAcknowledged: raw.isAcknowledgedAndroid ?? raw.isAcknowledged ?? false,
229
- expiresAt: raw.expirationDateAndroid,
230
- willAutoRenew: raw.autoRenewingAndroid ?? raw.isAutoRenewing,
231
- // Opaque material for the app's backend. Carried here and handed to the
232
- // validation hook only — never logged or put in an event (FR-074).
233
- verificationPayload: raw.transactionReceipt ?? raw.dataAndroid,
234
- };
235
- }
236
-
237
- /** Maps a binding error code onto the port's vocabulary, so no store code escapes. */
238
- function mapErrorCode(code: string | undefined): ProviderFailureReason {
239
- switch (code) {
240
- case 'E_USER_CANCELLED':
241
- case 'user-cancelled':
242
- return 'user_cancelled';
243
- case 'E_ALREADY_OWNED':
244
- case 'item-already-owned':
245
- return 'already_owned';
246
- case 'E_ITEM_UNAVAILABLE':
247
- case 'item-unavailable':
248
- return 'unknown_product';
249
- case 'E_NOT_PREPARED':
250
- case 'not-prepared':
251
- return 'not_ready';
252
- case 'E_NETWORK_ERROR':
253
- case 'network-error':
254
- return 'network_error';
255
- case 'E_DEFERRED_PAYMENT':
256
- // Not a failure — a pending purchase. The caller resolves it from the
257
- // purchase update rather than from this error.
258
- return 'store_error';
259
- default:
260
- return 'store_error';
261
- }
262
- }
263
-
264
- const ANDROID_CAPABILITIES: ProviderCapabilities = {
265
- supportsSubscriptions: true,
266
- supportsPlanChange: true,
267
- supportsPriceChangeConfirmation: false,
268
- /**
269
- * False, and this is a platform fact rather than a gap in this adapter.
270
- *
271
- * Client-side Play Billing cannot separate grace period from account hold: a
272
- * grace-period subscription is still returned as active, and one in account
273
- * hold stops being returned at all — indistinguishable from expired, cancelled,
274
- * or refunded. The entitlement layer reads this flag and reports
275
- * `indeterminate` rather than inventing a distinction (research.md R5).
276
- */
277
- reportsGraceAndHoldDistinctly: false,
278
- supportsExternalTransactions: false,
279
- /** This one really does move money, which is what arms the environment guard. */
280
- createsRealTransactions: true,
281
- };
282
-
283
- export interface IapAdapterOptions {
284
- /** Injected in tests that need to drive the mapping without the native module. */
285
- module?: IapModule;
286
- }
287
-
288
- export function createIapAdapter(options: IapAdapterOptions = {}): ProviderPort {
289
- let iap: IapModule | undefined = options.module;
290
-
291
- /** Tracked here, never read from the binding — see the openiap#408 note above. */
292
- let connected = false;
293
-
294
- const connectionListeners = new Set<
295
- (connected: boolean, reason?: string) => void
296
- >();
297
- const purchaseListeners = new Set<(purchase: ProviderPurchase) => void>();
298
- let updateSub: { remove(): void } | undefined;
299
- let errorSub: { remove(): void } | undefined;
300
-
301
- const module = (): IapModule => {
302
- if (!iap) {
303
- iap = loadModule();
304
- }
305
- return iap;
306
- };
307
-
308
- const notifyConnection = (next: boolean, reason?: string): void => {
309
- if (connected === next) {
310
- return;
311
- }
312
- connected = next;
313
- for (const listener of connectionListeners) {
314
- listener(next, reason);
315
- }
316
- };
317
-
318
- const attachListeners = (): void => {
319
- const mod = module();
320
- updateSub = mod.purchaseUpdatedListener(raw => {
321
- const purchase = normalizePurchase(raw);
322
- for (const listener of purchaseListeners) {
323
- listener(purchase);
324
- }
325
- });
326
- errorSub = mod.purchaseErrorListener(error => {
327
- // A `not-prepared` error is the one signal the binding gives that the
328
- // service went away underneath us, so it is treated as a disconnect
329
- // rather than as a purchase failure.
330
- if (mapErrorCode(error.code) === 'not_ready') {
331
- notifyConnection(false, 'not_prepared');
332
- }
333
- });
334
- };
335
-
336
- const detachListeners = (): void => {
337
- updateSub?.remove();
338
- updateSub = undefined;
339
- errorSub?.remove();
340
- errorSub = undefined;
341
- };
342
-
343
- return {
344
- async connect(): Promise<ProviderConnectOutcome> {
345
- try {
346
- const mod = module();
347
- // Always a full cycle. The binding's own reconnect has reported success
348
- // without rebuilding anything, so we never rely on it (openiap#408).
349
- if (connected) {
350
- await mod.endConnection().catch(() => undefined);
351
- connected = false;
352
- }
353
- const ok = await mod.initConnection();
354
- if (!ok) {
355
- return {
356
- ok: false,
357
- reason: 'no_billing_service',
358
- retryable: true,
359
- };
360
- }
361
- attachListeners();
362
- notifyConnection(true);
363
- return { ok: true };
364
- } catch (error) {
365
- const code = (error as { code?: string }).code;
366
- // A missing or too-old Play Services install is not the same as a
367
- // transient error, and the app shows different things for each (FR-021).
368
- if (code === 'E_IAP_NOT_AVAILABLE' || code === 'iap-not-available') {
369
- return { ok: false, reason: 'no_billing_service', retryable: false };
370
- }
371
- if (code === 'E_SERVICE_ERROR') {
372
- return {
373
- ok: false,
374
- reason: 'billing_service_outdated',
375
- retryable: true,
376
- };
377
- }
378
- return { ok: false, reason: 'store_error', retryable: true };
379
- }
380
- },
381
-
382
- async disconnect(): Promise<void> {
383
- detachListeners();
384
- try {
385
- await module().endConnection();
386
- } catch {
387
- // Already down; nothing to tear down.
388
- }
389
- notifyConnection(false, 'disconnect');
390
- },
391
-
392
- observeConnection(listener): Unsubscribe {
393
- connectionListeners.add(listener);
394
- let removed = false;
395
- return () => {
396
- if (removed) {
397
- return;
398
- }
399
- removed = true;
400
- connectionListeners.delete(listener);
401
- };
402
- },
403
-
404
- async queryProducts(
405
- storeProductIds: StoreProductId[],
406
- productType: ProductType,
407
- ): Promise<ProviderProduct[]> {
408
- const raw = await module().fetchProducts({
409
- skus: storeProductIds,
410
- type: productType === 'subscription' ? 'subs' : 'in-app',
411
- });
412
- return raw.map(product => normalizeProduct(product, productType));
413
- },
414
-
415
- async queryOwned(): Promise<ProviderPurchase[]> {
416
- const raw = await module().getAvailablePurchases();
417
- // Pending purchases are mapped through, flagged rather than filtered: the
418
- // engine needs to see them to raise the pending signal (FR-038).
419
- return raw.map(normalizePurchase);
420
- },
421
-
422
- async launchPurchase(
423
- request: ProviderPurchaseRequest,
424
- ): Promise<ProviderPurchaseOutcome> {
425
- try {
426
- const isSubscription = request.productType === 'subscription';
427
- const result = await module().requestPurchase({
428
- request: {
429
- android: {
430
- skus: [request.storeProductId],
431
- obfuscatedAccountIdAndroid: request.obfuscatedAccountId,
432
- ...(isSubscription && request.offerKey
433
- ? {
434
- subscriptionOffers: [
435
- {
436
- sku: request.storeProductId,
437
- offerToken: request.offerKey,
438
- },
439
- ],
440
- }
441
- : {}),
442
- ...(request.replaceStoreProductId
443
- ? {
444
- purchaseTokenAndroid: request.replaceStoreProductId,
445
- replacementModeAndroid: request.prorationMode,
446
- }
447
- : {}),
448
- },
449
- },
450
- type: isSubscription ? 'subs' : 'in-app',
451
- });
452
-
453
- // The binding may resolve with the purchase, or resolve empty and deliver
454
- // it through the update listener. Both are handled: the engine also
455
- // ingests listener-delivered purchases, so neither path loses one.
456
- const raw = Array.isArray(result) ? result[0] : result;
457
- if (!raw) {
458
- return { ok: false, reason: 'store_error', detail: 'no purchase returned' };
459
- }
460
- return { ok: true, purchase: normalizePurchase(raw as RawPurchase) };
461
- } catch (error) {
462
- const code = (error as { code?: string }).code;
463
- return { ok: false, reason: mapErrorCode(code), detail: code };
464
- }
465
- },
466
-
467
- observePurchases(listener): Unsubscribe {
468
- purchaseListeners.add(listener);
469
- let removed = false;
470
- return () => {
471
- if (removed) {
472
- return;
473
- }
474
- removed = true;
475
- purchaseListeners.delete(listener);
476
- };
477
- },
478
-
479
- async acknowledge(token: ProviderToken): Promise<void> {
480
- // Idempotent at the store: acknowledging an already-acknowledged purchase
481
- // is accepted, which is what FR-044 relies on.
482
- await module().finishTransaction({
483
- purchase: { purchaseToken: token },
484
- isConsumable: false,
485
- });
486
- },
487
-
488
- async consume(token: ProviderToken): Promise<void> {
489
- await module().finishTransaction({
490
- purchase: { purchaseToken: token },
491
- isConsumable: true,
492
- });
493
- },
494
-
495
- async openSubscriptionManagement(
496
- storeProductId?: StoreProductId,
497
- ): Promise<void> {
498
- // The store's own screen. Platforms forbid a self-built cancellation
499
- // screen, so there is deliberately no alternative path here (FR-066).
500
- const mod = module();
501
- if (!mod.deepLinkToSubscriptions) {
502
- return;
503
- }
504
- await mod.deepLinkToSubscriptions({ skuAndroid: storeProductId });
505
- },
506
-
507
- async confirmPriceChange(): Promise<ProviderPriceChangeOutcome> {
508
- // Play has no client-side price-change confirmation flow; it notifies the
509
- // user itself. Reported as unsupported rather than faked, matching
510
- // `supportsPriceChangeConfirmation: false` (FR-067).
511
- return { ok: false, reason: 'store_error' };
512
- },
513
-
514
- capabilities: () => ANDROID_CAPABILITIES,
515
- };
516
- }
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
+ * ## Verification status
10
+ *
11
+ * The binding is **not yet installed** — the root `react-native-nitro-modules`
12
+ * bump it requires is held pending approval (see specs/013-rn-payment-sdk/plan.md,
13
+ * Post-Implementation Notes). So the call shapes below are written against
14
+ * `react-native-iap` 16.x as documented, and **every one must be verified against
15
+ * the installed package** before this adapter is trusted on a device. The module
16
+ * is required lazily and the surface it needs is declared explicitly in
17
+ * `IapModule`, so a mismatch surfaces here rather than deep in the engine.
18
+ *
19
+ * No test exercises this file: the whole suite runs against the fake store, and
20
+ * the IAP test double throws on every call precisely so that reaching this code in
21
+ * a test fails loudly instead of passing against a stub.
22
+ *
23
+ * ## Known upstream defect this guards against
24
+ *
25
+ * openiap#408: the Android bridge did not clear its internal `isInitialized` flag
26
+ * on disconnect, so `connected` stayed true, later calls failed with
27
+ * `E_NOT_PREPARED`, and `reconnect()` reported success without rebuilding
28
+ * anything. This adapter therefore (a) tracks connection state itself rather than
29
+ * trusting the binding's flag, and (b) always performs a full
30
+ * `endConnection` + `initConnection` cycle instead of calling any reconnect
31
+ * shortcut.
32
+ */
33
+
34
+ import type { ProductType, Unsubscribe } from '../config/types';
35
+ import type {
36
+ ProviderCapabilities,
37
+ ProviderConnectOutcome,
38
+ ProviderFailureReason,
39
+ ProviderPort,
40
+ ProviderPriceChangeOutcome,
41
+ ProviderProduct,
42
+ ProviderPurchase,
43
+ ProviderPurchaseOutcome,
44
+ ProviderPurchaseRequest,
45
+ ProviderToken,
46
+ StoreProductId,
47
+ } from './port';
48
+
49
+ /**
50
+ * Exactly what this adapter needs from the binding.
51
+ *
52
+ * Declared narrowly on purpose: it documents the coupling, and it means a binding
53
+ * upgrade that changes one of these shapes fails to typecheck here instead of
54
+ * failing silently at runtime on a user's device.
55
+ */
56
+ interface IapModule {
57
+ initConnection(): Promise<boolean>;
58
+ endConnection(): Promise<void>;
59
+ fetchProducts(params: {
60
+ skus: string[];
61
+ type: 'in-app' | 'subs';
62
+ }): Promise<RawProduct[]>;
63
+ getAvailablePurchases(): Promise<RawPurchase[]>;
64
+ requestPurchase(params: unknown): Promise<unknown>;
65
+ finishTransaction(params: {
66
+ purchase: unknown;
67
+ isConsumable?: boolean;
68
+ }): Promise<unknown>;
69
+ purchaseUpdatedListener(
70
+ listener: (purchase: RawPurchase) => void,
71
+ ): { remove(): void };
72
+ purchaseErrorListener(
73
+ listener: (error: { code?: string; message?: string }) => void,
74
+ ): { remove(): void };
75
+ deepLinkToSubscriptions?(params: { skuAndroid?: string }): Promise<void>;
76
+ }
77
+
78
+ interface RawProduct {
79
+ id?: string;
80
+ productId?: string;
81
+ title?: string;
82
+ name?: string;
83
+ description?: string;
84
+ displayPrice?: string;
85
+ localizedPrice?: string;
86
+ currency?: string;
87
+ currencyCode?: string;
88
+ price?: string | number;
89
+ oneTimePurchaseOfferDetails?: {
90
+ formattedPrice?: string;
91
+ priceAmountMicros?: string | number;
92
+ priceCurrencyCode?: string;
93
+ };
94
+ subscriptionOfferDetails?: RawSubscriptionOffer[];
95
+ }
96
+
97
+ interface RawSubscriptionOffer {
98
+ offerToken?: string;
99
+ offerId?: string;
100
+ basePlanId?: string;
101
+ pricingPhases?: {
102
+ pricingPhaseList?: Array<{
103
+ formattedPrice?: string;
104
+ priceAmountMicros?: string | number;
105
+ priceCurrencyCode?: string;
106
+ billingPeriod?: string;
107
+ recurrenceMode?: number;
108
+ billingCycleCount?: number;
109
+ }>;
110
+ };
111
+ }
112
+
113
+ interface RawPurchase {
114
+ id?: string;
115
+ transactionId?: string;
116
+ productId?: string;
117
+ ids?: string[];
118
+ purchaseToken?: string;
119
+ purchaseStateAndroid?: number | null;
120
+ /** A string in the 16.x binding: `'pending' | 'purchased' | 'unknown'`. */
121
+ purchaseState?: number | string;
122
+ transactionDate?: number;
123
+ isAcknowledgedAndroid?: boolean;
124
+ isAcknowledged?: boolean;
125
+ autoRenewingAndroid?: boolean;
126
+ isAutoRenewing?: boolean;
127
+ expirationDateAndroid?: number;
128
+ transactionReceipt?: string;
129
+ dataAndroid?: string;
130
+ }
131
+
132
+ /** Play's `PurchaseState`: 0 unspecified, 1 purchased, 2 pending. */
133
+ const PLAY_STATE_PURCHASED = 1;
134
+ const PLAY_STATE_PENDING = 2;
135
+
136
+ function loadModule(): IapModule {
137
+ // Required lazily so importing the package does not require the native module.
138
+ const mod = require('react-native-iap') as IapModule;
139
+ return mod;
140
+ }
141
+
142
+ function toMicros(value: string | number | undefined): number {
143
+ if (typeof value === 'number') {
144
+ return value;
145
+ }
146
+ if (typeof value === 'string') {
147
+ const parsed = Number.parseInt(value, 10);
148
+ return Number.isFinite(parsed) ? parsed : 0;
149
+ }
150
+ return 0;
151
+ }
152
+
153
+ function normalizeProduct(
154
+ raw: RawProduct,
155
+ productType: ProductType,
156
+ ): ProviderProduct {
157
+ const oneTime = raw.oneTimePurchaseOfferDetails;
158
+ const currencyCode =
159
+ oneTime?.priceCurrencyCode ?? raw.currencyCode ?? raw.currency ?? '';
160
+
161
+ return {
162
+ storeProductId: raw.id ?? raw.productId ?? '',
163
+ productType,
164
+ title: raw.title ?? raw.name ?? '',
165
+ description: raw.description ?? '',
166
+ // Store-formatted, never built here: only the store knows the right currency
167
+ // symbol, separator, and placement for the user's locale (FR-028).
168
+ formattedPrice:
169
+ oneTime?.formattedPrice ?? raw.displayPrice ?? raw.localizedPrice ?? '',
170
+ currencyCode,
171
+ priceAmountMicros: toMicros(oneTime?.priceAmountMicros ?? raw.price),
172
+ offers: (raw.subscriptionOfferDetails ?? []).map(offer =>
173
+ normalizeOffer(offer, currencyCode),
174
+ ),
175
+ };
176
+ }
177
+
178
+ function normalizeOffer(
179
+ offer: RawSubscriptionOffer,
180
+ fallbackCurrency: string,
181
+ ): ProviderProduct['offers'][number] {
182
+ const phases = offer.pricingPhases?.pricingPhaseList ?? [];
183
+ // The last phase is the recurring price; earlier ones are trial or
184
+ // introductory. Play orders them that way.
185
+ const recurring = phases[phases.length - 1];
186
+ const intro = phases.length > 1 ? phases[0] : undefined;
187
+ const isFreeTrial = intro !== undefined && toMicros(intro.priceAmountMicros) === 0;
188
+
189
+ return {
190
+ offerKey: offer.offerToken ?? offer.offerId ?? offer.basePlanId ?? '',
191
+ billingPeriod: recurring?.billingPeriod ?? '',
192
+ formattedPrice: recurring?.formattedPrice ?? '',
193
+ priceAmountMicros: toMicros(recurring?.priceAmountMicros),
194
+ currencyCode: recurring?.priceCurrencyCode ?? fallbackCurrency,
195
+ trialPeriod: isFreeTrial ? intro?.billingPeriod : undefined,
196
+ introductoryPrice:
197
+ intro && !isFreeTrial
198
+ ? {
199
+ formattedPrice: intro.formattedPrice ?? '',
200
+ period: intro.billingPeriod ?? '',
201
+ cycles: intro.billingCycleCount ?? 1,
202
+ }
203
+ : undefined,
204
+ // Play decides eligibility by only returning offers the user qualifies for,
205
+ // so forwarding `true` reports the store's determination rather than
206
+ // computing our own (FR-026).
207
+ isEligible: true,
208
+ };
209
+ }
210
+
211
+ /**
212
+ * Reads the purchase state from whichever field the binding filled.
213
+ *
214
+ * Pending is preserved, never flattened to purchased: that distinction is what
215
+ * stops an entitlement being granted for money that has not arrived (FR-037).
216
+ * And an unrecognized or missing state is `unspecified`, never `purchased`.
217
+ *
218
+ * 0.1.0 read only Play's numeric state and treated anything else as purchased.
219
+ * The 16.x binding hands JavaScript the *string* state and does not carry the
220
+ * numeric one across, so on a device every pending purchase arrived as a string,
221
+ * fell through to the default, and was granted. Unit tests could not see it: they
222
+ * drive the fake store, which never passes through here.
223
+ */
224
+ export function toProviderPurchaseState(
225
+ raw: Pick<RawPurchase, 'purchaseStateAndroid' | 'purchaseState'>,
226
+ ): ProviderPurchase['state'] {
227
+ let numeric: number | undefined;
228
+ if (typeof raw.purchaseStateAndroid === 'number') {
229
+ numeric = raw.purchaseStateAndroid;
230
+ } else if (typeof raw.purchaseState === 'number') {
231
+ numeric = raw.purchaseState;
232
+ }
233
+ if (numeric !== undefined) {
234
+ if (numeric === PLAY_STATE_PENDING) {
235
+ return 'pending';
236
+ }
237
+ return numeric === PLAY_STATE_PURCHASED ? 'purchased' : 'unspecified';
238
+ }
239
+
240
+ switch (typeof raw.purchaseState === 'string' ? raw.purchaseState.toLowerCase() : '') {
241
+ case 'purchased':
242
+ case 'restored':
243
+ return 'purchased';
244
+ case 'pending':
245
+ case 'deferred':
246
+ return 'pending';
247
+ default:
248
+ return 'unspecified';
249
+ }
250
+ }
251
+
252
+ function normalizePurchase(raw: RawPurchase): ProviderPurchase {
253
+ return {
254
+ storeProductId: raw.productId ?? raw.ids?.[0] ?? '',
255
+ transactionId: raw.id ?? raw.transactionId ?? raw.purchaseToken ?? '',
256
+ token: raw.purchaseToken ?? '',
257
+ state: toProviderPurchaseState(raw),
258
+ purchasedAt: raw.transactionDate ?? Date.now(),
259
+ isAcknowledged: raw.isAcknowledgedAndroid ?? raw.isAcknowledged ?? false,
260
+ expiresAt: raw.expirationDateAndroid,
261
+ willAutoRenew: raw.autoRenewingAndroid ?? raw.isAutoRenewing,
262
+ // Opaque material for the app's backend. Carried here and handed to the
263
+ // validation hook only — never logged or put in an event (FR-074).
264
+ verificationPayload: raw.transactionReceipt ?? raw.dataAndroid,
265
+ };
266
+ }
267
+
268
+ /** Maps a binding error code onto the port's vocabulary, so no store code escapes. */
269
+ function mapErrorCode(code: string | undefined): ProviderFailureReason {
270
+ switch (code) {
271
+ case 'E_USER_CANCELLED':
272
+ case 'user-cancelled':
273
+ return 'user_cancelled';
274
+ case 'E_ALREADY_OWNED':
275
+ case 'item-already-owned':
276
+ return 'already_owned';
277
+ case 'E_ITEM_UNAVAILABLE':
278
+ case 'item-unavailable':
279
+ return 'unknown_product';
280
+ case 'E_NOT_PREPARED':
281
+ case 'not-prepared':
282
+ return 'not_ready';
283
+ case 'E_NETWORK_ERROR':
284
+ case 'network-error':
285
+ return 'network_error';
286
+ case 'E_DEFERRED_PAYMENT':
287
+ // Not a failure — a pending purchase. The caller resolves it from the
288
+ // purchase update rather than from this error.
289
+ return 'store_error';
290
+ default:
291
+ return 'store_error';
292
+ }
293
+ }
294
+
295
+ const ANDROID_CAPABILITIES: ProviderCapabilities = {
296
+ supportsSubscriptions: true,
297
+ supportsPlanChange: true,
298
+ supportsPriceChangeConfirmation: false,
299
+ /**
300
+ * False, and this is a platform fact rather than a gap in this adapter.
301
+ *
302
+ * Client-side Play Billing cannot separate grace period from account hold: a
303
+ * grace-period subscription is still returned as active, and one in account
304
+ * hold stops being returned at all — indistinguishable from expired, cancelled,
305
+ * or refunded. The entitlement layer reads this flag and reports
306
+ * `indeterminate` rather than inventing a distinction (research.md R5).
307
+ */
308
+ reportsGraceAndHoldDistinctly: false,
309
+ supportsExternalTransactions: false,
310
+ /** This one really does move money, which is what arms the environment guard. */
311
+ createsRealTransactions: true,
312
+ };
313
+
314
+ export interface IapAdapterOptions {
315
+ /** Injected in tests that need to drive the mapping without the native module. */
316
+ module?: IapModule;
317
+ }
318
+
319
+ export function createIapAdapter(options: IapAdapterOptions = {}): ProviderPort {
320
+ let iap: IapModule | undefined = options.module;
321
+
322
+ /** Tracked here, never read from the binding — see the openiap#408 note above. */
323
+ let connected = false;
324
+
325
+ const connectionListeners = new Set<
326
+ (connected: boolean, reason?: string) => void
327
+ >();
328
+ const purchaseListeners = new Set<(purchase: ProviderPurchase) => void>();
329
+ let updateSub: { remove(): void } | undefined;
330
+ let errorSub: { remove(): void } | undefined;
331
+
332
+ const module = (): IapModule => {
333
+ if (!iap) {
334
+ iap = loadModule();
335
+ }
336
+ return iap;
337
+ };
338
+
339
+ const notifyConnection = (next: boolean, reason?: string): void => {
340
+ if (connected === next) {
341
+ return;
342
+ }
343
+ connected = next;
344
+ for (const listener of connectionListeners) {
345
+ listener(next, reason);
346
+ }
347
+ };
348
+
349
+ const attachListeners = (): void => {
350
+ const mod = module();
351
+ updateSub = mod.purchaseUpdatedListener(raw => {
352
+ const purchase = normalizePurchase(raw);
353
+ for (const listener of purchaseListeners) {
354
+ listener(purchase);
355
+ }
356
+ });
357
+ errorSub = mod.purchaseErrorListener(error => {
358
+ // A `not-prepared` error is the one signal the binding gives that the
359
+ // service went away underneath us, so it is treated as a disconnect
360
+ // rather than as a purchase failure.
361
+ if (mapErrorCode(error.code) === 'not_ready') {
362
+ notifyConnection(false, 'not_prepared');
363
+ }
364
+ });
365
+ };
366
+
367
+ const detachListeners = (): void => {
368
+ updateSub?.remove();
369
+ updateSub = undefined;
370
+ errorSub?.remove();
371
+ errorSub = undefined;
372
+ };
373
+
374
+ return {
375
+ async connect(): Promise<ProviderConnectOutcome> {
376
+ try {
377
+ const mod = module();
378
+ // Always a full cycle. The binding's own reconnect has reported success
379
+ // without rebuilding anything, so we never rely on it (openiap#408).
380
+ if (connected) {
381
+ await mod.endConnection().catch(() => undefined);
382
+ connected = false;
383
+ }
384
+ const ok = await mod.initConnection();
385
+ if (!ok) {
386
+ return {
387
+ ok: false,
388
+ reason: 'no_billing_service',
389
+ retryable: true,
390
+ };
391
+ }
392
+ attachListeners();
393
+ notifyConnection(true);
394
+ return { ok: true };
395
+ } catch (error) {
396
+ const code = (error as { code?: string }).code;
397
+ // A missing or too-old Play Services install is not the same as a
398
+ // transient error, and the app shows different things for each (FR-021).
399
+ if (code === 'E_IAP_NOT_AVAILABLE' || code === 'iap-not-available') {
400
+ return { ok: false, reason: 'no_billing_service', retryable: false };
401
+ }
402
+ if (code === 'E_SERVICE_ERROR') {
403
+ return {
404
+ ok: false,
405
+ reason: 'billing_service_outdated',
406
+ retryable: true,
407
+ };
408
+ }
409
+ return { ok: false, reason: 'store_error', retryable: true };
410
+ }
411
+ },
412
+
413
+ async disconnect(): Promise<void> {
414
+ detachListeners();
415
+ try {
416
+ await module().endConnection();
417
+ } catch {
418
+ // Already down; nothing to tear down.
419
+ }
420
+ notifyConnection(false, 'disconnect');
421
+ },
422
+
423
+ observeConnection(listener): Unsubscribe {
424
+ connectionListeners.add(listener);
425
+ let removed = false;
426
+ return () => {
427
+ if (removed) {
428
+ return;
429
+ }
430
+ removed = true;
431
+ connectionListeners.delete(listener);
432
+ };
433
+ },
434
+
435
+ async queryProducts(
436
+ storeProductIds: StoreProductId[],
437
+ productType: ProductType,
438
+ ): Promise<ProviderProduct[]> {
439
+ const raw = await module().fetchProducts({
440
+ skus: storeProductIds,
441
+ type: productType === 'subscription' ? 'subs' : 'in-app',
442
+ });
443
+ return raw.map(product => normalizeProduct(product, productType));
444
+ },
445
+
446
+ async queryOwned(): Promise<ProviderPurchase[]> {
447
+ const raw = await module().getAvailablePurchases();
448
+ // Pending purchases are mapped through, flagged rather than filtered: the
449
+ // engine needs to see them to raise the pending signal (FR-038).
450
+ return raw.map(normalizePurchase);
451
+ },
452
+
453
+ async launchPurchase(
454
+ request: ProviderPurchaseRequest,
455
+ ): Promise<ProviderPurchaseOutcome> {
456
+ try {
457
+ const isSubscription = request.productType === 'subscription';
458
+ const result = await module().requestPurchase({
459
+ request: {
460
+ android: {
461
+ skus: [request.storeProductId],
462
+ obfuscatedAccountIdAndroid: request.obfuscatedAccountId,
463
+ ...(isSubscription && request.offerKey
464
+ ? {
465
+ subscriptionOffers: [
466
+ {
467
+ sku: request.storeProductId,
468
+ offerToken: request.offerKey,
469
+ },
470
+ ],
471
+ }
472
+ : {}),
473
+ ...(request.replaceStoreProductId
474
+ ? {
475
+ purchaseTokenAndroid: request.replaceStoreProductId,
476
+ replacementModeAndroid: request.prorationMode,
477
+ }
478
+ : {}),
479
+ },
480
+ },
481
+ type: isSubscription ? 'subs' : 'in-app',
482
+ });
483
+
484
+ // The binding may resolve with the purchase, or resolve empty and deliver
485
+ // it through the update listener. Both are handled: the engine also
486
+ // ingests listener-delivered purchases, so neither path loses one.
487
+ const raw = Array.isArray(result) ? result[0] : result;
488
+ if (!raw) {
489
+ return { ok: false, reason: 'store_error', detail: 'no purchase returned' };
490
+ }
491
+ return { ok: true, purchase: normalizePurchase(raw as RawPurchase) };
492
+ } catch (error) {
493
+ const code = (error as { code?: string }).code;
494
+ return { ok: false, reason: mapErrorCode(code), detail: code };
495
+ }
496
+ },
497
+
498
+ observePurchases(listener): Unsubscribe {
499
+ purchaseListeners.add(listener);
500
+ let removed = false;
501
+ return () => {
502
+ if (removed) {
503
+ return;
504
+ }
505
+ removed = true;
506
+ purchaseListeners.delete(listener);
507
+ };
508
+ },
509
+
510
+ async acknowledge(token: ProviderToken): Promise<void> {
511
+ // Idempotent at the store: acknowledging an already-acknowledged purchase
512
+ // is accepted, which is what FR-044 relies on.
513
+ await module().finishTransaction({
514
+ purchase: { purchaseToken: token },
515
+ isConsumable: false,
516
+ });
517
+ },
518
+
519
+ async consume(token: ProviderToken): Promise<void> {
520
+ await module().finishTransaction({
521
+ purchase: { purchaseToken: token },
522
+ isConsumable: true,
523
+ });
524
+ },
525
+
526
+ async openSubscriptionManagement(
527
+ storeProductId?: StoreProductId,
528
+ ): Promise<void> {
529
+ // The store's own screen. Platforms forbid a self-built cancellation
530
+ // screen, so there is deliberately no alternative path here (FR-066).
531
+ const mod = module();
532
+ if (!mod.deepLinkToSubscriptions) {
533
+ return;
534
+ }
535
+ await mod.deepLinkToSubscriptions({ skuAndroid: storeProductId });
536
+ },
537
+
538
+ async confirmPriceChange(): Promise<ProviderPriceChangeOutcome> {
539
+ // Play has no client-side price-change confirmation flow; it notifies the
540
+ // user itself. Reported as unsupported rather than faked, matching
541
+ // `supportsPriceChangeConfirmation: false` (FR-067).
542
+ return { ok: false, reason: 'store_error' };
543
+ },
544
+
545
+ capabilities: () => ANDROID_CAPABILITIES,
546
+ };
547
+ }