1 | |
2 |
|
3 | |
4 | * Create Billing Meter |
5 | * 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`). |
6 | */ |
7 | export async function main( |
8 | auth: RT.Stripe, |
9 | display_name: string, |
10 | event_name: string, |
11 | aggregation_formula: "count" | "sum" | "last", |
12 | value_payload_key: string | undefined, |
13 | customer_payload_key: string | undefined, |
14 | event_time_window: "day" | "hour" | undefined |
15 | ) { |
16 | const response = await fetch(`https://api.stripe.com/v1/billing/meters`, { |
17 | method: "POST", |
18 | headers: { |
19 | Authorization: `Bearer ${auth.token}`, |
20 | "Content-Type": "application/x-www-form-urlencoded", |
21 | Accept: "application/json", |
22 | "Stripe-Version": "2025-03-31.basil", |
23 | }, |
24 | body: toForm({ |
25 | display_name, |
26 | event_name, |
27 | default_aggregation: { formula: aggregation_formula }, |
28 | value_settings: { event_payload_key: value_payload_key }, |
29 | customer_mapping: customer_payload_key |
30 | ? { type: "by_id", event_payload_key: customer_payload_key } |
31 | : undefined, |
32 | event_time_window, |
33 | }), |
34 | }) |
35 |
|
36 | if (!response.ok) { |
37 | throw new Error(`${response.status} ${await response.text()}`) |
38 | } |
39 |
|
40 | return await response.json() |
41 | } |
42 |
|
43 | |
44 | function toForm( |
45 | params: { [key: string]: any }, |
46 | prefix = "", |
47 | out = new URLSearchParams() |
48 | ) { |
49 | for (const [key, value] of Object.entries(params)) { |
50 | if (value == null || value === "") continue |
51 | const name = prefix ? `${prefix}[${key}]` : key |
52 | if (typeof value === "object") toForm(value, name, out) |
53 | else out.append(name, String(value)) |
54 | } |
55 | return out |
56 | } |
57 |
|