expo-iap 6.2.0 → 6.3.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.
- package/.prettierignore +3 -1
- package/build/index.d.ts +12 -9
- package/build/index.d.ts.map +1 -1
- package/build/index.js +3 -2
- package/build/index.js.map +1 -1
- package/build/index.kepler.d.ts +6 -6
- package/build/index.kepler.d.ts.map +1 -1
- package/build/index.kepler.js +3 -2
- package/build/index.kepler.js.map +1 -1
- package/build/purchase-flow-confirmers.d.ts +99 -0
- package/build/purchase-flow-confirmers.d.ts.map +1 -0
- package/build/purchase-flow-confirmers.js +201 -0
- package/build/purchase-flow-confirmers.js.map +1 -0
- package/build/purchase-flow-core.d.ts +206 -0
- package/build/purchase-flow-core.d.ts.map +1 -0
- package/build/purchase-flow-core.js +343 -0
- package/build/purchase-flow-core.js.map +1 -0
- package/build/purchase-flow.d.ts +20 -297
- package/build/purchase-flow.d.ts.map +1 -1
- package/build/purchase-flow.js +13 -531
- package/build/purchase-flow.js.map +1 -1
- package/build/useIAP.d.ts +1 -1
- package/build/useIAP.d.ts.map +1 -1
- package/build/useIAP.js.map +1 -1
- package/build/utils/purchaseFlowBinding.d.ts +1 -1
- package/build/utils/purchaseFlowBinding.d.ts.map +1 -1
- package/build/utils/purchaseFlowBinding.js +1 -1
- package/build/utils/purchaseFlowBinding.js.map +1 -1
- package/build/vega-adapter.d.ts.map +1 -1
- package/build/vega-adapter.js +6 -5
- package/build/vega-adapter.js.map +1 -1
- package/openiap-versions.json +3 -3
- package/package.json +1 -1
- package/src/index.kepler.ts +9 -11
- package/src/index.ts +20 -19
- package/src/purchase-flow-confirmers.ts +346 -0
- package/src/purchase-flow-core.ts +604 -0
- package/src/purchase-flow.ts +43 -923
- package/src/useIAP.ts +1 -1
- package/src/utils/purchaseFlowBinding.ts +1 -1
- package/src/vega-adapter.ts +9 -7
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/** Published purchase shape; optional adapter evidence stays for compatibility. */
|
|
2
|
+
export interface PurchaseFlowPurchase {
|
|
3
|
+
id: string;
|
|
4
|
+
productId: string;
|
|
5
|
+
purchaseState: string;
|
|
6
|
+
purchaseToken?: string | null;
|
|
7
|
+
store: string;
|
|
8
|
+
storeId?: string | null;
|
|
9
|
+
ids?: string[] | null;
|
|
10
|
+
quantity?: number;
|
|
11
|
+
isAcknowledgedAndroid?: boolean | null;
|
|
12
|
+
/**
|
|
13
|
+
* A requested plan change that has not applied yet: Google Play waits for
|
|
14
|
+
* its payment, Amazon applies it at the next renewal.
|
|
15
|
+
*/
|
|
16
|
+
pendingPurchaseUpdateAndroid?: {
|
|
17
|
+
products: string[];
|
|
18
|
+
} | null;
|
|
19
|
+
/** Apple's `Sandbox` or `Production`, which a confirmer matches against its verdict. */
|
|
20
|
+
environmentIOS?: string | null;
|
|
21
|
+
/** The Amazon user the receipt belongs to, which Amazon RVS checks. */
|
|
22
|
+
userIdAmazon?: string | null;
|
|
23
|
+
revocationDateIOS?: number | null;
|
|
24
|
+
isUpgradedIOS?: boolean | null;
|
|
25
|
+
expirationDateIOS?: number | null;
|
|
26
|
+
}
|
|
27
|
+
/** Body the app sends its backend, which takes the user from its own session. */
|
|
28
|
+
export interface PurchaseConfirmationRequest {
|
|
29
|
+
store: "apple" | "google";
|
|
30
|
+
/** Apple JWS or Google Play purchase token, as the store issued it. */
|
|
31
|
+
purchaseToken: string;
|
|
32
|
+
/** The product the app expected, to compare with the store's answer. */
|
|
33
|
+
productId: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A confirmer's verdict on one purchase. Only `entitled` grants access;
|
|
37
|
+
* `verified` and `linked` mean the purchase is valid but access is not granted
|
|
38
|
+
* yet. `ownership_conflict` sets `alreadyGranted` when another account already
|
|
39
|
+
* got access, which lets the app finish it. `invalid` and
|
|
40
|
+
* `test_account_restricted` are settled rejections: return
|
|
41
|
+
* `verification_delayed` for any answer that may still change.
|
|
42
|
+
*/
|
|
43
|
+
export type PurchaseConfirmation = {
|
|
44
|
+
status: "store_pending";
|
|
45
|
+
} | {
|
|
46
|
+
status: "verification_delayed";
|
|
47
|
+
retryAfterMs: number;
|
|
48
|
+
} | {
|
|
49
|
+
status: "ownership_conflict";
|
|
50
|
+
alreadyGranted: boolean;
|
|
51
|
+
} | {
|
|
52
|
+
status: "test_account_restricted";
|
|
53
|
+
} | {
|
|
54
|
+
status: "invalid";
|
|
55
|
+
reason?: string;
|
|
56
|
+
} | {
|
|
57
|
+
status: "verified";
|
|
58
|
+
retryAfterMs?: number;
|
|
59
|
+
} | {
|
|
60
|
+
status: "linked";
|
|
61
|
+
retryAfterMs?: number;
|
|
62
|
+
} | {
|
|
63
|
+
status: "entitled";
|
|
64
|
+
alreadyGranted: boolean;
|
|
65
|
+
};
|
|
66
|
+
type Finishable = "entitled" | "ownership_conflict" | "test_account_restricted";
|
|
67
|
+
/**
|
|
68
|
+
* Where a purchase stands after the flow ran. `finishError` means finishing
|
|
69
|
+
* failed and recovery retries it; an `entitled` status still grants access.
|
|
70
|
+
* `changePending` marks an `entitled` purchase whose requested upgrade,
|
|
71
|
+
* downgrade, or prepaid top-up has not applied yet (Google Play waits for its
|
|
72
|
+
* payment, Amazon applies it at the next renewal): access stays on the current
|
|
73
|
+
* plan. `recovered` marks an `invalid` purchase recovery found, not one the
|
|
74
|
+
* user just bought.
|
|
75
|
+
*/
|
|
76
|
+
export type PurchaseFlowStatus = Exclude<PurchaseConfirmation, {
|
|
77
|
+
status: Finishable | "invalid";
|
|
78
|
+
}> | (Extract<PurchaseConfirmation, {
|
|
79
|
+
status: "entitled";
|
|
80
|
+
}> & {
|
|
81
|
+
finishError?: unknown;
|
|
82
|
+
changePending?: true;
|
|
83
|
+
}) | (Extract<PurchaseConfirmation, {
|
|
84
|
+
status: "ownership_conflict" | "test_account_restricted";
|
|
85
|
+
}> & {
|
|
86
|
+
finishError?: unknown;
|
|
87
|
+
}) | (Extract<PurchaseConfirmation, {
|
|
88
|
+
status: "invalid";
|
|
89
|
+
}> & {
|
|
90
|
+
finishError?: unknown;
|
|
91
|
+
recovered?: true;
|
|
92
|
+
}) | {
|
|
93
|
+
status: "failed";
|
|
94
|
+
error: unknown;
|
|
95
|
+
};
|
|
96
|
+
export interface PurchaseFlowOutcome<P extends PurchaseFlowPurchase> {
|
|
97
|
+
purchase: P;
|
|
98
|
+
status: PurchaseFlowStatus;
|
|
99
|
+
}
|
|
100
|
+
export interface PurchaseFlowOptions<P extends PurchaseFlowPurchase> {
|
|
101
|
+
/**
|
|
102
|
+
* Confirms and grants access before returning `entitled`; the flow finishes
|
|
103
|
+
* the purchase immediately after. Throws or timeouts leave it unfinished
|
|
104
|
+
* for recovery. An app backend or any verification service can answer here.
|
|
105
|
+
*/
|
|
106
|
+
confirmWithBackend: (purchase: P, context: {
|
|
107
|
+
isConsumable: boolean;
|
|
108
|
+
}) => Promise<PurchaseConfirmation>;
|
|
109
|
+
/**
|
|
110
|
+
* Milliseconds `confirmWithBackend` may take before the purchase ends as
|
|
111
|
+
* `failed`, so a hung call cannot hold it for the session. Default 30000.
|
|
112
|
+
*/
|
|
113
|
+
confirmTimeoutMs?: number;
|
|
114
|
+
finishTransaction: (args: {
|
|
115
|
+
purchase: P;
|
|
116
|
+
isConsumable: boolean;
|
|
117
|
+
}) => Promise<unknown>;
|
|
118
|
+
/**
|
|
119
|
+
* From the app's product config. On Android a wrong answer consumes a
|
|
120
|
+
* non-consumable or blocks rebuying a consumable.
|
|
121
|
+
*/
|
|
122
|
+
isConsumable: (productId: string) => boolean;
|
|
123
|
+
getAvailablePurchases: () => Promise<P[]>;
|
|
124
|
+
/**
|
|
125
|
+
* The SDK's `getPendingTransactionsIOS` on iOS, `undefined` elsewhere: off
|
|
126
|
+
* iOS an SDK may answer `[]`, which would hide unacknowledged Android
|
|
127
|
+
* purchases.
|
|
128
|
+
* Recovery reads unfinished StoreKit transactions, consumables included,
|
|
129
|
+
* from it. If it throws, recovery confirms every Apple purchase
|
|
130
|
+
* `getAvailablePurchases` lists instead.
|
|
131
|
+
*/
|
|
132
|
+
getPendingTransactionsIOS: (() => Promise<P[]>) | undefined;
|
|
133
|
+
/**
|
|
134
|
+
* Registers for the store's purchase deliveries; the flow processes each one
|
|
135
|
+
* until `dispose`. SDKs pass their purchase listener.
|
|
136
|
+
*/
|
|
137
|
+
listenForPurchases?: (onPurchase: (purchase: P) => void) => {
|
|
138
|
+
remove: () => void;
|
|
139
|
+
};
|
|
140
|
+
/**
|
|
141
|
+
* Whether the user's own request produced a delivered purchase. Only then
|
|
142
|
+
* may an `invalid` delivery offer buying again; without this, no delivery
|
|
143
|
+
* the flow listened for does.
|
|
144
|
+
*/
|
|
145
|
+
wasRequested?: (purchase: P) => boolean;
|
|
146
|
+
}
|
|
147
|
+
export interface RecoverPurchasesOptions {
|
|
148
|
+
/** Also re-confirm purchases that were already finished, for a restore button. */
|
|
149
|
+
includeFinished?: boolean;
|
|
150
|
+
}
|
|
151
|
+
export interface PurchaseFlow<P extends PurchaseFlowPurchase> {
|
|
152
|
+
/**
|
|
153
|
+
* Confirms one purchase the user just bought. Finishes it once access is
|
|
154
|
+
* granted to this or another account, and a settled rejection on iOS only:
|
|
155
|
+
* Google Play refunds a rejected purchase left unacknowledged, while iOS
|
|
156
|
+
* would redeliver it forever.
|
|
157
|
+
*/
|
|
158
|
+
processPurchase: (purchase: P) => Promise<PurchaseFlowStatus>;
|
|
159
|
+
/**
|
|
160
|
+
* Runs unfinished purchases (or every owned one) through the flow, one at a
|
|
161
|
+
* time; a call made while a pass runs shares it. Throws if it meets an
|
|
162
|
+
* Apple purchase without `getPendingTransactionsIOS`.
|
|
163
|
+
*/
|
|
164
|
+
recoverPurchases: (options?: RecoverPurchasesOptions) => Promise<PurchaseFlowOutcome<P>[]>;
|
|
165
|
+
/**
|
|
166
|
+
* Calls `listener` with every outcome: once per confirmation, however many
|
|
167
|
+
* deliveries shared it, and once per delivery of an already settled
|
|
168
|
+
* purchase. Returns the function that unsubscribes it.
|
|
169
|
+
*/
|
|
170
|
+
subscribe: (listener: (outcome: PurchaseFlowOutcome<P>) => void) => () => void;
|
|
171
|
+
/**
|
|
172
|
+
* Stops listening and publishing, and stops a recovery pass from confirming
|
|
173
|
+
* anything more; confirmations already running still finish. Call it when
|
|
174
|
+
* the signed-in account changes, then create the next account's flow.
|
|
175
|
+
*/
|
|
176
|
+
dispose: () => void;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* How far a store's purchase time may trail the moment the app asked for it
|
|
180
|
+
* and still count as that request: device clocks run ahead. A redelivered
|
|
181
|
+
* receipt is far older.
|
|
182
|
+
*/
|
|
183
|
+
export declare const PURCHASE_REQUEST_CLOCK_SKEW_MS = 600000;
|
|
184
|
+
/**
|
|
185
|
+
* Single-product, single-unit purchases only. Create one flow per
|
|
186
|
+
* authenticated app account. Capture that session in confirmWithBackend and
|
|
187
|
+
* dispose the flow after switching accounts.
|
|
188
|
+
*/
|
|
189
|
+
export declare function createPurchaseFlow<P extends PurchaseFlowPurchase>(options: PurchaseFlowOptions<P>): PurchaseFlow<P>;
|
|
190
|
+
/** Builds the backend request body; throws for a purchase without Apple or Google evidence. */
|
|
191
|
+
export declare function toPurchaseConfirmationRequest(purchase: PurchaseFlowPurchase): PurchaseConfirmationRequest;
|
|
192
|
+
export type PurchaseFlowGuidanceKey = "payment_pending" | "change_pending" | "verification_delayed" | "owned_by_another_account" | "test_purchase_not_accepted" | "purchase_not_valid" | "access_pending" | "access_granted" | "try_again_later";
|
|
193
|
+
/** Neutral guidance an app maps to its own copy. */
|
|
194
|
+
export interface PurchaseFlowGuidance {
|
|
195
|
+
key: PurchaseFlowGuidanceKey;
|
|
196
|
+
/**
|
|
197
|
+
* True only for an `invalid` purchase the user just made. False whenever the
|
|
198
|
+
* user may already have paid: never ask them to buy again.
|
|
199
|
+
*/
|
|
200
|
+
offerPurchase: boolean;
|
|
201
|
+
/** Earliest time to run the purchase through the flow again. */
|
|
202
|
+
retryAfterMs?: number;
|
|
203
|
+
}
|
|
204
|
+
export declare function describePurchaseFlowStatus(status: PurchaseFlowStatus): PurchaseFlowGuidance;
|
|
205
|
+
export {};
|
|
206
|
+
//# sourceMappingURL=purchase-flow-core.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"purchase-flow-core.d.ts","sourceRoot":"","sources":["../src/purchase-flow-core.ts"],"names":[],"mappings":"AAQA,mFAAmF;AACnF,MAAM,WAAW,oBAAoB;IACnC,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,qBAAqB,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IACvC;;;OAGG;IACH,4BAA4B,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,EAAE,CAAA;KAAE,GAAG,IAAI,CAAC;IAC7D,wFAAwF;IACxF,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,uEAAuE;IACvE,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,aAAa,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACnC;AAED,iFAAiF;AACjF,MAAM,WAAW,2BAA2B;IAC1C,KAAK,EAAE,OAAO,GAAG,QAAQ,CAAC;IAC1B,uEAAuE;IACvE,aAAa,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;GAOG;AACH,MAAM,MA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shared by every OpenIAP SDK. A confirmer (the app's backend,
|
|
3
|
+
// IAPKit, or any other verification service) confirms each purchase; this
|
|
4
|
+
// module decides when the app may finish a transaction, and makes no network
|
|
5
|
+
// calls of its own. Verification services live in separate adapters.
|
|
6
|
+
// Ports in other languages run purchase-flow.vectors.json.
|
|
7
|
+
// Guide: https://openiap.dev/docs/features/validation
|
|
8
|
+
/**
|
|
9
|
+
* How far a store's purchase time may trail the moment the app asked for it
|
|
10
|
+
* and still count as that request: device clocks run ahead. A redelivered
|
|
11
|
+
* receipt is far older.
|
|
12
|
+
*/
|
|
13
|
+
export const PURCHASE_REQUEST_CLOCK_SKEW_MS = 600_000;
|
|
14
|
+
/**
|
|
15
|
+
* Single-product, single-unit purchases only. Create one flow per
|
|
16
|
+
* authenticated app account. Capture that session in confirmWithBackend and
|
|
17
|
+
* dispose the flow after switching accounts.
|
|
18
|
+
*/
|
|
19
|
+
export function createPurchaseFlow(options) {
|
|
20
|
+
// A listener and a recovery pass can deliver the same transaction at once.
|
|
21
|
+
const runs = new Map();
|
|
22
|
+
// Finished purchases, and rejections the store settles on its own. A
|
|
23
|
+
// recovery pass can hold a store list read before the listener settled one.
|
|
24
|
+
const settled = new Map();
|
|
25
|
+
const recoveries = new Map();
|
|
26
|
+
const listeners = new Set();
|
|
27
|
+
let disposed = false;
|
|
28
|
+
// setTimeout runs a delay past 2^31 - 1 ms, Infinity included, at once.
|
|
29
|
+
const confirmTimeoutMs = Math.min(options.confirmTimeoutMs ?? 30_000, 2_147_483_647);
|
|
30
|
+
const subscription = options.listenForPurchases?.((purchase) => {
|
|
31
|
+
// A pending delivery leaves the mark for the completed one that follows.
|
|
32
|
+
const requested = purchase.purchaseState !== "pending" &&
|
|
33
|
+
(options.wasRequested?.(purchase) ?? false);
|
|
34
|
+
void deliver(purchase, requested);
|
|
35
|
+
});
|
|
36
|
+
function publish(outcome) {
|
|
37
|
+
if (disposed)
|
|
38
|
+
return;
|
|
39
|
+
for (const listener of listeners) {
|
|
40
|
+
try {
|
|
41
|
+
listener(outcome);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// One subscriber's error must not keep the outcome from the others.
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
// Marked per delivery: a shared run may have started from an older copy of
|
|
49
|
+
// the purchase, before Play attached the pending change.
|
|
50
|
+
function forDelivery(purchase, status, requested) {
|
|
51
|
+
if (status.status === "entitled" && purchase.pendingPurchaseUpdateAndroid) {
|
|
52
|
+
return { ...status, changePending: true };
|
|
53
|
+
}
|
|
54
|
+
// An old expired renewal must not ask a subscriber to buy again.
|
|
55
|
+
if (status.status === "invalid" && !requested) {
|
|
56
|
+
return { ...status, recovered: true };
|
|
57
|
+
}
|
|
58
|
+
return status;
|
|
59
|
+
}
|
|
60
|
+
function processPurchase(purchase) {
|
|
61
|
+
return deliver(purchase, true);
|
|
62
|
+
}
|
|
63
|
+
function deliver(purchase, requested, reconfirm = false) {
|
|
64
|
+
const immediate = immediateStatus(purchase, reconfirm);
|
|
65
|
+
if (immediate) {
|
|
66
|
+
const status = forDelivery(purchase, immediate, requested);
|
|
67
|
+
publish({ purchase, status });
|
|
68
|
+
return Promise.resolve(status);
|
|
69
|
+
}
|
|
70
|
+
let run = runs.get(purchase.id);
|
|
71
|
+
if (run) {
|
|
72
|
+
run.latest = purchase;
|
|
73
|
+
run.requested ||= requested;
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
const started = {
|
|
77
|
+
latest: purchase,
|
|
78
|
+
requested,
|
|
79
|
+
task: confirmAndFinish(purchase).then((status) => {
|
|
80
|
+
runs.delete(purchase.id);
|
|
81
|
+
if (isSettled(status))
|
|
82
|
+
settled.set(purchase.id, status);
|
|
83
|
+
publish({
|
|
84
|
+
purchase: started.latest,
|
|
85
|
+
status: forDelivery(started.latest, status, started.requested),
|
|
86
|
+
});
|
|
87
|
+
return status;
|
|
88
|
+
}),
|
|
89
|
+
};
|
|
90
|
+
runs.set(purchase.id, started);
|
|
91
|
+
run = started;
|
|
92
|
+
}
|
|
93
|
+
return run.task.then((status) => forDelivery(purchase, status, requested));
|
|
94
|
+
}
|
|
95
|
+
function immediateStatus(purchase, reconfirm) {
|
|
96
|
+
try {
|
|
97
|
+
assertSupportedPurchase(purchase);
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
return { status: "failed", error };
|
|
101
|
+
}
|
|
102
|
+
// Payment is not complete; the store delivers the purchase again once it is.
|
|
103
|
+
if (purchase.purchaseState === "pending")
|
|
104
|
+
return { status: "store_pending" };
|
|
105
|
+
return reconfirm || runs.has(purchase.id)
|
|
106
|
+
? undefined
|
|
107
|
+
: settled.get(purchase.id);
|
|
108
|
+
}
|
|
109
|
+
async function confirmAndFinish(purchase) {
|
|
110
|
+
let confirmation;
|
|
111
|
+
let isConsumable;
|
|
112
|
+
let timer;
|
|
113
|
+
try {
|
|
114
|
+
// Read once: finishing must consume exactly what confirmation granted.
|
|
115
|
+
isConsumable = options.isConsumable(purchase.productId);
|
|
116
|
+
const timeout = new Promise((_, reject) => {
|
|
117
|
+
timer = setTimeout(() => {
|
|
118
|
+
reject(new Error(`confirmWithBackend did not answer within ${confirmTimeoutMs} ms`));
|
|
119
|
+
}, confirmTimeoutMs);
|
|
120
|
+
});
|
|
121
|
+
confirmation = readConfirmation(await Promise.race([
|
|
122
|
+
options.confirmWithBackend(purchase, { isConsumable }),
|
|
123
|
+
timeout,
|
|
124
|
+
]));
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
return { status: "failed", error };
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
}
|
|
132
|
+
if (!confirmation) {
|
|
133
|
+
return {
|
|
134
|
+
status: "failed",
|
|
135
|
+
error: new Error("Unrecognized purchase confirmation from the backend"),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
// Finishing settles a purchase for good, so only a settled verdict does.
|
|
139
|
+
switch (confirmation.status) {
|
|
140
|
+
case "entitled":
|
|
141
|
+
return await finish(purchase, isConsumable, confirmation);
|
|
142
|
+
case "ownership_conflict":
|
|
143
|
+
return confirmation.alreadyGranted
|
|
144
|
+
? await finish(purchase, isConsumable, confirmation)
|
|
145
|
+
: confirmation;
|
|
146
|
+
case "invalid":
|
|
147
|
+
case "test_account_restricted":
|
|
148
|
+
return purchase.store === "apple"
|
|
149
|
+
? await finish(purchase, isConsumable, confirmation)
|
|
150
|
+
: confirmation;
|
|
151
|
+
default:
|
|
152
|
+
return confirmation;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
async function finish(purchase, isConsumable, confirmation) {
|
|
156
|
+
try {
|
|
157
|
+
// Play keeps an acknowledged purchase finished; a restore need not redo it.
|
|
158
|
+
if (purchase.isAcknowledgedAndroid === true && !isConsumable) {
|
|
159
|
+
return confirmation;
|
|
160
|
+
}
|
|
161
|
+
await options.finishTransaction({ purchase, isConsumable });
|
|
162
|
+
return confirmation;
|
|
163
|
+
}
|
|
164
|
+
catch (finishError) {
|
|
165
|
+
return { ...confirmation, finishError };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function recoverPurchases(recoverOptions = {}) {
|
|
169
|
+
const includeFinished = recoverOptions.includeFinished ?? false;
|
|
170
|
+
let pass = recoveries.get(includeFinished);
|
|
171
|
+
if (!pass) {
|
|
172
|
+
pass = recover(includeFinished).finally(() => {
|
|
173
|
+
recoveries.delete(includeFinished);
|
|
174
|
+
});
|
|
175
|
+
recoveries.set(includeFinished, pass);
|
|
176
|
+
}
|
|
177
|
+
return pass;
|
|
178
|
+
}
|
|
179
|
+
async function recover(includeFinished) {
|
|
180
|
+
const { getPendingTransactionsIOS } = options;
|
|
181
|
+
// iOS lists unfinished transactions directly; other stores list owned
|
|
182
|
+
// purchases, and isUnfinished picks the ones still to settle.
|
|
183
|
+
let pendingIOS;
|
|
184
|
+
let pendingIOSFailed = false;
|
|
185
|
+
try {
|
|
186
|
+
pendingIOS = await getPendingTransactionsIOS?.();
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
// One unverified transaction fails the whole list. Re-confirming a
|
|
190
|
+
// finished purchase is safe, so every owned Apple purchase stands in.
|
|
191
|
+
pendingIOSFailed = true;
|
|
192
|
+
}
|
|
193
|
+
const available = includeFinished || !pendingIOS
|
|
194
|
+
? await options.getAvailablePurchases()
|
|
195
|
+
: [];
|
|
196
|
+
if (!getPendingTransactionsIOS &&
|
|
197
|
+
available.some((purchase) => purchase.store === "apple")) {
|
|
198
|
+
throw new Error("recoverPurchases needs getPendingTransactionsIOS on iOS to find unfinished transactions");
|
|
199
|
+
}
|
|
200
|
+
const unfinished = available.filter((purchase) => includeFinished ||
|
|
201
|
+
(purchase.store === "apple"
|
|
202
|
+
? pendingIOSFailed
|
|
203
|
+
: isUnfinished(purchase)));
|
|
204
|
+
const purchases = new Map();
|
|
205
|
+
for (const purchase of [...(pendingIOS ?? []), ...unfinished]) {
|
|
206
|
+
if (!purchases.has(purchase.id))
|
|
207
|
+
purchases.set(purchase.id, purchase);
|
|
208
|
+
}
|
|
209
|
+
const outcomes = [];
|
|
210
|
+
for (const purchase of purchases.values()) {
|
|
211
|
+
// The next account's flow confirms the rest with its own session.
|
|
212
|
+
if (disposed)
|
|
213
|
+
break;
|
|
214
|
+
if (!includeFinished && settled.has(purchase.id))
|
|
215
|
+
continue;
|
|
216
|
+
const status = await deliver(purchase, false, includeFinished);
|
|
217
|
+
outcomes.push({ purchase, status });
|
|
218
|
+
}
|
|
219
|
+
return outcomes;
|
|
220
|
+
}
|
|
221
|
+
function isUnfinished(purchase) {
|
|
222
|
+
// Amazon and most community stores report no acknowledgment, and Amazon
|
|
223
|
+
// approves a Kids purchase later; a listed consumable is unconsumed.
|
|
224
|
+
return (purchase.isAcknowledgedAndroid !== true ||
|
|
225
|
+
options.isConsumable(purchase.productId));
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
processPurchase,
|
|
229
|
+
recoverPurchases,
|
|
230
|
+
subscribe(listener) {
|
|
231
|
+
const entry = (outcome) => listener(outcome);
|
|
232
|
+
listeners.add(entry);
|
|
233
|
+
return () => {
|
|
234
|
+
listeners.delete(entry);
|
|
235
|
+
};
|
|
236
|
+
},
|
|
237
|
+
dispose() {
|
|
238
|
+
disposed = true;
|
|
239
|
+
listeners.clear();
|
|
240
|
+
subscription?.remove();
|
|
241
|
+
},
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
// A settled purchase is finished, or rejected for good where the store
|
|
245
|
+
// settles it, so the same delivery need not be confirmed again.
|
|
246
|
+
function isSettled(status) {
|
|
247
|
+
switch (status.status) {
|
|
248
|
+
case "entitled":
|
|
249
|
+
case "invalid":
|
|
250
|
+
case "test_account_restricted":
|
|
251
|
+
return status.finishError === undefined;
|
|
252
|
+
case "ownership_conflict":
|
|
253
|
+
return status.alreadyGranted && status.finishError === undefined;
|
|
254
|
+
default:
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/** Builds the backend request body; throws for a purchase without Apple or Google evidence. */
|
|
259
|
+
export function toPurchaseConfirmationRequest(purchase) {
|
|
260
|
+
const { store, purchaseToken, productId } = purchase;
|
|
261
|
+
if ((store !== "apple" && store !== "google") || !purchaseToken) {
|
|
262
|
+
throw new Error(`Purchase ${productId} has no Apple or Google purchase token to confirm`);
|
|
263
|
+
}
|
|
264
|
+
assertSupportedPurchase(purchase);
|
|
265
|
+
return { store, purchaseToken, productId };
|
|
266
|
+
}
|
|
267
|
+
function assertSupportedPurchase(purchase) {
|
|
268
|
+
if (purchase.quantity !== undefined && purchase.quantity !== 1) {
|
|
269
|
+
throw new Error("Purchase flow supports only single-unit purchases");
|
|
270
|
+
}
|
|
271
|
+
if (new Set(purchase.ids ?? []).size > 1) {
|
|
272
|
+
throw new Error("Purchase flow cannot finish a multi-product purchase before every product is granted");
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
export function describePurchaseFlowStatus(status) {
|
|
276
|
+
switch (status.status) {
|
|
277
|
+
case "store_pending":
|
|
278
|
+
return { key: "payment_pending", offerPurchase: false };
|
|
279
|
+
case "verification_delayed":
|
|
280
|
+
return {
|
|
281
|
+
key: "verification_delayed",
|
|
282
|
+
offerPurchase: false,
|
|
283
|
+
retryAfterMs: status.retryAfterMs,
|
|
284
|
+
};
|
|
285
|
+
case "ownership_conflict":
|
|
286
|
+
return { key: "owned_by_another_account", offerPurchase: false };
|
|
287
|
+
case "test_account_restricted":
|
|
288
|
+
return { key: "test_purchase_not_accepted", offerPurchase: false };
|
|
289
|
+
case "invalid":
|
|
290
|
+
return {
|
|
291
|
+
key: "purchase_not_valid",
|
|
292
|
+
offerPurchase: status.recovered !== true,
|
|
293
|
+
};
|
|
294
|
+
case "verified":
|
|
295
|
+
case "linked":
|
|
296
|
+
return status.retryAfterMs === undefined
|
|
297
|
+
? { key: "access_pending", offerPurchase: false }
|
|
298
|
+
: {
|
|
299
|
+
key: "access_pending",
|
|
300
|
+
offerPurchase: false,
|
|
301
|
+
retryAfterMs: status.retryAfterMs,
|
|
302
|
+
};
|
|
303
|
+
case "entitled":
|
|
304
|
+
return {
|
|
305
|
+
key: status.changePending ? "change_pending" : "access_granted",
|
|
306
|
+
offerPurchase: false,
|
|
307
|
+
};
|
|
308
|
+
case "failed":
|
|
309
|
+
return { key: "try_again_later", offerPurchase: false };
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
// Backend JSON is untrusted: anything off-contract becomes `failed`, so a
|
|
313
|
+
// malformed body can never finish a transaction.
|
|
314
|
+
function readConfirmation(value) {
|
|
315
|
+
if (typeof value !== "object" || value === null)
|
|
316
|
+
return null;
|
|
317
|
+
const { status, retryAfterMs, alreadyGranted, reason } = value;
|
|
318
|
+
const retry = typeof retryAfterMs === "number" &&
|
|
319
|
+
Number.isFinite(retryAfterMs) &&
|
|
320
|
+
retryAfterMs >= 0
|
|
321
|
+
? retryAfterMs
|
|
322
|
+
: undefined;
|
|
323
|
+
switch (status) {
|
|
324
|
+
case "store_pending":
|
|
325
|
+
case "test_account_restricted":
|
|
326
|
+
return { status };
|
|
327
|
+
case "invalid":
|
|
328
|
+
return typeof reason === "string" ? { status, reason } : { status };
|
|
329
|
+
case "verification_delayed":
|
|
330
|
+
return retry === undefined ? null : { status, retryAfterMs: retry };
|
|
331
|
+
case "verified":
|
|
332
|
+
case "linked":
|
|
333
|
+
return retry === undefined ? { status } : { status, retryAfterMs: retry };
|
|
334
|
+
case "ownership_conflict":
|
|
335
|
+
case "entitled":
|
|
336
|
+
return typeof alreadyGranted === "boolean"
|
|
337
|
+
? { status, alreadyGranted }
|
|
338
|
+
: null;
|
|
339
|
+
default:
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
//# sourceMappingURL=purchase-flow-core.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"purchase-flow-core.js","sourceRoot":"","sources":["../src/purchase-flow-core.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,6EAA6E;AAC7E,0EAA0E;AAC1E,6EAA6E;AAC7E,qEAAqE;AACrE,2DAA2D;AAC3D,sDAAsD;AA8KtD;;;;GAIG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,OAAO,CAAC;AAQtD;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAA+B;IAE/B,2EAA2E;IAC3E,MAAM,IAAI,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC/C,qEAAqE;IACrE,4EAA4E;IAC5E,MAAM,OAAO,GAAG,IAAI,GAAG,EAA8B,CAAC;IACtD,MAAM,UAAU,GAAG,IAAI,GAAG,EAA8C,CAAC;IACzE,MAAM,SAAS,GAAG,IAAI,GAAG,EAA6C,CAAC;IACvE,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,wEAAwE;IACxE,MAAM,gBAAgB,GAAG,IAAI,CAAC,GAAG,CAC/B,OAAO,CAAC,gBAAgB,IAAI,MAAM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AU;YACb,OAAO,OAAO,cAAc,KAAK,SAAS;gBACxC,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,EAAE;gBAC5B,CAAC,CAAC,IAAI,CAAC;QACX;YACE,OAAO,IAAI,CAAC;IAChB,CAAC;AACH,CAAC","sourcesContent":["// Internal module; apps use the SDK root or Client Protocol /purchase-flow.\n// Purchase flow shared by every OpenIAP SDK. A confirmer (the app's backend,\n// IAPKit, or any other verification service) confirms each purchase; this\n// module decides when the app may finish a transaction, and makes no network\n// calls of its own. Verification services live in separate adapters.\n// Ports in other languages run purchase-flow.vectors.json.\n// Guide: https://openiap.dev/docs/features/validation\n\n/** Published purchase shape; optional adapter evidence stays for compatibility. */\nexport interface PurchaseFlowPurchase {\n id: string;\n productId: string;\n purchaseState: string;\n purchaseToken?: string | null;\n store: string;\n storeId?: string | null;\n ids?: string[] | null;\n quantity?: number;\n isAcknowledgedAndroid?: boolean | null;\n /**\n * A requested plan change that has not applied yet: Google Play waits for\n * its payment, Amazon applies it at the next renewal.\n */\n pendingPurchaseUpdateAndroid?: { products: string[] } | null;\n /** Apple's `Sandbox` or `Production`, which a confirmer matches against its verdict. */\n environmentIOS?: string | null;\n /** The Amazon user the receipt belongs to, which Amazon RVS checks. */\n userIdAmazon?: string | null;\n revocationDateIOS?: number | null;\n isUpgradedIOS?: boolean | null;\n expirationDateIOS?: number | null;\n}\n\n/** Body the app sends its backend, which takes the user from its own session. */\nexport interface PurchaseConfirmationRequest {\n store: \"apple\" | \"google\";\n /** Apple JWS or Google Play purchase token, as the store issued it. */\n purchaseToken: string;\n /** The product the app expected, to compare with the store's answer. */\n productId: string;\n}\n\n/**\n * A confirmer's verdict on one purchase. Only `entitled` grants access;\n * `verified` and `linked` mean the purchase is valid but access is not granted\n * yet. `ownership_conflict` sets `alreadyGranted` when another account already\n * got access, which lets the app finish it. `invalid` and\n * `test_account_restricted` are settled rejections: return\n * `verification_delayed` for any answer that may still change.\n */\nexport type PurchaseConfirmation =\n | { status: \"store_pending\" }\n | { status: \"verification_delayed\"; retryAfterMs: number }\n | { status: \"ownership_conflict\"; alreadyGranted: boolean }\n | { status: \"test_account_restricted\" }\n | { status: \"invalid\"; reason?: string }\n | { status: \"verified\"; retryAfterMs?: number }\n | { status: \"linked\"; retryAfterMs?: number }\n | { status: \"entitled\"; alreadyGranted: boolean };\n\ntype Finishable = \"entitled\" | \"ownership_conflict\" | \"test_account_restricted\";\n\n/**\n * Where a purchase stands after the flow ran. `finishError` means finishing\n * failed and recovery retries it; an `entitled` status still grants access.\n * `changePending` marks an `entitled` purchase whose requested upgrade,\n * downgrade, or prepaid top-up has not applied yet (Google Play waits for its\n * payment, Amazon applies it at the next renewal): access stays on the current\n * plan. `recovered` marks an `invalid` purchase recovery found, not one the\n * user just bought.\n */\nexport type PurchaseFlowStatus =\n | Exclude<PurchaseConfirmation, { status: Finishable | \"invalid\" }>\n | (Extract<PurchaseConfirmation, { status: \"entitled\" }> & {\n finishError?: unknown;\n changePending?: true;\n })\n | (Extract<\n PurchaseConfirmation,\n { status: \"ownership_conflict\" | \"test_account_restricted\" }\n > & {\n finishError?: unknown;\n })\n | (Extract<PurchaseConfirmation, { status: \"invalid\" }> & {\n finishError?: unknown;\n recovered?: true;\n })\n | { status: \"failed\"; error: unknown };\n\nexport interface PurchaseFlowOutcome<P extends PurchaseFlowPurchase> {\n purchase: P;\n status: PurchaseFlowStatus;\n}\n\nexport interface PurchaseFlowOptions<P extends PurchaseFlowPurchase> {\n /**\n * Confirms and grants access before returning `entitled`; the flow finishes\n * the purchase immediately after. Throws or timeouts leave it unfinished\n * for recovery. An app backend or any verification service can answer here.\n */\n confirmWithBackend: (\n purchase: P,\n context: { isConsumable: boolean },\n ) => Promise<PurchaseConfirmation>;\n /**\n * Milliseconds `confirmWithBackend` may take before the purchase ends as\n * `failed`, so a hung call cannot hold it for the session. Default 30000.\n */\n confirmTimeoutMs?: number;\n finishTransaction: (args: {\n purchase: P;\n isConsumable: boolean;\n }) => Promise<unknown>;\n /**\n * From the app's product config. On Android a wrong answer consumes a\n * non-consumable or blocks rebuying a consumable.\n */\n isConsumable: (productId: string) => boolean;\n getAvailablePurchases: () => Promise<P[]>;\n /**\n * The SDK's `getPendingTransactionsIOS` on iOS, `undefined` elsewhere: off\n * iOS an SDK may answer `[]`, which would hide unacknowledged Android\n * purchases.\n * Recovery reads unfinished StoreKit transactions, consumables included,\n * from it. If it throws, recovery confirms every Apple purchase\n * `getAvailablePurchases` lists instead.\n */\n getPendingTransactionsIOS: (() => Promise<P[]>) | undefined;\n /**\n * Registers for the store's purchase deliveries; the flow processes each one\n * until `dispose`. SDKs pass their purchase listener.\n */\n listenForPurchases?: (onPurchase: (purchase: P) => void) => {\n remove: () => void;\n };\n /**\n * Whether the user's own request produced a delivered purchase. Only then\n * may an `invalid` delivery offer buying again; without this, no delivery\n * the flow listened for does.\n */\n wasRequested?: (purchase: P) => boolean;\n}\n\nexport interface RecoverPurchasesOptions {\n /** Also re-confirm purchases that were already finished, for a restore button. */\n includeFinished?: boolean;\n}\n\nexport interface PurchaseFlow<P extends PurchaseFlowPurchase> {\n /**\n * Confirms one purchase the user just bought. Finishes it once access is\n * granted to this or another account, and a settled rejection on iOS only:\n * Google Play refunds a rejected purchase left unacknowledged, while iOS\n * would redeliver it forever.\n */\n processPurchase: (purchase: P) => Promise<PurchaseFlowStatus>;\n /**\n * Runs unfinished purchases (or every owned one) through the flow, one at a\n * time; a call made while a pass runs shares it. Throws if it meets an\n * Apple purchase without `getPendingTransactionsIOS`.\n */\n recoverPurchases: (\n options?: RecoverPurchasesOptions,\n ) => Promise<PurchaseFlowOutcome<P>[]>;\n /**\n * Calls `listener` with every outcome: once per confirmation, however many\n * deliveries shared it, and once per delivery of an already settled\n * purchase. Returns the function that unsubscribes it.\n */\n subscribe: (\n listener: (outcome: PurchaseFlowOutcome<P>) => void,\n ) => () => void;\n /**\n * Stops listening and publishing, and stops a recovery pass from confirming\n * anything more; confirmations already running still finish. Call it when\n * the signed-in account changes, then create the next account's flow.\n */\n dispose: () => void;\n}\n\n/**\n * How far a store's purchase time may trail the moment the app asked for it\n * and still count as that request: device clocks run ahead. A redelivered\n * receipt is far older.\n */\nexport const PURCHASE_REQUEST_CLOCK_SKEW_MS = 600_000;\n\ninterface PurchaseRun<P> {\n task: Promise<PurchaseFlowStatus>;\n latest: P;\n requested: boolean;\n}\n\n/**\n * Single-product, single-unit purchases only. Create one flow per\n * authenticated app account. Capture that session in confirmWithBackend and\n * dispose the flow after switching accounts.\n */\nexport function createPurchaseFlow<P extends PurchaseFlowPurchase>(\n options: PurchaseFlowOptions<P>,\n): PurchaseFlow<P> {\n // A listener and a recovery pass can deliver the same transaction at once.\n const runs = new Map<string, PurchaseRun<P>>();\n // Finished purchases, and rejections the store settles on its own. A\n // recovery pass can hold a store list read before the listener settled one.\n const settled = new Map<string, PurchaseFlowStatus>();\n const recoveries = new Map<boolean, Promise<PurchaseFlowOutcome<P>[]>>();\n const listeners = new Set<(outcome: PurchaseFlowOutcome<P>) => void>();\n let disposed = false;\n // setTimeout runs a delay past 2^31 - 1 ms, Infinity included, at once.\n const confirmTimeoutMs = Math.min(\n options.confirmTimeoutMs ?? 30_000,\n 2_147_483_647,\n );\n const subscription = options.listenForPurchases?.((purchase) => {\n // A pending delivery leaves the mark for the completed one that follows.\n const requested =\n purchase.purchaseState !== \"pending\" &&\n (options.wasRequested?.(purchase) ?? false);\n void deliver(purchase, requested);\n });\n\n function publish(outcome: PurchaseFlowOutcome<P>): void {\n if (disposed) return;\n for (const listener of listeners) {\n try {\n listener(outcome);\n } catch {\n // One subscriber's error must not keep the outcome from the others.\n }\n }\n }\n\n // Marked per delivery: a shared run may have started from an older copy of\n // the purchase, before Play attached the pending change.\n function forDelivery(\n purchase: P,\n status: PurchaseFlowStatus,\n requested: boolean,\n ): PurchaseFlowStatus {\n if (status.status === \"entitled\" && purchase.pendingPurchaseUpdateAndroid) {\n return { ...status, changePending: true };\n }\n // An old expired renewal must not ask a subscriber to buy again.\n if (status.status === \"invalid\" && !requested) {\n return { ...status, recovered: true };\n }\n return status;\n }\n\n function processPurchase(purchase: P): Promise<PurchaseFlowStatus> {\n return deliver(purchase, true);\n }\n\n function deliver(\n purchase: P,\n requested: boolean,\n reconfirm = false,\n ): Promise<PurchaseFlowStatus> {\n const immediate = immediateStatus(purchase, reconfirm);\n if (immediate) {\n const status = forDelivery(purchase, immediate, requested);\n publish({ purchase, status });\n return Promise.resolve(status);\n }\n let run = runs.get(purchase.id);\n if (run) {\n run.latest = purchase;\n run.requested ||= requested;\n } else {\n const started: PurchaseRun<P> = {\n latest: purchase,\n requested,\n task: confirmAndFinish(purchase).then((status) => {\n runs.delete(purchase.id);\n if (isSettled(status)) settled.set(purchase.id, status);\n publish({\n purchase: started.latest,\n status: forDelivery(started.latest, status, started.requested),\n });\n return status;\n }),\n };\n runs.set(purchase.id, started);\n run = started;\n }\n return run.task.then((status) => forDelivery(purchase, status, requested));\n }\n\n function immediateStatus(\n purchase: P,\n reconfirm: boolean,\n ): PurchaseFlowStatus | undefined {\n try {\n assertSupportedPurchase(purchase);\n } catch (error) {\n return { status: \"failed\", error };\n }\n // Payment is not complete; the store delivers the purchase again once it is.\n if (purchase.purchaseState === \"pending\")\n return { status: \"store_pending\" };\n return reconfirm || runs.has(purchase.id)\n ? undefined\n : settled.get(purchase.id);\n }\n\n async function confirmAndFinish(purchase: P): Promise<PurchaseFlowStatus> {\n let confirmation: PurchaseConfirmation | null;\n let isConsumable: boolean;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n // Read once: finishing must consume exactly what confirmation granted.\n isConsumable = options.isConsumable(purchase.productId);\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(\n new Error(\n `confirmWithBackend did not answer within ${confirmTimeoutMs} ms`,\n ),\n );\n }, confirmTimeoutMs);\n });\n confirmation = readConfirmation(\n await Promise.race([\n options.confirmWithBackend(purchase, { isConsumable }),\n timeout,\n ]),\n );\n } catch (error) {\n return { status: \"failed\", error };\n } finally {\n clearTimeout(timer);\n }\n if (!confirmation) {\n return {\n status: \"failed\",\n error: new Error(\"Unrecognized purchase confirmation from the backend\"),\n };\n }\n // Finishing settles a purchase for good, so only a settled verdict does.\n switch (confirmation.status) {\n case \"entitled\":\n return await finish(purchase, isConsumable, confirmation);\n case \"ownership_conflict\":\n return confirmation.alreadyGranted\n ? await finish(purchase, isConsumable, confirmation)\n : confirmation;\n case \"invalid\":\n case \"test_account_restricted\":\n return purchase.store === \"apple\"\n ? await finish(purchase, isConsumable, confirmation)\n : confirmation;\n default:\n return confirmation;\n }\n }\n\n async function finish(\n purchase: P,\n isConsumable: boolean,\n confirmation: Extract<\n PurchaseConfirmation,\n { status: Finishable | \"invalid\" }\n >,\n ): Promise<PurchaseFlowStatus> {\n try {\n // Play keeps an acknowledged purchase finished; a restore need not redo it.\n if (purchase.isAcknowledgedAndroid === true && !isConsumable) {\n return confirmation;\n }\n await options.finishTransaction({ purchase, isConsumable });\n return confirmation;\n } catch (finishError) {\n return { ...confirmation, finishError };\n }\n }\n\n function recoverPurchases(\n recoverOptions: RecoverPurchasesOptions = {},\n ): Promise<PurchaseFlowOutcome<P>[]> {\n const includeFinished = recoverOptions.includeFinished ?? false;\n let pass = recoveries.get(includeFinished);\n if (!pass) {\n pass = recover(includeFinished).finally(() => {\n recoveries.delete(includeFinished);\n });\n recoveries.set(includeFinished, pass);\n }\n return pass;\n }\n\n async function recover(\n includeFinished: boolean,\n ): Promise<PurchaseFlowOutcome<P>[]> {\n const { getPendingTransactionsIOS } = options;\n // iOS lists unfinished transactions directly; other stores list owned\n // purchases, and isUnfinished picks the ones still to settle.\n let pendingIOS: P[] | undefined;\n let pendingIOSFailed = false;\n try {\n pendingIOS = await getPendingTransactionsIOS?.();\n } catch {\n // One unverified transaction fails the whole list. Re-confirming a\n // finished purchase is safe, so every owned Apple purchase stands in.\n pendingIOSFailed = true;\n }\n const available =\n includeFinished || !pendingIOS\n ? await options.getAvailablePurchases()\n : [];\n if (\n !getPendingTransactionsIOS &&\n available.some((purchase) => purchase.store === \"apple\")\n ) {\n throw new Error(\n \"recoverPurchases needs getPendingTransactionsIOS on iOS to find unfinished transactions\",\n );\n }\n const unfinished = available.filter(\n (purchase) =>\n includeFinished ||\n (purchase.store === \"apple\"\n ? pendingIOSFailed\n : isUnfinished(purchase)),\n );\n const purchases = new Map<string, P>();\n for (const purchase of [...(pendingIOS ?? []), ...unfinished]) {\n if (!purchases.has(purchase.id)) purchases.set(purchase.id, purchase);\n }\n const outcomes: PurchaseFlowOutcome<P>[] = [];\n for (const purchase of purchases.values()) {\n // The next account's flow confirms the rest with its own session.\n if (disposed) break;\n if (!includeFinished && settled.has(purchase.id)) continue;\n const status = await deliver(purchase, false, includeFinished);\n outcomes.push({ purchase, status });\n }\n return outcomes;\n }\n\n function isUnfinished(purchase: P): boolean {\n // Amazon and most community stores report no acknowledgment, and Amazon\n // approves a Kids purchase later; a listed consumable is unconsumed.\n return (\n purchase.isAcknowledgedAndroid !== true ||\n options.isConsumable(purchase.productId)\n );\n }\n\n return {\n processPurchase,\n recoverPurchases,\n subscribe(listener) {\n const entry = (outcome: PurchaseFlowOutcome<P>) => listener(outcome);\n listeners.add(entry);\n return () => {\n listeners.delete(entry);\n };\n },\n dispose() {\n disposed = true;\n listeners.clear();\n subscription?.remove();\n },\n };\n}\n\n// A settled purchase is finished, or rejected for good where the store\n// settles it, so the same delivery need not be confirmed again.\nfunction isSettled(status: PurchaseFlowStatus): boolean {\n switch (status.status) {\n case \"entitled\":\n case \"invalid\":\n case \"test_account_restricted\":\n return status.finishError === undefined;\n case \"ownership_conflict\":\n return status.alreadyGranted && status.finishError === undefined;\n default:\n return false;\n }\n}\n\n/** Builds the backend request body; throws for a purchase without Apple or Google evidence. */\nexport function toPurchaseConfirmationRequest(\n purchase: PurchaseFlowPurchase,\n): PurchaseConfirmationRequest {\n const { store, purchaseToken, productId } = purchase;\n if ((store !== \"apple\" && store !== \"google\") || !purchaseToken) {\n throw new Error(\n `Purchase ${productId} has no Apple or Google purchase token to confirm`,\n );\n }\n assertSupportedPurchase(purchase);\n return { store, purchaseToken, productId };\n}\n\nfunction assertSupportedPurchase(purchase: PurchaseFlowPurchase): void {\n if (purchase.quantity !== undefined && purchase.quantity !== 1) {\n throw new Error(\"Purchase flow supports only single-unit purchases\");\n }\n if (new Set(purchase.ids ?? []).size > 1) {\n throw new Error(\n \"Purchase flow cannot finish a multi-product purchase before every product is granted\",\n );\n }\n}\n\nexport type PurchaseFlowGuidanceKey =\n | \"payment_pending\"\n | \"change_pending\"\n | \"verification_delayed\"\n | \"owned_by_another_account\"\n | \"test_purchase_not_accepted\"\n | \"purchase_not_valid\"\n | \"access_pending\"\n | \"access_granted\"\n | \"try_again_later\";\n\n/** Neutral guidance an app maps to its own copy. */\nexport interface PurchaseFlowGuidance {\n key: PurchaseFlowGuidanceKey;\n /**\n * True only for an `invalid` purchase the user just made. False whenever the\n * user may already have paid: never ask them to buy again.\n */\n offerPurchase: boolean;\n /** Earliest time to run the purchase through the flow again. */\n retryAfterMs?: number;\n}\n\nexport function describePurchaseFlowStatus(\n status: PurchaseFlowStatus,\n): PurchaseFlowGuidance {\n switch (status.status) {\n case \"store_pending\":\n return { key: \"payment_pending\", offerPurchase: false };\n case \"verification_delayed\":\n return {\n key: \"verification_delayed\",\n offerPurchase: false,\n retryAfterMs: status.retryAfterMs,\n };\n case \"ownership_conflict\":\n return { key: \"owned_by_another_account\", offerPurchase: false };\n case \"test_account_restricted\":\n return { key: \"test_purchase_not_accepted\", offerPurchase: false };\n case \"invalid\":\n return {\n key: \"purchase_not_valid\",\n offerPurchase: status.recovered !== true,\n };\n case \"verified\":\n case \"linked\":\n return status.retryAfterMs === undefined\n ? { key: \"access_pending\", offerPurchase: false }\n : {\n key: \"access_pending\",\n offerPurchase: false,\n retryAfterMs: status.retryAfterMs,\n };\n case \"entitled\":\n return {\n key: status.changePending ? \"change_pending\" : \"access_granted\",\n offerPurchase: false,\n };\n case \"failed\":\n return { key: \"try_again_later\", offerPurchase: false };\n }\n}\n\n// Backend JSON is untrusted: anything off-contract becomes `failed`, so a\n// malformed body can never finish a transaction.\nfunction readConfirmation(value: unknown): PurchaseConfirmation | null {\n if (typeof value !== \"object\" || value === null) return null;\n const { status, retryAfterMs, alreadyGranted, reason } = value as Record<\n string,\n unknown\n >;\n const retry =\n typeof retryAfterMs === \"number\" &&\n Number.isFinite(retryAfterMs) &&\n retryAfterMs >= 0\n ? retryAfterMs\n : undefined;\n switch (status) {\n case \"store_pending\":\n case \"test_account_restricted\":\n return { status };\n case \"invalid\":\n return typeof reason === \"string\" ? { status, reason } : { status };\n case \"verification_delayed\":\n return retry === undefined ? null : { status, retryAfterMs: retry };\n case \"verified\":\n case \"linked\":\n return retry === undefined ? { status } : { status, retryAfterMs: retry };\n case \"ownership_conflict\":\n case \"entitled\":\n return typeof alreadyGranted === \"boolean\"\n ? { status, alreadyGranted }\n : null;\n default:\n return null;\n }\n}\n"]}
|