0

Get invoices invoice lines

by
Published Oct 30, 2023

When retrieving an invoice, you’ll get a lines property containing the total count of line items and the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items.

Script stripe
  • Submitted by hugo697 Typescript (fetch-only)
    Created 534 days ago
    1
    type Stripe = {
    2
      token: string;
    3
    };
    4
    /**
    5
     * Get invoices invoice lines
    6
     * When retrieving an invoice, you’ll get a lines property containing the total count of line items and the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items.
    7
     */
    8
    export async function main(
    9
      auth: Stripe,
    10
      invoice: string,
    11
      ending_before: string | undefined,
    12
      expand: any,
    13
      limit: string | undefined,
    14
      starting_after: string | undefined
    15
    ) {
    16
      const url = new URL(`https://api.stripe.com/v1/invoices/${invoice}/lines`);
    17
      for (const [k, v] of [
    18
        ["ending_before", ending_before],
    19
        ["limit", limit],
    20
        ["starting_after", starting_after],
    21
      ]) {
    22
        if (v !== undefined && v !== "") {
    23
          url.searchParams.append(k, v);
    24
        }
    25
      }
    26
      encodeParams({ expand }).forEach((v, k) => {
    27
        if (v !== undefined && v !== "") {
    28
          url.searchParams.append(k, v);
    29
        }
    30
      });
    31
      const response = await fetch(url, {
    32
        method: "GET",
    33
        headers: {
    34
          "Content-Type": "application/x-www-form-urlencoded",
    35
          Authorization: "Bearer " + auth.token,
    36
        },
    37
        body: undefined,
    38
      });
    39
      if (!response.ok) {
    40
        const text = await response.text();
    41
        throw new Error(`${response.status} ${text}`);
    42
      }
    43
      return await response.json();
    44
    }
    45
    
    
    46
    function encodeParams(o: any) {
    47
      function iter(o: any, path: string) {
    48
        if (Array.isArray(o)) {
    49
          o.forEach(function (a) {
    50
            iter(a, path + "[]");
    51
          });
    52
          return;
    53
        }
    54
        if (o !== null && typeof o === "object") {
    55
          Object.keys(o).forEach(function (k) {
    56
            iter(o[k], path + "[" + k + "]");
    57
          });
    58
          return;
    59
        }
    60
        data.push(path + "=" + o);
    61
      }
    62
      const data: string[] = [];
    63
      Object.keys(o).forEach(function (k) {
    64
        if (o[k] !== undefined) {
    65
          iter(o[k], k);
    66
        }
    67
      });
    68
      return new URLSearchParams(data.join("&"));
    69
    }
    70