@apexara/stripe 1.0.5 → 1.1.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.
Files changed (57) hide show
  1. package/README.md +450 -28
  2. package/dist/apex-stripe.d.ts.map +1 -1
  3. package/dist/apex-stripe.js +10 -8
  4. package/dist/errors/http-error.d.ts +2 -1
  5. package/dist/errors/http-error.d.ts.map +1 -1
  6. package/dist/errors/http-error.js +3 -1
  7. package/dist/errors/stripe-error-status.d.ts +16 -0
  8. package/dist/errors/stripe-error-status.d.ts.map +1 -0
  9. package/dist/errors/stripe-error-status.js +60 -0
  10. package/dist/models/config.model.d.ts +2 -0
  11. package/dist/models/config.model.d.ts.map +1 -1
  12. package/dist/models/stripe.model.d.ts +12 -0
  13. package/dist/models/stripe.model.d.ts.map +1 -1
  14. package/dist/models/subscription.model.d.ts +1 -0
  15. package/dist/models/subscription.model.d.ts.map +1 -1
  16. package/dist/models/webhook.model.d.ts +16 -0
  17. package/dist/models/webhook.model.d.ts.map +1 -1
  18. package/dist/services/checkout/checkout.service.d.ts +8 -5
  19. package/dist/services/checkout/checkout.service.d.ts.map +1 -1
  20. package/dist/services/checkout/checkout.service.js +26 -13
  21. package/dist/services/connected-account/connected-account.service.d.ts +2 -1
  22. package/dist/services/connected-account/connected-account.service.d.ts.map +1 -1
  23. package/dist/services/connected-account/connected-account.service.js +4 -3
  24. package/dist/services/customer/customer.service.d.ts +2 -1
  25. package/dist/services/customer/customer.service.d.ts.map +1 -1
  26. package/dist/services/customer/customer.service.js +3 -2
  27. package/dist/services/invoice/invoice.service.d.ts +27 -3
  28. package/dist/services/invoice/invoice.service.d.ts.map +1 -1
  29. package/dist/services/invoice/invoice.service.js +108 -12
  30. package/dist/services/payment-link/payment-link.service.d.ts +2 -2
  31. package/dist/services/payment-link/payment-link.service.d.ts.map +1 -1
  32. package/dist/services/payment-link/payment-link.service.js +5 -4
  33. package/dist/services/payment-method/payment-method.service.d.ts +5 -4
  34. package/dist/services/payment-method/payment-method.service.d.ts.map +1 -1
  35. package/dist/services/payment-method/payment-method.service.js +35 -9
  36. package/dist/services/price/price.service.d.ts +2 -2
  37. package/dist/services/price/price.service.d.ts.map +1 -1
  38. package/dist/services/price/price.service.js +4 -3
  39. package/dist/services/subscription/subscription.service.d.ts +79 -12
  40. package/dist/services/subscription/subscription.service.d.ts.map +1 -1
  41. package/dist/services/subscription/subscription.service.js +337 -49
  42. package/dist/utils/idempotency.d.ts +29 -0
  43. package/dist/utils/idempotency.d.ts.map +1 -0
  44. package/dist/utils/idempotency.js +62 -0
  45. package/dist/webhooks/report-error.d.ts +7 -0
  46. package/dist/webhooks/report-error.d.ts.map +1 -0
  47. package/dist/webhooks/report-error.js +15 -0
  48. package/dist/webhooks/webhook.dispatcher.d.ts +15 -2
  49. package/dist/webhooks/webhook.dispatcher.d.ts.map +1 -1
  50. package/dist/webhooks/webhook.dispatcher.js +52 -9
  51. package/dist/webhooks/webhook.handler.d.ts +20 -1
  52. package/dist/webhooks/webhook.handler.d.ts.map +1 -1
  53. package/dist/webhooks/webhook.handler.js +94 -18
  54. package/package.json +5 -4
  55. package/dist/tests/helpers.d.ts +0 -5
  56. package/dist/tests/helpers.d.ts.map +0 -1
  57. package/dist/tests/helpers.js +0 -96
@@ -6,10 +6,17 @@ export declare class WebhookDispatcher {
6
6
  private readonly hooks;
7
7
  private readonly checkout;
8
8
  private readonly invoice;
9
- constructor(hooks: WebhookHooks, checkout: CheckoutService, invoice: InvoiceService);
9
+ private readonly voidUnpaidInvoicesOnEnd;
10
+ constructor(hooks: WebhookHooks, checkout: CheckoutService, invoice: InvoiceService, voidUnpaidInvoicesOnEnd?: boolean);
11
+ private readonly undoneVoidErrors;
12
+ /**
13
+ * True for an error this dispatcher threw from onSubscriptionDeleted while the void that follows it had failed too.
14
+ * The void still needs a run, so the handler gives that event back even when the hook's error is a refusal.
15
+ */
16
+ isVoidUndone(err: unknown): boolean;
10
17
  /**
11
18
  * Routes a main webhook event to the appropriate handler.
12
- * Unhandled event types are silently ignored.
19
+ * Every other event type goes to onOtherEvent, and is silently ignored without it.
13
20
  */
14
21
  dispatchMainEvent(event: Stripe.Event): Promise<void>;
15
22
  /**
@@ -19,6 +26,12 @@ export declare class WebhookDispatcher {
19
26
  private handleCheckoutCompleted;
20
27
  private handleInvoicePaid;
21
28
  private handleInvoicePaymentFailed;
29
+ /**
30
+ * Calls onSubscriptionDeleted, then voids the invoices the subscription left unpaid unless voidUnpaidInvoicesOnEnd
31
+ * is off. The void runs even when the hook throws, since Stripe has ended the subscription either way. The hook's
32
+ * error is thrown first; a refused void fails the event when the hook succeeded, and goes to onError when not, with
33
+ * the hook's error kept as a void left undone (isVoidUndone).
34
+ */
22
35
  private handleSubscriptionDeleted;
23
36
  private extractPaymentFailReason;
24
37
  }
@@ -1 +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"}
1
+ {"version":3,"file":"webhook.dispatcher.d.ts","sourceRoot":"","sources":["../../src/webhooks/webhook.dispatcher.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,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;IACxB,OAAO,CAAC,QAAQ,CAAC,uBAAuB;gBAHvB,KAAK,EAAE,YAAY,EACnB,QAAQ,EAAE,eAAe,EACzB,OAAO,EAAE,cAAc,EACvB,uBAAuB,GAAE,OAAc;IAG1D,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAyB;IAE1D;;;OAGG;IACI,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO;IAI1C;;;OAGG;IACU,iBAAiB,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IA4BlE;;OAEG;IACU,sBAAsB,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;YAgBzD,uBAAuB;YAmBvB,iBAAiB;YAYjB,0BAA0B;IAexC;;;;;OAKG;YACW,yBAAyB;YAyCzB,wBAAwB;CAmBvC"}
@@ -1,15 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WebhookDispatcher = void 0;
4
+ const report_error_1 = require("./report-error");
4
5
  class WebhookDispatcher {
5
- constructor(hooks, checkout, invoice) {
6
+ constructor(hooks, checkout, invoice, voidUnpaidInvoicesOnEnd = true) {
6
7
  this.hooks = hooks;
7
8
  this.checkout = checkout;
8
9
  this.invoice = invoice;
10
+ this.voidUnpaidInvoicesOnEnd = voidUnpaidInvoicesOnEnd;
11
+ // Hook errors thrown after the void of the ended subscription's unpaid invoices failed as well.
12
+ this.undoneVoidErrors = new WeakSet();
13
+ }
14
+ /**
15
+ * True for an error this dispatcher threw from onSubscriptionDeleted while the void that follows it had failed too.
16
+ * The void still needs a run, so the handler gives that event back even when the hook's error is a refusal.
17
+ */
18
+ isVoidUndone(err) {
19
+ return typeof err === 'object' && err !== null && this.undoneVoidErrors.has(err);
9
20
  }
10
21
  /**
11
22
  * Routes a main webhook event to the appropriate handler.
12
- * Unhandled event types are silently ignored.
23
+ * Every other event type goes to onOtherEvent, and is silently ignored without it.
13
24
  */
14
25
  async dispatchMainEvent(event) {
15
26
  switch (event.type) {
@@ -26,9 +37,10 @@ class WebhookDispatcher {
26
37
  await this.handleSubscriptionDeleted(event);
27
38
  break;
28
39
  default:
29
- // Unhandled event types are silently ignored — not an error.
40
+ // Without onOtherEvent the event is silently ignored — not an error.
30
41
  // Throwing here would cause Stripe to retry the event for up to 72 hours.
31
42
  // https://docs.stripe.com/webhooks#best-practices
43
+ await this.hooks.onOtherEvent?.(event);
32
44
  break;
33
45
  }
34
46
  }
@@ -78,13 +90,44 @@ class WebhookDispatcher {
78
90
  const payload = { event, invoice, failReason };
79
91
  await this.hooks.onInvoicePaymentFailed(payload);
80
92
  }
93
+ /**
94
+ * Calls onSubscriptionDeleted, then voids the invoices the subscription left unpaid unless voidUnpaidInvoicesOnEnd
95
+ * is off. The void runs even when the hook throws, since Stripe has ended the subscription either way. The hook's
96
+ * error is thrown first; a refused void fails the event when the hook succeeded, and goes to onError when not, with
97
+ * the hook's error kept as a void left undone (isVoidUndone).
98
+ */
81
99
  async handleSubscriptionDeleted(event) {
82
- if (!this.hooks.onSubscriptionDeleted) {
83
- return;
84
- }
85
100
  const subscription = event.data.object;
86
- const payload = { event, subscription };
87
- await this.hooks.onSubscriptionDeleted(payload);
101
+ let isHookFailed = false;
102
+ let hookError;
103
+ if (this.hooks.onSubscriptionDeleted) {
104
+ const payload = { event, subscription };
105
+ try {
106
+ await this.hooks.onSubscriptionDeleted(payload);
107
+ }
108
+ catch (err) {
109
+ isHookFailed = true;
110
+ hookError = err;
111
+ }
112
+ }
113
+ if (this.voidUnpaidInvoicesOnEnd) {
114
+ try {
115
+ await this.invoice.voidUnpaidInvoices(subscription);
116
+ }
117
+ catch (err) {
118
+ if (!isHookFailed) {
119
+ throw err;
120
+ }
121
+ // A thrown text or null carries no status, so the handler gives it back without this mark.
122
+ if (typeof hookError === 'object' && hookError !== null) {
123
+ this.undoneVoidErrors.add(hookError);
124
+ }
125
+ void (0, report_error_1.reportError)(this.hooks, 'voidUnpaidInvoices', err);
126
+ }
127
+ }
128
+ if (isHookFailed) {
129
+ throw hookError;
130
+ }
88
131
  }
89
132
  // Utility
90
133
  async extractPaymentFailReason(invoiceId) {
@@ -97,7 +140,7 @@ class WebhookDispatcher {
97
140
  return intent.last_payment_error?.decline_code ?? intent.last_payment_error?.code ?? null;
98
141
  }
99
142
  catch (err) {
100
- this.hooks.onError?.('extractPaymentFailReason', err);
143
+ void (0, report_error_1.reportError)(this.hooks, 'extractPaymentFailReason', err);
101
144
  return null;
102
145
  }
103
146
  }
@@ -19,20 +19,39 @@ export declare class StripeWebhookHandler {
19
19
  private readonly checkoutService;
20
20
  private readonly invoiceService;
21
21
  constructor(hooks: WebhookHooks, stripe: Stripe, config: WebhookHandlerConfig, checkoutService: CheckoutService, invoiceService: InvoiceService);
22
+ private static readonly laterTryStatuses;
22
23
  private readonly dispatcher;
23
24
  /**
24
25
  * Express request handler for the main Stripe webhook endpoint.
25
26
  * Requires the raw request body on req (use express.raw() middleware before this route).
26
27
  * Pass next to delegate errors to Express error middleware; omit it for standalone HTTP error responses.
28
+ * Refuses every event with a 500 while webhookSecret is blank.
27
29
  */
28
30
  handle: (req: WebhookRequest, res: WebhookResponse, next?: (err: unknown) => void) => Promise<void>;
29
31
  /**
30
32
  * Express request handler for the Stripe connected account webhook endpoint.
31
33
  * Requires the raw request body on req (use express.raw() middleware before this route).
32
- * Throws if connectedWebhookSecret is not configured.
34
+ * Refuses every event with a 500 while connectedWebhookSecret is blank.
33
35
  */
34
36
  handleConnected: (req: WebhookRequest, res: WebhookResponse, next?: (err: unknown) => void) => Promise<void>;
37
+ /**
38
+ * A blank secret is refused before the signature check, since an event signed with an empty key passes it.
39
+ * The handler is built when the app starts, so this answers per event (Stripe retries a 500) instead of
40
+ * stopping the whole app.
41
+ */
42
+ private constructEvent;
35
43
  private processWebhook;
44
+ private signatureOf;
45
+ /**
46
+ * Runs the hooks for an event tryInsert let through. When that throws, the store's release gives the event back
47
+ * before the error goes on, so Stripe's retry runs it again; finished work is marked done with markDone. With
48
+ * markRefusalsDone, a refusal is marked done instead, then given to onRefused without waiting. A store without
49
+ * either is not called.
50
+ */
51
+ private runClaimed;
52
+ private isRefusalMarkedDone;
53
+ private callStore;
54
+ private callOnRefused;
36
55
  private isVerificationError;
37
56
  }
38
57
  export {};
@@ -1 +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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 +5,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.StripeWebhookHandler = void 0;
7
7
  const stripe_1 = __importDefault(require("stripe"));
8
+ const report_error_1 = require("./report-error");
8
9
  const webhook_dispatcher_1 = require("./webhook.dispatcher");
10
+ const http_error_1 = require("./../errors/http-error");
11
+ const stripe_error_status_1 = require("./../errors/stripe-error-status");
9
12
  class StripeWebhookHandler {
10
13
  constructor(hooks, stripe, config, checkoutService, invoiceService) {
11
14
  this.hooks = hooks;
@@ -17,28 +20,35 @@ class StripeWebhookHandler {
17
20
  * Express request handler for the main Stripe webhook endpoint.
18
21
  * Requires the raw request body on req (use express.raw() middleware before this route).
19
22
  * Pass next to delegate errors to Express error middleware; omit it for standalone HTTP error responses.
23
+ * Refuses every event with a 500 while webhookSecret is blank.
20
24
  */
21
25
  this.handle = async (req, res, next) => {
22
- await this.processWebhook(req, res, next, (payload, sig) => this.stripe.webhooks.constructEvent(payload, sig, this.config.webhookSecret), (event) => this.dispatcher.dispatchMainEvent(event));
26
+ await this.processWebhook('handle', req, res, next, (payload, sig) => this.constructEvent(payload, sig, this.config.webhookSecret, 'webhookSecret'), (event) => this.dispatcher.dispatchMainEvent(event));
23
27
  };
24
28
  /**
25
29
  * Express request handler for the Stripe connected account webhook endpoint.
26
30
  * Requires the raw request body on req (use express.raw() middleware before this route).
27
- * Throws if connectedWebhookSecret is not configured.
31
+ * Refuses every event with a 500 while connectedWebhookSecret is blank.
28
32
  */
29
33
  this.handleConnected = async (req, res, next) => {
30
- await this.processWebhook(req, res, next, (payload, sig) => {
31
- if (!this.config.connectedWebhookSecret) {
32
- throw new Error('connectedWebhookSecret is not configured');
33
- }
34
- return this.stripe.webhooks.constructEvent(payload, sig, this.config.connectedWebhookSecret);
35
- }, (event) => this.dispatcher.dispatchConnectedEvent(event));
34
+ await this.processWebhook('handleConnected', req, res, next, (payload, sig) => this.constructEvent(payload, sig, this.config.connectedWebhookSecret, 'connectedWebhookSecret'), (event) => this.dispatcher.dispatchConnectedEvent(event));
36
35
  };
37
- this.dispatcher = new webhook_dispatcher_1.WebhookDispatcher(hooks, checkoutService, invoiceService);
36
+ this.dispatcher = new webhook_dispatcher_1.WebhookDispatcher(hooks, checkoutService, invoiceService, config.voidUnpaidInvoicesOnEnd ?? true);
38
37
  }
39
- async processWebhook(req, res, next, constructEvent, dispatch) {
38
+ /**
39
+ * A blank secret is refused before the signature check, since an event signed with an empty key passes it.
40
+ * The handler is built when the app starts, so this answers per event (Stripe retries a 500) instead of
41
+ * stopping the whole app.
42
+ */
43
+ constructEvent(payload, signature, secret, secretName) {
44
+ if (!secret?.trim()) {
45
+ throw new http_error_1.HttpError(500, `${secretName} is not configured`);
46
+ }
47
+ return this.stripe.webhooks.constructEvent(payload, signature, secret);
48
+ }
49
+ async processWebhook(context, req, res, next, constructEvent, dispatch) {
40
50
  const payload = req.rawBody ?? req.body;
41
- const signature = req.headers['stripe-signature'];
51
+ const signature = this.signatureOf(req);
42
52
  try {
43
53
  const event = constructEvent(payload, signature);
44
54
  // Idempotency check — skip if already processed (atomic insert)
@@ -47,20 +57,84 @@ class StripeWebhookHandler {
47
57
  res.status(200).json();
48
58
  return;
49
59
  }
50
- await dispatch(event);
60
+ await this.runClaimed(event, dispatch);
51
61
  res.status(200).json();
52
62
  }
53
63
  catch (err) {
54
64
  if (next) {
55
- // Express mode — delegate to the app's error middleware
56
- next(err);
65
+ // Express mode — delegate to the app's error middleware. withHttpStatus marks a bad signature as the sender's
66
+ // fault, with a client status and no alert. Every other error goes as it is.
67
+ next(this.isVerificationError(err) ? (0, stripe_error_status_1.withHttpStatus)(err) : err);
68
+ }
69
+ else if (this.isVerificationError(err)) {
70
+ // Standalone mode — a bad signature gets the status withHttpStatus gives it, so both modes answer it alike,
71
+ // and Stripe's reason, which names the part of the request that failed
72
+ const { status } = (0, stripe_error_status_1.withHttpStatus)(err);
73
+ res.status(status).json({ error: err.message });
57
74
  }
58
75
  else {
59
- // Standalone mode — handle the error and respond ourselves
60
- const status = this.isVerificationError(err) ? 400 : 500;
61
- const message = err instanceof Error ? err.message : 'Webhook processing error';
62
- res.status(status).json({ error: message });
76
+ // Standalone mode — the answer never carries the error's text. It goes out before onError runs, so a slow
77
+ // or failing onError cannot hold it back.
78
+ res.status(500).json({ error: 'Webhook processing error' });
79
+ await (0, report_error_1.reportError)(this.hooks, context, err);
80
+ }
81
+ }
82
+ }
83
+ // Node joins repeated headers into one text, so a list or bytes come only from a caller that builds the headers
84
+ // itself. Stripe's check refuses them as a missing header, the same bad signature as a forged one.
85
+ signatureOf(req) {
86
+ const header = req.headers['stripe-signature'];
87
+ return typeof header === 'string' ? header : '';
88
+ }
89
+ /**
90
+ * Runs the hooks for an event tryInsert let through. When that throws, the store's release gives the event back
91
+ * before the error goes on, so Stripe's retry runs it again; finished work is marked done with markDone. With
92
+ * markRefusalsDone, a refusal is marked done instead, then given to onRefused without waiting. A store without
93
+ * either is not called.
94
+ */
95
+ async runClaimed(event, dispatch) {
96
+ try {
97
+ await dispatch(event);
98
+ }
99
+ catch (err) {
100
+ const isRefusal = this.isRefusalMarkedDone(err);
101
+ await this.callStore(isRefusal ? 'markDone' : 'release', event.id);
102
+ if (isRefusal) {
103
+ void this.callOnRefused(event, err);
63
104
  }
105
+ throw err;
106
+ }
107
+ await this.callStore('markDone', event.id);
108
+ }
109
+ // A 4xx status, as HttpError and an app's own refusals carry, would fail the same way on Stripe's retry; 408, 429
110
+ // and an error marked shouldTryLater ask for a later try. A Stripe error's statusCode is not read, for the same
111
+ // reason. A refusal thrown after an ended subscription's void failed is given back, so the retry voids its unpaid
112
+ // invoices again.
113
+ isRefusalMarkedDone(err) {
114
+ if (this.config.markRefusalsDone !== true || this.dispatcher.isVoidUndone(err)) {
115
+ return false;
116
+ }
117
+ const { status, shouldTryLater } = (err ?? {});
118
+ const isLaterTry = shouldTryLater === true || StripeWebhookHandler.laterTryStatuses.includes(status);
119
+ return typeof status === 'number' && status >= 400 && status < 500 && !isLaterTry;
120
+ }
121
+ // A store call that fails goes to onError, so it never replaces the hook's error or the 200 for finished work. The
122
+ // answer does not wait for onError.
123
+ async callStore(method, eventId) {
124
+ try {
125
+ await this.hooks.eventStore[method]?.(eventId);
126
+ }
127
+ catch (err) {
128
+ void (0, report_error_1.reportError)(this.hooks, method, err);
129
+ }
130
+ }
131
+ // An onRefused that fails goes to onError, so it never replaces the hook's error or the store call already made.
132
+ async callOnRefused(event, refusal) {
133
+ try {
134
+ await this.hooks.onRefused?.(event, refusal);
135
+ }
136
+ catch (err) {
137
+ void (0, report_error_1.reportError)(this.hooks, 'onRefused', err);
64
138
  }
65
139
  }
66
140
  isVerificationError(err) {
@@ -68,3 +142,5 @@ class StripeWebhookHandler {
68
142
  }
69
143
  }
70
144
  exports.StripeWebhookHandler = StripeWebhookHandler;
145
+ // Request Timeout and Too Many Requests: client statuses that ask for the same request again later.
146
+ StripeWebhookHandler.laterTryStatuses = [408, 429];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apexara/stripe",
3
- "version": "1.0.5",
3
+ "version": "1.1.0",
4
4
  "description": "Stripe service layer and webhook dispatcher",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -21,7 +21,8 @@
21
21
  "test:coverage": "vitest run --coverage"
22
22
  },
23
23
  "files": [
24
- "dist"
24
+ "dist",
25
+ "!dist/tests"
25
26
  ],
26
27
  "keywords": [
27
28
  "stripe",
@@ -52,8 +53,8 @@
52
53
  "devDependencies": {
53
54
  "@types/express": "^5.0.0",
54
55
  "@types/node": "^22.0.0",
55
- "@vitest/coverage-v8": "^3.2.4",
56
+ "@vitest/coverage-v8": "^4.1.12",
56
57
  "typescript": "^5.0.0",
57
- "vitest": "^3.2.4"
58
+ "vitest": "^4.1.12"
58
59
  }
59
60
  }
@@ -1,5 +0,0 @@
1
- import Stripe from 'stripe';
2
- import { StripeServiceConfig } from './../models/config.model';
3
- export declare const MOCK_SERVICE_CONFIG: Required<StripeServiceConfig>;
4
- export declare function createMockStripe(): Stripe;
5
- //# sourceMappingURL=helpers.d.ts.map
@@ -1 +0,0 @@
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"}
@@ -1,96 +0,0 @@
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
- }