Post payment intents intent increment authorization

Perform an incremental authorization on an eligible PaymentIntent.

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 payment intents intent increment authorization
6
 * Perform an incremental authorization on an eligible
7
PaymentIntent.
8
 */
9
export async function main(
10
  auth: Stripe,
11
  intent: string,
12
  body: {
13
    amount: number;
14
    application_fee_amount?: number;
15
    description?: string;
16
    expand?: string[];
17
    metadata?: { [k: string]: string };
18
    statement_descriptor?: string;
19
    transfer_data?: { amount?: number; [k: string]: unknown };
20
  }
21
) {
22
  const url = new URL(
23
    `https://api.stripe.com/v1/payment_intents/${intent}/increment_authorization`
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