0

Post prices price

by
Published Oct 30, 2023

Updates the specified price by setting the values of the parameters passed. Any parameters not provided are left unchanged.

Script stripe Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 399 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Post prices price
6
 * Updates the specified price by setting the values of the parameters passed. Any parameters not provided are left unchanged.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  price: string,
11
  body: {
12
    active?: boolean;
13
    currency_options?:
14
      | {
15
          [k: string]: {
16
            custom_unit_amount?: {
17
              enabled: boolean;
18
              maximum?: number;
19
              minimum?: number;
20
              preset?: number;
21
              [k: string]: unknown;
22
            };
23
            tax_behavior?: "exclusive" | "inclusive" | "unspecified";
24
            tiers?: {
25
              flat_amount?: number;
26
              flat_amount_decimal?: string;
27
              unit_amount?: number;
28
              unit_amount_decimal?: string;
29
              up_to: "inf" | number;
30
              [k: string]: unknown;
31
            }[];
32
            unit_amount?: number;
33
            unit_amount_decimal?: string;
34
            [k: string]: unknown;
35
          };
36
        }
37
      | "";
38
    expand?: string[];
39
    lookup_key?: string;
40
    metadata?: { [k: string]: string } | "";
41
    nickname?: string;
42
    tax_behavior?: "exclusive" | "inclusive" | "unspecified";
43
    transfer_lookup_key?: boolean;
44
  }
45
) {
46
  const url = new URL(`https://api.stripe.com/v1/prices/${price}`);
47

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

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