Post subscription items

Adds a new item to an existing subscription. No existing items will be changed or replaced.

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 subscription items
6
 * Adds a new item to an existing subscription. No existing items will be changed or replaced.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: {
11
    billing_thresholds?: { usage_gte: number; [k: string]: unknown } | "";
12
    expand?: string[];
13
    metadata?: { [k: string]: string };
14
    payment_behavior?:
15
      | "allow_incomplete"
16
      | "default_incomplete"
17
      | "error_if_incomplete"
18
      | "pending_if_incomplete";
19
    price?: string;
20
    price_data?: {
21
      currency: string;
22
      product: string;
23
      recurring: {
24
        interval: "day" | "month" | "week" | "year";
25
        interval_count?: number;
26
        [k: string]: unknown;
27
      };
28
      tax_behavior?: "exclusive" | "inclusive" | "unspecified";
29
      unit_amount?: number;
30
      unit_amount_decimal?: string;
31
      [k: string]: unknown;
32
    };
33
    proration_behavior?: "always_invoice" | "create_prorations" | "none";
34
    proration_date?: number;
35
    quantity?: number;
36
    subscription: string;
37
    tax_rates?: string[] | "";
38
  }
39
) {
40
  const url = new URL(`https://api.stripe.com/v1/subscription_items`);
41

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

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