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 | |
27 | * List transactions for subscription |
28 | * Lists transactions for a subscription. |
29 | */ |
30 | export async function main( |
31 | auth: Paypal, |
32 | id: string, |
33 | start_time: string | undefined, |
34 | end_time: string | undefined |
35 | ) { |
36 | const token = await getToken(auth); |
37 | const url = new URL( |
38 | `https://api-m.paypal.com/v1/billing/subscriptions/${id}/transactions` |
39 | ); |
40 | for (const [k, v] of [ |
41 | ["start_time", start_time], |
42 | ["end_time", end_time], |
43 | ]) { |
44 | if (v !== undefined && v !== "" && k !== undefined) { |
45 | url.searchParams.append(k, v); |
46 | } |
47 | } |
48 | const response = await fetch(url, { |
49 | method: "GET", |
50 | headers: { |
51 | Authorization: "Bearer " + token, |
52 | }, |
53 | body: undefined, |
54 | }); |
55 | if (!response.ok) { |
56 | const text = await response.text(); |
57 | throw new Error(`${response.status} ${text}`); |
58 | } |
59 | return await response.json(); |
60 | } |
61 |
|