Get events

List events, going back up to 30 days. Each event data is rendered according to Stripe API version at its creation time, specified in event object api_version attribute (not according to your current Stripe API version or Stripe-Version header).

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 events
6
 * List events, going back up to 30 days. Each event data is rendered according to Stripe API version at its creation time, specified in event object api_version attribute (not according to your current Stripe API version or Stripe-Version header).
7
 */
8
export async function main(
9
  auth: Stripe,
10
  created: any,
11
  delivery_success: string | undefined,
12
  ending_before: string | undefined,
13
  expand: any,
14
  limit: string | undefined,
15
  starting_after: string | undefined,
16
  type: string | undefined,
17
  types: any
18
) {
19
  const url = new URL(`https://api.stripe.com/v1/events`);
20
  for (const [k, v] of [
21
    ["delivery_success", delivery_success],
22
    ["ending_before", ending_before],
23
    ["limit", limit],
24
    ["starting_after", starting_after],
25
    ["type", type],
26
  ]) {
27
    if (v !== undefined && v !== "") {
28
      url.searchParams.append(k, v);
29
    }
30
  }
31
  encodeParams({ created, expand, types }).forEach((v, k) => {
32
    if (v !== undefined && v !== "") {
33
      url.searchParams.append(k, v);
34
    }
35
  });
36
  const response = await fetch(url, {
37
    method: "GET",
38
    headers: {
39
      "Content-Type": "application/x-www-form-urlencoded",
40
      Authorization: "Bearer " + auth.token,
41
    },
42
    body: undefined,
43
  });
44
  if (!response.ok) {
45
    const text = await response.text();
46
    throw new Error(`${response.status} ${text}`);
47
  }
48
  return await response.json();
49
}
50

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