@extantape/payload-plugin-membership 0.0.0-stage → 0.2.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.
@@ -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? }: the member's own only. */
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): the member's own only. */
9
+ export declare const portalEndpoint: Endpoint;
10
+ /** POST /api/<memberships>/:id/wall { show, name }: the member's own choice for the backers wall. A manager may only send `show: false`. */
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,188 @@
1
+ import { managerReaches } 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 (unless `memberOnly`) one a manager may reach, on this request's
32
+ * site only. A manager is checked against this very row with `canManage`'s answer: `true` reaches
33
+ * every row, a query only the rows it matches. With `scopeField` and `scopeOf`, a membership from
34
+ * another site, or asked for from an unknown site, is not found.
35
+ */
36
+ async function ownMembership(req, { memberOnly = false } = {}) {
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 (memberOnly)
53
+ return null;
54
+ if (!(await managerReaches(o, req, o.memberships, m.id)))
55
+ return null;
56
+ // And the collection's own read access, so rules the host added there (a tenant plugin's, say) apply too.
57
+ const visible = await req.payload.count({ collection, where: { id: { equals: m.id } }, overrideAccess: false, user: req.user, req });
58
+ return visible.totalDocs > 0 ? m : null;
59
+ }
60
+ /** POST /api/<memberships>/checkout { tier? | pledges?, interval, wall?, successPath?, cancelPath? } → { url } */
61
+ export const checkoutEndpoint = {
62
+ path: '/checkout',
63
+ method: 'post',
64
+ handler: async (req) => {
65
+ if (!req.user)
66
+ return json({ error: 'Sign in first.' }, 401);
67
+ try {
68
+ const o = membershipOf(req.payload);
69
+ const b = await body(req);
70
+ const base = origin(req);
71
+ const result = await startCheckout(req.payload, {
72
+ user: req.user,
73
+ tier: b.tier ?? null,
74
+ pledges: Array.isArray(b.pledges) ? b.pledges : null,
75
+ interval: b.interval,
76
+ wall: b.wall,
77
+ scope: await siteOf(req),
78
+ successURL: `${base}${path(b.successPath, '/')}`,
79
+ cancelURL: `${base}${path(b.cancelPath, '/')}`,
80
+ });
81
+ return json(result);
82
+ }
83
+ catch (err) {
84
+ return fail(err);
85
+ }
86
+ },
87
+ };
88
+ /** POST /api/<memberships>/:id/change { tier? | pledges? }: the member's own only. */
89
+ export const changeEndpoint = {
90
+ path: '/:id/change',
91
+ method: 'post',
92
+ handler: async (req) => {
93
+ const m = await ownMembership(req, { memberOnly: true });
94
+ if (!m)
95
+ return json({ error: 'Not found.' }, 404);
96
+ try {
97
+ const b = await body(req);
98
+ return json({ membership: await changeMembership(req.payload, String(m.id), { tier: b.tier ?? null, pledges: Array.isArray(b.pledges) ? b.pledges : null }) });
99
+ }
100
+ catch (err) {
101
+ return fail(err);
102
+ }
103
+ },
104
+ };
105
+ /** POST /api/<memberships>/:id/cancel: ends at the close of the paid period. */
106
+ export const cancelEndpoint = {
107
+ path: '/:id/cancel',
108
+ method: 'post',
109
+ handler: async (req) => {
110
+ const m = await ownMembership(req);
111
+ if (!m)
112
+ return json({ error: 'Not found.' }, 404);
113
+ try {
114
+ return json({ membership: await cancelMembership(req.payload, String(m.id)) });
115
+ }
116
+ catch (err) {
117
+ return fail(err);
118
+ }
119
+ },
120
+ };
121
+ /** POST /api/<memberships>/:id/portal { returnPath? } → { url } (Stripe customer portal): the member's own only. */
122
+ export const portalEndpoint = {
123
+ path: '/:id/portal',
124
+ method: 'post',
125
+ handler: async (req) => {
126
+ const m = await ownMembership(req, { memberOnly: true });
127
+ if (!m)
128
+ return json({ error: 'Not found.' }, 404);
129
+ try {
130
+ const b = await body(req);
131
+ return json({ url: await portalLink(req.payload, String(m.id), `${origin(req)}${path(b.returnPath, '/')}`) });
132
+ }
133
+ catch (err) {
134
+ return fail(err);
135
+ }
136
+ },
137
+ };
138
+ /** POST /api/<memberships>/:id/wall { show, name }: the member's own choice for the backers wall. A manager may only send `show: false`. */
139
+ export const wallEndpoint = {
140
+ path: '/:id/wall',
141
+ method: 'post',
142
+ handler: async (req) => {
143
+ const m = await ownMembership(req);
144
+ if (!m)
145
+ return json({ error: 'Not found.' }, 404);
146
+ const b = await body(req);
147
+ const member = idOf(m.user) === String(req.user.id);
148
+ // Only the member shows themselves on the wall or changes the name; a manager may only hide it.
149
+ if (!member && b.show !== false)
150
+ return json({ error: 'Only the member can do that.' }, 403);
151
+ const name = member ? (typeof b.name === 'string' ? b.name.trim().slice(0, 80) : '') : (m.wall?.name ?? '');
152
+ const updated = await req.payload.update({
153
+ collection: membershipOf(req.payload).memberships,
154
+ id: m.id,
155
+ data: { wall: { show: member ? Boolean(b.show) && Boolean(name) : false, name: name || null } },
156
+ overrideAccess: true,
157
+ context: { membershipSync: true },
158
+ });
159
+ return json({ wall: updated.wall });
160
+ },
161
+ };
162
+ /** POST /api/<memberships>/stripe-webhook: Stripe events, verified with the endpoint's signing secret. */
163
+ export const webhookEndpoint = {
164
+ path: '/stripe-webhook',
165
+ method: 'post',
166
+ handler: async (req) => {
167
+ const o = membershipOf(req.payload);
168
+ const stripe = o.stripe();
169
+ if (!stripe || !o.webhookSecret)
170
+ return json({ error: 'Not configured.' }, 503);
171
+ const signature = req.headers.get('stripe-signature');
172
+ const raw = req.text ? await req.text() : '';
173
+ let event;
174
+ try {
175
+ event = stripe.webhooks.constructEvent(raw, signature ?? '', o.webhookSecret);
176
+ }
177
+ catch {
178
+ return json({ error: 'Invalid signature.' }, 400);
179
+ }
180
+ try {
181
+ return json({ received: true, result: await handleStripeEvent(req.payload, event) });
182
+ }
183
+ catch (err) {
184
+ req.payload.logger.error({ err, event: event.type }, 'Membership webhook failed');
185
+ return json({ error: 'Failed.' }, 500); // Stripe retries
186
+ }
187
+ },
188
+ };
@@ -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,161 @@
1
+ import type { CollectionConfig, Payload, PayloadRequest, Where } from 'payload';
2
+ /**
3
+ * Who manages tiers, categories and memberships in the admin (default: nobody but overrideAccess code).
4
+ * `true` is every row, a `Where` is only the rows it matches (e.g. `{ tenant: { equals: siteId } }`,
5
+ * written against the memberships collection and the `scopeField` of tiers and categories), anything
6
+ * else is no. An empty `{}` is no: return `true` for all.
7
+ */
8
+ export type CanManage = (args: {
9
+ req: PayloadRequest;
10
+ }) => boolean | Where | Promise<boolean | Where>;
11
+ export type Interval = 'month' | 'year';
12
+ /** A paid invoice, as recorded in the payments ledger. Amounts in the currency's minor unit (cents). */
13
+ export type PaymentRecord = {
14
+ id: string;
15
+ membership: string;
16
+ user: string;
17
+ amount: number;
18
+ currency: string;
19
+ paidAt: string;
20
+ invoiceId: string;
21
+ /** Pledged amounts per category in this payment (pledge memberships). */
22
+ pledges: {
23
+ category: string;
24
+ amount: number;
25
+ }[];
26
+ tier: string | null;
27
+ };
28
+ export type MembershipRecord = {
29
+ id: string;
30
+ user: string;
31
+ kind: 'tier' | 'pledge';
32
+ tier: string | null;
33
+ pledges: {
34
+ category: string;
35
+ amount: number;
36
+ }[];
37
+ interval: Interval;
38
+ amount: number;
39
+ currency: string;
40
+ status: MembershipStatus;
41
+ };
42
+ export type MembershipStatus = 'pending' | 'active' | 'past_due' | 'canceled' | 'incomplete';
43
+ /** The small part of the Stripe SDK the plugin uses (inject a fake in tests). */
44
+ export type StripeLike = {
45
+ checkout: {
46
+ sessions: {
47
+ create: (params: Record<string, unknown>) => Promise<{
48
+ id: string;
49
+ url: string | null;
50
+ }>;
51
+ };
52
+ };
53
+ billingPortal: {
54
+ sessions: {
55
+ create: (params: Record<string, unknown>) => Promise<{
56
+ url: string;
57
+ }>;
58
+ };
59
+ };
60
+ products: {
61
+ create: (params: Record<string, unknown>) => Promise<{
62
+ id: string;
63
+ }>;
64
+ };
65
+ subscriptions: {
66
+ retrieve: (id: string) => Promise<StripeSubscription>;
67
+ update: (id: string, params: Record<string, unknown>) => Promise<StripeSubscription>;
68
+ };
69
+ webhooks: {
70
+ constructEvent: (payload: string, signature: string, secret: string) => StripeEvent;
71
+ };
72
+ };
73
+ export type StripeSubscription = {
74
+ id: string;
75
+ status: string;
76
+ customer: string | {
77
+ id: string;
78
+ };
79
+ cancel_at_period_end?: boolean;
80
+ current_period_end?: number;
81
+ items: {
82
+ data: {
83
+ id: string;
84
+ current_period_end?: number;
85
+ }[];
86
+ };
87
+ metadata?: Record<string, string>;
88
+ };
89
+ export type StripeEvent = {
90
+ id: string;
91
+ type: string;
92
+ data: {
93
+ object: Record<string, unknown>;
94
+ };
95
+ };
96
+ export type MembershipPluginOptions = {
97
+ /** Slugs. Defaults: `membership-tiers`, `membership-categories`, `memberships`, `membership-payments`. */
98
+ slugs?: {
99
+ tiers?: string;
100
+ categories?: string;
101
+ memberships?: string;
102
+ payments?: string;
103
+ };
104
+ /** The auth collection of members. Default: `admin.user` of your config. */
105
+ users?: string;
106
+ /** Who manages tiers, categories and memberships in the admin. `true` (all rows) or a `Where` (those rows only) counts; anything else, `{}` and a throw included, is a no. */
107
+ canManage?: CanManage;
108
+ /** May members start memberships here right now (e.g. off in development)? Default: always. Only `true` allows it. */
109
+ canCheckout?: (args: {
110
+ payload: Payload;
111
+ }) => boolean | Promise<boolean>;
112
+ /** Stripe secret key (`sk_…`/`rk_…`), or a ready client. Without either, checkout is off. */
113
+ stripeSecretKey?: string;
114
+ stripe?: StripeLike;
115
+ /** Signing secret of the webhook endpoint (`whsec_…`) for `/api/<memberships>/stripe-webhook`. */
116
+ webhookSecret?: string;
117
+ /** ISO currency, lowercase. Default `usd`. */
118
+ currency?: string;
119
+ /** Public origin for Stripe return links. Default: `serverURL`. */
120
+ publicURL?: string;
121
+ /** A field that separates owners (e.g. `tenant`): new tiers/categories go A–Z among their own; memberships are per scope. */
122
+ scopeField?: string;
123
+ /** The scope of a request (e.g. the site of the request's host), stored on new memberships. */
124
+ scopeOf?: (req: PayloadRequest) => Promise<string | null> | string | null;
125
+ /** Called once per paid invoice (idempotent: never twice for the same invoice). Award perks, votes, credits here. */
126
+ onPayment?: (args: {
127
+ payload: Payload;
128
+ payment: PaymentRecord;
129
+ membership: MembershipRecord;
130
+ }) => Promise<void> | void;
131
+ /** Called when a membership's status changes (e.g. list or retire a sponsor-wall perk). */
132
+ onStatusChange?: (args: {
133
+ payload: Payload;
134
+ membership: MembershipRecord;
135
+ previous: MembershipStatus | null;
136
+ }) => Promise<void> | void;
137
+ /** Change the generated collections before they are added (fields, access, admin groups). */
138
+ overrides?: {
139
+ tiers?: (c: CollectionConfig) => CollectionConfig;
140
+ categories?: (c: CollectionConfig) => CollectionConfig;
141
+ memberships?: (c: CollectionConfig) => CollectionConfig;
142
+ payments?: (c: CollectionConfig) => CollectionConfig;
143
+ };
144
+ };
145
+ export type ResolvedMembership = {
146
+ tiers: string;
147
+ categories: string;
148
+ memberships: string;
149
+ payments: string;
150
+ users: string;
151
+ canManage: CanManage;
152
+ canCheckout?: MembershipPluginOptions['canCheckout'];
153
+ stripe: () => StripeLike | null;
154
+ webhookSecret?: string;
155
+ currency: string;
156
+ publicURL?: string;
157
+ scopeField?: string;
158
+ scopeOf?: MembershipPluginOptions['scopeOf'];
159
+ onPayment?: MembershipPluginOptions['onPayment'];
160
+ onStatusChange?: MembershipPluginOptions['onStatusChange'];
161
+ };
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.2.0",
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
+ }