@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/react.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useState } from "react";
|
|
4
|
+
import { apiPath, authPath, siteWords } from "tansy/react";
|
|
5
|
+
import { siteMessages } from "./site-messages";
|
|
6
|
+
const ENGLISH = { locale: "en", messages: siteMessages.en };
|
|
7
|
+
/**
|
|
8
|
+
* Buttons any template or block can place. Each sends the visitor to the payment provider and back to
|
|
9
|
+
* the page they were on. Signed-out visitors go to sign in first. Pass the page's `words`
|
|
10
|
+
* (`pickWords(words, "payments")`) to word them in its language.
|
|
11
|
+
*/
|
|
12
|
+
const here = () => `${window.location.pathname}${window.location.search}`;
|
|
13
|
+
const signIn = () => { window.location.assign(authPath(`signin?next=${encodeURIComponent(here())}`)); };
|
|
14
|
+
async function post(url, body) {
|
|
15
|
+
const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
16
|
+
const json = await response.json().catch(() => null);
|
|
17
|
+
return { status: response.status, ok: response.ok, url: json?.url };
|
|
18
|
+
}
|
|
19
|
+
function useRedirect(start, failed, t) {
|
|
20
|
+
const [busy, setBusy] = useState(false);
|
|
21
|
+
const [error, setError] = useState(null);
|
|
22
|
+
const go = async () => {
|
|
23
|
+
setBusy(true);
|
|
24
|
+
setError(null);
|
|
25
|
+
try {
|
|
26
|
+
const { status, ok, url } = await start();
|
|
27
|
+
if (status === 401)
|
|
28
|
+
return signIn();
|
|
29
|
+
// The route's message is English, for API callers, so the page says it in its own words.
|
|
30
|
+
if (!ok || !url)
|
|
31
|
+
return setError(failed);
|
|
32
|
+
window.location.assign(url);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
setError(t("payments.offline", { problem: failed }));
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
setBusy(false);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
return { busy, error, go };
|
|
42
|
+
}
|
|
43
|
+
function Action({ label, busyLabel, busy, error, onClick }) {
|
|
44
|
+
return (_jsxs("div", { className: "payments-cta", children: [_jsx("button", { type: "button", className: "payments-button", onClick: onClick, disabled: busy, children: busy ? busyLabel : label }), error && _jsx("p", { className: "payments-error", role: "alert", children: error })] }));
|
|
45
|
+
}
|
|
46
|
+
/** Buys one record of any collection with a Price field. */
|
|
47
|
+
export function BuyButton({ collection, id, label, words }) {
|
|
48
|
+
const { t } = siteWords(words ?? ENGLISH);
|
|
49
|
+
const { busy, error, go } = useRedirect(() => post(apiPath("/ext/payments/checkout"), { collection, id, returnPath: here() }), t("payments.checkoutFailed"), t);
|
|
50
|
+
return _jsx(Action, { label: label ?? t("payments.buy"), busyLabel: t("payments.opening"), busy: busy, error: error, onClick: go });
|
|
51
|
+
}
|
|
52
|
+
/** Subscribes to a plan from Payments → Plans, or switches to it, with whichever provider the site uses. */
|
|
53
|
+
export function SubscribeButton({ plan, annual = false, label, words }) {
|
|
54
|
+
const { t } = siteWords(words ?? ENGLISH);
|
|
55
|
+
const { busy, error, go } = useRedirect(() => post(apiPath("/ext/payments/subscribe"), { plan: plan.toLowerCase(), annual, returnPath: window.location.pathname }), t("payments.subscribeFailed"), t);
|
|
56
|
+
return _jsx(Action, { label: label ?? t("payments.subscribe"), busyLabel: t("payments.opening"), busy: busy, error: error, onClick: go });
|
|
57
|
+
}
|
|
58
|
+
/** The provider's billing page: change plan, update the card, see invoices, cancel. */
|
|
59
|
+
export function BillingButton({ label, words }) {
|
|
60
|
+
const { t } = siteWords(words ?? ENGLISH);
|
|
61
|
+
const { busy, error, go } = useRedirect(() => post(apiPath("/ext/payments/billing"), { returnPath: here() }), t("payments.billingFailed"), t);
|
|
62
|
+
return _jsx(Action, { label: label ?? t("payments.billing"), busyLabel: t("payments.openingBilling"), busy: busy, error: error, onClick: go });
|
|
63
|
+
}
|
package/render.d.ts
ADDED
package/render.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { defineRenderers, pickWords } from "tansy/react";
|
|
3
|
+
import { BillingButton, BuyButton, SubscribeButton } from "./react";
|
|
4
|
+
import { siteMessages } from "./site-messages";
|
|
5
|
+
import "./payments.css";
|
|
6
|
+
const text = (value) => (typeof value === "string" ? value.trim() : "");
|
|
7
|
+
const forParts = (words) => (words ? pickWords(words, "payments") : undefined);
|
|
8
|
+
function Buy({ value, words }) {
|
|
9
|
+
const collection = text(value.collection);
|
|
10
|
+
const id = typeof value.record === "number" ? value.record : null;
|
|
11
|
+
if (!collection || !id)
|
|
12
|
+
return null;
|
|
13
|
+
return _jsx(BuyButton, { collection: collection, id: id, label: text(value.label) || undefined, words: forParts(words) });
|
|
14
|
+
}
|
|
15
|
+
function Subscribe({ value, words }) {
|
|
16
|
+
const plan = text(value.plan);
|
|
17
|
+
if (!plan)
|
|
18
|
+
return null;
|
|
19
|
+
return _jsx(SubscribeButton, { plan: plan, annual: value.annual === true, label: text(value.label) || undefined, words: forParts(words) });
|
|
20
|
+
}
|
|
21
|
+
const Billing = ({ value, words }) => _jsx(BillingButton, { label: text(value.label) || undefined, words: forParts(words) });
|
|
22
|
+
export default defineRenderers({
|
|
23
|
+
messages: siteMessages,
|
|
24
|
+
blocks: { payments_buy: Buy, payments_subscribe: Subscribe, payments_billing: Billing },
|
|
25
|
+
});
|
package/shared.d.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import type { AfterHookContext, ExtensionContext } from "tansy/plugin";
|
|
2
|
+
import { type PlanRef } from "./logic";
|
|
3
|
+
/** What every provider shares: the plugin's collections, settings, and the records it keeps. */
|
|
4
|
+
export declare const PLANS = "payments-plans";
|
|
5
|
+
export declare const PURCHASES = "payments-purchases";
|
|
6
|
+
/** Subscriptions with providers whose better-auth plugins keep none (all but Stripe), from their webhooks. */
|
|
7
|
+
export declare const MEMBERSHIPS = "payments-memberships";
|
|
8
|
+
/** Kept by better-auth's payment plugins: each user's customer id with the provider. */
|
|
9
|
+
export declare const CUSTOMERS = "payments-user-data";
|
|
10
|
+
/** The user field rules gate on, such as `@request.auth.payments_plan = "pro"`. */
|
|
11
|
+
export declare const PLAN_FIELD = "payments_plan";
|
|
12
|
+
/** What plans open, kept by the owner: whole collections, and records "Included in" it. */
|
|
13
|
+
export declare const ACCESS = "payments-access";
|
|
14
|
+
/** One record per person: their active plans, and the access those include. */
|
|
15
|
+
export declare const ENTITLEMENTS = "payments-entitlements";
|
|
16
|
+
/** The user field rules gate access on: `included ?= @request.auth.payments_access`. */
|
|
17
|
+
export declare const ACCESS_FIELD = "payments_access";
|
|
18
|
+
export declare const PRICE_TYPE = "payments_price";
|
|
19
|
+
/**
|
|
20
|
+
* What a pricing page shows about a plan. The provider charges the price set with it, so
|
|
21
|
+
* these are for people to read, and never decide what anyone pays.
|
|
22
|
+
*/
|
|
23
|
+
export declare const PLAN_DISPLAY_FIELDS: ({
|
|
24
|
+
name: string;
|
|
25
|
+
type: string;
|
|
26
|
+
config: {
|
|
27
|
+
maxLength: number;
|
|
28
|
+
description: string;
|
|
29
|
+
multiline?: undefined;
|
|
30
|
+
min?: undefined;
|
|
31
|
+
};
|
|
32
|
+
} | {
|
|
33
|
+
name: string;
|
|
34
|
+
type: string;
|
|
35
|
+
config: {
|
|
36
|
+
multiline: boolean;
|
|
37
|
+
maxLength: number;
|
|
38
|
+
description: string;
|
|
39
|
+
min?: undefined;
|
|
40
|
+
};
|
|
41
|
+
} | {
|
|
42
|
+
name: string;
|
|
43
|
+
type: string;
|
|
44
|
+
config: {
|
|
45
|
+
min: number;
|
|
46
|
+
description: string;
|
|
47
|
+
maxLength?: undefined;
|
|
48
|
+
multiline?: undefined;
|
|
49
|
+
};
|
|
50
|
+
} | {
|
|
51
|
+
name: string;
|
|
52
|
+
type: string;
|
|
53
|
+
config: {
|
|
54
|
+
description: string;
|
|
55
|
+
maxLength?: undefined;
|
|
56
|
+
multiline?: undefined;
|
|
57
|
+
min?: undefined;
|
|
58
|
+
};
|
|
59
|
+
})[];
|
|
60
|
+
/** The settings Payments has itself, and each installed provider's, by name. */
|
|
61
|
+
export interface PaymentsSettings {
|
|
62
|
+
/** The id of the provider taking the money. */
|
|
63
|
+
provider: string;
|
|
64
|
+
currency: string;
|
|
65
|
+
createCustomerOnSignUp: boolean;
|
|
66
|
+
testMode: boolean;
|
|
67
|
+
[name: string]: unknown;
|
|
68
|
+
}
|
|
69
|
+
export declare const settingsOf: (context: ExtensionContext) => Promise<PaymentsSettings>;
|
|
70
|
+
export declare const str: (value: unknown) => string;
|
|
71
|
+
export declare const refuse: (status: number, code: string, message: string) => Response;
|
|
72
|
+
/** Plan records as providers that sell plans as products take them. */
|
|
73
|
+
export declare function loadPlanRefs(context: ExtensionContext): Promise<PlanRef[]>;
|
|
74
|
+
/** Has this user already bought this record? */
|
|
75
|
+
export declare function owns(context: ExtensionContext, buyer: string, collection: string, recordId: number): Promise<boolean>;
|
|
76
|
+
/** What Payments sends with every one-time checkout, and reads back from the provider. */
|
|
77
|
+
export interface PurchaseMetadata {
|
|
78
|
+
tansy: "purchase";
|
|
79
|
+
collection: string;
|
|
80
|
+
recordId: string;
|
|
81
|
+
userId: string;
|
|
82
|
+
ref?: string;
|
|
83
|
+
}
|
|
84
|
+
/** A checkout Payments started, remembered under its reference until the provider confirms it. */
|
|
85
|
+
export interface StartedCheckout {
|
|
86
|
+
id: string;
|
|
87
|
+
userId: string;
|
|
88
|
+
collection: string;
|
|
89
|
+
recordId: number;
|
|
90
|
+
at: number;
|
|
91
|
+
}
|
|
92
|
+
export declare const newReference: () => string;
|
|
93
|
+
export declare const rememberCheckout: (context: ExtensionContext, ref: string, checkout: StartedCheckout) => Promise<void>;
|
|
94
|
+
export declare function startedCheckout(context: ExtensionContext, ref: unknown): Promise<StartedCheckout | null>;
|
|
95
|
+
export declare function forgetOldCheckouts(context: ExtensionContext): Promise<void>;
|
|
96
|
+
export interface PaidCheckout {
|
|
97
|
+
provider: string;
|
|
98
|
+
/** Unique per checkout: Stripe's session id, or the reference Payments made for the others. */
|
|
99
|
+
sessionId: string;
|
|
100
|
+
/** The provider's id for the payment, which its refunds name. */
|
|
101
|
+
paymentRef: string | null;
|
|
102
|
+
metadata: Record<string, unknown> | null | undefined;
|
|
103
|
+
/** In the currency's smallest unit. */
|
|
104
|
+
amount: number;
|
|
105
|
+
currency: string;
|
|
106
|
+
/**
|
|
107
|
+
* Only for a provider whose better-auth plugin can't create one-time checkouts, so every
|
|
108
|
+
* checkout with Payments' metadata was created by Payments with the secret key, as with
|
|
109
|
+
* Stripe. Otherwise the checkout must be one Payments started and remembered.
|
|
110
|
+
*/
|
|
111
|
+
metadataTrusted?: boolean;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Records a paid checkout. Providers may send the event more than once, and the session id
|
|
115
|
+
* is unique, so a repeat changes nothing. The checkout must be one Payments started for
|
|
116
|
+
* this buyer and record, as most providers' better-auth plugins can create checkouts with
|
|
117
|
+
* metadata of the caller's choosing, so metadata alone proves nothing.
|
|
118
|
+
*/
|
|
119
|
+
export declare function recordPurchase(context: ExtensionContext, paid: PaidCheckout): Promise<boolean>;
|
|
120
|
+
/** A full refund takes the purchase back. Partial refunds leave it, as the buyer still paid for it. */
|
|
121
|
+
export declare function recordRefund(context: ExtensionContext, by: {
|
|
122
|
+
sessionId?: string | null;
|
|
123
|
+
paymentRef?: string | null;
|
|
124
|
+
}): Promise<void>;
|
|
125
|
+
/** The purchase of a checkout, for one buyer. */
|
|
126
|
+
export declare function purchaseOf(context: ExtensionContext, sessionId: string, buyer: string): Promise<import("tansy/plugin").RecordValues>;
|
|
127
|
+
export interface MembershipUpdate {
|
|
128
|
+
provider: string;
|
|
129
|
+
subscriptionId: string;
|
|
130
|
+
user: string | null;
|
|
131
|
+
/** The provider's product or plan id, matched against the plans collection. */
|
|
132
|
+
productId: string | null;
|
|
133
|
+
status: string;
|
|
134
|
+
periodEnd?: string | Date | null;
|
|
135
|
+
/** When the provider says this happened. An older event never overwrites a newer one. */
|
|
136
|
+
at: number;
|
|
137
|
+
}
|
|
138
|
+
/** Keeps one record per subscription with a provider other than Stripe. Webhooks repeat and arrive out of order, so this is idempotent and ignores stale events. */
|
|
139
|
+
export declare function upsertMembership(context: ExtensionContext, update: MembershipUpdate, plans: PlanRef[]): Promise<void>;
|
|
140
|
+
/**
|
|
141
|
+
* Where a provider's better-auth plugin keeps subscriptions itself, as Stripe's does, in the
|
|
142
|
+
* collection core makes for its table. Field names are the collection's.
|
|
143
|
+
*/
|
|
144
|
+
export interface SubscriptionRecords {
|
|
145
|
+
collection: string;
|
|
146
|
+
user: string;
|
|
147
|
+
plan: string;
|
|
148
|
+
state: string;
|
|
149
|
+
}
|
|
150
|
+
/** Plan names are lowercase words, so they're safe inside a filter's quotes. */
|
|
151
|
+
export declare const PLAN_NAME: RegExp;
|
|
152
|
+
/**
|
|
153
|
+
* Keeps each person's plans and access in step with their subscriptions, with any installed
|
|
154
|
+
* provider, so rules can gate on them: `payments_plan` and `payments_access` on the user, and
|
|
155
|
+
* their `payments-entitlements` record, which other plugins' hooks can follow. Runs as a
|
|
156
|
+
* durable hook, so a failure is retried. Changing a plan or an access updates everyone it
|
|
157
|
+
* reaches.
|
|
158
|
+
*/
|
|
159
|
+
export declare function accessSync(kept: SubscriptionRecords[]): (context: AfterHookContext) => Promise<void>;
|
package/shared.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { accessOf, ACTIVE_STATES, fromMinorUnits, isSlug, isUserId, membershipState, referenceIds, toPlanRef } from "./logic";
|
|
3
|
+
/** What every provider shares: the plugin's collections, settings, and the records it keeps. */
|
|
4
|
+
export const PLANS = "payments-plans";
|
|
5
|
+
export const PURCHASES = "payments-purchases";
|
|
6
|
+
/** Subscriptions with providers whose better-auth plugins keep none (all but Stripe), from their webhooks. */
|
|
7
|
+
export const MEMBERSHIPS = "payments-memberships";
|
|
8
|
+
/** Kept by better-auth's payment plugins: each user's customer id with the provider. */
|
|
9
|
+
export const CUSTOMERS = "payments-user-data";
|
|
10
|
+
/** The user field rules gate on, such as `@request.auth.payments_plan = "pro"`. */
|
|
11
|
+
export const PLAN_FIELD = "payments_plan";
|
|
12
|
+
/** What plans open, kept by the owner: whole collections, and records "Included in" it. */
|
|
13
|
+
export const ACCESS = "payments-access";
|
|
14
|
+
/** One record per person: their active plans, and the access those include. */
|
|
15
|
+
export const ENTITLEMENTS = "payments-entitlements";
|
|
16
|
+
/** The user field rules gate access on: `included ?= @request.auth.payments_access`. */
|
|
17
|
+
export const ACCESS_FIELD = "payments_access";
|
|
18
|
+
export const PRICE_TYPE = "payments_price";
|
|
19
|
+
/**
|
|
20
|
+
* What a pricing page shows about a plan. The provider charges the price set with it, so
|
|
21
|
+
* these are for people to read, and never decide what anyone pays.
|
|
22
|
+
*/
|
|
23
|
+
export const PLAN_DISPLAY_FIELDS = [
|
|
24
|
+
{ name: "title", type: "text", config: { maxLength: 80, description: "As a pricing page shows it, such as All courses. Empty shows the name." } },
|
|
25
|
+
{ name: "description", type: "text", config: { multiline: true, maxLength: 500, description: "A line or two for a pricing page." } },
|
|
26
|
+
{ name: "amount", type: "number", config: { min: 0, description: "The monthly price a pricing page shows. The provider charges the price set with it, so keep them the same." } },
|
|
27
|
+
{ name: "annualAmount", type: "number", config: { min: 0, description: "Optional, for a plan with a yearly price." } },
|
|
28
|
+
{ name: "currency", type: "text", config: { maxLength: 3, description: "Three letters, such as usd. Empty takes the currency from Payments' settings." } },
|
|
29
|
+
{ name: "featured", type: "boolean", config: { description: "A pricing page makes it stand out." } },
|
|
30
|
+
];
|
|
31
|
+
export const settingsOf = async (context) => (await context.settings.get());
|
|
32
|
+
export const str = (value) => (typeof value === "string" ? value : "");
|
|
33
|
+
export const refuse = (status, code, message) => Response.json({ error: { code, message } }, { status });
|
|
34
|
+
/** Plan records as providers that sell plans as products take them. */
|
|
35
|
+
export async function loadPlanRefs(context) {
|
|
36
|
+
const { items } = await context.system.records.list(PLANS, { filter: 'status = "published"', perPage: 200, fields: "name,priceId,annualPriceId" });
|
|
37
|
+
return items.map(toPlanRef).filter((plan) => plan !== null);
|
|
38
|
+
}
|
|
39
|
+
/** Has this user already bought this record? */
|
|
40
|
+
export async function owns(context, buyer, collection, recordId) {
|
|
41
|
+
const { items } = await context.system.records.list(PURCHASES, { filter: `buyer = "${buyer}" && collection = "${collection}" && recordId = ${recordId} && state = "paid"`, perPage: 1, fields: "id" });
|
|
42
|
+
return items.length > 0;
|
|
43
|
+
}
|
|
44
|
+
export const newReference = () => `ref_${randomBytes(16).toString("hex")}`;
|
|
45
|
+
const checkoutKey = (ref) => `checkout:${ref}`;
|
|
46
|
+
export const rememberCheckout = (context, ref, checkout) => context.store.set(checkoutKey(ref), checkout);
|
|
47
|
+
export async function startedCheckout(context, ref) {
|
|
48
|
+
if (typeof ref !== "string" || !ref.startsWith("ref_"))
|
|
49
|
+
return null;
|
|
50
|
+
const value = (await context.store.get(checkoutKey(ref)));
|
|
51
|
+
return value && typeof value.id === "string" && isUserId(value.userId) ? value : null;
|
|
52
|
+
}
|
|
53
|
+
/** Checkouts nobody finished are forgotten after this. Bank payments can take days, so it's generous. */
|
|
54
|
+
const CHECKOUT_TTL = 30 * 24 * 3600 * 1000;
|
|
55
|
+
export async function forgetOldCheckouts(context) {
|
|
56
|
+
for (const { key, value } of await context.store.list("checkout:")) {
|
|
57
|
+
if (Date.now() - (value?.at ?? 0) > CHECKOUT_TTL)
|
|
58
|
+
await context.store.delete(key);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const isDuplicate = (error) => {
|
|
62
|
+
const { code, details } = error;
|
|
63
|
+
return code === "VALIDATION_FAILED" && Array.isArray(details) && details.some((detail) => detail.path === "sessionId");
|
|
64
|
+
};
|
|
65
|
+
const safeId = (value) => value.replace(/[^A-Za-z0-9_-]/g, "");
|
|
66
|
+
/**
|
|
67
|
+
* Records a paid checkout. Providers may send the event more than once, and the session id
|
|
68
|
+
* is unique, so a repeat changes nothing. The checkout must be one Payments started for
|
|
69
|
+
* this buyer and record, as most providers' better-auth plugins can create checkouts with
|
|
70
|
+
* metadata of the caller's choosing, so metadata alone proves nothing.
|
|
71
|
+
*/
|
|
72
|
+
export async function recordPurchase(context, paid) {
|
|
73
|
+
const meta = paid.metadata ?? {};
|
|
74
|
+
if (meta.tansy !== "purchase" || !isSlug(meta.collection) || !isUserId(meta.userId))
|
|
75
|
+
return false;
|
|
76
|
+
const recordId = Number(meta.recordId);
|
|
77
|
+
if (!Number.isSafeInteger(recordId) || recordId <= 0)
|
|
78
|
+
return false;
|
|
79
|
+
if (!paid.metadataTrusted) {
|
|
80
|
+
const started = await startedCheckout(context, meta.ref);
|
|
81
|
+
if (!started || started.userId !== meta.userId || started.collection !== meta.collection || started.recordId !== recordId || paid.sessionId !== meta.ref)
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
const { items } = await context.system.records.list(PURCHASES, { filter: `sessionId = "${safeId(paid.sessionId)}"`, perPage: 1, fields: "id" });
|
|
85
|
+
if (items.length)
|
|
86
|
+
return true;
|
|
87
|
+
const currency = paid.currency.toLowerCase();
|
|
88
|
+
const buyer = await context.system.users.get(meta.userId);
|
|
89
|
+
try {
|
|
90
|
+
await context.system.records.create(PURCHASES, {
|
|
91
|
+
status: "published",
|
|
92
|
+
buyer: meta.userId,
|
|
93
|
+
collection: meta.collection,
|
|
94
|
+
recordId,
|
|
95
|
+
amount: fromMinorUnits(paid.amount, currency),
|
|
96
|
+
currency,
|
|
97
|
+
sessionId: paid.sessionId,
|
|
98
|
+
paymentIntent: paid.paymentRef,
|
|
99
|
+
state: "paid",
|
|
100
|
+
provider: paid.provider,
|
|
101
|
+
}, buyer ? { owner: buyer.id } : undefined);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
if (!isDuplicate(error))
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
/** A full refund takes the purchase back. Partial refunds leave it, as the buyer still paid for it. */
|
|
110
|
+
export async function recordRefund(context, by) {
|
|
111
|
+
const filters = [
|
|
112
|
+
...(by.sessionId ? [`sessionId = "${safeId(by.sessionId)}"`] : []),
|
|
113
|
+
...(by.paymentRef ? [`paymentIntent = "${safeId(by.paymentRef)}"`] : []),
|
|
114
|
+
];
|
|
115
|
+
if (!filters.length)
|
|
116
|
+
return;
|
|
117
|
+
const { items } = await context.system.records.list(PURCHASES, { filter: filters.join(" || "), perPage: 10, fields: "id,state" });
|
|
118
|
+
for (const purchase of items)
|
|
119
|
+
if (purchase.state !== "refunded")
|
|
120
|
+
await context.system.records.update(PURCHASES, purchase.id, { state: "refunded" });
|
|
121
|
+
}
|
|
122
|
+
/** The purchase of a checkout, for one buyer. */
|
|
123
|
+
export async function purchaseOf(context, sessionId, buyer) {
|
|
124
|
+
const { items } = await context.system.records.list(PURCHASES, { filter: `sessionId = "${safeId(sessionId)}" && buyer = "${buyer}"`, perPage: 1, fields: "id,state,collection,recordId" });
|
|
125
|
+
return items[0] ?? null;
|
|
126
|
+
}
|
|
127
|
+
/** Keeps one record per subscription with a provider other than Stripe. Webhooks repeat and arrive out of order, so this is idempotent and ignores stale events. */
|
|
128
|
+
export async function upsertMembership(context, update, plans) {
|
|
129
|
+
if (!update.subscriptionId)
|
|
130
|
+
return;
|
|
131
|
+
const id = safeId(update.subscriptionId);
|
|
132
|
+
const { items } = await context.system.records.list(MEMBERSHIPS, { filter: `subscriptionId = "${id}"`, perPage: 1, fields: "id,user,eventAt,plan" });
|
|
133
|
+
const existing = items[0];
|
|
134
|
+
if (existing && typeof existing.eventAt === "number" && existing.eventAt > update.at)
|
|
135
|
+
return;
|
|
136
|
+
const user = isUserId(update.user) ? update.user : str(existing?.user);
|
|
137
|
+
// A subscription nobody here can be matched to changes no one's plan.
|
|
138
|
+
if (!user || !(await context.system.users.get(user)))
|
|
139
|
+
return;
|
|
140
|
+
const named = update.productId ? plans.find((plan) => plan.productId === update.productId || plan.annualProductId === update.productId)?.name : undefined;
|
|
141
|
+
const periodEnd = update.periodEnd ? new Date(update.periodEnd) : null;
|
|
142
|
+
const values = {
|
|
143
|
+
provider: update.provider,
|
|
144
|
+
user,
|
|
145
|
+
plan: named ?? str(existing?.plan),
|
|
146
|
+
state: membershipState(update.status),
|
|
147
|
+
periodEnd: periodEnd && !Number.isNaN(periodEnd.getTime()) ? periodEnd.toISOString() : null,
|
|
148
|
+
eventAt: update.at,
|
|
149
|
+
};
|
|
150
|
+
if (existing) {
|
|
151
|
+
await context.system.records.update(MEMBERSHIPS, existing.id, values);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
await context.system.records.create(MEMBERSHIPS, { status: "published", subscriptionId: update.subscriptionId, ...values });
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
const { code, details } = error;
|
|
159
|
+
// Another delivery created it first: apply this one on top, still newest-wins.
|
|
160
|
+
if (code === "VALIDATION_FAILED" && details?.some((detail) => detail.path === "subscriptionId"))
|
|
161
|
+
return upsertMembership(context, update, plans);
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** Payments' own memberships, kept for providers whose plugins keep none. */
|
|
166
|
+
const OWN = { collection: MEMBERSHIPS, user: "user", plan: "plan", state: "state" };
|
|
167
|
+
/** Plan names are lowercase words, so they're safe inside a filter's quotes. */
|
|
168
|
+
export const PLAN_NAME = /^[a-z0-9][a-z0-9 _.-]{0,59}$/;
|
|
169
|
+
const anyOf = (field, values) => values.map((value) => `${field} = ${typeof value === "number" ? value : `"${value}"`}`).join(" || ");
|
|
170
|
+
async function listAll(context, slug, query) {
|
|
171
|
+
const items = [];
|
|
172
|
+
for (let page = 1;; page++) {
|
|
173
|
+
const result = await context.system.records.list(slug, { ...query, page, perPage: 200 });
|
|
174
|
+
items.push(...result.items);
|
|
175
|
+
if (page >= (result.totalPages ?? 1) || !result.items.length)
|
|
176
|
+
return items;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/** Lists of up to 50, so a filter stays short. */
|
|
180
|
+
const chunks = (list, size = 50) => Array.from({ length: Math.ceil(list.length / size) }, (_, index) => list.slice(index * size, (index + 1) * size));
|
|
181
|
+
/**
|
|
182
|
+
* Keeps each person's plans and access in step with their subscriptions, with any installed
|
|
183
|
+
* provider, so rules can gate on them: `payments_plan` and `payments_access` on the user, and
|
|
184
|
+
* their `payments-entitlements` record, which other plugins' hooks can follow. Runs as a
|
|
185
|
+
* durable hook, so a failure is retried. Changing a plan or an access updates everyone it
|
|
186
|
+
* reaches.
|
|
187
|
+
*/
|
|
188
|
+
export function accessSync(kept) {
|
|
189
|
+
const sources = [OWN, ...kept];
|
|
190
|
+
return async (context) => {
|
|
191
|
+
const slug = context.collection.slug;
|
|
192
|
+
const source = sources.find((candidate) => candidate.collection === slug);
|
|
193
|
+
let users;
|
|
194
|
+
if (source)
|
|
195
|
+
users = new Set([context.record[source.user], context.previous?.[source.user]]);
|
|
196
|
+
else if (slug === PLANS)
|
|
197
|
+
users = await subscribersOf(context, sources, [context.record.name, context.previous?.name]);
|
|
198
|
+
else if (slug === ACCESS)
|
|
199
|
+
users = await reachedByAccess(context, sources, context.record.id);
|
|
200
|
+
else
|
|
201
|
+
return;
|
|
202
|
+
for (const userId of users) {
|
|
203
|
+
// A subscription can belong to an organization instead, which has no user fields.
|
|
204
|
+
if (!isUserId(userId) || !(await context.system.users.get(userId)))
|
|
205
|
+
continue;
|
|
206
|
+
await syncUser(context, sources, userId);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/** Everyone subscribed to these plans, in any state, and everyone whose access still names them. */
|
|
211
|
+
async function subscribersOf(context, sources, names) {
|
|
212
|
+
const plans = [...new Set(names.filter((name) => typeof name === "string" && PLAN_NAME.test(name)))];
|
|
213
|
+
const users = new Set();
|
|
214
|
+
if (!plans.length)
|
|
215
|
+
return users;
|
|
216
|
+
for (const source of sources) {
|
|
217
|
+
// A provider that isn't set up yet has no collection.
|
|
218
|
+
const items = await listAll(context, source.collection, { filter: anyOf(source.plan, plans), fields: source.user }).catch(() => []);
|
|
219
|
+
for (const item of items)
|
|
220
|
+
users.add(item[source.user]);
|
|
221
|
+
}
|
|
222
|
+
for (const plan of plans) {
|
|
223
|
+
for (const item of await listAll(context, ENTITLEMENTS, { filter: `plans ?= "${plan}"`, fields: "user" }))
|
|
224
|
+
users.add(item.user);
|
|
225
|
+
}
|
|
226
|
+
return users;
|
|
227
|
+
}
|
|
228
|
+
/** Everyone on a plan that includes this access, and everyone who still has it, such as after it was deleted. */
|
|
229
|
+
async function reachedByAccess(context, sources, id) {
|
|
230
|
+
if (typeof id !== "number")
|
|
231
|
+
return new Set();
|
|
232
|
+
const plans = await listAll(context, PLANS, { filter: `includes ?= ${id}`, fields: "name" });
|
|
233
|
+
const users = await subscribersOf(context, sources, plans.map((plan) => plan.name));
|
|
234
|
+
for (const item of await listAll(context, ENTITLEMENTS, { filter: `access ?= ${id}`, fields: "user" }))
|
|
235
|
+
users.add(item.user);
|
|
236
|
+
return users;
|
|
237
|
+
}
|
|
238
|
+
/** The names of every plan this person's active subscriptions are on, in the order the sources list them. */
|
|
239
|
+
async function activePlans(context, sources, userId) {
|
|
240
|
+
const lists = await Promise.all(sources.map((source) => context.system.records
|
|
241
|
+
.list(source.collection, { filter: `${source.user} = "${userId}"`, perPage: 50, fields: `${source.plan},${source.state}` })
|
|
242
|
+
.then(({ items }) => items.map((item) => ({ plan: item[source.plan], state: item[source.state] })))
|
|
243
|
+
// A provider that isn't set up yet has no collection.
|
|
244
|
+
.catch(() => [])));
|
|
245
|
+
const names = lists.flat().filter((subscription) => ACTIVE_STATES.has(str(subscription.state)) && PLAN_NAME.test(str(subscription.plan))).map((subscription) => str(subscription.plan));
|
|
246
|
+
return [...new Set(names)].slice(0, 20);
|
|
247
|
+
}
|
|
248
|
+
/** Works out one person's plans and access from their subscriptions as they are now, and stores them. */
|
|
249
|
+
async function syncUser(context, sources, userId) {
|
|
250
|
+
const plans = await activePlans(context, sources, userId);
|
|
251
|
+
// Every plan with the name, published or not: someone still paying for a plan taken off the pricing page keeps what it includes.
|
|
252
|
+
const planRecords = plans.length ? await listAll(context, PLANS, { filter: anyOf("name", plans), fields: "name,includes" }) : [];
|
|
253
|
+
const included = planRecords.map((plan) => ({ name: str(plan.name), includes: referenceIds(plan.includes) }));
|
|
254
|
+
const ids = [...new Set(included.flatMap((plan) => plan.includes))];
|
|
255
|
+
const grants = [];
|
|
256
|
+
for (const chunk of chunks(ids)) {
|
|
257
|
+
for (const item of await listAll(context, ACCESS, { filter: anyOf("id", chunk), fields: "id,collections" })) {
|
|
258
|
+
grants.push({ id: item.id, collections: Array.isArray(item.collections) ? item.collections.filter(isSlug) : [] });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const access = accessOf(plans, included, grants);
|
|
262
|
+
await keepEntitlements(context, userId, plans, access);
|
|
263
|
+
await context.system.users.setValues(userId, { [PLAN_FIELD]: plans[0] ?? null, [ACCESS_FIELD]: access });
|
|
264
|
+
}
|
|
265
|
+
/** One record per person, written only when it changes, so hooks following it see real changes only. */
|
|
266
|
+
async function keepEntitlements(context, userId, plans, access) {
|
|
267
|
+
const { items } = await context.system.records.list(ENTITLEMENTS, { filter: `user = "${userId}"`, perPage: 1, fields: "id,plans,access" });
|
|
268
|
+
const existing = items[0];
|
|
269
|
+
if (existing) {
|
|
270
|
+
if (JSON.stringify(existing.plans) === JSON.stringify(plans) && JSON.stringify(existing.access) === JSON.stringify(access))
|
|
271
|
+
return;
|
|
272
|
+
await context.system.records.update(ENTITLEMENTS, existing.id, { plans, access });
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
// Nothing to keep for someone who never had a plan.
|
|
276
|
+
if (!plans.length && !access.length)
|
|
277
|
+
return;
|
|
278
|
+
const user = await context.system.users.get(userId);
|
|
279
|
+
try {
|
|
280
|
+
await context.system.records.create(ENTITLEMENTS, { status: "published", user: userId, plans, access }, user ? { owner: user.id } : undefined);
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
const { code, details } = error;
|
|
284
|
+
// Another delivery made it first: write this one over it.
|
|
285
|
+
if (code === "VALIDATION_FAILED" && details?.some((detail) => detail.path === "user"))
|
|
286
|
+
return keepEntitlements(context, userId, plans, access);
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
}
|
package/site-messages.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** What visitors read on Payments' buttons, as `t("payments.<key>")`. Themes and owners can word any of it differently. */
|
|
2
|
+
export const siteMessages = {
|
|
3
|
+
en: {
|
|
4
|
+
payments: {
|
|
5
|
+
buy: "Buy",
|
|
6
|
+
subscribe: "Subscribe",
|
|
7
|
+
billing: "Manage billing",
|
|
8
|
+
opening: "Opening checkout…",
|
|
9
|
+
openingBilling: "Opening…",
|
|
10
|
+
checkoutFailed: "The checkout couldn't start.",
|
|
11
|
+
subscribeFailed: "The subscription couldn't start.",
|
|
12
|
+
billingFailed: "The billing page couldn't open.",
|
|
13
|
+
offline: "{problem} Check your connection and try again.",
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
ar: {
|
|
17
|
+
payments: {
|
|
18
|
+
buy: "شراء",
|
|
19
|
+
subscribe: "اشترك",
|
|
20
|
+
billing: "إدارة الفوترة",
|
|
21
|
+
opening: "جارٍ فتح صفحة الدفع…",
|
|
22
|
+
openingBilling: "جارٍ الفتح…",
|
|
23
|
+
checkoutFailed: "تعذّر بدء الدفع.",
|
|
24
|
+
subscribeFailed: "تعذّر بدء الاشتراك.",
|
|
25
|
+
billingFailed: "تعذّر فتح صفحة الفوترة.",
|
|
26
|
+
offline: "{problem} تحقق من اتصالك وحاول مجددًا.",
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
};
|