Edits history of script submission #22555 for ' List Products (stripe)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * List Products
     * List products, newest first. `active` filters on active or archived products. Returns one page (`limit` 1-100, default 10); pass the last object's id as `starting_after` for the next page while `has_more` is true.
     */
    export async function main(
      auth: RT.Stripe,
      active: "true" | "false" | undefined,
      limit: number | undefined,
      starting_after: string | undefined,
      ending_before: string | undefined
    ) {
      const url = new URL(`https://api.stripe.com/v1/products`)
      url.search = toForm({
        active,
        limit,
        starting_after,
        ending_before,
      }).toString()
    
      const response = await fetch(url, {
        headers: {
          Authorization: `Bearer ${auth.token}`,
          Accept: "application/json",
          "Stripe-Version": "2025-03-31.basil",
        },
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    
    // Stripe takes form-encoded params with bracketed nesting: metadata[key]=v, items[0][price]=p
    function toForm(
      params: { [key: string]: any },
      prefix = "",
      out = new URLSearchParams()
    ) {
      for (const [key, value] of Object.entries(params)) {
        if (value == null || value === "") continue
        const name = prefix ? `${prefix}[${key}]` : key
        if (typeof value === "object") toForm(value, name, out)
        else out.append(name, String(value))
      }
      return out
    }
    

    Submitted by hugo989 3 hours ago

  • bunnative
    //native
    
    type Stripe = {
      token: string;
    };
    export async function main(stripeAuth: Stripe) {
      let has_more = true;
      let starting_after = "";
      const products = [];
    
      // if you have a lot of products (> 200), you may want to consider to throttle.
      while (has_more) {
        const res = await getStripeProductsIds(stripeAuth.token, starting_after);
        has_more = res.has_more;
        starting_after = res.data[res.data.length - 1].id;
        products.push(...res.data);
      }
    
      return products;
    }
    
    async function getStripeProductsIds(stripeKey: string, starting_after = "") {
      let url = "https://api.stripe.com/v1/products?limit=10";
      if (starting_after) {
        url += `&starting_after=${starting_after}`;
      }
      const products = await fetch(url, {
        headers: {
          Authorization: `Bearer ${stripeKey}`,
        },
      }).then((res) => res.json());
    
      return products;
    }
    

    Submitted by hugo989 136 days ago