1 | type Stripe = { |
2 | token: string; |
3 | }; |
4 | |
5 | * Get credit notes preview |
6 | * Get a preview of a credit note without creating it. |
7 | */ |
8 | export async function main( |
9 | auth: Stripe, |
10 | amount: string | undefined, |
11 | credit_amount: string | undefined, |
12 | effective_at: string | undefined, |
13 | expand: any, |
14 | invoice: string | undefined, |
15 | lines: any, |
16 | memo: string | undefined, |
17 | metadata: any, |
18 | out_of_band_amount: string | undefined, |
19 | reason: |
20 | | "duplicate" |
21 | | "fraudulent" |
22 | | "order_change" |
23 | | "product_unsatisfactory" |
24 | | undefined, |
25 | refund: string | undefined, |
26 | refund_amount: string | undefined, |
27 | shipping_cost: any |
28 | ) { |
29 | const url = new URL(`https://api.stripe.com/v1/credit_notes/preview`); |
30 | for (const [k, v] of [ |
31 | ["amount", amount], |
32 | ["credit_amount", credit_amount], |
33 | ["effective_at", effective_at], |
34 | ["invoice", invoice], |
35 | ["memo", memo], |
36 | ["out_of_band_amount", out_of_band_amount], |
37 | ["reason", reason], |
38 | ["refund", refund], |
39 | ["refund_amount", refund_amount], |
40 | ]) { |
41 | if (v !== undefined && v !== "") { |
42 | url.searchParams.append(k, v); |
43 | } |
44 | } |
45 | encodeParams({ expand, lines, metadata, shipping_cost }).forEach((v, k) => { |
46 | if (v !== undefined && v !== "") { |
47 | url.searchParams.append(k, v); |
48 | } |
49 | }); |
50 | const response = await fetch(url, { |
51 | method: "GET", |
52 | headers: { |
53 | "Content-Type": "application/x-www-form-urlencoded", |
54 | Authorization: "Bearer " + auth.token, |
55 | }, |
56 | body: undefined, |
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 |
|