Get treasury received debits

Returns a list of ReceivedDebits.

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
 * Get treasury received debits
6
 * Returns a list of ReceivedDebits.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  ending_before: string | undefined,
11
  expand: any,
12
  financial_account: string | undefined,
13
  limit: string | undefined,
14
  starting_after: string | undefined,
15
  status: "failed" | "succeeded" | undefined
16
) {
17
  const url = new URL(`https://api.stripe.com/v1/treasury/received_debits`);
18
  for (const [k, v] of [
19
    ["ending_before", ending_before],
20
    ["financial_account", financial_account],
21
    ["limit", limit],
22
    ["starting_after", starting_after],
23
    ["status", status],
24
  ]) {
25
    if (v !== undefined && v !== "") {
26
      url.searchParams.append(k, v);
27
    }
28
  }
29
  encodeParams({ expand }).forEach((v, k) => {
30
    if (v !== undefined && v !== "") {
31
      url.searchParams.append(k, v);
32
    }
33
  });
34
  const response = await fetch(url, {
35
    method: "GET",
36
    headers: {
37
      "Content-Type": "application/x-www-form-urlencoded",
38
      Authorization: "Bearer " + auth.token,
39
    },
40
    body: undefined,
41
  });
42
  if (!response.ok) {
43
    const text = await response.text();
44
    throw new Error(`${response.status} ${text}`);
45
  }
46
  return await response.json();
47
}
48

49
function encodeParams(o: any) {
50
  function iter(o: any, path: string) {
51
    if (Array.isArray(o)) {
52
      o.forEach(function (a) {
53
        iter(a, path + "[]");
54
      });
55
      return;
56
    }
57
    if (o !== null && typeof o === "object") {
58
      Object.keys(o).forEach(function (k) {
59
        iter(o[k], path + "[" + k + "]");
60
      });
61
      return;
62
    }
63
    data.push(path + "=" + o);
64
  }
65
  const data: string[] = [];
66
  Object.keys(o).forEach(function (k) {
67
    if (o[k] !== undefined) {
68
      iter(o[k], k);
69
    }
70
  });
71
  return new URLSearchParams(data.join("&"));
72
}
73