0
Post customers customer sources id
One script reply has been approved by the moderators Verified

Update a specified source for a given customer.

Created by hugo697 419 days ago Viewed 9192 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 419 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Post customers customer sources id
6
 * Update a specified source for a given customer.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  customer: string,
11
  id: string,
12
  body: {
13
    account_holder_name?: string;
14
    account_holder_type?: "company" | "individual";
15
    address_city?: string;
16
    address_country?: string;
17
    address_line1?: string;
18
    address_line2?: string;
19
    address_state?: string;
20
    address_zip?: string;
21
    exp_month?: string;
22
    exp_year?: string;
23
    expand?: string[];
24
    metadata?: { [k: string]: string } | "";
25
    name?: string;
26
    owner?: {
27
      address?: {
28
        city?: string;
29
        country?: string;
30
        line1?: string;
31
        line2?: string;
32
        postal_code?: string;
33
        state?: string;
34
        [k: string]: unknown;
35
      };
36
      email?: string;
37
      name?: string;
38
      phone?: string;
39
      [k: string]: unknown;
40
    };
41
  }
42
) {
43
  const url = new URL(
44
    `https://api.stripe.com/v1/customers/${customer}/sources/${id}`
45
  );
46

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

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