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 payment for invoice |
27 | * Records a payment for the invoice. If no payment is due, the invoice is marked as `PAID`. Otherwise, the invoice is marked as `PARTIALLY PAID`. |
28 | */ |
29 | export async function main( |
30 | auth: Paypal, |
31 | invoice_id: string, |
32 | body: { |
33 | type?: "PAYPAL" | "EXTERNAL"; |
34 | payment_id?: string; |
35 | payment_date?: string; |
36 | method: |
37 | | "PAYPAL" |
38 | | "BANK_TRANSFER" |
39 | | "CASH" |
40 | | "CHECK" |
41 | | "CREDIT_CARD" |
42 | | "DEBIT_CARD" |
43 | | "WIRE_TRANSFER" |
44 | | "OTHER"; |
45 | note?: string; |
46 | amount?: { currency_code: string; value: string }; |
47 | shipping_info?: { business_name?: string } & { |
48 | name?: { |
49 | prefix?: string; |
50 | given_name?: string; |
51 | surname?: string; |
52 | middle_name?: string; |
53 | suffix?: string; |
54 | alternate_full_name?: string; |
55 | full_name?: string; |
56 | }; |
57 | address?: { |
58 | address_line_1?: string; |
59 | address_line_2?: string; |
60 | address_line_3?: string; |
61 | admin_area_4?: string; |
62 | admin_area_3?: string; |
63 | admin_area_2?: string; |
64 | admin_area_1?: string; |
65 | postal_code?: string; |
66 | country_code: string; |
67 | address_details?: { |
68 | street_number?: string; |
69 | street_name?: string; |
70 | street_type?: string; |
71 | delivery_service?: string; |
72 | building_name?: string; |
73 | sub_building?: string; |
74 | }; |
75 | }; |
76 | }; |
77 | }, |
78 | ) { |
79 | const token = await getToken(auth); |
80 | const url = new URL( |
81 | `https://api-m.paypal.com/v2/invoicing/invoices/${invoice_id}/payments`, |
82 | ); |
83 |
|
84 | const response = await fetch(url, { |
85 | method: "POST", |
86 | headers: { |
87 | "Content-Type": "application/json", |
88 | Authorization: "Bearer " + token, |
89 | }, |
90 | body: JSON.stringify(body), |
91 | }); |
92 | if (!response.ok) { |
93 | const text = await response.text(); |
94 | throw new Error(`${response.status} ${text}`); |
95 | } |
96 | return await response.json(); |
97 | } |
98 |
|