Post shipping rates shipping rate token

Updates an existing 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 shipping rate token
6
 * Updates an existing shipping rate object.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  shipping_rate_token: string,
11
  body: {
12
    active?: boolean;
13
    expand?: string[];
14
    fixed_amount?: {
15
      currency_options?: {
16
        [k: string]: {
17
          amount?: number;
18
          tax_behavior?: "exclusive" | "inclusive" | "unspecified";
19
          [k: string]: unknown;
20
        };
21
      };
22
      [k: string]: unknown;
23
    };
24
    metadata?: { [k: string]: string } | "";
25
    tax_behavior?: "exclusive" | "inclusive" | "unspecified";
26
  }
27
) {
28
  const url = new URL(
29
    `https://api.stripe.com/v1/shipping_rates/${shipping_rate_token}`
30
  );
31

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

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