@extantape/payload-plugin-membership 0.5.2 → 0.5.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/README.md +45 -2
- package/dist/api.d.ts +6 -1
- package/dist/api.js +179 -15
- package/dist/collections.js +18 -0
- package/dist/endpoints.js +11 -2
- package/dist/types.d.ts +3 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -75,8 +75,8 @@ In Stripe, add a webhook endpoint `https://<your site>/api/memberships/stripe-we
|
|
|
75
75
|
| Endpoint | Body | Result |
|
|
76
76
|
|---|---|---|
|
|
77
77
|
| `POST /api/memberships/checkout` | `{ tier }` or `{ pledges: [{ category, amount }] }`, `interval` (`month`/`year`), `wall?: { show, name }`, `successPath?`, `cancelPath?` | `{ url }` of Stripe Checkout |
|
|
78
|
-
| `POST /api/memberships/:id/change` | `{ tier }` or `{ pledges }` | the updated membership (from the next invoice) |
|
|
79
|
-
| `POST /api/memberships/:id/cancel` | | cancels at the end of the paid period |
|
|
78
|
+
| `POST /api/memberships/:id/change` | `{ tier }` or `{ pledges }` | the updated membership as the caller can read it (from the next invoice) |
|
|
79
|
+
| `POST /api/memberships/:id/cancel` | | cancels at the end of the paid period; answers with the membership as the caller can read it |
|
|
80
80
|
| `POST /api/memberships/:id/portal` | `{ returnPath? }` | `{ url }` of Stripe's customer portal |
|
|
81
81
|
| `POST /api/memberships/:id/wall` | `{ show, name }` | the member's backers-wall choice. A manager may only send `show: false` |
|
|
82
82
|
|
|
@@ -90,6 +90,49 @@ saves of a single record only: Payload's own REST routes by id for the plugin's
|
|
|
90
90
|
and the wall endpoint. A bulk PATCH (one with a `where`) that meets a conflict still answers 500,
|
|
91
91
|
with nothing of it stored. GraphQL and the Local API pass on the database's error as before.
|
|
92
92
|
|
|
93
|
+
`change` and `cancel` call Stripe first and save the membership after. If that save loses to another
|
|
94
|
+
save made at the same moment, Stripe has already taken the change, so they answer 409 with
|
|
95
|
+
`Your change went through with Stripe. Your membership will update shortly.` Don't send it again.
|
|
96
|
+
Nothing of the lost save is stored, and the membership catches up when Stripe's
|
|
97
|
+
`customer.subscription.updated` event arrives. For that, `change` writes the new plan (tier or
|
|
98
|
+
pledges, and the amount) into the subscription's metadata under `membershipPlan`, in the same Stripe
|
|
99
|
+
call, and the webhook reads it from the subscription as Stripe holds it at that moment. Once a
|
|
100
|
+
subscription carries a plan there, that plan is what the membership follows, so change plans through
|
|
101
|
+
`change` or `changeMembership`. A plan that names a tier or category that no longer exists, or one
|
|
102
|
+
from another site, is left out and the membership keeps what it has. `change` also sends Stripe an
|
|
103
|
+
idempotency key made from the membership, the new plan and the subscription's current items, so the
|
|
104
|
+
same change sent to Stripe twice is one change there. `cancel` sends no key: asking twice does no
|
|
105
|
+
harm. `changeMembership` and `cancelMembership` throw the same 409 to server code. The clash is
|
|
106
|
+
logged at error level with the membership's id.
|
|
107
|
+
|
|
108
|
+
`change` and `cancel` answer with the membership read again with the caller's own access, so the body is what
|
|
109
|
+
`GET /api/memberships/:id` would give them. A member's answer has no `stripe` ids, no staff `notes` and no
|
|
110
|
+
`changingUntil`; staff get what staff can read, and still never `changingUntil`.
|
|
111
|
+
|
|
112
|
+
Changing plan after a cancel keeps the membership going. `change` tells Stripe not to cancel at the end of
|
|
113
|
+
the period, so the cancel is lifted, whoever made it, and the member has to cancel again to stop it.
|
|
114
|
+
|
|
115
|
+
One change of plan or cancel runs at a time for a membership. `change` and `cancel` (staff cancel
|
|
116
|
+
included, it is the same endpoint) hold the membership before they call Stripe and give it back when
|
|
117
|
+
they are done. A second change or cancel sent meanwhile answers 409 with
|
|
118
|
+
`Another change to this membership is in progress. Try again in a moment.` Nothing is sent to Stripe
|
|
119
|
+
for it and nothing is stored, so it is safe to send again. This also means a cancel can't be undone
|
|
120
|
+
by a change that was already at Stripe. The hold lasts two minutes at most, so a process that stops
|
|
121
|
+
halfway can't leave a membership stuck. It lives in a hidden `changingUntil` field that only the
|
|
122
|
+
plugin writes. It shows up in the GraphQL types, reads return null, and `where`, `sort` and
|
|
123
|
+
`select` on it are refused.
|
|
124
|
+
|
|
125
|
+
The hold is atomic on MongoDB, where it is tested. On Postgres and SQLite it has not been run:
|
|
126
|
+
`updateOne` with a `where` may be a read followed by a write there, so two claims could both win. The
|
|
127
|
+
`changingUntil` field also needs a migration on those adapters, or changes will fail.
|
|
128
|
+
|
|
129
|
+
On `customer.subscription.updated` the webhook reads the subscription from Stripe and takes the
|
|
130
|
+
status, `cancelAtPeriodEnd`, the period end and the plan from what Stripe holds at that moment. The
|
|
131
|
+
event's own copy isn't used, so an older event that arrives late can't undo a cancel or bring an
|
|
132
|
+
older plan back. A subscription event reaches only the membership that already holds that
|
|
133
|
+
subscription's id, which `checkout.session.completed` sets. An event for any other subscription is
|
|
134
|
+
ignored.
|
|
135
|
+
|
|
93
136
|
## Options
|
|
94
137
|
|
|
95
138
|
| Option | Default | |
|
package/dist/api.d.ts
CHANGED
|
@@ -33,13 +33,18 @@ export declare function startCheckout(payload: Payload, args: Choice & {
|
|
|
33
33
|
url: string;
|
|
34
34
|
membership: string;
|
|
35
35
|
}>;
|
|
36
|
+
/** What a member is told when Stripe took the change and the membership's own save lost to another save made at the same moment. */
|
|
37
|
+
export declare const WENT_THROUGH_MESSAGE = "Your change went through with Stripe. Your membership will update shortly.";
|
|
38
|
+
/** How long a change of plan or a cancel may hold a membership. Past this, a claim left by a process that stopped no longer blocks. */
|
|
39
|
+
export declare const CHANGE_HOLD_MS: number;
|
|
40
|
+
export declare const CHANGE_IN_PROGRESS_MESSAGE = "Another change to this membership is in progress. Try again in a moment.";
|
|
36
41
|
/**
|
|
37
42
|
* Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice).
|
|
38
43
|
* With `scopeField`, only to tiers and categories of the membership's own site; a membership with no
|
|
39
44
|
* site can't be changed (404) until it is given one.
|
|
40
45
|
*/
|
|
41
46
|
export declare function changeMembership(payload: Payload, membershipId: string, choice: Omit<Choice, 'interval'>): Promise<Doc>;
|
|
42
|
-
/** Cancels at the end of the paid period (the member keeps their perks until then). */
|
|
47
|
+
/** Cancels at the end of the paid period (the member keeps their perks until then). Takes the same hold as a change of plan. */
|
|
43
48
|
export declare function cancelMembership(payload: Payload, membershipId: string): Promise<Doc>;
|
|
44
49
|
/** Stripe's customer portal (payment method, invoices, cancel). */
|
|
45
50
|
export declare function portalLink(payload: Payload, membershipId: string, returnURL: string): Promise<string>;
|
package/dist/api.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
import { APIError } from 'payload';
|
|
2
3
|
import { checkoutAllowed } from './access.js';
|
|
4
|
+
import { isDatabaseWriteConflict } from './guard.js';
|
|
3
5
|
const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
|
|
4
6
|
const ctx = { membershipSync: true };
|
|
5
7
|
export const membershipOf = (payload) => payload.config.custom?.membership;
|
|
@@ -124,6 +126,125 @@ export async function startCheckout(payload, args) {
|
|
|
124
126
|
throw new APIError('Stripe did not return a checkout page.', 502, undefined, true);
|
|
125
127
|
return { url: session.url, membership: String(membership.id) };
|
|
126
128
|
}
|
|
129
|
+
/** The subscription metadata keys that hold the plan, in pieces of at most 500 characters (Stripe's limit for one value). */
|
|
130
|
+
const PLAN_KEY = /^membershipPlan\d*$/;
|
|
131
|
+
const planKey = (i) => (i === 0 ? 'membershipPlan' : `membershipPlan${i}`);
|
|
132
|
+
/**
|
|
133
|
+
* The plan as subscription metadata, sent in the same Stripe call that changes the subscription, so
|
|
134
|
+
* Stripe holds what the membership should say. Pieces left over from a longer plan are cleared.
|
|
135
|
+
*/
|
|
136
|
+
function planMetadata(plan, existing) {
|
|
137
|
+
const text = JSON.stringify({ k: plan.kind, t: plan.tier, p: plan.pledges.map((p) => [p.category, p.amount]), a: plan.amount });
|
|
138
|
+
const out = {};
|
|
139
|
+
for (const k of Object.keys(existing ?? {}))
|
|
140
|
+
if (PLAN_KEY.test(k))
|
|
141
|
+
out[k] = ''; // an empty value removes the key
|
|
142
|
+
for (let i = 0; i * 500 < text.length; i++)
|
|
143
|
+
out[planKey(i)] = text.slice(i * 500, (i + 1) * 500);
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
const wholeAmount = (v) => typeof v === 'number' && Number.isInteger(v) && v > 0;
|
|
147
|
+
/** The plan in a subscription's metadata, or `null` when there is none or it isn't exactly the shape `planMetadata` writes. */
|
|
148
|
+
function planFrom(metadata) {
|
|
149
|
+
let text = '';
|
|
150
|
+
for (let i = 0; typeof metadata?.[planKey(i)] === 'string' && metadata[planKey(i)] !== ''; i++)
|
|
151
|
+
text += metadata[planKey(i)];
|
|
152
|
+
if (!text)
|
|
153
|
+
return null;
|
|
154
|
+
try {
|
|
155
|
+
const v = JSON.parse(text);
|
|
156
|
+
if (!v || typeof v !== 'object' || !wholeAmount(v.a) || !Array.isArray(v.p))
|
|
157
|
+
return null;
|
|
158
|
+
const pledges = [];
|
|
159
|
+
for (const row of v.p) {
|
|
160
|
+
if (!Array.isArray(row) || row.length !== 2 || typeof row[0] !== 'string' || row[0] === '' || !wholeAmount(row[1]))
|
|
161
|
+
return null;
|
|
162
|
+
pledges.push({ category: row[0], amount: row[1] });
|
|
163
|
+
}
|
|
164
|
+
if (v.k === 'tier')
|
|
165
|
+
return typeof v.t === 'string' && v.t !== '' && pledges.length === 0 ? { kind: 'tier', tier: v.t, pledges, amount: v.a } : null;
|
|
166
|
+
if (v.k !== 'pledge' || v.t !== null || pledges.length === 0 || pledges.length > 20)
|
|
167
|
+
return null;
|
|
168
|
+
if (new Set(pledges.map((p) => p.category)).size !== pledges.length || pledges.reduce((sum, p) => sum + p.amount, 0) !== v.a)
|
|
169
|
+
return null;
|
|
170
|
+
return { kind: 'pledge', tier: null, pledges, amount: v.a };
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const samePlan = (m, plan) => m.kind === plan.kind &&
|
|
177
|
+
idOf(m.tier) === plan.tier &&
|
|
178
|
+
m.amount === plan.amount &&
|
|
179
|
+
JSON.stringify((m.pledges ?? []).map((p) => [idOf(p.category), p.amount])) === JSON.stringify(plan.pledges.map((p) => [p.category, p.amount]));
|
|
180
|
+
/**
|
|
181
|
+
* The plan a membership should be given from its own subscription as Stripe holds it now (`live`),
|
|
182
|
+
* or `null` to leave it alone. A plan that names a tier or category that is gone, or one from
|
|
183
|
+
* another site, is left out, and the membership keeps what it has.
|
|
184
|
+
*/
|
|
185
|
+
async function planToApply(payload, o, m, live) {
|
|
186
|
+
if (!m.stripe?.subscription || m.stripe.subscription !== live.id)
|
|
187
|
+
return null;
|
|
188
|
+
const plan = planFrom(live.metadata);
|
|
189
|
+
if (!plan || samePlan(m, plan))
|
|
190
|
+
return null;
|
|
191
|
+
const site = scopeOfRow(o, m);
|
|
192
|
+
const usable = (d) => Boolean(d) && (!o.scopeField || (site !== null && idOf(d[o.scopeField]) === site));
|
|
193
|
+
const rows = plan.kind === 'tier' ? [[o.tiers, plan.tier]] : plan.pledges.map((p) => [o.categories, p.category]);
|
|
194
|
+
const names = [];
|
|
195
|
+
for (const [slug, id] of rows) {
|
|
196
|
+
const row = (await payload.findByID({ collection: slug, id, depth: 0, overrideAccess: true, disableErrors: true }).catch(() => null));
|
|
197
|
+
if (!usable(row)) {
|
|
198
|
+
payload.logger.warn({ membership: String(m.id) }, 'Membership: the plan on the Stripe subscription names a tier or category that isn’t available, so the membership was left as it is');
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
names.push(String(row.name));
|
|
202
|
+
}
|
|
203
|
+
const user = (await payload.findByID({ collection: o.users, id: idOf(m.user), depth: 0, overrideAccess: true, disableErrors: true }).catch(() => null));
|
|
204
|
+
return { kind: plan.kind, tier: plan.tier, pledges: plan.pledges, amount: plan.amount, label: `${user?.name || user?.email || 'Member'} · ${names.join(', ')}`.slice(0, 200) };
|
|
205
|
+
}
|
|
206
|
+
/** What a member is told when Stripe took the change and the membership's own save lost to another save made at the same moment. */
|
|
207
|
+
export const WENT_THROUGH_MESSAGE = 'Your change went through with Stripe. Your membership will update shortly.';
|
|
208
|
+
/** How long a change of plan or a cancel may hold a membership. Past this, a claim left by a process that stopped no longer blocks. */
|
|
209
|
+
export const CHANGE_HOLD_MS = 2 * 60 * 1000;
|
|
210
|
+
export const CHANGE_IN_PROGRESS_MESSAGE = 'Another change to this membership is in progress. Try again in a moment.';
|
|
211
|
+
/**
|
|
212
|
+
* Claims a membership for one change of plan: a single conditional write that sets `changingUntil`
|
|
213
|
+
* only when no claim is held or the one held has run out. Returns the value to release with, or
|
|
214
|
+
* `null` when another change holds it. Outside any transaction, so two claims can't both succeed.
|
|
215
|
+
*/
|
|
216
|
+
async function claimForChange(payload, o, id) {
|
|
217
|
+
const now = Date.now();
|
|
218
|
+
const until = new Date(now + CHANGE_HOLD_MS).toISOString();
|
|
219
|
+
const free = { or: [{ changingUntil: { exists: false } }, { changingUntil: { equals: null } }, { changingUntil: { less_than: new Date(now).toISOString() } }] };
|
|
220
|
+
const claimed = await payload.db.updateOne({ collection: o.memberships, where: { and: [{ id: { equals: id } }, free] }, data: { changingUntil: until } });
|
|
221
|
+
return claimed ? until : null;
|
|
222
|
+
}
|
|
223
|
+
/** Gives a claim back, only if it is still this one. A failure here is logged and left to the expiry. */
|
|
224
|
+
async function releaseChange(payload, o, id, until) {
|
|
225
|
+
try {
|
|
226
|
+
await payload.db.updateOne({ collection: o.memberships, where: { and: [{ id: { equals: id } }, { changingUntil: { equals: until } }] }, data: { changingUntil: null }, returning: false });
|
|
227
|
+
}
|
|
228
|
+
catch (err) {
|
|
229
|
+
payload.logger.warn({ err, membership: String(id) }, 'Membership: a change’s claim on the membership couldn’t be released; it runs out by itself');
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Saves a membership after Stripe has already taken the change. When the save loses to another
|
|
234
|
+
* save made at the same moment, nothing of it is stored and Stripe's next subscription event brings
|
|
235
|
+
* the membership up to date, so the caller gets a 409 that says so. Any other error is passed on.
|
|
236
|
+
*/
|
|
237
|
+
async function saveAfterStripe(payload, o, id, data) {
|
|
238
|
+
try {
|
|
239
|
+
return (await payload.update({ collection: o.memberships, id: id, data: data, overrideAccess: true, context: ctx }));
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
if (!isDatabaseWriteConflict(err))
|
|
243
|
+
throw err;
|
|
244
|
+
payload.logger.error({ err, membership: String(id) }, 'Membership: Stripe took the change, and the membership’s save lost to another save at the same moment. The next subscription event updates it.');
|
|
245
|
+
throw new APIError(WENT_THROUGH_MESSAGE, 409, undefined, true);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
127
248
|
/**
|
|
128
249
|
* Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice).
|
|
129
250
|
* With `scopeField`, only to tiers and categories of the membership's own site; a membership with no
|
|
@@ -137,28 +258,56 @@ export async function changeMembership(payload, membershipId, choice) {
|
|
|
137
258
|
const scope = o.scopeField ? requireScope(o, idOf(m[o.scopeField])) : null;
|
|
138
259
|
const { kind, lines, tier, pledges } = await linesFor(payload, o, { ...choice, interval: m.interval }, scope);
|
|
139
260
|
const stripe = stripeOf(o);
|
|
261
|
+
// One change of plan at a time: two at once would each swap the same items and Stripe could end
|
|
262
|
+
// up billing both. A second change is refused here, before Stripe hears of it.
|
|
263
|
+
const claim = await claimForChange(payload, o, m.id);
|
|
264
|
+
if (!claim)
|
|
265
|
+
throw new APIError(CHANGE_IN_PROGRESS_MESSAGE, 409, undefined, true);
|
|
266
|
+
try {
|
|
267
|
+
return await changeClaimed(payload, o, stripe, m, { kind, lines, tier, pledges });
|
|
268
|
+
}
|
|
269
|
+
finally {
|
|
270
|
+
await releaseChange(payload, o, m.id, claim);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
async function changeClaimed(payload, o, stripe, read, { kind, lines, tier, pledges }) {
|
|
274
|
+
// Read again now that the claim is held: an earlier change may have finished in between.
|
|
275
|
+
const m = (await payload.findByID({ collection: o.memberships, id: read.id, depth: 1, overrideAccess: true }));
|
|
276
|
+
if (!m.stripe?.subscription || m.stripe.subscription !== read.stripe.subscription || m.interval !== read.interval || !['active', 'past_due'].includes(m.status))
|
|
277
|
+
throw new APIError('Only a running membership can be changed.', 409, undefined, true);
|
|
140
278
|
const sub = await stripe.subscriptions.retrieve(m.stripe.subscription);
|
|
279
|
+
const plan = { kind, tier: tier ? String(tier.id) : null, pledges, amount: lines.reduce((sum, l) => sum + l.amount, 0) };
|
|
280
|
+
// The same change sent twice against the same subscription items is one change to Stripe.
|
|
281
|
+
const items = sub.items.data.map((i) => i.id);
|
|
282
|
+
const idempotencyKey = `membership-change-${createHash('sha256').update(JSON.stringify([String(m.id), plan.kind, plan.tier, plan.pledges.map((p) => [p.category, p.amount]), plan.amount, [...items].sort()])).digest('hex')}`;
|
|
141
283
|
await stripe.subscriptions.update(sub.id, {
|
|
142
|
-
items: [...
|
|
284
|
+
items: [...items.map((id) => ({ id, deleted: true })), ...lines.map((l) => ({ quantity: 1, price_data: priceData(o, l, m.interval) }))],
|
|
285
|
+
metadata: planMetadata(plan, sub.metadata),
|
|
143
286
|
proration_behavior: 'none',
|
|
144
287
|
cancel_at_period_end: false,
|
|
145
|
-
});
|
|
146
|
-
return (
|
|
147
|
-
collection: o.memberships,
|
|
148
|
-
id: m.id,
|
|
149
|
-
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) },
|
|
150
|
-
overrideAccess: true,
|
|
151
|
-
context: ctx,
|
|
152
|
-
}));
|
|
288
|
+
}, { idempotencyKey });
|
|
289
|
+
return saveAfterStripe(payload, o, m.id, { kind, tier: tier ? tier.id : null, pledges, amount: plan.amount, cancelAtPeriodEnd: false, label: labelOf(typeof m.user === 'object' ? m.user : { email: '' }, kind, tier, lines) });
|
|
153
290
|
}
|
|
154
|
-
/** Cancels at the end of the paid period (the member keeps their perks until then). */
|
|
291
|
+
/** Cancels at the end of the paid period (the member keeps their perks until then). Takes the same hold as a change of plan. */
|
|
155
292
|
export async function cancelMembership(payload, membershipId) {
|
|
156
293
|
const o = membershipOf(payload);
|
|
157
294
|
const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 0, overrideAccess: true }));
|
|
158
295
|
if (!m.stripe?.subscription)
|
|
159
296
|
throw new APIError('This membership has no subscription to cancel.', 409, undefined, true);
|
|
160
|
-
|
|
161
|
-
|
|
297
|
+
const stripe = stripeOf(o);
|
|
298
|
+
// A cancel takes the same hold as a change of plan. Without it, a change already at Stripe would
|
|
299
|
+
// send cancel_at_period_end: false after the cancel and quietly undo it. The loser gets a 409
|
|
300
|
+
// before anything reaches Stripe.
|
|
301
|
+
const claim = await claimForChange(payload, o, m.id);
|
|
302
|
+
if (!claim)
|
|
303
|
+
throw new APIError(CHANGE_IN_PROGRESS_MESSAGE, 409, undefined, true);
|
|
304
|
+
try {
|
|
305
|
+
await stripe.subscriptions.update(m.stripe.subscription, { cancel_at_period_end: true });
|
|
306
|
+
return await saveAfterStripe(payload, o, m.id, { cancelAtPeriodEnd: true });
|
|
307
|
+
}
|
|
308
|
+
finally {
|
|
309
|
+
await releaseChange(payload, o, m.id, claim);
|
|
310
|
+
}
|
|
162
311
|
}
|
|
163
312
|
/** Stripe's customer portal (payment method, invoices, cancel). */
|
|
164
313
|
export async function portalLink(payload, membershipId, returnURL) {
|
|
@@ -282,13 +431,28 @@ export async function handleStripeEvent(payload, event) {
|
|
|
282
431
|
}
|
|
283
432
|
case 'customer.subscription.updated':
|
|
284
433
|
case 'customer.subscription.deleted': {
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
|
|
434
|
+
const named = obj;
|
|
435
|
+
// Only the membership that already holds this subscription: an event for any other
|
|
436
|
+
// subscription changes nothing, whatever its metadata says.
|
|
437
|
+
const m = typeof named.id === 'string' && named.id !== '' ? await findBy(payload, o, { 'stripe.subscription': { equals: named.id } }) : undefined;
|
|
438
|
+
if (!m || m.stripe?.subscription !== named.id)
|
|
288
439
|
return 'ignored';
|
|
440
|
+
// Stripe can deliver an update late or out of order, so an update only says something may have
|
|
441
|
+
// changed: the status, the cancel flag, the period end and the plan are read from the
|
|
442
|
+
// subscription as Stripe holds it now. A deleted subscription is final, and is taken as sent.
|
|
443
|
+
let sub = named;
|
|
444
|
+
if (event.type === 'customer.subscription.updated') {
|
|
445
|
+
const live = await stripeOf(o).subscriptions.retrieve(named.id);
|
|
446
|
+
if (!live || live.id !== named.id || typeof live.status !== 'string')
|
|
447
|
+
return 'ignored';
|
|
448
|
+
sub = live;
|
|
449
|
+
}
|
|
289
450
|
const status = event.type === 'customer.subscription.deleted' ? 'canceled' : statusFrom(sub.status);
|
|
290
451
|
const end = periodEndOf(sub);
|
|
452
|
+
// A change of plan whose own save didn't land is brought in here.
|
|
453
|
+
const plan = event.type === 'customer.subscription.updated' ? await planToApply(payload, o, m, sub) : null;
|
|
291
454
|
await setMembership(payload, o, m, {
|
|
455
|
+
...(plan ?? {}),
|
|
292
456
|
status,
|
|
293
457
|
cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
|
|
294
458
|
...(end ? { currentPeriodEnd: new Date(end * 1000).toISOString() } : {}),
|
package/dist/collections.js
CHANGED
|
@@ -422,6 +422,24 @@ export function membershipsCollection(o) {
|
|
|
422
422
|
],
|
|
423
423
|
},
|
|
424
424
|
{ name: 'notes', type: 'textarea', access: { read: managerField, update: managerField }, hooks: fresh(), admin: { position: 'sidebar' } },
|
|
425
|
+
{
|
|
426
|
+
// Held for a moment by a change of plan or a cancel, so two can't reach Stripe at once. Written only by
|
|
427
|
+
// the plugin's own atomic claim and release; like totalPaid it is left out of every save, so
|
|
428
|
+
// a whole-document save can't put an older value back. It appears in the GraphQL types, but reads
|
|
429
|
+
// return null, and where, sort and select on it are refused.
|
|
430
|
+
name: 'changingUntil',
|
|
431
|
+
type: 'date',
|
|
432
|
+
access: { read: () => false, create: () => false, update: () => false },
|
|
433
|
+
hooks: {
|
|
434
|
+
beforeChange: [
|
|
435
|
+
({ siblingData }) => {
|
|
436
|
+
delete siblingData.changingUntil;
|
|
437
|
+
return undefined;
|
|
438
|
+
},
|
|
439
|
+
],
|
|
440
|
+
},
|
|
441
|
+
admin: { hidden: true, readOnly: true },
|
|
442
|
+
},
|
|
425
443
|
],
|
|
426
444
|
timestamps: true,
|
|
427
445
|
};
|
package/dist/endpoints.js
CHANGED
|
@@ -56,6 +56,15 @@ async function ownMembership(req, { memberOnly = false } = {}) {
|
|
|
56
56
|
const visible = await req.payload.count({ collection, where: { id: { equals: m.id } }, overrideAccess: false, user: req.user, req });
|
|
57
57
|
return visible.totalDocs > 0 ? m : null;
|
|
58
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* The membership as this request's user may read it: what `GET /:id` would answer. The save behind
|
|
61
|
+
* `change` and `cancel` runs with full access, so its document is never sent. A row the user can't
|
|
62
|
+
* read comes back as its id alone.
|
|
63
|
+
*/
|
|
64
|
+
async function readableAs(req, saved) {
|
|
65
|
+
const found = await req.payload.findByID({ collection: membershipOf(req.payload).memberships, id: String(saved.id), overrideAccess: false, user: req.user, req, disableErrors: true });
|
|
66
|
+
return found ?? { id: saved.id };
|
|
67
|
+
}
|
|
59
68
|
/** POST /api/<memberships>/checkout { tier? | pledges?, interval, wall?, successPath?, cancelPath? } → { url } */
|
|
60
69
|
export const checkoutEndpoint = {
|
|
61
70
|
path: '/checkout',
|
|
@@ -94,7 +103,7 @@ export const changeEndpoint = {
|
|
|
94
103
|
return json({ error: 'Not found.' }, 404);
|
|
95
104
|
try {
|
|
96
105
|
const b = await body(req);
|
|
97
|
-
return json({ membership: await changeMembership(req.payload, String(m.id), { tier: b.tier ?? null, pledges: Array.isArray(b.pledges) ? b.pledges : null }) });
|
|
106
|
+
return json({ membership: await readableAs(req, await changeMembership(req.payload, String(m.id), { tier: b.tier ?? null, pledges: Array.isArray(b.pledges) ? b.pledges : null })) });
|
|
98
107
|
}
|
|
99
108
|
catch (err) {
|
|
100
109
|
return fail(err);
|
|
@@ -110,7 +119,7 @@ export const cancelEndpoint = {
|
|
|
110
119
|
if (!m)
|
|
111
120
|
return json({ error: 'Not found.' }, 404);
|
|
112
121
|
try {
|
|
113
|
-
return json({ membership: await cancelMembership(req.payload, String(m.id)) });
|
|
122
|
+
return json({ membership: await readableAs(req, await cancelMembership(req.payload, String(m.id))) });
|
|
114
123
|
}
|
|
115
124
|
catch (err) {
|
|
116
125
|
return fail(err);
|
package/dist/types.d.ts
CHANGED
|
@@ -68,7 +68,9 @@ export type StripeLike = {
|
|
|
68
68
|
};
|
|
69
69
|
subscriptions: {
|
|
70
70
|
retrieve: (id: string) => Promise<StripeSubscription>;
|
|
71
|
-
update: (id: string, params: Record<string, unknown
|
|
71
|
+
update: (id: string, params: Record<string, unknown>, options?: {
|
|
72
|
+
idempotencyKey?: string;
|
|
73
|
+
}) => Promise<StripeSubscription>;
|
|
72
74
|
};
|
|
73
75
|
webhooks: {
|
|
74
76
|
constructEvent: (payload: string, signature: string, secret: string) => StripeEvent;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-membership",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.3",
|
|
4
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
5
|
"homepage": "https://github.com/ExtantApe/payload-plugin-membership#readme",
|
|
6
6
|
"bugs": {
|