0
Get subscriptions subscription exposed id
One script reply has been approved by the moderators Verified

Retrieves the subscription with the given ID.

Created by hugo697 188 days ago Viewed 5595 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 188 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Get subscriptions subscription exposed id
6
 * Retrieves the subscription with the given ID.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  subscription_exposed_id: string,
11
  expand: any
12
) {
13
  const url = new URL(
14
    `https://api.stripe.com/v1/subscriptions/${subscription_exposed_id}`
15
  );
16
  encodeParams({ expand }).forEach((v, k) => {
17
    if (v !== undefined && v !== "") {
18
      url.searchParams.append(k, v);
19
    }
20
  });
21
  const response = await fetch(url, {
22
    method: "GET",
23
    headers: {
24
      "Content-Type": "application/x-www-form-urlencoded",
25
      Authorization: "Bearer " + auth.token,
26
    },
27
    body: undefined,
28
  });
29
  if (!response.ok) {
30
    const text = await response.text();
31
    throw new Error(`${response.status} ${text}`);
32
  }
33
  return await response.json();
34
}
35

36
function encodeParams(o: any) {
37
  function iter(o: any, path: string) {
38
    if (Array.isArray(o)) {
39
      o.forEach(function (a) {
40
        iter(a, path + "[]");
41
      });
42
      return;
43
    }
44
    if (o !== null && typeof o === "object") {
45
      Object.keys(o).forEach(function (k) {
46
        iter(o[k], path + "[" + k + "]");
47
      });
48
      return;
49
    }
50
    data.push(path + "=" + o);
51
  }
52
  const data: string[] = [];
53
  Object.keys(o).forEach(function (k) {
54
    if (o[k] !== undefined) {
55
      iter(o[k], k);
56
    }
57
  });
58
  return new URLSearchParams(data.join("&"));
59
}
60