1 | |
2 |
|
3 | |
4 | * Create Refund |
5 | * Refund a payment, given its `payment_intent` or `charge`. Leave `amount` empty to refund everything that remains; otherwise it's in the smallest currency unit. Set `idempotency_key` to make retries safe: Stripe returns the first result for a repeated key within 24 hours. `extra_params` passes any other documented field through as-is. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Stripe, |
9 | payment_intent: string | undefined, |
10 | charge: string | undefined, |
11 | amount: number | undefined, |
12 | reason: "duplicate" | "fraudulent" | "requested_by_customer" | undefined, |
13 | metadata: { [key: string]: string } | undefined, |
14 | idempotency_key: string | undefined, |
15 | extra_params: { [key: string]: any } | undefined |
16 | ) { |
17 | const response = await fetch(`https://api.stripe.com/v1/refunds`, { |
18 | method: "POST", |
19 | headers: { |
20 | Authorization: `Bearer ${auth.token}`, |
21 | "Content-Type": "application/x-www-form-urlencoded", |
22 | Accept: "application/json", |
23 | "Stripe-Version": "2025-03-31.basil", |
24 | ...(idempotency_key ? { "Idempotency-Key": idempotency_key } : {}), |
25 | }, |
26 | body: toForm({ |
27 | payment_intent, |
28 | charge, |
29 | amount, |
30 | reason, |
31 | metadata, |
32 | ...extra_params, |
33 | }), |
34 | }) |
35 |
|
36 | if (!response.ok) { |
37 | throw new Error(`${response.status} ${await response.text()}`) |
38 | } |
39 |
|
40 | return await response.json() |
41 | } |
42 |
|
43 | |
44 | function toForm( |
45 | params: { [key: string]: any }, |
46 | prefix = "", |
47 | out = new URLSearchParams() |
48 | ) { |
49 | for (const [key, value] of Object.entries(params)) { |
50 | if (value == null || value === "") continue |
51 | const name = prefix ? `${prefix}[${key}]` : key |
52 | if (typeof value === "object") toForm(value, name, out) |
53 | else out.append(name, String(value)) |
54 | } |
55 | return out |
56 | } |
57 |
|