0

Create Product

by
Published Oct 30, 2023

Create a product. Set `default_price_unit_amount` (smallest currency unit) and `default_price_currency` to create its default price in the same call; add a recurring interval for a subscription price. `extra_params` passes any other documented field through as-is.

Script stripe Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 2 hours ago
1
//native
2

3
/**
4
 * Create Product
5
 * Create a product. Set `default_price_unit_amount` (smallest currency unit) and `default_price_currency` to create its default price in the same call; add a recurring interval for a subscription price. `extra_params` passes any other documented field through as-is.
6
 */
7
export async function main(
8
  auth: RT.Stripe,
9
  name: string,
10
  description: string | undefined,
11
  unit_label: string | undefined,
12
  default_price_unit_amount: number | undefined,
13
  default_price_currency: string | undefined,
14
  default_price_recurring_interval:
15
    "day" | "week" | "month" | "year" | undefined,
16
  metadata: { [key: string]: string } | undefined,
17
  extra_params: { [key: string]: any } | undefined
18
) {
19
  const response = await fetch(`https://api.stripe.com/v1/products`, {
20
    method: "POST",
21
    headers: {
22
      Authorization: `Bearer ${auth.token}`,
23
      "Content-Type": "application/x-www-form-urlencoded",
24
      Accept: "application/json",
25
      "Stripe-Version": "2025-03-31.basil",
26
    },
27
    body: toForm({
28
      name,
29
      description,
30
      unit_label,
31
      default_price_data: default_price_currency
32
        ? {
33
            currency: default_price_currency,
34
            unit_amount: default_price_unit_amount,
35
            recurring: { interval: default_price_recurring_interval },
36
          }
37
        : undefined,
38
      metadata,
39
      ...extra_params,
40
    }),
41
  })
42

43
  if (!response.ok) {
44
    throw new Error(`${response.status} ${await response.text()}`)
45
  }
46

47
  return await response.json()
48
}
49

50
// Stripe takes form-encoded params with bracketed nesting: metadata[key]=v, items[0][price]=p
51
function toForm(
52
  params: { [key: string]: any },
53
  prefix = "",
54
  out = new URLSearchParams()
55
) {
56
  for (const [key, value] of Object.entries(params)) {
57
    if (value == null || value === "") continue
58
    const name = prefix ? `${prefix}[${key}]` : key
59
    if (typeof value === "object") toForm(value, name, out)
60
    else out.append(name, String(value))
61
  }
62
  return out
63
}
64

Other submissions
  • Submitted by hugo697 Typescript (fetch-only)
    Created 528 days ago
    1
    type Stripe = {
    2
      token: string;
    3
    };
    4
    /**
    5
     * Post products
    6
     * Creates a new product object.
    7
     */
    8
    export async function main(
    9
      auth: Stripe,
    10
      body: {
    11
        active?: boolean;
    12
        default_price_data?: {
    13
          currency: string;
    14
          currency_options?: {
    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
          recurring?: {
    38
            interval: "day" | "month" | "week" | "year";
    39
            interval_count?: number;
    40
            [k: string]: unknown;
    41
          };
    42
          tax_behavior?: "exclusive" | "inclusive" | "unspecified";
    43
          unit_amount?: number;
    44
          unit_amount_decimal?: string;
    45
          [k: string]: unknown;
    46
        };
    47
        description?: string;
    48
        expand?: string[];
    49
        features?: { name: string; [k: string]: unknown }[];
    50
        id?: string;
    51
        images?: string[];
    52
        metadata?: { [k: string]: string };
    53
        name: string;
    54
        package_dimensions?: {
    55
          height: number;
    56
          length: number;
    57
          weight: number;
    58
          width: number;
    59
          [k: string]: unknown;
    60
        };
    61
        shippable?: boolean;
    62
        statement_descriptor?: string;
    63
        tax_code?: string;
    64
        unit_label?: string;
    65
        url?: string;
    66
      }
    67
    ) {
    68
      const url = new URL(`https://api.stripe.com/v1/products`);
    69
    
    
    70
      const response = await fetch(url, {
    71
        method: "POST",
    72
        headers: {
    73
          "Content-Type": "application/x-www-form-urlencoded",
    74
          Authorization: "Bearer " + auth.token,
    75
        },
    76
        body: encodeParams(body),
    77
      });
    78
      if (!response.ok) {
    79
        const text = await response.text();
    80
        throw new Error(`${response.status} ${text}`);
    81
      }
    82
      return await response.json();
    83
    }
    84
    
    
    85
    function encodeParams(o: any) {
    86
      function iter(o: any, path: string) {
    87
        if (Array.isArray(o)) {
    88
          o.forEach(function (a) {
    89
            iter(a, path + "[]");
    90
          });
    91
          return;
    92
        }
    93
        if (o !== null && typeof o === "object") {
    94
          Object.keys(o).forEach(function (k) {
    95
            iter(o[k], path + "[" + k + "]");
    96
          });
    97
          return;
    98
        }
    99
        data.push(path + "=" + o);
    100
      }
    101
      const data: string[] = [];
    102
      Object.keys(o).forEach(function (k) {
    103
        if (o[k] !== undefined) {
    104
          iter(o[k], k);
    105
        }
    106
      });
    107
      return new URLSearchParams(data.join("&"));
    108
    }
    109