0

Get invoiceitems

by
Published Oct 30, 2023

Returns a list of your invoice items. Invoice items are returned sorted by creation date, with the most recently created invoice items appearing first.

Script stripe Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 398 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Get invoiceitems
6
 * Returns a list of your invoice items. Invoice items are returned sorted by creation date, with the most recently created invoice items appearing first.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  created: any,
11
  customer: string | undefined,
12
  ending_before: string | undefined,
13
  expand: any,
14
  invoice: string | undefined,
15
  limit: string | undefined,
16
  pending: string | undefined,
17
  starting_after: string | undefined
18
) {
19
  const url = new URL(`https://api.stripe.com/v1/invoiceitems`);
20
  for (const [k, v] of [
21
    ["customer", customer],
22
    ["ending_before", ending_before],
23
    ["invoice", invoice],
24
    ["limit", limit],
25
    ["pending", pending],
26
    ["starting_after", starting_after],
27
  ]) {
28
    if (v !== undefined && v !== "") {
29
      url.searchParams.append(k, v);
30
    }
31
  }
32
  encodeParams({ created, expand }).forEach((v, k) => {
33
    if (v !== undefined && v !== "") {
34
      url.searchParams.append(k, v);
35
    }
36
  });
37
  const response = await fetch(url, {
38
    method: "GET",
39
    headers: {
40
      "Content-Type": "application/x-www-form-urlencoded",
41
      Authorization: "Bearer " + auth.token,
42
    },
43
    body: undefined,
44
  });
45
  if (!response.ok) {
46
    const text = await response.text();
47
    throw new Error(`${response.status} ${text}`);
48
  }
49
  return await response.json();
50
}
51

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