Post payment methods payment method

Updates a PaymentMethod object. A PaymentMethod must be attached a customer to be updated.

Script stripe Verified

by hugo697 ยท 10/30/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 368 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Post payment methods payment method
6
 * Updates a PaymentMethod object. A PaymentMethod must be attached a customer to be updated.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  payment_method: string,
11
  body: {
12
    billing_details?: {
13
      address?:
14
        | {
15
            city?: string;
16
            country?: string;
17
            line1?: string;
18
            line2?: string;
19
            postal_code?: string;
20
            state?: string;
21
            [k: string]: unknown;
22
          }
23
        | "";
24
      email?: string | "";
25
      name?: string | "";
26
      phone?: string | "";
27
      [k: string]: unknown;
28
    };
29
    card?: {
30
      exp_month?: number;
31
      exp_year?: number;
32
      networks?: {
33
        preferred?: "" | "cartes_bancaires" | "mastercard" | "visa";
34
        [k: string]: unknown;
35
      };
36
      [k: string]: unknown;
37
    };
38
    expand?: string[];
39
    link?: { [k: string]: unknown };
40
    metadata?: { [k: string]: string } | "";
41
    us_bank_account?: {
42
      account_holder_type?: "company" | "individual";
43
      account_type?: "checking" | "savings";
44
      [k: string]: unknown;
45
    };
46
  }
47
) {
48
  const url = new URL(
49
    `https://api.stripe.com/v1/payment_methods/${payment_method}`
50
  );
51

52
  const response = await fetch(url, {
53
    method: "POST",
54
    headers: {
55
      "Content-Type": "application/x-www-form-urlencoded",
56
      Authorization: "Bearer " + auth.token,
57
    },
58
    body: encodeParams(body),
59
  });
60
  if (!response.ok) {
61
    const text = await response.text();
62
    throw new Error(`${response.status} ${text}`);
63
  }
64
  return await response.json();
65
}
66

67
function encodeParams(o: any) {
68
  function iter(o: any, path: string) {
69
    if (Array.isArray(o)) {
70
      o.forEach(function (a) {
71
        iter(a, path + "[]");
72
      });
73
      return;
74
    }
75
    if (o !== null && typeof o === "object") {
76
      Object.keys(o).forEach(function (k) {
77
        iter(o[k], path + "[" + k + "]");
78
      });
79
      return;
80
    }
81
    data.push(path + "=" + o);
82
  }
83
  const data: string[] = [];
84
  Object.keys(o).forEach(function (k) {
85
    if (o[k] !== undefined) {
86
      iter(o[k], k);
87
    }
88
  });
89
  return new URLSearchParams(data.join("&"));
90
}
91