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 | * Record refund for invoice |
27 | * Records a refund for the invoice. If all payments are refunded, the invoice is marked as `REFUNDED`. Otherwise, the invoice is marked as `PARTIALLY REFUNDED`. |
28 | */ |
29 | export async function main( |
30 | auth: Paypal, |
31 | invoice_id: string, |
32 | body: { |
33 | type?: "PAYPAL" | "EXTERNAL"; |
34 | refund_id?: string; |
35 | refund_date?: string; |
36 | amount?: { currency_code: string; value: string }; |
37 | method: |
38 | | "PAYPAL" |
39 | | "BANK_TRANSFER" |
40 | | "CASH" |
41 | | "CHECK" |
42 | | "CREDIT_CARD" |
43 | | "DEBIT_CARD" |
44 | | "WIRE_TRANSFER" |
45 | | "OTHER"; |
46 | }, |
47 | ) { |
48 | const token = await getToken(auth); |
49 | const url = new URL( |
50 | `https://api-m.paypal.com/v2/invoicing/invoices/${invoice_id}/refunds`, |
51 | ); |
52 |
|
53 | const response = await fetch(url, { |
54 | method: "POST", |
55 | headers: { |
56 | "Content-Type": "application/json", |
57 | Authorization: "Bearer " + token, |
58 | }, |
59 | body: JSON.stringify(body), |
60 | }); |
61 | if (!response.ok) { |
62 | const text = await response.text(); |
63 | throw new Error(`${response.status} ${text}`); |
64 | } |
65 | return await response.json(); |
66 | } |
67 |
|