@startsimpli/billing 0.4.17 → 0.4.18
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/package.json +1 -1
- package/src/utils/api.test.ts +195 -0
- package/src/utils/api.ts +6 -11
- package/src/utils/error-message.ts +111 -0
package/package.json
CHANGED
package/src/utils/api.test.ts
CHANGED
|
@@ -108,6 +108,201 @@ describe("BillingApiClient", () => {
|
|
|
108
108
|
});
|
|
109
109
|
});
|
|
110
110
|
|
|
111
|
+
// startsim-ol36d.27: a buyer saw "Checkout failed: 400" while Django was
|
|
112
|
+
// returning a specific reason. The app route proxies through
|
|
113
|
+
// proxyBillingRequest, which wraps Django's raw error text in an envelope,
|
|
114
|
+
// so the reason arrives as a JSON *string* under `details`.
|
|
115
|
+
describe("error messages carry the server's reason", () => {
|
|
116
|
+
// Captured verbatim from POST https://crochets.site/api/billing/offer-checkout/
|
|
117
|
+
// (signed in) on 2026-09-17.
|
|
118
|
+
const LIVE = {
|
|
119
|
+
bogusOfferUuid:
|
|
120
|
+
'{"error":"Billing API error","status":400,"details":"{\\"offer_id\\":[\\"Invalid or inactive offer\\"]}"}',
|
|
121
|
+
malformedOfferId:
|
|
122
|
+
'{"error":"Billing API error","status":400,"details":"{\\"offer_id\\":[\\"Must be a valid UUID.\\"]}"}',
|
|
123
|
+
emptyBody:
|
|
124
|
+
'{"error":"Billing API error","status":400,"details":"{\\"offer_id\\":[\\"This field is required.\\"],\\"success_url\\":[\\"This field is required.\\"],\\"cancel_url\\":[\\"This field is required.\\"]}"}',
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
function failWith(status: number, body: unknown) {
|
|
128
|
+
mockFetch.mockResolvedValue({
|
|
129
|
+
ok: false,
|
|
130
|
+
status,
|
|
131
|
+
json: () => Promise.resolve(body),
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function checkout() {
|
|
136
|
+
return createClient().createCheckout({
|
|
137
|
+
offerId: "bad",
|
|
138
|
+
successUrl: "x",
|
|
139
|
+
cancelUrl: "y",
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
it.each([
|
|
144
|
+
["bogus offer id", LIVE.bogusOfferUuid, "Offer id: Invalid or inactive offer"],
|
|
145
|
+
["malformed offer id", LIVE.malformedOfferId, "Offer id: Must be a valid UUID."],
|
|
146
|
+
["empty body (first field wins)", LIVE.emptyBody, "Offer id: This field is required."],
|
|
147
|
+
])("unwraps the live proxy envelope: %s", async (_name, raw, expected) => {
|
|
148
|
+
failWith(400, JSON.parse(raw));
|
|
149
|
+
await expect(checkout()).rejects.toThrow(new Error(expected));
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("unwraps the proxied non_field_errors that caused the original incident", async () => {
|
|
153
|
+
failWith(400, {
|
|
154
|
+
error: "Billing API error",
|
|
155
|
+
status: 400,
|
|
156
|
+
details: JSON.stringify({
|
|
157
|
+
non_field_errors: [
|
|
158
|
+
"BILLING_ALLOWED_REDIRECT_DOMAINS must be configured in production.",
|
|
159
|
+
],
|
|
160
|
+
}),
|
|
161
|
+
});
|
|
162
|
+
await expect(checkout()).rejects.toThrow(
|
|
163
|
+
new Error("BILLING_ALLOWED_REDIRECT_DOMAINS must be configured in production.")
|
|
164
|
+
);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it("unwraps a camelCased body inside the proxy envelope", async () => {
|
|
168
|
+
failWith(400, {
|
|
169
|
+
error: "Billing API error",
|
|
170
|
+
status: 400,
|
|
171
|
+
details: JSON.stringify({ offerId: ["Invalid or inactive offer"] }),
|
|
172
|
+
});
|
|
173
|
+
await expect(checkout()).rejects.toThrow(
|
|
174
|
+
new Error("Offer id: Invalid or inactive offer")
|
|
175
|
+
);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it.each([
|
|
179
|
+
["non_field_errors", { non_field_errors: ["Offer is not purchasable"] }],
|
|
180
|
+
["nonFieldErrors", { nonFieldErrors: ["Offer is not purchasable"] }],
|
|
181
|
+
])("reads a bare DRF %s array", async (_name, body) => {
|
|
182
|
+
failWith(400, body);
|
|
183
|
+
await expect(checkout()).rejects.toThrow(new Error("Offer is not purchasable"));
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it.each([
|
|
187
|
+
["offer_id", { offer_id: ["Invalid or inactive offer"] }],
|
|
188
|
+
["offerId", { offerId: ["Invalid or inactive offer"] }],
|
|
189
|
+
])("reads a bare DRF field error map keyed %s", async (_name, body) => {
|
|
190
|
+
failWith(400, body);
|
|
191
|
+
await expect(checkout()).rejects.toThrow(
|
|
192
|
+
new Error("Offer id: Invalid or inactive offer")
|
|
193
|
+
);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it("prefers detail over everything else", async () => {
|
|
197
|
+
failWith(400, {
|
|
198
|
+
detail: "Offer not synced",
|
|
199
|
+
non_field_errors: ["other"],
|
|
200
|
+
offer_id: ["other"],
|
|
201
|
+
});
|
|
202
|
+
await expect(checkout()).rejects.toThrow(new Error("Offer not synced"));
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("prefers non_field_errors over field errors", async () => {
|
|
206
|
+
failWith(400, {
|
|
207
|
+
offer_id: ["field message"],
|
|
208
|
+
non_field_errors: ["form message"],
|
|
209
|
+
});
|
|
210
|
+
await expect(checkout()).rejects.toThrow(new Error("form message"));
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it.each([
|
|
214
|
+
[401, { error: "Not authenticated", code: "UNAUTHORIZED" }, "Not authenticated"],
|
|
215
|
+
[503, { error: "Billing service unavailable", code: "INTERNAL_ERROR" }, "Billing service unavailable"],
|
|
216
|
+
])("surfaces an app route's {error, code} body (%i)", async (status, body, expected) => {
|
|
217
|
+
failWith(status, body);
|
|
218
|
+
await expect(checkout()).rejects.toThrow(new Error(expected));
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it("never shows the proxy's generic label or an HTML page", async () => {
|
|
222
|
+
failWith(502, {
|
|
223
|
+
error: "Billing API error",
|
|
224
|
+
status: 502,
|
|
225
|
+
details: "<html><body><h1>502 Bad Gateway</h1></body></html>",
|
|
226
|
+
});
|
|
227
|
+
await expect(checkout()).rejects.toThrow(new Error("Checkout failed: 502"));
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("never shows the proxy's network-failure label", async () => {
|
|
231
|
+
failWith(500, { error: "Internal server error", details: "fetch failed" });
|
|
232
|
+
await expect(checkout()).rejects.toThrow(new Error("Checkout failed: 500"));
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it("falls back to the status when the body is not JSON", async () => {
|
|
236
|
+
mockFetch.mockResolvedValue({
|
|
237
|
+
ok: false,
|
|
238
|
+
status: 400,
|
|
239
|
+
json: () => Promise.reject(new SyntaxError("Unexpected token <")),
|
|
240
|
+
});
|
|
241
|
+
await expect(checkout()).rejects.toThrow(new Error("Checkout failed: 400"));
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
it("falls back to the status when the body has no message", async () => {
|
|
245
|
+
failWith(400, {});
|
|
246
|
+
await expect(checkout()).rejects.toThrow(new Error("Checkout failed: 400"));
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("applies to subscribeFree", async () => {
|
|
250
|
+
failWith(400, JSON.parse(LIVE.bogusOfferUuid));
|
|
251
|
+
await expect(createClient().subscribeFree("bad")).rejects.toThrow(
|
|
252
|
+
new Error("Offer id: Invalid or inactive offer")
|
|
253
|
+
);
|
|
254
|
+
failWith(400, {});
|
|
255
|
+
await expect(createClient().subscribeFree("bad")).rejects.toThrow(
|
|
256
|
+
new Error("Free signup failed: 400")
|
|
257
|
+
);
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it("applies to createPortal", async () => {
|
|
261
|
+
failWith(400, {
|
|
262
|
+
error: "Billing API error",
|
|
263
|
+
status: 400,
|
|
264
|
+
details: JSON.stringify({ return_url: ["Enter a valid URL."] }),
|
|
265
|
+
});
|
|
266
|
+
await expect(createClient().createPortal("nope")).rejects.toThrow(
|
|
267
|
+
new Error("Return url: Enter a valid URL.")
|
|
268
|
+
);
|
|
269
|
+
failWith(400, {});
|
|
270
|
+
await expect(createClient().createPortal("nope")).rejects.toThrow(
|
|
271
|
+
new Error("Portal session failed: 400")
|
|
272
|
+
);
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it("applies to successSync", async () => {
|
|
276
|
+
failWith(400, {
|
|
277
|
+
error: "Billing API error",
|
|
278
|
+
status: 400,
|
|
279
|
+
details: JSON.stringify({ detail: "No checkout session to sync" }),
|
|
280
|
+
});
|
|
281
|
+
await expect(createClient().successSync()).rejects.toThrow(
|
|
282
|
+
new Error("No checkout session to sync")
|
|
283
|
+
);
|
|
284
|
+
failWith(500, {});
|
|
285
|
+
await expect(createClient().successSync()).rejects.toThrow(
|
|
286
|
+
new Error("Success sync failed: 500")
|
|
287
|
+
);
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it("applies to getSubscription", async () => {
|
|
291
|
+
failWith(403, {
|
|
292
|
+
error: "Billing API error",
|
|
293
|
+
status: 403,
|
|
294
|
+
details: JSON.stringify({ detail: "You are not a member of this team." }),
|
|
295
|
+
});
|
|
296
|
+
await expect(createClient().getSubscription("p")).rejects.toThrow(
|
|
297
|
+
new Error("You are not a member of this team.")
|
|
298
|
+
);
|
|
299
|
+
failWith(500, {});
|
|
300
|
+
await expect(createClient().getSubscription("p")).rejects.toThrow(
|
|
301
|
+
new Error("Failed to fetch subscription: 500")
|
|
302
|
+
);
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
|
|
111
306
|
describe("createPortal", () => {
|
|
112
307
|
it("sends POST with return_url", async () => {
|
|
113
308
|
mockFetch.mockResolvedValue({
|
package/src/utils/api.ts
CHANGED
|
@@ -12,6 +12,7 @@ import type {
|
|
|
12
12
|
SubscriptionInfo,
|
|
13
13
|
UsageMap,
|
|
14
14
|
} from "../types";
|
|
15
|
+
import { billingErrorMessage } from "./error-message";
|
|
15
16
|
|
|
16
17
|
export class BillingApiClient {
|
|
17
18
|
private config: BillingConfig;
|
|
@@ -60,9 +61,7 @@ export class BillingApiClient {
|
|
|
60
61
|
});
|
|
61
62
|
if (!resp.ok) {
|
|
62
63
|
const data = await resp.json().catch(() => ({}));
|
|
63
|
-
throw new Error(
|
|
64
|
-
data.detail ?? `Checkout failed: ${resp.status}`
|
|
65
|
-
);
|
|
64
|
+
throw new Error(billingErrorMessage(data, `Checkout failed: ${resp.status}`));
|
|
66
65
|
}
|
|
67
66
|
return resp.json();
|
|
68
67
|
}
|
|
@@ -77,7 +76,7 @@ export class BillingApiClient {
|
|
|
77
76
|
});
|
|
78
77
|
if (!resp.ok) {
|
|
79
78
|
const data = await resp.json().catch(() => ({}));
|
|
80
|
-
throw new Error(data
|
|
79
|
+
throw new Error(billingErrorMessage(data, `Free signup failed: ${resp.status}`));
|
|
81
80
|
}
|
|
82
81
|
return resp.json();
|
|
83
82
|
}
|
|
@@ -92,9 +91,7 @@ export class BillingApiClient {
|
|
|
92
91
|
});
|
|
93
92
|
if (!resp.ok) {
|
|
94
93
|
const data = await resp.json().catch(() => ({}));
|
|
95
|
-
throw new Error(
|
|
96
|
-
data.detail ?? `Portal session failed: ${resp.status}`
|
|
97
|
-
);
|
|
94
|
+
throw new Error(billingErrorMessage(data, `Portal session failed: ${resp.status}`));
|
|
98
95
|
}
|
|
99
96
|
return resp.json();
|
|
100
97
|
}
|
|
@@ -114,7 +111,7 @@ export class BillingApiClient {
|
|
|
114
111
|
}
|
|
115
112
|
if (!resp.ok) {
|
|
116
113
|
const data = await resp.json().catch(() => ({}));
|
|
117
|
-
throw new Error(data
|
|
114
|
+
throw new Error(billingErrorMessage(data, `Success sync failed: ${resp.status}`));
|
|
118
115
|
}
|
|
119
116
|
return resp.json();
|
|
120
117
|
}
|
|
@@ -150,9 +147,7 @@ export class BillingApiClient {
|
|
|
150
147
|
}
|
|
151
148
|
if (!resp.ok) {
|
|
152
149
|
const data = await resp.json().catch(() => ({}));
|
|
153
|
-
throw new Error(
|
|
154
|
-
data.detail ?? `Failed to fetch subscription: ${resp.status}`
|
|
155
|
-
);
|
|
150
|
+
throw new Error(billingErrorMessage(data, `Failed to fetch subscription: ${resp.status}`));
|
|
156
151
|
}
|
|
157
152
|
return this.normalizeSubscription(await resp.json());
|
|
158
153
|
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn a failed billing response body into one human-readable sentence.
|
|
3
|
+
*
|
|
4
|
+
* Shapes handled, in priority order:
|
|
5
|
+
* { detail: "..." } DRF's standard message
|
|
6
|
+
* { error: "Billing API error", details: "<json>" } proxyBillingRequest's envelope:
|
|
7
|
+
* Django's raw error text, as a string
|
|
8
|
+
* { non_field_errors: ["..."] } / { nonFieldErrors } first message
|
|
9
|
+
* { offer_id: ["..."] } / { offerId: [...] } "Offer id: ..." (first field wins)
|
|
10
|
+
* { error: "Not authenticated", code: "..." } app routes' own errors
|
|
11
|
+
* { error: { message: "..." } } (also app routes)
|
|
12
|
+
*
|
|
13
|
+
* Anything else (HTML error pages, the proxy's generic labels, empty bodies)
|
|
14
|
+
* yields `fallback`, so the user never sees raw JSON or markup.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// Labels proxyBillingRequest writes itself. They say that something failed,
|
|
18
|
+
// never why, so they must not be shown in place of the fallback.
|
|
19
|
+
const PROXY_LABELS = new Set(["Billing API error", "Internal server error"]);
|
|
20
|
+
|
|
21
|
+
const NON_FIELD_KEYS = new Set(["non_field_errors", "nonFieldErrors"]);
|
|
22
|
+
|
|
23
|
+
const META_KEYS = new Set([
|
|
24
|
+
"detail",
|
|
25
|
+
"details",
|
|
26
|
+
"error",
|
|
27
|
+
"message",
|
|
28
|
+
"code",
|
|
29
|
+
"status",
|
|
30
|
+
"statusCode",
|
|
31
|
+
"timestamp",
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
export function billingErrorMessage(body: unknown, fallback: string): string {
|
|
35
|
+
return messageFrom(body) ?? fallback;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function messageFrom(body: unknown): string | null {
|
|
39
|
+
if (Array.isArray(body)) return firstString(body);
|
|
40
|
+
if (!body || typeof body !== "object") return null;
|
|
41
|
+
const d = body as Record<string, unknown>;
|
|
42
|
+
|
|
43
|
+
const detail = typeof d.detail === "string" ? text(d.detail) : messageFrom(d.detail);
|
|
44
|
+
if (detail) return detail;
|
|
45
|
+
|
|
46
|
+
// The envelope carries Django's body as text. Only JSON is worth reading:
|
|
47
|
+
// plain text here is an HTML error page or a network error string.
|
|
48
|
+
if (typeof d.details === "string") {
|
|
49
|
+
const inner = messageFrom(parseJson(d.details));
|
|
50
|
+
if (inner) return inner;
|
|
51
|
+
} else {
|
|
52
|
+
const inner = messageFrom(d.details);
|
|
53
|
+
if (inner) return inner;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
for (const key of NON_FIELD_KEYS) {
|
|
57
|
+
const s = firstString(d[key]);
|
|
58
|
+
if (s) return s;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
for (const [key, val] of Object.entries(d)) {
|
|
62
|
+
if (META_KEYS.has(key) || NON_FIELD_KEYS.has(key)) continue;
|
|
63
|
+
// DRF field errors are always lists (or nested serializer maps); a scalar
|
|
64
|
+
// here is data, not an error.
|
|
65
|
+
if (!val || typeof val !== "object") continue;
|
|
66
|
+
const s = Array.isArray(val) ? firstString(val) : messageFrom(val);
|
|
67
|
+
if (s) return `${fieldLabel(key)}: ${s}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
for (const key of ["message", "error"]) {
|
|
71
|
+
const val = d[key];
|
|
72
|
+
const s = typeof val === "string" ? text(val) : messageFrom(val);
|
|
73
|
+
if (s && !PROXY_LABELS.has(s)) return s;
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function firstString(val: unknown): string | null {
|
|
79
|
+
if (typeof val === "string") return text(val);
|
|
80
|
+
if (!Array.isArray(val)) return null;
|
|
81
|
+
for (const item of val) {
|
|
82
|
+
const s = typeof item === "string" ? text(item) : messageFrom(item);
|
|
83
|
+
if (s) return s;
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function text(s: string): string | null {
|
|
89
|
+
const t = s.trim();
|
|
90
|
+
return t ? t : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function parseJson(s: string): unknown {
|
|
94
|
+
const t = s.trim();
|
|
95
|
+
if (!t.startsWith("{") && !t.startsWith("[")) return null;
|
|
96
|
+
try {
|
|
97
|
+
return JSON.parse(t);
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** "offer_id" / "offerId" → "Offer id" */
|
|
104
|
+
function fieldLabel(key: string): string {
|
|
105
|
+
const words = key
|
|
106
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
107
|
+
.replace(/_+/g, " ")
|
|
108
|
+
.trim()
|
|
109
|
+
.toLowerCase();
|
|
110
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
111
|
+
}
|