@donotdev/functions 0.1.44 → 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.
- package/README.md +25 -14
- package/lib/chunks/chunk-2JL3GDTO.js +151 -0
- package/lib/chunks/chunk-2JL3GDTO.js.map +7 -0
- package/lib/chunks/chunk-4TVLH2W2.js +22 -0
- package/lib/chunks/chunk-4TVLH2W2.js.map +7 -0
- package/lib/chunks/chunk-4U7QQWYG.js +22 -0
- package/lib/chunks/chunk-4U7QQWYG.js.map +7 -0
- package/lib/chunks/chunk-5DTPEM64.js +22 -0
- package/lib/chunks/chunk-5DTPEM64.js.map +7 -0
- package/lib/chunks/chunk-6CQXHNVL.js +22 -0
- package/lib/chunks/chunk-6CQXHNVL.js.map +7 -0
- package/lib/chunks/chunk-6DSCPZC6.js +22 -0
- package/lib/chunks/chunk-6DSCPZC6.js.map +7 -0
- package/lib/chunks/chunk-7E6TGWHU.js +22 -0
- package/lib/chunks/chunk-7E6TGWHU.js.map +7 -0
- package/lib/chunks/chunk-7LT32OWE.js +22 -0
- package/lib/chunks/chunk-7LT32OWE.js.map +7 -0
- package/lib/chunks/chunk-7VH2GJXT.js +151 -0
- package/lib/chunks/chunk-7VH2GJXT.js.map +7 -0
- package/lib/chunks/chunk-API5A4BV.js +22 -0
- package/lib/chunks/chunk-API5A4BV.js.map +7 -0
- package/lib/chunks/chunk-AYY7UXNI.js +22 -0
- package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
- package/lib/chunks/chunk-BUP7SXPV.js +23 -0
- package/lib/chunks/chunk-BUP7SXPV.js.map +7 -0
- package/lib/chunks/chunk-BXKRI3JJ.js +22 -0
- package/lib/chunks/chunk-BXKRI3JJ.js.map +7 -0
- package/lib/chunks/chunk-FSLGZD7A.js +21 -0
- package/lib/chunks/chunk-FSLGZD7A.js.map +7 -0
- package/lib/chunks/chunk-GVLSPWDD.js +151 -0
- package/lib/chunks/chunk-GVLSPWDD.js.map +7 -0
- package/lib/chunks/chunk-GXQVWEFT.js +22 -0
- package/lib/chunks/chunk-GXQVWEFT.js.map +7 -0
- package/lib/chunks/chunk-HB7EGXVI.js +22 -0
- package/lib/chunks/chunk-HB7EGXVI.js.map +7 -0
- package/lib/chunks/chunk-HLNYUAZH.js +22 -0
- package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
- package/lib/chunks/chunk-HM7XCMWW.js +22 -0
- package/lib/chunks/chunk-HM7XCMWW.js.map +7 -0
- package/lib/chunks/chunk-I7IOIL6U.js +151 -0
- package/lib/chunks/chunk-I7IOIL6U.js.map +7 -0
- package/lib/chunks/chunk-IFOYVSPU.js +22 -0
- package/lib/chunks/chunk-IFOYVSPU.js.map +7 -0
- package/lib/chunks/chunk-JTAGPPPL.js +22 -0
- package/lib/chunks/chunk-JTAGPPPL.js.map +7 -0
- package/lib/chunks/chunk-MZ232FUE.js +22 -0
- package/lib/chunks/chunk-MZ232FUE.js.map +7 -0
- package/lib/chunks/chunk-NE5ZTUUZ.js +22 -0
- package/lib/chunks/chunk-NE5ZTUUZ.js.map +7 -0
- package/lib/chunks/chunk-NP2AN2TV.js +22 -0
- package/lib/chunks/chunk-NP2AN2TV.js.map +7 -0
- package/lib/chunks/chunk-QJAU2MWV.js +22 -0
- package/lib/chunks/chunk-QJAU2MWV.js.map +7 -0
- package/lib/chunks/chunk-RM7DV6IQ.js +23 -0
- package/lib/chunks/chunk-RM7DV6IQ.js.map +7 -0
- package/lib/chunks/chunk-RQZGIZHD.js +151 -0
- package/lib/chunks/chunk-RQZGIZHD.js.map +7 -0
- package/lib/chunks/chunk-TBEDQLOB.js +23 -0
- package/lib/chunks/chunk-TBEDQLOB.js.map +7 -0
- package/lib/chunks/chunk-TMHBP3HB.js +22 -0
- package/lib/chunks/chunk-TMHBP3HB.js.map +7 -0
- package/lib/chunks/chunk-UH4L3EF3.js +151 -0
- package/lib/chunks/chunk-UH4L3EF3.js.map +7 -0
- package/lib/chunks/chunk-UJBIU6TL.js +22 -0
- package/lib/chunks/chunk-UJBIU6TL.js.map +7 -0
- package/lib/chunks/chunk-VKEYW3NT.js +22 -0
- package/lib/chunks/chunk-VKEYW3NT.js.map +7 -0
- package/lib/chunks/chunk-XGXBMXJ6.js +22 -0
- package/lib/chunks/chunk-XGXBMXJ6.js.map +7 -0
- package/lib/chunks/chunk-Y44NEQQG.js +22 -0
- package/lib/chunks/chunk-Y44NEQQG.js.map +7 -0
- package/lib/chunks/chunk-ZVU3KPXI.js +22 -0
- package/lib/chunks/chunk-ZVU3KPXI.js.map +7 -0
- package/lib/chunks/monitoring-AGCSU3FI.js +22 -0
- package/lib/chunks/monitoring-AGCSU3FI.js.map +7 -0
- package/lib/chunks/monitoring-PVQMFL34.js +22 -0
- package/lib/chunks/monitoring-PVQMFL34.js.map +7 -0
- package/lib/chunks/monitoring-V7FZXTTW.js +22 -0
- package/lib/chunks/monitoring-V7FZXTTW.js.map +7 -0
- package/lib/chunks/rateLimiter-6KO7AIZP.js +22 -0
- package/lib/chunks/rateLimiter-6KO7AIZP.js.map +7 -0
- package/lib/chunks/rateLimiter-OXVBFW5C.js +22 -0
- package/lib/chunks/rateLimiter-OXVBFW5C.js.map +7 -0
- package/lib/chunks/rateLimiter-U45OMTWR.js +22 -0
- package/lib/chunks/rateLimiter-U45OMTWR.js.map +7 -0
- package/lib/chunks/server-32A5RH4C.js +22 -0
- package/lib/chunks/server-32A5RH4C.js.map +7 -0
- package/lib/chunks/server-7HDAP5DL.js +22 -0
- package/lib/chunks/server-7HDAP5DL.js.map +7 -0
- package/lib/chunks/server-S2IMFOY7.js +22 -0
- package/lib/chunks/server-S2IMFOY7.js.map +7 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
- package/lib/firebase/baseFunction.d.ts +1 -1
- package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/firebase/billing/index.d.ts +2 -1
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
- package/lib/firebase/billing/webhookHandler.d.ts +17 -2
- package/lib/firebase/crud/aggregate.d.ts +0 -9
- package/lib/firebase/crud/bulk.d.ts +2 -2
- package/lib/firebase/crud/create.d.ts +1 -1
- package/lib/firebase/crud/delete.d.ts +1 -1
- package/lib/firebase/crud/get.d.ts +1 -1
- package/lib/firebase/crud/list.d.ts +1 -1
- package/lib/firebase/crud/update.d.ts +1 -9
- package/lib/firebase/index.js +1 -5
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/githubAccess.d.ts +2 -2
- package/lib/firebase/registerCrudFunctions.d.ts +9 -1
- package/lib/shared/billing/apiVersion.d.ts +22 -0
- package/lib/shared/billing/checkoutPrice.d.ts +27 -0
- package/lib/shared/billing/checkoutValidation.d.ts +89 -0
- package/lib/shared/billing/createCheckout.d.ts +73 -24
- package/lib/shared/billing/helpers/index.d.ts +0 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
- package/lib/shared/billing/idempotency.d.ts +32 -10
- package/lib/shared/billing/idempotencyContract.d.ts +121 -0
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +75 -0
- package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
- package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
- package/lib/shared/billing/webhookHandler.d.ts +28 -20
- package/lib/shared/index.js +1 -6
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/utils/functionWrapper.d.ts +1 -1
- package/lib/shared/utils/internal/auth.d.ts +38 -1
- package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
- package/lib/shared/utils/schemaValidation.d.ts +1 -1
- package/lib/shared/utils/vercelHelpers.d.ts +8 -0
- package/lib/shared/utils.d.ts +4 -17
- package/lib/supabase/baseFunction.d.ts +1 -1
- package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
- package/lib/supabase/crud/bulk.d.ts +1 -1
- package/lib/supabase/crud/entityStore.d.ts +71 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/helpers/authProvider.d.ts +5 -5
- package/lib/supabase/index.d.ts +10 -2
- package/lib/supabase/index.js +1 -3
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- package/lib/vercel/api/ai/chat.d.ts +0 -9
- package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
- package/lib/vercel/api/billing/backend.d.ts +39 -0
- package/lib/vercel/api/billing/cancel.d.ts +8 -0
- package/lib/vercel/api/billing/change-plan.d.ts +9 -1
- package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
- package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
- package/lib/vercel/api/billing/index.d.ts +4 -2
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
- package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
- package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
- package/lib/vercel/api/crud/bulk.d.ts +17 -0
- package/lib/vercel/api/crud/create.d.ts +8 -0
- package/lib/vercel/api/crud/delete.d.ts +8 -0
- package/lib/vercel/api/crud/get.d.ts +8 -0
- package/lib/vercel/api/crud/list.d.ts +8 -0
- package/lib/vercel/api/crud/update.d.ts +8 -0
- package/lib/vercel/api/index.js +1 -3
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
- package/lib/vercel/baseFunction.d.ts +4 -1
- package/lib/vercel/supabaseAdmin.d.ts +22 -0
- package/package.json +25 -26
- package/src/firebase/auth/getCustomClaims.ts +4 -5
- package/src/firebase/auth/getUserAuthStatus.ts +4 -5
- package/src/firebase/auth/removeCustomClaims.ts +4 -5
- package/src/firebase/auth/setCustomClaims.ts +4 -5
- package/src/firebase/baseFunction.ts +4 -5
- package/src/firebase/billing/cancelSubscription.ts +1 -2
- package/src/firebase/billing/changePlan.ts +2 -3
- package/src/firebase/billing/createCheckoutSession.ts +30 -56
- package/src/firebase/billing/createCustomerPortal.ts +4 -5
- package/src/firebase/billing/healthCheck.ts +0 -0
- package/src/firebase/billing/index.ts +8 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +2 -3
- package/src/firebase/billing/webhookHandler.ts +20 -4
- package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
- package/src/firebase/crud/aggregate.ts +1 -2
- package/src/firebase/crud/bulk.ts +5 -6
- package/src/firebase/crud/create.ts +5 -6
- package/src/firebase/crud/delete.ts +4 -5
- package/src/firebase/crud/get.ts +4 -5
- package/src/firebase/crud/list.ts +4 -5
- package/src/firebase/crud/update.ts +5 -6
- package/src/firebase/oauth/githubAccess.ts +2 -3
- package/src/firebase/registerCrudFunctions.ts +2 -2
- package/src/shared/__tests__/auth.test.ts +0 -3
- package/src/shared/__tests__/bulkCore.test.ts +3 -2
- package/src/shared/__tests__/errorHandling.test.ts +2 -2
- package/src/shared/__tests__/idempotency.test.ts +282 -55
- package/src/shared/__tests__/internalValidation.test.ts +3 -3
- package/src/shared/__tests__/rateLimiter.test.ts +2 -8
- package/src/shared/__tests__/schemaValidation.test.ts +1 -1
- package/src/shared/__tests__/utils.test.ts +2 -1
- package/src/shared/__tests__/validation-env.test.ts +0 -0
- package/src/shared/ai/createAIRoute.ts +53 -30
- package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
- package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
- package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +407 -23
- package/src/shared/billing/apiVersion.ts +25 -0
- package/src/shared/billing/checkoutPrice.ts +125 -0
- package/src/shared/billing/checkoutValidation.ts +284 -0
- package/src/shared/billing/createCheckout.ts +332 -196
- package/src/shared/billing/helpers/index.ts +0 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +7 -9
- package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
- package/src/shared/billing/idempotency.ts +253 -150
- package/src/shared/billing/idempotencyContract.ts +135 -0
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +269 -0
- package/src/shared/billing/supabaseIdempotency.ts +228 -0
- package/src/shared/billing/tierWebhookEvents.ts +432 -0
- package/src/shared/billing/webhookHandler.ts +188 -385
- package/src/shared/utils/external/subscription.ts +0 -0
- package/src/shared/utils/firebaseHelpers.ts +2 -3
- package/src/shared/utils/functionWrapper.ts +1 -2
- package/src/shared/utils/internal/auth.ts +55 -7
- package/src/shared/utils/internal/monitoring.ts +17 -9
- package/src/shared/utils/internal/rateLimiter.ts +14 -5
- package/src/shared/utils/schemaValidation.ts +1 -2
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +14 -31
- package/src/shared/validation.ts +1 -1
- package/src/supabase/__tests__/bulk.test.ts +3 -1
- package/src/supabase/__tests__/entityStore.test.ts +90 -0
- package/src/supabase/baseFunction.ts +1 -2
- package/src/supabase/billing/createCheckoutSession.ts +10 -36
- package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -2
- package/src/supabase/billing/stripeWebhook.ts +79 -0
- package/src/supabase/crud/aggregate.ts +1 -1
- package/src/supabase/crud/bulk.ts +3 -7
- package/src/supabase/crud/create.ts +1 -1
- package/src/supabase/crud/entityStore.ts +240 -0
- package/src/supabase/crud/index.ts +8 -0
- package/src/supabase/crud/update.ts +1 -1
- package/src/supabase/helpers/authProvider.ts +6 -5
- package/src/supabase/index.ts +26 -0
- package/src/supabase/utils/rateLimiter.ts +2 -2
- package/src/vercel/__tests__/bulk.test.ts +24 -21
- package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
- package/src/vercel/api/ai/chat.ts +2 -1
- package/src/vercel/api/auth/get-custom-claims.ts +2 -3
- package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
- package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
- package/src/vercel/api/auth/set-custom-claims.ts +3 -3
- package/src/vercel/api/billing/backend.ts +72 -0
- package/src/vercel/api/billing/cancel.ts +2 -4
- package/src/vercel/api/billing/change-plan.ts +3 -4
- package/src/vercel/api/billing/create-checkout-session.ts +42 -68
- package/src/vercel/api/billing/customer-portal.ts +2 -4
- package/src/vercel/api/billing/index.ts +4 -2
- package/src/vercel/api/billing/refresh-subscription-status.ts +21 -6
- package/src/vercel/api/billing/webhook-handler.ts +31 -25
- package/src/vercel/api/config/firebase-admin.ts +2 -2
- package/src/vercel/api/crud/bulk.ts +6 -9
- package/src/vercel/api/crud/create.ts +6 -5
- package/src/vercel/api/crud/delete.ts +4 -3
- package/src/vercel/api/crud/get.ts +6 -5
- package/src/vercel/api/crud/list.ts +6 -5
- package/src/vercel/api/crud/update.ts +6 -5
- package/src/vercel/api/oauth/check-github-access.ts +5 -5
- package/src/vercel/api/oauth/exchange-token.ts +3 -3
- package/src/vercel/api/oauth/grant-github-access.ts +5 -5
- package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
- package/src/vercel/baseFunction.ts +23 -8
- package/src/vercel/supabaseAdmin.ts +45 -0
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/tierWebhookEvents.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Stripe webhook handlers for tier items
|
|
5
|
+
* @description StripePayment / StripeSubscription event handlers routed by
|
|
6
|
+
* `processWebhook`: checkout grant (payment_status aware), renewal,
|
|
7
|
+
* cancellation and payment failure.
|
|
8
|
+
*
|
|
9
|
+
* @version 0.2.0
|
|
10
|
+
* @since 0.0.1
|
|
11
|
+
* @author AMBROISE PARK Consulting
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type Stripe from 'stripe';
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
calculateSubscriptionEndDate,
|
|
18
|
+
SUBSCRIPTION_STATUS,
|
|
19
|
+
SUBSCRIPTION_TIERS,
|
|
20
|
+
} from '@donotdev/core/server';
|
|
21
|
+
import type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from '@donotdev/core/server';
|
|
22
|
+
|
|
23
|
+
import { handleError } from '../errorHandling.js';
|
|
24
|
+
import { logger } from '../logger.js';
|
|
25
|
+
import type { OrderSessionEventType } from './orderWebhook.js';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Checkout Session event of a StripePayment / StripeSubscription item.
|
|
29
|
+
* Grants only once the payment is settled (Stripe fulfillment guide,
|
|
30
|
+
* https://docs.stripe.com/checkout/fulfillment):
|
|
31
|
+
* - `completed` + `paid` / `no_payment_required` → grant
|
|
32
|
+
* - `completed` + `unpaid` (delayed method, e.g. SEPA debit) → log, wait
|
|
33
|
+
* - `async_payment_succeeded` → grant
|
|
34
|
+
* - `async_payment_failed` → log (nothing was granted)
|
|
35
|
+
* - `expired` → ignored
|
|
36
|
+
*
|
|
37
|
+
* @throws When `payment_status` is not a known value, or when the grant fails
|
|
38
|
+
*
|
|
39
|
+
* @version 0.2.0
|
|
40
|
+
* @since 0.2.0
|
|
41
|
+
* @author AMBROISE PARK Consulting
|
|
42
|
+
*/
|
|
43
|
+
export async function handleTierCheckoutEvent(
|
|
44
|
+
eventType: OrderSessionEventType,
|
|
45
|
+
session: Stripe.Checkout.Session,
|
|
46
|
+
config: StripeBackConfig,
|
|
47
|
+
updateSubscription: UpdateSubscriptionFn,
|
|
48
|
+
authProvider: BillingAuthProvider | null
|
|
49
|
+
): Promise<void> {
|
|
50
|
+
const logContext = {
|
|
51
|
+
sessionId: session.id,
|
|
52
|
+
billingConfigKey: session.metadata?.billingConfigKey,
|
|
53
|
+
userId: session.metadata?.userId,
|
|
54
|
+
paymentStatus: session.payment_status,
|
|
55
|
+
};
|
|
56
|
+
switch (eventType) {
|
|
57
|
+
case 'checkout.session.completed':
|
|
58
|
+
if (session.payment_status === 'unpaid') {
|
|
59
|
+
logger.info('[Webhook] Purchase awaiting async payment', {
|
|
60
|
+
...logContext,
|
|
61
|
+
operation: 'purchase_payment_pending',
|
|
62
|
+
});
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (
|
|
66
|
+
session.payment_status !== 'paid' &&
|
|
67
|
+
session.payment_status !== 'no_payment_required'
|
|
68
|
+
) {
|
|
69
|
+
throw handleError(
|
|
70
|
+
new Error(
|
|
71
|
+
`Checkout session ${session.id} has unknown payment_status ${String(session.payment_status)}`
|
|
72
|
+
)
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
await grantCheckoutPurchase(
|
|
76
|
+
session,
|
|
77
|
+
config,
|
|
78
|
+
updateSubscription,
|
|
79
|
+
authProvider
|
|
80
|
+
);
|
|
81
|
+
return;
|
|
82
|
+
case 'checkout.session.async_payment_succeeded':
|
|
83
|
+
await grantCheckoutPurchase(
|
|
84
|
+
session,
|
|
85
|
+
config,
|
|
86
|
+
updateSubscription,
|
|
87
|
+
authProvider
|
|
88
|
+
);
|
|
89
|
+
return;
|
|
90
|
+
case 'checkout.session.async_payment_failed':
|
|
91
|
+
logger.warn('[Webhook] Async purchase payment failed, nothing granted', {
|
|
92
|
+
...logContext,
|
|
93
|
+
operation: 'purchase_payment_failed',
|
|
94
|
+
});
|
|
95
|
+
return;
|
|
96
|
+
case 'checkout.session.expired':
|
|
97
|
+
logger.debug('[Webhook] Checkout session expired', logContext);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Grant the tier bought in a paid Checkout Session, then run the item hook.
|
|
104
|
+
* Idempotent: it writes the same subscription state again on a replay.
|
|
105
|
+
*/
|
|
106
|
+
async function grantCheckoutPurchase(
|
|
107
|
+
session: Stripe.Checkout.Session,
|
|
108
|
+
config: StripeBackConfig,
|
|
109
|
+
updateSubscription: UpdateSubscriptionFn,
|
|
110
|
+
authProvider: BillingAuthProvider | null
|
|
111
|
+
): Promise<void> {
|
|
112
|
+
const { userId, billingConfigKey } = session.metadata || {};
|
|
113
|
+
|
|
114
|
+
if (!userId || !billingConfigKey) {
|
|
115
|
+
throw handleError(
|
|
116
|
+
new Error(
|
|
117
|
+
`Missing required metadata: userId=${userId}, billingConfigKey=${billingConfigKey}`
|
|
118
|
+
)
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const billingItem = config[billingConfigKey];
|
|
123
|
+
if (!billingItem) {
|
|
124
|
+
throw handleError(
|
|
125
|
+
new Error(`Unknown billing config key: ${billingConfigKey}`)
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
logger.info('[Webhook] Processing purchase', {
|
|
130
|
+
userId,
|
|
131
|
+
configKey: billingConfigKey,
|
|
132
|
+
type: billingItem.type,
|
|
133
|
+
operation: 'purchase_processing',
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// Update subscription
|
|
137
|
+
if (billingItem.type === 'StripePayment') {
|
|
138
|
+
if (!authProvider) {
|
|
139
|
+
throw handleError(
|
|
140
|
+
new Error('Auth provider required for subscription updates')
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
await updateSubscription(
|
|
144
|
+
userId,
|
|
145
|
+
{
|
|
146
|
+
tier: billingItem.tier,
|
|
147
|
+
status: SUBSCRIPTION_STATUS.ACTIVE,
|
|
148
|
+
subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),
|
|
149
|
+
customerId: session.customer as string,
|
|
150
|
+
},
|
|
151
|
+
authProvider
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
// Execute hook with graceful error handling
|
|
155
|
+
if (billingItem.onPurchaseSuccess) {
|
|
156
|
+
try {
|
|
157
|
+
await billingItem.onPurchaseSuccess(userId, session.metadata || {});
|
|
158
|
+
} catch (error) {
|
|
159
|
+
// Hook failures are non-critical - payment already processed
|
|
160
|
+
// Log for manual intervention but don't fail the webhook
|
|
161
|
+
logger.error('[Webhook] Hook failed (non-critical)', {
|
|
162
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
163
|
+
hookName: 'onPurchaseSuccess',
|
|
164
|
+
userId,
|
|
165
|
+
operation: 'hook_execution',
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (billingItem.type === 'StripeSubscription') {
|
|
172
|
+
if (!authProvider) {
|
|
173
|
+
throw handleError(
|
|
174
|
+
new Error('Auth provider required for subscription updates')
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
await updateSubscription(
|
|
178
|
+
userId,
|
|
179
|
+
{
|
|
180
|
+
tier: billingItem.tier,
|
|
181
|
+
status: SUBSCRIPTION_STATUS.ACTIVE,
|
|
182
|
+
subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),
|
|
183
|
+
subscriptionId: session.subscription as string,
|
|
184
|
+
customerId: session.customer as string,
|
|
185
|
+
},
|
|
186
|
+
authProvider
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
// Execute hook with graceful error handling
|
|
190
|
+
if (billingItem.onSubscriptionCreated) {
|
|
191
|
+
try {
|
|
192
|
+
await billingItem.onSubscriptionCreated(userId, session.metadata || {});
|
|
193
|
+
} catch (error) {
|
|
194
|
+
// Hook failures are non-critical - subscription already created
|
|
195
|
+
// Log for manual intervention but don't fail the webhook
|
|
196
|
+
logger.error('[Webhook] Hook failed (non-critical)', {
|
|
197
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
198
|
+
hookName: 'onSubscriptionCreated',
|
|
199
|
+
userId,
|
|
200
|
+
operation: 'hook_execution',
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
logger.info('[Webhook] Purchase processed', {
|
|
207
|
+
userId,
|
|
208
|
+
configKey: billingConfigKey,
|
|
209
|
+
operation: 'purchase_processed',
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Handle subscription renewal
|
|
215
|
+
*
|
|
216
|
+
* @version 0.1.0
|
|
217
|
+
* @since 0.0.1
|
|
218
|
+
* @author AMBROISE PARK Consulting
|
|
219
|
+
*/
|
|
220
|
+
export async function handleInvoicePaymentSucceeded(
|
|
221
|
+
invoice: Stripe.Invoice,
|
|
222
|
+
config: StripeBackConfig,
|
|
223
|
+
updateSubscription: UpdateSubscriptionFn,
|
|
224
|
+
stripe: Stripe,
|
|
225
|
+
authProvider: BillingAuthProvider | null
|
|
226
|
+
): Promise<void> {
|
|
227
|
+
const subscriptionId = (invoice as any).subscription as string;
|
|
228
|
+
if (!subscriptionId) return;
|
|
229
|
+
|
|
230
|
+
// ✅ FIX: Fetch subscription to get metadata
|
|
231
|
+
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
|
232
|
+
const { userId, billingConfigKey } = subscription.metadata || {};
|
|
233
|
+
if (!userId || !billingConfigKey) {
|
|
234
|
+
// G60: Log when subscription metadata is missing — silent return loses the event
|
|
235
|
+
logger.error(
|
|
236
|
+
'[Webhook] Subscription metadata missing userId or billingConfigKey',
|
|
237
|
+
{
|
|
238
|
+
subscriptionId,
|
|
239
|
+
hasUserId: !!userId,
|
|
240
|
+
hasBillingConfigKey: !!billingConfigKey,
|
|
241
|
+
operation: 'invoice_payment_succeeded_metadata_missing',
|
|
242
|
+
}
|
|
243
|
+
);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const billingItem = config[billingConfigKey];
|
|
248
|
+
if (!billingItem || billingItem.type !== 'StripeSubscription') return;
|
|
249
|
+
|
|
250
|
+
// Renew subscription
|
|
251
|
+
if (!authProvider) {
|
|
252
|
+
throw handleError(
|
|
253
|
+
new Error('Auth provider required for subscription updates')
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
await updateSubscription(
|
|
257
|
+
userId,
|
|
258
|
+
{
|
|
259
|
+
tier: billingItem.tier,
|
|
260
|
+
status: SUBSCRIPTION_STATUS.ACTIVE,
|
|
261
|
+
subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),
|
|
262
|
+
subscriptionId: subscriptionId,
|
|
263
|
+
customerId: invoice.customer as string,
|
|
264
|
+
},
|
|
265
|
+
authProvider
|
|
266
|
+
);
|
|
267
|
+
|
|
268
|
+
// Execute hook with graceful error handling
|
|
269
|
+
if (billingItem.onSubscriptionRenewed) {
|
|
270
|
+
try {
|
|
271
|
+
await billingItem.onSubscriptionRenewed(
|
|
272
|
+
userId,
|
|
273
|
+
subscription.metadata || {}
|
|
274
|
+
);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
// Hook failures are non-critical - subscription already renewed
|
|
277
|
+
// Log for manual intervention but don't fail the webhook
|
|
278
|
+
logger.error('[Webhook] Hook failed (non-critical)', {
|
|
279
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
280
|
+
hookName: 'onSubscriptionRenewed',
|
|
281
|
+
userId,
|
|
282
|
+
operation: 'hook_execution',
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
logger.info('[Webhook] Subscription renewed', {
|
|
288
|
+
userId,
|
|
289
|
+
billingConfigKey,
|
|
290
|
+
operation: 'subscription_renewed',
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Handle subscription cancellation
|
|
296
|
+
*
|
|
297
|
+
* @version 0.1.0
|
|
298
|
+
* @since 0.0.1
|
|
299
|
+
* @author AMBROISE PARK Consulting
|
|
300
|
+
*/
|
|
301
|
+
export async function handleSubscriptionDeleted(
|
|
302
|
+
subscription: Stripe.Subscription,
|
|
303
|
+
config: StripeBackConfig,
|
|
304
|
+
updateSubscription: UpdateSubscriptionFn,
|
|
305
|
+
authProvider: BillingAuthProvider | null
|
|
306
|
+
): Promise<void> {
|
|
307
|
+
const { userId, billingConfigKey } = subscription.metadata || {};
|
|
308
|
+
if (!userId || !billingConfigKey) return;
|
|
309
|
+
|
|
310
|
+
const billingItem = config[billingConfigKey];
|
|
311
|
+
if (!billingItem || billingItem.type !== 'StripeSubscription') return;
|
|
312
|
+
|
|
313
|
+
// Update to cancelled
|
|
314
|
+
if (!authProvider) {
|
|
315
|
+
throw handleError(
|
|
316
|
+
new Error('Auth provider required for subscription updates')
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
await updateSubscription(
|
|
320
|
+
userId,
|
|
321
|
+
{
|
|
322
|
+
tier: SUBSCRIPTION_TIERS.FREE,
|
|
323
|
+
status: SUBSCRIPTION_STATUS.CANCELED,
|
|
324
|
+
subscriptionEnd: new Date(
|
|
325
|
+
(subscription as any).current_period_end * 1000
|
|
326
|
+
).toISOString(),
|
|
327
|
+
subscriptionId: subscription.id,
|
|
328
|
+
customerId: subscription.customer as string,
|
|
329
|
+
},
|
|
330
|
+
authProvider
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
// Execute hook with graceful error handling
|
|
334
|
+
if (billingItem.onSubscriptionCancelled) {
|
|
335
|
+
try {
|
|
336
|
+
await billingItem.onSubscriptionCancelled(
|
|
337
|
+
userId,
|
|
338
|
+
subscription.metadata || {}
|
|
339
|
+
);
|
|
340
|
+
} catch (error) {
|
|
341
|
+
// Hook failures are non-critical - subscription already cancelled
|
|
342
|
+
// Log for manual intervention but don't fail the webhook
|
|
343
|
+
logger.error('[Webhook] Hook failed (non-critical)', {
|
|
344
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
345
|
+
hookName: 'onSubscriptionCancelled',
|
|
346
|
+
userId,
|
|
347
|
+
operation: 'hook_execution',
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
logger.info('[Webhook] Subscription cancelled', {
|
|
353
|
+
userId,
|
|
354
|
+
billingConfigKey,
|
|
355
|
+
operation: 'subscription_cancelled',
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Handle payment failure
|
|
361
|
+
*
|
|
362
|
+
* @version 0.1.0
|
|
363
|
+
* @since 0.0.1
|
|
364
|
+
* @author AMBROISE PARK Consulting
|
|
365
|
+
*/
|
|
366
|
+
export async function handlePaymentFailed(
|
|
367
|
+
invoice: Stripe.Invoice,
|
|
368
|
+
config: StripeBackConfig
|
|
369
|
+
): Promise<void> {
|
|
370
|
+
const { userId, billingConfigKey } = invoice.metadata || {};
|
|
371
|
+
if (!userId || !billingConfigKey) {
|
|
372
|
+
logger.warn('[Webhook] Payment failed - missing metadata', {
|
|
373
|
+
invoiceId: invoice.id,
|
|
374
|
+
hasUserId: !!userId,
|
|
375
|
+
hasBillingConfigKey: !!billingConfigKey,
|
|
376
|
+
operation: 'payment_failed_metadata_missing',
|
|
377
|
+
});
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const billingItem = config[billingConfigKey];
|
|
382
|
+
if (!billingItem) {
|
|
383
|
+
logger.error('[Webhook] Payment failed - unknown billing config', {
|
|
384
|
+
error: new Error(`Unknown billing config key: ${billingConfigKey}`),
|
|
385
|
+
userId,
|
|
386
|
+
billingConfigKey,
|
|
387
|
+
operation: 'payment_failed_unknown_config',
|
|
388
|
+
});
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Execute hooks with graceful error handling
|
|
393
|
+
if (billingItem.type === 'StripePayment' && billingItem.onPurchaseFailure) {
|
|
394
|
+
try {
|
|
395
|
+
// Pass the actual metadata - we've already validated it exists
|
|
396
|
+
await billingItem.onPurchaseFailure(userId, invoice.metadata || {});
|
|
397
|
+
} catch (error) {
|
|
398
|
+
// Hook failures are non-critical - payment already failed
|
|
399
|
+
// Log for manual intervention but don't fail the webhook
|
|
400
|
+
logger.error('[Webhook] Hook failed (non-critical)', {
|
|
401
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
402
|
+
hookName: 'onPurchaseFailure',
|
|
403
|
+
userId,
|
|
404
|
+
operation: 'hook_execution',
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (
|
|
410
|
+
billingItem.type === 'StripeSubscription' &&
|
|
411
|
+
billingItem.onPaymentFailed
|
|
412
|
+
) {
|
|
413
|
+
try {
|
|
414
|
+
await billingItem.onPaymentFailed(userId, invoice.metadata || {});
|
|
415
|
+
} catch (error) {
|
|
416
|
+
// Hook failures are non-critical - payment already failed
|
|
417
|
+
// Log for manual intervention but don't fail the webhook
|
|
418
|
+
logger.error('[Webhook] Hook failed (non-critical)', {
|
|
419
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
420
|
+
hookName: 'onPaymentFailed',
|
|
421
|
+
userId,
|
|
422
|
+
operation: 'hook_execution',
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
logger.warn('[Webhook] Payment failed', {
|
|
428
|
+
userId,
|
|
429
|
+
billingConfigKey,
|
|
430
|
+
operation: 'payment_failed',
|
|
431
|
+
});
|
|
432
|
+
}
|