1 | type Stripe = { |
2 | token: string; |
3 | }; |
4 | |
5 | * Post promotion codes promotion code |
6 | * Updates the specified promotion code by setting the values of the parameters passed. Most fields are, by design, not editable. |
7 | */ |
8 | export async function main( |
9 | auth: Stripe, |
10 | promotion_code: string, |
11 | body: { |
12 | active?: boolean; |
13 | expand?: string[]; |
14 | metadata?: { [k: string]: string } | ""; |
15 | restrictions?: { |
16 | currency_options?: { |
17 | [k: string]: { minimum_amount?: number; [k: string]: unknown }; |
18 | }; |
19 | [k: string]: unknown; |
20 | }; |
21 | } |
22 | ) { |
23 | const url = new URL( |
24 | `https://api.stripe.com/v1/promotion_codes/${promotion_code}` |
25 | ); |
26 |
|
27 | const response = await fetch(url, { |
28 | method: "POST", |
29 | headers: { |
30 | "Content-Type": "application/x-www-form-urlencoded", |
31 | Authorization: "Bearer " + auth.token, |
32 | }, |
33 | body: encodeParams(body), |
34 | }); |
35 | if (!response.ok) { |
36 | const text = await response.text(); |
37 | throw new Error(`${response.status} ${text}`); |
38 | } |
39 | return await response.json(); |
40 | } |
41 |
|
42 | function encodeParams(o: any) { |
43 | function iter(o: any, path: string) { |
44 | if (Array.isArray(o)) { |
45 | o.forEach(function (a) { |
46 | iter(a, path + "[]"); |
47 | }); |
48 | return; |
49 | } |
50 | if (o !== null && typeof o === "object") { |
51 | Object.keys(o).forEach(function (k) { |
52 | iter(o[k], path + "[" + k + "]"); |
53 | }); |
54 | return; |
55 | } |
56 | data.push(path + "=" + o); |
57 | } |
58 | const data: string[] = []; |
59 | Object.keys(o).forEach(function (k) { |
60 | if (o[k] !== undefined) { |
61 | iter(o[k], k); |
62 | } |
63 | }); |
64 | return new URLSearchParams(data.join("&")); |
65 | } |
66 |
|