@tansy/payments 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 +12 -2
- package/index.d.ts +23 -0
- package/index.js +504 -0
- package/logic.d.ts +63 -0
- package/logic.js +122 -0
- package/messages.d.ts +74 -0
- package/messages.js +263 -0
- package/package.json +45 -4
- package/payments.css +8 -0
- package/provider.d.ts +89 -0
- package/provider.js +4 -0
- package/react.d.ts +20 -0
- package/react.js +63 -0
- package/render.d.ts +3 -0
- package/render.js +25 -0
- package/shared.d.ts +159 -0
- package/shared.js +289 -0
- package/site-messages.d.ts +3 -0
- package/site-messages.js +29 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mohamed Salah
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# @tansy/payments
|
|
4
|
+
|
|
5
|
+
Sell anything on tansy: subscriptions and one-time purchases, through better-auth's payment plugins. Add a provider package, such as @tansy/payments-stripe.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @tansy/payments
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Add it to `tansy.config.ts`. See [the payments plugin documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/plugins/payments.md) for what it adds and the options it takes.
|
|
12
|
+
|
|
13
|
+
A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { PaymentProvider } from "./provider";
|
|
2
|
+
export { ACCESS, ACCESS_FIELD, ENTITLEMENTS, MEMBERSHIPS, PLAN_FIELD, PLANS, PRICE_TYPE, PURCHASES } from "./shared";
|
|
3
|
+
export type { PaymentProvider } from "./provider";
|
|
4
|
+
export interface PaymentsOptions {
|
|
5
|
+
/** The public site's origin, such as https://example.com. Checkout sends buyers back here. */
|
|
6
|
+
siteUrl: string;
|
|
7
|
+
/** The currency of prices that don't name one, until changed under Payments → Settings. */
|
|
8
|
+
currency?: string;
|
|
9
|
+
/**
|
|
10
|
+
* The providers the site can take money with, each from its own package, such as
|
|
11
|
+
* `stripe()` from @tansy/payments-stripe. Owners choose one under Payments → Settings.
|
|
12
|
+
*/
|
|
13
|
+
providers: PaymentProvider[];
|
|
14
|
+
/** Which of them takes the money until changed under Payments → Settings. The first when left out. */
|
|
15
|
+
provider?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Sell anything: subscriptions to plans, and any record with a price field, through the
|
|
19
|
+
* provider adapters a site installs, such as @tansy/payments-stripe. Each provider's
|
|
20
|
+
* better-auth plugin does customers and webhooks. This wires it to the CMS. See
|
|
21
|
+
* docs/plugins/payments.md.
|
|
22
|
+
*/
|
|
23
|
+
export declare function payments(options: PaymentsOptions): import("tansy/plugin").CmsPlugin;
|
package/index.js
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { defineField } from "tansy/fields";
|
|
3
|
+
import { defineBlock, definePlugin, defineRoute, mergeMessagesByLanguage } from "tansy/plugin";
|
|
4
|
+
import { accessCollectionsProblem, CURRENCY, isSlug, itemName, MAX_PLAN_ACCESS, returnUrl, sitePath, toMinorUnits, toPlanRef } from "./logic";
|
|
5
|
+
import { COLLECTION_LABELS, FIELD_LABELS, messages } from "./messages";
|
|
6
|
+
import { ACCESS, ACCESS_FIELD, accessSync, ENTITLEMENTS, forgetOldCheckouts, MEMBERSHIPS, owns, PLAN_DISPLAY_FIELDS, PLAN_FIELD, PLAN_NAME, PLANS, PRICE_TYPE, purchaseOf, PURCHASES, refuse, settingsOf, str, } from "./shared";
|
|
7
|
+
export { ACCESS, ACCESS_FIELD, ENTITLEMENTS, MEMBERSHIPS, PLAN_FIELD, PLANS, PRICE_TYPE, PURCHASES } from "./shared";
|
|
8
|
+
const PROVIDER_ID = /^[a-z][a-z0-9]{0,19}$/;
|
|
9
|
+
const optionsSchema = z.strictObject({
|
|
10
|
+
siteUrl: z.url(),
|
|
11
|
+
currency: z.string().regex(CURRENCY, 'Use a three-letter currency code in lowercase, such as "usd".'),
|
|
12
|
+
providers: z.array(z.object({ id: z.string().regex(PROVIDER_ID, "A provider's id is lowercase letters and digits."), label: z.string().min(1) }).loose()).min(1, "Add at least one provider, such as stripe() from @tansy/payments-stripe."),
|
|
13
|
+
provider: z.string(),
|
|
14
|
+
}).superRefine((value, issues) => {
|
|
15
|
+
const ids = value.providers.map((provider) => provider.id);
|
|
16
|
+
const twice = ids.find((id, index) => ids.indexOf(id) !== index);
|
|
17
|
+
if (twice)
|
|
18
|
+
issues.addIssue({ code: "custom", path: ["providers"], message: `The provider "${twice}" is listed twice.` });
|
|
19
|
+
if (!ids.includes(value.provider))
|
|
20
|
+
issues.addIssue({ code: "custom", path: ["provider"], message: `"${value.provider}" isn't one of the providers: ${ids.join(", ")}.` });
|
|
21
|
+
});
|
|
22
|
+
const LOCKED = { createRule: null, updateRule: null, deleteRule: null };
|
|
23
|
+
const notReady = (provider) => refuse(503, "PAYMENTS_NOT_SET_UP", `Payments aren't set up yet. Add the ${provider?.label ?? "provider"} keys under Payments → Settings.`);
|
|
24
|
+
/** Errors from a provider's better-auth endpoints, which core has already made into answers meant for the caller. */
|
|
25
|
+
const answered = new WeakSet();
|
|
26
|
+
/** The route's context, with `auth.call` marking its errors as answers. */
|
|
27
|
+
function withAnswers(context) {
|
|
28
|
+
return {
|
|
29
|
+
...context,
|
|
30
|
+
auth: {
|
|
31
|
+
...context.auth,
|
|
32
|
+
call: (path, input) => context.auth.call(path, input).catch((error) => {
|
|
33
|
+
if (error && typeof error === "object")
|
|
34
|
+
answered.add(error);
|
|
35
|
+
throw error;
|
|
36
|
+
}),
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** A provider's API failed. What it said stays in the server log, as it can name the site's account. */
|
|
41
|
+
function providerFailed(error, provider) {
|
|
42
|
+
if (error && typeof error === "object" && answered.has(error))
|
|
43
|
+
throw error;
|
|
44
|
+
console.error(`[payments] ${provider} failed`, error);
|
|
45
|
+
return refuse(502, "PROVIDER_FAILED", "The payment provider couldn't do that just now. Try again in a moment.");
|
|
46
|
+
}
|
|
47
|
+
function buyerOf(context) {
|
|
48
|
+
if (context.principal.kind === "anonymous")
|
|
49
|
+
return null;
|
|
50
|
+
const { id, email, name } = context.principal.user;
|
|
51
|
+
return { id, email, name: name ?? "" };
|
|
52
|
+
}
|
|
53
|
+
/** The collection's first price field, or null when its records aren't for sale. */
|
|
54
|
+
async function priceFieldOf(context, collection) {
|
|
55
|
+
if (!isSlug(collection))
|
|
56
|
+
return null;
|
|
57
|
+
return (await context.schema.describe(collection))?.fields.find((candidate) => candidate.type === PRICE_TYPE) ?? null;
|
|
58
|
+
}
|
|
59
|
+
const NOT_OFFERED = { forSale: false, amount: null, currency: null, once: false, purchased: false };
|
|
60
|
+
/** Payments' own settings. Each provider adds its own after them. */
|
|
61
|
+
const sharedSettings = (value, providers) => [
|
|
62
|
+
{ name: "provider", type: "select", default: value.provider, label: "Provider", description: "Who takes the money. Fill in that provider's settings below. Records of past purchases stay when you switch.", options: providers.map((provider) => ({ value: provider.id, label: provider.label })) },
|
|
63
|
+
{ name: "currency", type: "text", default: value.currency, maxLength: 3, label: "Currency", description: 'For prices that don\'t name one. A three-letter code, such as "usd".' },
|
|
64
|
+
{ name: "testMode", type: "boolean", default: false, label: "Test mode", description: "Use the provider's sandbox or test environment, for providers that pick it by setting rather than by key." },
|
|
65
|
+
{ name: "createCustomerOnSignUp", type: "boolean", default: false, label: "Create a customer with the provider for every new account", description: "Otherwise one is made the first time someone pays, for providers that support it." },
|
|
66
|
+
];
|
|
67
|
+
/** Every setting's name starts with its provider's id, so two providers can't claim one. */
|
|
68
|
+
function providerSettings(providers, siteUrl) {
|
|
69
|
+
const fields = providers.flatMap((provider) => provider.settings(siteUrl).map((field) => {
|
|
70
|
+
if (!field.name.startsWith(provider.id))
|
|
71
|
+
throw new Error(`Payments provider "${provider.id}": the setting "${field.name}" must start with "${provider.id}".`);
|
|
72
|
+
return field;
|
|
73
|
+
}));
|
|
74
|
+
return fields;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Sell anything: subscriptions to plans, and any record with a price field, through the
|
|
78
|
+
* provider adapters a site installs, such as @tansy/payments-stripe. Each provider's
|
|
79
|
+
* better-auth plugin does customers and webhooks. This wires it to the CMS. See
|
|
80
|
+
* docs/plugins/payments.md.
|
|
81
|
+
*/
|
|
82
|
+
export function payments(options) {
|
|
83
|
+
const value = optionsSchema.parse({ currency: "usd", provider: options.providers?.[0]?.id, ...Object.fromEntries(Object.entries(options).filter(([, option]) => option !== undefined)) });
|
|
84
|
+
const providers = options.providers;
|
|
85
|
+
const siteUrl = value.siteUrl.replace(/\/$/, "");
|
|
86
|
+
const byId = new Map(providers.map((provider) => [provider.id, provider]));
|
|
87
|
+
const fields = [...sharedSettings(value, providers), ...providerSettings(providers, siteUrl)];
|
|
88
|
+
const currencyOf = (field, settings) => str(field.config.currency) || (CURRENCY.test(settings.currency) ? settings.currency : value.currency);
|
|
89
|
+
/** The active provider, or null until its keys are set. */
|
|
90
|
+
const active = async (context) => {
|
|
91
|
+
const settings = await settingsOf(context);
|
|
92
|
+
const chosen = byId.get(settings.provider);
|
|
93
|
+
return { settings, chosen, provider: chosen?.ready(settings) ? chosen : null };
|
|
94
|
+
};
|
|
95
|
+
/** Plan names are stored in lowercase, as Stripe's plugin compares them that way, and each id must suit the provider. */
|
|
96
|
+
async function normalizePlan(context) {
|
|
97
|
+
if (context.collection.slug === ACCESS) {
|
|
98
|
+
const problem = accessCollectionsProblem(context.values.collections);
|
|
99
|
+
if (problem)
|
|
100
|
+
context.reject(problem, "collections");
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (context.collection.slug !== PLANS)
|
|
104
|
+
return;
|
|
105
|
+
if (typeof context.values.name === "string")
|
|
106
|
+
context.values.name = context.values.name.trim().toLowerCase();
|
|
107
|
+
const settings = await settingsOf(context);
|
|
108
|
+
// A price shown on a pricing page is in the site's currency unless the plan names its own.
|
|
109
|
+
if (typeof context.values.currency === "string")
|
|
110
|
+
context.values.currency = context.values.currency.trim().toLowerCase() || null;
|
|
111
|
+
if (context.values.currency && !CURRENCY.test(String(context.values.currency)))
|
|
112
|
+
context.reject("Use a three-letter currency code, such as usd.", "currency");
|
|
113
|
+
const shown = (name) => (Object.hasOwn(context.values, name) ? context.values[name] : context.record?.[name]);
|
|
114
|
+
if ((typeof shown("amount") === "number" || typeof shown("annualAmount") === "number") && !shown("currency") && (await context.schema.describe(PLANS))?.fields.some((field) => field.name === "currency")) {
|
|
115
|
+
context.values.currency = settings.currency;
|
|
116
|
+
}
|
|
117
|
+
const chosen = byId.get(settings.provider);
|
|
118
|
+
for (const field of ["priceId", "annualPriceId"]) {
|
|
119
|
+
const id = context.values[field];
|
|
120
|
+
const problem = chosen && typeof id === "string" && id.trim() ? chosen.planIdProblem(id.trim()) : null;
|
|
121
|
+
if (problem)
|
|
122
|
+
context.reject(problem, field);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const syncAccess = accessSync(providers.flatMap((provider) => (provider.subscriptionRecords ? [provider.subscriptionRecords] : [])));
|
|
126
|
+
return definePlugin({
|
|
127
|
+
name: "payments",
|
|
128
|
+
messages: mergeMessagesByLanguage(messages, ...providers.map((provider) => provider.messages?.(siteUrl))),
|
|
129
|
+
version: "0.1.0",
|
|
130
|
+
apiVersion: 1,
|
|
131
|
+
requires: { cms: "^0.1.0" },
|
|
132
|
+
admin: { render: "@tansy/payments/render" },
|
|
133
|
+
options: { schema: optionsSchema, value },
|
|
134
|
+
settings: { fields },
|
|
135
|
+
contract: {
|
|
136
|
+
[PLANS]: { name: "text", priceId: "text", annualPriceId: "text", trialDays: "number", limits: "json", group: "text", includes: "reference" },
|
|
137
|
+
[PURCHASES]: { buyer: "text", collection: "text", recordId: "number", amount: "number", currency: "text", sessionId: "text", paymentIntent: "text", state: "text" },
|
|
138
|
+
[MEMBERSHIPS]: { provider: "text", subscriptionId: "text", user: "text", plan: "text", state: "text" },
|
|
139
|
+
[ACCESS]: { name: "text", description: "text", collections: "json" },
|
|
140
|
+
[ENTITLEMENTS]: { user: "text", plans: "json", access: "json" },
|
|
141
|
+
},
|
|
142
|
+
fields: [
|
|
143
|
+
defineField({
|
|
144
|
+
type: PRICE_TYPE,
|
|
145
|
+
admin: { label: "Price", description: "Makes a record something people can buy", input: "number" },
|
|
146
|
+
config: {
|
|
147
|
+
currency: z.string().regex(CURRENCY).optional().describe("Leave empty for the currency under Payments → Settings."),
|
|
148
|
+
once: z.boolean().optional().describe("Each person can buy it once, such as a course or a download. On by default."),
|
|
149
|
+
},
|
|
150
|
+
value: () => z.number().min(0).max(1_000_000),
|
|
151
|
+
storage: () => ({ sql: "real" }),
|
|
152
|
+
}),
|
|
153
|
+
],
|
|
154
|
+
blocks: [
|
|
155
|
+
defineBlock({
|
|
156
|
+
name: "payments_buy",
|
|
157
|
+
label: "Buy button",
|
|
158
|
+
labels: { ar: "زر الشراء" },
|
|
159
|
+
category: "Payments",
|
|
160
|
+
fields: [
|
|
161
|
+
{ name: "collection", type: "text", config: { required: true, maxLength: 63, description: "The collection of the record to sell, such as blog-posts. It needs a Price field.", labels: { ar: "المجموعة" }, descriptions: { ar: "مجموعة السجل المعروض للبيع، مثل blog-posts. تحتاج إلى حقل سعر." } } },
|
|
162
|
+
{ name: "record", type: "number", config: { required: true, description: "The record's id.", labels: { ar: "السجل" }, descriptions: { ar: "معرّف السجل." } } },
|
|
163
|
+
{ name: "label", type: "text", config: { maxLength: 60, labels: { ar: "نص الزر" } } },
|
|
164
|
+
],
|
|
165
|
+
}),
|
|
166
|
+
defineBlock({
|
|
167
|
+
name: "payments_subscribe",
|
|
168
|
+
label: "Subscribe button",
|
|
169
|
+
labels: { ar: "زر الاشتراك" },
|
|
170
|
+
category: "Payments",
|
|
171
|
+
fields: [
|
|
172
|
+
{ name: "plan", type: "text", config: { required: true, maxLength: 60, description: "A plan's name from Payments → Plans.", labels: { ar: "الخطة" }, descriptions: { ar: "اسم خطة من المدفوعات ← الخطط." } } },
|
|
173
|
+
{ name: "annual", type: "boolean", config: { description: "Bill yearly, at the plan's annual price.", labels: { ar: "سنوي" }, descriptions: { ar: "الفوترة سنويًا، بالسعر السنوي للخطة." } } },
|
|
174
|
+
{ name: "label", type: "text", config: { maxLength: 60, labels: { ar: "نص الزر" } } },
|
|
175
|
+
],
|
|
176
|
+
}),
|
|
177
|
+
defineBlock({ name: "payments_billing", label: "Manage billing", labels: { ar: "إدارة الفوترة" }, category: "Payments", fields: [{ name: "label", type: "text", config: { maxLength: 60, labels: { ar: "نص الزر" } } }] }),
|
|
178
|
+
],
|
|
179
|
+
auth: {
|
|
180
|
+
plugins: async (_auth, context) => {
|
|
181
|
+
const { settings, provider } = await active(context);
|
|
182
|
+
return provider ? provider.authPlugins(settings, context, siteUrl) : [];
|
|
183
|
+
},
|
|
184
|
+
serverOnlyPaths: [...new Set(providers.flatMap((provider) => provider.serverOnlyPaths ?? []))],
|
|
185
|
+
},
|
|
186
|
+
hooks: {
|
|
187
|
+
"record.beforeCreate": normalizePlan,
|
|
188
|
+
"record.beforeUpdate": normalizePlan,
|
|
189
|
+
"record.afterCreate": syncAccess,
|
|
190
|
+
"record.afterUpdate": syncAccess,
|
|
191
|
+
"record.afterDelete": syncAccess,
|
|
192
|
+
},
|
|
193
|
+
jobs: [{ name: "payments-forget-checkouts", cron: "17 4 * * *", handler: forgetOldCheckouts }],
|
|
194
|
+
routes: [
|
|
195
|
+
defineRoute({
|
|
196
|
+
method: "POST",
|
|
197
|
+
path: "/checkout",
|
|
198
|
+
access: "authenticated",
|
|
199
|
+
audit: "payments.checkout",
|
|
200
|
+
rateLimit: { window: 60, max: 20 },
|
|
201
|
+
body: z.strictObject({ collection: z.string().max(63), id: z.number().int().positive(), returnPath: z.string().max(500).optional() }),
|
|
202
|
+
handler: async (context) => {
|
|
203
|
+
const buyer = buyerOf(context);
|
|
204
|
+
if (!buyer)
|
|
205
|
+
return refuse(401, "UNAUTHENTICATED", "Sign in to buy.");
|
|
206
|
+
const { settings, chosen, provider } = await active(context);
|
|
207
|
+
if (!provider)
|
|
208
|
+
return notReady(chosen);
|
|
209
|
+
const { collection, id, returnPath } = context.body;
|
|
210
|
+
const field = await priceFieldOf(context, collection);
|
|
211
|
+
if (!field)
|
|
212
|
+
return refuse(400, "NOT_FOR_SALE", "This isn't for sale.");
|
|
213
|
+
// As the caller, so a record they can't see reads as missing, and the price comes from what's stored.
|
|
214
|
+
const record = await context.records.get(collection, id);
|
|
215
|
+
const currency = currencyOf(field, settings);
|
|
216
|
+
const amount = toMinorUnits(record[field.name], currency);
|
|
217
|
+
if (amount === null)
|
|
218
|
+
return refuse(400, "NOT_FOR_SALE", "This has no price yet.");
|
|
219
|
+
if (field.config.once !== false && (await owns(context, buyer.id, collection, id)))
|
|
220
|
+
return refuse(409, "ALREADY_PURCHASED", "You already bought this.");
|
|
221
|
+
try {
|
|
222
|
+
const problem = await provider.currencyProblem?.(settings, currency);
|
|
223
|
+
if (problem)
|
|
224
|
+
return refuse(400, "NOT_FOR_SALE", problem);
|
|
225
|
+
const url = await provider.checkout({
|
|
226
|
+
context: withAnswers(context), settings, buyer, collection, recordId: id, name: itemName(record, `${collection} ${id}`), amount, currency,
|
|
227
|
+
successUrl: returnUrl(siteUrl, returnPath ?? "/", "purchase", "success"),
|
|
228
|
+
cancelUrl: returnUrl(siteUrl, returnPath ?? "/", "purchase", "canceled"),
|
|
229
|
+
});
|
|
230
|
+
context.auditTarget("record", `${collection}/${id}`, { provider: provider.id });
|
|
231
|
+
return { url };
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
return providerFailed(error, provider.label);
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
}),
|
|
238
|
+
defineRoute({
|
|
239
|
+
method: "POST",
|
|
240
|
+
path: "/confirm",
|
|
241
|
+
access: "authenticated",
|
|
242
|
+
audit: "payments.confirm",
|
|
243
|
+
rateLimit: { window: 60, max: 20 },
|
|
244
|
+
// The provider's checkout id, or the reference Payments put in the return address.
|
|
245
|
+
body: z.strictObject({ sessionId: z.string().regex(/^[A-Za-z0-9_-]{1,255}$/) }),
|
|
246
|
+
handler: async (context) => {
|
|
247
|
+
const buyer = buyerOf(context);
|
|
248
|
+
if (!buyer)
|
|
249
|
+
return refuse(401, "UNAUTHENTICATED", "Sign in first.");
|
|
250
|
+
const { settings, chosen, provider } = await active(context);
|
|
251
|
+
if (!provider)
|
|
252
|
+
return notReady(chosen);
|
|
253
|
+
const { sessionId } = context.body;
|
|
254
|
+
if (!provider.isReference(sessionId))
|
|
255
|
+
return refuse(400, "VALIDATION_FAILED", "That isn't a checkout reference.");
|
|
256
|
+
// Already recorded, by the webhook or an earlier visit.
|
|
257
|
+
const known = await purchaseOf(context, sessionId, buyer.id);
|
|
258
|
+
if (known)
|
|
259
|
+
return { paid: known.state === "paid" };
|
|
260
|
+
// Read from the provider with the site's key, so nothing the browser sends is trusted but the reference.
|
|
261
|
+
const confirmed = await provider.confirm(context, settings, sessionId, buyer).catch((error) => {
|
|
262
|
+
console.error(`[payments] ${provider.label} confirm failed`, error);
|
|
263
|
+
return null;
|
|
264
|
+
});
|
|
265
|
+
// Someone else's checkout reads as missing.
|
|
266
|
+
return confirmed ?? refuse(404, "NOT_FOUND", "There's no such checkout.");
|
|
267
|
+
},
|
|
268
|
+
}),
|
|
269
|
+
defineRoute({
|
|
270
|
+
method: "GET",
|
|
271
|
+
path: "/offer",
|
|
272
|
+
access: "public",
|
|
273
|
+
reason: "A price is part of the record it's on. The record is read as the caller, so one they can't see reads as missing, and only the caller's own purchase is reported.",
|
|
274
|
+
rateLimit: { window: 60, max: 120 },
|
|
275
|
+
query: z.object({ collection: z.string().max(63), id: z.coerce.number().int().positive() }),
|
|
276
|
+
handler: async (context) => {
|
|
277
|
+
const { collection, id } = context.query;
|
|
278
|
+
const field = await priceFieldOf(context, collection);
|
|
279
|
+
if (!field)
|
|
280
|
+
return NOT_OFFERED;
|
|
281
|
+
const record = await context.records.get(collection, id, { fields: field.name });
|
|
282
|
+
const { settings, provider } = await active(context);
|
|
283
|
+
const currency = currencyOf(field, settings);
|
|
284
|
+
// Without keys nothing can be bought, so nothing is offered.
|
|
285
|
+
if (!provider || toMinorUnits(record[field.name], currency) === null)
|
|
286
|
+
return NOT_OFFERED;
|
|
287
|
+
const once = field.config.once !== false;
|
|
288
|
+
const purchased = once && context.principal.kind !== "anonymous" && (await owns(context, context.principal.user.id, collection, id));
|
|
289
|
+
return { forSale: true, amount: record[field.name], currency, once, purchased };
|
|
290
|
+
},
|
|
291
|
+
}),
|
|
292
|
+
defineRoute({
|
|
293
|
+
method: "GET",
|
|
294
|
+
path: "/purchased",
|
|
295
|
+
access: "authenticated",
|
|
296
|
+
query: z.object({ collection: z.string().max(63), id: z.coerce.number().int().positive() }),
|
|
297
|
+
handler: async (context) => {
|
|
298
|
+
if (context.principal.kind === "anonymous" || !isSlug(context.query.collection))
|
|
299
|
+
return { purchased: false };
|
|
300
|
+
return { purchased: await owns(context, context.principal.user.id, context.query.collection, context.query.id) };
|
|
301
|
+
},
|
|
302
|
+
}),
|
|
303
|
+
defineRoute({
|
|
304
|
+
method: "POST",
|
|
305
|
+
path: "/subscribe",
|
|
306
|
+
access: "authenticated",
|
|
307
|
+
audit: "payments.subscribe",
|
|
308
|
+
rateLimit: { window: 60, max: 20 },
|
|
309
|
+
body: z.strictObject({ plan: z.string().max(60), annual: z.boolean().optional(), returnPath: z.string().max(500).optional() }),
|
|
310
|
+
handler: async (context) => {
|
|
311
|
+
const buyer = buyerOf(context);
|
|
312
|
+
if (!buyer)
|
|
313
|
+
return refuse(401, "UNAUTHENTICATED", "Sign in to subscribe.");
|
|
314
|
+
const { settings, chosen, provider } = await active(context);
|
|
315
|
+
if (!provider)
|
|
316
|
+
return notReady(chosen);
|
|
317
|
+
const name = context.body.plan.trim().toLowerCase();
|
|
318
|
+
const { items } = PLAN_NAME.test(name) ? await context.system.records.list(PLANS, { filter: `status = "published" && name = "${name}"`, perPage: 1, fields: "name,priceId,annualPriceId" }) : { items: [] };
|
|
319
|
+
const plan = items[0] ? toPlanRef(items[0]) : null;
|
|
320
|
+
if (!plan)
|
|
321
|
+
return refuse(404, "NOT_FOUND", "There's no such plan.");
|
|
322
|
+
const annual = context.body.annual === true;
|
|
323
|
+
if (annual && !plan.annualProductId && !provider.yearlyFromSamePlan)
|
|
324
|
+
return refuse(400, "NO_ANNUAL_PRICE", "This plan has no yearly price.");
|
|
325
|
+
const path = sitePath(context.body.returnPath ?? "/");
|
|
326
|
+
try {
|
|
327
|
+
const url = await provider.subscribe({
|
|
328
|
+
context: withAnswers(context), settings, buyer, plan, annual,
|
|
329
|
+
successUrl: returnUrl(siteUrl, path, "subscription", "success"),
|
|
330
|
+
cancelUrl: new URL(path, siteUrl).toString(),
|
|
331
|
+
});
|
|
332
|
+
context.auditTarget("plan", plan.name, { provider: provider.id, annual });
|
|
333
|
+
return { url };
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
return providerFailed(error, provider.label);
|
|
337
|
+
}
|
|
338
|
+
},
|
|
339
|
+
}),
|
|
340
|
+
defineRoute({
|
|
341
|
+
method: "POST",
|
|
342
|
+
path: "/billing",
|
|
343
|
+
access: "authenticated",
|
|
344
|
+
audit: "payments.billing",
|
|
345
|
+
rateLimit: { window: 60, max: 20 },
|
|
346
|
+
body: z.strictObject({ returnPath: z.string().max(500).optional() }),
|
|
347
|
+
handler: async (context) => {
|
|
348
|
+
const buyer = buyerOf(context);
|
|
349
|
+
if (!buyer)
|
|
350
|
+
return refuse(401, "UNAUTHENTICATED", "Sign in first.");
|
|
351
|
+
const { settings, chosen, provider } = await active(context);
|
|
352
|
+
if (!provider)
|
|
353
|
+
return notReady(chosen);
|
|
354
|
+
try {
|
|
355
|
+
const url = await provider.billing(withAnswers(context), settings, buyer, new URL(sitePath(context.body.returnPath ?? "/"), siteUrl).toString());
|
|
356
|
+
context.auditTarget("user", buyer.id, { provider: provider.id });
|
|
357
|
+
return { url };
|
|
358
|
+
}
|
|
359
|
+
catch (error) {
|
|
360
|
+
return providerFailed(error, provider.label);
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
}),
|
|
364
|
+
],
|
|
365
|
+
migrations: [
|
|
366
|
+
{
|
|
367
|
+
id: "001-collections",
|
|
368
|
+
up: async ({ schema }) => {
|
|
369
|
+
for (const slug of [PLANS, PURCHASES]) {
|
|
370
|
+
if (await schema.describe(slug))
|
|
371
|
+
throw new Error(`A collection called "${slug}" already exists, and the payments plugin didn't create it. Rename it under Dashboard → Collections, then start again.`);
|
|
372
|
+
}
|
|
373
|
+
await schema.apply({
|
|
374
|
+
version: 1,
|
|
375
|
+
collections: [
|
|
376
|
+
{
|
|
377
|
+
slug: PLANS,
|
|
378
|
+
name: "Plans",
|
|
379
|
+
description: "What people can subscribe to. Each needs a recurring price or product with your provider. Changes apply to new subscriptions.",
|
|
380
|
+
// Anyone may see published plans, for a pricing page.
|
|
381
|
+
rules: { listRule: 'status = "published"', viewRule: 'status = "published"', ...LOCKED },
|
|
382
|
+
fields: [
|
|
383
|
+
{ name: "name", type: "text", config: { required: true, unique: true, maxLength: 60, description: "Lowercase, such as pro. Rules check it: @request.auth.payments_plan = \"pro\"." } },
|
|
384
|
+
{ name: "priceId", type: "text", config: { required: true, maxLength: 100, description: "The provider's id: a Stripe price (price_…), a Polar product, a Dodo Payments product (pdt_…), a Creem product (prod_…) or a Commet plan." } },
|
|
385
|
+
{ name: "annualPriceId", type: "text", config: { maxLength: 100, description: "Optional yearly price or product. Commet bills the same plan yearly instead." } },
|
|
386
|
+
{ name: "trialDays", type: "number", config: { description: "Free days before the first payment, with Stripe. Other providers set trials on the product." } },
|
|
387
|
+
{ name: "limits", type: "json", config: { description: "Optional numbers your site reads, such as {\"projects\": 5}." } },
|
|
388
|
+
{ name: "group", type: "text", config: { maxLength: 60 } },
|
|
389
|
+
],
|
|
390
|
+
},
|
|
391
|
+
{
|
|
392
|
+
slug: PURCHASES,
|
|
393
|
+
name: "Purchases",
|
|
394
|
+
description: "One-time purchases, recorded when the provider confirms payment. Refund the whole payment with the provider and the purchase is marked refunded.",
|
|
395
|
+
// Each buyer sees their own. Only the plugin writes them.
|
|
396
|
+
rules: { listRule: "buyer = @request.auth.id", viewRule: "buyer = @request.auth.id", ...LOCKED },
|
|
397
|
+
fields: [
|
|
398
|
+
{ name: "buyer", type: "text", config: { required: true, maxLength: 64 } },
|
|
399
|
+
{ name: "collection", type: "text", config: { required: true, maxLength: 63 } },
|
|
400
|
+
{ name: "recordId", type: "number", config: { required: true } },
|
|
401
|
+
{ name: "amount", type: "number", config: {} },
|
|
402
|
+
{ name: "currency", type: "text", config: { maxLength: 3 } },
|
|
403
|
+
{ name: "sessionId", type: "text", config: { required: true, unique: true, maxLength: 255 } },
|
|
404
|
+
{ name: "paymentIntent", type: "text", config: { maxLength: 255 } },
|
|
405
|
+
{ name: "state", type: "text", config: { required: true, maxLength: 20, description: "paid or refunded." } },
|
|
406
|
+
],
|
|
407
|
+
},
|
|
408
|
+
],
|
|
409
|
+
userFields: [{ name: PLAN_FIELD, type: "text", config: { hidden: true, label: "Plan", description: "Set by Payments from the user's subscription. Rules read it." }, selfEditable: false }],
|
|
410
|
+
});
|
|
411
|
+
},
|
|
412
|
+
},
|
|
413
|
+
{
|
|
414
|
+
id: "002-providers",
|
|
415
|
+
up: async ({ schema }) => {
|
|
416
|
+
if (await schema.describe(MEMBERSHIPS))
|
|
417
|
+
throw new Error(`A collection called "${MEMBERSHIPS}" already exists, and the payments plugin didn't create it. Rename it under Dashboard → Collections, then start again.`);
|
|
418
|
+
await schema.addFields(PURCHASES, [{ name: "provider", type: "text", config: { maxLength: 20, description: "Who took the payment. Empty for purchases from before Payments had more than Stripe." } }]);
|
|
419
|
+
await schema.apply({
|
|
420
|
+
version: 1,
|
|
421
|
+
collections: [{
|
|
422
|
+
slug: MEMBERSHIPS,
|
|
423
|
+
name: "Memberships",
|
|
424
|
+
description: "Subscriptions with Polar, Dodo Payments, Creem or Commet, kept from their webhooks. Stripe's are under Subscription. Each person sees their own.",
|
|
425
|
+
rules: { listRule: "user = @request.auth.id", viewRule: "user = @request.auth.id", ...LOCKED },
|
|
426
|
+
fields: [
|
|
427
|
+
{ name: "provider", type: "text", config: { required: true, maxLength: 20 } },
|
|
428
|
+
{ name: "subscriptionId", type: "text", config: { required: true, unique: true, maxLength: 255 } },
|
|
429
|
+
{ name: "user", type: "text", config: { required: true, maxLength: 64 } },
|
|
430
|
+
{ name: "plan", type: "text", config: { maxLength: 60, description: "The plan's name from Plans, matched by the provider's product or plan id." } },
|
|
431
|
+
{ name: "state", type: "text", config: { required: true, maxLength: 20, description: "active, trialing, past_due, paused, canceled, expired or pending." } },
|
|
432
|
+
{ name: "periodEnd", type: "datetime", config: {} },
|
|
433
|
+
{ name: "eventAt", type: "number", config: { description: "When the provider's latest event about it happened, so older ones don't overwrite it." } },
|
|
434
|
+
],
|
|
435
|
+
}],
|
|
436
|
+
});
|
|
437
|
+
},
|
|
438
|
+
},
|
|
439
|
+
{
|
|
440
|
+
id: "003-access",
|
|
441
|
+
up: async ({ schema }) => {
|
|
442
|
+
for (const slug of [ACCESS, ENTITLEMENTS]) {
|
|
443
|
+
if (await schema.describe(slug))
|
|
444
|
+
throw new Error(`A collection called "${slug}" already exists, and the payments plugin didn't create it. Rename it under Dashboard → Collections, then start again.`);
|
|
445
|
+
}
|
|
446
|
+
await schema.apply({
|
|
447
|
+
version: 1,
|
|
448
|
+
collections: [
|
|
449
|
+
{
|
|
450
|
+
slug: ACCESS,
|
|
451
|
+
name: "Access",
|
|
452
|
+
description: "What plans open. Put records in an access with a Reference field to Access, or open whole collections. Plans list the access they include.",
|
|
453
|
+
// Anyone may see published access, for a pricing page.
|
|
454
|
+
rules: { listRule: 'status = "published"', viewRule: 'status = "published"', ...LOCKED },
|
|
455
|
+
fields: [
|
|
456
|
+
{ name: "name", type: "text", config: { required: true, unique: true, maxLength: 80, description: "Such as All courses or Premium posts." } },
|
|
457
|
+
{ name: "description", type: "text", config: { maxLength: 500 } },
|
|
458
|
+
{ name: "collections", type: "json", config: { description: 'Collections it opens whole, by slug, such as ["lms-courses"]. Rules check them: @request.auth.payments_access ?= "lms-courses".' } },
|
|
459
|
+
],
|
|
460
|
+
},
|
|
461
|
+
{
|
|
462
|
+
slug: ENTITLEMENTS,
|
|
463
|
+
name: "Entitlements",
|
|
464
|
+
description: "Each person's active plans and the access they include, kept by Payments from their subscriptions. Each person sees their own.",
|
|
465
|
+
rules: { listRule: "user = @request.auth.id", viewRule: "user = @request.auth.id", ...LOCKED },
|
|
466
|
+
fields: [
|
|
467
|
+
{ name: "user", type: "text", config: { required: true, unique: true, maxLength: 64 } },
|
|
468
|
+
{ name: "plans", type: "json", config: { description: "Names of the plans their active subscriptions are on." } },
|
|
469
|
+
{ name: "access", type: "json", config: { description: "Ids of the access those plans include, then the collections they open whole." } },
|
|
470
|
+
],
|
|
471
|
+
},
|
|
472
|
+
],
|
|
473
|
+
userFields: [{ name: ACCESS_FIELD, type: "json", config: { hidden: true, label: "Access", description: "Set by Payments from the user's plans. Rules read it." }, selfEditable: false }],
|
|
474
|
+
});
|
|
475
|
+
await schema.addFields(PLANS, [{ name: "includes", type: "reference", config: { collection: ACCESS, displayField: "name", allowMultiple: true, maxSelect: MAX_PLAN_ACCESS, description: "What subscribers to this plan may open." } }]);
|
|
476
|
+
},
|
|
477
|
+
},
|
|
478
|
+
{
|
|
479
|
+
id: "004-names-in-languages",
|
|
480
|
+
up: async ({ schema }) => {
|
|
481
|
+
for (const [slug, labels] of Object.entries(COLLECTION_LABELS))
|
|
482
|
+
await schema.addLabels(slug, labels);
|
|
483
|
+
},
|
|
484
|
+
},
|
|
485
|
+
{
|
|
486
|
+
id: "005-field-names-in-languages",
|
|
487
|
+
up: async ({ schema }) => {
|
|
488
|
+
for (const [slug, fields] of Object.entries(FIELD_LABELS))
|
|
489
|
+
await schema.addFieldLabels(slug, fields);
|
|
490
|
+
},
|
|
491
|
+
},
|
|
492
|
+
{
|
|
493
|
+
// What a pricing page shows. The provider still holds the price it charges.
|
|
494
|
+
id: "006-plans-on-pricing-pages",
|
|
495
|
+
up: async ({ schema }) => {
|
|
496
|
+
if (!(await schema.describe(PLANS)))
|
|
497
|
+
return;
|
|
498
|
+
await schema.addFields(PLANS, PLAN_DISPLAY_FIELDS);
|
|
499
|
+
await schema.addFieldLabels(PLANS, FIELD_LABELS[PLANS]);
|
|
500
|
+
},
|
|
501
|
+
},
|
|
502
|
+
],
|
|
503
|
+
});
|
|
504
|
+
}
|
package/logic.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** Pure helpers, kept apart from the plugin so they're easy to test. */
|
|
2
|
+
export declare const isUserId: (value: unknown) => value is string;
|
|
3
|
+
export declare const isSlug: (value: unknown) => value is string;
|
|
4
|
+
/** A price as owners type it, such as 19.99, in the smallest unit Stripe charges in, such as 1999 cents. Null when it can't be charged. */
|
|
5
|
+
export declare function toMinorUnits(amount: unknown, currency: string): number | null;
|
|
6
|
+
/** Back from Stripe's smallest unit to the amount owners see. */
|
|
7
|
+
export declare const fromMinorUnits: (minor: number, currency: string) => number;
|
|
8
|
+
export declare const CURRENCY: RegExp;
|
|
9
|
+
/** A path on this site to come back to, never somewhere else. */
|
|
10
|
+
export declare function sitePath(value: unknown): string;
|
|
11
|
+
/** The site address with a path and one more query parameter. */
|
|
12
|
+
export declare function returnUrl(siteUrl: string, path: string, key: string, value: string): string;
|
|
13
|
+
/** What a record is called on the checkout page. */
|
|
14
|
+
export declare function itemName(record: Record<string, unknown>, fallback: string): string;
|
|
15
|
+
/** Subscriptions that give access now. */
|
|
16
|
+
export declare const ACTIVE_STATES: Set<string>;
|
|
17
|
+
export declare const membershipState: (status: unknown) => string;
|
|
18
|
+
/** The reference in a return address that Payments made itself, for providers whose own ids can't go there. */
|
|
19
|
+
export declare const REFERENCE: RegExp;
|
|
20
|
+
export interface PlanRef {
|
|
21
|
+
name: string;
|
|
22
|
+
productId: string;
|
|
23
|
+
annualProductId?: string;
|
|
24
|
+
}
|
|
25
|
+
/** Plan records that name a product, for providers that sell plans as products. */
|
|
26
|
+
export declare function toPlanRef(plan: PlanRecord): PlanRef | null;
|
|
27
|
+
/** The slugs better-auth's Polar and Dodo plugins pick products by: the plan's name, and name-annual for the yearly one. */
|
|
28
|
+
export declare const productSlugs: (plans: PlanRef[]) => {
|
|
29
|
+
productId: string;
|
|
30
|
+
slug: string;
|
|
31
|
+
}[];
|
|
32
|
+
/** The plan a provider's product or plan id belongs to, monthly or yearly. */
|
|
33
|
+
export declare const planNamed: (plans: PlanRef[], productId: unknown) => string | null;
|
|
34
|
+
export interface PlanRecord {
|
|
35
|
+
name?: unknown;
|
|
36
|
+
priceId?: unknown;
|
|
37
|
+
annualPriceId?: unknown;
|
|
38
|
+
trialDays?: unknown;
|
|
39
|
+
limits?: unknown;
|
|
40
|
+
group?: unknown;
|
|
41
|
+
}
|
|
42
|
+
/** At most this many collections in one access, and this many access in one plan. */
|
|
43
|
+
export declare const MAX_ACCESS_COLLECTIONS = 50;
|
|
44
|
+
export declare const MAX_PLAN_ACCESS = 50;
|
|
45
|
+
/** What's wrong with an access's `collections`, or null. A list of collection slugs. */
|
|
46
|
+
export declare function accessCollectionsProblem(value: unknown): string | null;
|
|
47
|
+
/** The record ids in a reference field's value, which holds one id or a list. */
|
|
48
|
+
export declare function referenceIds(value: unknown): number[];
|
|
49
|
+
export interface PlanAccess {
|
|
50
|
+
name: string;
|
|
51
|
+
includes: number[];
|
|
52
|
+
}
|
|
53
|
+
export interface AccessGrant {
|
|
54
|
+
id: number;
|
|
55
|
+
collections: string[];
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* What a person on these plans may open: the ids of every access their plans include, then
|
|
59
|
+
* the slugs of the collections those open whole. Sorted, so the same plans always give the
|
|
60
|
+
* same list. Rules compare record fields with it: ids match "Included in" references, and
|
|
61
|
+
* slugs match a rule's `@request.auth.payments_access ?= "lms-courses"`.
|
|
62
|
+
*/
|
|
63
|
+
export declare function accessOf(active: string[], plans: PlanAccess[], grants: AccessGrant[]): Array<number | string>;
|