1 | |
2 |
|
3 | |
4 | * Cancel Payment Intent |
5 | * Cancel a PaymentIntent in `requires_payment_method`, `requires_capture`, `requires_confirmation`, `requires_action` or `processing` status. Held funds are released. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Stripe, |
9 | payment_intent_id: string, |
10 | cancellation_reason: |
11 | | "duplicate" |
12 | | "fraudulent" |
13 | | "requested_by_customer" |
14 | | "abandoned" |
15 | | undefined |
16 | ) { |
17 | const response = await fetch( |
18 | `https://api.stripe.com/v1/payment_intents/${payment_intent_id}/cancel`, |
19 | { |
20 | method: "POST", |
21 | headers: { |
22 | Authorization: `Bearer ${auth.token}`, |
23 | "Content-Type": "application/x-www-form-urlencoded", |
24 | Accept: "application/json", |
25 | "Stripe-Version": "2025-03-31.basil", |
26 | }, |
27 | body: toForm({ cancellation_reason }), |
28 | } |
29 | ) |
30 |
|
31 | if (!response.ok) { |
32 | throw new Error(`${response.status} ${await response.text()}`) |
33 | } |
34 |
|
35 | return await response.json() |
36 | } |
37 |
|
38 | |
39 | function toForm( |
40 | params: { [key: string]: any }, |
41 | prefix = "", |
42 | out = new URLSearchParams() |
43 | ) { |
44 | for (const [key, value] of Object.entries(params)) { |
45 | if (value == null || value === "") continue |
46 | const name = prefix ? `${prefix}[${key}]` : key |
47 | if (typeof value === "object") toForm(value, name, out) |
48 | else out.append(name, String(value)) |
49 | } |
50 | return out |
51 | } |
52 |
|