Post payment intents intent capture

Capture the funds of an existing uncaptured PaymentIntent when its status is requires_capture. Uncaptured PaymentIntents are cancelled a set number of days (7 by default) after their creation. Learn more about separate authorization and capture.

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 capture
6
 * Capture the funds of an existing uncaptured PaymentIntent when its status is requires_capture.
7

8
Uncaptured PaymentIntents are cancelled a set number of days (7 by default) after their creation.
9

10
Learn more about separate authorization and capture.
11
 */
12
export async function main(
13
  auth: Stripe,
14
  intent: string,
15
  body: {
16
    amount_to_capture?: number;
17
    application_fee_amount?: number;
18
    expand?: string[];
19
    final_capture?: boolean;
20
    metadata?: { [k: string]: string } | "";
21
    statement_descriptor?: string;
22
    statement_descriptor_suffix?: string;
23
    transfer_data?: { amount?: number; [k: string]: unknown };
24
  }
25
) {
26
  const url = new URL(
27
    `https://api.stripe.com/v1/payment_intents/${intent}/capture`
28
  );
29

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

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