//native
/**
* Create Invoice
* Create a draft invoice for a customer; add lines with Create Invoice Item (passing `invoice`), then finalize it. `send_invoice` collection needs `days_until_due`. Pending invoice items created without an `invoice` are only pulled in when `include_pending_invoice_items` is set. `auto_advance` lets Stripe finalize and collect it automatically. `extra_params` passes any other documented field through as-is.
*/
export async function main(
auth: RT.Stripe,
customer: string,
collection_method: "charge_automatically" | "send_invoice" | undefined,
days_until_due: number | undefined,
description: string | undefined,
subscription: string | undefined,
default_payment_method: string | undefined,
include_pending_invoice_items: boolean | undefined,
auto_advance: boolean | undefined,
metadata: { [key: string]: string } | undefined,
extra_params: { [key: string]: any } | undefined
) {
const response = await fetch(`https://api.stripe.com/v1/invoices`, {
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({
customer,
collection_method,
days_until_due,
description,
subscription,
default_payment_method,
pending_invoice_items_behavior: include_pending_invoice_items
? "include"
: undefined,
auto_advance: auto_advance || undefined,
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 2 days ago