@tenthbilling/expo 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +41 -2
- package/android/build.gradle +23 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/com/tenthbilling/expo/TenthStoreModule.kt +669 -0
- package/app.plugin.js +3 -0
- package/dist/api/client.d.ts +107 -0
- package/dist/api/client.js +139 -0
- package/dist/api/types.d.ts +17 -0
- package/dist/api/types.js +1 -0
- package/dist/cache.d.ts +23 -0
- package/dist/cache.js +40 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +42 -0
- package/dist/generated/openapi.d.ts +3208 -0
- package/dist/generated/openapi.js +1 -0
- package/dist/identity.d.ts +35 -0
- package/dist/identity.js +92 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +10 -0
- package/dist/keys.d.ts +8 -0
- package/dist/keys.js +14 -0
- package/dist/native/module.d.ts +12 -0
- package/dist/native/module.js +14 -0
- package/dist/native/spec.d.ts +166 -0
- package/dist/native/spec.js +1 -0
- package/dist/products.d.ts +32 -0
- package/dist/products.js +213 -0
- package/dist/react/Paywall.d.ts +28 -0
- package/dist/react/Paywall.js +19 -0
- package/dist/react/TenthProvider.d.ts +11 -0
- package/dist/react/TenthProvider.js +23 -0
- package/dist/react/context.d.ts +4 -0
- package/dist/react/context.js +8 -0
- package/dist/react/hooks.d.ts +48 -0
- package/dist/react/hooks.js +68 -0
- package/dist/react/present.d.ts +15 -0
- package/dist/react/present.js +47 -0
- package/dist/react/usePaywall.d.ts +12 -0
- package/dist/react/usePaywall.js +109 -0
- package/dist/storage/storage.d.ts +14 -0
- package/dist/storage/storage.js +63 -0
- package/dist/storage/storage.web.d.ts +4 -0
- package/dist/storage/storage.web.js +35 -0
- package/dist/store/apple.d.ts +19 -0
- package/dist/store/apple.js +127 -0
- package/dist/store/context.d.ts +46 -0
- package/dist/store/context.js +21 -0
- package/dist/store/google.d.ts +22 -0
- package/dist/store/google.js +145 -0
- package/dist/store/preview.d.ts +16 -0
- package/dist/store/preview.js +68 -0
- package/dist/stripe/appearance.d.ts +47 -0
- package/dist/stripe/appearance.js +44 -0
- package/dist/stripe/flows.d.ts +23 -0
- package/dist/stripe/flows.js +145 -0
- package/dist/stripe/payment-sheet.d.ts +1 -0
- package/dist/stripe/payment-sheet.js +24 -0
- package/dist/stripe/sheet-registry.d.ts +16 -0
- package/dist/stripe/sheet-registry.js +7 -0
- package/dist/stripe/web-step.d.ts +10 -0
- package/dist/stripe/web-step.js +4 -0
- package/dist/stripe/web-step.web.d.ts +4 -0
- package/dist/stripe/web-step.web.js +55 -0
- package/dist/tenth.d.ts +125 -0
- package/dist/tenth.js +329 -0
- package/dist/updates.d.ts +15 -0
- package/dist/updates.js +30 -0
- package/expo-module.config.json +9 -0
- package/ios/CountryCodes.swift +52 -0
- package/ios/TenthBilling.podspec +31 -0
- package/ios/TenthStoreExceptions.swift +88 -0
- package/ios/TenthStoreMapping.swift +108 -0
- package/ios/TenthStoreModule.swift +213 -0
- package/ios/TenthStoreRecords.swift +105 -0
- package/package.json +94 -3
- package/plugin/withTenth.js +249 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import { type TenthConfig } from '../tenth';
|
|
3
|
+
export interface TenthProviderProps extends Omit<TenthConfig, 'storage' | 'fetch' | 'updateSource' | 'nativeStore' | 'platform' | 'now'> {
|
|
4
|
+
/**
|
|
5
|
+
* Optional: your auth library's user id. When it changes (sign-in, sign-out, switching
|
|
6
|
+
* accounts), Tenth refreshes right away instead of on the next launch or foreground.
|
|
7
|
+
*/
|
|
8
|
+
userId?: string | null;
|
|
9
|
+
children: ReactNode;
|
|
10
|
+
}
|
|
11
|
+
export declare function TenthProvider({ children, userId, getCustomerToken, ...config }: TenthProviderProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect, useMemo, useRef } from 'react';
|
|
3
|
+
import { Tenth } from '../tenth';
|
|
4
|
+
import { TenthContext } from './context';
|
|
5
|
+
import { PaywallHost } from './present';
|
|
6
|
+
export function TenthProvider({ children, userId, getCustomerToken, ...config }) {
|
|
7
|
+
const tokenRef = useRef(getCustomerToken);
|
|
8
|
+
tokenRef.current = getCustomerToken;
|
|
9
|
+
const tenth = useMemo(() => new Tenth({
|
|
10
|
+
...config,
|
|
11
|
+
getCustomerToken: () => (tokenRef.current ? tokenRef.current() : Promise.resolve(null)),
|
|
12
|
+
}), [config.apiKey, config.apiUrl, config.preview, config.offlineGraceHours]);
|
|
13
|
+
useEffect(() => tenth.start(), [tenth]);
|
|
14
|
+
const firstUser = useRef(true);
|
|
15
|
+
useEffect(() => {
|
|
16
|
+
if (firstUser.current) {
|
|
17
|
+
firstUser.current = false;
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
void tenth.refresh('identity');
|
|
21
|
+
}, [tenth, userId]);
|
|
22
|
+
return (_jsxs(TenthContext.Provider, { value: tenth, children: [children, _jsx(PaywallHost, { tenth: tenth })] }));
|
|
23
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createContext, useContext } from 'react';
|
|
2
|
+
export const TenthContext = createContext(null);
|
|
3
|
+
export function useTenth() {
|
|
4
|
+
const tenth = useContext(TenthContext);
|
|
5
|
+
if (!tenth)
|
|
6
|
+
throw new Error('Wrap your app in <TenthProvider> to use Tenth hooks and components.');
|
|
7
|
+
return tenth;
|
|
8
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { CustomerState, EntitlementState } from '../api/types';
|
|
2
|
+
import { type TenthSdkError } from '../errors';
|
|
3
|
+
import type { LoadedOffering, TenthSnapshot } from '../tenth';
|
|
4
|
+
export declare function useTenthSnapshot(): TenthSnapshot;
|
|
5
|
+
export interface CustomerInfo {
|
|
6
|
+
customer: CustomerState | null;
|
|
7
|
+
/** True until the first state (cached or fresh) is available. */
|
|
8
|
+
loading: boolean;
|
|
9
|
+
/** Showing the device cache; a refresh is on its way. */
|
|
10
|
+
fromCache: boolean;
|
|
11
|
+
error: TenthSdkError | null;
|
|
12
|
+
/** Fetches the latest state now, e.g. from a "Restore / refresh" button. */
|
|
13
|
+
refresh: () => Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export declare function useCustomer(): CustomerInfo;
|
|
16
|
+
export interface EntitlementInfo {
|
|
17
|
+
/** The customer has access now. */
|
|
18
|
+
active: boolean;
|
|
19
|
+
loading: boolean;
|
|
20
|
+
/** Details: expiry, renewal, grace period, billing issue. Null when the customer never had it. */
|
|
21
|
+
entitlement: EntitlementState | null;
|
|
22
|
+
}
|
|
23
|
+
/** `const pro = useEntitlement('pro'); if (!pro.active) return <Paywall />;` */
|
|
24
|
+
export declare function useEntitlement(key: string): EntitlementInfo;
|
|
25
|
+
export interface CreditsInfo {
|
|
26
|
+
/** Total balance. */
|
|
27
|
+
balance: number;
|
|
28
|
+
/** Balance minus credits held by open reservations. */
|
|
29
|
+
available: number;
|
|
30
|
+
loading: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Spends credits from the app. Works only when the credit type allows app-side debits;
|
|
33
|
+
* spend from your server when payment matters. Pass the same idempotencyKey when
|
|
34
|
+
* retrying one spend.
|
|
35
|
+
*/
|
|
36
|
+
debit: (amount: number, options: {
|
|
37
|
+
idempotencyKey: string;
|
|
38
|
+
metadata?: Record<string, string>;
|
|
39
|
+
}) => Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
export declare function useCredits(creditType: string): CreditsInfo;
|
|
42
|
+
export interface OfferingInfo extends Partial<LoadedOffering> {
|
|
43
|
+
loading: boolean;
|
|
44
|
+
error: TenthSdkError | null;
|
|
45
|
+
reload: () => void;
|
|
46
|
+
}
|
|
47
|
+
/** An offering with store prices. `key` omitted: the current (targeted) offering. */
|
|
48
|
+
export declare function useOffering(key?: string): OfferingInfo;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
|
|
2
|
+
import { toSdkError } from '../errors';
|
|
3
|
+
import { useTenth } from './context';
|
|
4
|
+
export function useTenthSnapshot() {
|
|
5
|
+
const tenth = useTenth();
|
|
6
|
+
return useSyncExternalStore(tenth.subscribe, tenth.getSnapshot, tenth.getSnapshot);
|
|
7
|
+
}
|
|
8
|
+
export function useCustomer() {
|
|
9
|
+
const tenth = useTenth();
|
|
10
|
+
const snap = useTenthSnapshot();
|
|
11
|
+
const refresh = useCallback(async () => {
|
|
12
|
+
await tenth.refresh('manual');
|
|
13
|
+
}, [tenth]);
|
|
14
|
+
return {
|
|
15
|
+
customer: snap.customer,
|
|
16
|
+
loading: snap.status === 'loading' && !snap.customer,
|
|
17
|
+
fromCache: snap.fromCache,
|
|
18
|
+
error: snap.error,
|
|
19
|
+
refresh,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export function useEntitlement(key) {
|
|
23
|
+
const snap = useTenthSnapshot();
|
|
24
|
+
const entitlement = snap.customer?.entitlements[key] ?? null;
|
|
25
|
+
return {
|
|
26
|
+
active: entitlement?.active ?? false,
|
|
27
|
+
loading: snap.status === 'loading' && !snap.customer,
|
|
28
|
+
entitlement,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export function useCredits(creditType) {
|
|
32
|
+
const tenth = useTenth();
|
|
33
|
+
const snap = useTenthSnapshot();
|
|
34
|
+
const credit = snap.customer?.credits[creditType];
|
|
35
|
+
const debit = useCallback((amount, options) => tenth.debitCredits(creditType, amount, options), [tenth, creditType]);
|
|
36
|
+
return {
|
|
37
|
+
balance: credit?.balance ?? 0,
|
|
38
|
+
available: credit?.available ?? 0,
|
|
39
|
+
loading: snap.status === 'loading' && !snap.customer,
|
|
40
|
+
debit,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export function useOffering(key) {
|
|
44
|
+
const tenth = useTenth();
|
|
45
|
+
const [state, setState] = useState({
|
|
46
|
+
value: null,
|
|
47
|
+
error: null,
|
|
48
|
+
loading: true,
|
|
49
|
+
});
|
|
50
|
+
const [nonce, setNonce] = useState(0);
|
|
51
|
+
useEffect(() => {
|
|
52
|
+
let live = true;
|
|
53
|
+
setState((s) => ({ ...s, loading: true }));
|
|
54
|
+
tenth
|
|
55
|
+
.getOffering(key ?? null, { force: nonce > 0 })
|
|
56
|
+
.then((value) => live && setState({ value, error: null, loading: false }))
|
|
57
|
+
.catch((err) => live && setState({ value: null, error: toSdkError(err), loading: false }));
|
|
58
|
+
return () => {
|
|
59
|
+
live = false;
|
|
60
|
+
};
|
|
61
|
+
}, [tenth, key, nonce]);
|
|
62
|
+
return {
|
|
63
|
+
...(state.value ?? {}),
|
|
64
|
+
loading: state.loading,
|
|
65
|
+
error: state.error,
|
|
66
|
+
reload: () => setNonce((n) => n + 1),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Tenth } from '../tenth';
|
|
2
|
+
export type PaywallResult = 'purchased' | 'restored' | 'cancelled' | 'not_presented';
|
|
3
|
+
export interface PresentPaywallOptions {
|
|
4
|
+
offering?: string;
|
|
5
|
+
presentation?: 'modal' | 'sheet';
|
|
6
|
+
}
|
|
7
|
+
/** Shows the paywall over the app and resolves when it closes. */
|
|
8
|
+
export declare function presentPaywall(options?: PresentPaywallOptions): Promise<PaywallResult>;
|
|
9
|
+
/** Shows the paywall only if the customer doesn't have the entitlement. */
|
|
10
|
+
export declare function presentPaywallIfNeeded(options: PresentPaywallOptions & {
|
|
11
|
+
entitlement: string;
|
|
12
|
+
}): Promise<PaywallResult>;
|
|
13
|
+
export declare function PaywallHost({ tenth }: {
|
|
14
|
+
tenth: Tenth;
|
|
15
|
+
}): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect, useState } from 'react';
|
|
3
|
+
import { Paywall } from './Paywall';
|
|
4
|
+
let show = null;
|
|
5
|
+
let current = null;
|
|
6
|
+
export function presentPaywall(options = {}) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
if (!show) {
|
|
9
|
+
reject(new Error('Wrap your app in <TenthProvider> before calling presentPaywall.'));
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
show({ ...options, resolve });
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
export async function presentPaywallIfNeeded(options) {
|
|
16
|
+
if (!current)
|
|
17
|
+
throw new Error('Wrap your app in <TenthProvider> before calling presentPaywallIfNeeded.');
|
|
18
|
+
let state = current.getSnapshot().customer;
|
|
19
|
+
if (!state || current.getSnapshot().fromCache)
|
|
20
|
+
state = (await current.refresh('manual')) ?? state;
|
|
21
|
+
if (state?.entitlements[options.entitlement]?.active)
|
|
22
|
+
return 'not_presented';
|
|
23
|
+
return presentPaywall(options);
|
|
24
|
+
}
|
|
25
|
+
export function PaywallHost({ tenth }) {
|
|
26
|
+
const [request, setRequest] = useState(null);
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
current = tenth;
|
|
29
|
+
show = (r) => setRequest((prev) => {
|
|
30
|
+
prev?.resolve('cancelled');
|
|
31
|
+
return r;
|
|
32
|
+
});
|
|
33
|
+
return () => {
|
|
34
|
+
if (current === tenth) {
|
|
35
|
+
current = null;
|
|
36
|
+
show = null;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
}, [tenth]);
|
|
40
|
+
if (!request)
|
|
41
|
+
return null;
|
|
42
|
+
const close = (result) => {
|
|
43
|
+
request.resolve(result);
|
|
44
|
+
setRequest(null);
|
|
45
|
+
};
|
|
46
|
+
return (_jsx(Paywall, { offering: request.offering, presentation: request.presentation ?? 'modal', onPurchased: (_p) => close('purchased'), onRestored: () => close('restored'), onDismiss: () => close('cancelled') }));
|
|
47
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type PaywallController, type PaywallProduct } from '@tenthbilling/paywall';
|
|
2
|
+
import { type PaywallTemplate } from '@tenthbilling/paywall/schema';
|
|
3
|
+
export interface UsePaywallOptions {
|
|
4
|
+
/** Offering key; omitted, the current (targeted) offering. */
|
|
5
|
+
offering?: string;
|
|
6
|
+
locale?: string;
|
|
7
|
+
onPurchased?: (product: PaywallProduct) => void;
|
|
8
|
+
onRestored?: () => void;
|
|
9
|
+
}
|
|
10
|
+
/** The default template when no paywall is published: one product → hero, credit packs → credits. */
|
|
11
|
+
export declare function defaultTemplateFor(products: readonly PaywallProduct[]): PaywallTemplate;
|
|
12
|
+
export declare function usePaywall(options?: UsePaywallOptions): PaywallController;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { ctaLabel, } from '@tenthbilling/paywall';
|
|
2
|
+
import { defaultPaywallConfig, } from '@tenthbilling/paywall/schema';
|
|
3
|
+
import { themes } from '@tenthbilling/design';
|
|
4
|
+
import { useCallback, useMemo, useRef, useState } from 'react';
|
|
5
|
+
import { useColorScheme } from 'react-native';
|
|
6
|
+
import { useTenth } from './context';
|
|
7
|
+
import { useOffering, useTenthSnapshot } from './hooks';
|
|
8
|
+
export function defaultTemplateFor(products) {
|
|
9
|
+
if (products.length > 0 && products.every((p) => p.type === 'consumable'))
|
|
10
|
+
return 'credits';
|
|
11
|
+
if (products.length === 1)
|
|
12
|
+
return 'hero';
|
|
13
|
+
return 'tiers';
|
|
14
|
+
}
|
|
15
|
+
export function usePaywall(options = {}) {
|
|
16
|
+
const tenth = useTenth();
|
|
17
|
+
const snap = useTenthSnapshot();
|
|
18
|
+
const scheme = useColorScheme();
|
|
19
|
+
const loaded = useOffering(options.offering);
|
|
20
|
+
const [chosen, setChosen] = useState(null);
|
|
21
|
+
const [purchasing, setPurchasing] = useState(false);
|
|
22
|
+
const [restoring, setRestoring] = useState(false);
|
|
23
|
+
const [paymentStep, setPaymentStep] = useState(null);
|
|
24
|
+
const [lastError, setLastError] = useState(null);
|
|
25
|
+
const cancelStep = useRef(null);
|
|
26
|
+
const products = useMemo(() => loaded.products ?? [], [loaded.products]);
|
|
27
|
+
const config = useMemo(() => loaded.paywall?.config ?? defaultPaywallConfig(defaultTemplateFor(products)), [loaded.paywall, products]);
|
|
28
|
+
const selectedKey = (chosen && products.some((p) => p.key === chosen) ? chosen : null) ??
|
|
29
|
+
products.find((p) => p.highlighted)?.key ??
|
|
30
|
+
products[0]?.key ??
|
|
31
|
+
null;
|
|
32
|
+
const purchase = useCallback(async (key) => {
|
|
33
|
+
const productKey = key ?? selectedKey;
|
|
34
|
+
const product = products.find((p) => p.key === productKey);
|
|
35
|
+
if (!product)
|
|
36
|
+
return {
|
|
37
|
+
status: 'failed',
|
|
38
|
+
error: { code: 'product_unavailable', message: 'Choose a product first.' },
|
|
39
|
+
};
|
|
40
|
+
setPurchasing(true);
|
|
41
|
+
setLastError(null);
|
|
42
|
+
try {
|
|
43
|
+
const result = await tenth.purchase(product.key, {
|
|
44
|
+
offering: options.offering ?? null,
|
|
45
|
+
theme: themes[scheme === 'dark' ? 'dark' : 'light'],
|
|
46
|
+
payLabel: ctaLabel(product, { locale: options.locale ?? tenth.locale }),
|
|
47
|
+
showPaymentStep: (step, onCancel) => {
|
|
48
|
+
cancelStep.current = onCancel ?? null;
|
|
49
|
+
setPaymentStep(step);
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
if (result.status === 'purchased')
|
|
53
|
+
options.onPurchased?.(product);
|
|
54
|
+
if (result.status === 'failed')
|
|
55
|
+
setLastError(result.error);
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
cancelStep.current = null;
|
|
60
|
+
setPaymentStep(null);
|
|
61
|
+
setPurchasing(false);
|
|
62
|
+
}
|
|
63
|
+
}, [tenth, products, selectedKey, options, scheme]);
|
|
64
|
+
const restore = useCallback(async () => {
|
|
65
|
+
setRestoring(true);
|
|
66
|
+
setLastError(null);
|
|
67
|
+
try {
|
|
68
|
+
const result = await tenth.restore();
|
|
69
|
+
if (result.status === 'restored')
|
|
70
|
+
options.onRestored?.();
|
|
71
|
+
if (result.status === 'failed' && result.error)
|
|
72
|
+
setLastError(result.error);
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
setRestoring(false);
|
|
77
|
+
}
|
|
78
|
+
}, [tenth, options]);
|
|
79
|
+
const error = lastError ?? (loaded.error ? { code: loaded.error.code, message: loaded.error.message } : null);
|
|
80
|
+
return {
|
|
81
|
+
status: loaded.loading
|
|
82
|
+
? 'loading'
|
|
83
|
+
: loaded.error
|
|
84
|
+
? 'error'
|
|
85
|
+
: products.length === 0
|
|
86
|
+
? 'empty'
|
|
87
|
+
: 'ready',
|
|
88
|
+
error,
|
|
89
|
+
config,
|
|
90
|
+
assets: loaded.paywall?.assets ?? {},
|
|
91
|
+
products,
|
|
92
|
+
selectedKey,
|
|
93
|
+
select: setChosen,
|
|
94
|
+
purchase,
|
|
95
|
+
restore,
|
|
96
|
+
purchasing,
|
|
97
|
+
restoring,
|
|
98
|
+
paymentStep,
|
|
99
|
+
cancelPaymentStep: () => {
|
|
100
|
+
const cancel = cancelStep.current;
|
|
101
|
+
cancelStep.current = null;
|
|
102
|
+
setPaymentStep(null);
|
|
103
|
+
cancel?.();
|
|
104
|
+
},
|
|
105
|
+
preview: snap.preview,
|
|
106
|
+
environment: snap.environment,
|
|
107
|
+
locale: options.locale ?? tenth.locale,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import * as SecureStore from 'expo-secure-store';
|
|
2
|
+
export interface KeyValueStore {
|
|
3
|
+
get(key: string): Promise<string | null>;
|
|
4
|
+
set(key: string, value: string): Promise<void>;
|
|
5
|
+
remove(key: string): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export declare function chunkedStore(base: {
|
|
8
|
+
getItemAsync(key: string, options?: SecureStore.SecureStoreOptions): Promise<string | null>;
|
|
9
|
+
setItemAsync(key: string, value: string, options?: SecureStore.SecureStoreOptions): Promise<void>;
|
|
10
|
+
deleteItemAsync(key: string, options?: SecureStore.SecureStoreOptions): Promise<void>;
|
|
11
|
+
}): KeyValueStore;
|
|
12
|
+
export declare function defaultStore(): KeyValueStore;
|
|
13
|
+
/** For tests and for apps that opt out of persistence. */
|
|
14
|
+
export declare function memoryStore(): KeyValueStore;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import * as SecureStore from 'expo-secure-store';
|
|
2
|
+
const CHUNK = 1800;
|
|
3
|
+
const MAX_CHUNKS = 64;
|
|
4
|
+
const OPTIONS = {
|
|
5
|
+
keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
|
|
6
|
+
};
|
|
7
|
+
export function chunkedStore(base) {
|
|
8
|
+
return {
|
|
9
|
+
async get(key) {
|
|
10
|
+
try {
|
|
11
|
+
const count = Number(await base.getItemAsync(key, OPTIONS));
|
|
12
|
+
if (!Number.isInteger(count) || count < 1 || count > MAX_CHUNKS)
|
|
13
|
+
return null;
|
|
14
|
+
let out = '';
|
|
15
|
+
for (let i = 0; i < count; i++) {
|
|
16
|
+
const part = await base.getItemAsync(`${key}.${i}`, OPTIONS);
|
|
17
|
+
if (part === null)
|
|
18
|
+
return null;
|
|
19
|
+
out += part;
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
async set(key, value) {
|
|
28
|
+
const count = Math.ceil(value.length / CHUNK) || 1;
|
|
29
|
+
if (count > MAX_CHUNKS)
|
|
30
|
+
return;
|
|
31
|
+
const previous = Number(await base.getItemAsync(key, OPTIONS).catch(() => null));
|
|
32
|
+
for (let i = 0; i < count; i++) {
|
|
33
|
+
await base.setItemAsync(`${key}.${i}`, value.slice(i * CHUNK, (i + 1) * CHUNK), OPTIONS);
|
|
34
|
+
}
|
|
35
|
+
await base.setItemAsync(key, String(count), OPTIONS);
|
|
36
|
+
if (Number.isInteger(previous) && previous > count) {
|
|
37
|
+
for (let i = count; i < Math.min(previous, MAX_CHUNKS); i++) {
|
|
38
|
+
await base.deleteItemAsync(`${key}.${i}`, OPTIONS).catch(() => undefined);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
async remove(key) {
|
|
43
|
+
const count = Number(await base.getItemAsync(key, OPTIONS).catch(() => null));
|
|
44
|
+
await base.deleteItemAsync(key, OPTIONS).catch(() => undefined);
|
|
45
|
+
if (Number.isInteger(count)) {
|
|
46
|
+
for (let i = 0; i < Math.min(count, MAX_CHUNKS); i++) {
|
|
47
|
+
await base.deleteItemAsync(`${key}.${i}`, OPTIONS).catch(() => undefined);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
export function defaultStore() {
|
|
54
|
+
return chunkedStore(SecureStore);
|
|
55
|
+
}
|
|
56
|
+
export function memoryStore() {
|
|
57
|
+
const map = new Map();
|
|
58
|
+
return {
|
|
59
|
+
get: async (k) => map.get(k) ?? null,
|
|
60
|
+
set: async (k, v) => void map.set(k, v),
|
|
61
|
+
remove: async (k) => void map.delete(k),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export { memoryStore } from './storage';
|
|
2
|
+
export function defaultStore() {
|
|
3
|
+
const ls = () => {
|
|
4
|
+
try {
|
|
5
|
+
return globalThis.localStorage ?? null;
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
return {
|
|
12
|
+
get: async (k) => {
|
|
13
|
+
try {
|
|
14
|
+
return ls()?.getItem(k) ?? null;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
set: async (k, v) => {
|
|
21
|
+
try {
|
|
22
|
+
ls()?.setItem(k, v);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
remove: async (k) => {
|
|
28
|
+
try {
|
|
29
|
+
ls()?.removeItem(k);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { PaywallProduct, PurchaseResult, RestoreResult } from '@tenthbilling/paywall';
|
|
2
|
+
import type { OfferingProduct } from '../api/types';
|
|
3
|
+
import type { IosNative } from '../native/module';
|
|
4
|
+
import type { IosTransaction } from '../native/spec';
|
|
5
|
+
import { type PurchaseOptions, type StoreContext, type StoreFlow } from './context';
|
|
6
|
+
export declare class AppleStore implements StoreFlow {
|
|
7
|
+
private readonly native;
|
|
8
|
+
private stopObserving;
|
|
9
|
+
constructor(native: IosNative);
|
|
10
|
+
storefrontCountry(): Promise<string | null>;
|
|
11
|
+
loadProducts(products: readonly OfferingProduct[]): Promise<PaywallProduct[]>;
|
|
12
|
+
/** Sends one transaction to Tenth; finishes it once accepted (or refused for good). */
|
|
13
|
+
submit(tx: IosTransaction, ctx: StoreContext): Promise<void>;
|
|
14
|
+
purchase(product: OfferingProduct, ctx: StoreContext, options: PurchaseOptions): Promise<PurchaseResult>;
|
|
15
|
+
restore(ctx: StoreContext): Promise<RestoreResult>;
|
|
16
|
+
/** Transaction.updates (renewals, Ask to Buy approvals, purchases on other devices) and the launch retry. */
|
|
17
|
+
start(ctx: StoreContext): () => void;
|
|
18
|
+
manage(): Promise<void>;
|
|
19
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { TenthSdkError, messageFor, toSdkError } from '../errors';
|
|
2
|
+
import { fromIosProduct } from '../products';
|
|
3
|
+
import { failed, restoreFailed, } from './context';
|
|
4
|
+
const FINAL = new Set([
|
|
5
|
+
'receipt_invalid',
|
|
6
|
+
'receipt_belongs_to_other_customer',
|
|
7
|
+
'validation_failed',
|
|
8
|
+
]);
|
|
9
|
+
export class AppleStore {
|
|
10
|
+
native;
|
|
11
|
+
stopObserving = null;
|
|
12
|
+
constructor(native) {
|
|
13
|
+
this.native = native;
|
|
14
|
+
}
|
|
15
|
+
storefrontCountry() {
|
|
16
|
+
return this.native.storefrontCountry().catch(() => null);
|
|
17
|
+
}
|
|
18
|
+
async loadProducts(products) {
|
|
19
|
+
if (!this.native.canMakePayments() || products.length === 0)
|
|
20
|
+
return [];
|
|
21
|
+
const ids = [...new Set(products.map((p) => p.store_product_id))];
|
|
22
|
+
const found = new Map((await this.native.getProducts(ids)).map((s) => [s.id, s]));
|
|
23
|
+
return products.flatMap((p) => {
|
|
24
|
+
const s = found.get(p.store_product_id);
|
|
25
|
+
const mapped = s ? fromIosProduct(p, s) : null;
|
|
26
|
+
return mapped ? [mapped] : [];
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async submit(tx, ctx) {
|
|
30
|
+
const { identity } = await ctx.identity();
|
|
31
|
+
try {
|
|
32
|
+
const res = await ctx.api.postReceipt(identity, { platform: 'ios', signed_transaction: tx.jws }, `receipt:ios:${tx.transactionId}`);
|
|
33
|
+
ctx.apply(res.customer);
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
const e = toSdkError(err);
|
|
37
|
+
if (FINAL.has(e.code))
|
|
38
|
+
await this.native.finishTransaction(tx.transactionId).catch(() => undefined);
|
|
39
|
+
throw e;
|
|
40
|
+
}
|
|
41
|
+
await this.native.finishTransaction(tx.transactionId);
|
|
42
|
+
}
|
|
43
|
+
async purchase(product, ctx, options) {
|
|
44
|
+
try {
|
|
45
|
+
if (!this.native.canMakePayments()) {
|
|
46
|
+
throw new TenthSdkError('purchases_unavailable', messageFor('purchases_unavailable', ''));
|
|
47
|
+
}
|
|
48
|
+
const customer = await ctx.customer();
|
|
49
|
+
let offer = null;
|
|
50
|
+
if (options.appleOfferId) {
|
|
51
|
+
const { identity } = await ctx.identity();
|
|
52
|
+
const sig = await ctx.api.appleOfferSignature(identity, {
|
|
53
|
+
product_id: product.store_product_id,
|
|
54
|
+
offer_id: options.appleOfferId,
|
|
55
|
+
});
|
|
56
|
+
offer = {
|
|
57
|
+
offerId: options.appleOfferId,
|
|
58
|
+
keyId: sig.key_identifier,
|
|
59
|
+
nonce: sig.nonce,
|
|
60
|
+
signature: sig.signature,
|
|
61
|
+
timestamp: sig.timestamp,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const result = await this.native.purchase(product.store_product_id, customer.customer.app_account_token, offer);
|
|
65
|
+
if (result.status === 'userCancelled')
|
|
66
|
+
return { status: 'cancelled' };
|
|
67
|
+
if (result.status === 'pending')
|
|
68
|
+
return { status: 'pending' };
|
|
69
|
+
try {
|
|
70
|
+
await this.submit(result.transaction, ctx);
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
const e = toSdkError(err);
|
|
74
|
+
if (e.retryable)
|
|
75
|
+
return { status: 'pending' };
|
|
76
|
+
throw e;
|
|
77
|
+
}
|
|
78
|
+
return { status: 'purchased' };
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
return failed(err);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async restore(ctx) {
|
|
85
|
+
try {
|
|
86
|
+
await this.native.sync().catch(() => undefined);
|
|
87
|
+
const txs = await this.native.currentEntitlements();
|
|
88
|
+
if (txs.length === 0)
|
|
89
|
+
return { status: 'nothing_to_restore' };
|
|
90
|
+
const { identity } = await ctx.identity();
|
|
91
|
+
const res = await ctx.api.restore(identity, {
|
|
92
|
+
platform: 'ios',
|
|
93
|
+
signed_transactions: txs.slice(0, 100).map((t) => t.jws),
|
|
94
|
+
});
|
|
95
|
+
ctx.apply(res.customer);
|
|
96
|
+
return res.results.some((r) => r.outcome !== 'invalid')
|
|
97
|
+
? { status: 'restored' }
|
|
98
|
+
: { status: 'nothing_to_restore' };
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
return restoreFailed(err);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
start(ctx) {
|
|
105
|
+
if (this.stopObserving)
|
|
106
|
+
return this.stopObserving;
|
|
107
|
+
this.native.startObserving();
|
|
108
|
+
const sub = this.native.addListener('onTransactionUpdate', (tx) => {
|
|
109
|
+
void this.submit(tx, ctx).catch(() => undefined);
|
|
110
|
+
});
|
|
111
|
+
void this.native
|
|
112
|
+
.unfinishedTransactions()
|
|
113
|
+
.then(async (txs) => {
|
|
114
|
+
for (const tx of txs)
|
|
115
|
+
await this.submit(tx, ctx).catch(() => undefined);
|
|
116
|
+
})
|
|
117
|
+
.catch(() => undefined);
|
|
118
|
+
this.stopObserving = () => {
|
|
119
|
+
sub.remove();
|
|
120
|
+
this.stopObserving = null;
|
|
121
|
+
};
|
|
122
|
+
return this.stopObserving;
|
|
123
|
+
}
|
|
124
|
+
manage() {
|
|
125
|
+
return this.native.showManageSubscriptions();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Theme } from '@tenthbilling/design';
|
|
2
|
+
import type { PaywallProduct, PurchaseResult, RestoreResult } from '@tenthbilling/paywall';
|
|
3
|
+
import type { ReactNode } from 'react';
|
|
4
|
+
import type { ApiClient } from '../api/client';
|
|
5
|
+
import type { CustomerState, OfferingProduct } from '../api/types';
|
|
6
|
+
import type { ResolvedIdentity } from '../identity';
|
|
7
|
+
export interface StoreContext {
|
|
8
|
+
api: ApiClient;
|
|
9
|
+
identity(): Promise<ResolvedIdentity>;
|
|
10
|
+
/** The customer's current server state, fetched if the SDK doesn't have it yet. */
|
|
11
|
+
customer(): Promise<CustomerState>;
|
|
12
|
+
/** Records state the server just returned (after a receipt, restore or refresh). */
|
|
13
|
+
apply(state: CustomerState): void;
|
|
14
|
+
/**
|
|
15
|
+
* Refreshes from the server until `done` holds or the window closes (every 2 s for 30 s by
|
|
16
|
+
* default; `timeoutMs: 0` checks once).
|
|
17
|
+
*/
|
|
18
|
+
refreshUntil(done: (state: CustomerState) => boolean, options?: {
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
}): Promise<boolean>;
|
|
21
|
+
locale: string;
|
|
22
|
+
}
|
|
23
|
+
export interface PurchaseOptions {
|
|
24
|
+
/** App Store promotional offer id (configured in the catalog; Tenth signs it). */
|
|
25
|
+
appleOfferId?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Shows an embedded payment step in the paywall (Stripe on web), or hides it with null.
|
|
28
|
+
* `onCancel` is called if the customer backs out of the step.
|
|
29
|
+
*/
|
|
30
|
+
showPaymentStep?: (step: ReactNode | null, onCancel?: () => void) => void;
|
|
31
|
+
/** The paywall's resolved theme, passed to Stripe's appearance settings. */
|
|
32
|
+
theme?: Theme;
|
|
33
|
+
/** The purchase button's label, reused on the payment step's pay button. */
|
|
34
|
+
payLabel?: string;
|
|
35
|
+
}
|
|
36
|
+
/** A store or payment path the SDK can sell through. */
|
|
37
|
+
export interface StoreFlow {
|
|
38
|
+
/** Paywall products for the offering's products this flow can sell, in offering order. */
|
|
39
|
+
loadProducts(products: readonly OfferingProduct[], ctx: StoreContext): Promise<PaywallProduct[]>;
|
|
40
|
+
purchase(product: OfferingProduct, ctx: StoreContext, options: PurchaseOptions): Promise<PurchaseResult>;
|
|
41
|
+
}
|
|
42
|
+
/** Whether a state shows what a product grants: its entitlements active, or (packs) any credit. */
|
|
43
|
+
export declare function grantsVisible(state: CustomerState, product: Pick<OfferingProduct, 'entitlements' | 'credits'>, creditsBefore: Readonly<Record<string, number>>): boolean;
|
|
44
|
+
export declare function balances(state: CustomerState | null): Record<string, number>;
|
|
45
|
+
export declare function failed(err: unknown): PurchaseResult;
|
|
46
|
+
export declare function restoreFailed(err: unknown): RestoreResult;
|