1 | |
2 |
|
3 | |
4 | * Create Invoice |
5 | * Create a draft invoice for a customer; add lines with Create Invoice Item (passing `invoice`), then finalize it. `send_invoice` collection needs `days_until_due`. Pending invoice items created without an `invoice` are only pulled in when `include_pending_invoice_items` is set. `auto_advance` lets Stripe finalize and collect it automatically. `extra_params` passes any other documented field through as-is. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Stripe, |
9 | customer: string, |
10 | collection_method: "charge_automatically" | "send_invoice" | undefined, |
11 | days_until_due: number | undefined, |
12 | description: string | undefined, |
13 | subscription: string | undefined, |
14 | default_payment_method: string | undefined, |
15 | include_pending_invoice_items: boolean | undefined, |
16 | auto_advance: boolean | undefined, |
17 | metadata: { [key: string]: string } | undefined, |
18 | extra_params: { [key: string]: any } | undefined |
19 | ) { |
20 | const response = await fetch(`https://api.stripe.com/v1/invoices`, { |
21 | method: "POST", |
22 | headers: { |
23 | Authorization: `Bearer ${auth.token}`, |
24 | "Content-Type": "application/x-www-form-urlencoded", |
25 | Accept: "application/json", |
26 | "Stripe-Version": "2025-03-31.basil", |
27 | }, |
28 | body: toForm({ |
29 | customer, |
30 | collection_method, |
31 | days_until_due, |
32 | description, |
33 | subscription, |
34 | default_payment_method, |
35 | pending_invoice_items_behavior: include_pending_invoice_items |
36 | ? "include" |
37 | : undefined, |
38 | auto_advance: auto_advance || undefined, |
39 | metadata, |
40 | ...extra_params, |
41 | }), |
42 | }) |
43 |
|
44 | if (!response.ok) { |
45 | throw new Error(`${response.status} ${await response.text()}`) |
46 | } |
47 |
|
48 | return await response.json() |
49 | } |
50 |
|
51 | |
52 | function toForm( |
53 | params: { [key: string]: any }, |
54 | prefix = "", |
55 | out = new URLSearchParams() |
56 | ) { |
57 | for (const [key, value] of Object.entries(params)) { |
58 | if (value == null || value === "") continue |
59 | const name = prefix ? `${prefix}[${key}]` : key |
60 | if (typeof value === "object") toForm(value, name, out) |
61 | else out.append(name, String(value)) |
62 | } |
63 | return out |
64 | } |
65 |
|