@extantape/payload-plugin-membership 0.0.0-stage → 0.1.3

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 EXTANT APE
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,119 @@
1
- # Temporary Holding Version
1
+ # payload-plugin-membership
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Memberships for [Payload](https://payloadcms.com), billed as Stripe subscriptions. Run it like
4
+ Patreon, or let members support **categories** with **their own amount** — or both.
5
+
6
+ - **Tiers** (Patreon-style): fixed monthly and/or yearly prices, perks, colors. Drag-and-drop order.
7
+ - **Categories**: things members can choose to support (e.g. "Turtles", "North American turtles"),
8
+ nestable, with a minimum amount and an optional **earmarked** flag (otherwise the category is the
9
+ member's preference). New categories go in A–Z; drag to reorder. Add your own fields to tie them to
10
+ anything (taxa, regions, projects…).
11
+ - **Memberships**: one running membership per member (per scope); a tier, or pledges split across
12
+ categories. Monthly or yearly. Members change, cancel (at the end of the paid period) or open Stripe's
13
+ customer portal.
14
+ - **Payments ledger**: every paid invoice recorded once (idempotent webhooks). `onPayment` runs once per
15
+ invoice: award perks, votes, credits, receipts.
16
+ - **Backers wall**: opt-in only, with the name the member chooses; listed under their tier or under each
17
+ category they support, **A–Z within each group**.
18
+ - **Works with** [`@extantape/payload-plugin-sponsors`](https://www.npmjs.com/package/@extantape/payload-plugin-sponsors):
19
+ mark a tier "Members are listed as sponsors" and call `upsertListing`/`retireListing` from `onStatusChange`.
20
+
21
+ ## On its own, and with others
22
+
23
+ **On its own.** Membership needs a Stripe account (a secret key and a webhook) and an auth collection for members. It doesn't import any other Captive Origins plugin. Perks, votes and credits are whatever your own `onPayment` and `onStatusChange` do.
24
+
25
+ **Works with:**
26
+
27
+ - **Sponsors** (`@extantape/payload-plugin-sponsors`): tick "Members are listed as sponsors" on a tier, and call Sponsors' `upsertListing()` and `retireListing()` from `onStatusChange`. Your site makes the call; neither plugin imports the other.
28
+ - **Roadmap** (`@extantape/payload-plugin-roadmap`): Roadmap's extra votes come from a number your site works out (`allocation.earned`), and a membership can be where they come from. There's no adapter for this. It's a few lines of your own code.
29
+ - **Multi-tenant** (`@payloadcms/plugin-multi-tenant`): set `scopeField` and `scopeOf`, and each site has its own tiers and members. The member endpoints answer only for the site `scopeOf` names: another site's membership, or a request from a site `scopeOf` doesn't know, gets a 404, and so does a request where `scopeOf` throws (only the error's name is logged). Managers also need the collection's read access, so the tenant plugin's rules apply to them. Pass `scope` to `getBackers`, or it lists every site.
30
+
31
+ **Family.** Membership is in the Patronage family, with Sponsors, Backing, Credits, Printify and Roadmap. Backing and Credits are named but not built yet, and the families are a working draft that may change.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ npm install @extantape/payload-plugin-membership
37
+ ```
38
+
39
+ ```ts
40
+ import { membershipPlugin } from '@extantape/payload-plugin-membership'
41
+
42
+ export default buildConfig({
43
+ plugins: [
44
+ membershipPlugin({
45
+ stripeSecretKey: process.env.STRIPE_SECRET_KEY,
46
+ webhookSecret: process.env.STRIPE_MEMBERSHIP_WEBHOOK_SECRET,
47
+ canManage: ({ req }) => req.user?.role === 'admin',
48
+ onPayment: async ({ payload, payment, membership }) => {
49
+ // e.g. thank the member, grant perks
50
+ },
51
+ }),
52
+ ],
53
+ })
54
+ ```
55
+
56
+ In Stripe, add a webhook endpoint `https://<your site>/api/memberships/stripe-webhook` for
57
+ `checkout.session.completed`, `invoice.paid`, `invoice.payment_failed`,
58
+ `customer.subscription.updated` and `customer.subscription.deleted`.
59
+
60
+ ## Endpoints (signed-in members)
61
+
62
+ | Endpoint | Body | Result |
63
+ |---|---|---|
64
+ | `POST /api/memberships/checkout` | `{ tier }` or `{ pledges: [{ category, amount }] }`, `interval` (`month`/`year`), `wall?: { show, name }`, `successPath?`, `cancelPath?` | `{ url }` of Stripe Checkout |
65
+ | `POST /api/memberships/:id/change` | `{ tier }` or `{ pledges }` | the updated membership (from the next invoice) |
66
+ | `POST /api/memberships/:id/cancel` | | cancels at the end of the paid period |
67
+ | `POST /api/memberships/:id/portal` | `{ returnPath? }` | `{ url }` of Stripe's customer portal |
68
+ | `POST /api/memberships/:id/wall` | `{ show, name }` | the member's backers-wall choice |
69
+
70
+ Amounts are in cents. Server code can call `startCheckout`, `changeMembership`, `cancelMembership`,
71
+ `portalLink`, `myMembership` and `getBackers` directly.
72
+
73
+ ## Options
74
+
75
+ | Option | Default | |
76
+ |---|---|---|
77
+ | `slugs` | `membership-tiers`, `membership-categories`, `memberships`, `membership-payments` | |
78
+ | `users` | `admin.user` | The members' auth collection |
79
+ | `canManage` | nobody | Who manages tiers, categories and memberships in the admin. Only `true` counts: see [Access](#access) |
80
+ | `canCheckout` | always | E.g. off in development. Only `true` allows a checkout |
81
+ | `stripeSecretKey` / `stripe` | | Key, or a ready client (tests) |
82
+ | `webhookSecret` | | Signing secret of the webhook endpoint |
83
+ | `currency` | `usd` | |
84
+ | `publicURL` | `serverURL` | Origin for Stripe return links |
85
+ | `scopeField` / `scopeOf` | | Multi-site: the owner field (e.g. `tenant`) and how to read it from a request |
86
+ | `onPayment` | | Once per paid invoice |
87
+ | `onStatusChange` | | When a membership's status changes |
88
+ | `overrides` | | Adjust the generated collections |
89
+
90
+ ## Access
91
+
92
+ `canManage` decides everything a manager can do, and only an answer of exactly `true` counts.
93
+ Anything else is a no: `false`, `1`, `'yes'`, an object, or an error thrown or rejected. An error
94
+ doesn't escape as a 500; the request is refused. Nobody who isn't signed in is a manager, whatever
95
+ `canManage` says.
96
+
97
+ | Where | A manager | A signed-in member | Signed out |
98
+ |---|---|---|---|
99
+ | Tiers, categories | Reads, creates, edits, deletes | Reads | Reads |
100
+ | Their `stripeProduct` (field) | Reads and writes | Never sees it | Never sees it |
101
+ | Memberships | Reads all, edits, deletes | Reads their own | Nothing |
102
+ | A membership's `stripe` and `notes` (fields) | Reads and writes | Never sees them | Nothing |
103
+ | Payments | Reads all, deletes | Reads their own | Nothing |
104
+ | `change`, `cancel`, `portal`, `wall` endpoints | Any membership on their site | Their own | 404 |
105
+
106
+ Nobody creates memberships or payments directly: checkout and Stripe do. The member endpoints answer
107
+ 404, not 403, to anyone who may not use them, so they don't say whether a membership exists.
108
+
109
+ Memberships' and payments' read access returns a query for members: the plugin's own "your rows"
110
+ filter. What `canManage` returns is never passed to Payload, so an object that looks like a query
111
+ can't widen it to every row. `canCheckout` follows the same rule: only `true` lets a checkout start,
112
+ and anything else, an error included, refuses it with "Memberships are not available here yet."
113
+ (503).
114
+
115
+ `overrides` can change a collection's `access`; if you do, your rules replace these.
116
+
117
+ ## License
118
+
119
+ MIT
@@ -0,0 +1,8 @@
1
+ import type { Payload, PayloadRequest } from 'payload';
2
+ import type { ResolvedMembership } from './types.js';
3
+ /** Only an answer of exactly `true` passes; anything else, a thrown error included, is no. */
4
+ export declare function exactlyTrue(check: () => unknown): Promise<boolean>;
5
+ /** A signed-in manager: `canManage` answered exactly `true` (a truthy value or an error is a no). */
6
+ export declare const isManager: (o: Pick<ResolvedMembership, "canManage">, req: PayloadRequest) => Promise<boolean>;
7
+ /** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
8
+ export declare const checkoutAllowed: (o: Pick<ResolvedMembership, "canCheckout">, payload: Payload) => Promise<boolean>;
package/dist/access.js ADDED
@@ -0,0 +1,13 @@
1
+ /** Only an answer of exactly `true` passes; anything else, a thrown error included, is no. */
2
+ export async function exactlyTrue(check) {
3
+ try {
4
+ return (await check()) === true;
5
+ }
6
+ catch {
7
+ return false;
8
+ }
9
+ }
10
+ /** A signed-in manager: `canManage` answered exactly `true` (a truthy value or an error is a no). */
11
+ export const isManager = (o, req) => req.user ? exactlyTrue(() => o.canManage({ req })) : Promise.resolve(false);
12
+ /** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
13
+ export const checkoutAllowed = (o, payload) => o.canCheckout ? exactlyTrue(() => o.canCheckout({ payload })) : Promise.resolve(true);
package/dist/api.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { type Payload } from 'payload';
2
+ import type { Interval, ResolvedMembership, StripeEvent } from './types.js';
3
+ type Doc = Record<string, any>;
4
+ export declare const membershipOf: (payload: Payload) => ResolvedMembership;
5
+ /** What a member chooses: a tier, or amounts (cents per interval) for categories. */
6
+ export type Choice = {
7
+ tier?: string | null;
8
+ pledges?: {
9
+ category: string;
10
+ amount: number;
11
+ }[] | null;
12
+ interval: Interval;
13
+ };
14
+ /**
15
+ * Starts a membership: validates the choice, records it as pending and opens
16
+ * Stripe Checkout (a subscription with the member's own amounts). Returns the
17
+ * Checkout URL; the webhook activates it once Stripe confirms.
18
+ */
19
+ export declare function startCheckout(payload: Payload, args: Choice & {
20
+ user: Doc;
21
+ successURL: string;
22
+ cancelURL: string;
23
+ scope?: string | null;
24
+ wall?: {
25
+ show?: boolean;
26
+ name?: string | null;
27
+ };
28
+ }): Promise<{
29
+ url: string;
30
+ membership: string;
31
+ }>;
32
+ /** Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice). */
33
+ export declare function changeMembership(payload: Payload, membershipId: string, choice: Omit<Choice, 'interval'>): Promise<Doc>;
34
+ /** Cancels at the end of the paid period (the member keeps their perks until then). */
35
+ export declare function cancelMembership(payload: Payload, membershipId: string): Promise<Doc>;
36
+ /** Stripe's customer portal (payment method, invoices, cancel). */
37
+ export declare function portalLink(payload: Payload, membershipId: string, returnURL: string): Promise<string>;
38
+ /**
39
+ * Applies one Stripe webhook event. Safe to receive twice: payments are keyed
40
+ * by invoice, and status updates are idempotent.
41
+ */
42
+ export declare function handleStripeEvent(payload: Payload, event: StripeEvent): Promise<'handled' | 'ignored'>;
43
+ export type Backer = {
44
+ name: string;
45
+ since: string | null;
46
+ };
47
+ export type BackerGroup<T> = {
48
+ group: T;
49
+ backers: Backer[];
50
+ };
51
+ /**
52
+ * The backers wall: active members who chose to be shown, under their tier or
53
+ * under each category they support, A–Z within each (user decision for
54
+ * Captive Origins). Groups follow the admin's (drag-and-drop) order.
55
+ */
56
+ export declare function getBackers(payload: Payload, opts?: {
57
+ scope?: string | null;
58
+ locale?: string;
59
+ }): Promise<{
60
+ tiers: BackerGroup<Doc>[];
61
+ categories: BackerGroup<Doc>[];
62
+ }>;
63
+ /** The signed-in member's current membership in a scope (for account pages). */
64
+ export declare function myMembership(payload: Payload, userId: string, scope?: string | null): Promise<Doc | null>;
65
+ export {};
package/dist/api.js ADDED
@@ -0,0 +1,319 @@
1
+ import { APIError } from 'payload';
2
+ import { checkoutAllowed } from './access.js';
3
+ const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
4
+ const ctx = { membershipSync: true };
5
+ export const membershipOf = (payload) => payload.config.custom?.membership;
6
+ const stripeOf = (o) => {
7
+ const s = o.stripe();
8
+ if (!s)
9
+ throw new APIError('Memberships are not available here yet.', 503, undefined, true);
10
+ return s;
11
+ };
12
+ /** Validates a choice and turns it into priced lines (creating Stripe products on first use). */
13
+ async function linesFor(payload, o, choice, scope) {
14
+ if (choice.interval !== 'month' && choice.interval !== 'year')
15
+ throw new APIError('Choose monthly or yearly.', 400, undefined, true);
16
+ const inScope = (d) => !o.scopeField || !scope || idOf(d[o.scopeField]) === scope;
17
+ if (choice.tier) {
18
+ const tier = (await payload.findByID({ collection: o.tiers, id: choice.tier, depth: 0, overrideAccess: true, disableErrors: true }));
19
+ const price = tier?.[choice.interval === 'month' ? 'monthly' : 'yearly'];
20
+ if (!tier || !tier.active || !inScope(tier) || !(price > 0))
21
+ throw new APIError('That tier isn’t available.', 400, undefined, true);
22
+ return { kind: 'tier', tier, pledges: [], lines: [{ product: await productFor(payload, o, o.tiers, tier), name: tier.name, amount: Math.round(price) }] };
23
+ }
24
+ const pledges = (choice.pledges ?? []).filter((p) => p && p.category && Number(p.amount) > 0).map((p) => ({ category: String(p.category), amount: Math.round(Number(p.amount)) }));
25
+ if (pledges.length === 0)
26
+ throw new APIError('Choose a tier, or at least one category with an amount.', 400, undefined, true);
27
+ if (pledges.length > 20)
28
+ throw new APIError('Choose at most 20 categories.', 400, undefined, true);
29
+ if (new Set(pledges.map((p) => p.category)).size !== pledges.length)
30
+ throw new APIError('Each category once, please.', 400, undefined, true);
31
+ const lines = [];
32
+ for (const p of pledges) {
33
+ const cat = (await payload.findByID({ collection: o.categories, id: p.category, depth: 0, overrideAccess: true, disableErrors: true }));
34
+ if (!cat || !cat.active || !inScope(cat))
35
+ throw new APIError('One of those categories isn’t available.', 400, undefined, true);
36
+ const minimum = (Number(cat.minimum) || 0) * (choice.interval === 'year' ? 12 : 1);
37
+ if (p.amount < Math.max(minimum, 50))
38
+ throw new APIError(`The minimum for ${cat.name} is ${(Math.max(minimum, 50) / 100).toFixed(2)}.`, 400, undefined, true);
39
+ lines.push({ product: await productFor(payload, o, o.categories, cat), name: cat.name, amount: p.amount });
40
+ }
41
+ return { kind: 'pledge', tier: null, pledges, lines };
42
+ }
43
+ async function productFor(payload, o, slug, doc) {
44
+ if (doc.stripeProduct)
45
+ return doc.stripeProduct;
46
+ const product = await stripeOf(o).products.create({ name: doc.name, metadata: { payloadCollection: slug, payloadId: String(doc.id) } });
47
+ await payload.update({ collection: slug, id: doc.id, data: { stripeProduct: product.id }, overrideAccess: true, context: ctx });
48
+ return product.id;
49
+ }
50
+ const priceData = (o, line, interval) => ({
51
+ currency: o.currency,
52
+ product: line.product,
53
+ unit_amount: line.amount,
54
+ recurring: { interval },
55
+ });
56
+ const labelOf = (user, kind, tier, lines) => `${user.name || user.email || 'Member'} · ${kind === 'tier' ? tier.name : lines.map((l) => l.name).join(', ')}`.slice(0, 200);
57
+ /** Members in good standing (or still paying) block a second membership in the same scope. */
58
+ async function currentMembership(payload, o, userId, scope) {
59
+ const where = { and: [{ user: { equals: userId } }, { status: { in: ['active', 'past_due', 'incomplete'] } }, ...(o.scopeField && scope ? [{ [o.scopeField]: { equals: scope } }] : [])] };
60
+ return (await payload.find({ collection: o.memberships, where, limit: 1, depth: 0, overrideAccess: true })).docs[0];
61
+ }
62
+ /**
63
+ * Starts a membership: validates the choice, records it as pending and opens
64
+ * Stripe Checkout (a subscription with the member's own amounts). Returns the
65
+ * Checkout URL; the webhook activates it once Stripe confirms.
66
+ */
67
+ export async function startCheckout(payload, args) {
68
+ const o = membershipOf(payload);
69
+ if (!(await checkoutAllowed(o, payload)))
70
+ throw new APIError('Memberships are not available here yet.', 503, undefined, true);
71
+ const stripe = stripeOf(o);
72
+ const scope = args.scope ?? null;
73
+ if (await currentMembership(payload, o, String(args.user.id), scope))
74
+ throw new APIError('You already have a membership: change it instead.', 409, undefined, true);
75
+ const { kind, lines, tier, pledges } = await linesFor(payload, o, args, scope);
76
+ const previous = (await payload.find({ collection: o.memberships, where: { and: [{ user: { equals: args.user.id } }, { 'stripe.customer': { exists: true } }] }, sort: '-createdAt', limit: 1, depth: 0, overrideAccess: true })).docs[0];
77
+ const membership = (await payload.create({
78
+ collection: o.memberships,
79
+ data: {
80
+ label: labelOf(args.user, kind, tier, lines),
81
+ user: args.user.id,
82
+ kind,
83
+ tier: tier ? tier.id : null,
84
+ pledges,
85
+ interval: args.interval,
86
+ amount: lines.reduce((sum, l) => sum + l.amount, 0),
87
+ currency: o.currency,
88
+ status: 'pending',
89
+ wall: { show: Boolean(args.wall?.show), name: args.wall?.name?.trim().slice(0, 80) || null },
90
+ ...(o.scopeField && scope ? { [o.scopeField]: scope } : {}),
91
+ },
92
+ overrideAccess: true,
93
+ context: ctx,
94
+ }));
95
+ const session = await stripe.checkout.sessions.create({
96
+ mode: 'subscription',
97
+ line_items: lines.map((l) => ({ quantity: 1, price_data: priceData(o, l, args.interval) })),
98
+ ...(previous?.stripe?.customer ? { customer: previous.stripe.customer } : { customer_email: args.user.email }),
99
+ client_reference_id: String(membership.id),
100
+ metadata: { membership: String(membership.id) },
101
+ subscription_data: { metadata: { membership: String(membership.id) } },
102
+ success_url: args.successURL,
103
+ cancel_url: args.cancelURL,
104
+ });
105
+ await payload.update({ collection: o.memberships, id: membership.id, data: { stripe: { checkoutSession: session.id } }, overrideAccess: true, context: ctx });
106
+ if (!session.url)
107
+ throw new APIError('Stripe did not return a checkout page.', 502, undefined, true);
108
+ return { url: session.url, membership: String(membership.id) };
109
+ }
110
+ /** Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice). */
111
+ export async function changeMembership(payload, membershipId, choice) {
112
+ const o = membershipOf(payload);
113
+ const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 1, overrideAccess: true }));
114
+ if (!m.stripe?.subscription || !['active', 'past_due'].includes(m.status))
115
+ throw new APIError('Only a running membership can be changed.', 409, undefined, true);
116
+ const scope = o.scopeField ? idOf(m[o.scopeField]) : null;
117
+ const { kind, lines, tier, pledges } = await linesFor(payload, o, { ...choice, interval: m.interval }, scope);
118
+ const stripe = stripeOf(o);
119
+ const sub = await stripe.subscriptions.retrieve(m.stripe.subscription);
120
+ await stripe.subscriptions.update(sub.id, {
121
+ items: [...sub.items.data.map((i) => ({ id: i.id, deleted: true })), ...lines.map((l) => ({ quantity: 1, price_data: priceData(o, l, m.interval) }))],
122
+ proration_behavior: 'none',
123
+ cancel_at_period_end: false,
124
+ });
125
+ return (await payload.update({
126
+ collection: o.memberships,
127
+ id: m.id,
128
+ data: { kind, tier: tier ? tier.id : null, pledges, amount: lines.reduce((sum, l) => sum + l.amount, 0), cancelAtPeriodEnd: false, label: labelOf(typeof m.user === 'object' ? m.user : { email: '' }, kind, tier, lines) },
129
+ overrideAccess: true,
130
+ context: ctx,
131
+ }));
132
+ }
133
+ /** Cancels at the end of the paid period (the member keeps their perks until then). */
134
+ export async function cancelMembership(payload, membershipId) {
135
+ const o = membershipOf(payload);
136
+ const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 0, overrideAccess: true }));
137
+ if (!m.stripe?.subscription)
138
+ throw new APIError('This membership has no subscription to cancel.', 409, undefined, true);
139
+ await stripeOf(o).subscriptions.update(m.stripe.subscription, { cancel_at_period_end: true });
140
+ return (await payload.update({ collection: o.memberships, id: m.id, data: { cancelAtPeriodEnd: true }, overrideAccess: true, context: ctx }));
141
+ }
142
+ /** Stripe's customer portal (payment method, invoices, cancel). */
143
+ export async function portalLink(payload, membershipId, returnURL) {
144
+ const o = membershipOf(payload);
145
+ const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 0, overrideAccess: true }));
146
+ if (!m.stripe?.customer)
147
+ throw new APIError('Nothing to manage yet.', 409, undefined, true);
148
+ return (await stripeOf(o).billingPortal.sessions.create({ customer: m.stripe.customer, return_url: returnURL })).url;
149
+ }
150
+ const statusFrom = (s) => s === 'active' || s === 'trialing' ? 'active' : s === 'past_due' || s === 'unpaid' ? 'past_due' : s === 'incomplete' ? 'incomplete' : s === 'paused' ? 'past_due' : 'canceled';
151
+ const recordOf = (m) => ({
152
+ id: String(m.id),
153
+ user: String(idOf(m.user)),
154
+ kind: m.kind,
155
+ tier: idOf(m.tier),
156
+ pledges: (m.pledges ?? []).map((p) => ({ category: String(idOf(p.category)), amount: p.amount })),
157
+ interval: m.interval,
158
+ amount: m.amount,
159
+ currency: m.currency,
160
+ status: m.status,
161
+ });
162
+ async function setMembership(payload, o, m, data) {
163
+ const updated = (await payload.update({ collection: o.memberships, id: m.id, data: data, overrideAccess: true, depth: 0, context: ctx }));
164
+ if (data.status && data.status !== m.status && o.onStatusChange)
165
+ await o.onStatusChange({ payload, membership: recordOf(updated), previous: m.status ?? null });
166
+ return updated;
167
+ }
168
+ async function findBy(payload, o, where) {
169
+ return (await payload.find({ collection: o.memberships, where, limit: 1, depth: 0, overrideAccess: true })).docs[0];
170
+ }
171
+ const subscriptionIdOf = (obj) => idOf(obj.subscription) ?? idOf(obj.parent?.subscription_details?.subscription) ?? idOf(obj.lines?.data?.[0]?.parent?.subscription_item_details?.subscription) ?? null;
172
+ const periodEndOf = (sub) => sub.current_period_end ?? sub.items?.data?.[0]?.current_period_end;
173
+ /**
174
+ * Applies one Stripe webhook event. Safe to receive twice: payments are keyed
175
+ * by invoice, and status updates are idempotent.
176
+ */
177
+ export async function handleStripeEvent(payload, event) {
178
+ const o = membershipOf(payload);
179
+ const obj = event.data.object;
180
+ switch (event.type) {
181
+ case 'checkout.session.completed': {
182
+ if (obj.mode !== 'subscription')
183
+ return 'ignored';
184
+ const id = obj.metadata?.membership ?? obj.client_reference_id;
185
+ const m = id ? await findBy(payload, o, { id: { equals: id } }) : undefined;
186
+ if (!m)
187
+ return 'ignored';
188
+ const subId = idOf(obj.subscription);
189
+ const sub = subId ? await stripeOf(o).subscriptions.retrieve(subId) : null;
190
+ const end = sub ? periodEndOf(sub) : undefined;
191
+ await setMembership(payload, o, m, {
192
+ stripe: { ...m.stripe, customer: idOf(obj.customer), subscription: subId },
193
+ status: sub ? statusFrom(sub.status) : 'incomplete',
194
+ startedAt: m.startedAt ?? new Date().toISOString(),
195
+ ...(end ? { currentPeriodEnd: new Date(end * 1000).toISOString() } : {}),
196
+ });
197
+ return 'handled';
198
+ }
199
+ case 'invoice.paid': {
200
+ const subId = subscriptionIdOf(obj);
201
+ const m = subId ? await findBy(payload, o, { 'stripe.subscription': { equals: subId } }) : undefined;
202
+ if (!m || !(obj.amount_paid > 0))
203
+ return 'ignored';
204
+ const exists = await payload.find({ collection: o.payments, where: { invoiceId: { equals: obj.id } }, limit: 1, depth: 0, overrideAccess: true });
205
+ if (exists.totalDocs)
206
+ return 'ignored';
207
+ const paidAt = new Date((obj.status_transitions?.paid_at ?? obj.created ?? Date.now() / 1000) * 1000).toISOString();
208
+ const share = (amount) => (m.amount > 0 ? Math.round((amount * obj.amount_paid) / m.amount) : 0);
209
+ const pledges = (m.pledges ?? []).map((p) => ({ category: idOf(p.category), amount: share(p.amount) }));
210
+ let payment;
211
+ try {
212
+ payment = (await payload.create({
213
+ collection: o.payments,
214
+ data: { membership: m.id, user: idOf(m.user), amount: obj.amount_paid, currency: obj.currency ?? m.currency, paidAt, invoiceId: obj.id, tier: idOf(m.tier), pledges, ...(o.scopeField && m[o.scopeField] ? { [o.scopeField]: idOf(m[o.scopeField]) } : {}) },
215
+ overrideAccess: true,
216
+ context: ctx,
217
+ // One document, kept unique by the invoiceId index; no transaction needed. Inside one,
218
+ // a multi-tenant host's relationship checks run in parallel and Mongo aborts them.
219
+ disableTransaction: true,
220
+ }));
221
+ }
222
+ catch (err) {
223
+ // The same invoice arrived twice at once: the unique invoiceId let the other copy record it.
224
+ const recorded = await payload.count({ collection: o.payments, where: { invoiceId: { equals: obj.id } }, overrideAccess: true });
225
+ if (recorded.totalDocs)
226
+ return 'ignored';
227
+ throw err; // anything else (or the other copy not committed yet): fail, so Stripe retries
228
+ }
229
+ const periodEnd = obj.lines?.data?.[0]?.period?.end;
230
+ // Atomic writes outside a transaction, so two invoices paid at once both count: the total
231
+ // goes up with $inc, and only the delivery that actually flips the status reports it.
232
+ const memberships = o.memberships;
233
+ await payload.db.updateOne({
234
+ collection: memberships,
235
+ id: m.id,
236
+ data: { totalPaid: { $inc: obj.amount_paid }, ...(periodEnd ? { currentPeriodEnd: new Date(periodEnd * 1000).toISOString() } : {}) },
237
+ returning: false,
238
+ });
239
+ const activated = m.status !== 'active' &&
240
+ (await payload.db.updateOne({ collection: memberships, where: { and: [{ id: { equals: m.id } }, { status: { not_equals: 'active' } }] }, data: { status: 'active' } }));
241
+ const updated = (await payload.findByID({ collection: memberships, id: m.id, depth: 0, overrideAccess: true }));
242
+ if (activated && o.onStatusChange)
243
+ await o.onStatusChange({ payload, membership: recordOf(updated), previous: m.status ?? null });
244
+ if (o.onPayment)
245
+ await o.onPayment({
246
+ payload,
247
+ membership: recordOf(updated),
248
+ payment: { id: String(payment.id), membership: String(m.id), user: String(idOf(m.user)), amount: obj.amount_paid, currency: payment.currency, paidAt, invoiceId: obj.id, pledges: pledges, tier: idOf(m.tier) },
249
+ });
250
+ return 'handled';
251
+ }
252
+ case 'invoice.payment_failed': {
253
+ const subId = subscriptionIdOf(obj);
254
+ const m = subId ? await findBy(payload, o, { 'stripe.subscription': { equals: subId } }) : undefined;
255
+ if (!m)
256
+ return 'ignored';
257
+ await setMembership(payload, o, m, { status: 'past_due' });
258
+ return 'handled';
259
+ }
260
+ case 'customer.subscription.updated':
261
+ case 'customer.subscription.deleted': {
262
+ const sub = obj;
263
+ const m = (await findBy(payload, o, { 'stripe.subscription': { equals: sub.id } })) ?? (sub.metadata?.membership ? await findBy(payload, o, { id: { equals: sub.metadata.membership } }) : undefined);
264
+ if (!m)
265
+ return 'ignored';
266
+ const status = event.type === 'customer.subscription.deleted' ? 'canceled' : statusFrom(sub.status);
267
+ const end = periodEndOf(sub);
268
+ await setMembership(payload, o, m, {
269
+ status,
270
+ cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
271
+ ...(end ? { currentPeriodEnd: new Date(end * 1000).toISOString() } : {}),
272
+ ...(status === 'canceled' ? { canceledAt: new Date().toISOString() } : {}),
273
+ });
274
+ return 'handled';
275
+ }
276
+ default:
277
+ return 'ignored';
278
+ }
279
+ }
280
+ /**
281
+ * The backers wall: active members who chose to be shown, under their tier or
282
+ * under each category they support, A–Z within each (user decision for
283
+ * Captive Origins). Groups follow the admin's (drag-and-drop) order.
284
+ */
285
+ export async function getBackers(payload, opts = {}) {
286
+ const o = membershipOf(payload);
287
+ const scoped = (w) => ({ and: [...w, ...(o.scopeField && opts.scope ? [{ [o.scopeField]: { equals: opts.scope } }] : [])] });
288
+ const read = { depth: 0, pagination: false, overrideAccess: true, locale: opts.locale };
289
+ const [members, tiers, categories] = await Promise.all([
290
+ payload.find({ collection: o.memberships, where: scoped([{ status: { equals: 'active' } }, { 'wall.show': { equals: true } }]), select: { kind: true, tier: true, pledges: true, wall: true, startedAt: true }, ...read }),
291
+ payload.find({ collection: o.tiers, where: scoped([]), sort: '_order', select: { name: true, description: true, color: true }, ...read }),
292
+ payload.find({ collection: o.categories, where: scoped([]), sort: '_order', select: { name: true, description: true, color: true, parent: true }, ...read }),
293
+ ]);
294
+ const byTier = new Map();
295
+ const byCategory = new Map();
296
+ const add = (map, key, b) => key && map.set(key, [...(map.get(key) ?? []), b]);
297
+ for (const m of members.docs) {
298
+ const name = String(m.wall?.name ?? '').trim();
299
+ if (!name)
300
+ continue;
301
+ const b = { name, since: m.startedAt ?? null };
302
+ if (m.kind === 'tier')
303
+ add(byTier, idOf(m.tier), b);
304
+ else
305
+ for (const p of m.pledges ?? [])
306
+ add(byCategory, idOf(p.category), b);
307
+ }
308
+ const az = (list) => [...list].sort((a, b) => a.name.localeCompare(b.name, opts.locale ?? 'en', { sensitivity: 'base' }));
309
+ return {
310
+ tiers: tiers.docs.map((t) => ({ group: t, backers: az(byTier.get(String(t.id)) ?? []) })).filter((g) => g.backers.length),
311
+ categories: categories.docs.map((c) => ({ group: c, backers: az(byCategory.get(String(c.id)) ?? []) })).filter((g) => g.backers.length),
312
+ };
313
+ }
314
+ /** The signed-in member's current membership in a scope (for account pages). */
315
+ export async function myMembership(payload, userId, scope = null) {
316
+ const o = membershipOf(payload);
317
+ const where = { and: [{ user: { equals: userId } }, { status: { not_equals: 'pending' } }, ...(o.scopeField && scope ? [{ [o.scopeField]: { equals: scope } }] : [])] };
318
+ return (await payload.find({ collection: o.memberships, where, sort: '-createdAt', limit: 1, depth: 1, overrideAccess: true })).docs[0] ?? null;
319
+ }
@@ -0,0 +1,6 @@
1
+ import type { CollectionConfig } from 'payload';
2
+ import type { ResolvedMembership } from './types.js';
3
+ export declare function tiersCollection(o: ResolvedMembership): CollectionConfig;
4
+ export declare function categoriesCollection(o: ResolvedMembership): CollectionConfig;
5
+ export declare function membershipsCollection(o: ResolvedMembership): CollectionConfig;
6
+ export declare function paymentsCollection(o: ResolvedMembership): CollectionConfig;
@@ -0,0 +1,242 @@
1
+ import { generateKeyBetween } from 'payload/shared';
2
+ import { isManager } from './access.js';
3
+ const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
4
+ /** Drag-and-drop ordered (Payload `orderable`); a new record goes between its alphabetical neighbours. */
5
+ const placeAlphabetically = (o, slug, field) => async ({ data, operation, req }) => {
6
+ if (operation !== 'create' || data._order || !data[field])
7
+ return data;
8
+ const scope = o.scopeField ? idOf(data[o.scopeField]) : null;
9
+ const { docs } = await req.payload.find({
10
+ collection: slug,
11
+ where: o.scopeField && scope ? { [o.scopeField]: { equals: scope } } : {},
12
+ sort: '_order',
13
+ depth: 0,
14
+ pagination: false,
15
+ overrideAccess: true,
16
+ select: { [field]: true, _order: true },
17
+ req,
18
+ });
19
+ const ordered = docs;
20
+ const next = ordered.findIndex((d) => String(d[field]).localeCompare(String(data[field]), 'en', { sensitivity: 'base' }) > 0);
21
+ const before = next === -1 ? (ordered.at(-1)?._order ?? null) : next > 0 ? (ordered[next - 1]._order ?? null) : null;
22
+ const after = next === -1 ? null : (ordered[next]._order ?? null);
23
+ try {
24
+ data._order = generateKeyBetween(before, after);
25
+ }
26
+ catch {
27
+ // Neighbours out of order after manual moves: Payload appends it at the end instead.
28
+ }
29
+ return data;
30
+ };
31
+ const money = (name, label, description) => ({ name, label, type: 'number', min: 0, admin: { description: `${description} In cents (e.g. 500 = 5.00).` } });
32
+ export function tiersCollection(o) {
33
+ // Only an exact `true` from `canManage` makes a manager; a truthy value or a thrown error is a no.
34
+ const manager = ({ req }) => isManager(o, req);
35
+ const managerField = ({ req }) => isManager(o, req);
36
+ return {
37
+ slug: o.tiers,
38
+ labels: { singular: 'Membership tier', plural: 'Membership tiers' },
39
+ admin: {
40
+ useAsTitle: 'name',
41
+ defaultColumns: ['name', 'monthly', 'yearly', 'active'],
42
+ description: 'Fixed-price levels (Patreon-style). Shown in this order: drag rows to change it.',
43
+ },
44
+ access: { read: () => true, create: manager, update: manager, delete: manager },
45
+ orderable: true,
46
+ defaultSort: '_order',
47
+ hooks: { beforeChange: [placeAlphabetically(o, o.tiers, 'name')] },
48
+ fields: [
49
+ { name: 'name', type: 'text', required: true },
50
+ { name: 'active', label: 'Open to new members', type: 'checkbox', defaultValue: true, admin: { position: 'sidebar' } },
51
+ { type: 'row', fields: [{ ...money('monthly', 'Monthly price', 'Per month; empty: not offered monthly.'), admin: { width: '50%' } }, { ...money('yearly', 'Yearly price', 'Per year; empty: not offered yearly.'), admin: { width: '50%' } }] },
52
+ { name: 'description', type: 'textarea' },
53
+ { name: 'perks', type: 'array', fields: [{ name: 'perk', type: 'text', required: true }] },
54
+ { name: 'color', type: 'text', admin: { position: 'sidebar', description: 'Badge color, e.g. #cf8137.' } },
55
+ {
56
+ name: 'sponsorListing',
57
+ label: 'Members are listed as sponsors',
58
+ type: 'checkbox',
59
+ admin: { position: 'sidebar', description: 'A perk your site can act on in onStatusChange (e.g. with payload-plugin-sponsors).' },
60
+ },
61
+ // Stripe product for this tier/category (created on first checkout; prices are set per member).
62
+ { name: 'stripeProduct', type: 'text', access: { read: managerField, create: managerField, update: managerField }, admin: { position: 'sidebar', readOnly: true } },
63
+ ],
64
+ timestamps: true,
65
+ };
66
+ }
67
+ export function categoriesCollection(o) {
68
+ // Only an exact `true` from `canManage` makes a manager; a truthy value or a thrown error is a no.
69
+ const manager = ({ req }) => isManager(o, req);
70
+ const managerField = ({ req }) => isManager(o, req);
71
+ return {
72
+ slug: o.categories,
73
+ labels: { singular: 'Membership category', plural: 'Membership categories' },
74
+ admin: {
75
+ useAsTitle: 'name',
76
+ defaultColumns: ['name', 'parent', 'minimum', 'active'],
77
+ description: 'What members can choose to support, setting their own amount (A–Z for new ones; drag to reorder). Add your own fields to tie categories to anything.',
78
+ },
79
+ access: { read: () => true, create: manager, update: manager, delete: manager },
80
+ orderable: true,
81
+ defaultSort: '_order',
82
+ hooks: { beforeChange: [placeAlphabetically(o, o.categories, 'name')] },
83
+ fields: [
84
+ { name: 'name', type: 'text', required: true },
85
+ { name: 'active', label: 'Open to new pledges', type: 'checkbox', defaultValue: true, admin: { position: 'sidebar' } },
86
+ { name: 'parent', type: 'relationship', relationTo: o.categories, admin: { position: 'sidebar', description: 'Optional: nest under a broader category.' } },
87
+ { name: 'description', type: 'textarea' },
88
+ money('minimum', 'Minimum per month', 'Smallest monthly amount for this category (yearly: 12×).'),
89
+ {
90
+ name: 'earmarked',
91
+ type: 'checkbox',
92
+ admin: { description: 'Off: the category is the member’s preference. On: pledges are reserved for work in this category (say so on your page).' },
93
+ },
94
+ { name: 'color', type: 'text', admin: { position: 'sidebar' } },
95
+ // Stripe product for this tier/category (created on first checkout; prices are set per member).
96
+ { name: 'stripeProduct', type: 'text', access: { read: managerField, create: managerField, update: managerField }, admin: { position: 'sidebar', readOnly: true } },
97
+ ],
98
+ timestamps: true,
99
+ };
100
+ }
101
+ export function membershipsCollection(o) {
102
+ // Only an exact `true` from `canManage` makes a manager; a truthy value or a thrown error is a no.
103
+ const manager = ({ req }) => isManager(o, req);
104
+ const managerField = ({ req }) => isManager(o, req);
105
+ // Managers read all; members read their own (the plugin's own query, never the site's answer).
106
+ const ownOrManager = async ({ req }) => {
107
+ if (!req.user)
108
+ return false;
109
+ if (await isManager(o, req))
110
+ return true;
111
+ return { user: { equals: req.user.id } };
112
+ };
113
+ const nobody = () => false;
114
+ return {
115
+ slug: o.memberships,
116
+ labels: { singular: 'Membership', plural: 'Memberships' },
117
+ admin: {
118
+ useAsTitle: 'label',
119
+ defaultColumns: ['label', 'kind', 'amount', 'interval', 'status', 'currentPeriodEnd'],
120
+ description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the wall name or notes here.',
121
+ },
122
+ // Created by checkout and updated by Stripe webhooks; members manage theirs through the plugin's endpoints.
123
+ access: { read: ownOrManager, create: nobody, update: manager, delete: manager },
124
+ fields: [
125
+ { name: 'label', type: 'text', admin: { readOnly: true } },
126
+ { name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true, admin: { readOnly: true } },
127
+ {
128
+ type: 'row',
129
+ fields: [
130
+ { name: 'kind', type: 'select', required: true, options: [{ label: 'Tier', value: 'tier' }, { label: 'Pledge to categories', value: 'pledge' }], admin: { width: '33%', readOnly: true } },
131
+ {
132
+ name: 'status',
133
+ type: 'select',
134
+ required: true,
135
+ defaultValue: 'pending',
136
+ index: true,
137
+ options: ['pending', 'incomplete', 'active', 'past_due', 'canceled'].map((v) => ({ label: v.replace('_', ' '), value: v })),
138
+ admin: { width: '33%', readOnly: true },
139
+ },
140
+ { name: 'interval', type: 'select', required: true, options: [{ label: 'Monthly', value: 'month' }, { label: 'Yearly', value: 'year' }], admin: { width: '34%', readOnly: true } },
141
+ ],
142
+ },
143
+ { name: 'tier', type: 'relationship', relationTo: o.tiers, index: true, admin: { readOnly: true, condition: (d) => d?.kind === 'tier' } },
144
+ {
145
+ name: 'pledges',
146
+ type: 'array',
147
+ admin: { readOnly: true, condition: (d) => d?.kind === 'pledge' },
148
+ fields: [
149
+ { name: 'category', type: 'relationship', relationTo: o.categories, required: true, index: true },
150
+ { name: 'amount', type: 'number', required: true, min: 0, admin: { description: 'Per interval, in cents.' } },
151
+ ],
152
+ },
153
+ {
154
+ type: 'row',
155
+ fields: [
156
+ { name: 'amount', type: 'number', required: true, min: 0, admin: { width: '33%', readOnly: true, description: 'Per interval, in cents.' } },
157
+ { name: 'currency', type: 'text', required: true, admin: { width: '33%', readOnly: true } },
158
+ {
159
+ name: 'totalPaid',
160
+ type: 'number',
161
+ defaultValue: 0,
162
+ // Only invoice.paid changes it, with an atomic $inc. Payload saves the whole document,
163
+ // so an edit, a Stripe event or a hook saved at the same moment as an invoice would
164
+ // write back an older total: leave it out of every save (0 on create).
165
+ access: { create: () => false, update: () => false },
166
+ hooks: {
167
+ beforeChange: [
168
+ ({ operation, siblingData }) => {
169
+ if (operation === 'create')
170
+ return 0;
171
+ delete siblingData.totalPaid;
172
+ return undefined;
173
+ },
174
+ ],
175
+ },
176
+ admin: { width: '34%', readOnly: true, description: 'All paid invoices, in cents.' },
177
+ },
178
+ ],
179
+ },
180
+ {
181
+ type: 'row',
182
+ fields: [
183
+ { name: 'startedAt', type: 'date', admin: { width: '25%', readOnly: true } },
184
+ { name: 'currentPeriodEnd', type: 'date', admin: { width: '25%', readOnly: true } },
185
+ { name: 'cancelAtPeriodEnd', type: 'checkbox', admin: { width: '25%', readOnly: true } },
186
+ { name: 'canceledAt', type: 'date', admin: { width: '25%', readOnly: true } },
187
+ ],
188
+ },
189
+ {
190
+ name: 'wall',
191
+ label: 'Backers wall',
192
+ type: 'group',
193
+ admin: { description: 'Members choose whether and how they appear; nothing is public otherwise.' },
194
+ fields: [
195
+ { name: 'show', label: 'Show on the backers wall', type: 'checkbox', defaultValue: false },
196
+ { name: 'name', label: 'Name on the wall', type: 'text', maxLength: 80 },
197
+ ],
198
+ },
199
+ // Stripe references: managers only, never in public responses.
200
+ {
201
+ name: 'stripe',
202
+ type: 'group',
203
+ access: { read: managerField, create: managerField, update: managerField },
204
+ admin: { position: 'sidebar', readOnly: true },
205
+ fields: [
206
+ { name: 'customer', type: 'text', index: true },
207
+ { name: 'subscription', type: 'text', index: true },
208
+ { name: 'checkoutSession', type: 'text', index: true },
209
+ ],
210
+ },
211
+ { name: 'notes', type: 'textarea', access: { read: managerField, update: managerField }, admin: { position: 'sidebar' } },
212
+ ],
213
+ timestamps: true,
214
+ };
215
+ }
216
+ export function paymentsCollection(o) {
217
+ // Only an exact `true` from `canManage` makes a manager; a truthy value or a thrown error is a no.
218
+ const manager = ({ req }) => isManager(o, req);
219
+ // Managers read all; members read their own (the plugin's own query, never the site's answer).
220
+ const ownOrManager = async ({ req }) => {
221
+ if (!req.user)
222
+ return false;
223
+ if (await isManager(o, req))
224
+ return true;
225
+ return { user: { equals: req.user.id } };
226
+ };
227
+ return {
228
+ slug: o.payments,
229
+ labels: { singular: 'Membership payment', plural: 'Membership payments' },
230
+ admin: { useAsTitle: 'invoiceId', defaultColumns: ['membership', 'amount', 'currency', 'paidAt'], description: 'Every paid invoice, recorded once from Stripe.' },
231
+ access: { read: ownOrManager, create: () => false, update: () => false, delete: manager },
232
+ fields: [
233
+ { name: 'membership', type: 'relationship', relationTo: o.memberships, required: true, index: true },
234
+ { name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true },
235
+ { type: 'row', fields: [{ name: 'amount', type: 'number', required: true, admin: { width: '33%' } }, { name: 'currency', type: 'text', required: true, admin: { width: '33%' } }, { name: 'paidAt', type: 'date', required: true, index: true, admin: { width: '34%' } }] },
236
+ { name: 'invoiceId', type: 'text', required: true, unique: true },
237
+ { name: 'tier', type: 'relationship', relationTo: o.tiers },
238
+ { name: 'pledges', type: 'array', fields: [{ name: 'category', type: 'relationship', relationTo: o.categories }, { name: 'amount', type: 'number' }] },
239
+ ],
240
+ timestamps: true,
241
+ };
242
+ }
@@ -0,0 +1,13 @@
1
+ import type { Endpoint } from 'payload';
2
+ /** POST /api/<memberships>/checkout { tier? | pledges?, interval, wall?, successPath?, cancelPath? } → { url } */
3
+ export declare const checkoutEndpoint: Endpoint;
4
+ /** POST /api/<memberships>/:id/change { tier? | pledges? } */
5
+ export declare const changeEndpoint: Endpoint;
6
+ /** POST /api/<memberships>/:id/cancel: ends at the close of the paid period. */
7
+ export declare const cancelEndpoint: Endpoint;
8
+ /** POST /api/<memberships>/:id/portal { returnPath? } → { url } (Stripe customer portal). */
9
+ export declare const portalEndpoint: Endpoint;
10
+ /** POST /api/<memberships>/:id/wall { show, name }: the member's own choice for the backers wall. */
11
+ export declare const wallEndpoint: Endpoint;
12
+ /** POST /api/<memberships>/stripe-webhook: Stripe events, verified with the endpoint's signing secret. */
13
+ export declare const webhookEndpoint: Endpoint;
@@ -0,0 +1,181 @@
1
+ import { isManager } from './access.js';
2
+ import { cancelMembership, changeMembership, handleStripeEvent, membershipOf, portalLink, startCheckout } from './api.js';
3
+ const json = (body, status = 200) => Response.json(body, { status });
4
+ const fail = (err) => {
5
+ const e = err;
6
+ return json({ error: e.isPublic || (e.status && e.status < 500) ? e.message : 'Something went wrong.' }, e.status && e.status >= 400 ? e.status : 500);
7
+ };
8
+ const body = async (req) => (req.json ? (await req.json().catch(() => ({}))) : {}); // eslint-disable-line @typescript-eslint/no-explicit-any
9
+ const origin = (req) => membershipOf(req.payload).publicURL ?? req.payload.config.serverURL ?? new URL(req.url ?? 'http://localhost').origin;
10
+ /** Same-site paths only. */
11
+ const path = (p, fallback) => (typeof p === 'string' && /^\/(?!\/)/.test(p) ? p : fallback);
12
+ /**
13
+ * The request's site, from `scopeOf`. A throw or rejection counts as no site, so the caller
14
+ * refuses as it would for an unknown site. Only the error's name is logged: its message could
15
+ * carry the host's request details.
16
+ */
17
+ async function siteOf(req) {
18
+ const o = membershipOf(req.payload);
19
+ if (!o.scopeOf)
20
+ return null;
21
+ try {
22
+ return await o.scopeOf(req);
23
+ }
24
+ catch (err) {
25
+ req.payload.logger.warn(`Membership: scopeOf failed (${err instanceof Error ? err.name : typeof err}); treated as no site`);
26
+ return null;
27
+ }
28
+ }
29
+ const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
30
+ /**
31
+ * The member's own membership, or one a manager may read, on this request's site only.
32
+ * Managers go through the collection's read access (so a multi-tenant host's tenant rules
33
+ * apply); with `scopeField` and `scopeOf`, a membership from another site, or asked for from
34
+ * an unknown site, is not found.
35
+ */
36
+ async function ownMembership(req) {
37
+ const o = membershipOf(req.payload);
38
+ if (!req.user)
39
+ return null;
40
+ const id = String(req.routeParams?.id ?? '');
41
+ const collection = o.memberships;
42
+ const m = await req.payload.findByID({ collection, id, depth: 0, overrideAccess: true, disableErrors: true });
43
+ if (!m)
44
+ return null;
45
+ if (o.scopeField && o.scopeOf) {
46
+ const here = await siteOf(req);
47
+ if (here == null || idOf(m[o.scopeField]) !== String(here))
48
+ return null;
49
+ }
50
+ if (idOf(m.user) === String(req.user.id))
51
+ return m;
52
+ if (!(await isManager(o, req)))
53
+ return null;
54
+ const visible = await req.payload.count({ collection, where: { id: { equals: m.id } }, overrideAccess: false, user: req.user, req });
55
+ return visible.totalDocs > 0 ? m : null;
56
+ }
57
+ /** POST /api/<memberships>/checkout { tier? | pledges?, interval, wall?, successPath?, cancelPath? } → { url } */
58
+ export const checkoutEndpoint = {
59
+ path: '/checkout',
60
+ method: 'post',
61
+ handler: async (req) => {
62
+ if (!req.user)
63
+ return json({ error: 'Sign in first.' }, 401);
64
+ try {
65
+ const o = membershipOf(req.payload);
66
+ const b = await body(req);
67
+ const base = origin(req);
68
+ const result = await startCheckout(req.payload, {
69
+ user: req.user,
70
+ tier: b.tier ?? null,
71
+ pledges: Array.isArray(b.pledges) ? b.pledges : null,
72
+ interval: b.interval,
73
+ wall: b.wall,
74
+ scope: await siteOf(req),
75
+ successURL: `${base}${path(b.successPath, '/')}`,
76
+ cancelURL: `${base}${path(b.cancelPath, '/')}`,
77
+ });
78
+ return json(result);
79
+ }
80
+ catch (err) {
81
+ return fail(err);
82
+ }
83
+ },
84
+ };
85
+ /** POST /api/<memberships>/:id/change { tier? | pledges? } */
86
+ export const changeEndpoint = {
87
+ path: '/:id/change',
88
+ method: 'post',
89
+ handler: async (req) => {
90
+ const m = await ownMembership(req);
91
+ if (!m)
92
+ return json({ error: 'Not found.' }, 404);
93
+ try {
94
+ const b = await body(req);
95
+ return json({ membership: await changeMembership(req.payload, String(m.id), { tier: b.tier ?? null, pledges: Array.isArray(b.pledges) ? b.pledges : null }) });
96
+ }
97
+ catch (err) {
98
+ return fail(err);
99
+ }
100
+ },
101
+ };
102
+ /** POST /api/<memberships>/:id/cancel: ends at the close of the paid period. */
103
+ export const cancelEndpoint = {
104
+ path: '/:id/cancel',
105
+ method: 'post',
106
+ handler: async (req) => {
107
+ const m = await ownMembership(req);
108
+ if (!m)
109
+ return json({ error: 'Not found.' }, 404);
110
+ try {
111
+ return json({ membership: await cancelMembership(req.payload, String(m.id)) });
112
+ }
113
+ catch (err) {
114
+ return fail(err);
115
+ }
116
+ },
117
+ };
118
+ /** POST /api/<memberships>/:id/portal { returnPath? } → { url } (Stripe customer portal). */
119
+ export const portalEndpoint = {
120
+ path: '/:id/portal',
121
+ method: 'post',
122
+ handler: async (req) => {
123
+ const m = await ownMembership(req);
124
+ if (!m)
125
+ return json({ error: 'Not found.' }, 404);
126
+ try {
127
+ const b = await body(req);
128
+ return json({ url: await portalLink(req.payload, String(m.id), `${origin(req)}${path(b.returnPath, '/')}`) });
129
+ }
130
+ catch (err) {
131
+ return fail(err);
132
+ }
133
+ },
134
+ };
135
+ /** POST /api/<memberships>/:id/wall { show, name }: the member's own choice for the backers wall. */
136
+ export const wallEndpoint = {
137
+ path: '/:id/wall',
138
+ method: 'post',
139
+ handler: async (req) => {
140
+ const m = await ownMembership(req);
141
+ if (!m)
142
+ return json({ error: 'Not found.' }, 404);
143
+ const b = await body(req);
144
+ const name = typeof b.name === 'string' ? b.name.trim().slice(0, 80) : '';
145
+ const updated = await req.payload.update({
146
+ collection: membershipOf(req.payload).memberships,
147
+ id: m.id,
148
+ data: { wall: { show: Boolean(b.show) && Boolean(name), name: name || null } },
149
+ overrideAccess: true,
150
+ context: { membershipSync: true },
151
+ });
152
+ return json({ wall: updated.wall });
153
+ },
154
+ };
155
+ /** POST /api/<memberships>/stripe-webhook: Stripe events, verified with the endpoint's signing secret. */
156
+ export const webhookEndpoint = {
157
+ path: '/stripe-webhook',
158
+ method: 'post',
159
+ handler: async (req) => {
160
+ const o = membershipOf(req.payload);
161
+ const stripe = o.stripe();
162
+ if (!stripe || !o.webhookSecret)
163
+ return json({ error: 'Not configured.' }, 503);
164
+ const signature = req.headers.get('stripe-signature');
165
+ const raw = req.text ? await req.text() : '';
166
+ let event;
167
+ try {
168
+ event = stripe.webhooks.constructEvent(raw, signature ?? '', o.webhookSecret);
169
+ }
170
+ catch {
171
+ return json({ error: 'Invalid signature.' }, 400);
172
+ }
173
+ try {
174
+ return json({ received: true, result: await handleStripeEvent(req.payload, event) });
175
+ }
176
+ catch (err) {
177
+ req.payload.logger.error({ err, event: event.type }, 'Membership webhook failed');
178
+ return json({ error: 'Failed.' }, 500); // Stripe retries
179
+ }
180
+ },
181
+ };
@@ -0,0 +1,3 @@
1
+ export { membershipPlugin } from './plugin.js';
2
+ export { cancelMembership, changeMembership, getBackers, handleStripeEvent, membershipOf, myMembership, portalLink, startCheckout, type Backer, type BackerGroup, type Choice } from './api.js';
3
+ export type { CanManage, Interval, MembershipPluginOptions, MembershipRecord, MembershipStatus, PaymentRecord, ResolvedMembership, StripeEvent, StripeLike, StripeSubscription } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { membershipPlugin } from './plugin.js';
2
+ export { cancelMembership, changeMembership, getBackers, handleStripeEvent, membershipOf, myMembership, portalLink, startCheckout } from './api.js';
@@ -0,0 +1,9 @@
1
+ import type { Plugin } from 'payload';
2
+ import type { MembershipPluginOptions } from './types.js';
3
+ /**
4
+ * Memberships: fixed tiers (Patreon-style) and/or pledges where members pick
5
+ * categories and set their own amounts, billed monthly or yearly as Stripe
6
+ * subscriptions. A payments ledger calls `onPayment` once per paid invoice;
7
+ * `getBackers` builds an opt-in backers wall, A–Z within each tier/category.
8
+ */
9
+ export declare const membershipPlugin: (options?: MembershipPluginOptions) => Plugin;
package/dist/plugin.js ADDED
@@ -0,0 +1,43 @@
1
+ import Stripe from 'stripe';
2
+ import { categoriesCollection, membershipsCollection, paymentsCollection, tiersCollection } from './collections.js';
3
+ import { cancelEndpoint, changeEndpoint, checkoutEndpoint, portalEndpoint, wallEndpoint, webhookEndpoint } from './endpoints.js';
4
+ /**
5
+ * Memberships: fixed tiers (Patreon-style) and/or pledges where members pick
6
+ * categories and set their own amounts, billed monthly or yearly as Stripe
7
+ * subscriptions. A payments ledger calls `onPayment` once per paid invoice;
8
+ * `getBackers` builds an opt-in backers wall, A–Z within each tier/category.
9
+ */
10
+ export const membershipPlugin = (options = {}) => (config) => {
11
+ let client = options.stripe;
12
+ const o = {
13
+ tiers: options.slugs?.tiers ?? 'membership-tiers',
14
+ categories: options.slugs?.categories ?? 'membership-categories',
15
+ memberships: options.slugs?.memberships ?? 'memberships',
16
+ payments: options.slugs?.payments ?? 'membership-payments',
17
+ users: options.users ?? config.admin?.user ?? 'users',
18
+ canManage: options.canManage ?? (() => false),
19
+ canCheckout: options.canCheckout,
20
+ stripe: () => (client === undefined ? (client = options.stripeSecretKey ? new Stripe(options.stripeSecretKey) : null) : client),
21
+ webhookSecret: options.webhookSecret,
22
+ currency: (options.currency ?? 'usd').toLowerCase(),
23
+ publicURL: options.publicURL,
24
+ scopeField: options.scopeField,
25
+ scopeOf: options.scopeOf,
26
+ onPayment: options.onPayment,
27
+ onStatusChange: options.onStatusChange,
28
+ };
29
+ const apply = (c, f) => (f ? f(c) : c);
30
+ const memberships = membershipsCollection(o);
31
+ memberships.endpoints = [checkoutEndpoint, webhookEndpoint, changeEndpoint, cancelEndpoint, portalEndpoint, wallEndpoint];
32
+ return {
33
+ ...config,
34
+ collections: [
35
+ ...(config.collections ?? []),
36
+ apply(tiersCollection(o), options.overrides?.tiers),
37
+ apply(categoriesCollection(o), options.overrides?.categories),
38
+ apply(memberships, options.overrides?.memberships),
39
+ apply(paymentsCollection(o), options.overrides?.payments),
40
+ ],
41
+ custom: { ...config.custom, membership: o },
42
+ };
43
+ };
@@ -0,0 +1,156 @@
1
+ import type { CollectionConfig, Payload, PayloadRequest } from 'payload';
2
+ /** Who manages tiers, categories and memberships in the admin (default: nobody but overrideAccess code). */
3
+ export type CanManage = (args: {
4
+ req: PayloadRequest;
5
+ }) => boolean | Promise<boolean>;
6
+ export type Interval = 'month' | 'year';
7
+ /** A paid invoice, as recorded in the payments ledger. Amounts in the currency's minor unit (cents). */
8
+ export type PaymentRecord = {
9
+ id: string;
10
+ membership: string;
11
+ user: string;
12
+ amount: number;
13
+ currency: string;
14
+ paidAt: string;
15
+ invoiceId: string;
16
+ /** Pledged amounts per category in this payment (pledge memberships). */
17
+ pledges: {
18
+ category: string;
19
+ amount: number;
20
+ }[];
21
+ tier: string | null;
22
+ };
23
+ export type MembershipRecord = {
24
+ id: string;
25
+ user: string;
26
+ kind: 'tier' | 'pledge';
27
+ tier: string | null;
28
+ pledges: {
29
+ category: string;
30
+ amount: number;
31
+ }[];
32
+ interval: Interval;
33
+ amount: number;
34
+ currency: string;
35
+ status: MembershipStatus;
36
+ };
37
+ export type MembershipStatus = 'pending' | 'active' | 'past_due' | 'canceled' | 'incomplete';
38
+ /** The small part of the Stripe SDK the plugin uses (inject a fake in tests). */
39
+ export type StripeLike = {
40
+ checkout: {
41
+ sessions: {
42
+ create: (params: Record<string, unknown>) => Promise<{
43
+ id: string;
44
+ url: string | null;
45
+ }>;
46
+ };
47
+ };
48
+ billingPortal: {
49
+ sessions: {
50
+ create: (params: Record<string, unknown>) => Promise<{
51
+ url: string;
52
+ }>;
53
+ };
54
+ };
55
+ products: {
56
+ create: (params: Record<string, unknown>) => Promise<{
57
+ id: string;
58
+ }>;
59
+ };
60
+ subscriptions: {
61
+ retrieve: (id: string) => Promise<StripeSubscription>;
62
+ update: (id: string, params: Record<string, unknown>) => Promise<StripeSubscription>;
63
+ };
64
+ webhooks: {
65
+ constructEvent: (payload: string, signature: string, secret: string) => StripeEvent;
66
+ };
67
+ };
68
+ export type StripeSubscription = {
69
+ id: string;
70
+ status: string;
71
+ customer: string | {
72
+ id: string;
73
+ };
74
+ cancel_at_period_end?: boolean;
75
+ current_period_end?: number;
76
+ items: {
77
+ data: {
78
+ id: string;
79
+ current_period_end?: number;
80
+ }[];
81
+ };
82
+ metadata?: Record<string, string>;
83
+ };
84
+ export type StripeEvent = {
85
+ id: string;
86
+ type: string;
87
+ data: {
88
+ object: Record<string, unknown>;
89
+ };
90
+ };
91
+ export type MembershipPluginOptions = {
92
+ /** Slugs. Defaults: `membership-tiers`, `membership-categories`, `memberships`, `membership-payments`. */
93
+ slugs?: {
94
+ tiers?: string;
95
+ categories?: string;
96
+ memberships?: string;
97
+ payments?: string;
98
+ };
99
+ /** The auth collection of members. Default: `admin.user` of your config. */
100
+ users?: string;
101
+ /** Who manages tiers, categories and memberships in the admin. Only `true` counts; anything else, or a throw, is a no. */
102
+ canManage?: CanManage;
103
+ /** May members start memberships here right now (e.g. off in development)? Default: always. Only `true` allows it. */
104
+ canCheckout?: (args: {
105
+ payload: Payload;
106
+ }) => boolean | Promise<boolean>;
107
+ /** Stripe secret key (`sk_…`/`rk_…`), or a ready client. Without either, checkout is off. */
108
+ stripeSecretKey?: string;
109
+ stripe?: StripeLike;
110
+ /** Signing secret of the webhook endpoint (`whsec_…`) for `/api/<memberships>/stripe-webhook`. */
111
+ webhookSecret?: string;
112
+ /** ISO currency, lowercase. Default `usd`. */
113
+ currency?: string;
114
+ /** Public origin for Stripe return links. Default: `serverURL`. */
115
+ publicURL?: string;
116
+ /** A field that separates owners (e.g. `tenant`): new tiers/categories go A–Z among their own; memberships are per scope. */
117
+ scopeField?: string;
118
+ /** The scope of a request (e.g. the site of the request's host), stored on new memberships. */
119
+ scopeOf?: (req: PayloadRequest) => Promise<string | null> | string | null;
120
+ /** Called once per paid invoice (idempotent: never twice for the same invoice). Award perks, votes, credits here. */
121
+ onPayment?: (args: {
122
+ payload: Payload;
123
+ payment: PaymentRecord;
124
+ membership: MembershipRecord;
125
+ }) => Promise<void> | void;
126
+ /** Called when a membership's status changes (e.g. list or retire a sponsor-wall perk). */
127
+ onStatusChange?: (args: {
128
+ payload: Payload;
129
+ membership: MembershipRecord;
130
+ previous: MembershipStatus | null;
131
+ }) => Promise<void> | void;
132
+ /** Change the generated collections before they are added (fields, access, admin groups). */
133
+ overrides?: {
134
+ tiers?: (c: CollectionConfig) => CollectionConfig;
135
+ categories?: (c: CollectionConfig) => CollectionConfig;
136
+ memberships?: (c: CollectionConfig) => CollectionConfig;
137
+ payments?: (c: CollectionConfig) => CollectionConfig;
138
+ };
139
+ };
140
+ export type ResolvedMembership = {
141
+ tiers: string;
142
+ categories: string;
143
+ memberships: string;
144
+ payments: string;
145
+ users: string;
146
+ canManage: CanManage;
147
+ canCheckout?: MembershipPluginOptions['canCheckout'];
148
+ stripe: () => StripeLike | null;
149
+ webhookSecret?: string;
150
+ currency: string;
151
+ publicURL?: string;
152
+ scopeField?: string;
153
+ scopeOf?: MembershipPluginOptions['scopeOf'];
154
+ onPayment?: MembershipPluginOptions['onPayment'];
155
+ onStatusChange?: MembershipPluginOptions['onStatusChange'];
156
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-membership",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.3",
4
+ "description": "Memberships for Payload: Patreon-style tiers or pick-your-own-amount pledges to categories, billed as Stripe subscriptions, with a backers wall and hooks for perks.",
5
+ "homepage": "https://github.com/ExtantApe/payload-plugin-membership#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/ExtantApe/payload-plugin-membership/issues"
8
+ },
9
+ "keywords": [
10
+ "payload",
11
+ "payload-plugin",
12
+ "payloadcms",
13
+ "membership",
14
+ "memberships",
15
+ "patreon",
16
+ "subscriptions",
17
+ "stripe",
18
+ "donations",
19
+ "nonprofit"
20
+ ],
21
+ "license": "MIT",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/ExtantApe/payload-plugin-membership.git"
25
+ },
26
+ "type": "module",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js"
31
+ }
32
+ },
33
+ "main": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "engines": {
41
+ "node": ">=20.9"
42
+ },
43
+ "scripts": {
44
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
45
+ "typecheck": "tsc --noEmit",
46
+ "test": "vitest run",
47
+ "prepack": "npm run build",
48
+ "prepublishOnly": "npm run typecheck && npm test"
49
+ },
50
+ "dependencies": {
51
+ "stripe": "^23.1.0"
52
+ },
53
+ "peerDependencies": {
54
+ "payload": "^3.80.0"
55
+ },
56
+ "devDependencies": {
57
+ "@payloadcms/db-mongodb": "3.92.1",
58
+ "@payloadcms/plugin-multi-tenant": "3.92.1",
59
+ "@types/node": "^24.0.0",
60
+ "graphql": "^16.14.2",
61
+ "mongodb-memory-server": "^11.3.0",
62
+ "payload": "3.92.1",
63
+ "typescript": "^5.9.0",
64
+ "vitest": "^5.1.0"
65
+ }
66
+ }