1 | |
2 |
|
3 | |
4 | * Cancel Subscription |
5 | * Cancel a subscription now, or at the end of the current period when `at_period_end` is set (it stays active until then and can be resumed by updating `cancel_at_period_end`). `invoice_now` and `prorate` apply to immediate cancellation only. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Stripe, |
9 | subscription_id: string, |
10 | at_period_end: boolean | undefined, |
11 | invoice_now: boolean | undefined, |
12 | prorate: boolean | undefined, |
13 | comment: string | undefined |
14 | ) { |
15 | const url = new URL( |
16 | `https://api.stripe.com/v1/subscriptions/${subscription_id}` |
17 | ) |
18 | const headers = { |
19 | Authorization: `Bearer ${auth.token}`, |
20 | Accept: "application/json", |
21 | "Stripe-Version": "2025-03-31.basil", |
22 | } |
23 |
|
24 | let response: Response |
25 | if (at_period_end) { |
26 | response = await fetch(url, { |
27 | method: "POST", |
28 | headers: { |
29 | ...headers, |
30 | "Content-Type": "application/x-www-form-urlencoded", |
31 | }, |
32 | body: toForm({ |
33 | cancel_at_period_end: true, |
34 | cancellation_details: { comment }, |
35 | }), |
36 | }) |
37 | } else { |
38 | url.search = toForm({ |
39 | invoice_now: invoice_now || undefined, |
40 | prorate: prorate || undefined, |
41 | cancellation_details: { comment }, |
42 | }).toString() |
43 | response = await fetch(url, { method: "DELETE", headers }) |
44 | } |
45 |
|
46 | if (!response.ok) { |
47 | throw new Error(`${response.status} ${await response.text()}`) |
48 | } |
49 |
|
50 | return await response.json() |
51 | } |
52 |
|
53 | |
54 | function toForm( |
55 | params: { [key: string]: any }, |
56 | prefix = "", |
57 | out = new URLSearchParams() |
58 | ) { |
59 | for (const [key, value] of Object.entries(params)) { |
60 | if (value == null || value === "") continue |
61 | const name = prefix ? `${prefix}[${key}]` : key |
62 | if (typeof value === "object") toForm(value, name, out) |
63 | else out.append(name, String(value)) |
64 | } |
65 | return out |
66 | } |
67 |
|