1 | type Stripe = { |
2 | token: string; |
3 | }; |
4 | |
5 | * Post products |
6 | * Creates a new product object. |
7 | */ |
8 | export async function main( |
9 | auth: Stripe, |
10 | body: { |
11 | active?: boolean; |
12 | default_price_data?: { |
13 | currency: string; |
14 | currency_options?: { |
15 | [k: string]: { |
16 | custom_unit_amount?: { |
17 | enabled: boolean; |
18 | maximum?: number; |
19 | minimum?: number; |
20 | preset?: number; |
21 | [k: string]: unknown; |
22 | }; |
23 | tax_behavior?: "exclusive" | "inclusive" | "unspecified"; |
24 | tiers?: { |
25 | flat_amount?: number; |
26 | flat_amount_decimal?: string; |
27 | unit_amount?: number; |
28 | unit_amount_decimal?: string; |
29 | up_to: "inf" | number; |
30 | [k: string]: unknown; |
31 | }[]; |
32 | unit_amount?: number; |
33 | unit_amount_decimal?: string; |
34 | [k: string]: unknown; |
35 | }; |
36 | }; |
37 | recurring?: { |
38 | interval: "day" | "month" | "week" | "year"; |
39 | interval_count?: number; |
40 | [k: string]: unknown; |
41 | }; |
42 | tax_behavior?: "exclusive" | "inclusive" | "unspecified"; |
43 | unit_amount?: number; |
44 | unit_amount_decimal?: string; |
45 | [k: string]: unknown; |
46 | }; |
47 | description?: string; |
48 | expand?: string[]; |
49 | features?: { name: string; [k: string]: unknown }[]; |
50 | id?: string; |
51 | images?: string[]; |
52 | metadata?: { [k: string]: string }; |
53 | name: string; |
54 | package_dimensions?: { |
55 | height: number; |
56 | length: number; |
57 | weight: number; |
58 | width: number; |
59 | [k: string]: unknown; |
60 | }; |
61 | shippable?: boolean; |
62 | statement_descriptor?: string; |
63 | tax_code?: string; |
64 | unit_label?: string; |
65 | url?: string; |
66 | } |
67 | ) { |
68 | const url = new URL(`https://api.stripe.com/v1/products`); |
69 |
|
70 | const response = await fetch(url, { |
71 | method: "POST", |
72 | headers: { |
73 | "Content-Type": "application/x-www-form-urlencoded", |
74 | Authorization: "Bearer " + auth.token, |
75 | }, |
76 | body: encodeParams(body), |
77 | }); |
78 | if (!response.ok) { |
79 | const text = await response.text(); |
80 | throw new Error(`${response.status} ${text}`); |
81 | } |
82 | return await response.json(); |
83 | } |
84 |
|
85 | function encodeParams(o: any) { |
86 | function iter(o: any, path: string) { |
87 | if (Array.isArray(o)) { |
88 | o.forEach(function (a) { |
89 | iter(a, path + "[]"); |
90 | }); |
91 | return; |
92 | } |
93 | if (o !== null && typeof o === "object") { |
94 | Object.keys(o).forEach(function (k) { |
95 | iter(o[k], path + "[" + k + "]"); |
96 | }); |
97 | return; |
98 | } |
99 | data.push(path + "=" + o); |
100 | } |
101 | const data: string[] = []; |
102 | Object.keys(o).forEach(function (k) { |
103 | if (o[k] !== undefined) { |
104 | iter(o[k], k); |
105 | } |
106 | }); |
107 | return new URLSearchParams(data.join("&")); |
108 | } |
109 |
|