Edits history of script submission #23787 for ' Search Customers (stripe)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Search Customers
     * Search customers with Stripe's search query language, e.g. `email~"@example.com" AND metadata["plan"]:"pro"`. Pass the response's `next_page` as `page` for more. Search is not available in India and new objects can take a minute to become searchable.
     */
    export async function main(
      auth: RT.Stripe,
      query: string,
      limit: number | undefined,
      page: string | undefined
    ) {
      const url = new URL(`https://api.stripe.com/v1/customers/search`)
      url.search = toForm({ query, limit, page }).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