Edits history of script submission #23801 for ' Create Subscription (stripe)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create Subscription
     * Subscribe a customer to one or more recurring prices. With `charge_automatically`, the customer needs a default payment method (or use `payment_behavior: default_incomplete` and confirm the first invoice's payment). `send_invoice` needs `days_until_due`. Set `idempotency_key` to make retries safe: Stripe returns the first result for a repeated key within 24 hours. `extra_params` passes any other documented field through as-is.
     */
    export async function main(
      auth: RT.Stripe,
      customer: string,
      items: { price: string; quantity?: number }[],
      collection_method: "charge_automatically" | "send_invoice" | undefined,
      days_until_due: number | undefined,
      default_payment_method: string | undefined,
      payment_behavior:
        | "allow_incomplete"
        | "default_incomplete"
        | "error_if_incomplete"
        | "pending_if_incomplete"
        | undefined,
      trial_period_days: number | undefined,
      description: string | undefined,
      metadata: { [key: string]: string } | undefined,
      idempotency_key: string | undefined,
      extra_params: { [key: string]: any } | undefined
    ) {
      const response = await fetch(`https://api.stripe.com/v1/subscriptions`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/x-www-form-urlencoded",
          Accept: "application/json",
          "Stripe-Version": "2025-03-31.basil",
          ...(idempotency_key ? { "Idempotency-Key": idempotency_key } : {}),
        },
        body: toForm({
          customer,
          items,
          collection_method,
          days_until_due,
          default_payment_method,
          payment_behavior,
          trial_period_days,
          description,
          metadata,
          ...extra_params,
        }),
      })
    
      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