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 | * Create plan |
27 | * Creates a plan that defines pricing and billing cycle details for subscriptions. |
28 | */ |
29 | export async function main( |
30 | auth: Paypal, |
31 | Prefer: string, |
32 | PayPal_Request_Id: string, |
33 | body: { |
34 | product_id: string; |
35 | name: string; |
36 | status?: "CREATED" | "INACTIVE" | "ACTIVE"; |
37 | description?: string; |
38 | billing_cycles: { |
39 | pricing_scheme?: { |
40 | version?: number; |
41 | fixed_price?: { currency_code: string; value: string }; |
42 | pricing_model?: "VOLUME" | "TIERED"; |
43 | tiers?: { |
44 | starting_quantity: string; |
45 | ending_quantity?: string; |
46 | amount: { currency_code: string; value: string }; |
47 | }[]; |
48 | create_time?: string; |
49 | update_time?: string; |
50 | }; |
51 | frequency: { |
52 | interval_unit: "DAY" | "WEEK" | "MONTH" | "YEAR"; |
53 | interval_count?: number; |
54 | }; |
55 | tenure_type: "REGULAR" | "TRIAL"; |
56 | sequence: number; |
57 | total_cycles?: number; |
58 | }[]; |
59 | payment_preferences: { |
60 | auto_bill_outstanding?: false | true; |
61 | setup_fee?: { currency_code: string; value: string }; |
62 | setup_fee_failure_action?: "CONTINUE" | "CANCEL"; |
63 | payment_failure_threshold?: number; |
64 | }; |
65 | taxes?: { percentage: string; inclusive?: false | true }; |
66 | quantity_supported?: false | true; |
67 | }, |
68 | ) { |
69 | const token = await getToken(auth); |
70 | const url = new URL(`https://api-m.paypal.com/v1/billing/plans`); |
71 |
|
72 | const response = await fetch(url, { |
73 | method: "POST", |
74 | headers: { |
75 | Prefer: Prefer, |
76 | "PayPal-Request-Id": PayPal_Request_Id, |
77 | "Content-Type": "application/json", |
78 | Authorization: "Bearer " + token, |
79 | }, |
80 | body: JSON.stringify(body), |
81 | }); |
82 | if (!response.ok) { |
83 | const text = await response.text(); |
84 | throw new Error(`${response.status} ${text}`); |
85 | } |
86 | return await response.json(); |
87 | } |
88 |
|