Post terminal readers reader process payment intent

Initiates a payment flow on a Reader.

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 process payment intent
6
 * Initiates a payment flow on a Reader.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  reader: string,
11
  body: {
12
    expand?: string[];
13
    payment_intent: string;
14
    process_config?: {
15
      enable_customer_cancellation?: boolean;
16
      skip_tipping?: boolean;
17
      tipping?: { amount_eligible?: number; [k: string]: unknown };
18
      [k: string]: unknown;
19
    };
20
  }
21
) {
22
  const url = new URL(
23
    `https://api.stripe.com/v1/terminal/readers/${reader}/process_payment_intent`
24
  );
25

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

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