@apexara/stripe 1.0.2
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 +1003 -0
- package/dist/apex-stripe.d.ts +23 -0
- package/dist/apex-stripe.d.ts.map +1 -0
- package/dist/apex-stripe.js +41 -0
- package/dist/client.d.ts +7 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +14 -0
- package/dist/errors/http-error.d.ts +7 -0
- package/dist/errors/http-error.d.ts.map +1 -0
- package/dist/errors/http-error.js +14 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +48 -0
- package/dist/models/config.model.d.ts +31 -0
- package/dist/models/config.model.d.ts.map +1 -0
- package/dist/models/config.model.js +2 -0
- package/dist/models/index.d.ts +5 -0
- package/dist/models/index.d.ts.map +1 -0
- package/dist/models/index.js +20 -0
- package/dist/models/stripe.model.d.ts +69 -0
- package/dist/models/stripe.model.d.ts.map +1 -0
- package/dist/models/stripe.model.js +2 -0
- package/dist/models/subscription.model.d.ts +24 -0
- package/dist/models/subscription.model.d.ts.map +1 -0
- package/dist/models/subscription.model.js +2 -0
- package/dist/models/webhook.model.d.ts +43 -0
- package/dist/models/webhook.model.d.ts.map +1 -0
- package/dist/models/webhook.model.js +2 -0
- package/dist/services/checkout/checkout.service.d.ts +31 -0
- package/dist/services/checkout/checkout.service.d.ts.map +1 -0
- package/dist/services/checkout/checkout.service.js +119 -0
- package/dist/services/connected-account/connected-account.service.d.ts +25 -0
- package/dist/services/connected-account/connected-account.service.d.ts.map +1 -0
- package/dist/services/connected-account/connected-account.service.js +46 -0
- package/dist/services/customer/customer.service.d.ts +14 -0
- package/dist/services/customer/customer.service.d.ts.map +1 -0
- package/dist/services/customer/customer.service.js +23 -0
- package/dist/services/invoice/invoice.service.d.ts +24 -0
- package/dist/services/invoice/invoice.service.d.ts.map +1 -0
- package/dist/services/invoice/invoice.service.js +65 -0
- package/dist/services/payment-link/payment-link.service.d.ts +18 -0
- package/dist/services/payment-link/payment-link.service.d.ts.map +1 -0
- package/dist/services/payment-link/payment-link.service.js +53 -0
- package/dist/services/payment-method/payment-method.service.d.ts +43 -0
- package/dist/services/payment-method/payment-method.service.d.ts.map +1 -0
- package/dist/services/payment-method/payment-method.service.js +89 -0
- package/dist/services/price/price.service.d.ts +17 -0
- package/dist/services/price/price.service.d.ts.map +1 -0
- package/dist/services/price/price.service.js +32 -0
- package/dist/services/subscription/subscription.service.d.ts +89 -0
- package/dist/services/subscription/subscription.service.d.ts.map +1 -0
- package/dist/services/subscription/subscription.service.js +272 -0
- package/dist/tests/helpers.d.ts +5 -0
- package/dist/tests/helpers.d.ts.map +1 -0
- package/dist/tests/helpers.js +96 -0
- package/dist/utils/helpers.d.ts +15 -0
- package/dist/utils/helpers.d.ts.map +1 -0
- package/dist/utils/helpers.js +41 -0
- package/dist/webhooks/webhook.dispatcher.d.ts +25 -0
- package/dist/webhooks/webhook.dispatcher.d.ts.map +1 -0
- package/dist/webhooks/webhook.dispatcher.js +105 -0
- package/dist/webhooks/webhook.handler.d.ts +39 -0
- package/dist/webhooks/webhook.handler.d.ts.map +1 -0
- package/dist/webhooks/webhook.handler.js +70 -0
- package/package.json +57 -0
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SubscriptionService = void 0;
|
|
4
|
+
const http_error_1 = require("./../../errors/http-error");
|
|
5
|
+
class SubscriptionService {
|
|
6
|
+
constructor(stripe, config) {
|
|
7
|
+
this.stripe = stripe;
|
|
8
|
+
this.config = config;
|
|
9
|
+
}
|
|
10
|
+
// Subscription basics
|
|
11
|
+
/**
|
|
12
|
+
* Retrieves a subscription with its price items expanded.
|
|
13
|
+
*/
|
|
14
|
+
async getSubscriptionById(subscriptionId) {
|
|
15
|
+
return this.stripe.subscriptions.retrieve(subscriptionId, { expand: ['items.data.price'] });
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Lists all subscriptions for a customer across all statuses.
|
|
19
|
+
* Returns an empty array if no customerId is provided.
|
|
20
|
+
*/
|
|
21
|
+
async getAllUserSubscriptions(customerId) {
|
|
22
|
+
if (!customerId) {
|
|
23
|
+
return [];
|
|
24
|
+
}
|
|
25
|
+
const subscriptions = await this.stripe.subscriptions.list({
|
|
26
|
+
customer: customerId,
|
|
27
|
+
status: 'all',
|
|
28
|
+
expand: ['data.default_payment_method'],
|
|
29
|
+
});
|
|
30
|
+
return subscriptions.data;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Updates a subscription with arbitrary Stripe params.
|
|
34
|
+
*/
|
|
35
|
+
async updateSubscription(subscriptionId, params) {
|
|
36
|
+
return this.stripe.subscriptions.update(subscriptionId, params);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Immediately cancels a subscription.
|
|
40
|
+
*/
|
|
41
|
+
async cancelSubscription(subscriptionId) {
|
|
42
|
+
return this.stripe.subscriptions.cancel(subscriptionId);
|
|
43
|
+
}
|
|
44
|
+
// Subscription lifecycle
|
|
45
|
+
/**
|
|
46
|
+
* Schedules a subscription to cancel at the end of the current billing period.
|
|
47
|
+
* Throws if the subscription is not active or past_due.
|
|
48
|
+
*/
|
|
49
|
+
async cancelSubscriptionAtPeriodEnd(subscriptionId) {
|
|
50
|
+
const subscription = await this.stripe.subscriptions.retrieve(subscriptionId);
|
|
51
|
+
if (subscription.status !== 'active' && subscription.status !== 'past_due') {
|
|
52
|
+
throw new http_error_1.HttpError(400, `Subscription ${subscriptionId} cannot be cancelled (status: ${subscription.status})`);
|
|
53
|
+
}
|
|
54
|
+
return this.stripe.subscriptions.update(subscriptionId, { cancel_at_period_end: true });
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Resumes a subscription that has cancel_at_period_end set.
|
|
58
|
+
* Throws if cancel_at_period_end is false or the subscription is not active or past_due.
|
|
59
|
+
*/
|
|
60
|
+
async resumeSubscription(subscriptionId) {
|
|
61
|
+
const subscription = await this.stripe.subscriptions.retrieve(subscriptionId);
|
|
62
|
+
const canResume = subscription.cancel_at_period_end &&
|
|
63
|
+
(subscription.status === 'active' || subscription.status === 'past_due');
|
|
64
|
+
if (!canResume) {
|
|
65
|
+
throw new http_error_1.HttpError(400, `Subscription ${subscriptionId} cannot be resumed (status: ${subscription.status}, cancelAtPeriodEnd: ${subscription.cancel_at_period_end})`);
|
|
66
|
+
}
|
|
67
|
+
return this.stripe.subscriptions.update(subscriptionId, { cancel_at_period_end: false });
|
|
68
|
+
}
|
|
69
|
+
// Subscription schedules
|
|
70
|
+
/**
|
|
71
|
+
* Returns the subscription's existing schedule or creates one from it.
|
|
72
|
+
*/
|
|
73
|
+
async getOrCreateSubscriptionSchedule(subscription) {
|
|
74
|
+
if (subscription.schedule) {
|
|
75
|
+
return this.stripe.subscriptionSchedules.retrieve(subscription.schedule);
|
|
76
|
+
}
|
|
77
|
+
return this.stripe.subscriptionSchedules.create({ from_subscription: subscription.id });
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Schedules a plan downgrade to take effect at the end of the current billing period.
|
|
81
|
+
* Tags the schedule with { type: 'downgrade' } in its metadata so it can be identified
|
|
82
|
+
* and released later by releaseScheduleIfDowngrade.
|
|
83
|
+
*/
|
|
84
|
+
async scheduleDowngrade(subscription, newPriceId, options) {
|
|
85
|
+
const schedule = await this.getOrCreateSubscriptionSchedule(subscription);
|
|
86
|
+
const phases = await this.buildDowngradePhases(schedule, newPriceId, {
|
|
87
|
+
quantity: options?.quantity,
|
|
88
|
+
transferData: options?.transferData,
|
|
89
|
+
phaseMetadata: options?.phaseMetadata,
|
|
90
|
+
});
|
|
91
|
+
return this.stripe.subscriptionSchedules.update(schedule.id, {
|
|
92
|
+
end_behavior: 'release',
|
|
93
|
+
metadata: { type: SubscriptionService.phaseTypeDowngrade, ...options?.scheduleMetadata },
|
|
94
|
+
phases,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Returns the downgrade schedule for a subscription, or null if none exists or it is not tagged as a downgrade.
|
|
99
|
+
*/
|
|
100
|
+
async getDowngradeSchedule(subscription) {
|
|
101
|
+
if (!subscription.schedule) {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
const schedule = await this.stripe.subscriptionSchedules.retrieve(subscription.schedule);
|
|
105
|
+
if (schedule.metadata?.['type'] !== SubscriptionService.phaseTypeDowngrade) {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
return schedule;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Releases the subscription's schedule if it is tagged as a downgrade.
|
|
112
|
+
* Safe to call when no schedule is present — returns false in that case.
|
|
113
|
+
* Returns true if a schedule was released.
|
|
114
|
+
*/
|
|
115
|
+
async releaseScheduleIfDowngrade(subscription) {
|
|
116
|
+
if (!subscription.schedule) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
const schedule = await this.stripe.subscriptionSchedules.retrieve(subscription.schedule);
|
|
120
|
+
if (schedule.metadata?.['type'] !== SubscriptionService.phaseTypeDowngrade) {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
await this.stripe.subscriptionSchedules.release(schedule.id);
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
// Plan changes
|
|
127
|
+
/**
|
|
128
|
+
* Creates a pending negative invoice item that offsets the customer's next invoice.
|
|
129
|
+
* Pass a positive amount — it is stored as negative automatically.
|
|
130
|
+
* Call this before switchSubscriptionPlan when managing billing credits manually.
|
|
131
|
+
*/
|
|
132
|
+
async applyPlanCredit(customerId, subscriptionId, amount, currency, description, metadata) {
|
|
133
|
+
await this.stripe.invoiceItems.create({
|
|
134
|
+
customer: customerId,
|
|
135
|
+
subscription: subscriptionId,
|
|
136
|
+
amount: -Math.abs(amount),
|
|
137
|
+
currency,
|
|
138
|
+
description: description ?? 'Plan credit',
|
|
139
|
+
metadata,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Switches a subscription to a new price immediately, resetting the billing cycle anchor to now.
|
|
144
|
+
* Defaults to proration_behavior: 'none' — pair with applyPlanCredit for manual credits,
|
|
145
|
+
* or pass proration: 'create_prorations' to let Stripe calculate what's owed.
|
|
146
|
+
*/
|
|
147
|
+
async switchSubscriptionPlan(subscriptionId, itemId, newPriceId, options) {
|
|
148
|
+
return this.stripe.subscriptions.update(subscriptionId, {
|
|
149
|
+
items: [{ id: itemId, price: newPriceId, quantity: options?.quantity ?? 1 }],
|
|
150
|
+
proration_behavior: options?.proration ?? 'none',
|
|
151
|
+
billing_cycle_anchor: 'now',
|
|
152
|
+
payment_behavior: 'pending_if_incomplete',
|
|
153
|
+
expand: ['latest_invoice.payment_intent', 'pending_update'],
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
// Invoice-based subscriptions
|
|
157
|
+
/**
|
|
158
|
+
* Creates a subscription with send_invoice collection and immediately emails the invoice.
|
|
159
|
+
*/
|
|
160
|
+
async createInvoiceBasedSubscription(customerId, priceId, options) {
|
|
161
|
+
const subscriptionParams = {
|
|
162
|
+
customer: customerId,
|
|
163
|
+
collection_method: 'send_invoice',
|
|
164
|
+
days_until_due: options?.daysUntilDue ?? this.config.invoiceDaysUntilDue,
|
|
165
|
+
payment_settings: {
|
|
166
|
+
payment_method_types: options?.paymentMethodTypes ?? this.config.invoicePaymentMethodTypes,
|
|
167
|
+
},
|
|
168
|
+
billing_mode: { type: 'flexible' },
|
|
169
|
+
items: [{ price: priceId, quantity: options?.quantity ?? 1 }],
|
|
170
|
+
metadata: options?.metadata,
|
|
171
|
+
expand: ['latest_invoice'],
|
|
172
|
+
};
|
|
173
|
+
if (options?.transferData) {
|
|
174
|
+
subscriptionParams.transfer_data = options.transferData;
|
|
175
|
+
}
|
|
176
|
+
const subscription = await this.stripe.subscriptions.create(subscriptionParams);
|
|
177
|
+
const latestInvoice = subscription.latest_invoice;
|
|
178
|
+
if (!latestInvoice) {
|
|
179
|
+
throw new http_error_1.HttpError(500, `Stripe did not return the latest invoice for subscription ${subscription.id}. ` +
|
|
180
|
+
'Ensure latest_invoice is expanded.');
|
|
181
|
+
}
|
|
182
|
+
const invoiceId = typeof latestInvoice === 'string' ? latestInvoice : latestInvoice.id;
|
|
183
|
+
const sentInvoice = await this.stripe.invoices.sendInvoice(invoiceId);
|
|
184
|
+
return {
|
|
185
|
+
subscription,
|
|
186
|
+
invoiceId: sentInvoice.id,
|
|
187
|
+
invoiceUrl: sentInvoice.hosted_invoice_url ?? null,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
// Utilities
|
|
191
|
+
/**
|
|
192
|
+
* Extracts the fields needed to keep a local subscription document in sync with Stripe.
|
|
193
|
+
* Falls back to the provided values if the subscription has no items.
|
|
194
|
+
*/
|
|
195
|
+
buildSubscriptionSyncFields(subscription, fallback = {}) {
|
|
196
|
+
const periodStarts = subscription.items.data.map(item => item.current_period_start);
|
|
197
|
+
const periodEnds = subscription.items.data.map(item => item.current_period_end);
|
|
198
|
+
const currentPeriodStart = periodStarts.length > 0
|
|
199
|
+
? new Date(Math.min(...periodStarts) * 1000)
|
|
200
|
+
: fallback.currentPeriodStart ?? null;
|
|
201
|
+
const currentPeriodEnd = periodEnds.length > 0
|
|
202
|
+
? new Date(Math.max(...periodEnds) * 1000)
|
|
203
|
+
: fallback.currentPeriodEnd ?? null;
|
|
204
|
+
let itemId = fallback.itemId ?? '';
|
|
205
|
+
if (!itemId || !subscription.items.data.some(item => item.id === itemId)) {
|
|
206
|
+
itemId = subscription.items.data[0]?.id ?? itemId;
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
status: subscription.status,
|
|
210
|
+
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
|
211
|
+
currentPeriodStart,
|
|
212
|
+
currentPeriodEnd,
|
|
213
|
+
itemId,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Returns the primary subscription item, preferring the one matching preferredItemId if provided.
|
|
218
|
+
*/
|
|
219
|
+
getPrimarySubscriptionItem(subscription, preferredItemId) {
|
|
220
|
+
if (!subscription.items?.data?.length) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
if (preferredItemId) {
|
|
224
|
+
const match = subscription.items.data.find(item => item.id === preferredItemId);
|
|
225
|
+
if (match) {
|
|
226
|
+
return match;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return subscription.items.data[0] ?? null;
|
|
230
|
+
}
|
|
231
|
+
// Private helpers
|
|
232
|
+
async buildDowngradePhases(schedule, newPriceId, options) {
|
|
233
|
+
const phases = [];
|
|
234
|
+
if (schedule.phases && schedule.current_phase) {
|
|
235
|
+
const currentPhaseStart = schedule.current_phase.start_date;
|
|
236
|
+
const currentPhaseIndex = schedule.phases.findIndex(phase => phase.start_date === currentPhaseStart);
|
|
237
|
+
if (currentPhaseIndex === -1) {
|
|
238
|
+
throw new http_error_1.HttpError(500, 'Unable to determine the current subscription phase: ' +
|
|
239
|
+
'current_phase.start_date does not match any phase start_date.');
|
|
240
|
+
}
|
|
241
|
+
const currentPhase = schedule.phases[currentPhaseIndex];
|
|
242
|
+
phases.push({
|
|
243
|
+
items: currentPhase.items.map(item => ({
|
|
244
|
+
price: typeof item.price === 'string' ? item.price : item.price.id,
|
|
245
|
+
quantity: item.quantity,
|
|
246
|
+
})),
|
|
247
|
+
start_date: currentPhase.start_date,
|
|
248
|
+
end_date: currentPhase.end_date || undefined,
|
|
249
|
+
metadata: currentPhase.metadata || undefined,
|
|
250
|
+
proration_behavior: currentPhase.proration_behavior,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
const newPrice = await this.stripe.prices.retrieve(newPriceId);
|
|
254
|
+
const interval = newPrice.recurring.interval;
|
|
255
|
+
const intervalCount = newPrice.recurring?.interval_count ?? 1;
|
|
256
|
+
const newPhase = {
|
|
257
|
+
items: [{ price: newPriceId, quantity: options?.quantity ?? 1 }],
|
|
258
|
+
metadata: { type: SubscriptionService.phaseTypeNew, ...options?.phaseMetadata },
|
|
259
|
+
proration_behavior: 'none',
|
|
260
|
+
billing_cycle_anchor: 'phase_start',
|
|
261
|
+
duration: { interval, interval_count: intervalCount },
|
|
262
|
+
};
|
|
263
|
+
if (options?.transferData) {
|
|
264
|
+
newPhase.transfer_data = options.transferData;
|
|
265
|
+
}
|
|
266
|
+
phases.push(newPhase);
|
|
267
|
+
return phases;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
exports.SubscriptionService = SubscriptionService;
|
|
271
|
+
SubscriptionService.phaseTypeNew = 'new';
|
|
272
|
+
SubscriptionService.phaseTypeDowngrade = 'downgrade';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/tests/helpers.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAE/D,eAAO,MAAM,mBAAmB,EAAE,QAAQ,CAAC,mBAAmB,CAa7D,CAAC;AAEF,wBAAgB,gBAAgB,IAAI,MAAM,CA4EzC"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MOCK_SERVICE_CONFIG = void 0;
|
|
4
|
+
exports.createMockStripe = createMockStripe;
|
|
5
|
+
const vitest_1 = require("vitest");
|
|
6
|
+
exports.MOCK_SERVICE_CONFIG = {
|
|
7
|
+
currency: 'usd',
|
|
8
|
+
orderPaymentMethods: ['card'],
|
|
9
|
+
subscriptionPaymentMethods: ['card'],
|
|
10
|
+
setupIntentPaymentMethods: ['card'],
|
|
11
|
+
checkoutUiMode: 'custom',
|
|
12
|
+
allowPromotionCodes: true,
|
|
13
|
+
savePaymentMethod: true,
|
|
14
|
+
orderInvoiceCreation: true,
|
|
15
|
+
invoiceCollectionMethod: 'send_invoice',
|
|
16
|
+
invoiceDaysUntilDue: 3,
|
|
17
|
+
invoicePaymentMethodTypes: ['card', 'link'],
|
|
18
|
+
connectedAccountType: 'express',
|
|
19
|
+
};
|
|
20
|
+
function createMockStripe() {
|
|
21
|
+
return {
|
|
22
|
+
customers: {
|
|
23
|
+
create: vitest_1.vi.fn(),
|
|
24
|
+
update: vitest_1.vi.fn(),
|
|
25
|
+
retrieve: vitest_1.vi.fn(),
|
|
26
|
+
},
|
|
27
|
+
subscriptions: {
|
|
28
|
+
retrieve: vitest_1.vi.fn(),
|
|
29
|
+
list: vitest_1.vi.fn(),
|
|
30
|
+
update: vitest_1.vi.fn(),
|
|
31
|
+
cancel: vitest_1.vi.fn(),
|
|
32
|
+
create: vitest_1.vi.fn(),
|
|
33
|
+
},
|
|
34
|
+
subscriptionSchedules: {
|
|
35
|
+
retrieve: vitest_1.vi.fn(),
|
|
36
|
+
create: vitest_1.vi.fn(),
|
|
37
|
+
update: vitest_1.vi.fn(),
|
|
38
|
+
release: vitest_1.vi.fn(),
|
|
39
|
+
},
|
|
40
|
+
checkout: {
|
|
41
|
+
sessions: {
|
|
42
|
+
create: vitest_1.vi.fn(),
|
|
43
|
+
expire: vitest_1.vi.fn(),
|
|
44
|
+
retrieve: vitest_1.vi.fn(),
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
setupIntents: {
|
|
48
|
+
create: vitest_1.vi.fn(),
|
|
49
|
+
},
|
|
50
|
+
prices: {
|
|
51
|
+
create: vitest_1.vi.fn(),
|
|
52
|
+
update: vitest_1.vi.fn(),
|
|
53
|
+
retrieve: vitest_1.vi.fn(),
|
|
54
|
+
},
|
|
55
|
+
products: {
|
|
56
|
+
update: vitest_1.vi.fn(),
|
|
57
|
+
},
|
|
58
|
+
paymentLinks: {
|
|
59
|
+
create: vitest_1.vi.fn(),
|
|
60
|
+
update: vitest_1.vi.fn(),
|
|
61
|
+
},
|
|
62
|
+
invoices: {
|
|
63
|
+
create: vitest_1.vi.fn(),
|
|
64
|
+
list: vitest_1.vi.fn(),
|
|
65
|
+
sendInvoice: vitest_1.vi.fn(),
|
|
66
|
+
finalizeInvoice: vitest_1.vi.fn(),
|
|
67
|
+
retrieve: vitest_1.vi.fn(),
|
|
68
|
+
},
|
|
69
|
+
invoiceItems: {
|
|
70
|
+
create: vitest_1.vi.fn(),
|
|
71
|
+
},
|
|
72
|
+
invoicePayments: {
|
|
73
|
+
list: vitest_1.vi.fn(),
|
|
74
|
+
},
|
|
75
|
+
paymentMethods: {
|
|
76
|
+
retrieve: vitest_1.vi.fn(),
|
|
77
|
+
list: vitest_1.vi.fn(),
|
|
78
|
+
attach: vitest_1.vi.fn(),
|
|
79
|
+
detach: vitest_1.vi.fn(),
|
|
80
|
+
},
|
|
81
|
+
paymentIntents: {
|
|
82
|
+
retrieve: vitest_1.vi.fn(),
|
|
83
|
+
},
|
|
84
|
+
accounts: {
|
|
85
|
+
create: vitest_1.vi.fn(),
|
|
86
|
+
del: vitest_1.vi.fn(),
|
|
87
|
+
createLoginLink: vitest_1.vi.fn(),
|
|
88
|
+
},
|
|
89
|
+
accountLinks: {
|
|
90
|
+
create: vitest_1.vi.fn(),
|
|
91
|
+
},
|
|
92
|
+
webhooks: {
|
|
93
|
+
constructEvent: vitest_1.vi.fn(),
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { StripeProcessingFees } from './../models/config.model';
|
|
2
|
+
/**
|
|
3
|
+
* Returns a human-readable label for a billing cycle.
|
|
4
|
+
*/
|
|
5
|
+
export declare function getBillingCycleLabel(billingPeriod: string, billingIntervalCount: number): string;
|
|
6
|
+
/**
|
|
7
|
+
* Calculates the Stripe transfer percentage for a subscription affiliate payout after deducting processing fees.
|
|
8
|
+
* Formula: P = ((G - F) * A) / G, where G = gross, F = Stripe fee, A = affiliate payout percent.
|
|
9
|
+
*/
|
|
10
|
+
export declare function calculateAffiliateSubscriptionPayoutPercent(subscriptionCost: number, payoutPercent: number, processingFees: StripeProcessingFees): number;
|
|
11
|
+
/**
|
|
12
|
+
* Calculates the flat payout amount for a one-time payment affiliate payout after deducting processing fees.
|
|
13
|
+
*/
|
|
14
|
+
export declare function calculateAffiliatePaymentPayoutAmount(cost: number, affiliatePayoutPercent: number, processingFees: StripeProcessingFees): number;
|
|
15
|
+
//# sourceMappingURL=helpers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/utils/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAEhE;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,aAAa,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,GAAG,MAAM,CAmBhG;AAED;;;GAGG;AACH,wBAAgB,2CAA2C,CAAC,gBAAgB,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,cAAc,EAAE,oBAAoB,GAAG,MAAM,CAKzJ;AAED;;GAEG;AACH,wBAAgB,qCAAqC,CAAC,IAAI,EAAE,MAAM,EAAE,sBAAsB,EAAE,MAAM,EAAE,cAAc,EAAE,oBAAoB,GAAG,MAAM,CAIhJ"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getBillingCycleLabel = getBillingCycleLabel;
|
|
4
|
+
exports.calculateAffiliateSubscriptionPayoutPercent = calculateAffiliateSubscriptionPayoutPercent;
|
|
5
|
+
exports.calculateAffiliatePaymentPayoutAmount = calculateAffiliatePaymentPayoutAmount;
|
|
6
|
+
/**
|
|
7
|
+
* Returns a human-readable label for a billing cycle.
|
|
8
|
+
*/
|
|
9
|
+
function getBillingCycleLabel(billingPeriod, billingIntervalCount) {
|
|
10
|
+
if (billingIntervalCount === 1) {
|
|
11
|
+
switch (billingPeriod) {
|
|
12
|
+
case 'day': return 'Daily';
|
|
13
|
+
case 'week': return 'Weekly';
|
|
14
|
+
case 'month': return 'Monthly';
|
|
15
|
+
case 'year': return 'Yearly';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
if (billingPeriod === 'month' && billingIntervalCount === 3) {
|
|
19
|
+
return 'Quarterly';
|
|
20
|
+
}
|
|
21
|
+
if (billingPeriod === 'month' && billingIntervalCount === 6) {
|
|
22
|
+
return 'Semi-Annually';
|
|
23
|
+
}
|
|
24
|
+
return `Every ${billingIntervalCount} ${billingPeriod}s`;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Calculates the Stripe transfer percentage for a subscription affiliate payout after deducting processing fees.
|
|
28
|
+
* Formula: P = ((G - F) * A) / G, where G = gross, F = Stripe fee, A = affiliate payout percent.
|
|
29
|
+
*/
|
|
30
|
+
function calculateAffiliateSubscriptionPayoutPercent(subscriptionCost, payoutPercent, processingFees) {
|
|
31
|
+
const stripeFee = Math.round((subscriptionCost * processingFees.percent) + processingFees.flat);
|
|
32
|
+
const affiliatePayoutPercentRaw = ((subscriptionCost - stripeFee) * payoutPercent) / subscriptionCost;
|
|
33
|
+
return Number(affiliatePayoutPercentRaw.toFixed(2));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Calculates the flat payout amount for a one-time payment affiliate payout after deducting processing fees.
|
|
37
|
+
*/
|
|
38
|
+
function calculateAffiliatePaymentPayoutAmount(cost, affiliatePayoutPercent, processingFees) {
|
|
39
|
+
const stripeFee = Math.round((cost * processingFees.percent) + processingFees.flat);
|
|
40
|
+
return Math.round((cost - stripeFee) * (affiliatePayoutPercent / 100));
|
|
41
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import Stripe from 'stripe';
|
|
2
|
+
import { InvoiceService } from './../services/invoice/invoice.service';
|
|
3
|
+
import { CheckoutService } from './../services/checkout/checkout.service';
|
|
4
|
+
import { WebhookHooks } from './../models/webhook.model';
|
|
5
|
+
export declare class WebhookDispatcher {
|
|
6
|
+
private readonly hooks;
|
|
7
|
+
private readonly checkout;
|
|
8
|
+
private readonly invoice;
|
|
9
|
+
constructor(hooks: WebhookHooks, checkout: CheckoutService, invoice: InvoiceService);
|
|
10
|
+
/**
|
|
11
|
+
* Routes a main webhook event to the appropriate handler.
|
|
12
|
+
* Unhandled event types are silently ignored.
|
|
13
|
+
*/
|
|
14
|
+
dispatchMainEvent(event: Stripe.Event): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Routes a connected account webhook event. Currently handles account.updated only.
|
|
17
|
+
*/
|
|
18
|
+
dispatchConnectedEvent(event: Stripe.Event): Promise<void>;
|
|
19
|
+
private handleCheckoutCompleted;
|
|
20
|
+
private handleInvoicePaid;
|
|
21
|
+
private handleInvoicePaymentFailed;
|
|
22
|
+
private handleSubscriptionDeleted;
|
|
23
|
+
private extractPaymentFailReason;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=webhook.dispatcher.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webhook.dispatcher.d.ts","sourceRoot":"","sources":["../../src/webhooks/webhook.dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,cAAc,EAAE,MAAM,uCAAuC,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,yCAAyC,CAAC;AAE1E,OAAO,EAAE,YAAY,EAAyG,MAAM,2BAA2B,CAAC;AAEhK,qBAAa,iBAAiB;IAG1B,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAFP,KAAK,EAAE,YAAY,EACnB,QAAQ,EAAE,eAAe,EACzB,OAAO,EAAE,cAAc;IAE1C;;;OAGG;IACU,iBAAiB,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IA0BlE;;OAEG;IACU,sBAAsB,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;YAgBzD,uBAAuB;YAmBvB,iBAAiB;YAYjB,0BAA0B;YAe1B,yBAAyB;YAczB,wBAAwB;CAmBvC"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WebhookDispatcher = void 0;
|
|
4
|
+
class WebhookDispatcher {
|
|
5
|
+
constructor(hooks, checkout, invoice) {
|
|
6
|
+
this.hooks = hooks;
|
|
7
|
+
this.checkout = checkout;
|
|
8
|
+
this.invoice = invoice;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Routes a main webhook event to the appropriate handler.
|
|
12
|
+
* Unhandled event types are silently ignored.
|
|
13
|
+
*/
|
|
14
|
+
async dispatchMainEvent(event) {
|
|
15
|
+
switch (event.type) {
|
|
16
|
+
case 'checkout.session.completed':
|
|
17
|
+
await this.handleCheckoutCompleted(event);
|
|
18
|
+
break;
|
|
19
|
+
case 'invoice.paid':
|
|
20
|
+
await this.handleInvoicePaid(event);
|
|
21
|
+
break;
|
|
22
|
+
case 'invoice.payment_failed':
|
|
23
|
+
await this.handleInvoicePaymentFailed(event);
|
|
24
|
+
break;
|
|
25
|
+
case 'customer.subscription.deleted':
|
|
26
|
+
await this.handleSubscriptionDeleted(event);
|
|
27
|
+
break;
|
|
28
|
+
default:
|
|
29
|
+
// Unhandled event types are silently ignored — not an error.
|
|
30
|
+
// Throwing here would cause Stripe to retry the event for up to 72 hours.
|
|
31
|
+
// https://docs.stripe.com/webhooks#best-practices
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Routes a connected account webhook event. Currently handles account.updated only.
|
|
37
|
+
*/
|
|
38
|
+
async dispatchConnectedEvent(event) {
|
|
39
|
+
if (event.type !== 'account.updated') {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (!this.hooks.onConnectedAccountUpdated) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const account = event.data.object;
|
|
46
|
+
await this.hooks.onConnectedAccountUpdated({ account });
|
|
47
|
+
}
|
|
48
|
+
// Private handlers — Stripe API calls done here, hook called with enriched data
|
|
49
|
+
async handleCheckoutCompleted(event) {
|
|
50
|
+
if (!this.hooks.onCheckoutCompleted) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const baseSession = event.data.object;
|
|
54
|
+
const session = await this.checkout.retrieveCheckoutSession(baseSession.id, {
|
|
55
|
+
expand: ['payment_intent.latest_charge', 'invoice'],
|
|
56
|
+
});
|
|
57
|
+
const payload = {
|
|
58
|
+
session,
|
|
59
|
+
metadata: session.metadata ?? {},
|
|
60
|
+
};
|
|
61
|
+
await this.hooks.onCheckoutCompleted(payload);
|
|
62
|
+
}
|
|
63
|
+
async handleInvoicePaid(event) {
|
|
64
|
+
if (!this.hooks.onInvoicePaid) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const invoice = event.data.object;
|
|
68
|
+
const payload = { event, invoice };
|
|
69
|
+
await this.hooks.onInvoicePaid(payload);
|
|
70
|
+
}
|
|
71
|
+
async handleInvoicePaymentFailed(event) {
|
|
72
|
+
if (!this.hooks.onInvoicePaymentFailed) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const invoice = event.data.object;
|
|
76
|
+
// Extract fail reason from payment intent before calling the hook
|
|
77
|
+
const failReason = await this.extractPaymentFailReason(invoice.id);
|
|
78
|
+
const payload = { event, invoice, failReason };
|
|
79
|
+
await this.hooks.onInvoicePaymentFailed(payload);
|
|
80
|
+
}
|
|
81
|
+
async handleSubscriptionDeleted(event) {
|
|
82
|
+
if (!this.hooks.onSubscriptionDeleted) {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const subscription = event.data.object;
|
|
86
|
+
const payload = { event, subscription };
|
|
87
|
+
await this.hooks.onSubscriptionDeleted(payload);
|
|
88
|
+
}
|
|
89
|
+
// Utility
|
|
90
|
+
async extractPaymentFailReason(invoiceId) {
|
|
91
|
+
try {
|
|
92
|
+
const payments = await this.invoice.listInvoicePayments(invoiceId);
|
|
93
|
+
if (!payments.data.length || !payments.data[0].payment.payment_intent) {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const intent = await this.checkout.getPaymentIntent(payments.data[0].payment.payment_intent.toString());
|
|
97
|
+
return intent.last_payment_error?.decline_code ?? intent.last_payment_error?.code ?? null;
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
this.hooks.onError?.('extractPaymentFailReason', err);
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
exports.WebhookDispatcher = WebhookDispatcher;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import Stripe from 'stripe';
|
|
2
|
+
import { InvoiceService } from './../services/invoice/invoice.service';
|
|
3
|
+
import { CheckoutService } from './../services/checkout/checkout.service';
|
|
4
|
+
import { WebhookHooks } from './../models/webhook.model';
|
|
5
|
+
import { WebhookHandlerConfig } from './../models/config.model';
|
|
6
|
+
interface WebhookRequest {
|
|
7
|
+
rawBody?: string | Buffer;
|
|
8
|
+
body?: any;
|
|
9
|
+
headers: Record<string, string | string[] | undefined>;
|
|
10
|
+
}
|
|
11
|
+
interface WebhookResponse {
|
|
12
|
+
status(code: number): WebhookResponse;
|
|
13
|
+
json(body?: any): void;
|
|
14
|
+
}
|
|
15
|
+
export declare class StripeWebhookHandler {
|
|
16
|
+
private readonly hooks;
|
|
17
|
+
private readonly stripe;
|
|
18
|
+
private readonly config;
|
|
19
|
+
private readonly checkoutService;
|
|
20
|
+
private readonly invoiceService;
|
|
21
|
+
constructor(hooks: WebhookHooks, stripe: Stripe, config: WebhookHandlerConfig, checkoutService: CheckoutService, invoiceService: InvoiceService);
|
|
22
|
+
private readonly dispatcher;
|
|
23
|
+
/**
|
|
24
|
+
* Express request handler for the main Stripe webhook endpoint.
|
|
25
|
+
* Requires the raw request body on req (use express.raw() middleware before this route).
|
|
26
|
+
* Pass next to delegate errors to Express error middleware; omit it for standalone HTTP error responses.
|
|
27
|
+
*/
|
|
28
|
+
handle: (req: WebhookRequest, res: WebhookResponse, next?: (err: unknown) => void) => Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Express request handler for the Stripe connected account webhook endpoint.
|
|
31
|
+
* Requires the raw request body on req (use express.raw() middleware before this route).
|
|
32
|
+
* Throws if connectedWebhookSecret is not configured.
|
|
33
|
+
*/
|
|
34
|
+
handleConnected: (req: WebhookRequest, res: WebhookResponse, next?: (err: unknown) => void) => Promise<void>;
|
|
35
|
+
private processWebhook;
|
|
36
|
+
private isVerificationError;
|
|
37
|
+
}
|
|
38
|
+
export {};
|
|
39
|
+
//# sourceMappingURL=webhook.handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webhook.handler.d.ts","sourceRoot":"","sources":["../../src/webhooks/webhook.handler.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAI5B,OAAO,EAAE,cAAc,EAAE,MAAM,uCAAuC,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,yCAAyC,CAAC;AAE1E,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAGhE,UAAU,cAAc;IACtB,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC1B,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;CACxD;AAED,UAAU,eAAe;IACvB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,CAAC;IACtC,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC;CACxB;AAED,qBAAa,oBAAoB;IAG7B,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,eAAe;IAChC,OAAO,CAAC,QAAQ,CAAC,cAAc;gBAJd,KAAK,EAAE,YAAY,EACnB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,oBAAoB,EAC5B,eAAe,EAAE,eAAe,EAChC,cAAc,EAAE,cAAc;IAKjD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAoB;IAE/C;;;;OAIG;IACI,MAAM,GAAU,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,KAAG,OAAO,CAAC,IAAI,CAAC,CAM7G;IAEF;;;;OAIG;IACI,eAAe,GAAU,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,KAAG,OAAO,CAAC,IAAI,CAAC,CAYtH;YAEY,cAAc;IAuC5B,OAAO,CAAC,mBAAmB;CAG5B"}
|