Edits history of script submission #23785 for ' Create Webhook Endpoint (stripe)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create Webhook Endpoint
     * Register a URL (e.g. a Windmill HTTP route) to receive events. `enabled_events` lists event types such as `invoice.paid`, or `*` for all. The response's `secret` (`whsec_...`) verifies the Stripe-Signature header and is only returned here. Without `api_version`, payloads use the account's default API version.
     */
    export async function main(
      auth: RT.Stripe,
      url: string,
      enabled_events: string[],
      description: string | undefined,
      api_version: string | undefined,
      metadata: { [key: string]: string } | undefined
    ) {
      const response = await fetch(`https://api.stripe.com/v1/webhook_endpoints`, {
        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({ url, enabled_events, description, api_version, metadata }),
      })
    
      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