1 | type Stripe = { |
2 | token: string; |
3 | }; |
4 | |
5 | * Get invoices |
6 | * You can list all invoices, or list the invoices for a specific customer. The invoices are returned sorted by creation date, with the most recently created invoices appearing first. |
7 | */ |
8 | export async function main( |
9 | auth: Stripe, |
10 | collection_method: "charge_automatically" | "send_invoice" | undefined, |
11 | created: any, |
12 | customer: string | undefined, |
13 | due_date: any, |
14 | ending_before: string | undefined, |
15 | expand: any, |
16 | limit: string | undefined, |
17 | starting_after: string | undefined, |
18 | status: "draft" | "open" | "paid" | "uncollectible" | "void" | undefined, |
19 | subscription: string | undefined |
20 | ) { |
21 | const url = new URL(`https://api.stripe.com/v1/invoices`); |
22 | for (const [k, v] of [ |
23 | ["collection_method", collection_method], |
24 | ["customer", customer], |
25 | ["ending_before", ending_before], |
26 | ["limit", limit], |
27 | ["starting_after", starting_after], |
28 | ["status", status], |
29 | ["subscription", subscription], |
30 | ]) { |
31 | if (v !== undefined && v !== "") { |
32 | url.searchParams.append(k, v); |
33 | } |
34 | } |
35 | encodeParams({ created, due_date, expand }).forEach((v, k) => { |
36 | if (v !== undefined && v !== "") { |
37 | url.searchParams.append(k, v); |
38 | } |
39 | }); |
40 | const response = await fetch(url, { |
41 | method: "GET", |
42 | headers: { |
43 | "Content-Type": "application/x-www-form-urlencoded", |
44 | Authorization: "Bearer " + auth.token, |
45 | }, |
46 | body: undefined, |
47 | }); |
48 | if (!response.ok) { |
49 | const text = await response.text(); |
50 | throw new Error(`${response.status} ${text}`); |
51 | } |
52 | return await response.json(); |
53 | } |
54 |
|
55 | function encodeParams(o: any) { |
56 | function iter(o: any, path: string) { |
57 | if (Array.isArray(o)) { |
58 | o.forEach(function (a) { |
59 | iter(a, path + "[]"); |
60 | }); |
61 | return; |
62 | } |
63 | if (o !== null && typeof o === "object") { |
64 | Object.keys(o).forEach(function (k) { |
65 | iter(o[k], path + "[" + k + "]"); |
66 | }); |
67 | return; |
68 | } |
69 | data.push(path + "=" + o); |
70 | } |
71 | const data: string[] = []; |
72 | Object.keys(o).forEach(function (k) { |
73 | if (o[k] !== undefined) { |
74 | iter(o[k], k); |
75 | } |
76 | }); |
77 | return new URLSearchParams(data.join("&")); |
78 | } |
79 |
|