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

Returns a list of PaymentMethods for a given Customer

Created by hugo697 168 days ago Viewed 3733 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 168 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Get customers customer payment methods
6
 * Returns a list of PaymentMethods for a given Customer
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
  type:
16
    | "acss_debit"
17
    | "affirm"
18
    | "afterpay_clearpay"
19
    | "alipay"
20
    | "au_becs_debit"
21
    | "bacs_debit"
22
    | "bancontact"
23
    | "blik"
24
    | "boleto"
25
    | "card"
26
    | "cashapp"
27
    | "customer_balance"
28
    | "eps"
29
    | "fpx"
30
    | "giropay"
31
    | "grabpay"
32
    | "ideal"
33
    | "klarna"
34
    | "konbini"
35
    | "link"
36
    | "oxxo"
37
    | "p24"
38
    | "paynow"
39
    | "paypal"
40
    | "pix"
41
    | "promptpay"
42
    | "revolut_pay"
43
    | "sepa_debit"
44
    | "sofort"
45
    | "swish"
46
    | "us_bank_account"
47
    | "wechat_pay"
48
    | "zip"
49
    | undefined
50
) {
51
  const url = new URL(
52
    `https://api.stripe.com/v1/customers/${customer}/payment_methods`
53
  );
54
  for (const [k, v] of [
55
    ["ending_before", ending_before],
56
    ["limit", limit],
57
    ["starting_after", starting_after],
58
    ["type", type],
59
  ]) {
60
    if (v !== undefined && v !== "") {
61
      url.searchParams.append(k, v);
62
    }
63
  }
64
  encodeParams({ expand }).forEach((v, k) => {
65
    if (v !== undefined && v !== "") {
66
      url.searchParams.append(k, v);
67
    }
68
  });
69
  const response = await fetch(url, {
70
    method: "GET",
71
    headers: {
72
      "Content-Type": "application/x-www-form-urlencoded",
73
      Authorization: "Bearer " + auth.token,
74
    },
75
    body: undefined,
76
  });
77
  if (!response.ok) {
78
    const text = await response.text();
79
    throw new Error(`${response.status} ${text}`);
80
  }
81
  return await response.json();
82
}
83

84
function encodeParams(o: any) {
85
  function iter(o: any, path: string) {
86
    if (Array.isArray(o)) {
87
      o.forEach(function (a) {
88
        iter(a, path + "[]");
89
      });
90
      return;
91
    }
92
    if (o !== null && typeof o === "object") {
93
      Object.keys(o).forEach(function (k) {
94
        iter(o[k], path + "[" + k + "]");
95
      });
96
      return;
97
    }
98
    data.push(path + "=" + o);
99
  }
100
  const data: string[] = [];
101
  Object.keys(o).forEach(function (k) {
102
    if (o[k] !== undefined) {
103
      iter(o[k], k);
104
    }
105
  });
106
  return new URLSearchParams(data.join("&"));
107
}
108