better-auth-streampay 0.2.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -15
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/index.cjs +437 -288
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +434 -289
- package/dist/index.js.map +1 -1
- package/dist/{streampay-DeyntFo9.d.cts → streampay-DtFFwULq.d.cts} +297 -264
- package/dist/{streampay-DeyntFo9.d.ts → streampay-DtFFwULq.d.ts} +297 -264
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -5,7 +5,11 @@ import { createHmac, timingSafeEqual } from 'crypto';
|
|
|
5
5
|
// src/plugins/checkout.ts
|
|
6
6
|
|
|
7
7
|
// src/utils/consumer.ts
|
|
8
|
-
async function findConsumerByExternalId(client, {
|
|
8
|
+
async function findConsumerByExternalId(client, {
|
|
9
|
+
externalId,
|
|
10
|
+
maxPages = DEFAULT_CONSUMER_LOOKUP_MAX_PAGES,
|
|
11
|
+
pageSize = 100
|
|
12
|
+
}) {
|
|
9
13
|
const hit = await scanConsumers(
|
|
10
14
|
client,
|
|
11
15
|
{ maxPages, pageSize },
|
|
@@ -14,7 +18,7 @@ async function findConsumerByExternalId(client, { externalId, maxPages = 10, pag
|
|
|
14
18
|
return hit?.id ?? null;
|
|
15
19
|
}
|
|
16
20
|
async function findConsumerByIdentifiers(client, identifiers, opts = {}) {
|
|
17
|
-
const { maxPages =
|
|
21
|
+
const { maxPages = DEFAULT_CONSUMER_LOOKUP_MAX_PAGES, pageSize = 100 } = opts;
|
|
18
22
|
return scanConsumers(client, { maxPages, pageSize }, (c) => matchesAnyIdentifier(c, identifiers));
|
|
19
23
|
}
|
|
20
24
|
function matchesAnyIdentifier(consumer, identifiers) {
|
|
@@ -34,12 +38,213 @@ async function scanConsumers(client, { maxPages, pageSize }, predicate) {
|
|
|
34
38
|
const items = response.data ?? [];
|
|
35
39
|
const hit = items.find(predicate);
|
|
36
40
|
if (hit) return hit;
|
|
37
|
-
|
|
38
|
-
if (items.length < pageSize || page * pageSize >= total) return null;
|
|
41
|
+
if (response.pagination?.has_next_page !== true) return null;
|
|
39
42
|
}
|
|
40
43
|
return null;
|
|
41
44
|
}
|
|
42
45
|
|
|
46
|
+
// src/utils/format-error.ts
|
|
47
|
+
function formatStreamPayError(err) {
|
|
48
|
+
if (!(err instanceof Error)) return String(err);
|
|
49
|
+
if (!("body" in err)) return err.message;
|
|
50
|
+
const { body } = err;
|
|
51
|
+
if (!body || typeof body !== "object") return err.message;
|
|
52
|
+
const envelope = readEnvelopeMessage(body);
|
|
53
|
+
if (envelope !== null) return envelope;
|
|
54
|
+
const validation = readValidationMessage(body);
|
|
55
|
+
if (validation !== null) return validation;
|
|
56
|
+
try {
|
|
57
|
+
return JSON.stringify(body);
|
|
58
|
+
} catch {
|
|
59
|
+
return err.message;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function readEnvelopeMessage(body) {
|
|
63
|
+
if (!("error" in body) || !body.error || typeof body.error !== "object") {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
const error = body.error;
|
|
67
|
+
if ("additional_info" in error && typeof error.additional_info === "string") {
|
|
68
|
+
return error.additional_info;
|
|
69
|
+
}
|
|
70
|
+
if ("message" in error && typeof error.message === "string") {
|
|
71
|
+
return error.message;
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
function readValidationMessage(body) {
|
|
76
|
+
if (!("detail" in body) || !Array.isArray(body.detail) || body.detail.length === 0) {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
return body.detail.map(formatValidationEntry).join("; ");
|
|
80
|
+
}
|
|
81
|
+
function formatValidationEntry(entry) {
|
|
82
|
+
if (!entry || typeof entry !== "object") return String(entry);
|
|
83
|
+
const loc = "loc" in entry && Array.isArray(entry.loc) ? entry.loc.join(".") : "?";
|
|
84
|
+
const msg = "msg" in entry && typeof entry.msg === "string" ? entry.msg : "invalid";
|
|
85
|
+
return `${loc}: ${msg}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// src/utils/ensure-consumer.ts
|
|
89
|
+
var DEFAULT_CONSUMER_LOOKUP_MAX_PAGES = 100;
|
|
90
|
+
function resolveConsumerLookupMaxPages(options, override) {
|
|
91
|
+
const raw = override ?? options.consumerLookupMaxPages ?? DEFAULT_CONSUMER_LOOKUP_MAX_PAGES;
|
|
92
|
+
const coerced = Math.floor(Number(raw));
|
|
93
|
+
return Number.isFinite(coerced) ? Math.max(1, coerced) : DEFAULT_CONSUMER_LOOKUP_MAX_PAGES;
|
|
94
|
+
}
|
|
95
|
+
function sameEmail(a, b) {
|
|
96
|
+
if (!a || !b) return false;
|
|
97
|
+
return a.trim().toLowerCase() === b.trim().toLowerCase();
|
|
98
|
+
}
|
|
99
|
+
function samePhone(a, b) {
|
|
100
|
+
if (!a || !b) return false;
|
|
101
|
+
return a.trim() === b.trim();
|
|
102
|
+
}
|
|
103
|
+
function canClaimBy(mode, identifier) {
|
|
104
|
+
return mode?.includes(identifier) ?? false;
|
|
105
|
+
}
|
|
106
|
+
function isDuplicateConsumerError(err) {
|
|
107
|
+
if (!(err instanceof Error)) return false;
|
|
108
|
+
if (!("body" in err)) return false;
|
|
109
|
+
const { body } = err;
|
|
110
|
+
if (!body || typeof body !== "object") return false;
|
|
111
|
+
if (!("error" in body) || !body.error || typeof body.error !== "object") {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
const error = body.error;
|
|
115
|
+
return "code" in error && typeof error.code === "string" && error.code === "DUPLICATE_CONSUMER";
|
|
116
|
+
}
|
|
117
|
+
function isNotFoundError(err) {
|
|
118
|
+
if (!(err instanceof Error)) return false;
|
|
119
|
+
if (!("status" in err)) return false;
|
|
120
|
+
return typeof err.status === "number" && err.status === 404;
|
|
121
|
+
}
|
|
122
|
+
async function resolveDuplicateConsumer(options, createPayload, context) {
|
|
123
|
+
const maxPages = resolveConsumerLookupMaxPages(options);
|
|
124
|
+
const emailMatch = createPayload.email ? await findConsumerByIdentifiers(
|
|
125
|
+
options.client,
|
|
126
|
+
{ email: createPayload.email },
|
|
127
|
+
{ maxPages }
|
|
128
|
+
) : null;
|
|
129
|
+
const phoneMatch = !emailMatch && createPayload.phone_number ? await findConsumerByIdentifiers(
|
|
130
|
+
options.client,
|
|
131
|
+
{ phone_number: createPayload.phone_number },
|
|
132
|
+
{ maxPages }
|
|
133
|
+
) : null;
|
|
134
|
+
const identifiers = {
|
|
135
|
+
email: createPayload.email ?? null,
|
|
136
|
+
phone_number: createPayload.phone_number ?? null,
|
|
137
|
+
external_id: createPayload.external_id ?? null,
|
|
138
|
+
iban: createPayload.iban ?? null
|
|
139
|
+
};
|
|
140
|
+
const existing = emailMatch ?? phoneMatch ?? await findConsumerByIdentifiers(options.client, identifiers, { maxPages });
|
|
141
|
+
if (!existing?.id) return null;
|
|
142
|
+
if (existing.external_id) {
|
|
143
|
+
if (createPayload.external_id && existing.external_id === createPayload.external_id) {
|
|
144
|
+
return existing.id;
|
|
145
|
+
}
|
|
146
|
+
if (canClaimBy(options.claimExistingConsumerBy, "email") && sameEmail(existing.email, createPayload.email)) {
|
|
147
|
+
return existing.id;
|
|
148
|
+
}
|
|
149
|
+
if (canClaimBy(options.claimExistingConsumerBy, "phone") && samePhone(existing.phone_number, createPayload.phone_number)) {
|
|
150
|
+
return existing.id;
|
|
151
|
+
}
|
|
152
|
+
context.context.logger.error(
|
|
153
|
+
`StreamPay duplicate: consumer ${existing.id} is already linked to external_id=${existing.external_id}`
|
|
154
|
+
);
|
|
155
|
+
throw new APIError("CONFLICT", {
|
|
156
|
+
message: "This account cannot be created at this time. Please contact support."
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
return existing.id;
|
|
160
|
+
}
|
|
161
|
+
async function ensureConsumerForUser(options, ctx, user) {
|
|
162
|
+
if (user.streampayConsumerId) {
|
|
163
|
+
return { consumerId: user.streampayConsumerId, created: false };
|
|
164
|
+
}
|
|
165
|
+
const maxPages = resolveConsumerLookupMaxPages(options);
|
|
166
|
+
const recovered = await findConsumerByExternalId(options.client, {
|
|
167
|
+
externalId: user.id,
|
|
168
|
+
maxPages
|
|
169
|
+
});
|
|
170
|
+
if (recovered) {
|
|
171
|
+
await persistConsumerId(ctx, user.id, recovered);
|
|
172
|
+
return { consumerId: recovered, created: false };
|
|
173
|
+
}
|
|
174
|
+
if (!user.email) {
|
|
175
|
+
throw new APIError("BAD_REQUEST", {
|
|
176
|
+
message: "StreamPay requires an email address to create a consumer."
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
const userForParams = { id: user.id, email: user.email };
|
|
180
|
+
if (user.name !== void 0) userForParams.name = user.name;
|
|
181
|
+
const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user: userForParams }) : {};
|
|
182
|
+
const payload = {
|
|
183
|
+
name: user.name || user.email,
|
|
184
|
+
email: user.email,
|
|
185
|
+
external_id: user.id,
|
|
186
|
+
...extras
|
|
187
|
+
};
|
|
188
|
+
try {
|
|
189
|
+
const consumer = await options.client.createConsumer(payload);
|
|
190
|
+
if (!consumer.id) {
|
|
191
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
192
|
+
message: "StreamPay consumer was created but did not return an id."
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
await persistConsumerId(ctx, user.id, consumer.id);
|
|
196
|
+
return { consumerId: consumer.id, created: true };
|
|
197
|
+
} catch (err) {
|
|
198
|
+
if (err instanceof APIError) throw err;
|
|
199
|
+
if (isDuplicateConsumerError(err)) {
|
|
200
|
+
const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
|
|
201
|
+
if (reusedId) {
|
|
202
|
+
try {
|
|
203
|
+
await options.client.updateConsumer(reusedId, { external_id: user.id });
|
|
204
|
+
} catch (backfillErr) {
|
|
205
|
+
ctx.context.logger.error(
|
|
206
|
+
`StreamPay consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
await persistConsumerId(ctx, user.id, reusedId);
|
|
210
|
+
return { consumerId: reusedId, created: false };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
ctx.context.logger.error(
|
|
214
|
+
`StreamPay consumer creation failed for user=${user.id}: ${formatStreamPayError(err)}`
|
|
215
|
+
);
|
|
216
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
217
|
+
message: "StreamPay consumer provisioning failed. Please try again."
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async function persistConsumerId(ctx, userId, consumerId) {
|
|
222
|
+
try {
|
|
223
|
+
await ctx.context.internalAdapter.updateUser(userId, {
|
|
224
|
+
streampayConsumerId: consumerId
|
|
225
|
+
});
|
|
226
|
+
} catch (err) {
|
|
227
|
+
ctx.context.logger.error(
|
|
228
|
+
`StreamPay consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
function toAPIError(messageOrConfig, err, logger) {
|
|
233
|
+
if (err instanceof APIError) throw err;
|
|
234
|
+
const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
|
|
235
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
236
|
+
logger.error(`${logPrefix} ${detail}`);
|
|
237
|
+
throw new APIError("INTERNAL_SERVER_ERROR", { message: userMessage });
|
|
238
|
+
}
|
|
239
|
+
function rejectUnauthorized(user, anonymousMessage) {
|
|
240
|
+
if (!user) {
|
|
241
|
+
throw new APIError("UNAUTHORIZED", { message: "Session user is missing." });
|
|
242
|
+
}
|
|
243
|
+
if (user.isAnonymous) {
|
|
244
|
+
throw new APIError("UNAUTHORIZED", { message: anonymousMessage });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
43
248
|
// src/utils/session.ts
|
|
44
249
|
function asSessionUser(user) {
|
|
45
250
|
if (user === null || typeof user !== "object") return null;
|
|
@@ -137,13 +342,15 @@ function resolveRedirectUrl(urlOrPath, request, baseURL) {
|
|
|
137
342
|
if (!urlOrPath) return void 0;
|
|
138
343
|
return new URL(urlOrPath, request?.url ?? baseURL).toString();
|
|
139
344
|
}
|
|
140
|
-
async function resolveConsumerId(
|
|
345
|
+
async function resolveConsumerId(options, ctx, body, user) {
|
|
141
346
|
if (body.consumerId) return body.consumerId;
|
|
142
347
|
if (!user) return null;
|
|
143
|
-
if (user.
|
|
144
|
-
|
|
348
|
+
if (user.isAnonymous) return null;
|
|
349
|
+
const { consumerId } = await ensureConsumerForUser(options, ctx, user);
|
|
350
|
+
return consumerId;
|
|
145
351
|
}
|
|
146
|
-
var checkout = (checkoutOptions = {}) => (
|
|
352
|
+
var checkout = (checkoutOptions = {}) => (options) => {
|
|
353
|
+
const client = options.client;
|
|
147
354
|
return {
|
|
148
355
|
checkout: createAuthEndpoint(
|
|
149
356
|
"/checkout",
|
|
@@ -167,7 +374,7 @@ var checkout = (checkoutOptions = {}) => (client) => {
|
|
|
167
374
|
}
|
|
168
375
|
}
|
|
169
376
|
const items = await resolveProducts(ctx.body, checkoutOptions);
|
|
170
|
-
const consumerId = await resolveConsumerId(
|
|
377
|
+
const consumerId = await resolveConsumerId(options, ctx, ctx.body, sessionUser);
|
|
171
378
|
const successUrl = resolveRedirectUrl(
|
|
172
379
|
ctx.body.successUrl ?? checkoutOptions.successUrl,
|
|
173
380
|
ctx.request,
|
|
@@ -221,60 +428,52 @@ var checkout = (checkoutOptions = {}) => (client) => {
|
|
|
221
428
|
redirect: ctx.body.redirect ?? true
|
|
222
429
|
});
|
|
223
430
|
} catch (err) {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
431
|
+
toAPIError(
|
|
432
|
+
{
|
|
433
|
+
logPrefix: "StreamPay checkout creation failed:",
|
|
434
|
+
userMessage: "StreamPay checkout creation failed."
|
|
435
|
+
},
|
|
436
|
+
err,
|
|
437
|
+
ctx.context.logger
|
|
438
|
+
);
|
|
230
439
|
}
|
|
231
440
|
}
|
|
232
441
|
)
|
|
233
442
|
};
|
|
234
443
|
};
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
limit: z.coerce.number().int().positive().max(200).optional()
|
|
238
|
-
}).optional();
|
|
239
|
-
async function requireConsumerId(client, user, maxPages) {
|
|
240
|
-
if (!user) {
|
|
241
|
-
throw new APIError("UNAUTHORIZED", { message: "Session user is missing." });
|
|
242
|
-
}
|
|
444
|
+
async function getConsumerIdOrNull(client, user, maxPages) {
|
|
445
|
+
rejectUnauthorized(user, "Anonymous users cannot access the billing portal.");
|
|
243
446
|
if (user.streampayConsumerId) return user.streampayConsumerId;
|
|
244
|
-
|
|
447
|
+
return findConsumerByExternalId(client, {
|
|
245
448
|
externalId: user.id,
|
|
246
449
|
maxPages
|
|
247
450
|
});
|
|
248
|
-
if (!resolved) {
|
|
249
|
-
throw new APIError("NOT_FOUND", {
|
|
250
|
-
message: "No StreamPay consumer is linked to this user."
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
return resolved;
|
|
254
451
|
}
|
|
255
|
-
function
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
return result;
|
|
452
|
+
async function collectByConsumer(fetchPage, consumerId, maxPages) {
|
|
453
|
+
const out = [];
|
|
454
|
+
for (let page = 1; page <= maxPages; page++) {
|
|
455
|
+
const response = await fetchPage({ page, size: 100 });
|
|
456
|
+
for (const item of response.data ?? []) {
|
|
457
|
+
if (item.organization_consumer_id === consumerId) out.push(item);
|
|
458
|
+
}
|
|
459
|
+
if (response.pagination?.has_next_page !== true) break;
|
|
460
|
+
}
|
|
461
|
+
return out;
|
|
266
462
|
}
|
|
267
|
-
var portal = ({ consumerLookupMaxPages
|
|
463
|
+
var portal = ({ consumerLookupMaxPages } = {}) => (options) => {
|
|
464
|
+
const client = options.client;
|
|
465
|
+
const maxPages = resolveConsumerLookupMaxPages(options, consumerLookupMaxPages);
|
|
268
466
|
return {
|
|
269
467
|
state: createAuthEndpoint(
|
|
270
468
|
"/consumer/state",
|
|
271
469
|
{ method: "GET", use: [sessionMiddleware] },
|
|
272
470
|
async (ctx) => {
|
|
273
471
|
const user = asSessionUser(ctx.context.session?.user);
|
|
274
|
-
const consumerId = await
|
|
472
|
+
const consumerId = await getConsumerIdOrNull(client, user, maxPages);
|
|
473
|
+
if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
|
|
275
474
|
try {
|
|
276
475
|
const consumer = await client.getConsumer(consumerId);
|
|
277
|
-
return ctx.json(consumer);
|
|
476
|
+
return ctx.json({ hasConsumer: true, consumer });
|
|
278
477
|
} catch (err) {
|
|
279
478
|
toAPIError("StreamPay getConsumer failed.", err, ctx.context.logger);
|
|
280
479
|
}
|
|
@@ -282,22 +481,20 @@ var portal = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
|
|
|
282
481
|
),
|
|
283
482
|
subscriptions: createAuthEndpoint(
|
|
284
483
|
"/consumer/subscriptions/list",
|
|
285
|
-
{
|
|
286
|
-
method: "GET",
|
|
287
|
-
query: PaginationQuery,
|
|
288
|
-
use: [sessionMiddleware]
|
|
289
|
-
},
|
|
484
|
+
{ method: "GET", use: [sessionMiddleware] },
|
|
290
485
|
async (ctx) => {
|
|
291
486
|
const user = asSessionUser(ctx.context.session?.user);
|
|
292
|
-
const consumerId = await
|
|
487
|
+
const consumerId = await getConsumerIdOrNull(client, user, maxPages);
|
|
488
|
+
if (!consumerId) {
|
|
489
|
+
return ctx.json({ hasConsumer: false, data: [] });
|
|
490
|
+
}
|
|
293
491
|
try {
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
});
|
|
492
|
+
const items = await collectByConsumer(
|
|
493
|
+
(params) => client.listSubscriptions(params),
|
|
494
|
+
consumerId,
|
|
495
|
+
maxPages
|
|
496
|
+
);
|
|
497
|
+
return ctx.json({ hasConsumer: true, data: items });
|
|
301
498
|
} catch (err) {
|
|
302
499
|
toAPIError("StreamPay listSubscriptions failed.", err, ctx.context.logger);
|
|
303
500
|
}
|
|
@@ -305,50 +502,24 @@ var portal = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
|
|
|
305
502
|
),
|
|
306
503
|
invoices: createAuthEndpoint(
|
|
307
504
|
"/consumer/invoices/list",
|
|
308
|
-
{
|
|
309
|
-
method: "GET",
|
|
310
|
-
query: PaginationQuery,
|
|
311
|
-
use: [sessionMiddleware]
|
|
312
|
-
},
|
|
505
|
+
{ method: "GET", use: [sessionMiddleware] },
|
|
313
506
|
async (ctx) => {
|
|
314
507
|
const user = asSessionUser(ctx.context.session?.user);
|
|
315
|
-
const consumerId = await
|
|
508
|
+
const consumerId = await getConsumerIdOrNull(client, user, maxPages);
|
|
509
|
+
if (!consumerId) {
|
|
510
|
+
return ctx.json({ hasConsumer: false, data: [] });
|
|
511
|
+
}
|
|
316
512
|
try {
|
|
317
|
-
const
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
513
|
+
const items = await collectByConsumer(
|
|
514
|
+
(params) => client.listInvoices(params),
|
|
515
|
+
consumerId,
|
|
516
|
+
maxPages
|
|
321
517
|
);
|
|
322
|
-
return ctx.json({
|
|
518
|
+
return ctx.json({ hasConsumer: true, data: items });
|
|
323
519
|
} catch (err) {
|
|
324
520
|
toAPIError("StreamPay listInvoices failed.", err, ctx.context.logger);
|
|
325
521
|
}
|
|
326
522
|
}
|
|
327
|
-
),
|
|
328
|
-
payments: createAuthEndpoint(
|
|
329
|
-
"/consumer/payments/list",
|
|
330
|
-
{
|
|
331
|
-
method: "GET",
|
|
332
|
-
query: z.object({
|
|
333
|
-
page: z.coerce.number().int().positive().optional(),
|
|
334
|
-
limit: z.coerce.number().int().positive().max(200).optional(),
|
|
335
|
-
invoiceId: z.string().uuid().optional()
|
|
336
|
-
}).optional(),
|
|
337
|
-
use: [sessionMiddleware]
|
|
338
|
-
},
|
|
339
|
-
async (ctx) => {
|
|
340
|
-
const user = asSessionUser(ctx.context.session?.user);
|
|
341
|
-
await requireConsumerId(client, user, consumerLookupMaxPages);
|
|
342
|
-
const invoiceId = ctx.query?.invoiceId;
|
|
343
|
-
try {
|
|
344
|
-
const params = {};
|
|
345
|
-
if (invoiceId) params.invoice_id = invoiceId;
|
|
346
|
-
const result = await client.listPayments(params);
|
|
347
|
-
return ctx.json(result);
|
|
348
|
-
} catch (err) {
|
|
349
|
-
toAPIError("StreamPay listPayments failed.", err, ctx.context.logger);
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
523
|
)
|
|
353
524
|
};
|
|
354
525
|
};
|
|
@@ -362,24 +533,22 @@ var FreezeBody = z.object({
|
|
|
362
533
|
freezeEndDatetime: z.string().datetime().nullable().optional(),
|
|
363
534
|
notes: z.string().optional()
|
|
364
535
|
});
|
|
365
|
-
async function assertOwnsSubscription(
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
if (!consumerId) {
|
|
371
|
-
throw new APIError("NOT_FOUND", {
|
|
372
|
-
message: "No StreamPay consumer is linked to this user."
|
|
536
|
+
async function assertOwnsSubscription(options, _ctx, user, subscriptionId) {
|
|
537
|
+
rejectUnauthorized(user, "Anonymous users cannot manage subscriptions.");
|
|
538
|
+
if (!user.streampayConsumerId) {
|
|
539
|
+
throw new APIError("FORBIDDEN", {
|
|
540
|
+
message: "Subscription does not belong to this user."
|
|
373
541
|
});
|
|
374
542
|
}
|
|
375
|
-
const subscription = await client.getSubscription(subscriptionId);
|
|
376
|
-
if (subscription.organization_consumer_id !==
|
|
543
|
+
const subscription = await options.client.getSubscription(subscriptionId);
|
|
544
|
+
if (subscription.organization_consumer_id !== user.streampayConsumerId) {
|
|
377
545
|
throw new APIError("FORBIDDEN", {
|
|
378
546
|
message: "Subscription does not belong to this user."
|
|
379
547
|
});
|
|
380
548
|
}
|
|
381
549
|
}
|
|
382
|
-
var subscriptions = (
|
|
550
|
+
var subscriptions = (_subscriptionsOptions = {}) => (options) => {
|
|
551
|
+
const client = options.client;
|
|
383
552
|
return {
|
|
384
553
|
cancelSubscription: createAuthEndpoint(
|
|
385
554
|
"/consumer/subscriptions/cancel",
|
|
@@ -390,12 +559,7 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
|
|
|
390
559
|
},
|
|
391
560
|
async (ctx) => {
|
|
392
561
|
const sessionUser = asSessionUser(ctx.context.session?.user);
|
|
393
|
-
await assertOwnsSubscription(
|
|
394
|
-
client,
|
|
395
|
-
sessionUser,
|
|
396
|
-
ctx.body.subscriptionId,
|
|
397
|
-
consumerLookupMaxPages
|
|
398
|
-
);
|
|
562
|
+
await assertOwnsSubscription(options, ctx, sessionUser, ctx.body.subscriptionId);
|
|
399
563
|
const payload = {
|
|
400
564
|
cancel_related_invoices: ctx.body.cancelRelatedInvoices ?? false
|
|
401
565
|
};
|
|
@@ -403,12 +567,14 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
|
|
|
403
567
|
const result = await client.cancelSubscription(ctx.body.subscriptionId, payload);
|
|
404
568
|
return ctx.json(result);
|
|
405
569
|
} catch (err) {
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
570
|
+
toAPIError(
|
|
571
|
+
{
|
|
572
|
+
logPrefix: "StreamPay cancelSubscription failed:",
|
|
573
|
+
userMessage: "Subscription cancellation failed."
|
|
574
|
+
},
|
|
575
|
+
err,
|
|
576
|
+
ctx.context.logger
|
|
577
|
+
);
|
|
412
578
|
}
|
|
413
579
|
}
|
|
414
580
|
),
|
|
@@ -421,12 +587,7 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
|
|
|
421
587
|
},
|
|
422
588
|
async (ctx) => {
|
|
423
589
|
const sessionUser = asSessionUser(ctx.context.session?.user);
|
|
424
|
-
await assertOwnsSubscription(
|
|
425
|
-
client,
|
|
426
|
-
sessionUser,
|
|
427
|
-
ctx.body.subscriptionId,
|
|
428
|
-
consumerLookupMaxPages
|
|
429
|
-
);
|
|
590
|
+
await assertOwnsSubscription(options, ctx, sessionUser, ctx.body.subscriptionId);
|
|
430
591
|
const payload = {
|
|
431
592
|
freeze_start_datetime: ctx.body.freezeStartDatetime
|
|
432
593
|
};
|
|
@@ -440,12 +601,14 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
|
|
|
440
601
|
const result = await client.freezeSubscription(ctx.body.subscriptionId, payload);
|
|
441
602
|
return ctx.json(result);
|
|
442
603
|
} catch (err) {
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
604
|
+
toAPIError(
|
|
605
|
+
{
|
|
606
|
+
logPrefix: "StreamPay freezeSubscription failed:",
|
|
607
|
+
userMessage: "Subscription freeze failed."
|
|
608
|
+
},
|
|
609
|
+
err,
|
|
610
|
+
ctx.context.logger
|
|
611
|
+
);
|
|
449
612
|
}
|
|
450
613
|
}
|
|
451
614
|
)
|
|
@@ -453,38 +616,89 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
|
|
|
453
616
|
};
|
|
454
617
|
|
|
455
618
|
// src/webhooks/dispatcher.ts
|
|
456
|
-
var HANDLER_BY_EVENT = {
|
|
457
|
-
PAYMENT_SUCCEEDED: "onPaymentSucceeded",
|
|
458
|
-
PAYMENT_FAILED: "onPaymentFailed",
|
|
459
|
-
PAYMENT_CANCELED: "onPaymentCanceled",
|
|
460
|
-
PAYMENT_REFUNDED: "onPaymentRefunded",
|
|
461
|
-
PAYMENT_MARKED_AS_PAID: "onPaymentMarkedAsPaid",
|
|
462
|
-
INVOICE_CREATED: "onInvoiceCreated",
|
|
463
|
-
INVOICE_SENT: "onInvoiceSent",
|
|
464
|
-
INVOICE_ACCEPTED: "onInvoiceAccepted",
|
|
465
|
-
INVOICE_REJECTED: "onInvoiceRejected",
|
|
466
|
-
INVOICE_COMPLETED: "onInvoiceCompleted",
|
|
467
|
-
INVOICE_CANCELED: "onInvoiceCanceled",
|
|
468
|
-
INVOICE_UPDATED: "onInvoiceUpdated",
|
|
469
|
-
SUBSCRIPTION_CREATED: "onSubscriptionCreated",
|
|
470
|
-
SUBSCRIPTION_ACTIVATED: "onSubscriptionActivated",
|
|
471
|
-
SUBSCRIPTION_INACTIVATED: "onSubscriptionInactivated",
|
|
472
|
-
SUBSCRIPTION_CANCELED: "onSubscriptionCanceled",
|
|
473
|
-
SUBSCRIPTION_FROZEN: "onSubscriptionFrozen",
|
|
474
|
-
SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "onSubscriptionCycleRenewalFailed",
|
|
475
|
-
SUBSCRIPTION_CANCEL_AT_PERIOD_END: "onSubscriptionCancelAtPeriodEnd",
|
|
476
|
-
SUBSCRIPTION_FREEZE_NOW: "onSubscriptionFreezeNow",
|
|
477
|
-
SUBSCRIPTION_UNFREEZE_NOW: "onSubscriptionUnfreezeNow",
|
|
478
|
-
SUBSCRIPTION_UNFREEZE_FUTURE: "onSubscriptionUnfreezeFuture",
|
|
479
|
-
SUBSCRIPTION_FREEZE_CANCEL: "onSubscriptionFreezeCancel",
|
|
480
|
-
PAYMENT_LINK_PAY_ATTEMPT_FAILED: "onPaymentLinkPayAttemptFailed"
|
|
481
|
-
};
|
|
482
619
|
async function dispatchWebhook(payload, handlers) {
|
|
483
620
|
if (handlers.onPayload) await handlers.onPayload(payload);
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
621
|
+
switch (payload.event_type) {
|
|
622
|
+
// Payment
|
|
623
|
+
case "PAYMENT_SUCCEEDED":
|
|
624
|
+
await handlers.onPaymentSucceeded?.(payload);
|
|
625
|
+
return;
|
|
626
|
+
case "PAYMENT_FAILED":
|
|
627
|
+
await handlers.onPaymentFailed?.(payload);
|
|
628
|
+
return;
|
|
629
|
+
case "PAYMENT_CANCELED":
|
|
630
|
+
await handlers.onPaymentCanceled?.(payload);
|
|
631
|
+
return;
|
|
632
|
+
case "PAYMENT_REFUNDED":
|
|
633
|
+
await handlers.onPaymentRefunded?.(payload);
|
|
634
|
+
return;
|
|
635
|
+
case "PAYMENT_MARKED_AS_PAID":
|
|
636
|
+
await handlers.onPaymentMarkedAsPaid?.(payload);
|
|
637
|
+
return;
|
|
638
|
+
// Invoice
|
|
639
|
+
case "INVOICE_CREATED":
|
|
640
|
+
await handlers.onInvoiceCreated?.(payload);
|
|
641
|
+
return;
|
|
642
|
+
case "INVOICE_SENT":
|
|
643
|
+
await handlers.onInvoiceSent?.(payload);
|
|
644
|
+
return;
|
|
645
|
+
case "INVOICE_ACCEPTED":
|
|
646
|
+
await handlers.onInvoiceAccepted?.(payload);
|
|
647
|
+
return;
|
|
648
|
+
case "INVOICE_REJECTED":
|
|
649
|
+
await handlers.onInvoiceRejected?.(payload);
|
|
650
|
+
return;
|
|
651
|
+
case "INVOICE_COMPLETED":
|
|
652
|
+
await handlers.onInvoiceCompleted?.(payload);
|
|
653
|
+
return;
|
|
654
|
+
case "INVOICE_CANCELED":
|
|
655
|
+
await handlers.onInvoiceCanceled?.(payload);
|
|
656
|
+
return;
|
|
657
|
+
case "INVOICE_UPDATED":
|
|
658
|
+
await handlers.onInvoiceUpdated?.(payload);
|
|
659
|
+
return;
|
|
660
|
+
// Subscription
|
|
661
|
+
case "SUBSCRIPTION_CREATED":
|
|
662
|
+
await handlers.onSubscriptionCreated?.(payload);
|
|
663
|
+
return;
|
|
664
|
+
case "SUBSCRIPTION_ACTIVATED":
|
|
665
|
+
await handlers.onSubscriptionActivated?.(payload);
|
|
666
|
+
return;
|
|
667
|
+
case "SUBSCRIPTION_INACTIVATED":
|
|
668
|
+
await handlers.onSubscriptionInactivated?.(payload);
|
|
669
|
+
return;
|
|
670
|
+
case "SUBSCRIPTION_CANCELED":
|
|
671
|
+
await handlers.onSubscriptionCanceled?.(payload);
|
|
672
|
+
return;
|
|
673
|
+
case "SUBSCRIPTION_FROZEN":
|
|
674
|
+
await handlers.onSubscriptionFrozen?.(payload);
|
|
675
|
+
return;
|
|
676
|
+
case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
|
|
677
|
+
await handlers.onSubscriptionCycleRenewalFailed?.(payload);
|
|
678
|
+
return;
|
|
679
|
+
case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
|
|
680
|
+
await handlers.onSubscriptionCancelAtPeriodEnd?.(payload);
|
|
681
|
+
return;
|
|
682
|
+
case "SUBSCRIPTION_FREEZE_NOW":
|
|
683
|
+
await handlers.onSubscriptionFreezeNow?.(payload);
|
|
684
|
+
return;
|
|
685
|
+
case "SUBSCRIPTION_UNFREEZE_NOW":
|
|
686
|
+
await handlers.onSubscriptionUnfreezeNow?.(payload);
|
|
687
|
+
return;
|
|
688
|
+
case "SUBSCRIPTION_UNFREEZE_FUTURE":
|
|
689
|
+
await handlers.onSubscriptionUnfreezeFuture?.(payload);
|
|
690
|
+
return;
|
|
691
|
+
case "SUBSCRIPTION_FREEZE_CANCEL":
|
|
692
|
+
await handlers.onSubscriptionFreezeCancel?.(payload);
|
|
693
|
+
return;
|
|
694
|
+
// Payment Link
|
|
695
|
+
case "PAYMENT_LINK_PAY_ATTEMPT_FAILED":
|
|
696
|
+
await handlers.onPaymentLinkPayAttemptFailed?.(payload);
|
|
697
|
+
return;
|
|
698
|
+
default: {
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
488
702
|
}
|
|
489
703
|
var StreamPayWebhookError = class extends Error {
|
|
490
704
|
reason;
|
|
@@ -552,8 +766,8 @@ function parseWebhookPayload(value) {
|
|
|
552
766
|
function toErrorCode(reason) {
|
|
553
767
|
return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
|
|
554
768
|
}
|
|
555
|
-
var webhooks = (
|
|
556
|
-
const { secret, toleranceSeconds, ...handlers } =
|
|
769
|
+
var webhooks = (webhooksOptions) => (_options) => {
|
|
770
|
+
const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
|
|
557
771
|
return {
|
|
558
772
|
streampayWebhooks: createAuthEndpoint(
|
|
559
773
|
"/streampay/webhooks",
|
|
@@ -618,61 +832,9 @@ var webhooks = (options) => (_client) => {
|
|
|
618
832
|
)
|
|
619
833
|
};
|
|
620
834
|
};
|
|
621
|
-
|
|
622
|
-
// src/utils/format-error.ts
|
|
623
|
-
function formatStreamPayError(err) {
|
|
624
|
-
if (!(err instanceof Error)) return String(err);
|
|
625
|
-
if (!("body" in err)) return err.message;
|
|
626
|
-
const { body } = err;
|
|
627
|
-
if (!body || typeof body !== "object") return err.message;
|
|
628
|
-
const envelope = readEnvelopeMessage(body);
|
|
629
|
-
if (envelope !== null) return envelope;
|
|
630
|
-
const validation = readValidationMessage(body);
|
|
631
|
-
if (validation !== null) return validation;
|
|
632
|
-
try {
|
|
633
|
-
return JSON.stringify(body);
|
|
634
|
-
} catch {
|
|
635
|
-
return err.message;
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
function readEnvelopeMessage(body) {
|
|
639
|
-
if (!("error" in body) || !body.error || typeof body.error !== "object") {
|
|
640
|
-
return null;
|
|
641
|
-
}
|
|
642
|
-
const error = body.error;
|
|
643
|
-
if ("additional_info" in error && typeof error.additional_info === "string") {
|
|
644
|
-
return error.additional_info;
|
|
645
|
-
}
|
|
646
|
-
if ("message" in error && typeof error.message === "string") {
|
|
647
|
-
return error.message;
|
|
648
|
-
}
|
|
649
|
-
return null;
|
|
650
|
-
}
|
|
651
|
-
function readValidationMessage(body) {
|
|
652
|
-
if (!("detail" in body) || !Array.isArray(body.detail) || body.detail.length === 0) {
|
|
653
|
-
return null;
|
|
654
|
-
}
|
|
655
|
-
return body.detail.map(formatValidationEntry).join("; ");
|
|
656
|
-
}
|
|
657
|
-
function formatValidationEntry(entry) {
|
|
658
|
-
if (!entry || typeof entry !== "object") return String(entry);
|
|
659
|
-
const loc = "loc" in entry && Array.isArray(entry.loc) ? entry.loc.join(".") : "?";
|
|
660
|
-
const msg = "msg" in entry && typeof entry.msg === "string" ? entry.msg : "invalid";
|
|
661
|
-
return `${loc}: ${msg}`;
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
// src/hooks/consumer.ts
|
|
665
835
|
var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
|
|
666
|
-
function
|
|
667
|
-
|
|
668
|
-
return a.trim().toLowerCase() === b.trim().toLowerCase();
|
|
669
|
-
}
|
|
670
|
-
function samePhone(a, b) {
|
|
671
|
-
if (!a || !b) return false;
|
|
672
|
-
return a.trim() === b.trim();
|
|
673
|
-
}
|
|
674
|
-
function canClaimBy(mode, identifier) {
|
|
675
|
-
return mode?.includes(identifier) ?? false;
|
|
836
|
+
function hasInternalAdapter(ctx) {
|
|
837
|
+
return "internalAdapter" in ctx.context && ctx.context.internalAdapter !== null && typeof ctx.context.internalAdapter === "object" && "updateUser" in ctx.context.internalAdapter && typeof ctx.context.internalAdapter.updateUser === "function";
|
|
676
838
|
}
|
|
677
839
|
var onBeforeUserCreate = (options) => async (user, context) => {
|
|
678
840
|
if (!context || !options.createConsumerOnSignUp) return void 0;
|
|
@@ -704,55 +866,14 @@ var onBeforeUserCreate = (options) => async (user, context) => {
|
|
|
704
866
|
return { data: { streampayConsumerId: reusedId } };
|
|
705
867
|
}
|
|
706
868
|
}
|
|
707
|
-
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
708
|
-
message: `StreamPay consumer creation failed: ${formatStreamPayError(err)}`
|
|
709
|
-
});
|
|
710
|
-
}
|
|
711
|
-
};
|
|
712
|
-
function isDuplicateConsumerError(err) {
|
|
713
|
-
if (!(err instanceof Error)) return false;
|
|
714
|
-
if (!("body" in err)) return false;
|
|
715
|
-
const { body } = err;
|
|
716
|
-
if (!body || typeof body !== "object") return false;
|
|
717
|
-
if (!("error" in body) || !body.error || typeof body.error !== "object") {
|
|
718
|
-
return false;
|
|
719
|
-
}
|
|
720
|
-
const error = body.error;
|
|
721
|
-
return "code" in error && typeof error.code === "string" && error.code === "DUPLICATE_CONSUMER";
|
|
722
|
-
}
|
|
723
|
-
async function resolveDuplicateConsumer(options, createPayload, context) {
|
|
724
|
-
const emailMatch = createPayload.email ? await findConsumerByIdentifiers(options.client, {
|
|
725
|
-
email: createPayload.email
|
|
726
|
-
}) : null;
|
|
727
|
-
const phoneMatch = !emailMatch && createPayload.phone_number ? await findConsumerByIdentifiers(options.client, {
|
|
728
|
-
phone_number: createPayload.phone_number
|
|
729
|
-
}) : null;
|
|
730
|
-
const identifiers = {
|
|
731
|
-
email: createPayload.email ?? null,
|
|
732
|
-
phone_number: createPayload.phone_number ?? null,
|
|
733
|
-
external_id: createPayload.external_id ?? null,
|
|
734
|
-
iban: createPayload.iban ?? null
|
|
735
|
-
};
|
|
736
|
-
const existing = emailMatch ?? phoneMatch ?? await findConsumerByIdentifiers(options.client, identifiers);
|
|
737
|
-
if (!existing?.id) {
|
|
738
|
-
return null;
|
|
739
|
-
}
|
|
740
|
-
if (existing.external_id) {
|
|
741
|
-
if (canClaimBy(options.claimExistingConsumerBy, "email") && sameEmail(existing.email, createPayload.email)) {
|
|
742
|
-
return existing.id;
|
|
743
|
-
}
|
|
744
|
-
if (canClaimBy(options.claimExistingConsumerBy, "phone") && samePhone(existing.phone_number, createPayload.phone_number)) {
|
|
745
|
-
return existing.id;
|
|
746
|
-
}
|
|
747
869
|
context.context.logger.error(
|
|
748
|
-
`StreamPay
|
|
870
|
+
`StreamPay consumer creation failed for user=${user.id ?? "<pre-insert>"}: ${formatStreamPayError(err)}`
|
|
749
871
|
);
|
|
750
|
-
throw new APIError("
|
|
751
|
-
message: "
|
|
872
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
873
|
+
message: "StreamPay consumer provisioning failed. Please try again."
|
|
752
874
|
});
|
|
753
875
|
}
|
|
754
|
-
|
|
755
|
-
}
|
|
876
|
+
};
|
|
756
877
|
var onAfterUserCreate = (options) => async (user, context) => {
|
|
757
878
|
if (!context || !options.createConsumerOnSignUp) return;
|
|
758
879
|
if (isAnonymous(user)) return;
|
|
@@ -764,51 +885,67 @@ var onAfterUserCreate = (options) => async (user, context) => {
|
|
|
764
885
|
});
|
|
765
886
|
} catch (err) {
|
|
766
887
|
context.context.logger.error(
|
|
767
|
-
`StreamPay consumer external_id link failed: ${formatStreamPayError(err)}`
|
|
888
|
+
`StreamPay consumer external_id link failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
|
|
768
889
|
);
|
|
769
890
|
}
|
|
770
891
|
};
|
|
771
892
|
var onUserUpdate = (options) => async (user, context) => {
|
|
772
|
-
if (!context
|
|
893
|
+
if (!context) return;
|
|
773
894
|
if (isAnonymous(user)) return;
|
|
774
895
|
const sessionUser = asSessionUser(user);
|
|
775
|
-
if (!sessionUser) return;
|
|
776
|
-
const consumerId = await resolveConsumerId2(options, sessionUser);
|
|
777
|
-
if (!consumerId) return;
|
|
778
|
-
const update = {};
|
|
779
|
-
if (sessionUser.name !== void 0) update.name = sessionUser.name;
|
|
780
|
-
if (sessionUser.email !== void 0) update.email = sessionUser.email;
|
|
896
|
+
if (!sessionUser?.streampayConsumerId) return;
|
|
781
897
|
try {
|
|
782
|
-
await options.client.
|
|
898
|
+
const remote = await options.client.getConsumer(sessionUser.streampayConsumerId);
|
|
899
|
+
if (remote.is_deleted === true) return;
|
|
900
|
+
const patch = {};
|
|
901
|
+
if (sessionUser.name !== void 0 && remote.name !== sessionUser.name) {
|
|
902
|
+
patch.name = sessionUser.name;
|
|
903
|
+
}
|
|
904
|
+
if (sessionUser.email !== void 0 && remote.email !== sessionUser.email) {
|
|
905
|
+
patch.email = sessionUser.email;
|
|
906
|
+
}
|
|
907
|
+
if (Object.keys(patch).length === 0) return;
|
|
908
|
+
await options.client.updateConsumer(sessionUser.streampayConsumerId, patch);
|
|
783
909
|
} catch (err) {
|
|
910
|
+
if (isNotFoundError(err)) {
|
|
911
|
+
context.context.logger.error(
|
|
912
|
+
`StreamPay consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
|
|
913
|
+
);
|
|
914
|
+
if (hasInternalAdapter(context)) {
|
|
915
|
+
try {
|
|
916
|
+
await context.context.internalAdapter.updateUser(sessionUser.id, {
|
|
917
|
+
streampayConsumerId: null
|
|
918
|
+
});
|
|
919
|
+
} catch (clearErr) {
|
|
920
|
+
context.context.logger.error(
|
|
921
|
+
`StreamPay stale-link clear failed for user=${sessionUser.id}: ${formatStreamPayError(clearErr)}`
|
|
922
|
+
);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
784
927
|
context.context.logger.error(
|
|
785
|
-
`StreamPay consumer update failed: ${formatStreamPayError(err)}`
|
|
928
|
+
`StreamPay consumer update failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
|
|
786
929
|
);
|
|
787
930
|
}
|
|
788
931
|
};
|
|
789
932
|
var onUserDelete = (options) => async (user, context) => {
|
|
790
|
-
if (!context
|
|
933
|
+
if (!context) return;
|
|
791
934
|
if (isAnonymous(user)) return;
|
|
792
935
|
const sessionUser = asSessionUser(user);
|
|
793
|
-
if (!sessionUser) return;
|
|
794
|
-
const consumerId = await resolveConsumerId2(options, sessionUser);
|
|
795
|
-
if (!consumerId) return;
|
|
936
|
+
if (!sessionUser?.streampayConsumerId) return;
|
|
796
937
|
try {
|
|
797
|
-
await options.client.deleteConsumer(
|
|
938
|
+
await options.client.deleteConsumer(sessionUser.streampayConsumerId);
|
|
798
939
|
} catch (err) {
|
|
799
940
|
context.context.logger.error(
|
|
800
|
-
`StreamPay consumer delete failed: ${formatStreamPayError(err)}`
|
|
941
|
+
`StreamPay consumer delete failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
|
|
801
942
|
);
|
|
802
943
|
}
|
|
803
944
|
};
|
|
804
|
-
async function resolveConsumerId2(options, user) {
|
|
805
|
-
if (user.streampayConsumerId) return user.streampayConsumerId;
|
|
806
|
-
return findConsumerByExternalId(options.client, { externalId: user.id });
|
|
807
|
-
}
|
|
808
945
|
|
|
809
946
|
// src/streampay.ts
|
|
810
947
|
var streampay = (options) => {
|
|
811
|
-
const endpoints = options.use.map((use) => use(options
|
|
948
|
+
const endpoints = options.use.map((use) => use(options)).reduce((acc, plugin) => {
|
|
812
949
|
Object.assign(acc, plugin);
|
|
813
950
|
return acc;
|
|
814
951
|
}, {});
|
|
@@ -850,22 +987,23 @@ var streampay = (options) => {
|
|
|
850
987
|
};
|
|
851
988
|
|
|
852
989
|
// src/webhooks/events.ts
|
|
853
|
-
var
|
|
854
|
-
// Payment
|
|
990
|
+
var STREAMPAY_PAYMENT_EVENT_TYPES = [
|
|
855
991
|
"PAYMENT_SUCCEEDED",
|
|
856
992
|
"PAYMENT_FAILED",
|
|
857
993
|
"PAYMENT_CANCELED",
|
|
858
994
|
"PAYMENT_REFUNDED",
|
|
859
|
-
"PAYMENT_MARKED_AS_PAID"
|
|
860
|
-
|
|
995
|
+
"PAYMENT_MARKED_AS_PAID"
|
|
996
|
+
];
|
|
997
|
+
var STREAMPAY_INVOICE_EVENT_TYPES = [
|
|
861
998
|
"INVOICE_CREATED",
|
|
862
999
|
"INVOICE_SENT",
|
|
863
1000
|
"INVOICE_ACCEPTED",
|
|
864
1001
|
"INVOICE_REJECTED",
|
|
865
1002
|
"INVOICE_COMPLETED",
|
|
866
1003
|
"INVOICE_CANCELED",
|
|
867
|
-
"INVOICE_UPDATED"
|
|
868
|
-
|
|
1004
|
+
"INVOICE_UPDATED"
|
|
1005
|
+
];
|
|
1006
|
+
var STREAMPAY_SUBSCRIPTION_EVENT_TYPES = [
|
|
869
1007
|
"SUBSCRIPTION_CREATED",
|
|
870
1008
|
"SUBSCRIPTION_ACTIVATED",
|
|
871
1009
|
"SUBSCRIPTION_INACTIVATED",
|
|
@@ -876,11 +1014,18 @@ var STREAMPAY_EVENT_TYPES = [
|
|
|
876
1014
|
"SUBSCRIPTION_FREEZE_NOW",
|
|
877
1015
|
"SUBSCRIPTION_UNFREEZE_NOW",
|
|
878
1016
|
"SUBSCRIPTION_UNFREEZE_FUTURE",
|
|
879
|
-
"SUBSCRIPTION_FREEZE_CANCEL"
|
|
880
|
-
|
|
1017
|
+
"SUBSCRIPTION_FREEZE_CANCEL"
|
|
1018
|
+
];
|
|
1019
|
+
var STREAMPAY_PAYMENT_LINK_EVENT_TYPES = [
|
|
881
1020
|
"PAYMENT_LINK_PAY_ATTEMPT_FAILED"
|
|
882
1021
|
];
|
|
1022
|
+
var STREAMPAY_EVENT_TYPES = [
|
|
1023
|
+
...STREAMPAY_PAYMENT_EVENT_TYPES,
|
|
1024
|
+
...STREAMPAY_INVOICE_EVENT_TYPES,
|
|
1025
|
+
...STREAMPAY_SUBSCRIPTION_EVENT_TYPES,
|
|
1026
|
+
...STREAMPAY_PAYMENT_LINK_EVENT_TYPES
|
|
1027
|
+
];
|
|
883
1028
|
|
|
884
|
-
export { CheckoutBody, STREAMPAY_EVENT_TYPES, StreamPayWebhookError, checkout, dispatchWebhook, findConsumerByExternalId, findConsumerByIdentifiers, formatStreamPayError, portal, streampay, subscriptions, verifyWebhook, verifyWebhookOrThrow, webhooks };
|
|
1029
|
+
export { CheckoutBody, STREAMPAY_EVENT_TYPES, STREAMPAY_INVOICE_EVENT_TYPES, STREAMPAY_PAYMENT_EVENT_TYPES, STREAMPAY_PAYMENT_LINK_EVENT_TYPES, STREAMPAY_SUBSCRIPTION_EVENT_TYPES, StreamPayWebhookError, checkout, dispatchWebhook, findConsumerByExternalId, findConsumerByIdentifiers, formatStreamPayError, portal, streampay, subscriptions, verifyWebhook, verifyWebhookOrThrow, webhooks };
|
|
885
1030
|
//# sourceMappingURL=index.js.map
|
|
886
1031
|
//# sourceMappingURL=index.js.map
|