1 | type Stripe = { |
2 | token: string; |
3 | }; |
4 | |
5 | * Post customers customer cards |
6 | * When you create a new credit card, you must specify a customer or recipient on which to create it. |
7 |
|
8 | If the card’s owner has no default card, then the new card will become the default. |
9 | However, if the owner already has a default, then it will not change. |
10 | To change the default, you should update the customer to have a new default_source. |
11 | */ |
12 | export async function main( |
13 | auth: Stripe, |
14 | customer: string, |
15 | body: { |
16 | alipay_account?: string; |
17 | bank_account?: |
18 | | { |
19 | account_holder_name?: string; |
20 | account_holder_type?: "company" | "individual"; |
21 | account_number: string; |
22 | country: string; |
23 | currency?: string; |
24 | object?: "bank_account"; |
25 | routing_number?: string; |
26 | [k: string]: unknown; |
27 | } |
28 | | string; |
29 | card?: |
30 | | { |
31 | address_city?: string; |
32 | address_country?: string; |
33 | address_line1?: string; |
34 | address_line2?: string; |
35 | address_state?: string; |
36 | address_zip?: string; |
37 | cvc?: string; |
38 | exp_month: number; |
39 | exp_year: number; |
40 | metadata?: { [k: string]: string }; |
41 | name?: string; |
42 | number: string; |
43 | object?: "card"; |
44 | [k: string]: unknown; |
45 | } |
46 | | string; |
47 | expand?: string[]; |
48 | metadata?: { [k: string]: string }; |
49 | source?: string; |
50 | } |
51 | ) { |
52 | const url = new URL(`https://api.stripe.com/v1/customers/${customer}/cards`); |
53 |
|
54 | const response = await fetch(url, { |
55 | method: "POST", |
56 | headers: { |
57 | "Content-Type": "application/x-www-form-urlencoded", |
58 | Authorization: "Bearer " + auth.token, |
59 | }, |
60 | body: encodeParams(body), |
61 | }); |
62 | if (!response.ok) { |
63 | const text = await response.text(); |
64 | throw new Error(`${response.status} ${text}`); |
65 | } |
66 | return await response.json(); |
67 | } |
68 |
|
69 | function encodeParams(o: any) { |
70 | function iter(o: any, path: string) { |
71 | if (Array.isArray(o)) { |
72 | o.forEach(function (a) { |
73 | iter(a, path + "[]"); |
74 | }); |
75 | return; |
76 | } |
77 | if (o !== null && typeof o === "object") { |
78 | Object.keys(o).forEach(function (k) { |
79 | iter(o[k], path + "[" + k + "]"); |
80 | }); |
81 | return; |
82 | } |
83 | data.push(path + "=" + o); |
84 | } |
85 | const data: string[] = []; |
86 | Object.keys(o).forEach(function (k) { |
87 | if (o[k] !== undefined) { |
88 | iter(o[k], k); |
89 | } |
90 | }); |
91 | return new URLSearchParams(data.join("&")); |
92 | } |
93 |
|