1 | type Stripe = { |
2 | token: string; |
3 | }; |
4 | |
5 | * Post coupons |
6 | * You can create coupons easily via the coupon management page of the Stripe dashboard. |
7 | */ |
8 | export async function main( |
9 | auth: Stripe, |
10 | body: { |
11 | amount_off?: number; |
12 | applies_to?: { products?: string[]; [k: string]: unknown }; |
13 | currency?: string; |
14 | currency_options?: { |
15 | [k: string]: { amount_off: number; [k: string]: unknown }; |
16 | }; |
17 | duration?: "forever" | "once" | "repeating"; |
18 | duration_in_months?: number; |
19 | expand?: string[]; |
20 | id?: string; |
21 | max_redemptions?: number; |
22 | metadata?: { [k: string]: string } | ""; |
23 | name?: string; |
24 | percent_off?: number; |
25 | redeem_by?: number; |
26 | } |
27 | ) { |
28 | const url = new URL(`https://api.stripe.com/v1/coupons`); |
29 |
|
30 | const response = await fetch(url, { |
31 | method: "POST", |
32 | headers: { |
33 | "Content-Type": "application/x-www-form-urlencoded", |
34 | Authorization: "Bearer " + auth.token, |
35 | }, |
36 | body: encodeParams(body), |
37 | }); |
38 | if (!response.ok) { |
39 | const text = await response.text(); |
40 | throw new Error(`${response.status} ${text}`); |
41 | } |
42 | return await response.json(); |
43 | } |
44 |
|
45 | function encodeParams(o: any) { |
46 | function iter(o: any, path: string) { |
47 | if (Array.isArray(o)) { |
48 | o.forEach(function (a) { |
49 | iter(a, path + "[]"); |
50 | }); |
51 | return; |
52 | } |
53 | if (o !== null && typeof o === "object") { |
54 | Object.keys(o).forEach(function (k) { |
55 | iter(o[k], path + "[" + k + "]"); |
56 | }); |
57 | return; |
58 | } |
59 | data.push(path + "=" + o); |
60 | } |
61 | const data: string[] = []; |
62 | Object.keys(o).forEach(function (k) { |
63 | if (o[k] !== undefined) { |
64 | iter(o[k], k); |
65 | } |
66 | }); |
67 | return new URLSearchParams(data.join("&")); |
68 | } |
69 |
|