0

Post tax settings

by
Published Oct 30, 2023

Updates Tax Settings parameters used in tax calculations. All parameters are editable but none can be removed once set.

Script stripe Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 398 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Post tax settings
6
 * Updates Tax Settings parameters used in tax calculations. All parameters are editable but none can be removed once set.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: {
11
    defaults?: {
12
      tax_behavior?: "exclusive" | "inclusive" | "inferred_by_currency";
13
      tax_code?: string;
14
      [k: string]: unknown;
15
    };
16
    expand?: string[];
17
    head_office?: {
18
      address: {
19
        city?: string;
20
        country?: string;
21
        line1?: string;
22
        line2?: string;
23
        postal_code?: string;
24
        state?: string;
25
        [k: string]: unknown;
26
      };
27
      [k: string]: unknown;
28
    };
29
  }
30
) {
31
  const url = new URL(`https://api.stripe.com/v1/tax/settings`);
32

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

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