0

Post invoiceitems

by
Published Oct 30, 2023

Creates an item to be added to a draft invoice (up to 250 items per invoice). If no invoice is specified, the item will be on the next invoice created for the customer specified.

Script stripe Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 398 days ago
1
type Stripe = {
2
  token: string;
3
};
4
/**
5
 * Post invoiceitems
6
 * Creates an item to be added to a draft invoice (up to 250 items per invoice). If no invoice is specified, the item will be on the next invoice created for the customer specified.
7
 */
8
export async function main(
9
  auth: Stripe,
10
  body: {
11
    amount?: number;
12
    currency?: string;
13
    customer: string;
14
    description?: string;
15
    discountable?: boolean;
16
    discounts?:
17
      | { coupon?: string; discount?: string; [k: string]: unknown }[]
18
      | "";
19
    expand?: string[];
20
    invoice?: string;
21
    metadata?: { [k: string]: string } | "";
22
    period?: { end: number; start: number; [k: string]: unknown };
23
    price?: string;
24
    price_data?: {
25
      currency: string;
26
      product: string;
27
      tax_behavior?: "exclusive" | "inclusive" | "unspecified";
28
      unit_amount?: number;
29
      unit_amount_decimal?: string;
30
      [k: string]: unknown;
31
    };
32
    quantity?: number;
33
    subscription?: string;
34
    tax_behavior?: "exclusive" | "inclusive" | "unspecified";
35
    tax_code?: string | "";
36
    tax_rates?: string[];
37
    unit_amount?: number;
38
    unit_amount_decimal?: string;
39
  }
40
) {
41
  const url = new URL(`https://api.stripe.com/v1/invoiceitems`);
42

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

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