Post plans

You can now model subscriptions more flexibly using the Prices API. It replaces the Plans API and is backwards compatible to simplify your migration.

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 plans
6
 * You can now model subscriptions more flexibly using the Prices API. It replaces the Plans API and is backwards compatible to simplify your migration.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: {
11
    active?: boolean;
12
    aggregate_usage?: "last_during_period" | "last_ever" | "max" | "sum";
13
    amount?: number;
14
    amount_decimal?: string;
15
    billing_scheme?: "per_unit" | "tiered";
16
    currency: string;
17
    expand?: string[];
18
    id?: string;
19
    interval: "day" | "month" | "week" | "year";
20
    interval_count?: number;
21
    metadata?: { [k: string]: string } | "";
22
    nickname?: string;
23
    product?:
24
      | {
25
          active?: boolean;
26
          id?: string;
27
          metadata?: { [k: string]: string };
28
          name: string;
29
          statement_descriptor?: string;
30
          tax_code?: string;
31
          unit_label?: string;
32
          [k: string]: unknown;
33
        }
34
      | string;
35
    tiers?: {
36
      flat_amount?: number;
37
      flat_amount_decimal?: string;
38
      unit_amount?: number;
39
      unit_amount_decimal?: string;
40
      up_to: "inf" | number;
41
      [k: string]: unknown;
42
    }[];
43
    tiers_mode?: "graduated" | "volume";
44
    transform_usage?: {
45
      divide_by: number;
46
      round: "down" | "up";
47
      [k: string]: unknown;
48
    };
49
    trial_period_days?: number;
50
    usage_type?: "licensed" | "metered";
51
  }
52
) {
53
  const url = new URL(`https://api.stripe.com/v1/plans`);
54

55
  const response = await fetch(url, {
56
    method: "POST",
57
    headers: {
58
      "Content-Type": "application/x-www-form-urlencoded",
59
      Authorization: "Bearer " + auth.token,
60
    },
61
    body: encodeParams(body),
62
  });
63
  if (!response.ok) {
64
    const text = await response.text();
65
    throw new Error(`${response.status} ${text}`);
66
  }
67
  return await response.json();
68
}
69

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