@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.
Files changed (65) hide show
  1. package/README.md +1003 -0
  2. package/dist/apex-stripe.d.ts +23 -0
  3. package/dist/apex-stripe.d.ts.map +1 -0
  4. package/dist/apex-stripe.js +41 -0
  5. package/dist/client.d.ts +7 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +14 -0
  8. package/dist/errors/http-error.d.ts +7 -0
  9. package/dist/errors/http-error.d.ts.map +1 -0
  10. package/dist/errors/http-error.js +14 -0
  11. package/dist/index.d.ts +16 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +48 -0
  14. package/dist/models/config.model.d.ts +31 -0
  15. package/dist/models/config.model.d.ts.map +1 -0
  16. package/dist/models/config.model.js +2 -0
  17. package/dist/models/index.d.ts +5 -0
  18. package/dist/models/index.d.ts.map +1 -0
  19. package/dist/models/index.js +20 -0
  20. package/dist/models/stripe.model.d.ts +69 -0
  21. package/dist/models/stripe.model.d.ts.map +1 -0
  22. package/dist/models/stripe.model.js +2 -0
  23. package/dist/models/subscription.model.d.ts +24 -0
  24. package/dist/models/subscription.model.d.ts.map +1 -0
  25. package/dist/models/subscription.model.js +2 -0
  26. package/dist/models/webhook.model.d.ts +43 -0
  27. package/dist/models/webhook.model.d.ts.map +1 -0
  28. package/dist/models/webhook.model.js +2 -0
  29. package/dist/services/checkout/checkout.service.d.ts +31 -0
  30. package/dist/services/checkout/checkout.service.d.ts.map +1 -0
  31. package/dist/services/checkout/checkout.service.js +119 -0
  32. package/dist/services/connected-account/connected-account.service.d.ts +25 -0
  33. package/dist/services/connected-account/connected-account.service.d.ts.map +1 -0
  34. package/dist/services/connected-account/connected-account.service.js +46 -0
  35. package/dist/services/customer/customer.service.d.ts +14 -0
  36. package/dist/services/customer/customer.service.d.ts.map +1 -0
  37. package/dist/services/customer/customer.service.js +23 -0
  38. package/dist/services/invoice/invoice.service.d.ts +24 -0
  39. package/dist/services/invoice/invoice.service.d.ts.map +1 -0
  40. package/dist/services/invoice/invoice.service.js +65 -0
  41. package/dist/services/payment-link/payment-link.service.d.ts +18 -0
  42. package/dist/services/payment-link/payment-link.service.d.ts.map +1 -0
  43. package/dist/services/payment-link/payment-link.service.js +53 -0
  44. package/dist/services/payment-method/payment-method.service.d.ts +43 -0
  45. package/dist/services/payment-method/payment-method.service.d.ts.map +1 -0
  46. package/dist/services/payment-method/payment-method.service.js +89 -0
  47. package/dist/services/price/price.service.d.ts +17 -0
  48. package/dist/services/price/price.service.d.ts.map +1 -0
  49. package/dist/services/price/price.service.js +32 -0
  50. package/dist/services/subscription/subscription.service.d.ts +89 -0
  51. package/dist/services/subscription/subscription.service.d.ts.map +1 -0
  52. package/dist/services/subscription/subscription.service.js +272 -0
  53. package/dist/tests/helpers.d.ts +5 -0
  54. package/dist/tests/helpers.d.ts.map +1 -0
  55. package/dist/tests/helpers.js +96 -0
  56. package/dist/utils/helpers.d.ts +15 -0
  57. package/dist/utils/helpers.d.ts.map +1 -0
  58. package/dist/utils/helpers.js +41 -0
  59. package/dist/webhooks/webhook.dispatcher.d.ts +25 -0
  60. package/dist/webhooks/webhook.dispatcher.d.ts.map +1 -0
  61. package/dist/webhooks/webhook.dispatcher.js +105 -0
  62. package/dist/webhooks/webhook.handler.d.ts +39 -0
  63. package/dist/webhooks/webhook.handler.d.ts.map +1 -0
  64. package/dist/webhooks/webhook.handler.js +70 -0
  65. package/package.json +57 -0
package/README.md ADDED
@@ -0,0 +1,1003 @@
1
+ # @apexara/stripe
2
+
3
+ A typed Stripe service layer for Node.js. Wraps the official Stripe SDK into focused, independently injectable services with built-in webhook handling, idempotency, and affiliate payout math.
4
+
5
+ ## Contents
6
+
7
+ - [Installation](#installation)
8
+ - [Quick Start](#quick-start)
9
+ - [Configuration](#configuration)
10
+ - [Services](#services)
11
+ - [CheckoutService](#checkoutservice)
12
+ - [CustomerService](#customerservice)
13
+ - [InvoiceService](#invoiceservice)
14
+ - [PaymentLinkService](#paymentlinkservice)
15
+ - [PaymentMethodService](#paymentmethodservice)
16
+ - [PriceService](#priceservice)
17
+ - [ConnectedAccountService](#connectedaccountservice)
18
+ - [SubscriptionService](#subscriptionservice)
19
+ - [Webhooks](#webhooks)
20
+ - [Advanced Usage](#advanced-usage)
21
+ - [API Reference — Types](#api-reference--types)
22
+ - [Development](#development)
23
+
24
+ ---
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install @apexara/stripe
30
+ ```
31
+
32
+ Express is an optional peer dependency — only required if you use `StripeWebhookHandler`:
33
+
34
+ ```bash
35
+ npm install express
36
+ ```
37
+
38
+ **Requirements:** Node.js 18+, TypeScript 5+
39
+
40
+ ---
41
+
42
+ ## Quick Start
43
+
44
+ ```typescript
45
+ import { ApexStripe } from '@apexara/stripe';
46
+
47
+ const stripe = new ApexStripe(
48
+ { secretKey: process.env.STRIPE_SECRET_KEY! },
49
+ { currency: 'usd' },
50
+ );
51
+
52
+ // Create a customer
53
+ const customer = await stripe.customers.createCustomer('Jane', 'Doe', 'jane@example.com');
54
+
55
+ // Create a checkout session
56
+ const clientSecret = await stripe.checkout.createCheckoutSession({
57
+ mode: 'payment',
58
+ customerId: customer.id,
59
+ name: 'Order #1234',
60
+ cost: 4900, // $49.00 in cents
61
+ quantity: 1,
62
+ returnUrl: 'https://example.com/payment-result',
63
+ });
64
+
65
+ // Access the raw Stripe client if needed
66
+ const balance = await stripe.client.balance.retrieve();
67
+ ```
68
+
69
+ ---
70
+
71
+ ## Configuration
72
+
73
+ ### `StripeClientConfig`
74
+
75
+ Passed as the first argument to `ApexStripe`. Controls how the Stripe SDK client is created.
76
+
77
+ ```typescript
78
+ interface StripeClientConfig {
79
+ secretKey: string;
80
+ apiVersion?: Stripe.LatestApiVersion; // Default: '2025-08-27.basil'
81
+ }
82
+ ```
83
+
84
+ ### `StripeServiceConfig`
85
+
86
+ Passed as the second (optional) argument to `ApexStripe`. All fields are optional — defaults are applied for any field not provided.
87
+
88
+ ```typescript
89
+ interface StripeServiceConfig {
90
+ // Stripe settings
91
+ currency?: string; // Default: 'usd'
92
+
93
+ // Payment methods per context
94
+ orderPaymentMethods?: string[]; // Default: ['card', 'link', 'cashapp', 'klarna']
95
+ subscriptionPaymentMethods?: string[]; // Default: ['card', 'link', 'cashapp']
96
+ setupIntentPaymentMethods?: string[]; // Default: ['card']
97
+
98
+ // Checkout behavior
99
+ checkoutUiMode?: 'custom' | 'embedded' | 'hosted'; // Default: 'custom'
100
+ allowPromotionCodes?: boolean; // Default: true
101
+ savePaymentMethod?: boolean; // Default: true
102
+ orderInvoiceCreation?: boolean; // Default: true
103
+
104
+ // Invoices
105
+ invoiceCollectionMethod?: 'send_invoice' | 'charge_automatically'; // Default: 'send_invoice'
106
+ invoiceDaysUntilDue?: number; // Default: 3
107
+ invoicePaymentMethodTypes?: string[]; // Default: ['card', 'link']
108
+
109
+ // Connected accounts
110
+ connectedAccountType?: 'express' | 'standard' | 'custom'; // Default: 'express'
111
+
112
+ }
113
+ ```
114
+
115
+ **Full example with all defaults overridden:**
116
+
117
+ ```typescript
118
+ const stripe = new ApexStripe(
119
+ { secretKey: process.env.STRIPE_SECRET_KEY! },
120
+ {
121
+ currency: 'eur',
122
+ orderPaymentMethods: ['card'],
123
+ subscriptionPaymentMethods: ['card'],
124
+ setupIntentPaymentMethods: ['card'],
125
+ checkoutUiMode: 'embedded',
126
+ allowPromotionCodes: false,
127
+ savePaymentMethod: false,
128
+ orderInvoiceCreation: false,
129
+ invoiceCollectionMethod: 'charge_automatically',
130
+ invoiceDaysUntilDue: 7,
131
+ invoicePaymentMethodTypes: ['card'],
132
+ connectedAccountType: 'standard',
133
+ },
134
+ );
135
+ ```
136
+
137
+ ---
138
+
139
+ ## Services
140
+
141
+ All services are available as properties on the `ApexStripe` instance. They can also be instantiated independently — see [Advanced Usage](#advanced-usage).
142
+
143
+ ---
144
+
145
+ ### CheckoutService
146
+
147
+ `stripe.checkout`
148
+
149
+ Handles Stripe Checkout sessions, Setup Intents, and affiliate payout calculations.
150
+
151
+ ---
152
+
153
+ #### `createCheckoutSession(params)`
154
+
155
+ Creates a payment or subscription checkout session. Returns the `client_secret` for use with Stripe.js.
156
+
157
+ **Payment mode:**
158
+
159
+ ```typescript
160
+ const clientSecret = await stripe.checkout.createCheckoutSession({
161
+ mode: 'payment',
162
+ customerId: 'cus_xxx',
163
+ name: 'Order #1234',
164
+ cost: 4900, // Amount in cents
165
+ quantity: 1,
166
+ returnUrl: 'https://example.com/result',
167
+ metadata: { orderId: '1234' },
168
+ // Optional: affiliate payout
169
+ affiliate: {
170
+ accountId: 'acct_xxx', // Connected account ID
171
+ amount: 490, // Payout amount in cents
172
+ },
173
+ });
174
+ ```
175
+
176
+ **Subscription mode:**
177
+
178
+ ```typescript
179
+ const clientSecret = await stripe.checkout.createCheckoutSession({
180
+ mode: 'subscription',
181
+ customerId: 'cus_xxx',
182
+ priceIds: ['price_xxx'],
183
+ quantity: 1,
184
+ returnUrl: 'https://example.com/result',
185
+ metadata: { userId: 'user_123' },
186
+ // Optional: affiliate payout
187
+ affiliate: {
188
+ transferData: { destination: 'acct_xxx', amount_percent: 19 },
189
+ metadata: { affiliateId: 'aff_xxx' },
190
+ },
191
+ });
192
+ ```
193
+
194
+ ---
195
+
196
+ #### `createSetupIntentSession(customerId)`
197
+
198
+ Creates a Setup Intent for saving a payment method without charging. Returns the `client_secret`.
199
+
200
+ ```typescript
201
+ const clientSecret = await stripe.checkout.createSetupIntentSession('cus_xxx');
202
+ ```
203
+
204
+ ---
205
+
206
+ #### `expireCheckoutSession(sessionId)`
207
+
208
+ Expires an open checkout session. Silently ignores sessions that are already expired — safe to call unconditionally.
209
+
210
+ ```typescript
211
+ await stripe.checkout.expireCheckoutSession('cs_xxx');
212
+ ```
213
+
214
+ ---
215
+
216
+ #### `retrieveCheckoutSession(sessionId, options?)`
217
+
218
+ Retrieves a checkout session with optional expansion.
219
+
220
+ ```typescript
221
+ const session = await stripe.checkout.retrieveCheckoutSession('cs_xxx', {
222
+ expand: ['payment_intent.latest_charge', 'invoice'],
223
+ });
224
+ ```
225
+
226
+ ---
227
+
228
+ #### `getPaymentIntent(paymentIntentId, options?)`
229
+
230
+ Retrieves a payment intent.
231
+
232
+ ```typescript
233
+ const intent = await stripe.checkout.getPaymentIntent('pi_xxx');
234
+ ```
235
+
236
+ ---
237
+
238
+ ### CustomerService
239
+
240
+ `stripe.customers`
241
+
242
+ ---
243
+
244
+ #### `createCustomer(firstName, lastName, email)`
245
+
246
+ Creates a Stripe customer. The full name is stored as `${firstName} ${lastName}`.
247
+
248
+ ```typescript
249
+ const customer = await stripe.customers.createCustomer('Jane', 'Doe', 'jane@example.com');
250
+ // → Stripe.Customer
251
+ ```
252
+
253
+ ---
254
+
255
+ #### `updateCustomerDefaultPaymentMethod(customerId, paymentMethodId)`
256
+
257
+ Sets the default payment method on a customer's invoice settings.
258
+
259
+ ```typescript
260
+ await stripe.customers.updateCustomerDefaultPaymentMethod('cus_xxx', 'pm_xxx');
261
+ ```
262
+
263
+ ---
264
+
265
+ ### InvoiceService
266
+
267
+ `stripe.invoices`
268
+
269
+ ---
270
+
271
+ #### `createInvoice(params)`
272
+
273
+ Creates an invoice with a single line item and either sends it or finalizes it, depending on `invoiceCollectionMethod`.
274
+
275
+ - `send_invoice` — creates, adds line item, sends — customer receives an email with payment link
276
+ - `charge_automatically` — creates, adds line item, finalizes — Stripe charges the default payment method
277
+
278
+ ```typescript
279
+ const invoice = await stripe.invoices.createInvoice({
280
+ customerId: 'cus_xxx',
281
+ amount: 2000, // In cents
282
+ description: 'Credit top-up — 500 records',
283
+ metadata: { origin: 'admin', credits: '500' },
284
+ });
285
+ // → Stripe.Invoice (sent or finalized)
286
+ ```
287
+
288
+ ---
289
+
290
+ #### `listInvoicePayments(invoiceId, params?)`
291
+
292
+ Lists all payments recorded against an invoice.
293
+
294
+ ```typescript
295
+ const payments = await stripe.invoices.listInvoicePayments('in_xxx');
296
+ // → Stripe.ApiList<Stripe.InvoicePayment>
297
+ ```
298
+
299
+ ---
300
+
301
+ #### `findPendingActivationInvoice(customerId)`
302
+
303
+ Checks whether a customer has an open invoice from a `subscription_create` event whose subscription is still active or incomplete. Returns the invoice data or `null`.
304
+
305
+ Use this to prompt the user to pay their pending subscription invoice after an admin-created invoice-based subscription.
306
+
307
+ ```typescript
308
+ const pending = await stripe.invoices.findPendingActivationInvoice('cus_xxx');
309
+
310
+ if (pending) {
311
+ // { subscriptionId: 'sub_xxx', hostedInvoiceUrl: 'https://...' }
312
+ redirectToInvoice(pending.hostedInvoiceUrl);
313
+ }
314
+ ```
315
+
316
+ Returns `null` when:
317
+ - No open invoices exist
318
+ - No invoice has `billing_reason === 'subscription_create'`
319
+ - The subscription is `canceled` or `incomplete_expired`
320
+
321
+ ---
322
+
323
+ ### PaymentLinkService
324
+
325
+ `stripe.paymentLinks`
326
+
327
+ ---
328
+
329
+ #### `createPaymentLink(params)`
330
+
331
+ Creates a Stripe Price and Payment Link in one call. Returns the link ID, URL, and the underlying price/product IDs needed to archive later.
332
+
333
+ ```typescript
334
+ const link = await stripe.paymentLinks.createPaymentLink({
335
+ name: 'Order #1234',
336
+ cost: 4900,
337
+ redirectUrl: 'https://example.com/result',
338
+ metadata: { orderId: '1234' },
339
+ // Optional: affiliate payout
340
+ affiliate: {
341
+ accountId: 'acct_xxx',
342
+ amount: 490,
343
+ },
344
+ });
345
+ // → { id, url, productId, priceId }
346
+ ```
347
+
348
+ ---
349
+
350
+ #### `archivePaymentLink(linkId, productId, priceId)`
351
+
352
+ Deactivates the payment link, product, and price so they no longer appear in Stripe or accept payments.
353
+
354
+ ```typescript
355
+ await stripe.paymentLinks.archivePaymentLink(
356
+ link.id,
357
+ link.productId,
358
+ link.priceId,
359
+ );
360
+ ```
361
+
362
+ ---
363
+
364
+ ### PaymentMethodService
365
+
366
+ `stripe.paymentMethods`
367
+
368
+ ---
369
+
370
+ #### `getPaymentMethod(paymentMethodId)`
371
+
372
+ ```typescript
373
+ const pm = await stripe.paymentMethods.getPaymentMethod('pm_xxx');
374
+ // → Stripe.PaymentMethod
375
+ ```
376
+
377
+ #### `listPaymentMethods(customerId)`
378
+
379
+ Returns the customer's saved payment methods as a flat array.
380
+
381
+ ```typescript
382
+ const methods = await stripe.paymentMethods.listPaymentMethods('cus_xxx');
383
+ // → Stripe.PaymentMethod[]
384
+ ```
385
+
386
+ #### `attachPaymentMethod(paymentMethodId, customerId)`
387
+
388
+ Attaches a payment method to a customer.
389
+
390
+ ```typescript
391
+ const pm = await stripe.paymentMethods.attachPaymentMethod('pm_xxx', 'cus_xxx');
392
+ ```
393
+
394
+ #### `setDefaultPaymentMethodForCustomerAndSubscription(customerId, subscriptionId, paymentMethodId)`
395
+
396
+ Attaches the payment method, sets it as the customer's invoice default, and sets it as the subscription's default — all in one call.
397
+
398
+ ```typescript
399
+ await stripe.paymentMethods.setDefaultPaymentMethodForCustomerAndSubscription(
400
+ 'cus_xxx',
401
+ 'sub_xxx',
402
+ 'pm_xxx',
403
+ );
404
+ ```
405
+
406
+ #### `setDefaultPaymentMethod(subscriptionId, paymentMethodId)`
407
+
408
+ Sets the subscription's default payment method unconditionally.
409
+
410
+ ```typescript
411
+ await stripe.paymentMethods.setDefaultPaymentMethod('sub_xxx', 'pm_xxx');
412
+ ```
413
+
414
+ #### `setDefaultPaymentMethodIfMissing(subscriptionId, paymentMethodId)`
415
+
416
+ Sets the default only if the subscription has no default payment method currently set.
417
+
418
+ ```typescript
419
+ const { changed } = await stripe.paymentMethods.setDefaultPaymentMethodIfMissing('sub_xxx', 'pm_xxx');
420
+ ```
421
+
422
+ #### `removePaymentMethod(customerId, subscriptionId, paymentMethodId)`
423
+
424
+ Removes a payment method safely. If it is the subscription's default, another payment method is assigned first. Throws if it is the only payment method on the customer.
425
+
426
+ ```typescript
427
+ const { newDefaultId } = await stripe.paymentMethods.removePaymentMethod(
428
+ 'cus_xxx',
429
+ 'sub_xxx',
430
+ 'pm_xxx',
431
+ );
432
+ ```
433
+
434
+ ---
435
+
436
+ ### PriceService
437
+
438
+ `stripe.prices`
439
+
440
+ ---
441
+
442
+ #### `createCustomSubscriptionPrice(params)`
443
+
444
+ Creates a recurring price on an existing Stripe product.
445
+
446
+ ```typescript
447
+ const price = await stripe.prices.createCustomSubscriptionPrice({
448
+ cost: 9900, // In cents
449
+ billingPeriod: 'month',
450
+ billingIntervalCount: 1,
451
+ label: 'Pro Monthly',
452
+ stripeProductId: 'prod_xxx',
453
+ metadata: { label: 'Pro Monthly', credits: '1000' },
454
+ });
455
+ // → Stripe.Price
456
+ ```
457
+
458
+ `billingPeriod` accepts: `'day' | 'week' | 'month' | 'year'`
459
+
460
+ ---
461
+
462
+ #### `archivePrice(priceId)`
463
+
464
+ Sets a price to `active: false` so it can no longer be used for new subscriptions.
465
+
466
+ ```typescript
467
+ await stripe.prices.archivePrice('price_xxx');
468
+ ```
469
+
470
+ ---
471
+
472
+ ### ConnectedAccountService
473
+
474
+ `stripe.connectedAccounts`
475
+
476
+ Handles Stripe Connect for marketplace and affiliate payout scenarios.
477
+
478
+ ---
479
+
480
+ #### `createConnectedAccount(metadata?)`
481
+
482
+ Creates a new connected account (type from config, defaults to `'express'`). Returns the account ID.
483
+
484
+ ```typescript
485
+ const accountId = await stripe.connectedAccounts.createConnectedAccount({
486
+ userId: 'user_123',
487
+ });
488
+ // → 'acct_xxx'
489
+ ```
490
+
491
+ ---
492
+
493
+ #### `deleteConnectedAccount(accountId)`
494
+
495
+ Permanently deletes a connected account.
496
+
497
+ ```typescript
498
+ await stripe.connectedAccounts.deleteConnectedAccount('acct_xxx');
499
+ ```
500
+
501
+ ---
502
+
503
+ #### `createAccountLink(accountId, refreshUrl, returnUrl, type?)`
504
+
505
+ Generates a Stripe-hosted onboarding or management URL for a connected account. Returns the URL string.
506
+
507
+ ```typescript
508
+ const url = await stripe.connectedAccounts.createAccountLink(
509
+ 'acct_xxx',
510
+ 'https://example.com/onboarding/refresh',
511
+ 'https://example.com/onboarding/return',
512
+ // type defaults to 'account_onboarding'
513
+ );
514
+ ```
515
+
516
+ `type` accepts: `'account_onboarding' | 'account_update'`
517
+
518
+ ---
519
+
520
+ #### `createLoginLink(accountId)`
521
+
522
+ Generates a single-use Express Dashboard login URL for a connected account. Returns the URL string.
523
+
524
+ ```typescript
525
+ const url = await stripe.connectedAccounts.createLoginLink('acct_xxx');
526
+ ```
527
+
528
+ ---
529
+
530
+ ### SubscriptionService
531
+
532
+ `stripe.subscriptions`
533
+
534
+ The most comprehensive service. Covers the full subscription lifecycle including scheduling, upgrades, downgrades, and payment method management.
535
+
536
+ ---
537
+
538
+ #### Basic operations
539
+
540
+ ```typescript
541
+ // Get a subscription (expands items.data.price)
542
+ const sub = await stripe.subscriptions.getSubscriptionById('sub_xxx');
543
+
544
+ // Get all subscriptions for a customer (status: 'all', expands default_payment_method)
545
+ const subs = await stripe.subscriptions.getAllUserSubscriptions('cus_xxx');
546
+ // → Stripe.Subscription[] (empty array if customerId is falsy)
547
+
548
+ // Update a subscription
549
+ const updated = await stripe.subscriptions.updateSubscription('sub_xxx', {
550
+ metadata: { userId: 'user_123' },
551
+ });
552
+
553
+ // Cancel immediately
554
+ const cancelled = await stripe.subscriptions.cancelSubscription('sub_xxx');
555
+ ```
556
+
557
+ ---
558
+
559
+ #### Lifecycle — cancel at period end / resume
560
+
561
+ ```typescript
562
+ // Schedule cancellation at end of billing period.
563
+ // Throws if status is not 'active' or 'past_due'.
564
+ const sub = await stripe.subscriptions.cancelSubscriptionAtPeriodEnd('sub_xxx');
565
+
566
+ // Undo a scheduled cancellation.
567
+ // Throws if cancel_at_period_end is false or status is not resumable.
568
+ const sub = await stripe.subscriptions.resumeSubscription('sub_xxx');
569
+ ```
570
+
571
+ ---
572
+
573
+ #### Plan switching and credits
574
+
575
+ Use `applyPlanCredit` to create a credit invoice item (a negative charge) before switching plans, so the customer is credited for unused days on their current plan:
576
+
577
+ ```typescript
578
+ await stripe.subscriptions.applyPlanCredit(
579
+ 'cus_xxx',
580
+ 'sub_xxx',
581
+ 3200, // Amount in cents — stored as a negative invoice item
582
+ 'usd',
583
+ 'Credit for unused Pro plan days', // Optional
584
+ { type: 'upgrade_credit' }, // Optional metadata
585
+ );
586
+ ```
587
+
588
+ Then switch the subscription to the new price immediately (billing cycle resets to now, no proration by default):
589
+
590
+ ```typescript
591
+ const updated = await stripe.subscriptions.switchSubscriptionPlan(
592
+ 'sub_xxx',
593
+ 'si_xxx', // The subscription item being replaced
594
+ 'price_xxx',
595
+ {
596
+ quantity: 1, // Optional, defaults to 1
597
+ proration: 'none', // Optional — pass 'create_prorations' to let Stripe calculate
598
+ },
599
+ );
600
+ ```
601
+
602
+ ---
603
+
604
+ #### Downgrades (scheduled)
605
+
606
+ Downgrades are scheduled to take effect at the end of the current billing period using Stripe Subscription Schedules.
607
+
608
+ ```typescript
609
+ // Schedule a downgrade to a lower price at period end.
610
+ // Tags the schedule with { type: 'downgrade' } for later identification.
611
+ const schedule = await stripe.subscriptions.scheduleDowngrade(
612
+ subscription,
613
+ 'price_lower_xxx',
614
+ {
615
+ transferData: { destination: 'acct_xxx', amount_percent: 19 }, // Optional
616
+ phaseMetadata: { affiliateId: 'aff_xxx' }, // Optional
617
+ scheduleMetadata: { initiatedBy: 'user' }, // Optional
618
+ },
619
+ );
620
+
621
+ // Check if a downgrade is scheduled (returns null if not, or if the
622
+ // schedule is not tagged as a downgrade).
623
+ const schedule = await stripe.subscriptions.getDowngradeSchedule(subscription);
624
+ if (schedule) {
625
+ // schedule.phases[1].items[0].price → the new lower price
626
+ }
627
+
628
+ // Cancel a scheduled downgrade (e.g. the user upgrades instead).
629
+ // Returns true if a downgrade schedule was found and released, false otherwise.
630
+ const released = await stripe.subscriptions.releaseScheduleIfDowngrade(subscription);
631
+ ```
632
+
633
+ For more control, get or create the schedule directly:
634
+
635
+ ```typescript
636
+ const schedule = await stripe.subscriptions.getOrCreateSubscriptionSchedule(subscription);
637
+ ```
638
+
639
+ ---
640
+
641
+ #### Invoice-based subscriptions (admin-created)
642
+
643
+ Creates a subscription using `send_invoice` collection and immediately emails the invoice to the customer. Use this for admin-created subscriptions where the customer pays via an emailed link rather than through a checkout session.
644
+
645
+ ```typescript
646
+ const { subscription, invoiceId, invoiceUrl } =
647
+ await stripe.subscriptions.createInvoiceBasedSubscription(
648
+ 'cus_xxx',
649
+ 'price_xxx',
650
+ {
651
+ daysUntilDue: 3, // Overrides config default
652
+ paymentMethodTypes: ['card', 'link'],
653
+ metadata: { adminId: 'admin_123', userId: 'user_456' },
654
+ transferData: { destination: 'acct_xxx', amount_percent: 19 }, // Optional affiliate
655
+ quantity: 1,
656
+ },
657
+ );
658
+
659
+ // invoiceUrl — the hosted_invoice_url to show the customer
660
+ // invoiceId — the Stripe invoice ID
661
+ ```
662
+
663
+ ---
664
+
665
+ #### Utilities
666
+
667
+ ```typescript
668
+ // Extract fields needed to keep a local subscription document in sync.
669
+ // Falls back to provided values when the subscription has no items yet.
670
+ const fields = stripe.subscriptions.buildSubscriptionSyncFields(subscription, {
671
+ currentPeriodStart: existingDoc.currentPeriodStart,
672
+ currentPeriodEnd: existingDoc.currentPeriodEnd,
673
+ itemId: existingDoc.itemId,
674
+ });
675
+ // → { status, cancelAtPeriodEnd, currentPeriodStart, currentPeriodEnd, itemId }
676
+
677
+ // Get the primary subscription item, preferring a known item ID.
678
+ const item = stripe.subscriptions.getPrimarySubscriptionItem(subscription, 'si_xxx');
679
+ // → Stripe.SubscriptionItem | null
680
+ ```
681
+
682
+ ---
683
+
684
+ ## Affiliate Payout Helpers
685
+
686
+ Two standalone functions are exported for calculating affiliate payouts after deducting Stripe processing fees. Both require a `processingFees` object (`{ flat: number, percent: number }`).
687
+
688
+ ```typescript
689
+ import {
690
+ calculateAffiliatePaymentPayoutAmount,
691
+ calculateAffiliateSubscriptionPayoutPercent,
692
+ } from '@apexara/stripe';
693
+
694
+ const fees = { flat: 30, percent: 0.029 }; // Standard Stripe rates
695
+
696
+ // One-time payment payout — returns flat amount in cents
697
+ // cost = 10000 ($100), affiliatePayoutPercent = 20
698
+ // stripeFee = round(10000 * 0.029 + 30) = 320
699
+ // payout = round((10000 - 320) * 0.20) = 1936 ($19.36)
700
+ const amount = calculateAffiliatePaymentPayoutAmount(10000, 20, fees);
701
+ // → 1936
702
+
703
+ // Subscription payout — returns percentage to pass to transfer_data.amount_percent
704
+ // subscriptionCost = 10000, payoutPercent = 0.20
705
+ // result = ((10000 - 320) * 0.20) / 10000 ≈ 0.19
706
+ const percent = calculateAffiliateSubscriptionPayoutPercent(10000, 0.20, fees);
707
+ // → 0.19
708
+ ```
709
+
710
+ ---
711
+
712
+ ## Webhooks
713
+
714
+ `StripeWebhookHandler` handles the main Stripe webhook and the connected account webhook. It performs signature verification, idempotency checks, and event dispatch.
715
+
716
+ ### Setup
717
+
718
+ ```typescript
719
+ import { StripeWebhookHandler, WebhookHooks, WebhookHandlerConfig } from '@apexara/stripe';
720
+
721
+ const config: WebhookHandlerConfig = {
722
+ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
723
+ connectedWebhookSecret: process.env.STRIPE_WEBHOOK_CONNECTED_SECRET, // Optional
724
+ };
725
+
726
+ const hooks: WebhookHooks = {
727
+ // Required: pluggable idempotency store
728
+ eventStore: {
729
+ tryInsert: async (eventId, type) => {
730
+ // Return true if this is a new event (insert succeeded).
731
+ // Return false if the event was already processed (duplicate).
732
+ // Use a unique index to make this atomic.
733
+ return db.stripeEvents.tryInsert({ eventId, type });
734
+ },
735
+ },
736
+
737
+ // Optional: implement only the events you care about
738
+
739
+ onCheckoutCompleted: async ({ session, metadata }) => {
740
+ // session is pre-expanded: payment_intent.latest_charge + invoice
741
+ await handleOrder(session, metadata);
742
+ },
743
+
744
+ onInvoicePaid: async ({ event, invoice }) => {
745
+ await grantCredits(invoice);
746
+ },
747
+
748
+ onInvoicePaymentFailed: async ({ event, invoice, failReason }) => {
749
+ // failReason is pre-extracted from the payment intent (decline_code or error code)
750
+ await notifyUser(invoice, failReason);
751
+ },
752
+
753
+ onSubscriptionDeleted: async ({ event, subscription }) => {
754
+ await deactivateSubscription(subscription.id);
755
+ },
756
+
757
+ onConnectedAccountUpdated: async ({ account }) => {
758
+ await syncAffiliateStatus(account);
759
+ },
760
+
761
+ // Optional: called when a non-critical internal error occurs (e.g. fail reason extraction)
762
+ onError: (context, error) => {
763
+ logger.error(`Webhook error in ${context}`, error);
764
+ },
765
+ };
766
+
767
+ const handler = new StripeWebhookHandler(
768
+ hooks,
769
+ stripeClient, // Raw Stripe instance — use ApexStripe.client or createStripeClient()
770
+ config,
771
+ checkoutService, // ApexStripe.checkout or a standalone CheckoutService
772
+ invoiceService, // ApexStripe.invoices or a standalone InvoiceService
773
+ );
774
+ ```
775
+
776
+ ### Express routes
777
+
778
+ The handler plugs directly into Express. **The raw body must be available on `req`** — register `express.raw()` before the webhook routes.
779
+
780
+ ```typescript
781
+ app.use('/stripe/webhook', express.raw({ type: 'application/json' }));
782
+ app.use('/stripe/webhook/connected', express.raw({ type: 'application/json' }));
783
+
784
+ // Express mode — pass next to delegate errors to the app's error middleware
785
+ app.post('/stripe/webhook', (req, res, next) => handler.handle(req, res, next));
786
+ app.post('/stripe/webhook/connected', (req, res, next) => handler.handleConnected(req, res, next));
787
+
788
+ // Standalone mode — omit next and the handler manages error responses itself
789
+ app.post('/stripe/webhook', (req, res) => handler.handle(req, res));
790
+ ```
791
+
792
+ ### Idempotency
793
+
794
+ Every incoming event is checked against the event store before being dispatched. If `tryInsert` returns `false`, the event is acknowledged with HTTP 200 and skipped — no hook is called. This prevents duplicate processing when Stripe retries delivery.
795
+
796
+ **The `tryInsert` implementation must be atomic.** Use a unique index (MongoDB, PostgreSQL) or a Redis `SET NX` to avoid race conditions when Stripe delivers the same event to multiple server instances simultaneously.
797
+
798
+ **MongoDB example:**
799
+
800
+ ```typescript
801
+ eventStore: {
802
+ tryInsert: async (eventId, type) => {
803
+ try {
804
+ await StripeEventModel.create({ eventId, type, processedAt: new Date() });
805
+ return true;
806
+ } catch (err: any) {
807
+ if (err.code === 11000) return false; // Duplicate key — already processed
808
+ throw err;
809
+ }
810
+ },
811
+ },
812
+ ```
813
+
814
+ ### Events dispatched
815
+
816
+ | Stripe event | Hook called | Notes |
817
+ |---|---|---|
818
+ | `checkout.session.completed` | `onCheckoutCompleted` | Session re-fetched and expanded with `payment_intent.latest_charge` and `invoice` before the hook is called |
819
+ | `invoice.paid` | `onInvoicePaid` | Raw invoice from event data |
820
+ | `invoice.payment_failed` | `onInvoicePaymentFailed` | Raw invoice + `failReason` pre-extracted from the payment intent (`decline_code` or `code`) |
821
+ | `customer.subscription.deleted` | `onSubscriptionDeleted` | Raw subscription from event data |
822
+ | `account.updated` (connected) | `onConnectedAccountUpdated` | Raw account from event data |
823
+ | All other event types | — | Silently ignored — HTTP 200 returned. Throwing for unknown events would cause Stripe to retry for up to 72 hours. |
824
+
825
+ ---
826
+
827
+ ## Advanced Usage
828
+
829
+ ### Using services independently
830
+
831
+ Every service can be instantiated on its own with an injected Stripe client. This is useful when you only need part of the package or when injecting the client from elsewhere.
832
+
833
+ ```typescript
834
+ import Stripe from 'stripe';
835
+ import { createStripeClient, SubscriptionService, InvoiceService } from '@apexara/stripe';
836
+
837
+ const client = createStripeClient({ secretKey: process.env.STRIPE_SECRET_KEY! });
838
+
839
+ // Services that need config
840
+ const subscriptions = new SubscriptionService(client, {
841
+ currency: 'usd',
842
+ invoiceDaysUntilDue: 7,
843
+ invoiceCollectionMethod: 'send_invoice',
844
+ invoicePaymentMethodTypes: ['card', 'link'],
845
+ // All other StripeServiceConfig fields are required when constructing directly —
846
+ // use ApexStripe to have defaults applied automatically.
847
+ });
848
+
849
+ // Services that only need the client
850
+ import { CustomerService, PaymentMethodService } from '@apexara/stripe';
851
+
852
+ const customers = new CustomerService(client);
853
+ const paymentMethods = new PaymentMethodService(client);
854
+ ```
855
+
856
+ ### Using the raw Stripe client
857
+
858
+ The raw Stripe instance is accessible via `ApexStripe.client`:
859
+
860
+ ```typescript
861
+ const apex = new ApexStripe({ secretKey: '...' });
862
+
863
+ // Full Stripe SDK — use for anything not covered by the services
864
+ const products = await apex.client.products.list({ limit: 10 });
865
+ ```
866
+
867
+ Or create it independently:
868
+
869
+ ```typescript
870
+ import { createStripeClient } from '@apexara/stripe';
871
+
872
+ const stripe = createStripeClient({
873
+ secretKey: process.env.STRIPE_SECRET_KEY!,
874
+ apiVersion: '2025-08-27.basil', // Optional
875
+ });
876
+ ```
877
+
878
+ ---
879
+
880
+ ## API Reference — Types
881
+
882
+ All types are exported from the package root.
883
+
884
+ ### Config
885
+
886
+ ```typescript
887
+ import {
888
+ StripeClientConfig,
889
+ StripeServiceConfig,
890
+ StripeProcessingFees,
891
+ WebhookHandlerConfig,
892
+ } from '@apexara/stripe';
893
+ ```
894
+
895
+ ### Checkout
896
+
897
+ ```typescript
898
+ import {
899
+ CreateCheckoutSessionParams,
900
+ CreatePaymentCheckoutSessionParams,
901
+ CreateSubscriptionCheckoutSessionParams,
902
+ AffiliatePaymentParams,
903
+ AffiliateSubscriptionParams,
904
+ } from '@apexara/stripe';
905
+ ```
906
+
907
+ ### Subscriptions
908
+
909
+ ```typescript
910
+ import {
911
+ ScheduleDowngradeOptions,
912
+ SwitchSubscriptionPlanOptions,
913
+ CreateInvoiceSubscriptionOptions,
914
+ CreateInvoiceSubscriptionResult,
915
+ SubscriptionSyncFields,
916
+ } from '@apexara/stripe';
917
+ ```
918
+
919
+ ### Invoices
920
+
921
+ ```typescript
922
+ import {
923
+ CreateInvoiceParams,
924
+ PendingActivationInvoice,
925
+ } from '@apexara/stripe';
926
+ ```
927
+
928
+ ### Payment links
929
+
930
+ ```typescript
931
+ import {
932
+ CreatePaymentLinkParams,
933
+ PaymentLinkResult,
934
+ } from '@apexara/stripe';
935
+ ```
936
+
937
+ ### Prices
938
+
939
+ ```typescript
940
+ import { CreateCustomPriceParams } from '@apexara/stripe';
941
+ ```
942
+
943
+ ### Webhooks
944
+
945
+ ```typescript
946
+ import {
947
+ WebhookHooks,
948
+ WebhookEventStore,
949
+ CheckoutCompletedPayload,
950
+ InvoicePaidPayload,
951
+ InvoicePaymentFailedPayload,
952
+ SubscriptionDeletedPayload,
953
+ ConnectedAccountUpdatedPayload,
954
+ } from '@apexara/stripe';
955
+ ```
956
+
957
+ ### Utilities
958
+
959
+ ```typescript
960
+ import { getBillingCycleLabel } from '@apexara/stripe';
961
+
962
+ getBillingCycleLabel('month', 1); // → 'Monthly'
963
+ getBillingCycleLabel('year', 1); // → 'Yearly'
964
+ getBillingCycleLabel('week', 1); // → 'Weekly'
965
+ getBillingCycleLabel('day', 1); // → 'Daily'
966
+ getBillingCycleLabel('month', 3); // → 'Quarterly'
967
+ getBillingCycleLabel('month', 6); // → 'Semi-Annually'
968
+ getBillingCycleLabel('month', 2); // → 'Every 2 months'
969
+ ```
970
+
971
+ ---
972
+
973
+ ## Development
974
+
975
+ ```bash
976
+ # Install dependencies
977
+ npm install
978
+
979
+ # Build
980
+ npm run build
981
+
982
+ # Build in watch mode
983
+ npm run build:watch
984
+
985
+ # Type check (no emit)
986
+ npm run type-check
987
+
988
+ # Run tests
989
+ npm test
990
+
991
+ # Run tests with coverage
992
+ npm run test:coverage
993
+ ```
994
+
995
+ **Test stack:** Vitest with v8 coverage. Tests live in `src/tests/` and are excluded from the build output.
996
+
997
+ **Stripe API version:** `2025-08-27.basil` — pinned in `src/client.ts`. To use a different version, pass `apiVersion` in `StripeClientConfig`.
998
+
999
+ ---
1000
+
1001
+ ## License
1002
+
1003
+ ISC