Post tax transactions create reversal

Partially or fully reverses a previously created Transaction.

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 tax transactions create reversal
6
 * Partially or fully reverses a previously created Transaction.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: {
11
    expand?: string[];
12
    flat_amount?: number;
13
    line_items?: {
14
      amount: number;
15
      amount_tax: number;
16
      metadata?: { [k: string]: string };
17
      original_line_item: string;
18
      quantity?: number;
19
      reference: string;
20
      [k: string]: unknown;
21
    }[];
22
    metadata?: { [k: string]: string };
23
    mode: "full" | "partial";
24
    original_transaction: string;
25
    reference: string;
26
    shipping_cost?: {
27
      amount: number;
28
      amount_tax: number;
29
      [k: string]: unknown;
30
    };
31
  }
32
) {
33
  const url = new URL(
34
    `https://api.stripe.com/v1/tax/transactions/create_reversal`
35
  );
36

37
  const response = await fetch(url, {
38
    method: "POST",
39
    headers: {
40
      "Content-Type": "application/x-www-form-urlencoded",
41
      Authorization: "Bearer " + auth.token,
42
    },
43
    body: encodeParams(body),
44
  });
45
  if (!response.ok) {
46
    const text = await response.text();
47
    throw new Error(`${response.status} ${text}`);
48
  }
49
  return await response.json();
50
}
51

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