Get subscription schedules

Retrieves the list of your subscription schedules.

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

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