Post terminal readers reader set reader display

Sets reader display to show cart details.

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 terminal readers reader set reader display
6
 * Sets reader display to show cart details.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  reader: string,
11
  body: {
12
    cart?: {
13
      currency: string;
14
      line_items: {
15
        amount: number;
16
        description: string;
17
        quantity: number;
18
        [k: string]: unknown;
19
      }[];
20
      tax?: number;
21
      total: number;
22
      [k: string]: unknown;
23
    };
24
    expand?: string[];
25
    type: "cart";
26
  }
27
) {
28
  const url = new URL(
29
    `https://api.stripe.com/v1/terminal/readers/${reader}/set_reader_display`
30
  );
31

32
  const response = await fetch(url, {
33
    method: "POST",
34
    headers: {
35
      "Content-Type": "application/x-www-form-urlencoded",
36
      Authorization: "Bearer " + auth.token,
37
    },
38
    body: encodeParams(body),
39
  });
40
  if (!response.ok) {
41
    const text = await response.text();
42
    throw new Error(`${response.status} ${text}`);
43
  }
44
  return await response.json();
45
}
46

47
function encodeParams(o: any) {
48
  function iter(o: any, path: string) {
49
    if (Array.isArray(o)) {
50
      o.forEach(function (a) {
51
        iter(a, path + "[]");
52
      });
53
      return;
54
    }
55
    if (o !== null && typeof o === "object") {
56
      Object.keys(o).forEach(function (k) {
57
        iter(o[k], path + "[" + k + "]");
58
      });
59
      return;
60
    }
61
    data.push(path + "=" + o);
62
  }
63
  const data: string[] = [];
64
  Object.keys(o).forEach(function (k) {
65
    if (o[k] !== undefined) {
66
      iter(o[k], k);
67
    }
68
  });
69
  return new URLSearchParams(data.join("&"));
70
}
71