@apexara/stripe 1.0.5 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +465 -28
- package/dist/apex-stripe.d.ts.map +1 -1
- package/dist/apex-stripe.js +10 -8
- package/dist/errors/http-error.d.ts +5 -1
- package/dist/errors/http-error.d.ts.map +1 -1
- package/dist/errors/http-error.js +6 -1
- package/dist/errors/stripe-error-status.d.ts +16 -0
- package/dist/errors/stripe-error-status.d.ts.map +1 -0
- package/dist/errors/stripe-error-status.js +60 -0
- package/dist/models/config.model.d.ts +2 -0
- package/dist/models/config.model.d.ts.map +1 -1
- package/dist/models/stripe.model.d.ts +16 -0
- package/dist/models/stripe.model.d.ts.map +1 -1
- package/dist/models/subscription.model.d.ts +1 -0
- package/dist/models/subscription.model.d.ts.map +1 -1
- package/dist/models/webhook.model.d.ts +16 -0
- package/dist/models/webhook.model.d.ts.map +1 -1
- package/dist/services/checkout/checkout.service.d.ts +8 -5
- package/dist/services/checkout/checkout.service.d.ts.map +1 -1
- package/dist/services/checkout/checkout.service.js +26 -13
- package/dist/services/connected-account/connected-account.service.d.ts +2 -1
- package/dist/services/connected-account/connected-account.service.d.ts.map +1 -1
- package/dist/services/connected-account/connected-account.service.js +4 -3
- package/dist/services/customer/customer.service.d.ts +2 -1
- package/dist/services/customer/customer.service.d.ts.map +1 -1
- package/dist/services/customer/customer.service.js +3 -2
- package/dist/services/invoice/invoice.service.d.ts +27 -3
- package/dist/services/invoice/invoice.service.d.ts.map +1 -1
- package/dist/services/invoice/invoice.service.js +108 -12
- package/dist/services/payment-link/payment-link.service.d.ts +2 -2
- package/dist/services/payment-link/payment-link.service.d.ts.map +1 -1
- package/dist/services/payment-link/payment-link.service.js +5 -4
- package/dist/services/payment-method/payment-method.service.d.ts +5 -4
- package/dist/services/payment-method/payment-method.service.d.ts.map +1 -1
- package/dist/services/payment-method/payment-method.service.js +35 -9
- package/dist/services/price/price.service.d.ts +2 -2
- package/dist/services/price/price.service.d.ts.map +1 -1
- package/dist/services/price/price.service.js +4 -3
- package/dist/services/subscription/subscription.service.d.ts +79 -12
- package/dist/services/subscription/subscription.service.d.ts.map +1 -1
- package/dist/services/subscription/subscription.service.js +337 -49
- package/dist/utils/idempotency.d.ts +29 -0
- package/dist/utils/idempotency.d.ts.map +1 -0
- package/dist/utils/idempotency.js +62 -0
- package/dist/webhooks/report-error.d.ts +7 -0
- package/dist/webhooks/report-error.d.ts.map +1 -0
- package/dist/webhooks/report-error.js +15 -0
- package/dist/webhooks/webhook.dispatcher.d.ts +15 -2
- package/dist/webhooks/webhook.dispatcher.d.ts.map +1 -1
- package/dist/webhooks/webhook.dispatcher.js +52 -9
- package/dist/webhooks/webhook.handler.d.ts +20 -1
- package/dist/webhooks/webhook.handler.d.ts.map +1 -1
- package/dist/webhooks/webhook.handler.js +94 -18
- package/package.json +5 -4
- package/dist/tests/helpers.d.ts +0 -5
- package/dist/tests/helpers.d.ts.map +0 -1
- package/dist/tests/helpers.js +0 -96
package/README.md
CHANGED
|
@@ -4,10 +4,14 @@ A typed Stripe service layer for Node.js. Wraps the official Stripe SDK into foc
|
|
|
4
4
|
|
|
5
5
|
## Contents
|
|
6
6
|
|
|
7
|
+
- [Changes since 1.1.0](#changes-since-110)
|
|
8
|
+
- [Changes since 1.0.5](#changes-since-105)
|
|
7
9
|
- [Installation](#installation)
|
|
8
10
|
- [Quick Start](#quick-start)
|
|
9
11
|
- [Configuration](#configuration)
|
|
10
12
|
- [Services](#services)
|
|
13
|
+
- [Repeated writes](#repeated-writes)
|
|
14
|
+
- [Errors](#errors)
|
|
11
15
|
- [CheckoutService](#checkoutservice)
|
|
12
16
|
- [CustomerService](#customerservice)
|
|
13
17
|
- [InvoiceService](#invoiceservice)
|
|
@@ -23,6 +27,102 @@ A typed Stripe service layer for Node.js. Wraps the official Stripe SDK into foc
|
|
|
23
27
|
|
|
24
28
|
---
|
|
25
29
|
|
|
30
|
+
## Changes since 1.1.0
|
|
31
|
+
|
|
32
|
+
These changes ship as 1.2.0. Nothing an existing call does changes.
|
|
33
|
+
|
|
34
|
+
### New
|
|
35
|
+
|
|
36
|
+
- **`HttpError` carries `code` and `declineCode`.** A refusal that came from Stripe keeps Stripe's error code and the
|
|
37
|
+
bank's decline code, so an app can word or log it its own way: `payPastDueInvoice`'s declined card carries
|
|
38
|
+
`code: 'card_declined'` and the bank's `declineCode` (such as `insufficient_funds`), and its bank-check refusal
|
|
39
|
+
`code: 'invoice_payment_intent_requires_action'`. Both are `null` on the library's own refusals. `HttpError` takes them
|
|
40
|
+
as an optional fourth argument, `{ code, declineCode }` (`HttpErrorReason`).
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Changes since 1.0.5
|
|
45
|
+
|
|
46
|
+
These changes ship as 1.1.0, and some change what an existing call does (see "Behaves differently"). An app on a `^1`
|
|
47
|
+
version range takes them on its next fresh install. An app pinned to an exact version sees none of this until it moves
|
|
48
|
+
to 1.1.0.
|
|
49
|
+
|
|
50
|
+
### Behaves differently
|
|
51
|
+
|
|
52
|
+
- **An ended subscription's unpaid bills are voided.** When Stripe ends a subscription, the webhook handler voids its
|
|
53
|
+
open and uncollectible invoices after `onSubscriptionDeleted` runs, so a plan that has ended is never charged. On by
|
|
54
|
+
default; `voidUnpaidInvoicesOnEnd: false` turns it off. A `WebhookDispatcher` built on its own does the same, and
|
|
55
|
+
takes the setting as its fourth constructor argument. See [Ended subscriptions](#ended-subscriptions).
|
|
56
|
+
- **A blank webhook signing secret refuses every event** with a 500 before the signature check, at the main and the
|
|
57
|
+
connected endpoints. Stripe's own check accepts an event signed with an empty key. Stripe retries the refused events
|
|
58
|
+
once the secret is set.
|
|
59
|
+
- **A declined card carries 402** with the bank's reason and asks for no alert email. Every other Stripe error passes
|
|
60
|
+
through as before. See [Errors](#errors).
|
|
61
|
+
- **A declined plan switch fails.** `switchSubscriptionPlan` throws 402 with the decline reason and voids the switch's
|
|
62
|
+
open bill, where it answered as a success and left the bill open. A booked downgrade stays in place after a decline
|
|
63
|
+
or a refusal.
|
|
64
|
+
- **A booked plan change is released when it is in the way.** Cancel and resume release it first, so they no longer
|
|
65
|
+
fail on such a plan. A switch releases it only once the switch has gone through.
|
|
66
|
+
- **A booked downgrade keeps what the member has now.** The current period keeps its discounts, a running free trial,
|
|
67
|
+
its card and its payout and billing settings, and the new price keeps the same discounts until each one ends.
|
|
68
|
+
- **Removing a card checks its owner.** `removePaymentMethod` answers 404 for a card that belongs to another customer
|
|
69
|
+
or to none, and for an id Stripe does not know.
|
|
70
|
+
- **Webhook errors answer plainly.** In standalone mode a hook or store error answers 500 with the message
|
|
71
|
+
`Webhook processing error`, and the error goes to `onError`. A `stripe-signature` header that is missing, a list or
|
|
72
|
+
not text is refused as a bad signature. In Express mode a failed signature check reaches `next` with status 400 and
|
|
73
|
+
no alert.
|
|
74
|
+
- **`createInvoiceBasedSubscription` finalizes the first bill before it sends it,** and its answer carries the bill's
|
|
75
|
+
payment link.
|
|
76
|
+
- **`SubscriptionSyncFields` gains `cancelAt` and `isEnding`, both required.** An app that builds that type itself, such
|
|
77
|
+
as a test fixture, adds the two fields.
|
|
78
|
+
|
|
79
|
+
### New
|
|
80
|
+
|
|
81
|
+
- **Idempotency keys.** Twelve writes take a last, optional `{ idempotencyKey }`, sent to Stripe with each write's step
|
|
82
|
+
name added. See [Repeated writes](#repeated-writes).
|
|
83
|
+
- **`invoices.findConfirmPaymentUrl(subscription)`** gives the page where the customer confirms a renewal their bank
|
|
84
|
+
holds for its security check.
|
|
85
|
+
- **`invoices.payPastDueInvoice(subscription, idempotency?)`** charges the open bill of a past due plan at once, for
|
|
86
|
+
right after the customer sets a new default card.
|
|
87
|
+
- **`invoices.voidUnpaidInvoices(subscription)`** is public, so an app can retry the void from a nightly job.
|
|
88
|
+
- **The event store takes optional `release` and `markDone`,** so an event that failed is given back and Stripe's
|
|
89
|
+
retry runs it again. See [Retrying an event that failed](#retrying-an-event-that-failed).
|
|
90
|
+
- **`markRefusalsDone`** in the webhook config, off by default, marks an event done when its hook refuses it with a
|
|
91
|
+
4xx status, except one that asks for a later try. See [Marking a refusal done](#marking-a-refusal-done).
|
|
92
|
+
- **`HttpError` takes a third argument, `shouldTryLater`,** for a 4xx that asks for a later try, as the library's 409
|
|
93
|
+
for an idempotency key still in use does. `markRefusalsDone` gives such an event back.
|
|
94
|
+
- **`onOtherEvent` and `onRefused`** in the webhook hooks, both optional. `onOtherEvent(event)` runs an event the
|
|
95
|
+
package has no hook for inside the same claim as its own, so an app hands every Stripe event to the handler.
|
|
96
|
+
`onRefused(event, error)` is called when a refusal is marked done, so the app can tell its team. See
|
|
97
|
+
[Events dispatched](#events-dispatched) and [Marking a refusal done](#marking-a-refusal-done).
|
|
98
|
+
- **`scheduleDowngrade` takes an optional `discounts`** for the new price. Left out, the current discounts carry on;
|
|
99
|
+
`[]` sets none. See [Downgrades (scheduled)](#downgrades-scheduled).
|
|
100
|
+
- **`WebhookDispatcher.isVoidUndone(err)`** is public: true for an error thrown from `onSubscriptionDeleted` while the
|
|
101
|
+
void after it failed too, which the handler gives back even under `markRefusalsDone`.
|
|
102
|
+
- **Discounts.** `getSubscriptionWithDiscounts`, `getSubscriptionDiscount`, `getCostWithDiscount` and the
|
|
103
|
+
`SubscriptionDiscount` type. See [Discounts](#discounts).
|
|
104
|
+
- **`buildSubscriptionSyncFields` returns `cancelAt` and `isEnding`,** so a plan given an end date in the Stripe
|
|
105
|
+
dashboard shows as ending.
|
|
106
|
+
|
|
107
|
+
### Fixed
|
|
108
|
+
|
|
109
|
+
- Cancel and resume work on a trial.
|
|
110
|
+
- Removing the default card makes another card on file the default first.
|
|
111
|
+
- Lists read every page, up to 1000 items.
|
|
112
|
+
- Hosted checkout works: `createCheckoutSession` returns the address of Stripe's page in place of an empty
|
|
113
|
+
`client_secret`, and sends its return address as `success_url`. An automatically charged invoice is finalized with
|
|
114
|
+
automatic collection on.
|
|
115
|
+
- `expireCheckoutSession` returns quietly when the checkout is already expired or complete.
|
|
116
|
+
- A throw or a rejection from `onError` is dropped: it never changes a webhook's answer or stops the process.
|
|
117
|
+
|
|
118
|
+
### Release and tooling
|
|
119
|
+
|
|
120
|
+
- The release pipeline runs the type check and the tests before the build, and a failure stops the publish.
|
|
121
|
+
- `qs` moves to 6.17.1 and `npm audit` reports nothing. The Stripe range stays `^18.5.0`.
|
|
122
|
+
- The tests run on Vitest 4. Nothing an app installs changes, and the package leaves its tests out.
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
26
126
|
## Installation
|
|
27
127
|
|
|
28
128
|
```bash
|
|
@@ -142,6 +242,75 @@ All services are available as properties on the `ApexStripe` instance. They can
|
|
|
142
242
|
|
|
143
243
|
---
|
|
144
244
|
|
|
245
|
+
### Repeated writes
|
|
246
|
+
|
|
247
|
+
A second press or a retry after a slow answer calls a write again, and Stripe makes a new object for each call: a
|
|
248
|
+
second plan, bill, credit, customer or charge. The SDK's own network retries already reuse one key, so only a repeat by
|
|
249
|
+
the app is open. The writes below take a last, optional `{ idempotencyKey }` (`IdempotencyOptions`). With a key,
|
|
250
|
+
Stripe answers a repeat within 24 hours with the first call's result instead of running it again. Without one a call
|
|
251
|
+
works as before.
|
|
252
|
+
|
|
253
|
+
| Method | Stripe writes, by step name |
|
|
254
|
+
|---|---|
|
|
255
|
+
| `checkout.createCheckoutSession(params, idempotency?)` | `checkout` |
|
|
256
|
+
| `checkout.createSetupIntentSession(customerId, idempotency?)` | `setup-intent` |
|
|
257
|
+
| `customers.createCustomer(firstName, lastName, email, idempotency?)` | `customer` |
|
|
258
|
+
| `invoices.createInvoice(params, idempotency?)` | `invoice`, `invoice-line`, then `invoice-send` or `invoice-finalize` |
|
|
259
|
+
| `invoices.payPastDueInvoice(subscription, idempotency?)` | `invoice-pay` |
|
|
260
|
+
| `paymentLinks.createPaymentLink(params, idempotency?)` | `payment-link-price`, `payment-link` |
|
|
261
|
+
| `prices.createCustomSubscriptionPrice(params, idempotency?)` | `price` |
|
|
262
|
+
| `connectedAccounts.createConnectedAccount(metadata?, idempotency?)` | `connected-account` |
|
|
263
|
+
| `subscriptions.applyPlanCredit(customerId, subscriptionId, amount, currency, description?, metadata?, idempotency?)` | `plan-credit` |
|
|
264
|
+
| `subscriptions.switchSubscriptionPlan(subscriptionId, itemId, newPriceId, options?, idempotency?)` | `plan-switch` |
|
|
265
|
+
| `subscriptions.createInvoiceBasedSubscription(customerId, priceId, options?, idempotency?)` | `invoice-subscription`, `invoice-subscription-finalize`, `invoice-subscription-send` |
|
|
266
|
+
| `subscriptions.updateSubscription(subscriptionId, params, idempotency?)` | `subscription-update` |
|
|
267
|
+
|
|
268
|
+
Each Stripe write gets the key with its step name added (`<key>:invoice-line`). A repeated write of several steps so
|
|
269
|
+
makes one bill with one line, emailed once, and one key can cover every library call of one user action.
|
|
270
|
+
|
|
271
|
+
- Make one key per user action, such as a form's submit, and send it again only for a repeat of that action. A UUID
|
|
272
|
+
the browser makes when the form opens, sent as an `Idempotency-Key` header, does this.
|
|
273
|
+
- Call each method once per key: a second call of the same method with the same key gets the first one's result.
|
|
274
|
+
- A repeat gets the first answer, a Stripe error included: a declined card stays declined for that key, also after the
|
|
275
|
+
card is changed. A new attempt needs a new key.
|
|
276
|
+
- A key has at most 200 characters, all visible ASCII (letters, digits and symbols, no spaces), so a UUID fits. Any
|
|
277
|
+
other key is refused with `HttpError` 400 before Stripe is called.
|
|
278
|
+
- The same key with other details is refused with `HttpError` 422, and a repeat while the first call still runs with
|
|
279
|
+
`HttpError` 409, to try again a moment later (`shouldTryLater` is true). Neither asks for an alert email
|
|
280
|
+
(`shouldSendEmail` is false).
|
|
281
|
+
|
|
282
|
+
```typescript
|
|
283
|
+
const idempotency = { idempotencyKey: req.header('Idempotency-Key') }; // the form's key, made when the form opens
|
|
284
|
+
|
|
285
|
+
const customer = await stripe.customers.createCustomer('Jane', 'Doe', 'jane@example.com', idempotency);
|
|
286
|
+
const { invoiceUrl } = await stripe.subscriptions.createInvoiceBasedSubscription(customer.id, 'price_xxx', { metadata }, idempotency);
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Writes that are safe to repeat as they are take no key: the fixed updates (a card, the cancel flag), cancels, voids,
|
|
290
|
+
deletes, attaches, detaches and archives. Neither do a downgrade's schedule, which Stripe allows once per subscription,
|
|
291
|
+
and the short lived account and login links. `updateSubscription` passes its params on as they are, so a change that
|
|
292
|
+
can bill (a new price, `billing_cycle_anchor: 'now'`) should carry a key.
|
|
293
|
+
|
|
294
|
+
---
|
|
295
|
+
|
|
296
|
+
### Errors
|
|
297
|
+
|
|
298
|
+
A declined card thrown through a service of `ApexStripe` (Stripe's `StripeCardError`) carries `status` 402 and asks for
|
|
299
|
+
no alert email (`shouldSendEmail` is false), as the library's own `HttpError` refusals do. Its `message` is the bank's
|
|
300
|
+
reason, written by Stripe for the customer ("Your card has insufficient funds."), so an app can show it. The error
|
|
301
|
+
stays Stripe's, with its class, `type` and `code`.
|
|
302
|
+
|
|
303
|
+
Every other Stripe error passes through as Stripe threw it, with no `status`: a missing object, a bad request, a wrong
|
|
304
|
+
or restricted key, too many requests, a failure at Stripe or no connection. An app's error middleware answers it 500
|
|
305
|
+
(`err.status || 500`) and sends its alert, and Stripe's own words never reach a member. Two methods answer a missing
|
|
306
|
+
object themselves: `removePaymentMethod` throws `HttpError` 404 for a card Stripe does not know, and
|
|
307
|
+
`expireCheckoutSession` returns quietly for a checkout Stripe does not know.
|
|
308
|
+
|
|
309
|
+
Services made on their own (see [Advanced Usage](#advanced-usage)) and calls through `client` throw Stripe's errors as
|
|
310
|
+
they are.
|
|
311
|
+
|
|
312
|
+
---
|
|
313
|
+
|
|
145
314
|
### CheckoutService
|
|
146
315
|
|
|
147
316
|
`stripe.checkout`
|
|
@@ -150,9 +319,11 @@ Handles Stripe Checkout sessions, Setup Intents, and affiliate payout calculatio
|
|
|
150
319
|
|
|
151
320
|
---
|
|
152
321
|
|
|
153
|
-
#### `createCheckoutSession(params)`
|
|
322
|
+
#### `createCheckoutSession(params, idempotency?)`
|
|
154
323
|
|
|
155
|
-
Creates a payment or subscription checkout session. Returns the `client_secret` for use with Stripe.js
|
|
324
|
+
Creates a payment or subscription checkout session. Returns the `client_secret` for use with Stripe.js or, when
|
|
325
|
+
`checkoutUiMode` is `'hosted'`, the address of Stripe's page to send the customer to. On Stripe's page `returnUrl` is
|
|
326
|
+
where Stripe sends the customer once they have paid (`success_url`).
|
|
156
327
|
|
|
157
328
|
**Payment mode:**
|
|
158
329
|
|
|
@@ -193,7 +364,7 @@ const clientSecret = await stripe.checkout.createCheckoutSession({
|
|
|
193
364
|
|
|
194
365
|
---
|
|
195
366
|
|
|
196
|
-
#### `createSetupIntentSession(customerId)`
|
|
367
|
+
#### `createSetupIntentSession(customerId, idempotency?)`
|
|
197
368
|
|
|
198
369
|
Creates a Setup Intent for saving a payment method without charging. Returns the `client_secret`.
|
|
199
370
|
|
|
@@ -205,7 +376,7 @@ const clientSecret = await stripe.checkout.createSetupIntentSession('cus_xxx');
|
|
|
205
376
|
|
|
206
377
|
#### `expireCheckoutSession(sessionId)`
|
|
207
378
|
|
|
208
|
-
Expires an open checkout session.
|
|
379
|
+
Expires an open checkout session. Returns quietly when Stripe has no such session or the session is no longer open (already expired, or complete because it was paid), so it is safe to call unconditionally. Any other error, a 500 or 429 included, also counts as done when the session then reads back expired or complete; the call throws it when the session reads back open or cannot be read.
|
|
209
380
|
|
|
210
381
|
```typescript
|
|
211
382
|
await stripe.checkout.expireCheckoutSession('cs_xxx');
|
|
@@ -241,7 +412,7 @@ const intent = await stripe.checkout.getPaymentIntent('pi_xxx');
|
|
|
241
412
|
|
|
242
413
|
---
|
|
243
414
|
|
|
244
|
-
#### `createCustomer(firstName, lastName, email)`
|
|
415
|
+
#### `createCustomer(firstName, lastName, email, idempotency?)`
|
|
245
416
|
|
|
246
417
|
Creates a Stripe customer. The full name is stored as `${firstName} ${lastName}`.
|
|
247
418
|
|
|
@@ -268,12 +439,14 @@ await stripe.customers.updateCustomerDefaultPaymentMethod('cus_xxx', 'pm_xxx');
|
|
|
268
439
|
|
|
269
440
|
---
|
|
270
441
|
|
|
271
|
-
#### `createInvoice(params)`
|
|
442
|
+
#### `createInvoice(params, idempotency?)`
|
|
272
443
|
|
|
273
444
|
Creates an invoice with a single line item and either sends it or finalizes it, depending on `invoiceCollectionMethod`.
|
|
274
445
|
|
|
275
446
|
- `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
|
|
447
|
+
- `charge_automatically` — creates, adds line item, finalizes with automatic collection on — Stripe charges the
|
|
448
|
+
customer's default payment method about an hour later. The invoice has no due date, so `invoiceDaysUntilDue` is not
|
|
449
|
+
used.
|
|
277
450
|
|
|
278
451
|
```typescript
|
|
279
452
|
const invoice = await stripe.invoices.createInvoice({
|
|
@@ -300,7 +473,7 @@ const payments = await stripe.invoices.listInvoicePayments('in_xxx');
|
|
|
300
473
|
|
|
301
474
|
#### `findPendingActivationInvoice(customerId)`
|
|
302
475
|
|
|
303
|
-
Checks whether a customer
|
|
476
|
+
Checks whether any of a customer's open invoices is from a `subscription_create` event whose subscription is still active or incomplete. Returns the invoice data or `null`.
|
|
304
477
|
|
|
305
478
|
Use this to prompt the user to pay their pending subscription invoice after an admin-created invoice-based subscription.
|
|
306
479
|
|
|
@@ -320,13 +493,74 @@ Returns `null` when:
|
|
|
320
493
|
|
|
321
494
|
---
|
|
322
495
|
|
|
496
|
+
#### `payPastDueInvoice(subscription, idempotency?)`
|
|
497
|
+
|
|
498
|
+
Charges a `past_due` subscription's latest invoice now, with the card the subscription charges. Stripe's retries keep
|
|
499
|
+
their own schedule after the customer saves a new card, so call this right after setting the new default card, the way
|
|
500
|
+
app stores charge at once on a card update. Returns the invoice once it is paid, also when a retry paid it meanwhile
|
|
501
|
+
and the subscription reads `active` again. Returns `null` for a subscription in any other status, one with no invoice,
|
|
502
|
+
a draft or void invoice, and an `active` subscription's open invoice, which are never charged here. A declined card throws `HttpError` 402 with the card's reason, Stripe's `code` and the bank's `declineCode`, and a payment that waits for the
|
|
503
|
+
customer's bank check (3D Secure) throws 402 "Your bank needs you to confirm this payment." with `code` `invoice_payment_intent_requires_action`. After a decline Stripe
|
|
504
|
+
keeps retrying as before; a payment that waits for the bank check waits for the customer to confirm it
|
|
505
|
+
(`findConfirmPaymentUrl`). Any other refusal from Stripe is thrown as it is.
|
|
506
|
+
|
|
507
|
+
```typescript
|
|
508
|
+
await stripe.paymentMethods.setDefaultPaymentMethod(subscriptionId, paymentMethodId);
|
|
509
|
+
const subscription = await stripe.subscriptions.getSubscriptionById(subscriptionId);
|
|
510
|
+
try {
|
|
511
|
+
const paid = await stripe.invoices.payPastDueInvoice(subscription);
|
|
512
|
+
// → the paid invoice, or null when there was nothing to pay
|
|
513
|
+
} catch (err) {
|
|
514
|
+
// err.status === 402: err.message is the reason to show the customer; err.code and err.declineCode say why
|
|
515
|
+
}
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
---
|
|
519
|
+
|
|
520
|
+
#### `voidUnpaidInvoices(subscription)`
|
|
521
|
+
|
|
522
|
+
Voids the `open` and `uncollectible` invoices of a `canceled` subscription, so nobody can pay for a plan that has
|
|
523
|
+
ended. Stripe keeps those invoices payable after a cancel, and an uncollectible invoice still takes a payment; only a
|
|
524
|
+
void one is refused. A subscription in any other status is left alone, because voiding a live subscription's latest
|
|
525
|
+
invoice changes its status. An invoice paid or voided in the meantime is left as it is, so calling it again changes
|
|
526
|
+
nothing. Any other refusal from Stripe is thrown. Returns how many invoices it voided.
|
|
527
|
+
|
|
528
|
+
The webhook handler calls this for every `customer.subscription.deleted` (see [Webhooks](#webhooks)). Call it
|
|
529
|
+
yourself to retry later, for example from a nightly job over the subscriptions that ended in the last few days.
|
|
530
|
+
|
|
531
|
+
```typescript
|
|
532
|
+
const subscription = await stripe.subscriptions.getSubscriptionById('sub_xxx');
|
|
533
|
+
const voided = await stripe.invoices.voidUnpaidInvoices(subscription);
|
|
534
|
+
// → 1
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
---
|
|
538
|
+
|
|
539
|
+
#### `findConfirmPaymentUrl(subscription)`
|
|
540
|
+
|
|
541
|
+
Returns Stripe's hosted page for a `past_due` subscription's latest invoice when its payment waits for the customer's
|
|
542
|
+
bank check (3D Secure, a PaymentIntent in `requires_action`). Stripe never retries such a payment on its own, so the
|
|
543
|
+
customer has to confirm it on that page. Returns `null` for a declined card or any other failure, an invoice that is
|
|
544
|
+
no longer `open`, and a subscription in any other status. Reads the latest invoice once; a refusal from Stripe is
|
|
545
|
+
thrown.
|
|
546
|
+
|
|
547
|
+
Show the link on the billing page next to the plan, so a renewal held by the bank is one click from being paid.
|
|
548
|
+
|
|
549
|
+
```typescript
|
|
550
|
+
const subscription = await stripe.subscriptions.getSubscriptionById('sub_xxx');
|
|
551
|
+
const confirmUrl = await stripe.invoices.findConfirmPaymentUrl(subscription);
|
|
552
|
+
// → 'https://invoice.stripe.com/i/...' or null
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
---
|
|
556
|
+
|
|
323
557
|
### PaymentLinkService
|
|
324
558
|
|
|
325
559
|
`stripe.paymentLinks`
|
|
326
560
|
|
|
327
561
|
---
|
|
328
562
|
|
|
329
|
-
#### `createPaymentLink(params)`
|
|
563
|
+
#### `createPaymentLink(params, idempotency?)`
|
|
330
564
|
|
|
331
565
|
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
566
|
|
|
@@ -376,7 +610,7 @@ const pm = await stripe.paymentMethods.getPaymentMethod('pm_xxx');
|
|
|
376
610
|
|
|
377
611
|
#### `listPaymentMethods(customerId)`
|
|
378
612
|
|
|
379
|
-
Returns the customer's saved payment methods as a flat array.
|
|
613
|
+
Returns all the customer's saved payment methods as a flat array, reading every page Stripe returns.
|
|
380
614
|
|
|
381
615
|
```typescript
|
|
382
616
|
const methods = await stripe.paymentMethods.listPaymentMethods('cus_xxx');
|
|
@@ -421,7 +655,10 @@ const { changed } = await stripe.paymentMethods.setDefaultPaymentMethodIfMissing
|
|
|
421
655
|
|
|
422
656
|
#### `removePaymentMethod(customerId, subscriptionId, paymentMethodId)`
|
|
423
657
|
|
|
424
|
-
Removes a payment method safely. If it is the subscription's default
|
|
658
|
+
Removes a payment method safely. If it is the subscription's default or the customer's default, another card on file
|
|
659
|
+
takes its place first, so a plan is not left without a card to charge. Throws if it is the only payment method on the
|
|
660
|
+
customer, and `HttpError` 404 when the card is not this customer's, also for an id Stripe does not know.
|
|
661
|
+
`newDefaultId` is the subscription's new default, or `null` when the subscription's default did not change.
|
|
425
662
|
|
|
426
663
|
```typescript
|
|
427
664
|
const { newDefaultId } = await stripe.paymentMethods.removePaymentMethod(
|
|
@@ -439,7 +676,7 @@ const { newDefaultId } = await stripe.paymentMethods.removePaymentMethod(
|
|
|
439
676
|
|
|
440
677
|
---
|
|
441
678
|
|
|
442
|
-
#### `createCustomSubscriptionPrice(params)`
|
|
679
|
+
#### `createCustomSubscriptionPrice(params, idempotency?)`
|
|
443
680
|
|
|
444
681
|
Creates a recurring price on an existing Stripe product.
|
|
445
682
|
|
|
@@ -477,7 +714,7 @@ Handles Stripe Connect for marketplace and affiliate payout scenarios.
|
|
|
477
714
|
|
|
478
715
|
---
|
|
479
716
|
|
|
480
|
-
#### `createConnectedAccount(metadata?)`
|
|
717
|
+
#### `createConnectedAccount(metadata?, idempotency?)`
|
|
481
718
|
|
|
482
719
|
Creates a new connected account (type from config, defaults to `'express'`). Returns the account ID.
|
|
483
720
|
|
|
@@ -541,7 +778,7 @@ The most comprehensive service. Covers the full subscription lifecycle including
|
|
|
541
778
|
// Get a subscription (expands items.data.price)
|
|
542
779
|
const sub = await stripe.subscriptions.getSubscriptionById('sub_xxx');
|
|
543
780
|
|
|
544
|
-
// Get all subscriptions for a customer (status: 'all', expands default_payment_method)
|
|
781
|
+
// Get all subscriptions for a customer, every page (status: 'all', expands default_payment_method)
|
|
545
782
|
const subs = await stripe.subscriptions.getAllUserSubscriptions('cus_xxx');
|
|
546
783
|
// → Stripe.Subscription[] (empty array if customerId is falsy)
|
|
547
784
|
|
|
@@ -559,15 +796,21 @@ const cancelled = await stripe.subscriptions.cancelSubscription('sub_xxx');
|
|
|
559
796
|
#### Lifecycle — cancel at period end / resume
|
|
560
797
|
|
|
561
798
|
```typescript
|
|
562
|
-
// Schedule cancellation at end of billing period.
|
|
563
|
-
// Throws if status is not 'active' or '
|
|
799
|
+
// Schedule cancellation at end of billing period (for a free trial, the trial's end).
|
|
800
|
+
// Throws if status is not 'active', 'past_due' or 'trialing'.
|
|
564
801
|
const sub = await stripe.subscriptions.cancelSubscriptionAtPeriodEnd('sub_xxx');
|
|
565
802
|
|
|
566
803
|
// Undo a scheduled cancellation.
|
|
567
|
-
// Throws if
|
|
804
|
+
// Throws if the plan is not set to end (cancel_at_period_end, or a schedule that ends it) or status is not resumable.
|
|
568
805
|
const sub = await stripe.subscriptions.resumeSubscription('sub_xxx');
|
|
569
806
|
```
|
|
570
807
|
|
|
808
|
+
Stripe refuses to change a plan's cancellation while a schedule is attached to it, such as a booked downgrade. Both
|
|
809
|
+
methods therefore release an attached schedule first: the plan stays on its current price and the schedule's later
|
|
810
|
+
phases are dropped. A plan that an attached schedule ends shows `cancel_at` with `cancel_at_period_end` false;
|
|
811
|
+
`resumeSubscription` resumes it too. A schedule another call has just released is passed over. Neither method
|
|
812
|
+
releases anything when it refuses the call.
|
|
813
|
+
|
|
571
814
|
---
|
|
572
815
|
|
|
573
816
|
#### Plan switching and credits
|
|
@@ -599,11 +842,22 @@ const updated = await stripe.subscriptions.switchSubscriptionPlan(
|
|
|
599
842
|
);
|
|
600
843
|
```
|
|
601
844
|
|
|
845
|
+
An attached schedule, such as a booked downgrade, is released once the switch has gone through; left attached, its next
|
|
846
|
+
phase would move the plan back when the current one ends. A declined charge or a switch Stripe refuses leaves it
|
|
847
|
+
attached, so the member keeps what they booked. A repeat with the key releases only the schedule the first call found,
|
|
848
|
+
so a downgrade booked since then stays. The answer names no schedule even then, so read the subscription again before
|
|
849
|
+
acting on its schedule. If the release fails, the call throws although the plan has switched and been charged; a repeat
|
|
850
|
+
with the key releases it without switching again, while a repeat without a key switches and charges again. A key the
|
|
851
|
+
library refuses stops the call before anything changes.
|
|
852
|
+
|
|
602
853
|
---
|
|
603
854
|
|
|
604
855
|
#### Downgrades (scheduled)
|
|
605
856
|
|
|
606
857
|
Downgrades are scheduled to take effect at the end of the current billing period using Stripe Subscription Schedules.
|
|
858
|
+
The current period keeps everything it already has: its discounts, a running free trial, its own card and affiliate
|
|
859
|
+
payout. The new price keeps the same discounts (each runs on to its own end date, so one that ends before the change
|
|
860
|
+
is not carried), unless `discounts` says otherwise. A failed call releases a schedule it made itself.
|
|
607
861
|
|
|
608
862
|
```typescript
|
|
609
863
|
// Schedule a downgrade to a lower price at period end.
|
|
@@ -615,6 +869,7 @@ const schedule = await stripe.subscriptions.scheduleDowngrade(
|
|
|
615
869
|
transferData: { destination: 'acct_xxx', amount_percent: 19 }, // Optional
|
|
616
870
|
phaseMetadata: { affiliateId: 'aff_xxx' }, // Optional
|
|
617
871
|
scheduleMetadata: { initiatedBy: 'user' }, // Optional
|
|
872
|
+
discounts: [], // Optional: none on the new price
|
|
618
873
|
},
|
|
619
874
|
);
|
|
620
875
|
|
|
@@ -640,7 +895,7 @@ const schedule = await stripe.subscriptions.getOrCreateSubscriptionSchedule(subs
|
|
|
640
895
|
|
|
641
896
|
#### Invoice-based subscriptions (admin-created)
|
|
642
897
|
|
|
643
|
-
Creates a subscription using `send_invoice` collection and
|
|
898
|
+
Creates a subscription using `send_invoice` collection, finalizes its first invoice and emails it to the customer at once, and answers with the invoice's payment link. Use this for admin-created subscriptions where the customer pays via an emailed link rather than through a checkout session.
|
|
644
899
|
|
|
645
900
|
```typescript
|
|
646
901
|
const { subscription, invoiceId, invoiceUrl } =
|
|
@@ -672,7 +927,9 @@ const fields = stripe.subscriptions.buildSubscriptionSyncFields(subscription, {
|
|
|
672
927
|
currentPeriodEnd: existingDoc.currentPeriodEnd,
|
|
673
928
|
itemId: existingDoc.itemId,
|
|
674
929
|
});
|
|
675
|
-
// → { status, cancelAtPeriodEnd, currentPeriodStart, currentPeriodEnd, itemId }
|
|
930
|
+
// → { status, cancelAtPeriodEnd, cancelAt, isEnding, currentPeriodStart, currentPeriodEnd, itemId }
|
|
931
|
+
// cancelAt is the day Stripe ends the plan: the period's end, or a date picked in the dashboard, which can fall
|
|
932
|
+
// after the period's end. isEnding is true when it is set to end either way; cancelAtPeriodEnd stays Stripe's flag.
|
|
676
933
|
|
|
677
934
|
// Get the primary subscription item, preferring a known item ID.
|
|
678
935
|
const item = stripe.subscriptions.getPrimarySubscriptionItem(subscription, 'si_xxx');
|
|
@@ -681,6 +938,39 @@ const item = stripe.subscriptions.getPrimarySubscriptionItem(subscription, 'si_x
|
|
|
681
938
|
|
|
682
939
|
---
|
|
683
940
|
|
|
941
|
+
#### Discounts
|
|
942
|
+
|
|
943
|
+
These read the discount a customer's subscription carries, such as a promotion code they entered at checkout, and
|
|
944
|
+
work out what a charge comes to once it is taken off, for example to show the next charge on a billing page.
|
|
945
|
+
|
|
946
|
+
```typescript
|
|
947
|
+
// Get the subscription with its discounts and the promotion codes behind them expanded.
|
|
948
|
+
// Other fields to expand go in the second argument; each is added once.
|
|
949
|
+
const subscription = await stripe.subscriptions.getSubscriptionWithDiscounts('sub_xxx', ['latest_invoice']);
|
|
950
|
+
|
|
951
|
+
// Read its discount.
|
|
952
|
+
const discount = stripe.subscriptions.getSubscriptionDiscount(subscription);
|
|
953
|
+
// → { code: 'FOUNDERS25', name: 'Founders', percentOff: 25, amountOff: null, endsAt: null }, or null without one
|
|
954
|
+
|
|
955
|
+
// What a $49.00 charge on nextChargeAt comes to with it off, in cents. nextChargeAt is the next charge's date,
|
|
956
|
+
// e.g. currentPeriodEnd from buildSubscriptionSyncFields (the trial's end during a trial).
|
|
957
|
+
const next = stripe.subscriptions.getCostWithDiscount(4900, discount, nextChargeAt);
|
|
958
|
+
// → 3675
|
|
959
|
+
```
|
|
960
|
+
|
|
961
|
+
- `getSubscriptionDiscount` reads the first discount Stripe expanded. `code` is the promotion code the customer
|
|
962
|
+
entered, `null` without one; `amountOff` is in cents; `endsAt` is `null` for a discount that lasts as long as the
|
|
963
|
+
subscription, and also for a once coupon, which Stripe takes off one bill and then removes: it gives the price of
|
|
964
|
+
the next charge, not of the ones after it. Pass a subscription from `getSubscriptionWithDiscounts`: from
|
|
965
|
+
`getSubscriptionById` the discounts are ids, so it returns `null`.
|
|
966
|
+
- `getCostWithDiscount` takes off the percent rounded to the cent (12.5% of $49.00 is $6.125, so $6.13 comes off
|
|
967
|
+
and $42.87 is charged), or the amount off, never going below 0. A discount that ends on or before `nextChargeAt`
|
|
968
|
+
takes nothing off; a `nextChargeAt` of `null` keeps it.
|
|
969
|
+
- For a subscription with one price and one discount and no tax, the result is the total of Stripe's own preview of
|
|
970
|
+
that bill.
|
|
971
|
+
|
|
972
|
+
---
|
|
973
|
+
|
|
684
974
|
## Affiliate Payout Helpers
|
|
685
975
|
|
|
686
976
|
Two standalone functions are exported for calculating affiliate payouts after deducting Stripe processing fees. Both require a `processingFees` object (`{ flat: number, percent: number }`).
|
|
@@ -700,11 +990,11 @@ const fees = { flat: 30, percent: 0.029 }; // Standard Stripe rates
|
|
|
700
990
|
const amount = calculateAffiliatePaymentPayoutAmount(10000, 20, fees);
|
|
701
991
|
// → 1936
|
|
702
992
|
|
|
703
|
-
// Subscription payout — returns
|
|
704
|
-
// subscriptionCost = 10000, payoutPercent =
|
|
705
|
-
// result = ((10000 - 320) *
|
|
706
|
-
const percent = calculateAffiliateSubscriptionPayoutPercent(10000,
|
|
707
|
-
// →
|
|
993
|
+
// Subscription payout — returns the percent to pass to transfer_data.amount_percent (20 for 20%)
|
|
994
|
+
// subscriptionCost = 10000, payoutPercent = 20
|
|
995
|
+
// result = ((10000 - 320) * 20) / 10000 = 19.36
|
|
996
|
+
const percent = calculateAffiliateSubscriptionPayoutPercent(10000, 20, fees);
|
|
997
|
+
// → 19.36
|
|
708
998
|
```
|
|
709
999
|
|
|
710
1000
|
---
|
|
@@ -713,6 +1003,10 @@ const percent = calculateAffiliateSubscriptionPayoutPercent(10000, 0.20, fees);
|
|
|
713
1003
|
|
|
714
1004
|
`StripeWebhookHandler` handles the main Stripe webhook and the connected account webhook. It performs signature verification, idempotency checks, and event dispatch.
|
|
715
1005
|
|
|
1006
|
+
While a secret is blank or missing, its endpoint refuses every event with a 500 (passed to `next` in Express mode),
|
|
1007
|
+
since an event signed with an empty key would pass the signature check. Stripe retries those events, so they run once
|
|
1008
|
+
the secret is set.
|
|
1009
|
+
|
|
716
1010
|
### Setup
|
|
717
1011
|
|
|
718
1012
|
```typescript
|
|
@@ -721,6 +1015,8 @@ import { StripeWebhookHandler, WebhookHooks, WebhookHandlerConfig } from '@apexa
|
|
|
721
1015
|
const config: WebhookHandlerConfig = {
|
|
722
1016
|
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
|
|
723
1017
|
connectedWebhookSecret: process.env.STRIPE_WEBHOOK_CONNECTED_SECRET, // Optional
|
|
1018
|
+
voidUnpaidInvoicesOnEnd: true, // Optional, defaults to true: see "Ended subscriptions" below
|
|
1019
|
+
markRefusalsDone: false, // Optional, defaults to false: see "Marking a refusal done" below
|
|
724
1020
|
};
|
|
725
1021
|
|
|
726
1022
|
const hooks: WebhookHooks = {
|
|
@@ -732,6 +1028,8 @@ const hooks: WebhookHooks = {
|
|
|
732
1028
|
// Use a unique index to make this atomic.
|
|
733
1029
|
return db.stripeEvents.tryInsert({ eventId, type });
|
|
734
1030
|
},
|
|
1031
|
+
// Optional: release, so Stripe's retry runs a failed event again, and markDone
|
|
1032
|
+
// (see "Retrying an event that failed")
|
|
735
1033
|
},
|
|
736
1034
|
|
|
737
1035
|
// Optional: implement only the events you care about
|
|
@@ -758,7 +1056,22 @@ const hooks: WebhookHooks = {
|
|
|
758
1056
|
await syncAffiliateStatus(account);
|
|
759
1057
|
},
|
|
760
1058
|
|
|
761
|
-
// Optional:
|
|
1059
|
+
// Optional: every other event on the main endpoint, run in the same claim as the hooks above, so the event store
|
|
1060
|
+
// treats it as it treats them (see "Events dispatched")
|
|
1061
|
+
onOtherEvent: async (event) => {
|
|
1062
|
+
if (event.type === 'charge.refunded') {
|
|
1063
|
+
await recordRefund(event.data.object);
|
|
1064
|
+
}
|
|
1065
|
+
},
|
|
1066
|
+
|
|
1067
|
+
// Optional: called when markRefusalsDone marks a refused event done (see "Marking a refusal done")
|
|
1068
|
+
onRefused: (event, error) => {
|
|
1069
|
+
alertTeam(`Stripe event ${event.id} (${event.type}) was refused`, error);
|
|
1070
|
+
},
|
|
1071
|
+
|
|
1072
|
+
// Optional: gets the errors the package does not pass on, such as a failed fail reason extraction, and in
|
|
1073
|
+
// standalone mode the error behind each 500 (see "Express routes"). A throw or a rejection from it is dropped,
|
|
1074
|
+
// and no answer waits for it.
|
|
762
1075
|
onError: (context, error) => {
|
|
763
1076
|
logger.error(`Webhook error in ${context}`, error);
|
|
764
1077
|
},
|
|
@@ -789,6 +1102,34 @@ app.post('/stripe/webhook/connected', (req, res, next) => handler.handleConnecte
|
|
|
789
1102
|
app.post('/stripe/webhook', (req, res) => handler.handle(req, res));
|
|
790
1103
|
```
|
|
791
1104
|
|
|
1105
|
+
In standalone mode the handler answers errors itself:
|
|
1106
|
+
|
|
1107
|
+
- A bad signature gets a 400 with Stripe's reason. That covers a forged request and a `stripe-signature` header that
|
|
1108
|
+
is missing, a list or not text.
|
|
1109
|
+
- Anything else gets a 500 with `{ "error": "Webhook processing error" }`, so no internal error text leaves the app.
|
|
1110
|
+
The error itself goes to `onError('handle' | 'handleConnected', error)` once the answer is sent; without `onError`
|
|
1111
|
+
it is not seen anywhere. A throw or a rejection from `onError` there is dropped, since the answer has already gone.
|
|
1112
|
+
|
|
1113
|
+
In Express mode both go to `next`. A bad signature goes as Stripe's `StripeSignatureVerificationError` with `status`
|
|
1114
|
+
400 and `shouldSendEmail` false, as the library's own `HttpError` refusals carry, so an error middleware that answers
|
|
1115
|
+
`err.status || 500` answers it 400 without an alert. Anything else goes to `next` as it is.
|
|
1116
|
+
|
|
1117
|
+
#### Noticing a wrong signing secret
|
|
1118
|
+
|
|
1119
|
+
A bad signature raises no alert in either mode, since anyone can send one. But a wrong signing secret on the endpoint
|
|
1120
|
+
(another endpoint's, or another Stripe account's) refuses every event Stripe sends it the same way, so no event runs
|
|
1121
|
+
until it is fixed. To notice it, an app checks the signature itself before it calls the handler:
|
|
1122
|
+
|
|
1123
|
+
- Check with `stripeClient.webhooks.constructEvent`, on the same raw body and secret the handler uses. When it throws,
|
|
1124
|
+
answer 400 and do not call the handler.
|
|
1125
|
+
- Email the team when a refused request carries a `stripe-signature` header. Stripe sends one with every event, so
|
|
1126
|
+
such a request most likely comes from Stripe, signed with a secret the app does not hold.
|
|
1127
|
+
- A forger can send the header too, so cap these emails at a few an hour, under an alert source of their own so they
|
|
1128
|
+
cannot use up the alerts the rest of the app needs.
|
|
1129
|
+
|
|
1130
|
+
In live mode Stripe retries a refused event for up to three days, so the events refused meanwhile still run once the
|
|
1131
|
+
secret is fixed.
|
|
1132
|
+
|
|
792
1133
|
### Idempotency
|
|
793
1134
|
|
|
794
1135
|
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.
|
|
@@ -811,6 +1152,76 @@ eventStore: {
|
|
|
811
1152
|
},
|
|
812
1153
|
```
|
|
813
1154
|
|
|
1155
|
+
#### Retrying an event that failed
|
|
1156
|
+
|
|
1157
|
+
`tryInsert` records an event before its hooks run. With `tryInsert` alone the package never gives the event back, so
|
|
1158
|
+
when a hook throws, Stripe's retry finds it recorded and gets a 200. Two optional store methods change that:
|
|
1159
|
+
|
|
1160
|
+
- `release(eventId)` is called when handling the event throws (a hook, or the package's own Stripe call around it),
|
|
1161
|
+
before the error goes on (to `next`, or the 500). Give the event back there, for example by deleting its record,
|
|
1162
|
+
and Stripe's retry runs it again. Add it only once every hook is safe to run again after failing part way, since the
|
|
1163
|
+
retry runs the whole hook again. `onSubscriptionDeleted` must also be safe to run again after it finished: when
|
|
1164
|
+
Stripe refuses the void that follows it, the event is given back too (see "Ended subscriptions"). With
|
|
1165
|
+
`markRefusalsDone`, a refusal is marked done instead (see "Marking a refusal done").
|
|
1166
|
+
- `markDone(eventId)` is called once the hooks have finished, before the 200. It suits a store that claims an event
|
|
1167
|
+
before it runs and records it as done after.
|
|
1168
|
+
- A `release` or `markDone` that fails goes to `onError('release' | 'markDone', error)`: the hook's error still goes on,
|
|
1169
|
+
and finished work is still answered 200.
|
|
1170
|
+
- Neither is called for a repeat, when `tryInsert` throws, or for an event refused before `tryInsert` (a blank
|
|
1171
|
+
webhook secret or a failed signature check).
|
|
1172
|
+
|
|
1173
|
+
```typescript
|
|
1174
|
+
eventStore: {
|
|
1175
|
+
tryInsert: async (eventId, type) => { /* as above */ },
|
|
1176
|
+
release: async (eventId) => {
|
|
1177
|
+
await StripeEventModel.deleteOne({ eventId }); // Stripe's retry inserts it again
|
|
1178
|
+
},
|
|
1179
|
+
},
|
|
1180
|
+
```
|
|
1181
|
+
|
|
1182
|
+
The store above loses an event when a second delivery of it arrives while the first is still running: `tryInsert`
|
|
1183
|
+
finds the record, so the second delivery gets a 200 and Stripe takes the event as delivered. When the first run then
|
|
1184
|
+
fails and gives the event back, no retry comes. A store that claims an event first and marks it done after closes that
|
|
1185
|
+
gap:
|
|
1186
|
+
|
|
1187
|
+
- `tryInsert` claims a new event as being handled. It returns `false` only for an event marked done, and throws for
|
|
1188
|
+
one still being handled, so that delivery is answered with an error and Stripe sends it again later. The package
|
|
1189
|
+
calls neither `release` nor `markDone` for it, so the first run keeps its claim.
|
|
1190
|
+
- `markDone` marks the claim done, and `release` deletes it.
|
|
1191
|
+
- A run cut off part way (a restart, a crash) leaves its claim behind, so `tryInsert` also takes over a claim older
|
|
1192
|
+
than a time limit far longer than any hook runs.
|
|
1193
|
+
- `release` and `markDone` get the event id only, so they act on the event's claim as it is now: a run that outlasts
|
|
1194
|
+
the time limit and then ends would release or mark done the claim of the delivery that took it over. The long time
|
|
1195
|
+
limit keeps that out of reach.
|
|
1196
|
+
|
|
1197
|
+
#### Marking a refusal done
|
|
1198
|
+
|
|
1199
|
+
This setting stops Stripe sending an event again and again when your hook refuses it on purpose, for example an
|
|
1200
|
+
event about a customer your app has deleted, which would otherwise come back for up to three days.
|
|
1201
|
+
|
|
1202
|
+
With `release`, Stripe's retry runs every failed event again, also one that fails the same way every time, such as a
|
|
1203
|
+
hook that refuses an event with a 4xx status (an `HttpError`, or the app's own error with `status` 404). Set
|
|
1204
|
+
`markRefusalsDone: true` in `WebhookHandlerConfig` and such an event is marked done with `markDone` instead:
|
|
1205
|
+
|
|
1206
|
+
- An error whose `status` is a number from 400 to 499 is a refusal, except 408, 429 and any error with
|
|
1207
|
+
`shouldTryLater: true` (`new HttpError(409, message, true)` makes one, as the library's 409 for an idempotency key
|
|
1208
|
+
still in use does), which ask for a later try. Every other error gives the event back as before: a 5xx, a later try,
|
|
1209
|
+
an error with no `status`, and a Stripe error that has only a `statusCode`, since its 429 or 409 passes on Stripe's
|
|
1210
|
+
retry.
|
|
1211
|
+
- A refusal from `onSubscriptionDeleted` while the void after it failed too gives the event back, so Stripe's retry
|
|
1212
|
+
voids the unpaid invoices again (see "Ended subscriptions"). That mark sits on the error object, so a hook throws a
|
|
1213
|
+
new error for each event rather than one shared object.
|
|
1214
|
+
- The answer does not change: the error still goes to `next`, or the 500, and a failed `markDone` goes to
|
|
1215
|
+
`onError('markDone', error)`.
|
|
1216
|
+
- `onRefused(event, error)`, when given, is called once for each refusal marked done, with the hook's error, after
|
|
1217
|
+
`markDone` and also when `markDone` failed. It is not called for finished work, for an error that gives the event
|
|
1218
|
+
back (a 5xx, a later try, no `status`, the ended subscription whose void failed), with the setting off, for a
|
|
1219
|
+
repeat, when `tryInsert` throws, or for a bad signature. No answer waits for it, and a throw or a rejection from it
|
|
1220
|
+
goes to `onError('onRefused', error)` and changes neither the answer nor the store call. A failed `markDone` lets
|
|
1221
|
+
the claim expire, so Stripe's retry can run the event again and call `onRefused` once more.
|
|
1222
|
+
- It is off by default. A store without `markDone` is not called, so the event stays as `tryInsert` recorded it;
|
|
1223
|
+
`onRefused` is still called.
|
|
1224
|
+
|
|
814
1225
|
### Events dispatched
|
|
815
1226
|
|
|
816
1227
|
| Stripe event | Hook called | Notes |
|
|
@@ -818,9 +1229,28 @@ eventStore: {
|
|
|
818
1229
|
| `checkout.session.completed` | `onCheckoutCompleted` | Session re-fetched and expanded with `payment_intent.latest_charge` and `invoice` before the hook is called |
|
|
819
1230
|
| `invoice.paid` | `onInvoicePaid` | Raw invoice from event data |
|
|
820
1231
|
| `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 |
|
|
1232
|
+
| `customer.subscription.deleted` | `onSubscriptionDeleted` | Raw subscription from event data; then the subscription's unpaid invoices are voided (see below) |
|
|
822
1233
|
| `account.updated` (connected) | `onConnectedAccountUpdated` | Raw account from event data |
|
|
823
|
-
| All other event types |
|
|
1234
|
+
| All other event types | `onOtherEvent` | Raw event, run in the same claim as the hooks above, so `release`, `markDone` and `markRefusalsDone` apply to it as to them. Without `onOtherEvent`, silently ignored — HTTP 200 returned. |
|
|
1235
|
+
|
|
1236
|
+
`onOtherEvent` gets the main endpoint's events only. On the connected endpoint every event but `account.updated` is
|
|
1237
|
+
ignored and answered 200. The four main endpoint events in the table never reach `onOtherEvent`, also when their own
|
|
1238
|
+
hook is left out.
|
|
1239
|
+
|
|
1240
|
+
### Ended subscriptions
|
|
1241
|
+
|
|
1242
|
+
When Stripe ends a subscription, its unpaid invoices stay payable: a cancel leaves them open, and when payment retries
|
|
1243
|
+
run out Stripe can mark the last one uncollectible, which still takes a payment. So after `onSubscriptionDeleted` the
|
|
1244
|
+
handler calls `invoices.voidUnpaidInvoices(subscription)`. Set `voidUnpaidInvoicesOnEnd: false` to turn this off.
|
|
1245
|
+
|
|
1246
|
+
- The hook runs first, so the app ends access even when Stripe refuses a void. The void runs even when the hook
|
|
1247
|
+
throws.
|
|
1248
|
+
- A refused void fails the event when the hook succeeded. The event is retried only if the app's event store lets
|
|
1249
|
+
Stripe deliver it again, for example with `release` (see "Retrying an event that failed"), and that retry runs
|
|
1250
|
+
`onSubscriptionDeleted` again although it had finished. With a store that keeps every event it has seen, a nightly
|
|
1251
|
+
job calling `voidUnpaidInvoices` is the only retry.
|
|
1252
|
+
- When both fail, the hook's error is thrown and the refused void goes to `onError('voidUnpaidInvoices', error)`. The
|
|
1253
|
+
event is given back even when the hook's error is a refusal under `markRefusalsDone`, so the retry voids again.
|
|
824
1254
|
|
|
825
1255
|
---
|
|
826
1256
|
|
|
@@ -892,6 +1322,12 @@ import {
|
|
|
892
1322
|
} from '@apexara/stripe';
|
|
893
1323
|
```
|
|
894
1324
|
|
|
1325
|
+
### Idempotency keys
|
|
1326
|
+
|
|
1327
|
+
```typescript
|
|
1328
|
+
import { IdempotencyOptions } from '@apexara/stripe';
|
|
1329
|
+
```
|
|
1330
|
+
|
|
895
1331
|
### Checkout
|
|
896
1332
|
|
|
897
1333
|
```typescript
|
|
@@ -913,6 +1349,7 @@ import {
|
|
|
913
1349
|
CreateInvoiceSubscriptionOptions,
|
|
914
1350
|
CreateInvoiceSubscriptionResult,
|
|
915
1351
|
SubscriptionSyncFields,
|
|
1352
|
+
SubscriptionDiscount,
|
|
916
1353
|
} from '@apexara/stripe';
|
|
917
1354
|
```
|
|
918
1355
|
|
|
@@ -992,7 +1429,7 @@ npm test
|
|
|
992
1429
|
npm run test:coverage
|
|
993
1430
|
```
|
|
994
1431
|
|
|
995
|
-
**Test stack:** Vitest with v8 coverage. Tests live in `src/tests/` and are excluded from the build output.
|
|
1432
|
+
**Test stack:** Vitest 4 with v8 coverage. Tests live in `src/tests/` and are excluded from the build output. Running them needs Node 20.19 or later; the library itself still runs on Node 18 (`engines`).
|
|
996
1433
|
|
|
997
1434
|
**Stripe API version:** `2025-08-27.basil` — pinned in `src/client.ts`. To use a different version, pass `apiVersion` in `StripeClientConfig`.
|
|
998
1435
|
|