Get products

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

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 products
6
 * Returns a list of your products. The products are returned sorted by creation date, with the most recently created products appearing first.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  active: string | undefined,
11
  created: any,
12
  ending_before: string | undefined,
13
  expand: any,
14
  ids: any,
15
  limit: string | undefined,
16
  shippable: string | undefined,
17
  starting_after: string | undefined,
18
  url: string | undefined
19
) {
20
  const url_ = new URL(`https://api.stripe.com/v1/products`);
21
  for (const [k, v] of [
22
    ["active", active],
23
    ["ending_before", ending_before],
24
    ["limit", limit],
25
    ["shippable", shippable],
26
    ["starting_after", starting_after],
27
    ["url", url],
28
  ]) {
29
    if (v !== undefined && v !== "") {
30
      url_.searchParams.append(k, v);
31
    }
32
  }
33
  encodeParams({ created, expand, ids }).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