@fantastic.dev/better-stripe 0.50.2 → 0.50.3

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.
@@ -0,0 +1,284 @@
1
+ # React API reference
2
+
3
+ ## React Hooks
4
+
5
+ Import from `@fantastic.dev/better-stripe/react`. All hooks use Convex's `useQuery` and `useMutation` internally.
6
+
7
+ Read hooks are exported as factory functions that take the app's `useQuery` binding and a query function reference, allowing them to work with any component registration name. Hooks that take a single ID argument accept `undefined` and skip the query (via Convex's `"skip"` sentinel) until the ID is available.
8
+
9
+ ### Read Hooks
10
+
11
+ | Hook Factory | Hook Arguments | Returns |
12
+ | ------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
13
+ | `createUseAccount` | `(userId?)` | `{ account, isLoading }` |
14
+ | `createUseProducts` | `({ accountId?, active? }?)` | `{ products, isLoading }` |
15
+ | `createUsePrices` | `(productId?)` | `{ prices, isLoading }` |
16
+ | `createUseSubscription` | `(subscriptionId?)` | `{ subscription, isActive, isTrialing, isCanceling, daysUntilRenewal, daysUntilTrialEnd, isLoading }` |
17
+ | `createUseSubscriptions` | `({ userId?, status? }?)` | `{ subscriptions, activeSubscription, isLoading }` |
18
+ | `createUseCheckout` | `(sessionId?)` | `{ session, status, isComplete, isLoading }` |
19
+ | `createUsePaymentMethods` | `(accountId?)` | `{ methods, defaultMethod, isLoading }` |
20
+ | `createUseInvoices` | `({ userId?, subscriptionId?, status? }?)` | `{ invoices, isLoading }` |
21
+ | `createUseAccountOnboarding` | `(accountId?)` | `{ account, status, isReady, missingRequirements, isLoading }` |
22
+ | `createUseEarnings` | `(accountId?)` | `{ gross, reversed, net, payouts, paidOut, transfers, isLoading }` — recipient balance/earnings |
23
+ | `createUseSplitBreakdown` | `({ sourceChargeId?, saleAmount? })` | `{ breakdown: { legs, store, affiliate, other, recipientsTotal, platform? } \| null, isLoading }` — per-sale split |
24
+ | `createUseDisputes` | `({ accountId?, status? }?)` | `{ disputes, isLoading }` |
25
+ | `createUseDisputeWithCountdown` | `(stripeDisputeId?)` | `{ dispute, countdown: { dueBy?, daysRemaining?, isOverdue } \| null, isLoading }` |
26
+
27
+ ### Checkout Session Hooks
28
+
29
+ For Stripe Checkout Session custom UI flows (CheckoutProvider-based):
30
+
31
+ | Hook / Component | Description |
32
+ | ------------------------- | ----------------------------------------------------------------------------------------------------------- |
33
+ | `CheckoutSessionProvider` | Provider wrapping Stripe's `CheckoutProvider`. Accepts `publishableKey`, `clientSecret`, `appearance`. |
34
+ | `useCheckoutSession()` | Returns `{ type, sessionId, canConfirm, confirm(opts?) }` — discriminated union for checkout state/actions. |
35
+
36
+ ```tsx
37
+ import {
38
+ CheckoutSessionProvider,
39
+ PaymentElement,
40
+ useCheckoutSession,
41
+ } from "@fantastic.dev/better-stripe/react";
42
+
43
+ <CheckoutSessionProvider publishableKey={pk} clientSecret={token}>
44
+ <MyForm />
45
+ </CheckoutSessionProvider>;
46
+
47
+ function MyForm() {
48
+ const checkout = useCheckoutSession();
49
+ if (checkout.type !== "success") return <Spinner />;
50
+ return (
51
+ <>
52
+ <PaymentElement />
53
+ <button
54
+ disabled={!checkout.canConfirm}
55
+ onClick={() => checkout.confirm()}
56
+ >
57
+ Pay
58
+ </button>
59
+ </>
60
+ );
61
+ }
62
+ ```
63
+
64
+ ### Payment Confirmation Hooks
65
+
66
+ | Hook | Description |
67
+ | --------------------- | ----------------------------------------------------------------------------------------------------- |
68
+ | `useConfirmPayment()` | Provides `confirmPayment(clientSecret)`, `confirmCardSetup(clientSecret)`, `confirmSetup(returnUrl?)` |
69
+
70
+ All return `{ success: true } | { success: false, error: string }`.
71
+
72
+ ### Payment Method Action Hooks
73
+
74
+ | Hook | Description |
75
+ | ----------------------------- | ------------------------------------------------------------------------------------- |
76
+ | `usePaymentMethodActions(cb)` | Provides `createAndAttach()`, `detach(id)`, `setDefault(id)` with loading/error state |
77
+
78
+ Accepts app-provided callbacks for backend operations (attach, detach, setDefault, reload).
79
+
80
+ ### Theming
81
+
82
+ | API | Description |
83
+ | -------------------------------- | ------------------------------------------------------------------------- |
84
+ | `createStripeAppearance(config)` | Factory: color tokens → Stripe `Appearance` object |
85
+ | `createStripeElementStyles(cfg)` | Factory: color tokens → inline `style` for CardNumber/Expiry/CVC elements |
86
+ | `defaultStripeAppearance` | Light preset |
87
+ | `darkStripeAppearance` | Dark preset |
88
+
89
+ ### Re-exported Stripe Elements
90
+
91
+ These are re-exported so apps never need to import from `@stripe/react-stripe-js` directly:
92
+
93
+ `PaymentElement`, `CardElement`, `CardNumberElement`, `CardExpiryElement`, `CardCvcElement`
94
+
95
+ ## React Components
96
+
97
+ Import from `@fantastic.dev/better-stripe/react`. The package includes the
98
+ example's reusable checkout, payouts, refunds, disputes, accounts, onboarding,
99
+ products, subscriptions, billing, referrals, and admin/setup workflows.
100
+
101
+ Use native unstyled markup, render props, or companion hooks with your own
102
+ design system. Bind authenticated server callbacks and query data in your app.
103
+ Supported workflows can select Stripe Connect embedded presentation; checkout
104
+ supports five integrations. No example router, persona provider, or CSS is required.
105
+
106
+ See [the React workflow guide](react-workflows.md) for usage, the full
107
+ component/hook matrix, styling, data contracts, and Stripe integration limits.
108
+ Existing low-level components remain available below. Props vary by component;
109
+ Stripe iframe styling uses `appearance`, while custom markup uses render props
110
+ or the low-level component's `className`/label props.
111
+
112
+ ### Hosted onboarding navigation
113
+
114
+ Since 0.14.0, `Onboarding` and `useOnboarding` suppress hosted navigation from
115
+ create/continue responses after unmount or authenticated scope replacement.
116
+ Current-scope responses still navigate through `onNavigate` or the default
117
+ `window.location.assign`. Shared pending locks, duplicate-submit prevention and
118
+ error state remain intact. Set `scopeKey` to identify the authenticated
119
+ account/resource; it controls lifecycle isolation and does not authorize access.
120
+ See the [workflow guide](react-workflows.md#dispute-evidence-uploads-and-onboarding-navigation).
121
+
122
+ ### Provider
123
+
124
+ | Component | Description |
125
+ | ------------------------- | ------------------------------------------------------------------------------------------------ |
126
+ | `StripeProvider` | Stripe Elements context provider. Accepts `publishableKey` prop. |
127
+ | `CheckoutSessionProvider` | Checkout Session context provider for custom UI flows. Accepts `publishableKey`, `clientSecret`. |
128
+
129
+ ### Checkout and Subscription
130
+
131
+ | Component | Description |
132
+ | ----------------------- | --------------------------------------------------------- |
133
+ | `EmbeddedCheckout` | Headless embedded checkout with render-prop loading state |
134
+ | `CheckoutStatus` | Checkout session status display |
135
+ | `PricePicker` | Plan/price selection with render-prop customization |
136
+ | `PriceCard` | Individual price card (controlled or uncontrolled) |
137
+ | `IntervalSelector` | Billing interval toggle (month/year) |
138
+ | `SubscriptionCard` | Current subscription display |
139
+ | `SubscriptionLineItems` | Line item breakdown |
140
+ | `PriceBadge` | Price/plan badge |
141
+ | `TrialAlert` | Trial status and renewal alert |
142
+ | `BillingPortalLink` | Link/button to Stripe billing portal |
143
+ | `SubscriptionActions` | Cancel/reactivate action buttons (status-aware) |
144
+
145
+ ### Payment Methods
146
+
147
+ | Component | Description |
148
+ | --------------------------- | -------------------------------------------------- |
149
+ | `AddCardForm` | Headless add-payment-method form |
150
+ | `PaymentMethodsList` | Saved payment methods list with render props |
151
+ | `DeletePaymentMethodDialog` | Remove payment method (app provides dialog chrome) |
152
+ | `PaymentMethodActions` | Per-method set-default/delete actions |
153
+
154
+ ### Buyer Billing
155
+
156
+ | Component | Description |
157
+ | ------------------ | ------------------------------------------------------------------------------------------------------- |
158
+ | `BuyerBillingView` | Per-store buyer billing view: subscriptions grouped by store, reusable saved card, embedded card update |
159
+
160
+ An embedded-only billing surface for buyers: their subscriptions are grouped by
161
+ store (each store scoped via the `listSubscriptionsByUserAndStore` /
162
+ `groupSubscriptionsByStore` per-store queries) with per-store cancel/reactivate,
163
+ alongside the ONE saved payment method that is reusable across every store. The
164
+ card is updated in place via an embedded `AddCardForm` slot — no redirect.
165
+
166
+ ```tsx
167
+ import {
168
+ BuyerBillingView,
169
+ AddCardForm,
170
+ StripeProvider,
171
+ } from "@fantastic.dev/better-stripe/react";
172
+ import { groupSubscriptionsByStore } from "@fantastic.dev/better-stripe";
173
+
174
+ function BuyerBilling({ userId, customerAccount }: Props) {
175
+ const subscriptions = useQuery(api.stripe.listSubscriptionsByUser, {
176
+ userId,
177
+ });
178
+ const { defaultMethod } = usePaymentMethods(customerAccount);
179
+ const cancel = useMutation(api.stripe.cancelSubscription);
180
+ const reactivate = useMutation(api.stripe.reactivateSubscription);
181
+
182
+ return (
183
+ <BuyerBillingView
184
+ // groupSubscriptionsByStore reused, not recomputed
185
+ subscriptions={subscriptions?.map((s) => ({
186
+ ...s,
187
+ id: s.stripeSubscriptionId,
188
+ }))}
189
+ paymentMethod={defaultMethod}
190
+ isLoading={subscriptions === undefined}
191
+ onCancel={(sub) => cancel({ stripeSubscriptionId: sub.id })}
192
+ onReactivate={(sub) => reactivate({ stripeSubscriptionId: sub.id })}
193
+ updateCardSlot={
194
+ <StripeProvider publishableKey={pk}>
195
+ <AddCardForm onSuccess={handleCardSaved} />
196
+ </StripeProvider>
197
+ }
198
+ />
199
+ );
200
+ }
201
+ ```
202
+
203
+ ### Connect and Marketplace
204
+
205
+ | Component | Description |
206
+ | ------------------------- | --------------------------------------------- |
207
+ | `ConnectStatusBadge` | Connect verification status badge |
208
+ | `AccountOnboardingCard` | Connect onboarding progress display |
209
+ | `AccountOnboardingButton` | Continue onboarding action (status-aware) |
210
+ | `AccountCreateCard` | Create Connect account card |
211
+ | `AccountCreateButton` | Create account action with loading state |
212
+ | `AccountLoginCard` | Login to Connect dashboard card |
213
+ | `AccountLoginButton` | Dashboard login/open action |
214
+ | `AccountCloseCard` | Close/restart account card (status-aware) |
215
+ | `AccountCloseButton` | Close/restart action with status-aware labels |
216
+ | `ConnectRequirements` | Missing requirements checklist |
217
+
218
+ ### Payouts and Earnings
219
+
220
+ Use React's `formatPayoutAmount(amount, currency, locale?)` when rendering
221
+ observed ordinary Stripe balances and payouts. It preserves supported currency
222
+ units, including JPY and fractional ISK/UGX compatibility values. Unknown
223
+ precision is shown explicitly as raw minor units with `display unavailable`.
224
+ This display helper does not establish payout eligibility or Global Payouts
225
+ currency support. See the [React workflow guide](react-workflows.md).
226
+
227
+ | Component | Description |
228
+ | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
229
+ | `PayoutSchedule` | Recipient balance + next-payout display, fed by a `balance` snapshot and `listPayouts` rows. Payouts are automatic/rolling — no manual-withdrawal action is offered. |
230
+ | `EarningsSummary` | Gross / reversals & adjustments / net + latest payout, fed by `useEarnings(accountId)`. Reversals cover both deferred fee collection and refund/dispute clawbacks — not a pure fees figure, hence the "Reversals & adjustments" label rather than "Fees". |
231
+ | `SplitBreakdown` | Per-sale store / affiliate / other / platform split lines, fed by `useSplitBreakdown`. The platform line reads "unknown" (not $0) when the hook wasn't given the sale amount. |
232
+
233
+ ### Disputes (headless)
234
+
235
+ The app-owned alternative to [Embedded Disputes](#embedded-disputes-stripe-connect) below — build a custom dispute UI on the read hooks and these components instead of Stripe's hosted ConnectJS components.
236
+
237
+ | Component | Description |
238
+ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
239
+ | `DisputesList` | Sorted-by-deadline dispute list (soonest evidence due-by first, no-deadline last), fed by `useDisputes` |
240
+ | `DisputeDetail` | Amount, reason, status, evidence-due countdown, and linked transfers for one dispute, fed by `useDisputeWithCountdown` |
241
+ | `EvidenceUpload` | Since 0.14.0: unstyled file-selection, pending, failure and retry control with render props; bind `onUpload(file)` to an authenticated server adapter that attaches to a draft |
242
+ | `EvidenceForm` | Plain-language evidence form (product description, access activity, additional info, customer communication) that maps through `buildDisputeEvidence` before calling an app-wired `onUpdateDispute`; `stage()` saves a draft, `submit()` finalizes |
243
+
244
+ ### Embedded Disputes (Stripe Connect)
245
+
246
+ The Stripe-hosted alternative to the headless dispute components: each seller
247
+ views and responds to their own disputes via Stripe's embedded `disputes_list`
248
+ / `payment_disputes` components, driven by the Account Session that
249
+ `createDisputeSession` creates.
250
+
251
+ | Component | Description |
252
+ | ------------------ | ----------------------------------------------------------------------------------------------- |
253
+ | `ConnectProvider` | Initializes ConnectJS with your publishable key + an account-session fetcher |
254
+ | `EmbeddedDisputes` | Mounts the embedded `disputes_list` (or `payment_disputes` when scoped via `payment`) component |
255
+
256
+ **Dependencies:** the wrapper uses [`@stripe/react-connect-js`](https://www.npmjs.com/package/@stripe/react-connect-js) and [`@stripe/connect-js`](https://www.npmjs.com/package/@stripe/connect-js), which ship as regular dependencies of this package (same convention as `@stripe/react-stripe-js` / `@stripe/stripe-js`) -- no extra install step. ConnectJS components are client-only iframes; render them in client components.
257
+
258
+ ```tsx
259
+ // convex/stripe.ts — expose the account session (server side)
260
+ export const createDisputeSession = action({
261
+ args: { stripeAccountId: v.string() },
262
+ handler: async (ctx, args) => stripe.createDisputeSession(ctx, args),
263
+ });
264
+
265
+ // Seller disputes page (client side)
266
+ import {
267
+ ConnectProvider,
268
+ EmbeddedDisputes,
269
+ } from "@fantastic.dev/better-stripe/react";
270
+
271
+ function SellerDisputes({ stripeAccountId }: { stripeAccountId: string }) {
272
+ const createSession = useAction(api.stripe.createDisputeSession);
273
+ return (
274
+ <ConnectProvider
275
+ publishableKey={import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY}
276
+ fetchClientSecret={async () =>
277
+ (await createSession({ stripeAccountId })).clientSecret
278
+ }
279
+ >
280
+ <EmbeddedDisputes />
281
+ </ConnectProvider>
282
+ );
283
+ }
284
+ ```
package/docs/releasing.md CHANGED
@@ -50,3 +50,22 @@ the extensionless import exposed by the public SDK in 0.47.0. Use explicit `.js`
50
50
  extensions for reachable relative imports; do not hide failures behind a custom
51
51
  resolver. A corrected local build is candidate evidence; verify the normal
52
52
  published artifact before application adoption.
53
+
54
+ ## Release workflow
55
+
56
+ Releases are automated with [Release Please](https://github.com/googleapis/release-please-action) and published to npmjs.com as `@fantastic.dev/better-stripe`. **Don't bump the version or edit `CHANGELOG.md` by hand.**
57
+
58
+ 1. **Give every PR a Conventional Commit title** (it becomes the squash-merge commit):
59
+ - `fix: …` makes a patch release.
60
+ - `feat: …` makes a minor release.
61
+ - `feat!: …` (or a `BREAKING CHANGE:` footer) makes a minor release while the package is pre-1.0.
62
+ - `docs:`, `chore:`, `ci:`, `refactor:`, `test:`, `build:` and `perf:` appear in the changelog too. On their own they still open a patch release PR, which auto-merges once its required checks pass.
63
+
64
+ Write the title for consumers of the package: it becomes the changelog entry. A title that isn't a Conventional Commit is left out.
65
+
66
+ 2. **On merge to `main`**, the `Release` workflow opens or updates a release PR that bumps `package.json`, `CHANGELOG.md`, the README version line and `.release-please-manifest.json`. It formats the generated changelog with the repository's pinned Prettier and commits any formatting changes through the release GitHub App, so CI validates the formatted branch. An already formatted changelog creates no extra commit. After formatting, the workflow enables squash auto-merge for the generated release PR using the release GitHub App.
67
+ 3. **Auto-merge waits for green checks**. The active `main` ruleset requires `ci`, `Shadscan UI quality gate (100)` and `codegen`, with no bypass actors. Failed or pending required checks prevent merging. Once GitHub merges the generated release PR, the resulting `Release` workflow run tags the version, creates the GitHub release and publishes to npm through [trusted publishing](https://docs.npmjs.com/trusted-publishers) with provenance. There's no npm token.
68
+
69
+ Release policy lives in `release-please-config.json`. Keep the workflow file named `release.yml`, because the trusted publisher on npmjs.com is bound to that filename. A manually pushed `vX.Y.Z` tag also publishes, but only if it matches `package.json` and `CHANGELOG.md` has a section for it (`scripts/release-notes.mjs`). If publishing fails after the GitHub release is created, use **Re-run failed jobs** on that run. Check npm first if the outcome is uncertain: a published version can't be overwritten.
70
+
71
+ The private `example` workspace isn't published.
@@ -0,0 +1,52 @@
1
+ # Testing utilities
2
+
3
+ Import from `@fantastic.dev/better-stripe/testing`.
4
+
5
+ ### assertTestEnvironment
6
+
7
+ Guards against running test fixtures with live Stripe keys:
8
+
9
+ ```typescript
10
+ import { assertTestEnvironment } from "@fantastic.dev/better-stripe/testing";
11
+
12
+ assertTestEnvironment(); // Throws if STRIPE_SECRET_KEY does not start with sk_test_
13
+ ```
14
+
15
+ ### Fixture Factories
16
+
17
+ Typed factories for creating Stripe test data:
18
+
19
+ ```typescript
20
+ import {
21
+ createTestAccount,
22
+ createTestPrice,
23
+ createTestProduct,
24
+ createTestSubscription,
25
+ } from "@fantastic.dev/better-stripe/testing";
26
+
27
+ const account = await createTestAccount(stripe, { email: "test@example.com" });
28
+ const product = await createTestProduct(stripe, { name: "Pro Plan" });
29
+ const price = await createTestPrice(stripe, {
30
+ productId: product.id,
31
+ unitAmount: 2999,
32
+ interval: "month",
33
+ });
34
+ ```
35
+
36
+ ### Mock Webhook Events
37
+
38
+ Factories for creating mock webhook events in tests:
39
+
40
+ ```typescript
41
+ import {
42
+ mockAccountUpdated,
43
+ mockCheckoutCompleted,
44
+ mockInvoicePaid,
45
+ mockSubscriptionUpdated,
46
+ } from "@fantastic.dev/better-stripe/testing";
47
+
48
+ const event = mockCheckoutCompleted({
49
+ stripeSessionId: "cs_test_123",
50
+ metadata: { userId: "user_abc" },
51
+ });
52
+ ```
@@ -0,0 +1,259 @@
1
+ # Webhooks and triggers
2
+
3
+ ## Webhook API
4
+
5
+ ### registerRoutes
6
+
7
+ Register the webhook endpoint on your Convex HTTP router:
8
+
9
+ ```typescript
10
+ import { registerRoutes } from "@fantastic.dev/better-stripe";
11
+
12
+ registerRoutes(http, components.betterStripe, {
13
+ webhookPath: "/stripe/webhook", // Default path
14
+ stripeSecretKey: process.env.STRIPE_SECRET_KEY,
15
+ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
16
+ webhookSecretV2: process.env.STRIPE_WEBHOOK_SECRET_V2, // For V2 thin events
17
+ webhooks: internal.stripe, // The { syncWebhook, asyncWebhook } pair from webhookHandlers()
18
+ events: { ... }, // Optional per-event handlers (advanced)
19
+ onEvent: (ctx, event) => { ... }, // Optional catch-all handler (advanced)
20
+ });
21
+ ```
22
+
23
+ ### Webhook Setup
24
+
25
+ Stripe event destinations come in two flavors that cannot be mixed:
26
+
27
+ - **Snapshot** (`event_payload: 'snapshot'`) — V1 events include the full object in the payload. Used for payments, subscriptions, invoices, products, and payouts.
28
+ - **Thin** (`event_payload: 'thin'`) — V2 events include only the event type and object reference. The handler fetches the full object from the Stripe API. Used for Connect account lifecycle events.
29
+
30
+ You need **two** event destinations pointing to the same webhook URL, each with its own signing secret.
31
+
32
+ #### Programmatic setup
33
+
34
+ Use `setupEventDestination()` to create or update destinations:
35
+
36
+ ```typescript
37
+ // Create V1 snapshot destination
38
+ const v1 = await stripe.setupEventDestination(ctx, {
39
+ url: webhookUrl,
40
+ eventPayload: "snapshot",
41
+ });
42
+
43
+ // Create V2 thin destination
44
+ const v2 = await stripe.setupEventDestination(ctx, {
45
+ url: webhookUrl,
46
+ eventPayload: "thin",
47
+ });
48
+ ```
49
+
50
+ The method is idempotent — it finds an existing destination matching the URL and payload type, updates its events, or creates a new one.
51
+
52
+ #### Admin UI setup
53
+
54
+ The example app includes an `/admin/setup` page that handles webhook creation, env var verification, demo data seeding, and Stripe data syncing — all from the browser.
55
+
56
+ #### Event constants
57
+
58
+ ```typescript
59
+ import {
60
+ BETTER_STRIPE_WEBHOOK_EVENTS, // V1 snapshot events (20 events)
61
+ BETTER_STRIPE_V2_WEBHOOK_EVENTS, // V2 thin events (12 events)
62
+ ALL_BETTER_STRIPE_EVENTS, // Combined (32 events)
63
+ } from "@fantastic.dev/better-stripe";
64
+ ```
65
+
66
+ ### Event Processing
67
+
68
+ Records synced from Stripe objects without `userId` metadata are stored unattributed (`userId: ""`) and are not returned by user-scoped queries.
69
+
70
+ The webhook handler processes events through these steps:
71
+
72
+ 1. Verify Stripe signature
73
+ 2. Record the event in the `webhookEvents` ledger by `stripeEventId`. If the event was already seen and is `processing`, `processed`, or `ignored`, return 200 immediately. If the previous delivery `failed` (its writes rolled back), the ledger row is reset and the event is reprocessed on Stripe's retry.
74
+ 3. Upsert the component-owned domain table. When `webhooks` is configured, the upsert runs through `syncWebhook` — an internal mutation that performs the upsert **and** the sync trigger in the same transaction.
75
+ 4. On failure, mark the ledger row `failed` and return 500 so Stripe retries; otherwise mark it `processed`
76
+ 5. Schedule the matching `after*` async hook via `ctx.scheduler` (separate action)
77
+
78
+ ### Ledger-Based Deduplication
79
+
80
+ The component maintains a `webhookEvents` table that tracks every event by its Stripe event ID. This provides:
81
+
82
+ - **Replay protection** -- duplicate events are detected and skipped
83
+ - **Retry recovery** -- events whose processing failed (and rolled back) are reprocessed when Stripe retries, instead of deduplicating forever
84
+ - **Crash recovery** -- if a delivery dies mid-processing (timeout, restart), the `processing` row goes stale after 10 minutes and the event is reprocessed on Stripe's next retry instead of deduplicating forever
85
+ - **Failure tracking** -- failed events are marked with status and error message
86
+ - **Observability** -- all events (including unsupported types) are logged with `ignored` status
87
+
88
+ ### Supported Events
89
+
90
+ **Accounts V2 (thin events -- component fetches latest state, requires V2 event destination):**
91
+
92
+ - `v2.core.account.created`, `.updated`
93
+ - `v2.core.account[identity].updated`
94
+ - `v2.core.account[requirements].updated`
95
+ - `v2.core.account[configuration.merchant].updated`, `.capability_status_updated`
96
+ - `v2.core.account[configuration.customer].updated`
97
+ - `v2.core.account[configuration.recipient].updated`
98
+ - `v2.core.account[defaults].updated`
99
+ - `v2.core.account_person.created`, `.updated`
100
+ - `v2.core.account_link.returned`
101
+
102
+ **Billing (snapshot events -- payload contains full state):**
103
+
104
+ - `checkout.session.completed`
105
+ - `customer.subscription.created`, `.updated`, `.deleted`, `.trial_will_end`
106
+ - `invoice.created`, `.finalized`, `.paid`, `.payment_failed`
107
+ - `payment_intent.succeeded`, `.payment_failed`, `.canceled`
108
+ - `payout.created`, `.updated`, `.paid`, `.failed`, `.canceled`
109
+
110
+ - `refund.created`, `.updated`, `.failed`
111
+ - `application_fee.refunded` -- keeps `feeCollectedAmount`/`feeRefundedAmount` accurate on the linked payment
112
+ - `charge.dispute.created`, `.updated`, `.closed`, `.funds_withdrawn`, `.funds_reinstated`
113
+ - `product.created`, `.updated`
114
+ - `price.created`, `.updated`
115
+
116
+ Note: Subscription and invoice events use v1 Billing API event names even when the billing entity is a V2 account referenced via `customer_account`.
117
+
118
+ Dedicated payout cancellations use the same signed V1 endpoint, payout record
119
+ and connected-account association as other payout events. Generic `onEvent`
120
+ and `events["payout.canceled"]` callbacks run after reconciliation. Cancellation
121
+ does not invoke the paid/completed convenience hook. Normal verified replay is
122
+ deduplicated by the existing event ledger.
123
+
124
+ When upgrading from 0.11.0 or earlier, add `payout.canceled` to the existing V1
125
+ endpoint's selected events. New endpoints created with the corrected package's
126
+ defaults include it. Updating the library alone does not edit an existing provider
127
+ endpoint or recover already missed events. Consumers must adopt a published
128
+ version containing this correction; a merged source fix is not a package release.
129
+
130
+ ## Trigger API
131
+
132
+ The trigger system follows the BetterAuth pattern: define callbacks at client init time, export the `syncWebhook`/`asyncWebhook` pair via `webhookHandlers()`, and pass their function references to `registerRoutes` via `webhooks`.
133
+
134
+ ### SyncTriggers
135
+
136
+ Sync triggers run in the same transaction as the component's database write. They must be DB-only and idempotent. Throwing from a sync trigger rolls back the entire transaction (including the component upsert), causing Stripe to retry the webhook.
137
+
138
+ ```typescript
139
+ interface SyncTriggers {
140
+ account?: {
141
+ onCreate?: (ctx, doc) => Promise<void>;
142
+ onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
143
+ };
144
+ subscription?: {
145
+ onCreate?: (ctx, doc) => Promise<void>;
146
+ onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
147
+ onDelete?: (ctx, doc) => Promise<void>;
148
+ };
149
+ checkoutSession?: {
150
+ onCompleted?: (ctx, doc) => Promise<void>;
151
+ };
152
+ product?: {
153
+ onCreate?: (ctx, doc) => Promise<void>;
154
+ onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
155
+ };
156
+ price?: {
157
+ onCreate?: (ctx, doc) => Promise<void>;
158
+ onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
159
+ };
160
+ invoice?: {
161
+ onCreate?: (ctx, doc) => Promise<void>;
162
+ onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
163
+ };
164
+ payment?: {
165
+ onCreate?: (ctx, doc) => Promise<void>;
166
+ };
167
+ payout?: {
168
+ onCreate?: (ctx, doc) => Promise<void>;
169
+ onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
170
+ };
171
+ refund?: {
172
+ onCreate?: (ctx, doc) => Promise<void>;
173
+ onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
174
+ };
175
+ dispute?: {
176
+ onCreate?: (ctx, doc) => Promise<void>;
177
+ onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
178
+ };
179
+ }
180
+ ```
181
+
182
+ ### AsyncHooks
183
+
184
+ Async hooks run after the component's database write commits, in a separate scheduled action. Use these for external API calls (email, Slack, analytics). Failures do not roll back the component write.
185
+
186
+ ```typescript
187
+ interface AsyncHooks {
188
+ onAccountUpdated?: (ctx, account) => Promise<void>;
189
+ onCheckoutCompleted?: (ctx, session) => Promise<void>;
190
+ onSubscriptionUpdated?: (ctx, subscription) => Promise<void>;
191
+ onSubscriptionCanceled?: (ctx, subscription) => Promise<void>;
192
+ onTrialEnding?: (ctx, subscription) => Promise<void>;
193
+ onInvoicePaid?: (ctx, invoice) => Promise<void>;
194
+ onInvoicePaymentFailed?: (ctx, invoice) => Promise<void>;
195
+ onPaymentSucceeded?: (ctx, payment) => Promise<void>;
196
+ onPaymentFailed?: (ctx, payment) => Promise<void>;
197
+ onPayoutCompleted?: (ctx, payout) => Promise<void>;
198
+ onRefundCreated?: (ctx, refund) => Promise<void>;
199
+ onDisputeCreated?: (ctx, dispute) => Promise<void>;
200
+ onDisputeClosed?: (ctx, dispute) => Promise<void>;
201
+ }
202
+ ```
203
+
204
+ ### webhookHandlers()
205
+
206
+ Returns the `{ syncWebhook, asyncWebhook }` pair that bridges your app callbacks into the webhook processing pipeline. Export them from a Convex module (e.g. `convex/stripe.ts`) so they get function references the webhook handler can call:
207
+
208
+ ```typescript
209
+ export const { syncWebhook, asyncWebhook } = stripe.webhookHandlers();
210
+ ```
211
+
212
+ Then pass the module to `registerRoutes` as `webhooks: internal.stripe`.
213
+
214
+ **How `syncWebhook` works.** It is a single internal mutation that routes by a `dispatcher` discriminator to perform the component table upsert **and** your configured sync trigger inside one transaction. It reads the existing doc (to decide `onCreate` vs `onUpdate` and supply `oldDoc`), runs the upsert, re-reads the doc, and invokes your trigger. If the trigger throws, the whole mutation — including the component write — rolls back, the webhook handler marks the ledger row `failed`, and returns 500 so Stripe retries. On retry, failed ledger rows are reset and the event is reprocessed.
215
+
216
+ **How `asyncWebhook` works.** It is a single internal action that routes by a `hook` discriminator. After the `syncWebhook` transaction commits and the ledger marks the event `processed`, the webhook handler schedules `asyncWebhook` via `ctx.scheduler` with the committed doc. Hook failures never roll back the component write.
217
+
218
+ Exactly one hook (at most) is scheduled per event:
219
+
220
+ | Stripe event | Scheduled hook |
221
+ | ------------------------------------------------- | --------------------------- |
222
+ | `v2.core.account*` (all account lifecycle events) | `afterAccountUpdated` |
223
+ | `checkout.session.completed` | `afterCheckoutCompleted` |
224
+ | `customer.subscription.created` / `.updated` | `afterSubscriptionUpdated` |
225
+ | `customer.subscription.deleted` | `afterSubscriptionCanceled` |
226
+ | `customer.subscription.trial_will_end` | `afterTrialEnding` |
227
+ | `invoice.paid` | `afterInvoicePaid` |
228
+ | `invoice.payment_failed` | `afterInvoicePaymentFailed` |
229
+ | `payment_intent.succeeded` | `afterPaymentSucceeded` |
230
+ | `payment_intent.payment_failed` | `afterPaymentFailed` |
231
+ | `payout.paid` | `afterPayoutCompleted` |
232
+ | `refund.created` | `afterRefundCreated` |
233
+ | `charge.dispute.created` | `afterDisputeCreated` |
234
+ | `charge.dispute.closed` | `afterDisputeClosed` |
235
+
236
+ All other processed events (e.g. `payment_intent.canceled`, `payout.failed`, `invoice.created`, `refund.updated`, `charge.dispute.funds_withdrawn`) update the component tables but schedule no hook.
237
+
238
+ > **Note:** async hooks should be idempotent. Duplicate delivery is possible in rare ledger-failure cases (e.g. the event is processed and the hook scheduled, but the ledger update fails and Stripe redelivers).
239
+
240
+ The raw callbacks you pass to `triggers` and `hooks` on the `BetterStripe` constructor are the source of truth for app behavior. The exported `syncWebhook`/`asyncWebhook` pair is the bridge that makes them callable from the Convex runtime — events whose triggers you did not configure simply run the upsert (no sync trigger) and schedule no hook.
241
+
242
+ ### Dunning & smart retries
243
+
244
+ Failed recurring payments are recovered by **Stripe Smart Retries**, not by any retry loop in this library. The component never re-attempts a charge itself — it tracks the delinquency and fires hooks so your app can notify the customer. Retry _timing and count_ are owned entirely by Stripe.
245
+
246
+ **Required Dashboard settings** (Stripe controls the schedule; enable these once):
247
+
248
+ - **Subscriptions:** Dashboard → **Billing → Revenue recovery → Retries** — turn on **Smart Retries** (Stripe's recommended, ML-timed schedule). Also set what happens when retries are exhausted (leave `past_due`, mark `unpaid`, or cancel).
249
+ - **One-time invoices:** Dashboard → **Settings → Billing → Invoices** — configure retry behavior for invoices not tied to a subscription.
250
+ - Ensure the `invoice.payment_failed` and `customer.subscription.updated` events are delivered to your webhook endpoint.
251
+
252
+ **What the component surfaces:**
253
+
254
+ - The subscription row tracks Stripe's delinquency states — `past_due` (first failed charge) and `unpaid` (retries exhausted) — arriving via `customer.subscription.updated`, which fires **`onSubscriptionUpdated`**.
255
+ - Each `invoice.payment_failed` fires **`onInvoicePaymentFailed`** with the committed invoice. Under Smart Retries the invoice carries `nextPaymentAttempt` (ISO time of Stripe's next retry) and `attemptCount`, so a dunning email can tell the buyer exactly when Stripe will try again. Both clear once the invoice is paid or retries stop.
256
+
257
+ `onInvoicePaymentFailed` is the **invoice-level** (subscription-cycle) failure — distinct from `onPaymentFailed`, which fires on a one-time **PaymentIntent** failure (`payment_intent.payment_failed`) and receives a payment, not an invoice.
258
+
259
+ > **Limitation:** `nextPaymentAttempt` is captured from the `invoice.payment_failed` payload, which is correct for Smart Retries. If you instead use a **custom retry _automation_**, Stripe sets `next_payment_attempt` on `invoice.updated` (not `invoice.payment_failed`); the component does not currently process `invoice.updated`, so the retry timestamp may lag until the next handled invoice event.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.50.2",
3
+ "version": "0.50.3",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -85,7 +85,17 @@
85
85
  "docs/releasing.md",
86
86
  "docs/release-handoff.md",
87
87
  "docs/setup-intent-recovery.md",
88
- "docs/metered-usage.md"
88
+ "docs/metered-usage.md",
89
+ "docs/README.md",
90
+ "docs/overview.md",
91
+ "docs/client-api.md",
92
+ "docs/webhooks.md",
93
+ "docs/marketplace.md",
94
+ "docs/react-api.md",
95
+ "docs/testing.md",
96
+ "docs/configuration.md",
97
+ "docs/architecture.md",
98
+ "docs/development.md"
89
99
  ],
90
100
  "scripts": {
91
101
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",