1 | |
2 |
|
3 | |
4 | * Create Product |
5 | * Create a product. Set `default_price_unit_amount` (smallest currency unit) and `default_price_currency` to create its default price in the same call; add a recurring interval for a subscription price. `extra_params` passes any other documented field through as-is. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Stripe, |
9 | name: string, |
10 | description: string | undefined, |
11 | unit_label: string | undefined, |
12 | default_price_unit_amount: number | undefined, |
13 | default_price_currency: string | undefined, |
14 | default_price_recurring_interval: |
15 | "day" | "week" | "month" | "year" | undefined, |
16 | metadata: { [key: string]: string } | undefined, |
17 | extra_params: { [key: string]: any } | undefined |
18 | ) { |
19 | const response = await fetch(`https://api.stripe.com/v1/products`, { |
20 | method: "POST", |
21 | headers: { |
22 | Authorization: `Bearer ${auth.token}`, |
23 | "Content-Type": "application/x-www-form-urlencoded", |
24 | Accept: "application/json", |
25 | "Stripe-Version": "2025-03-31.basil", |
26 | }, |
27 | body: toForm({ |
28 | name, |
29 | description, |
30 | unit_label, |
31 | default_price_data: default_price_currency |
32 | ? { |
33 | currency: default_price_currency, |
34 | unit_amount: default_price_unit_amount, |
35 | recurring: { interval: default_price_recurring_interval }, |
36 | } |
37 | : undefined, |
38 | metadata, |
39 | ...extra_params, |
40 | }), |
41 | }) |
42 |
|
43 | if (!response.ok) { |
44 | throw new Error(`${response.status} ${await response.text()}`) |
45 | } |
46 |
|
47 | return await response.json() |
48 | } |
49 |
|
50 | |
51 | function toForm( |
52 | params: { [key: string]: any }, |
53 | prefix = "", |
54 | out = new URLSearchParams() |
55 | ) { |
56 | for (const [key, value] of Object.entries(params)) { |
57 | if (value == null || value === "") continue |
58 | const name = prefix ? `${prefix}[${key}]` : key |
59 | if (typeof value === "object") toForm(value, name, out) |
60 | else out.append(name, String(value)) |
61 | } |
62 | return out |
63 | } |
64 |
|