0
Get checkout sessions
One script reply has been approved by the moderators Verified

Returns a list of Checkout Sessions.

Created by hugo697 188 days ago Viewed 5572 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 188 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Get checkout sessions
6
 * Returns a list of Checkout Sessions.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  created: any,
11
  customer: string | undefined,
12
  customer_details: any,
13
  ending_before: string | undefined,
14
  expand: any,
15
  limit: string | undefined,
16
  payment_intent: string | undefined,
17
  payment_link: string | undefined,
18
  starting_after: string | undefined,
19
  status: "complete" | "expired" | "open" | undefined,
20
  subscription: string | undefined
21
) {
22
  const url = new URL(`https://api.stripe.com/v1/checkout/sessions`);
23
  for (const [k, v] of [
24
    ["customer", customer],
25
    ["ending_before", ending_before],
26
    ["limit", limit],
27
    ["payment_intent", payment_intent],
28
    ["payment_link", payment_link],
29
    ["starting_after", starting_after],
30
    ["status", status],
31
    ["subscription", subscription],
32
  ]) {
33
    if (v !== undefined && v !== "") {
34
      url.searchParams.append(k, v);
35
    }
36
  }
37
  encodeParams({ created, customer_details, expand }).forEach((v, k) => {
38
    if (v !== undefined && v !== "") {
39
      url.searchParams.append(k, v);
40
    }
41
  });
42
  const response = await fetch(url, {
43
    method: "GET",
44
    headers: {
45
      "Content-Type": "application/x-www-form-urlencoded",
46
      Authorization: "Bearer " + auth.token,
47
    },
48
    body: undefined,
49
  });
50
  if (!response.ok) {
51
    const text = await response.text();
52
    throw new Error(`${response.status} ${text}`);
53
  }
54
  return await response.json();
55
}
56

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