Get balance

Retrieves the current account balance, based on the authentication that was used to make the request. For a sample request, see Accounting for negative balances.

Script stripe Verified

by hugo697 ยท 10/30/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 354 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Get balance
6
 * Retrieves the current account balance, based on the authentication that was used to make the request.
7
 For a sample request, see Accounting for negative balances.
8
 */
9
export async function main(auth: Stripe, expand: any) {
10
  const url = new URL(`https://api.stripe.com/v1/balance`);
11
  encodeParams({ expand }).forEach((v, k) => {
12
    if (v !== undefined && v !== "") {
13
      url.searchParams.append(k, v);
14
    }
15
  });
16
  const response = await fetch(url, {
17
    method: "GET",
18
    headers: {
19
      "Content-Type": "application/x-www-form-urlencoded",
20
      Authorization: "Bearer " + auth.token,
21
    },
22
    body: undefined,
23
  });
24
  if (!response.ok) {
25
    const text = await response.text();
26
    throw new Error(`${response.status} ${text}`);
27
  }
28
  return await response.json();
29
}
30

31
function encodeParams(o: any) {
32
  function iter(o: any, path: string) {
33
    if (Array.isArray(o)) {
34
      o.forEach(function (a) {
35
        iter(a, path + "[]");
36
      });
37
      return;
38
    }
39
    if (o !== null && typeof o === "object") {
40
      Object.keys(o).forEach(function (k) {
41
        iter(o[k], path + "[" + k + "]");
42
      });
43
      return;
44
    }
45
    data.push(path + "=" + o);
46
  }
47
  const data: string[] = [];
48
  Object.keys(o).forEach(function (k) {
49
    if (o[k] !== undefined) {
50
      iter(o[k], k);
51
    }
52
  });
53
  return new URLSearchParams(data.join("&"));
54
}
55