0
Get customers customer subscriptions
One script reply has been approved by the moderators Verified

You can see a list of the customer’s active subscriptions. Note that the 10 most recent active subscriptions are always available by default on the customer object. If you need more than those 10, you can use the limit and starting_after parameters to page through additional subscriptions.

Created by hugo697 170 days ago Viewed 3950 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 170 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Get customers customer subscriptions
6
 * You can see a list of the customer’s active subscriptions. Note that the 10 most recent active subscriptions are always available by default on the customer object. If you need more than those 10, you can use the limit and starting_after parameters to page through additional subscriptions.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  customer: string,
11
  ending_before: string | undefined,
12
  expand: any,
13
  limit: string | undefined,
14
  starting_after: string | undefined
15
) {
16
  const url = new URL(
17
    `https://api.stripe.com/v1/customers/${customer}/subscriptions`
18
  );
19
  for (const [k, v] of [
20
    ["ending_before", ending_before],
21
    ["limit", limit],
22
    ["starting_after", starting_after],
23
  ]) {
24
    if (v !== undefined && v !== "") {
25
      url.searchParams.append(k, v);
26
    }
27
  }
28
  encodeParams({ expand }).forEach((v, k) => {
29
    if (v !== undefined && v !== "") {
30
      url.searchParams.append(k, v);
31
    }
32
  });
33
  const response = await fetch(url, {
34
    method: "GET",
35
    headers: {
36
      "Content-Type": "application/x-www-form-urlencoded",
37
      Authorization: "Bearer " + auth.token,
38
    },
39
    body: undefined,
40
  });
41
  if (!response.ok) {
42
    const text = await response.text();
43
    throw new Error(`${response.status} ${text}`);
44
  }
45
  return await response.json();
46
}
47

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