Post payment intents intent cancel

You can cancel a PaymentIntent object when it’s in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action or, in rare cases, processing.

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 cancel
6
 * You can cancel a PaymentIntent object when it’s in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_action or, in rare cases, processing.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  intent: string,
11
  body: {
12
    cancellation_reason?:
13
      | "abandoned"
14
      | "duplicate"
15
      | "fraudulent"
16
      | "requested_by_customer";
17
    expand?: string[];
18
  }
19
) {
20
  const url = new URL(
21
    `https://api.stripe.com/v1/payment_intents/${intent}/cancel`
22
  );
23

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

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