0
Delete customers customer cards id
One script reply has been approved by the moderators Verified

Delete a specified source for a given customer.

Created by hugo697 450 days ago Viewed 12026 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 450 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Delete customers customer cards id
6
 * Delete a specified source for a given customer.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  customer: string,
11
  id: string,
12
  body: { expand?: string[] }
13
) {
14
  const url = new URL(
15
    `https://api.stripe.com/v1/customers/${customer}/cards/${id}`
16
  );
17

18
  const response = await fetch(url, {
19
    method: "DELETE",
20
    headers: {
21
      "Content-Type": "application/x-www-form-urlencoded",
22
      Authorization: "Bearer " + auth.token,
23
    },
24
    body: encodeParams(body),
25
  });
26
  if (!response.ok) {
27
    const text = await response.text();
28
    throw new Error(`${response.status} ${text}`);
29
  }
30
  return await response.json();
31
}
32

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