Post charges charge refund

When you create a new refund, you must specify either a Charge or a PaymentIntent object.

Script stripe Verified

by hugo697 ยท 10/30/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 368 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Post charges charge refund
6
 * When you create a new refund, you must specify either a Charge or a PaymentIntent object.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  charge: string,
11
  body: {
12
    amount?: number;
13
    expand?: string[];
14
    instructions_email?: string;
15
    metadata?: { [k: string]: string } | "";
16
    payment_intent?: string;
17
    reason?: "duplicate" | "fraudulent" | "requested_by_customer";
18
    refund_application_fee?: boolean;
19
    reverse_transfer?: boolean;
20
  }
21
) {
22
  const url = new URL(`https://api.stripe.com/v1/charges/${charge}/refund`);
23

24
  const response = await fetch(url, {
25
    method: "POST",
26
    headers: {
27
      "Content-Type": "application/x-www-form-urlencoded",
28
      Authorization: "Bearer " + auth.token,
29
    },
30
    body: encodeParams(body),
31
  });
32
  if (!response.ok) {
33
    const text = await response.text();
34
    throw new Error(`${response.status} ${text}`);
35
  }
36
  return await response.json();
37
}
38

39
function encodeParams(o: any) {
40
  function iter(o: any, path: string) {
41
    if (Array.isArray(o)) {
42
      o.forEach(function (a) {
43
        iter(a, path + "[]");
44
      });
45
      return;
46
    }
47
    if (o !== null && typeof o === "object") {
48
      Object.keys(o).forEach(function (k) {
49
        iter(o[k], path + "[" + k + "]");
50
      });
51
      return;
52
    }
53
    data.push(path + "=" + o);
54
  }
55
  const data: string[] = [];
56
  Object.keys(o).forEach(function (k) {
57
    if (o[k] !== undefined) {
58
      iter(o[k], k);
59
    }
60
  });
61
  return new URLSearchParams(data.join("&"));
62
}
63