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 | * Generate QR code |
27 | * Generates a QR code for an invoice, by ID. |
28 | */ |
29 | export async function main( |
30 | auth: Paypal, |
31 | invoice_id: string, |
32 | body: { width?: number; height?: number; action?: string }, |
33 | ) { |
34 | const token = await getToken(auth); |
35 | const url = new URL( |
36 | `https://api-m.paypal.com/v2/invoicing/invoices/${invoice_id}/generate-qr-code`, |
37 | ); |
38 |
|
39 | const response = await fetch(url, { |
40 | method: "POST", |
41 | headers: { |
42 | "Content-Type": "application/json", |
43 | Authorization: "Bearer " + token, |
44 | }, |
45 | body: JSON.stringify(body), |
46 | }); |
47 | if (!response.ok) { |
48 | const text = await response.text(); |
49 | throw new Error(`${response.status} ${text}`); |
50 | } |
51 | return await response.json(); |
52 | } |
53 |
|