Get treasury transactions

Retrieves a list of Transaction objects.

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

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