1 | |
2 |
|
3 | |
4 | * List Invoices |
5 | * List invoices, newest first, filtered by customer, subscription, status or collection method. `created_gte`/`created_lte` take ISO 8601 date-times. Returns one page (`limit` 1-100, default 10); pass the last object's id as `starting_after` for the next page while `has_more` is true. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Stripe, |
9 | customer: string | undefined, |
10 | subscription: string | undefined, |
11 | status: "draft" | "open" | "paid" | "uncollectible" | "void" | undefined, |
12 | collection_method: "charge_automatically" | "send_invoice" | undefined, |
13 | created_gte: string | undefined, |
14 | created_lte: string | undefined, |
15 | limit: number | undefined, |
16 | starting_after: string | undefined, |
17 | ending_before: string | undefined |
18 | ) { |
19 | const url = new URL(`https://api.stripe.com/v1/invoices`) |
20 | url.search = toForm({ |
21 | customer, |
22 | subscription, |
23 | status, |
24 | collection_method, |
25 | created: { gte: ts(created_gte), lte: ts(created_lte) }, |
26 | limit, |
27 | starting_after, |
28 | ending_before, |
29 | }).toString() |
30 |
|
31 | const response = await fetch(url, { |
32 | headers: { |
33 | Authorization: `Bearer ${auth.token}`, |
34 | Accept: "application/json", |
35 | "Stripe-Version": "2025-03-31.basil", |
36 | }, |
37 | }) |
38 |
|
39 | if (!response.ok) { |
40 | throw new Error(`${response.status} ${await response.text()}`) |
41 | } |
42 |
|
43 | return await response.json() |
44 | } |
45 |
|
46 | |
47 | function toForm( |
48 | params: { [key: string]: any }, |
49 | prefix = "", |
50 | out = new URLSearchParams() |
51 | ) { |
52 | for (const [key, value] of Object.entries(params)) { |
53 | if (value == null || value === "") continue |
54 | const name = prefix ? `${prefix}[${key}]` : key |
55 | if (typeof value === "object") toForm(value, name, out) |
56 | else out.append(name, String(value)) |
57 | } |
58 | return out |
59 | } |
60 |
|
61 | const ts = (iso: string | undefined) => |
62 | iso ? Math.floor(new Date(iso).getTime() / 1000) : undefined |
63 |
|