@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,238 +1,274 @@
1
- /**
2
- * Hooks over the engine.
3
- *
4
- * Each subscribes on mount and unsubscribes on unmount, so repeated mount/unmount
5
- * leaves no duplicate subscription and no surviving listener (FR-006, PERF-002).
6
- *
7
- * Reads are synchronous: the engine holds entitlements in memory, so a hook never
8
- * returns a loading placeholder for an entitlement it already knows (PERF-001).
9
- */
10
-
11
- import { useCallback, useEffect, useState } from 'react';
12
- import { usePaymentEngine } from './PaymentProvider';
13
- import type {
14
- EntitlementKey,
15
- FinalizeResult,
16
- PaymentStatus,
17
- PurchaseOptions,
18
- PurchaseResult,
19
- TransactionRef,
20
- } from '../config/types';
21
- import type {
22
- EntitlementMap,
23
- EntitlementState,
24
- } from '../entitlements/aggregate';
25
- import type { PaymentError } from '../diagnostics/errors';
26
- import type { MissingProduct, ProductInfo } from '../engine/products';
27
- import type { RestoreOutcome, SyncOutcome } from '../engine/engine';
28
-
29
- /**
30
- * One entitlement, re-rendering only when that one changes.
31
- *
32
- * The returned `status` is `unknown` until the first sync completes. That is the
33
- * point: an app must be able to tell "not yet known" from "not entitled" so a
34
- * paying user never sees the unpaid experience flash (FR-047).
35
- */
36
- export function useEntitlement(key: EntitlementKey): EntitlementState {
37
- const engine = usePaymentEngine();
38
- const [state, setState] = useState<EntitlementState>(() =>
39
- engine.getEntitlement(key),
40
- );
41
-
42
- useEffect(() => {
43
- // Re-read on subscribe: the entitlement may have changed between the initial
44
- // render and this effect.
45
- setState(engine.getEntitlement(key));
46
- return engine.subscribeEntitlements(map => {
47
- const next = map[key];
48
- if (next) {
49
- setState(next);
50
- }
51
- });
52
- }, [engine, key]);
53
-
54
- return state;
55
- }
56
-
57
- /** Every entitlement at once, for a screen that shows overall plan state. */
58
- export function useEntitlements(): EntitlementMap {
59
- const engine = usePaymentEngine();
60
- const [map, setMap] = useState<EntitlementMap>(() =>
61
- engine.getAllEntitlements(),
62
- );
63
-
64
- useEffect(() => {
65
- setMap(engine.getAllEntitlements());
66
- return engine.subscribeEntitlements(setMap);
67
- }, [engine]);
68
-
69
- return map;
70
- }
71
-
72
- /** Package status, so an app can tell "cannot sell here" from "not paid" (FR-022). */
73
- export function usePaymentStatus(): PaymentStatus {
74
- const engine = usePaymentEngine();
75
- const [status, setStatus] = useState<PaymentStatus>(() => engine.getStatus());
76
-
77
- useEffect(() => {
78
- setStatus(engine.getStatus());
79
- return engine.subscribeStatus(setStatus);
80
- }, [engine]);
81
-
82
- return status;
83
- }
84
-
85
- export interface UsePurchaseResult {
86
- purchase: (
87
- productKey: EntitlementKey,
88
- options?: PurchaseOptions,
89
- ) => Promise<PurchaseResult>;
90
- consume: (ref: TransactionRef) => Promise<FinalizeResult>;
91
- isPurchasing: boolean;
92
- /** The last outcome, so a screen can render cancellation differently from failure. */
93
- lastResult: PurchaseResult | undefined;
94
- }
95
-
96
- /**
97
- * Starting a purchase.
98
- *
99
- * `lastResult` is the full typed union rather than a boolean, because a screen has
100
- * to treat `user_cancelled` differently from `store_error` — showing an error
101
- * banner to someone who simply changed their mind is the most common paywall bug.
102
- */
103
- export function usePurchase(): UsePurchaseResult {
104
- const engine = usePaymentEngine();
105
- const [isPurchasing, setIsPurchasing] = useState(false);
106
- const [lastResult, setLastResult] = useState<PurchaseResult | undefined>();
107
-
108
- const purchase = useCallback(
109
- async (
110
- productKey: string,
111
- options?: PurchaseOptions,
112
- ): Promise<PurchaseResult> => {
113
- setIsPurchasing(true);
114
- try {
115
- const result = await engine.purchase(productKey, options);
116
- setLastResult(result);
117
- return result;
118
- } finally {
119
- setIsPurchasing(false);
120
- }
121
- },
122
- [engine],
123
- );
124
-
125
- const consume = useCallback(
126
- (ref: TransactionRef): Promise<FinalizeResult> => engine.consume(ref),
127
- [engine],
128
- );
129
-
130
- return { purchase, consume, isPurchasing, lastResult };
131
- }
132
-
133
- export interface UseProductsResult {
134
- products: ProductInfo[];
135
- /** Reported so a paywall explains an absent row instead of rendering a blank. */
136
- missing: MissingProduct[];
137
- isLoading: boolean;
138
- error: PaymentError | undefined;
139
- refresh: () => Promise<void>;
140
- }
141
-
142
- /**
143
- * Store-supplied product information for a paywall.
144
- *
145
- * Every price here is already formatted by the store for the user's locale. An app
146
- * must render `formattedPrice` and never build its own string from
147
- * `priceAmountMicros` — that field exists for sorting and comparison only
148
- * (FR-028).
149
- */
150
- export function useProducts(productKeys: readonly string[]): UseProductsResult {
151
- const engine = usePaymentEngine();
152
- const [products, setProducts] = useState<ProductInfo[]>([]);
153
- const [missing, setMissing] = useState<MissingProduct[]>([]);
154
- const [isLoading, setIsLoading] = useState(false);
155
- const [error, setError] = useState<PaymentError | undefined>();
156
-
157
- // Joined so the effect depends on the contents rather than the array identity:
158
- // a caller passing a literal would otherwise re-query on every render.
159
- const keyToken = productKeys.join('|');
160
-
161
- const load = useCallback(
162
- async (fresh: boolean): Promise<void> => {
163
- const keys = keyToken === '' ? [] : keyToken.split('|');
164
- if (keys.length === 0) {
165
- setProducts([]);
166
- setMissing([]);
167
- return;
168
- }
169
- setIsLoading(true);
170
- try {
171
- const result = fresh
172
- ? await engine.refreshProducts(keys)
173
- : await engine.getProducts(keys);
174
- if (result.ok) {
175
- setProducts(result.products);
176
- setMissing(result.missing);
177
- setError(undefined);
178
- } else {
179
- setError(result.error);
180
- }
181
- } finally {
182
- setIsLoading(false);
183
- }
184
- },
185
- [engine, keyToken],
186
- );
187
-
188
- useEffect(() => {
189
- load(false).catch(() => undefined);
190
- }, [load]);
191
-
192
- const refresh = useCallback(() => load(true), [load]);
193
-
194
- return { products, missing, isLoading, error, refresh };
195
- }
196
-
197
- export interface UseSyncResult {
198
- sync: () => Promise<SyncOutcome>;
199
- restore: () => Promise<RestoreOutcome>;
200
- isSyncing: boolean;
201
- lastSyncedAt: number | undefined;
202
- }
203
-
204
- /**
205
- * Sync and restore, for a "Restore purchases" control.
206
- *
207
- * `restore`'s outcome distinguishes "restored" from "nothing found", so the app
208
- * can avoid telling a user their purchases came back when none existed (FR-061).
209
- */
210
- export function useSync(): UseSyncResult {
211
- const engine = usePaymentEngine();
212
- const [isSyncing, setIsSyncing] = useState(false);
213
- const [lastSyncedAt, setLastSyncedAt] = useState<number | undefined>(() =>
214
- engine.getLastSyncedAt(),
215
- );
216
-
217
- const sync = useCallback(async (): Promise<SyncOutcome> => {
218
- setIsSyncing(true);
219
- try {
220
- return await engine.sync('manual');
221
- } finally {
222
- setIsSyncing(false);
223
- setLastSyncedAt(engine.getLastSyncedAt());
224
- }
225
- }, [engine]);
226
-
227
- const restore = useCallback(async (): Promise<RestoreOutcome> => {
228
- setIsSyncing(true);
229
- try {
230
- return await engine.restore();
231
- } finally {
232
- setIsSyncing(false);
233
- setLastSyncedAt(engine.getLastSyncedAt());
234
- }
235
- }, [engine]);
236
-
237
- return { sync, restore, isSyncing, lastSyncedAt };
238
- }
1
+ /**
2
+ * Hooks over the engine.
3
+ *
4
+ * Each subscribes on mount and unsubscribes on unmount, so repeated mount/unmount
5
+ * leaves no duplicate subscription and no surviving listener (FR-006, PERF-002).
6
+ *
7
+ * Reads are synchronous: the engine holds entitlements in memory, so a hook never
8
+ * returns a loading placeholder for an entitlement it already knows (PERF-001).
9
+ */
10
+
11
+ import { useCallback, useEffect, useState } from 'react';
12
+ import { usePaymentEngine } from './PaymentProvider';
13
+ import type {
14
+ EntitlementKey,
15
+ FinalizeResult,
16
+ PaymentStatus,
17
+ PendingPurchasesState,
18
+ PurchaseOptions,
19
+ PurchaseResult,
20
+ TransactionRef,
21
+ } from '../config/types';
22
+ import type {
23
+ EntitlementMap,
24
+ EntitlementState,
25
+ } from '../entitlements/aggregate';
26
+ import type { PaymentError } from '../diagnostics/errors';
27
+ import type { MissingProduct, ProductInfo } from '../engine/products';
28
+ import type { RestoreOutcome, SyncOutcome } from '../engine/engine';
29
+
30
+ /**
31
+ * One entitlement, re-rendering only when that one changes.
32
+ *
33
+ * The returned `status` is `unknown` until the first sync completes. That is the
34
+ * point: an app must be able to tell "not yet known" from "not entitled" so a
35
+ * paying user never sees the unpaid experience flash (FR-047).
36
+ */
37
+ export function useEntitlement(key: EntitlementKey): EntitlementState {
38
+ const engine = usePaymentEngine();
39
+ const [state, setState] = useState<EntitlementState>(() =>
40
+ engine.getEntitlement(key),
41
+ );
42
+
43
+ useEffect(() => {
44
+ // Re-read on subscribe: the entitlement may have changed between the initial
45
+ // render and this effect.
46
+ setState(engine.getEntitlement(key));
47
+ return engine.subscribeEntitlements(map => {
48
+ const next = map[key];
49
+ if (next) {
50
+ setState(next);
51
+ }
52
+ });
53
+ }, [engine, key]);
54
+
55
+ return state;
56
+ }
57
+
58
+ /** Every entitlement at once, for a screen that shows overall plan state. */
59
+ export function useEntitlements(): EntitlementMap {
60
+ const engine = usePaymentEngine();
61
+ const [map, setMap] = useState<EntitlementMap>(() =>
62
+ engine.getAllEntitlements(),
63
+ );
64
+
65
+ useEffect(() => {
66
+ setMap(engine.getAllEntitlements());
67
+ return engine.subscribeEntitlements(setMap);
68
+ }, [engine]);
69
+
70
+ return map;
71
+ }
72
+
73
+ function narrowPending(
74
+ state: PendingPurchasesState,
75
+ keys: readonly string[] | null,
76
+ ): PendingPurchasesState {
77
+ return keys
78
+ ? { ...state, purchases: state.purchases.filter(p => keys.includes(p.productKey)) }
79
+ : state;
80
+ }
81
+
82
+ /**
83
+ * Pending purchases, in this session or an earlier one (FR-101). Added in 0.2.0.
84
+ *
85
+ * Pass product keys to narrow it to the products one screen sells. Read
86
+ * `status` before the list: under `unknown`, an empty list is not "nothing
87
+ * pending", and a Buy button shown on it could charge a user twice.
88
+ */
89
+ export function usePendingPurchases(
90
+ productKeys?: readonly string[],
91
+ ): PendingPurchasesState {
92
+ const engine = usePaymentEngine();
93
+ // Joined so a caller passing a literal array does not resubscribe each render.
94
+ const keyToken = productKeys ? productKeys.join('|') : null;
95
+ const [state, setState] = useState<PendingPurchasesState>(() =>
96
+ narrowPending(engine.getPendingPurchases(), productKeys ?? null),
97
+ );
98
+
99
+ useEffect(() => {
100
+ const keys = keyToken === null ? null : keyToken.split('|').filter(Boolean);
101
+ setState(narrowPending(engine.getPendingPurchases(), keys));
102
+ return engine.subscribePendingPurchases(next => setState(narrowPending(next, keys)));
103
+ }, [engine, keyToken]);
104
+
105
+ return state;
106
+ }
107
+
108
+ /** Package status, so an app can tell "cannot sell here" from "not paid" (FR-022). */
109
+ export function usePaymentStatus(): PaymentStatus {
110
+ const engine = usePaymentEngine();
111
+ const [status, setStatus] = useState<PaymentStatus>(() => engine.getStatus());
112
+
113
+ useEffect(() => {
114
+ setStatus(engine.getStatus());
115
+ return engine.subscribeStatus(setStatus);
116
+ }, [engine]);
117
+
118
+ return status;
119
+ }
120
+
121
+ export interface UsePurchaseResult {
122
+ purchase: (
123
+ productKey: EntitlementKey,
124
+ options?: PurchaseOptions,
125
+ ) => Promise<PurchaseResult>;
126
+ consume: (ref: TransactionRef) => Promise<FinalizeResult>;
127
+ isPurchasing: boolean;
128
+ /** The last outcome, so a screen can render cancellation differently from failure. */
129
+ lastResult: PurchaseResult | undefined;
130
+ }
131
+
132
+ /**
133
+ * Starting a purchase.
134
+ *
135
+ * `lastResult` is the full typed union rather than a boolean, because a screen has
136
+ * to treat `user_cancelled` differently from `store_error` — showing an error
137
+ * banner to someone who simply changed their mind is the most common paywall bug.
138
+ */
139
+ export function usePurchase(): UsePurchaseResult {
140
+ const engine = usePaymentEngine();
141
+ const [isPurchasing, setIsPurchasing] = useState(false);
142
+ const [lastResult, setLastResult] = useState<PurchaseResult | undefined>();
143
+
144
+ const purchase = useCallback(
145
+ async (
146
+ productKey: string,
147
+ options?: PurchaseOptions,
148
+ ): Promise<PurchaseResult> => {
149
+ setIsPurchasing(true);
150
+ try {
151
+ const result = await engine.purchase(productKey, options);
152
+ setLastResult(result);
153
+ return result;
154
+ } finally {
155
+ setIsPurchasing(false);
156
+ }
157
+ },
158
+ [engine],
159
+ );
160
+
161
+ const consume = useCallback(
162
+ (ref: TransactionRef): Promise<FinalizeResult> => engine.consume(ref),
163
+ [engine],
164
+ );
165
+
166
+ return { purchase, consume, isPurchasing, lastResult };
167
+ }
168
+
169
+ export interface UseProductsResult {
170
+ products: ProductInfo[];
171
+ /** Reported so a paywall explains an absent row instead of rendering a blank. */
172
+ missing: MissingProduct[];
173
+ isLoading: boolean;
174
+ error: PaymentError | undefined;
175
+ refresh: () => Promise<void>;
176
+ }
177
+
178
+ /**
179
+ * Store-supplied product information for a paywall.
180
+ *
181
+ * Every price here is already formatted by the store for the user's locale. An app
182
+ * must render `formattedPrice` and never build its own string from
183
+ * `priceAmountMicros` — that field exists for sorting and comparison only
184
+ * (FR-028).
185
+ */
186
+ export function useProducts(productKeys: readonly string[]): UseProductsResult {
187
+ const engine = usePaymentEngine();
188
+ const [products, setProducts] = useState<ProductInfo[]>([]);
189
+ const [missing, setMissing] = useState<MissingProduct[]>([]);
190
+ const [isLoading, setIsLoading] = useState(false);
191
+ const [error, setError] = useState<PaymentError | undefined>();
192
+
193
+ // Joined so the effect depends on the contents rather than the array identity:
194
+ // a caller passing a literal would otherwise re-query on every render.
195
+ const keyToken = productKeys.join('|');
196
+
197
+ const load = useCallback(
198
+ async (fresh: boolean): Promise<void> => {
199
+ const keys = keyToken === '' ? [] : keyToken.split('|');
200
+ if (keys.length === 0) {
201
+ setProducts([]);
202
+ setMissing([]);
203
+ return;
204
+ }
205
+ setIsLoading(true);
206
+ try {
207
+ const result = fresh
208
+ ? await engine.refreshProducts(keys)
209
+ : await engine.getProducts(keys);
210
+ if (result.ok) {
211
+ setProducts(result.products);
212
+ setMissing(result.missing);
213
+ setError(undefined);
214
+ } else {
215
+ setError(result.error);
216
+ }
217
+ } finally {
218
+ setIsLoading(false);
219
+ }
220
+ },
221
+ [engine, keyToken],
222
+ );
223
+
224
+ useEffect(() => {
225
+ load(false).catch(() => undefined);
226
+ }, [load]);
227
+
228
+ const refresh = useCallback(() => load(true), [load]);
229
+
230
+ return { products, missing, isLoading, error, refresh };
231
+ }
232
+
233
+ export interface UseSyncResult {
234
+ sync: () => Promise<SyncOutcome>;
235
+ restore: () => Promise<RestoreOutcome>;
236
+ isSyncing: boolean;
237
+ lastSyncedAt: number | undefined;
238
+ }
239
+
240
+ /**
241
+ * Sync and restore, for a "Restore purchases" control.
242
+ *
243
+ * `restore`'s outcome distinguishes "restored" from "nothing found", so the app
244
+ * can avoid telling a user their purchases came back when none existed (FR-061).
245
+ */
246
+ export function useSync(): UseSyncResult {
247
+ const engine = usePaymentEngine();
248
+ const [isSyncing, setIsSyncing] = useState(false);
249
+ const [lastSyncedAt, setLastSyncedAt] = useState<number | undefined>(() =>
250
+ engine.getLastSyncedAt(),
251
+ );
252
+
253
+ const sync = useCallback(async (): Promise<SyncOutcome> => {
254
+ setIsSyncing(true);
255
+ try {
256
+ return await engine.sync('manual');
257
+ } finally {
258
+ setIsSyncing(false);
259
+ setLastSyncedAt(engine.getLastSyncedAt());
260
+ }
261
+ }, [engine]);
262
+
263
+ const restore = useCallback(async (): Promise<RestoreOutcome> => {
264
+ setIsSyncing(true);
265
+ try {
266
+ return await engine.restore();
267
+ } finally {
268
+ setIsSyncing(false);
269
+ setLastSyncedAt(engine.getLastSyncedAt());
270
+ }
271
+ }, [engine]);
272
+
273
+ return { sync, restore, isSyncing, lastSyncedAt };
274
+ }
@@ -49,6 +49,21 @@ export interface FakeStore extends ProviderPort {
49
49
  pushPurchaseUpdate(purchase: ProviderPurchase): void;
50
50
  /** Stop reporting a transaction as valid — a refund or revocation (FR-064). */
51
51
  revoke(transactionId: string): void;
52
+
53
+ // --- Ending a pending purchase (0.2.0) -------------------------------------
54
+ // Each changes store-side state only, as the real store does: the engine sees
55
+ // it at its next sync, so it works the same across a simulated app kill. To
56
+ // deliver a settlement without a sync, `pushPurchaseUpdate` it as well.
57
+ /** The money arrives: the owned record turns `purchased` (FR-039). */
58
+ settlePending(transactionId: string): void;
59
+ /** The payment is declined or abandoned: the store stops reporting it (FR-040). */
60
+ cancelPending(transactionId: string): void;
61
+ /**
62
+ * The pending window runs out. Reported through `pendingEndReason`, which a
63
+ * store that knows implements — Play does not, so on device this is
64
+ * indistinguishable from `cancelPending` (FR-102).
65
+ */
66
+ expirePending(transactionId: string): void;
52
67
  setProducts(products: ProviderProduct[]): void;
53
68
 
54
69
  // --- Connection ------------------------------------------------------------
@@ -123,6 +138,8 @@ export function createFakeStore(options: FakeStoreOptions = {}): FakeStore {
123
138
 
124
139
  let finalizeFails = false;
125
140
  let connected = false;
141
+ /** Why each pending purchase ended, for the ones `expirePending` or `cancelPending` ended. */
142
+ const endReasons = new Map<string, 'cancelled' | 'expired'>();
126
143
 
127
144
  const acknowledgedTokens: ProviderToken[] = [];
128
145
  const consumedTokens: ProviderToken[] = [];
@@ -263,6 +280,8 @@ export function createFakeStore(options: FakeStoreOptions = {}): FakeStore {
263
280
 
264
281
  capabilities: () => capabilities,
265
282
 
283
+ pendingEndReason: transactionId => endReasons.get(transactionId),
284
+
266
285
  // --- Scripting ---------------------------------------------------------
267
286
  scriptPurchaseSuccess(overrides) {
268
287
  scripted = { kind: 'success', overrides };
@@ -290,6 +309,19 @@ export function createFakeStore(options: FakeStoreOptions = {}): FakeStore {
290
309
  revoke(transactionId) {
291
310
  owned = owned.filter(p => p.transactionId !== transactionId);
292
311
  },
312
+ settlePending(transactionId) {
313
+ owned = owned.map(p =>
314
+ p.transactionId === transactionId ? { ...p, state: 'purchased' } : p,
315
+ );
316
+ },
317
+ cancelPending(transactionId) {
318
+ owned = owned.filter(p => p.transactionId !== transactionId);
319
+ endReasons.set(transactionId, 'cancelled');
320
+ },
321
+ expirePending(transactionId) {
322
+ owned = owned.filter(p => p.transactionId !== transactionId);
323
+ endReasons.set(transactionId, 'expired');
324
+ },
293
325
  setProducts(next) {
294
326
  products = [...next];
295
327
  },
@@ -327,6 +359,7 @@ export function createFakeStore(options: FakeStoreOptions = {}): FakeStore {
327
359
  scripted = undefined;
328
360
  finalizeFails = false;
329
361
  connected = false;
362
+ endReasons.clear();
330
363
  acknowledgedTokens.length = 0;
331
364
  consumedTokens.length = 0;
332
365
  managementOpenedFor.length = 0;