1 | |
2 |
|
3 | |
4 | * Create Customer |
5 | * Create a customer. `payment_method` attaches an existing PaymentMethod id. `extra_params` passes any other documented field through as-is. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Stripe, |
9 | name: string | undefined, |
10 | email: string | undefined, |
11 | phone: string | undefined, |
12 | description: string | undefined, |
13 | address: |
14 | | { |
15 | line1?: string |
16 | line2?: string |
17 | city?: string |
18 | state?: string |
19 | postal_code?: string |
20 | country?: string |
21 | } |
22 | | undefined, |
23 | payment_method: string | undefined, |
24 | metadata: { [key: string]: string } | undefined, |
25 | extra_params: { [key: string]: any } | undefined |
26 | ) { |
27 | const response = await fetch(`https://api.stripe.com/v1/customers`, { |
28 | method: "POST", |
29 | headers: { |
30 | Authorization: `Bearer ${auth.token}`, |
31 | "Content-Type": "application/x-www-form-urlencoded", |
32 | Accept: "application/json", |
33 | "Stripe-Version": "2025-03-31.basil", |
34 | }, |
35 | body: toForm({ |
36 | name, |
37 | email, |
38 | phone, |
39 | description, |
40 | address, |
41 | payment_method, |
42 | metadata, |
43 | ...extra_params, |
44 | }), |
45 | }) |
46 |
|
47 | if (!response.ok) { |
48 | throw new Error(`${response.status} ${await response.text()}`) |
49 | } |
50 |
|
51 | return await response.json() |
52 | } |
53 |
|
54 | |
55 | function toForm( |
56 | params: { [key: string]: any }, |
57 | prefix = "", |
58 | out = new URLSearchParams() |
59 | ) { |
60 | for (const [key, value] of Object.entries(params)) { |
61 | if (value == null || value === "") continue |
62 | const name = prefix ? `${prefix}[${key}]` : key |
63 | if (typeof value === "object") toForm(value, name, out) |
64 | else out.append(name, String(value)) |
65 | } |
66 | return out |
67 | } |
68 |
|