Post charges charge capture

Capture the payment of an existing, uncaptured charge that was created with the capture option set to false. Uncaptured payments expire a set number of days after they are created (7 by default), after which they are marked as refunded and capture attempts will fail. Don’t use this method to capture a PaymentIntent-initiated charge. Use Capture a 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 charges charge capture
6
 * Capture the payment of an existing, uncaptured charge that was created with the capture option set to false.
7

8
Uncaptured payments expire a set number of days after they are created (7 by default), after which they are marked as refunded and capture attempts will fail.
9

10
Don’t use this method to capture a PaymentIntent-initiated charge. Use Capture a PaymentIntent.
11
 */
12
export async function main(
13
  auth: Stripe,
14
  charge: string,
15
  body: {
16
    amount?: number;
17
    application_fee?: number;
18
    application_fee_amount?: number;
19
    expand?: string[];
20
    receipt_email?: string;
21
    statement_descriptor?: string;
22
    statement_descriptor_suffix?: string;
23
    transfer_data?: { amount?: number; [k: string]: unknown };
24
    transfer_group?: string;
25
  }
26
) {
27
  const url = new URL(`https://api.stripe.com/v1/charges/${charge}/capture`);
28

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

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