@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,21 @@
|
|
|
1
|
+
import { toSdkError } from '../errors';
|
|
2
|
+
export function grantsVisible(state, product, creditsBefore) {
|
|
3
|
+
if (product.entitlements.length > 0) {
|
|
4
|
+
return product.entitlements.every((e) => state.entitlements[e]?.active);
|
|
5
|
+
}
|
|
6
|
+
return product.credits.some((c) => (state.credits[c.credit_type]?.balance ?? 0) > (creditsBefore[c.credit_type] ?? 0));
|
|
7
|
+
}
|
|
8
|
+
export function balances(state) {
|
|
9
|
+
const out = {};
|
|
10
|
+
for (const [k, v] of Object.entries(state?.credits ?? {}))
|
|
11
|
+
out[k] = v.balance;
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
export function failed(err) {
|
|
15
|
+
const e = toSdkError(err);
|
|
16
|
+
return { status: 'failed', error: { code: e.code, message: e.message } };
|
|
17
|
+
}
|
|
18
|
+
export function restoreFailed(err) {
|
|
19
|
+
const e = toSdkError(err);
|
|
20
|
+
return { status: 'failed', error: { code: e.code, message: e.message } };
|
|
21
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { PaywallProduct, PurchaseResult, RestoreResult } from '@tenthbilling/paywall';
|
|
2
|
+
import type { OfferingProduct } from '../api/types';
|
|
3
|
+
import type { AndroidNative } from '../native/module';
|
|
4
|
+
import type { AndroidPurchase } from '../native/spec';
|
|
5
|
+
import { type StoreContext, type StoreFlow } from './context';
|
|
6
|
+
export declare class GoogleStore implements StoreFlow {
|
|
7
|
+
private readonly native;
|
|
8
|
+
private readonly packageName;
|
|
9
|
+
/** Offer tokens for the products last loaded, by catalog key. */
|
|
10
|
+
private offerTokens;
|
|
11
|
+
private stop;
|
|
12
|
+
constructor(native: AndroidNative, packageName: string | null);
|
|
13
|
+
storefrontCountry(): Promise<string | null>;
|
|
14
|
+
loadProducts(products: readonly OfferingProduct[]): Promise<PaywallProduct[]>;
|
|
15
|
+
/** Sends one purchase to Tenth, which records it and then acknowledges or consumes it. */
|
|
16
|
+
submit(p: AndroidPurchase, ctx: StoreContext): Promise<void>;
|
|
17
|
+
purchase(product: OfferingProduct, ctx: StoreContext): Promise<PurchaseResult>;
|
|
18
|
+
restore(ctx: StoreContext): Promise<RestoreResult>;
|
|
19
|
+
/** Purchases completed outside the flow (pending → purchased) and the launch retry. */
|
|
20
|
+
start(ctx: StoreContext): () => void;
|
|
21
|
+
manage(productId: string | null): Promise<void>;
|
|
22
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { Platform } from 'react-native';
|
|
2
|
+
import { TenthSdkError, messageFor, toSdkError } from '../errors';
|
|
3
|
+
import { fromAndroidProduct } from '../products';
|
|
4
|
+
import { failed, restoreFailed } from './context';
|
|
5
|
+
const PURCHASED = 1;
|
|
6
|
+
const PENDING = 2;
|
|
7
|
+
function receiptBody(p) {
|
|
8
|
+
return {
|
|
9
|
+
platform: 'android',
|
|
10
|
+
purchase_token: p.purchaseToken,
|
|
11
|
+
product_id: p.productIds[0] ?? '',
|
|
12
|
+
type: p.productType === 'subs' ? 'subscription' : 'one_time',
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export class GoogleStore {
|
|
16
|
+
native;
|
|
17
|
+
packageName;
|
|
18
|
+
offerTokens = new Map();
|
|
19
|
+
stop = null;
|
|
20
|
+
constructor(native, packageName) {
|
|
21
|
+
this.native = native;
|
|
22
|
+
this.packageName = packageName;
|
|
23
|
+
}
|
|
24
|
+
storefrontCountry() {
|
|
25
|
+
return this.native.storefrontCountry().catch(() => null);
|
|
26
|
+
}
|
|
27
|
+
async loadProducts(products) {
|
|
28
|
+
if (products.length === 0 || !(await this.native.isReady()))
|
|
29
|
+
return [];
|
|
30
|
+
const requests = [
|
|
31
|
+
...new Map(products.map((p) => [
|
|
32
|
+
p.store_product_id,
|
|
33
|
+
{
|
|
34
|
+
productId: p.store_product_id,
|
|
35
|
+
type: p.type === 'subscription' ? 'subs' : 'inapp',
|
|
36
|
+
},
|
|
37
|
+
])).values(),
|
|
38
|
+
];
|
|
39
|
+
const found = new Map((await this.native.getProducts(requests)).map((s) => [s.productId, s]));
|
|
40
|
+
return products.flatMap((p) => {
|
|
41
|
+
const s = found.get(p.store_product_id);
|
|
42
|
+
const mapped = s ? fromAndroidProduct(p, s) : null;
|
|
43
|
+
if (!mapped)
|
|
44
|
+
return [];
|
|
45
|
+
this.offerTokens.set(p.key, mapped.offerToken);
|
|
46
|
+
return [mapped.product];
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async submit(p, ctx) {
|
|
50
|
+
if (p.purchaseState !== PURCHASED || !p.productIds[0])
|
|
51
|
+
return;
|
|
52
|
+
const { identity } = await ctx.identity();
|
|
53
|
+
const res = await ctx.api.postReceipt(identity, receiptBody(p), `receipt:android:${p.purchaseToken}`);
|
|
54
|
+
ctx.apply(res.customer);
|
|
55
|
+
}
|
|
56
|
+
async purchase(product, ctx) {
|
|
57
|
+
try {
|
|
58
|
+
const subs = product.type === 'subscription';
|
|
59
|
+
const offerToken = this.offerTokens.get(product.key) ?? null;
|
|
60
|
+
if (subs && !offerToken) {
|
|
61
|
+
throw new TenthSdkError('product_unavailable', messageFor('product_unavailable', ''));
|
|
62
|
+
}
|
|
63
|
+
const customer = await ctx.customer();
|
|
64
|
+
const result = await this.native.purchase({
|
|
65
|
+
productId: product.store_product_id,
|
|
66
|
+
type: subs ? 'subs' : 'inapp',
|
|
67
|
+
offerToken,
|
|
68
|
+
obfuscatedAccountId: customer.customer.obfuscated_account_id,
|
|
69
|
+
oldPurchaseToken: null,
|
|
70
|
+
replacementMode: null,
|
|
71
|
+
});
|
|
72
|
+
if (result.status === 'userCancelled')
|
|
73
|
+
return { status: 'cancelled' };
|
|
74
|
+
if (result.status === 'pending' ||
|
|
75
|
+
result.purchases.every((p) => p.purchaseState === PENDING)) {
|
|
76
|
+
return { status: 'pending' };
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
for (const p of result.purchases)
|
|
80
|
+
await this.submit(p, ctx);
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
const e = toSdkError(err);
|
|
84
|
+
if (e.retryable)
|
|
85
|
+
return { status: 'pending' };
|
|
86
|
+
throw e;
|
|
87
|
+
}
|
|
88
|
+
return { status: 'purchased' };
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
return failed(err);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async restore(ctx) {
|
|
95
|
+
try {
|
|
96
|
+
const purchases = (await this.native.queryPurchases()).filter((p) => p.purchaseState === PURCHASED && p.productIds[0]);
|
|
97
|
+
if (purchases.length === 0)
|
|
98
|
+
return { status: 'nothing_to_restore' };
|
|
99
|
+
const { identity } = await ctx.identity();
|
|
100
|
+
const res = await ctx.api.restore(identity, {
|
|
101
|
+
platform: 'android',
|
|
102
|
+
purchases: purchases.slice(0, 100).map((p) => {
|
|
103
|
+
const { platform: _platform, ...rest } = receiptBody(p);
|
|
104
|
+
return rest;
|
|
105
|
+
}),
|
|
106
|
+
});
|
|
107
|
+
ctx.apply(res.customer);
|
|
108
|
+
return res.results.some((r) => r.outcome !== 'invalid')
|
|
109
|
+
? { status: 'restored' }
|
|
110
|
+
: { status: 'nothing_to_restore' };
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
return restoreFailed(err);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
start(ctx) {
|
|
117
|
+
if (this.stop)
|
|
118
|
+
return this.stop;
|
|
119
|
+
const sub = this.native.addListener('onPurchasesUpdated', ({ purchases }) => {
|
|
120
|
+
void (async () => {
|
|
121
|
+
for (const p of purchases)
|
|
122
|
+
await this.submit(p, ctx).catch(() => undefined);
|
|
123
|
+
})();
|
|
124
|
+
});
|
|
125
|
+
void this.native
|
|
126
|
+
.queryPurchases()
|
|
127
|
+
.then(async (purchases) => {
|
|
128
|
+
for (const p of purchases) {
|
|
129
|
+
if (!p.isAcknowledged)
|
|
130
|
+
await this.submit(p, ctx).catch(() => undefined);
|
|
131
|
+
}
|
|
132
|
+
})
|
|
133
|
+
.catch(() => undefined);
|
|
134
|
+
this.stop = () => {
|
|
135
|
+
sub.remove();
|
|
136
|
+
this.stop = null;
|
|
137
|
+
};
|
|
138
|
+
return this.stop;
|
|
139
|
+
}
|
|
140
|
+
manage(productId) {
|
|
141
|
+
if (!this.packageName || Platform.OS !== 'android')
|
|
142
|
+
return Promise.resolve();
|
|
143
|
+
return this.native.showManageSubscriptions(productId, this.packageName);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { PaywallProduct, PurchaseResult, RestoreResult } from '@tenthbilling/paywall';
|
|
2
|
+
import type { CustomerState, OfferingProduct } from '../api/types';
|
|
3
|
+
import { type StoreContext, type StoreFlow } from './context';
|
|
4
|
+
export declare class PreviewStore implements StoreFlow {
|
|
5
|
+
private readonly environment;
|
|
6
|
+
private readonly onChange;
|
|
7
|
+
private purchased;
|
|
8
|
+
constructor(environment: 'test' | 'live', onChange: () => void);
|
|
9
|
+
loadProducts(products: readonly OfferingProduct[], ctx: StoreContext): Promise<PaywallProduct[]>;
|
|
10
|
+
purchase(product: OfferingProduct): Promise<PurchaseResult>;
|
|
11
|
+
restore(): Promise<RestoreResult>;
|
|
12
|
+
/** The server state with simulated purchases applied on top. */
|
|
13
|
+
overlay(state: CustomerState): CustomerState;
|
|
14
|
+
}
|
|
15
|
+
/** Stand-in customer for preview mode when the API can't be reached. */
|
|
16
|
+
export declare function previewCustomer(): CustomerState;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { TenthSdkError, messageFor } from '../errors';
|
|
2
|
+
import { previewProduct } from '../products';
|
|
3
|
+
import { failed } from './context';
|
|
4
|
+
export class PreviewStore {
|
|
5
|
+
environment;
|
|
6
|
+
onChange;
|
|
7
|
+
purchased = [];
|
|
8
|
+
constructor(environment, onChange) {
|
|
9
|
+
this.environment = environment;
|
|
10
|
+
this.onChange = onChange;
|
|
11
|
+
}
|
|
12
|
+
async loadProducts(products, ctx) {
|
|
13
|
+
return products.map((p, i) => previewProduct(p, i, ctx.locale));
|
|
14
|
+
}
|
|
15
|
+
async purchase(product) {
|
|
16
|
+
if (this.environment === 'live') {
|
|
17
|
+
return failed(new TenthSdkError('preview_live_key', messageFor('preview_live_key', '')));
|
|
18
|
+
}
|
|
19
|
+
this.purchased.push(product);
|
|
20
|
+
this.onChange();
|
|
21
|
+
return { status: 'purchased' };
|
|
22
|
+
}
|
|
23
|
+
async restore() {
|
|
24
|
+
return { status: this.purchased.length > 0 ? 'restored' : 'nothing_to_restore' };
|
|
25
|
+
}
|
|
26
|
+
overlay(state) {
|
|
27
|
+
if (this.purchased.length === 0)
|
|
28
|
+
return state;
|
|
29
|
+
const entitlements = { ...state.entitlements };
|
|
30
|
+
const credits = { ...state.credits };
|
|
31
|
+
for (const p of this.purchased) {
|
|
32
|
+
for (const e of p.entitlements) {
|
|
33
|
+
entitlements[e] = {
|
|
34
|
+
active: true,
|
|
35
|
+
source: p.type === 'subscription' ? 'subscription' : 'purchase',
|
|
36
|
+
store: null,
|
|
37
|
+
expires_at: null,
|
|
38
|
+
will_renew: p.type === 'subscription',
|
|
39
|
+
in_grace: false,
|
|
40
|
+
billing_issue: false,
|
|
41
|
+
quantity: null,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
for (const c of p.credits) {
|
|
45
|
+
const cur = credits[c.credit_type] ?? { balance: 0, available: 0 };
|
|
46
|
+
credits[c.credit_type] = {
|
|
47
|
+
balance: cur.balance + c.amount,
|
|
48
|
+
available: cur.available + c.amount,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { ...state, entitlements, credits };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export function previewCustomer() {
|
|
56
|
+
return {
|
|
57
|
+
customer: {
|
|
58
|
+
id: 'preview',
|
|
59
|
+
app_user_id: 'preview',
|
|
60
|
+
app_account_token: '00000000-0000-0000-0000-000000000000',
|
|
61
|
+
obfuscated_account_id: 'preview',
|
|
62
|
+
created_at: new Date(0).toISOString(),
|
|
63
|
+
},
|
|
64
|
+
entitlements: {},
|
|
65
|
+
credits: {},
|
|
66
|
+
subscriptions: [],
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Theme } from '@tenthbilling/design';
|
|
2
|
+
export declare function stripeWebAppearance(theme: Theme): {
|
|
3
|
+
theme: "stripe" | "night";
|
|
4
|
+
variables: {
|
|
5
|
+
colorPrimary: string;
|
|
6
|
+
colorBackground: string;
|
|
7
|
+
colorText: string;
|
|
8
|
+
colorTextSecondary: string;
|
|
9
|
+
colorDanger: string;
|
|
10
|
+
colorIcon: string;
|
|
11
|
+
fontFamily: "\"Public Sans\", system-ui, -apple-system, \"Segoe UI\", sans-serif";
|
|
12
|
+
borderRadius: string;
|
|
13
|
+
spacingUnit: string;
|
|
14
|
+
focusOutline: string;
|
|
15
|
+
};
|
|
16
|
+
rules: {
|
|
17
|
+
'.Input': {
|
|
18
|
+
borderColor: string;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
export declare function stripeNativeAppearance(theme: Theme): {
|
|
23
|
+
colors: {
|
|
24
|
+
primary: string;
|
|
25
|
+
background: string;
|
|
26
|
+
componentBackground: string;
|
|
27
|
+
componentBorder: string;
|
|
28
|
+
componentDivider: string;
|
|
29
|
+
primaryText: string;
|
|
30
|
+
secondaryText: string;
|
|
31
|
+
placeholderText: string;
|
|
32
|
+
icon: string;
|
|
33
|
+
error: string;
|
|
34
|
+
};
|
|
35
|
+
shapes: {
|
|
36
|
+
borderRadius: 6;
|
|
37
|
+
};
|
|
38
|
+
primaryButton: {
|
|
39
|
+
colors: {
|
|
40
|
+
background: string;
|
|
41
|
+
text: string;
|
|
42
|
+
};
|
|
43
|
+
shapes: {
|
|
44
|
+
borderRadius: 6;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { fontStacks } from '@tenthbilling/design';
|
|
2
|
+
export function stripeWebAppearance(theme) {
|
|
3
|
+
const c = theme.colors;
|
|
4
|
+
return {
|
|
5
|
+
theme: theme.name === 'dark' ? 'night' : 'stripe',
|
|
6
|
+
variables: {
|
|
7
|
+
colorPrimary: c.brand,
|
|
8
|
+
colorBackground: c.surfaceRaised,
|
|
9
|
+
colorText: c.ink,
|
|
10
|
+
colorTextSecondary: c.inkMuted,
|
|
11
|
+
colorDanger: c.danger,
|
|
12
|
+
colorIcon: c.inkMuted,
|
|
13
|
+
fontFamily: fontStacks.sans,
|
|
14
|
+
borderRadius: `${theme.radius.md}px`,
|
|
15
|
+
spacingUnit: `${theme.space[1]}px`,
|
|
16
|
+
focusOutline: `2px solid ${c.focus}`,
|
|
17
|
+
},
|
|
18
|
+
rules: {
|
|
19
|
+
'.Input': { borderColor: c.lineStrong },
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export function stripeNativeAppearance(theme) {
|
|
24
|
+
const c = theme.colors;
|
|
25
|
+
return {
|
|
26
|
+
colors: {
|
|
27
|
+
primary: c.brand,
|
|
28
|
+
background: c.surfaceRaised,
|
|
29
|
+
componentBackground: c.surfaceRaised,
|
|
30
|
+
componentBorder: c.lineStrong,
|
|
31
|
+
componentDivider: c.line,
|
|
32
|
+
primaryText: c.ink,
|
|
33
|
+
secondaryText: c.inkMuted,
|
|
34
|
+
placeholderText: c.inkMuted,
|
|
35
|
+
icon: c.inkMuted,
|
|
36
|
+
error: c.danger,
|
|
37
|
+
},
|
|
38
|
+
shapes: { borderRadius: theme.radius.md },
|
|
39
|
+
primaryButton: {
|
|
40
|
+
colors: { background: c.brand, text: c.onBrand },
|
|
41
|
+
shapes: { borderRadius: theme.radius.md },
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { PaywallProduct, PurchaseResult } from '@tenthbilling/paywall';
|
|
2
|
+
import type { OfferingProduct } from '../api/types';
|
|
3
|
+
import { type PurchaseOptions, type StoreContext, type StoreFlow } from '../store/context';
|
|
4
|
+
/** Web: the Payment Element, shown inside the paywall. */
|
|
5
|
+
export declare class StripeWebFlow implements StoreFlow {
|
|
6
|
+
loadProducts(products: readonly OfferingProduct[], ctx: StoreContext): Promise<PaywallProduct[]>;
|
|
7
|
+
purchase(product: OfferingProduct, ctx: StoreContext, options: PurchaseOptions): Promise<PurchaseResult>;
|
|
8
|
+
}
|
|
9
|
+
/** Native `in_app_stripe`: PaymentSheet (needs `@tenthbilling/expo/payment-sheet`). */
|
|
10
|
+
export declare class PaymentSheetFlow implements StoreFlow {
|
|
11
|
+
private readonly merchantDisplayName;
|
|
12
|
+
private readonly urlScheme;
|
|
13
|
+
constructor(merchantDisplayName: string, urlScheme: string | null);
|
|
14
|
+
loadProducts(products: readonly OfferingProduct[], ctx: StoreContext): Promise<PaywallProduct[]>;
|
|
15
|
+
purchase(product: OfferingProduct, ctx: StoreContext, options: PurchaseOptions): Promise<PurchaseResult>;
|
|
16
|
+
}
|
|
17
|
+
/** Native `web_link_out`: hosted Checkout in the system browser, back by deep link. */
|
|
18
|
+
export declare class LinkOutFlow implements StoreFlow {
|
|
19
|
+
private readonly urlScheme;
|
|
20
|
+
constructor(urlScheme: string | null);
|
|
21
|
+
loadProducts(products: readonly OfferingProduct[], ctx: StoreContext): Promise<PaywallProduct[]>;
|
|
22
|
+
purchase(product: OfferingProduct, ctx: StoreContext): Promise<PurchaseResult>;
|
|
23
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { themes } from '@tenthbilling/design';
|
|
2
|
+
import * as WebBrowser from 'expo-web-browser';
|
|
3
|
+
import { createElement } from 'react';
|
|
4
|
+
import { TenthSdkError, messageFor } from '../errors';
|
|
5
|
+
import { fromStripePrice } from '../products';
|
|
6
|
+
import { balances, failed, grantsVisible, } from '../store/context';
|
|
7
|
+
import { paymentSheetPresenter } from './sheet-registry';
|
|
8
|
+
import { StripePaymentStep, hasStripeWeb } from './web-step';
|
|
9
|
+
function loadStripeProducts(products, ctx) {
|
|
10
|
+
return products.flatMap((p) => {
|
|
11
|
+
const mapped = fromStripePrice(p, p.price, ctx.locale);
|
|
12
|
+
return mapped ? [mapped] : [];
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
async function confirmGrant(product, ctx, before) {
|
|
16
|
+
const seen = await ctx.refreshUntil((s) => grantsVisible(s, product, before));
|
|
17
|
+
return seen ? { status: 'purchased' } : { status: 'pending' };
|
|
18
|
+
}
|
|
19
|
+
async function currentBalances(ctx) {
|
|
20
|
+
return balances(await ctx.customer().catch(() => null));
|
|
21
|
+
}
|
|
22
|
+
export class StripeWebFlow {
|
|
23
|
+
async loadProducts(products, ctx) {
|
|
24
|
+
return loadStripeProducts(products, ctx);
|
|
25
|
+
}
|
|
26
|
+
async purchase(product, ctx, options) {
|
|
27
|
+
try {
|
|
28
|
+
if (!hasStripeWeb)
|
|
29
|
+
throw new TenthSdkError('purchases_unavailable', messageFor('purchases_unavailable', ''));
|
|
30
|
+
const before = await currentBalances(ctx);
|
|
31
|
+
const { identity } = await ctx.identity();
|
|
32
|
+
const returnUrl = typeof window !== 'undefined' ? window.location.href : undefined;
|
|
33
|
+
const form = await ctx.api.createPaymentForm(identity, {
|
|
34
|
+
product: product.key,
|
|
35
|
+
form: 'elements',
|
|
36
|
+
...(returnUrl?.startsWith('https://') || returnUrl?.startsWith('http://localhost')
|
|
37
|
+
? { return_url: returnUrl }
|
|
38
|
+
: {}),
|
|
39
|
+
});
|
|
40
|
+
if (!form.client_secret || !form.publishable_key) {
|
|
41
|
+
throw new TenthSdkError('stripe_not_ready', 'Payments aren’t set up for this app yet.');
|
|
42
|
+
}
|
|
43
|
+
const show = options.showPaymentStep;
|
|
44
|
+
if (!show) {
|
|
45
|
+
throw new TenthSdkError('payment_step_unavailable', 'Open the paywall to pay on the web.');
|
|
46
|
+
}
|
|
47
|
+
const outcome = await new Promise((resolve) => {
|
|
48
|
+
show(createElement(StripePaymentStep, {
|
|
49
|
+
clientSecret: form.client_secret,
|
|
50
|
+
publishableKey: form.publishable_key,
|
|
51
|
+
stripeAccount: form.stripe_account,
|
|
52
|
+
payLabel: options.payLabel ?? 'Pay',
|
|
53
|
+
onDone: () => resolve('confirmed'),
|
|
54
|
+
}), () => resolve('cancelled'));
|
|
55
|
+
});
|
|
56
|
+
show(null);
|
|
57
|
+
if (outcome === 'cancelled')
|
|
58
|
+
return { status: 'cancelled' };
|
|
59
|
+
return await confirmGrant(product, ctx, before);
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
options.showPaymentStep?.(null);
|
|
63
|
+
return failed(err);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export class PaymentSheetFlow {
|
|
68
|
+
merchantDisplayName;
|
|
69
|
+
urlScheme;
|
|
70
|
+
constructor(merchantDisplayName, urlScheme) {
|
|
71
|
+
this.merchantDisplayName = merchantDisplayName;
|
|
72
|
+
this.urlScheme = urlScheme;
|
|
73
|
+
}
|
|
74
|
+
async loadProducts(products, ctx) {
|
|
75
|
+
return paymentSheetPresenter() ? loadStripeProducts(products, ctx) : [];
|
|
76
|
+
}
|
|
77
|
+
async purchase(product, ctx, options) {
|
|
78
|
+
try {
|
|
79
|
+
const present = paymentSheetPresenter();
|
|
80
|
+
if (!present)
|
|
81
|
+
throw new TenthSdkError('payment_sheet_missing', messageFor('payment_sheet_missing', ''));
|
|
82
|
+
const before = await currentBalances(ctx);
|
|
83
|
+
const { identity } = await ctx.identity();
|
|
84
|
+
const form = await ctx.api.createPaymentForm(identity, {
|
|
85
|
+
product: product.key,
|
|
86
|
+
form: 'payment_sheet',
|
|
87
|
+
});
|
|
88
|
+
if (!form.client_secret || !form.publishable_key) {
|
|
89
|
+
throw new TenthSdkError('stripe_not_ready', 'Payments aren’t set up for this app yet.');
|
|
90
|
+
}
|
|
91
|
+
const outcome = await present({
|
|
92
|
+
clientSecret: form.client_secret,
|
|
93
|
+
publishableKey: form.publishable_key,
|
|
94
|
+
stripeAccount: form.stripe_account,
|
|
95
|
+
merchantDisplayName: this.merchantDisplayName,
|
|
96
|
+
returnURL: this.urlScheme ? `${this.urlScheme}://stripe-redirect` : null,
|
|
97
|
+
theme: options.theme ?? themes.light,
|
|
98
|
+
});
|
|
99
|
+
if (outcome === 'canceled')
|
|
100
|
+
return { status: 'cancelled' };
|
|
101
|
+
if (outcome !== 'completed')
|
|
102
|
+
throw new TenthSdkError('payment_failed', outcome.failed);
|
|
103
|
+
return await confirmGrant(product, ctx, before);
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
return failed(err);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
export class LinkOutFlow {
|
|
111
|
+
urlScheme;
|
|
112
|
+
constructor(urlScheme) {
|
|
113
|
+
this.urlScheme = urlScheme;
|
|
114
|
+
}
|
|
115
|
+
async loadProducts(products, ctx) {
|
|
116
|
+
return this.urlScheme ? loadStripeProducts(products, ctx) : [];
|
|
117
|
+
}
|
|
118
|
+
async purchase(product, ctx) {
|
|
119
|
+
try {
|
|
120
|
+
if (!this.urlScheme) {
|
|
121
|
+
throw new TenthSdkError('url_scheme_missing', 'Set a URL scheme in app.json (expo.scheme) so customers can return to the app after paying.');
|
|
122
|
+
}
|
|
123
|
+
const before = await currentBalances(ctx);
|
|
124
|
+
const { identity } = await ctx.identity();
|
|
125
|
+
const session = await ctx.api.createCheckoutSession(identity, {
|
|
126
|
+
product: product.key,
|
|
127
|
+
return: 'app',
|
|
128
|
+
});
|
|
129
|
+
if (!session.url.startsWith('https://')) {
|
|
130
|
+
throw new TenthSdkError('payment_failed', 'Checkout could not be opened.');
|
|
131
|
+
}
|
|
132
|
+
const result = await WebBrowser.openAuthSessionAsync(session.url, `${this.urlScheme}://tenth/checkout-return`);
|
|
133
|
+
const succeeded = result.type === 'success' && /[?&]status=success(&|$)/.test(result.url);
|
|
134
|
+
if (succeeded)
|
|
135
|
+
return await confirmGrant(product, ctx, before);
|
|
136
|
+
const seen = await ctx
|
|
137
|
+
.refreshUntil((s) => grantsVisible(s, product, before), { timeoutMs: 0 })
|
|
138
|
+
.catch(() => false);
|
|
139
|
+
return seen ? { status: 'purchased' } : { status: 'cancelled' };
|
|
140
|
+
}
|
|
141
|
+
catch (err) {
|
|
142
|
+
return failed(err);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { initPaymentSheet, initStripe, presentPaymentSheet } from '@stripe/stripe-react-native';
|
|
2
|
+
import { stripeNativeAppearance } from './appearance';
|
|
3
|
+
import { registerPaymentSheet } from './sheet-registry';
|
|
4
|
+
registerPaymentSheet(async (input) => {
|
|
5
|
+
await initStripe({
|
|
6
|
+
publishableKey: input.publishableKey,
|
|
7
|
+
stripeAccountId: input.stripeAccount ?? undefined,
|
|
8
|
+
urlScheme: input.returnURL ? new URL(input.returnURL).protocol.replace(':', '') : undefined,
|
|
9
|
+
});
|
|
10
|
+
const init = await initPaymentSheet({
|
|
11
|
+
paymentIntentClientSecret: input.clientSecret,
|
|
12
|
+
merchantDisplayName: input.merchantDisplayName,
|
|
13
|
+
returnURL: input.returnURL ?? undefined,
|
|
14
|
+
appearance: stripeNativeAppearance(input.theme),
|
|
15
|
+
style: input.theme.name === 'dark' ? 'alwaysDark' : 'alwaysLight',
|
|
16
|
+
});
|
|
17
|
+
if (init.error)
|
|
18
|
+
return { failed: init.error.message };
|
|
19
|
+
const result = await presentPaymentSheet();
|
|
20
|
+
if (!result.error)
|
|
21
|
+
return 'completed';
|
|
22
|
+
return result.error.code === 'Canceled' ? 'canceled' : { failed: result.error.message };
|
|
23
|
+
});
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Theme } from '@tenthbilling/design';
|
|
2
|
+
export interface PaymentSheetInput {
|
|
3
|
+
clientSecret: string;
|
|
4
|
+
publishableKey: string;
|
|
5
|
+
stripeAccount: string | null;
|
|
6
|
+
merchantDisplayName: string;
|
|
7
|
+
/** Where 3-D Secure and bank redirects return to (`<scheme>://stripe-redirect`). */
|
|
8
|
+
returnURL: string | null;
|
|
9
|
+
theme: Theme;
|
|
10
|
+
}
|
|
11
|
+
export type PaymentSheetOutcome = 'completed' | 'canceled' | {
|
|
12
|
+
failed: string;
|
|
13
|
+
};
|
|
14
|
+
export type PaymentSheetPresenter = (input: PaymentSheetInput) => Promise<PaymentSheetOutcome>;
|
|
15
|
+
export declare function registerPaymentSheet(p: PaymentSheetPresenter): void;
|
|
16
|
+
export declare function paymentSheetPresenter(): PaymentSheetPresenter | null;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface StripeStepProps {
|
|
2
|
+
clientSecret: string;
|
|
3
|
+
publishableKey: string;
|
|
4
|
+
stripeAccount: string | null;
|
|
5
|
+
/** The pay button's label, naming what happens ("Subscribe for $59.99/year"). */
|
|
6
|
+
payLabel: string;
|
|
7
|
+
onDone: (outcome: 'confirmed') => void;
|
|
8
|
+
}
|
|
9
|
+
export declare function StripePaymentStep(_props: StripeStepProps): null;
|
|
10
|
+
export declare const hasStripeWeb = false;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { Button, Banner, useTheme } from '@tenthbilling/paywall';
|
|
3
|
+
import { loadStripe } from '@stripe/stripe-js';
|
|
4
|
+
import { CheckoutElementsProvider, PaymentElement, useCheckoutElements, } from '@stripe/react-stripe-js/checkout';
|
|
5
|
+
import { useMemo, useState } from 'react';
|
|
6
|
+
import { View } from 'react-native';
|
|
7
|
+
import { stripeWebAppearance } from './appearance';
|
|
8
|
+
const stripes = new Map();
|
|
9
|
+
function stripeFor(publishableKey, stripeAccount) {
|
|
10
|
+
const key = `${publishableKey}:${stripeAccount ?? ''}`;
|
|
11
|
+
let s = stripes.get(key);
|
|
12
|
+
if (!s) {
|
|
13
|
+
s = loadStripe(publishableKey, stripeAccount ? { stripeAccount } : undefined);
|
|
14
|
+
stripes.set(key, s);
|
|
15
|
+
}
|
|
16
|
+
return s;
|
|
17
|
+
}
|
|
18
|
+
function PayButton({ label, onDone }) {
|
|
19
|
+
const checkout = useCheckoutElements();
|
|
20
|
+
const { space } = useTheme();
|
|
21
|
+
const [busy, setBusy] = useState(false);
|
|
22
|
+
const [error, setError] = useState(null);
|
|
23
|
+
if (checkout.type === 'error')
|
|
24
|
+
return _jsx(Banner, { kind: "danger", children: checkout.error.message });
|
|
25
|
+
const pay = async () => {
|
|
26
|
+
if (checkout.type !== 'success')
|
|
27
|
+
return;
|
|
28
|
+
setBusy(true);
|
|
29
|
+
setError(null);
|
|
30
|
+
const result = await checkout.checkout.confirm({ redirect: 'if_required' });
|
|
31
|
+
setBusy(false);
|
|
32
|
+
if (result.type === 'success')
|
|
33
|
+
onDone('confirmed');
|
|
34
|
+
else
|
|
35
|
+
setError(result.error.message);
|
|
36
|
+
};
|
|
37
|
+
return (_jsxs(View, { style: { gap: space[3] }, children: [error ? _jsx(Banner, { kind: "danger", children: error }) : null, _jsx(Button, { label: label, variant: "primary", size: "block", loading: busy || checkout.type === 'loading', onPress: () => void pay() })] }));
|
|
38
|
+
}
|
|
39
|
+
export function StripePaymentStep(props) {
|
|
40
|
+
const theme = useTheme();
|
|
41
|
+
const stripe = useMemo(() => stripeFor(props.publishableKey, props.stripeAccount), [props.publishableKey, props.stripeAccount]);
|
|
42
|
+
const options = useMemo(() => ({
|
|
43
|
+
clientSecret: props.clientSecret,
|
|
44
|
+
elementsOptions: {
|
|
45
|
+
appearance: stripeWebAppearance(theme),
|
|
46
|
+
fonts: [
|
|
47
|
+
{
|
|
48
|
+
cssSrc: 'https://fonts.googleapis.com/css2?family=Public+Sans:wght@400;500;600&display=swap',
|
|
49
|
+
},
|
|
50
|
+
],
|
|
51
|
+
},
|
|
52
|
+
}), [props.clientSecret, theme]);
|
|
53
|
+
return (_jsx(CheckoutElementsProvider, { stripe: stripe, options: options, children: _jsxs(View, { style: { gap: theme.space[4] }, children: [_jsx(PaymentElement, {}), _jsx(PayButton, { label: props.payLabel, onDone: props.onDone })] }) }));
|
|
54
|
+
}
|
|
55
|
+
export const hasStripeWeb = true;
|