Post test helpers test clocks

Creates a new test clock that can be attached to new customers and quotes.

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 test helpers test clocks
6
 * Creates a new test clock that can be attached to new customers and quotes.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: { expand?: string[]; frozen_time: number; name?: string }
11
) {
12
  const url = new URL(`https://api.stripe.com/v1/test_helpers/test_clocks`);
13

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

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