0
Get subscription items
One script reply has been approved by the moderators Verified

Returns a list of your subscription items for a given subscription.

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

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