Edits history of script submission #23811 for ' Create Billing Meter (stripe)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create Billing Meter
     * Create a billing meter for usage-based prices. Meter events with `event_name` are aggregated by `aggregation_formula`; `value_payload_key` names the payload field holding the value (default `value`) and `customer_payload_key` the one holding the customer id (default `stripe_customer_id`).
     */
    export async function main(
      auth: RT.Stripe,
      display_name: string,
      event_name: string,
      aggregation_formula: "count" | "sum" | "last",
      value_payload_key: string | undefined,
      customer_payload_key: string | undefined,
      event_time_window: "day" | "hour" | undefined
    ) {
      const response = await fetch(`https://api.stripe.com/v1/billing/meters`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/x-www-form-urlencoded",
          Accept: "application/json",
          "Stripe-Version": "2025-03-31.basil",
        },
        body: toForm({
          display_name,
          event_name,
          default_aggregation: { formula: aggregation_formula },
          value_settings: { event_payload_key: value_payload_key },
          customer_mapping: customer_payload_key
            ? { type: "by_id", event_payload_key: customer_payload_key }
            : undefined,
          event_time_window,
        }),
      })
    
      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