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