Post tax rates

Creates a new tax rate.

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 rates
6
 * Creates a new tax rate.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: {
11
    active?: boolean;
12
    country?: string;
13
    description?: string;
14
    display_name: string;
15
    expand?: string[];
16
    inclusive: boolean;
17
    jurisdiction?: string;
18
    metadata?: { [k: string]: string };
19
    percentage: number;
20
    state?: string;
21
    tax_type?:
22
      | "amusement_tax"
23
      | "communications_tax"
24
      | "gst"
25
      | "hst"
26
      | "igst"
27
      | "jct"
28
      | "lease_tax"
29
      | "pst"
30
      | "qst"
31
      | "rst"
32
      | "sales_tax"
33
      | "vat";
34
  }
35
) {
36
  const url = new URL(`https://api.stripe.com/v1/tax_rates`);
37

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

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