Post shipping rates

Creates a new shipping rate object.

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 shipping rates
6
 * Creates a new shipping rate object.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: {
11
    delivery_estimate?: {
12
      maximum?: {
13
        unit: "business_day" | "day" | "hour" | "month" | "week";
14
        value: number;
15
        [k: string]: unknown;
16
      };
17
      minimum?: {
18
        unit: "business_day" | "day" | "hour" | "month" | "week";
19
        value: number;
20
        [k: string]: unknown;
21
      };
22
      [k: string]: unknown;
23
    };
24
    display_name: string;
25
    expand?: string[];
26
    fixed_amount?: {
27
      amount: number;
28
      currency: string;
29
      currency_options?: {
30
        [k: string]: {
31
          amount: number;
32
          tax_behavior?: "exclusive" | "inclusive" | "unspecified";
33
          [k: string]: unknown;
34
        };
35
      };
36
      [k: string]: unknown;
37
    };
38
    metadata?: { [k: string]: string };
39
    tax_behavior?: "exclusive" | "inclusive" | "unspecified";
40
    tax_code?: string;
41
    type?: "fixed_amount";
42
  }
43
) {
44
  const url = new URL(`https://api.stripe.com/v1/shipping_rates`);
45

46
  const response = await fetch(url, {
47
    method: "POST",
48
    headers: {
49
      "Content-Type": "application/x-www-form-urlencoded",
50
      Authorization: "Bearer " + auth.token,
51
    },
52
    body: encodeParams(body),
53
  });
54
  if (!response.ok) {
55
    const text = await response.text();
56
    throw new Error(`${response.status} ${text}`);
57
  }
58
  return await response.json();
59
}
60

61
function encodeParams(o: any) {
62
  function iter(o: any, path: string) {
63
    if (Array.isArray(o)) {
64
      o.forEach(function (a) {
65
        iter(a, path + "[]");
66
      });
67
      return;
68
    }
69
    if (o !== null && typeof o === "object") {
70
      Object.keys(o).forEach(function (k) {
71
        iter(o[k], path + "[" + k + "]");
72
      });
73
      return;
74
    }
75
    data.push(path + "=" + o);
76
  }
77
  const data: string[] = [];
78
  Object.keys(o).forEach(function (k) {
79
    if (o[k] !== undefined) {
80
      iter(o[k], k);
81
    }
82
  });
83
  return new URLSearchParams(data.join("&"));
84
}
85