1 | |
2 | type Paypal = { |
3 | clientId: string; |
4 | clientSecret: string; |
5 | }; |
6 |
|
7 | async function getToken(auth: Paypal): Promise<string> { |
8 | const url = new URL(`https://api-m.paypal.com/v1/oauth2/token`); |
9 | const response = await fetch(url, { |
10 | method: "POST", |
11 | headers: { |
12 | Authorization: `Basic ${btoa(`${auth.clientId}:${auth.clientSecret}`)}`, |
13 | }, |
14 | body: new URLSearchParams({ |
15 | grant_type: "client_credentials", |
16 | }), |
17 | }); |
18 | if (!response.ok) { |
19 | const text = await response.text(); |
20 | throw new Error(`Could not get token: ${response.status} ${text}`); |
21 | } |
22 | const json = await response.json(); |
23 | return json.access_token; |
24 | } |
25 | |
26 | * List plans |
27 | * Lists billing plans. |
28 | */ |
29 | export async function main( |
30 | auth: Paypal, |
31 | product_id: string | undefined, |
32 | plan_ids: string | undefined, |
33 | page_size: string | undefined, |
34 | page: string | undefined, |
35 | total_required: string | undefined, |
36 | Prefer: string, |
37 | ) { |
38 | const token = await getToken(auth); |
39 | const url = new URL(`https://api-m.paypal.com/v1/billing/plans`); |
40 | for (const [k, v] of [ |
41 | ["product_id", product_id], |
42 | ["plan_ids", plan_ids], |
43 | ["page_size", page_size], |
44 | ["page", page], |
45 | ["total_required", total_required], |
46 | ]) { |
47 | if (v !== undefined && v !== "" && k !== undefined) { |
48 | url.searchParams.append(k, v); |
49 | } |
50 | } |
51 | const response = await fetch(url, { |
52 | method: "GET", |
53 | headers: { |
54 | Prefer: Prefer, |
55 | Authorization: "Bearer " + token, |
56 | }, |
57 | body: undefined, |
58 | }); |
59 | if (!response.ok) { |
60 | const text = await response.text(); |
61 | throw new Error(`${response.status} ${text}`); |
62 | } |
63 | return await response.json(); |
64 | } |
65 |
|