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 | * Search for invoices |
27 | * Searches for and lists invoices that match search criteria. If you pass multiple criteria, the response lists invoices that match all criteria. |
28 | */ |
29 | export async function main( |
30 | auth: Paypal, |
31 | page: string | undefined, |
32 | page_size: string | undefined, |
33 | total_required: string | undefined, |
34 | body: { |
35 | recipient_email?: string; |
36 | recipient_first_name?: string; |
37 | recipient_last_name?: string; |
38 | recipient_business_name?: string; |
39 | invoice_number?: string; |
40 | status?: |
41 | | "DRAFT" |
42 | | "SENT" |
43 | | "SCHEDULED" |
44 | | "PAID" |
45 | | "MARKED_AS_PAID" |
46 | | "CANCELLED" |
47 | | "REFUNDED" |
48 | | "PARTIALLY_PAID" |
49 | | "PARTIALLY_REFUNDED" |
50 | | "MARKED_AS_REFUNDED" |
51 | | "UNPAID" |
52 | | "PAYMENT_PENDING"[]; |
53 | reference?: string; |
54 | currency_code?: string; |
55 | memo?: string; |
56 | total_amount_range?: { |
57 | lower_amount: { currency_code: string; value: string }; |
58 | upper_amount: { currency_code: string; value: string }; |
59 | }; |
60 | invoice_date_range?: { start: string; end: string }; |
61 | due_date_range?: { start: string; end: string }; |
62 | payment_date_range?: { start: string; end: string }; |
63 | creation_date_range?: { start: string; end: string }; |
64 | archived?: false | true; |
65 | fields?: string[]; |
66 | }, |
67 | ) { |
68 | const token = await getToken(auth); |
69 | const url = new URL(`https://api-m.paypal.com/v2/invoicing/search-invoices`); |
70 | for (const [k, v] of [ |
71 | ["page", page], |
72 | ["page_size", page_size], |
73 | ["total_required", total_required], |
74 | ]) { |
75 | if (v !== undefined && v !== "" && k !== undefined) { |
76 | url.searchParams.append(k, v); |
77 | } |
78 | } |
79 | const response = await fetch(url, { |
80 | method: "POST", |
81 | headers: { |
82 | "Content-Type": "application/json", |
83 | Authorization: "Bearer " + token, |
84 | }, |
85 | body: JSON.stringify(body), |
86 | }); |
87 | if (!response.ok) { |
88 | const text = await response.text(); |
89 | throw new Error(`${response.status} ${text}`); |
90 | } |
91 | return await response.json(); |
92 | } |
93 |
|