Post topups

Top up the balance of an account

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 topups
6
 * Top up the balance of an account
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: {
11
    amount: number;
12
    currency: string;
13
    description?: string;
14
    expand?: string[];
15
    metadata?: { [k: string]: string } | "";
16
    source?: string;
17
    statement_descriptor?: string;
18
    transfer_group?: string;
19
  }
20
) {
21
  const url = new URL(`https://api.stripe.com/v1/topups`);
22

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

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