1 | type Stripe = { |
2 | token: string; |
3 | }; |
4 | |
5 | * Post credit notes |
6 | * Issue a credit note to adjust the amount of a finalized invoice. |
7 | */ |
8 | export async function main( |
9 | auth: Stripe, |
10 | body: { |
11 | amount?: number; |
12 | credit_amount?: number; |
13 | effective_at?: number; |
14 | expand?: string[]; |
15 | invoice: string; |
16 | lines?: { |
17 | amount?: number; |
18 | description?: string; |
19 | invoice_line_item?: string; |
20 | quantity?: number; |
21 | tax_amounts?: |
22 | | { |
23 | amount: number; |
24 | tax_rate: string; |
25 | taxable_amount: number; |
26 | [k: string]: unknown; |
27 | }[] |
28 | | ""; |
29 | tax_rates?: string[] | ""; |
30 | type: "custom_line_item" | "invoice_line_item"; |
31 | unit_amount?: number; |
32 | unit_amount_decimal?: string; |
33 | [k: string]: unknown; |
34 | }[]; |
35 | memo?: string; |
36 | metadata?: { [k: string]: string }; |
37 | out_of_band_amount?: number; |
38 | reason?: |
39 | | "duplicate" |
40 | | "fraudulent" |
41 | | "order_change" |
42 | | "product_unsatisfactory"; |
43 | refund?: string; |
44 | refund_amount?: number; |
45 | shipping_cost?: { shipping_rate?: string; [k: string]: unknown }; |
46 | } |
47 | ) { |
48 | const url = new URL(`https://api.stripe.com/v1/credit_notes`); |
49 |
|
50 | const response = await fetch(url, { |
51 | method: "POST", |
52 | headers: { |
53 | "Content-Type": "application/x-www-form-urlencoded", |
54 | Authorization: "Bearer " + auth.token, |
55 | }, |
56 | body: encodeParams(body), |
57 | }); |
58 | if (!response.ok) { |
59 | const text = await response.text(); |
60 | throw new Error(`${response.status} ${text}`); |
61 | } |
62 | return await response.json(); |
63 | } |
64 |
|
65 | function encodeParams(o: any) { |
66 | function iter(o: any, path: string) { |
67 | if (Array.isArray(o)) { |
68 | o.forEach(function (a) { |
69 | iter(a, path + "[]"); |
70 | }); |
71 | return; |
72 | } |
73 | if (o !== null && typeof o === "object") { |
74 | Object.keys(o).forEach(function (k) { |
75 | iter(o[k], path + "[" + k + "]"); |
76 | }); |
77 | return; |
78 | } |
79 | data.push(path + "=" + o); |
80 | } |
81 | const data: string[] = []; |
82 | Object.keys(o).forEach(function (k) { |
83 | if (o[k] !== undefined) { |
84 | iter(o[k], k); |
85 | } |
86 | }); |
87 | return new URLSearchParams(data.join("&")); |
88 | } |
89 |
|