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 | * Refund captured payment |
27 | * Refunds a captured payment, by ID. For a full refund, include an empty payload in the JSON request body. For a partial refund, include an amount object in the JSON request body. |
28 | */ |
29 | export async function main( |
30 | auth: Paypal, |
31 | capture_id: string, |
32 | PayPal_Request_Id: string, |
33 | Prefer: string, |
34 | PayPal_Auth_Assertion: string, |
35 | body: { |
36 | amount?: { currency_code: string; value: string }; |
37 | custom_id?: string; |
38 | invoice_id?: string; |
39 | note_to_payer?: string; |
40 | payment_instruction?: { |
41 | platform_fees?: { |
42 | amount: { currency_code: string; value: string }; |
43 | payee?: { email_address?: string; merchant_id?: string }; |
44 | }[]; |
45 | }; |
46 | }, |
47 | ) { |
48 | const token = await getToken(auth); |
49 | const url = new URL( |
50 | `https://api-m.paypal.com/v2/payments/captures/${capture_id}/refund`, |
51 | ); |
52 |
|
53 | const response = await fetch(url, { |
54 | method: "POST", |
55 | headers: { |
56 | "PayPal-Request-Id": PayPal_Request_Id, |
57 | Prefer: Prefer, |
58 | "PayPal-Auth-Assertion": PayPal_Auth_Assertion, |
59 | "Content-Type": "application/json", |
60 | Authorization: "Bearer " + token, |
61 | }, |
62 | body: JSON.stringify(body), |
63 | }); |
64 | if (!response.ok) { |
65 | const text = await response.text(); |
66 | throw new Error(`${response.status} ${text}`); |
67 | } |
68 | return await response.json(); |
69 | } |
70 |
|