@fantastic.dev/better-stripe 0.76.0 → 0.78.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 (35) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  4. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  5. package/dist/client/core/accountLinks.d.ts +4 -1
  6. package/dist/client/core/accountLinks.d.ts.map +1 -1
  7. package/dist/client/core/accountLinks.js +26 -8
  8. package/dist/client/core/accountLinks.js.map +1 -1
  9. package/dist/client/core/billingPortalFlow.d.ts +46 -0
  10. package/dist/client/core/billingPortalFlow.d.ts.map +1 -0
  11. package/dist/client/core/billingPortalFlow.js +78 -0
  12. package/dist/client/core/billingPortalFlow.js.map +1 -0
  13. package/dist/client/index.d.ts +1 -1
  14. package/dist/client/index.d.ts.map +1 -1
  15. package/dist/client/index.js.map +1 -1
  16. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  17. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  18. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  19. package/dist/component/earnings/triggers.d.ts +16 -16
  20. package/dist/component/payoutRelease/queries.d.ts +2 -2
  21. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  22. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  23. package/dist/react/workflows/Billing.d.ts.map +1 -1
  24. package/dist/react/workflows/Billing.js +6 -4
  25. package/dist/react/workflows/Billing.js.map +1 -1
  26. package/docs/captured-checkout-payment.md +50 -4
  27. package/docs/checkout-session-pages.md +6 -0
  28. package/docs/client-api.md +51 -0
  29. package/package.json +1 -1
  30. package/src/client/core/accountLinks.ts +38 -9
  31. package/src/client/core/billingPortalFlow.test.ts +331 -0
  32. package/src/client/core/billingPortalFlow.ts +95 -0
  33. package/src/client/index.ts +1 -0
  34. package/src/react/workflows/Billing.tsx +15 -8
  35. package/src/react/workflows/BillingPortal.test.tsx +101 -0
@@ -0,0 +1,331 @@
1
+ import type Stripe from "stripe";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { BetterStripe, type BetterStripeComponent } from "../index.js";
4
+ import type { RunCtx } from "../helpers.js";
5
+ import type {
6
+ BillingPortalSubscriptionUpdateFlow,
7
+ CreateBillingPortalSessionOptions,
8
+ } from "./accountLinks.js";
9
+
10
+ const ctx = {} as RunCtx;
11
+ const flowData = {
12
+ type: "subscription_update_confirm",
13
+ subscription_update_confirm: {
14
+ subscription: "sub_original",
15
+ items: [{ id: "si_original", price: "price_target" }],
16
+ },
17
+ after_completion: {
18
+ type: "redirect",
19
+ redirect: { return_url: "https://host.example/billing/confirmed" },
20
+ },
21
+ } satisfies BillingPortalSubscriptionUpdateFlow;
22
+
23
+ function fixture(connectedAccountId?: string) {
24
+ const subscription = {
25
+ object: "subscription",
26
+ id: "sub_original",
27
+ customer_account: "acct_customer",
28
+ items: {
29
+ has_more: false,
30
+ data: [{ id: "si_original", price: { id: "price_current" } }],
31
+ },
32
+ };
33
+ const retrieve = vi.fn().mockResolvedValue(subscription);
34
+ const create = vi
35
+ .fn()
36
+ .mockResolvedValue({ url: "https://billing.stripe.test" });
37
+ class Client extends BetterStripe {
38
+ protected stripe() {
39
+ return {
40
+ subscriptions: { retrieve },
41
+ billingPortal: { sessions: { create } },
42
+ } as unknown as Stripe;
43
+ }
44
+ }
45
+ const client = new Client({} as BetterStripeComponent);
46
+ const options = {
47
+ stripeAccountId: "acct_customer",
48
+ connectedAccountId,
49
+ configurationId: "bpc_policy",
50
+ returnUrl: "https://host.example/billing",
51
+ flowData,
52
+ } satisfies CreateBillingPortalSessionOptions;
53
+ return { client, options, subscription, retrieve, create };
54
+ }
55
+
56
+ describe("targeted Billing Portal subscription confirmation", () => {
57
+ it.each([undefined, "acct_connected"])(
58
+ "retains exact subscription/item/price and completion routing in scope %s",
59
+ async (connectedAccountId) => {
60
+ const f = fixture(connectedAccountId);
61
+ expect(await f.client.createBillingPortalSession(ctx, f.options)).toEqual(
62
+ {
63
+ url: "https://billing.stripe.test",
64
+ },
65
+ );
66
+ expect(f.retrieve.mock.calls).toEqual([
67
+ connectedAccountId
68
+ ? ["sub_original", {}, { stripeAccount: connectedAccountId }]
69
+ : ["sub_original"],
70
+ ]);
71
+ const params = {
72
+ customer_account: "acct_customer",
73
+ configuration: "bpc_policy",
74
+ return_url: "https://host.example/billing",
75
+ flow_data: flowData,
76
+ };
77
+ expect(f.create.mock.calls).toEqual([
78
+ connectedAccountId
79
+ ? [params, { stripeAccount: connectedAccountId }]
80
+ : [params],
81
+ ]);
82
+ },
83
+ );
84
+
85
+ it.each([
86
+ { id: "sub_other" },
87
+ { customer_account: "acct_other" },
88
+ { customer_account: null },
89
+ { items: { has_more: false, data: [{ id: "si_other" }] } },
90
+ {
91
+ items: {
92
+ has_more: false,
93
+ data: [{ id: "si_original" }, { id: "si_original" }],
94
+ },
95
+ },
96
+ ])(
97
+ "denies mismatched or ambiguous original subscription: %j",
98
+ async (fields) => {
99
+ const f = fixture();
100
+ f.retrieve.mockResolvedValue({ ...f.subscription, ...fields });
101
+ await expect(
102
+ f.client.createBillingPortalSession(ctx, f.options),
103
+ ).rejects.toThrow();
104
+ expect(f.create).not.toHaveBeenCalled();
105
+ },
106
+ );
107
+
108
+ // Original recovered success stub is preserved separately: the provider disallows multi-item updates.
109
+ it("rejects a multi-item subscription instead of silently selecting its first item", async () => {
110
+ const f = fixture();
111
+ f.retrieve.mockResolvedValue({
112
+ ...f.subscription,
113
+ items: {
114
+ has_more: false,
115
+ data: [{ id: "si_unrelated" }, { id: "si_original" }],
116
+ },
117
+ });
118
+ await expect(
119
+ f.client.createBillingPortalSession(ctx, f.options),
120
+ ).rejects.toThrow();
121
+ expect(f.retrieve).toHaveBeenCalledExactlyOnceWith("sub_original");
122
+ expect(f.create).not.toHaveBeenCalled();
123
+ });
124
+
125
+ it.each([
126
+ null,
127
+ true,
128
+ [],
129
+ "subscription_update_confirm",
130
+ { ...flowData, type: "subscription_update" },
131
+ {
132
+ ...flowData,
133
+ subscription_update_confirm: { subscription: "sub_original", items: [] },
134
+ },
135
+ {
136
+ ...flowData,
137
+ subscription_update_confirm: {
138
+ subscription: "sub_original",
139
+ items: [{ id: "si_original", price: "prod_wrong" }],
140
+ },
141
+ },
142
+ {
143
+ ...flowData,
144
+ subscription_update_confirm: {
145
+ subscription: "sub_original",
146
+ items: [
147
+ { id: "si_original", price: "price_target" },
148
+ { id: "si_other", price: "price_other" },
149
+ ],
150
+ },
151
+ },
152
+ {
153
+ ...flowData,
154
+ after_completion: {
155
+ type: "redirect",
156
+ redirect: { return_url: "javascript:alert(1)" },
157
+ },
158
+ },
159
+ { ...flowData, unknownPolicy: true },
160
+ {
161
+ ...flowData,
162
+ subscription_update_confirm: {
163
+ subscription: 42,
164
+ items: [{ id: "si_original", price: "price_target" }],
165
+ },
166
+ },
167
+ {
168
+ ...flowData,
169
+ subscription_update_confirm: {
170
+ subscription: "sub_original",
171
+ items: [{ id: false, price: "price_target" }],
172
+ },
173
+ },
174
+ {
175
+ ...flowData,
176
+ subscription_update_confirm: {
177
+ subscription: "sub_original",
178
+ items: [
179
+ { id: "si_original", price: "price_target", unknownPolicy: true },
180
+ ],
181
+ },
182
+ },
183
+ {
184
+ ...flowData,
185
+ after_completion: { type: "redirect", redirect: { return_url: 42 } },
186
+ },
187
+ ])(
188
+ "rejects unsupported input before provider dispatch: %j",
189
+ async (untrusted) => {
190
+ const f = fixture();
191
+ const options = {
192
+ ...f.options,
193
+ flowData: untrusted,
194
+ } as CreateBillingPortalSessionOptions;
195
+ await expect(
196
+ f.client.createBillingPortalSession(ctx, options),
197
+ ).rejects.toThrow();
198
+ expect(f.retrieve).not.toHaveBeenCalled();
199
+ expect(f.create).not.toHaveBeenCalled();
200
+ },
201
+ );
202
+
203
+ it.each([
204
+ 0,
205
+ -1,
206
+ 1.5,
207
+ "2",
208
+ null,
209
+ Number.NaN,
210
+ Number.POSITIVE_INFINITY,
211
+ Number.MAX_SAFE_INTEGER + 1,
212
+ ])(
213
+ "rejects an invalid target quantity before dispatch: %j",
214
+ async (quantity) => {
215
+ const f = fixture();
216
+ const options = {
217
+ ...f.options,
218
+ flowData: {
219
+ ...flowData,
220
+ subscription_update_confirm: {
221
+ subscription: "sub_original",
222
+ items: [{ id: "si_original", price: "price_target", quantity }],
223
+ },
224
+ },
225
+ } as CreateBillingPortalSessionOptions;
226
+ await expect(
227
+ f.client.createBillingPortalSession(ctx, options),
228
+ ).rejects.toThrow();
229
+ expect(f.retrieve).not.toHaveBeenCalled();
230
+ expect(f.create).not.toHaveBeenCalled();
231
+ },
232
+ );
233
+
234
+ it.each([1, 2, Number.MAX_SAFE_INTEGER])(
235
+ "forwards an explicit positive integer target quantity: %j",
236
+ async (quantity) => {
237
+ const f = fixture();
238
+ const requested: BillingPortalSubscriptionUpdateFlow = {
239
+ ...flowData,
240
+ subscription_update_confirm: {
241
+ subscription: "sub_original",
242
+ items: [{ id: "si_original", price: "price_target", quantity }],
243
+ },
244
+ };
245
+ await f.client.createBillingPortalSession(ctx, {
246
+ ...f.options,
247
+ flowData: requested,
248
+ });
249
+ expect(f.create.mock.calls[0]?.[0].flow_data).toEqual(requested);
250
+ },
251
+ );
252
+
253
+ it("rejects a partial item page even when the selected item is present", async () => {
254
+ const f = fixture();
255
+ f.retrieve.mockResolvedValue({
256
+ ...f.subscription,
257
+ items: { ...f.subscription.items, has_more: true },
258
+ });
259
+ await expect(
260
+ f.client.createBillingPortalSession(ctx, f.options),
261
+ ).rejects.toThrow();
262
+ expect(f.create).not.toHaveBeenCalled();
263
+ });
264
+
265
+ it("retains the authorized scalar snapshot while the original subscription read awaits", async () => {
266
+ const f = fixture("acct_connected");
267
+ const options: CreateBillingPortalSessionOptions = {
268
+ ...f.options,
269
+ flowData: {
270
+ ...flowData,
271
+ subscription_update_confirm: {
272
+ subscription: "sub_original",
273
+ items: [{ id: "si_original", price: "price_target" }],
274
+ },
275
+ },
276
+ };
277
+ let release!: (value: typeof f.subscription) => void;
278
+ f.retrieve.mockReturnValue(
279
+ new Promise((resolve) => {
280
+ release = resolve;
281
+ }),
282
+ );
283
+ const pending = f.client.createBillingPortalSession(ctx, options);
284
+ options.stripeAccountId = "acct_changed";
285
+ options.connectedAccountId = "acct_changed";
286
+ options.returnUrl = "https://untrusted.example/changed";
287
+ options.flowData!.subscription_update_confirm.items[0].price =
288
+ "price_changed";
289
+ release(f.subscription);
290
+ await pending;
291
+ expect(f.create.mock.calls).toEqual([
292
+ [
293
+ {
294
+ customer_account: "acct_customer",
295
+ configuration: "bpc_policy",
296
+ return_url: "https://host.example/billing",
297
+ flow_data: flowData,
298
+ },
299
+ { stripeAccount: "acct_connected" },
300
+ ],
301
+ ]);
302
+ });
303
+
304
+ it("preserves ordinary configured sessions without a subscription lookup", async () => {
305
+ const f = fixture();
306
+ const { flowData: _flowData, ...ordinary } = f.options;
307
+ await f.client.createBillingPortalSession(ctx, ordinary);
308
+ expect(f.retrieve).not.toHaveBeenCalled();
309
+ expect(f.create.mock.calls).toEqual([
310
+ [
311
+ {
312
+ customer_account: ordinary.stripeAccountId,
313
+ return_url: ordinary.returnUrl,
314
+ configuration: ordinary.configurationId,
315
+ },
316
+ ],
317
+ ]);
318
+ });
319
+
320
+ it("does not fall back to an account-wide session after a scoped read fails", async () => {
321
+ const f = fixture("acct_connected");
322
+ f.retrieve.mockRejectedValue(
323
+ new Error("Original subscription unavailable"),
324
+ );
325
+ await expect(
326
+ f.client.createBillingPortalSession(ctx, f.options),
327
+ ).rejects.toThrow();
328
+ expect(f.retrieve).toHaveBeenCalledTimes(1);
329
+ expect(f.create).not.toHaveBeenCalled();
330
+ });
331
+ });
@@ -0,0 +1,95 @@
1
+ import { z } from "zod";
2
+
3
+ const id = (prefix: string) =>
4
+ z
5
+ .string()
6
+ .max(255)
7
+ .regex(new RegExp(`^${prefix}_[A-Za-z0-9_]+$`));
8
+ const redirectUrl = z
9
+ .string()
10
+ .max(2048)
11
+ .url()
12
+ .refine((value) => {
13
+ const url = new URL(value);
14
+ return (
15
+ ["https:", "http:"].includes(url.protocol) &&
16
+ !url.username &&
17
+ !url.password
18
+ );
19
+ }, "A public HTTP(S) redirect URL is required.");
20
+ const item = z
21
+ .object({
22
+ id: id("si"),
23
+ price: id("price"),
24
+ quantity: z
25
+ .number()
26
+ .int()
27
+ .positive()
28
+ .max(Number.MAX_SAFE_INTEGER)
29
+ .optional(),
30
+ })
31
+ .strict();
32
+ const flow = z
33
+ .object({
34
+ type: z.literal("subscription_update_confirm"),
35
+ subscription_update_confirm: z
36
+ .object({
37
+ subscription: id("sub"),
38
+ items: z.tuple([item]),
39
+ })
40
+ .strict(),
41
+ after_completion: z
42
+ .object({
43
+ type: z.literal("redirect"),
44
+ redirect: z.object({ return_url: redirectUrl }).strict(),
45
+ })
46
+ .strict()
47
+ .optional(),
48
+ })
49
+ .strict();
50
+
51
+ /** One existing subscription item; host authorization and target policy remain required. */
52
+ export type BillingPortalSubscriptionUpdateFlow = z.infer<typeof flow>;
53
+
54
+ // Parsing makes a bounded scalar copy before the first provider await.
55
+ export const targetedPortalOptions = z
56
+ .object({
57
+ stripeAccountId: id("acct"),
58
+ connectedAccountId: id("acct").optional(),
59
+ configurationId: id("bpc").optional(),
60
+ returnUrl: redirectUrl,
61
+ flowData: flow,
62
+ })
63
+ .strict();
64
+
65
+ export function assertTargetedPortalSubscription(
66
+ value: unknown,
67
+ options: z.infer<typeof targetedPortalOptions>,
68
+ ): void {
69
+ const subscription = z
70
+ .object({
71
+ object: z.literal("subscription"),
72
+ id: id("sub"),
73
+ deleted: z.literal(false).optional(),
74
+ customer_account: id("acct"),
75
+ items: z.object({
76
+ has_more: z.literal(false),
77
+ data: z.array(z.object({ id: id("si") })).max(100),
78
+ }),
79
+ })
80
+ .parse(value);
81
+ const target = options.flowData.subscription_update_confirm;
82
+ if (
83
+ subscription.id !== target.subscription ||
84
+ subscription.customer_account !== options.stripeAccountId ||
85
+ subscription.items.data.filter((entry) => entry.id === target.items[0].id)
86
+ .length !== 1
87
+ )
88
+ throw new Error(
89
+ "The original subscription item does not belong to this customer account.",
90
+ );
91
+ if (subscription.items.data.length !== 1)
92
+ throw new Error(
93
+ "Billing Portal confirmation does not support multi-item subscriptions.",
94
+ );
95
+ }
@@ -73,6 +73,7 @@ export type {
73
73
  RetrieveBillingPortalConfigurationOptions,
74
74
  UpdateBillingPortalConfigurationOptions,
75
75
  CreateBillingPortalSessionOptions,
76
+ BillingPortalSubscriptionUpdateFlow,
76
77
  } from "./core/accountLinks.js";
77
78
  export type {
78
79
  AdoptProductOptions,
@@ -183,15 +183,22 @@ export type BillingPortalProps = {
183
183
  }) => ReactNode;
184
184
  };
185
185
  export function BillingPortal(props: BillingPortalProps) {
186
- const action = useWorkflowAction(async () => {
187
- const result = await props.createSession();
188
- const url = typeof result === "string" ? result : result.url;
189
- if (!url) throw new Error("Stripe did not return a portal URL.");
190
- (props.onNavigate ?? ((url) => window.location.assign(url)))(url);
191
- return true as const;
192
- }, props.scopeKey);
186
+ const action = useWorkflowAction(
187
+ async () => {
188
+ const result = await props.createSession();
189
+ const url = typeof result === "string" ? result : result.url;
190
+ if (!url) throw new Error("Stripe did not return a portal URL.");
191
+ return url;
192
+ },
193
+ props.scopeKey,
194
+ (url) => {
195
+ (props.onNavigate ?? ((nextUrl) => window.location.assign(nextUrl)))(url);
196
+ },
197
+ );
198
+ const open = async (): Promise<true | undefined> =>
199
+ (await action.run()) === undefined ? undefined : true;
193
200
  const state = {
194
- open: action.run,
201
+ open,
195
202
  isPending: action.isPending,
196
203
  error: action.error,
197
204
  };
@@ -0,0 +1,101 @@
1
+ // @vitest-environment jsdom
2
+ import { act, cleanup, render, screen } from "@testing-library/react";
3
+ import userEvent from "@testing-library/user-event";
4
+ import { afterEach, expect, it, vi } from "vitest";
5
+ import { BillingPortal, type BillingPortalProps } from "./Billing.js";
6
+ afterEach(cleanup);
7
+ type PortalState = Parameters<NonNullable<BillingPortalProps["children"]>>[0];
8
+
9
+ it.each(["scope", "unmount"])(
10
+ "does not navigate after a pending portal's %s changes",
11
+ async (change) => {
12
+ let release!: (url: string) => void;
13
+ const createSession = vi.fn(
14
+ () =>
15
+ new Promise<string>((resolve) => {
16
+ release = resolve;
17
+ }),
18
+ );
19
+ const onNavigate = vi.fn();
20
+ let state!: PortalState;
21
+ const child = (value: PortalState) => {
22
+ state = value;
23
+ return null;
24
+ };
25
+ const view = render(
26
+ <BillingPortal
27
+ scopeKey="actor-a:sub-a:target-a"
28
+ createSession={createSession}
29
+ onNavigate={onNavigate}
30
+ >
31
+ {child}
32
+ </BillingPortal>,
33
+ );
34
+ let pending!: Promise<true | undefined>;
35
+ act(() => {
36
+ pending = state.open();
37
+ });
38
+ expect(createSession).toHaveBeenCalledOnce();
39
+ if (change === "scope")
40
+ view.rerender(
41
+ <BillingPortal
42
+ scopeKey="actor-b:sub-b:target-a"
43
+ createSession={createSession}
44
+ onNavigate={onNavigate}
45
+ >
46
+ {child}
47
+ </BillingPortal>,
48
+ );
49
+ else view.unmount();
50
+ await act(async () => {
51
+ release("https://billing.stripe.test/old");
52
+ expect(await pending).toBeUndefined();
53
+ });
54
+ expect(onNavigate).not.toHaveBeenCalled();
55
+ },
56
+ );
57
+
58
+ it("navigates once on current success and preserves the true return contract", async () => {
59
+ const onNavigate = vi.fn();
60
+ let state!: PortalState;
61
+ render(
62
+ <BillingPortal
63
+ scopeKey="actor:original:target"
64
+ createSession={async () => ({
65
+ url: "https://billing.stripe.test/current",
66
+ })}
67
+ onNavigate={onNavigate}
68
+ >
69
+ {(value) => {
70
+ state = value;
71
+ return null;
72
+ }}
73
+ </BillingPortal>,
74
+ );
75
+ await act(async () => {
76
+ expect(await state.open()).toBe(true);
77
+ });
78
+ expect(onNavigate).toHaveBeenCalledExactlyOnceWith(
79
+ "https://billing.stripe.test/current",
80
+ );
81
+ });
82
+
83
+ it("keeps provider failure visible without navigating or fabricating success", async () => {
84
+ const onNavigate = vi.fn();
85
+ render(
86
+ <BillingPortal
87
+ scopeKey="actor:original:target"
88
+ createSession={async () => {
89
+ throw new Error("Confirmation unavailable");
90
+ }}
91
+ onNavigate={onNavigate}
92
+ />,
93
+ );
94
+ await userEvent.click(
95
+ screen.getByRole("button", { name: "Open Stripe Billing Portal" }),
96
+ );
97
+ expect((await screen.findByRole("alert")).textContent).toContain(
98
+ "Confirmation unavailable",
99
+ );
100
+ expect(onNavigate).not.toHaveBeenCalled();
101
+ });