0
# Billing
1
2
Stripe's advanced billing namespace provides sophisticated usage metering, credit management, and billing alerting capabilities. These features enable complex billing scenarios including usage-based pricing, prepaid credits, and automated billing monitoring.
3
4
## Usage Metering
5
6
### Billing.Meters
7
8
Define and manage usage meters for tracking billable events:
9
10
```typescript { .api }
11
interface BillingMeter {
12
id: string;
13
object: 'billing.meter';
14
created: number;
15
display_name: string;
16
event_name: string;
17
status: 'active' | 'inactive';
18
customer_mapping: {
19
event_payload_key: string;
20
type: 'by_id';
21
};
22
default_aggregation: {
23
formula: 'count' | 'sum';
24
};
25
value_settings?: {
26
event_payload_key?: string;
27
};
28
}
29
30
// Create usage meter
31
const meter = await stripe.billing.meters.create({
32
display_name: 'API Requests',
33
event_name: 'api_request',
34
customer_mapping: {
35
event_payload_key: 'customer_id',
36
type: 'by_id'
37
},
38
default_aggregation: {
39
formula: 'count'
40
}
41
});
42
43
// Create value-based meter
44
const valueMeter = await stripe.billing.meters.create({
45
display_name: 'Storage Usage (GB)',
46
event_name: 'storage_used',
47
customer_mapping: {
48
event_payload_key: 'stripe_customer_id',
49
type: 'by_id'
50
},
51
default_aggregation: {
52
formula: 'sum'
53
},
54
value_settings: {
55
event_payload_key: 'gb_used'
56
}
57
});
58
59
// Retrieve meter
60
const retrieved = await stripe.billing.meters.retrieve('mtr_123');
61
62
// Update meter
63
const updated = await stripe.billing.meters.update('mtr_123', {
64
display_name: 'Updated API Request Meter'
65
});
66
67
// List meters
68
const meters = await stripe.billing.meters.list({
69
status: 'active',
70
limit: 10
71
});
72
73
// Deactivate meter
74
const deactivated = await stripe.billing.meters.deactivate('mtr_123');
75
76
// Reactivate meter
77
const reactivated = await stripe.billing.meters.reactivate('mtr_123');
78
79
// List event summaries
80
const eventSummaries = await stripe.billing.meters.listEventSummaries(
81
'mtr_123',
82
{
83
customer: 'cus_123',
84
start_time: Math.floor(Date.now() / 1000) - 86400 * 30, // Last 30 days
85
end_time: Math.floor(Date.now() / 1000)
86
}
87
);
88
```
89
90
### Billing.MeterEvents
91
92
Record usage events for billing:
93
94
```typescript { .api }
95
interface BillingMeterEvent {
96
object: 'billing.meter_event';
97
created: number;
98
event_name: string;
99
identifier: string;
100
payload: {
101
[key: string]: string;
102
};
103
}
104
105
// Create meter event
106
const meterEvent = await stripe.billing.meterEvents.create({
107
event_name: 'api_request',
108
payload: {
109
customer_id: 'cus_123',
110
endpoint: '/api/users',
111
method: 'GET'
112
}
113
});
114
115
// Create value-based meter event
116
const valueMeterEvent = await stripe.billing.meterEvents.create({
117
event_name: 'storage_used',
118
payload: {
119
stripe_customer_id: 'cus_123',
120
gb_used: '2.5',
121
timestamp: Math.floor(Date.now() / 1000).toString()
122
}
123
});
124
125
// Batch meter events (recommended for high volume)
126
const events = [
127
{
128
event_name: 'api_request',
129
payload: { customer_id: 'cus_123', endpoint: '/api/data' }
130
},
131
{
132
event_name: 'api_request',
133
payload: { customer_id: 'cus_456', endpoint: '/api/users' }
134
}
135
];
136
137
for (const event of events) {
138
await stripe.billing.meterEvents.create(event);
139
}
140
```
141
142
### Billing.MeterEventAdjustments
143
144
Adjust previously recorded usage events:
145
146
```typescript { .api }
147
// Create meter event adjustment (correction)
148
const adjustment = await stripe.billing.meterEventAdjustments.create({
149
event_name: 'api_request',
150
type: 'cancel',
151
original_event_id: 'mevt_123'
152
});
153
154
// Create value adjustment
155
const valueAdjustment = await stripe.billing.meterEventAdjustments.create({
156
event_name: 'storage_used',
157
type: 'cancel',
158
original_event_id: 'mevt_456'
159
});
160
```
161
162
## V2 Billing API (Latest)
163
164
### V2.Billing.MeterEvents
165
166
Enhanced meter events with improved performance:
167
168
```typescript { .api }
169
// Create V2 meter event
170
const v2MeterEvent = await stripe.v2.billing.meterEvents.create({
171
event_name: 'api_call',
172
payload: {
173
stripe_customer_id: 'cus_123',
174
value: '1'
175
}
176
});
177
178
// Create V2 meter event adjustment
179
const v2Adjustment = await stripe.v2.billing.meterEventAdjustments.create({
180
event_name: 'api_call',
181
type: 'cancel',
182
original_event_id: 'mevt_789'
183
});
184
```
185
186
### V2.Billing.MeterEventSession
187
188
Batch meter events for improved performance:
189
190
```typescript { .api }
191
// Create meter event session for batch operations
192
const session = await stripe.v2.billing.meterEventSession.create({
193
meter_event_session: {
194
// Session configuration
195
}
196
});
197
```
198
199
### V2.Billing.MeterEventStream
200
201
Stream meter events for real-time processing:
202
203
```typescript { .api }
204
// Create meter event stream
205
const stream = await stripe.v2.billing.meterEventStream.create({
206
// Stream configuration
207
});
208
```
209
210
## Credit Management
211
212
### Billing.CreditGrants
213
214
Issue and manage customer credit grants:
215
216
```typescript { .api }
217
interface BillingCreditGrant {
218
id: string;
219
object: 'billing.credit_grant';
220
customer: string;
221
amount: {
222
monetary?: {
223
currency: string;
224
value: number;
225
};
226
type: 'monetary';
227
};
228
applicability_config: {
229
scope: {
230
price_type: 'metered';
231
};
232
};
233
category: 'paid' | 'promotional';
234
effective_at: number;
235
expires_at?: number;
236
}
237
238
// Create monetary credit grant
239
const creditGrant = await stripe.billing.creditGrants.create({
240
customer: 'cus_123',
241
amount: {
242
monetary: {
243
currency: 'usd',
244
value: 1000 // $10.00 in cents
245
},
246
type: 'monetary'
247
},
248
applicability_config: {
249
scope: {
250
price_type: 'metered'
251
}
252
},
253
category: 'promotional',
254
effective_at: Math.floor(Date.now() / 1000),
255
expires_at: Math.floor(Date.now() / 1000) + 86400 * 90, // 90 days
256
name: 'Welcome Bonus Credit'
257
});
258
259
// Create credit grant for specific products
260
const productCredit = await stripe.billing.creditGrants.create({
261
customer: 'cus_123',
262
amount: {
263
monetary: {
264
currency: 'usd',
265
value: 2000
266
},
267
type: 'monetary'
268
},
269
applicability_config: {
270
scope: {
271
price_type: 'metered',
272
filters: [
273
{
274
prices: ['price_api_calls', 'price_storage']
275
}
276
]
277
}
278
},
279
category: 'paid'
280
});
281
282
// Retrieve credit grant
283
const retrieved = await stripe.billing.creditGrants.retrieve('cg_123');
284
285
// Update credit grant
286
const updated = await stripe.billing.creditGrants.update('cg_123', {
287
name: 'Updated Credit Grant',
288
metadata: { campaign: 'spring_2024' }
289
});
290
291
// List credit grants
292
const creditGrants = await stripe.billing.creditGrants.list({
293
customer: 'cus_123',
294
limit: 10
295
});
296
297
// Expire credit grant
298
const expired = await stripe.billing.creditGrants.expire('cg_123');
299
300
// Void credit grant
301
const voided = await stripe.billing.creditGrants.voidGrant('cg_123');
302
```
303
304
### Billing.CreditBalanceSummary
305
306
View customer's current credit balance:
307
308
```typescript { .api }
309
interface BillingCreditBalanceSummary {
310
object: 'billing.credit_balance_summary';
311
customer: string;
312
balance: {
313
monetary: Array<{
314
currency: string;
315
available_balance: {
316
currency: string;
317
value: number;
318
};
319
ledger_balance: {
320
currency: string;
321
value: number;
322
};
323
}>;
324
};
325
}
326
327
// Retrieve credit balance summary
328
const balanceSummary = await stripe.billing.creditBalanceSummary.retrieve({
329
customer: 'cus_123'
330
});
331
332
console.log('Available USD credit:',
333
balanceSummary.balance.monetary.find(b => b.currency === 'usd')?.available_balance.value
334
);
335
```
336
337
### Billing.CreditBalanceTransactions
338
339
Track credit balance changes:
340
341
```typescript { .api }
342
interface BillingCreditBalanceTransaction {
343
id: string;
344
object: 'billing.credit_balance_transaction';
345
customer: string;
346
type: 'credit_grant' | 'credit_grant_adjustment' | 'credit_reversal' | 'invoice_applied_credit' | 'invoice_voided_credit';
347
amount: {
348
monetary: {
349
currency: string;
350
value: number;
351
};
352
type: 'monetary';
353
};
354
created: number;
355
}
356
357
// Retrieve credit balance transaction
358
const transaction = await stripe.billing.creditBalanceTransactions.retrieve('cbt_123');
359
360
// List credit balance transactions
361
const transactions = await stripe.billing.creditBalanceTransactions.list({
362
customer: 'cus_123',
363
limit: 20,
364
type: 'credit_grant'
365
});
366
367
// List transactions by date range
368
const recentTransactions = await stripe.billing.creditBalanceTransactions.list({
369
customer: 'cus_123',
370
created: {
371
gte: Math.floor(Date.now() / 1000) - 86400 * 30 // Last 30 days
372
}
373
});
374
```
375
376
## Billing Alerts
377
378
### Billing.Alerts
379
380
Monitor and alert on billing events:
381
382
```typescript { .api }
383
interface BillingAlert {
384
id: string;
385
object: 'billing.alert';
386
alert_type: 'usage_threshold';
387
filter?: {
388
customer?: string;
389
};
390
status: 'active' | 'archived';
391
title: string;
392
usage_threshold_config?: {
393
gte: number;
394
meter: string;
395
recurrence: 'one_time' | 'daily' | 'monthly';
396
};
397
}
398
399
// Create usage threshold alert
400
const usageAlert = await stripe.billing.alerts.create({
401
alert_type: 'usage_threshold',
402
title: 'High API Usage Alert',
403
usage_threshold_config: {
404
gte: 1000, // Alert when usage >= 1000
405
meter: 'mtr_api_requests',
406
recurrence: 'daily'
407
}
408
});
409
410
// Create customer-specific alert
411
const customerAlert = await stripe.billing.alerts.create({
412
alert_type: 'usage_threshold',
413
title: 'Enterprise Customer Alert',
414
filter: {
415
customer: 'cus_enterprise_123'
416
},
417
usage_threshold_config: {
418
gte: 10000,
419
meter: 'mtr_api_requests',
420
recurrence: 'monthly'
421
}
422
});
423
424
// Retrieve alert
425
const retrieved = await stripe.billing.alerts.retrieve('ba_123');
426
427
// List alerts
428
const alerts = await stripe.billing.alerts.list({
429
alert_type: 'usage_threshold',
430
limit: 10
431
});
432
433
// Activate alert
434
const activated = await stripe.billing.alerts.activate('ba_123');
435
436
// Deactivate alert
437
const deactivated = await stripe.billing.alerts.deactivate('ba_123');
438
439
// Archive alert
440
const archived = await stripe.billing.alerts.archive('ba_123');
441
```
442
443
## Usage-Based Pricing Integration
444
445
Combine billing features with pricing for complete usage-based billing:
446
447
```typescript { .api }
448
// Create metered price
449
const meteredPrice = await stripe.prices.create({
450
product: 'prod_api_service',
451
currency: 'usd',
452
recurring: {
453
interval: 'month',
454
usage_type: 'metered'
455
},
456
billing_scheme: 'per_unit',
457
unit_amount: 10, // $0.10 per unit
458
transform_usage: {
459
divide_by: 1,
460
round: 'up'
461
}
462
});
463
464
// Create tiered usage pricing
465
const tieredPrice = await stripe.prices.create({
466
product: 'prod_api_service',
467
currency: 'usd',
468
recurring: {
469
interval: 'month',
470
usage_type: 'metered'
471
},
472
billing_scheme: 'tiered',
473
tiers_mode: 'graduated',
474
tiers: [
475
{
476
up_to: 1000,
477
unit_amount: 10 // $0.10 for first 1000
478
},
479
{
480
up_to: 5000,
481
unit_amount: 8 // $0.08 for next 4000
482
},
483
{
484
up_to: 'inf',
485
unit_amount: 5 // $0.05 for everything above
486
}
487
]
488
});
489
490
// Create subscription with usage-based pricing
491
const usageSubscription = await stripe.subscriptions.create({
492
customer: 'cus_123',
493
items: [{
494
price: meteredPrice.id
495
}],
496
billing_thresholds: {
497
amount_gte: 5000, // Generate invoice when amount >= $50
498
reset_billing_cycle_anchor: false
499
}
500
});
501
502
// Record usage events
503
await stripe.billing.meterEvents.create({
504
event_name: 'api_request',
505
payload: {
506
customer_id: 'cus_123',
507
units: '10' // 10 API calls
508
}
509
});
510
511
// Apply promotional credit
512
const promoCredit = await stripe.billing.creditGrants.create({
513
customer: 'cus_123',
514
amount: {
515
monetary: {
516
currency: 'usd',
517
value: 500 // $5.00 credit
518
},
519
type: 'monetary'
520
},
521
applicability_config: {
522
scope: {
523
price_type: 'metered'
524
}
525
},
526
category: 'promotional',
527
effective_at: Math.floor(Date.now() / 1000),
528
name: 'First Month Free Credit'
529
});
530
```
531
532
## Best Practices
533
534
### Event Recording
535
```typescript { .api }
536
// Use idempotency for reliable event recording
537
const eventId = `api_call_${customerId}_${timestamp}_${uniqueId}`;
538
await stripe.billing.meterEvents.create({
539
event_name: 'api_request',
540
payload: {
541
customer_id: 'cus_123'
542
}
543
}, {
544
idempotencyKey: eventId
545
});
546
547
// Batch events for better performance
548
const events = collectUsageEvents(); // Your event collection logic
549
for (const event of events) {
550
await stripe.billing.meterEvents.create(event, {
551
idempotencyKey: event.unique_id
552
});
553
}
554
```
555
556
### Credit Management
557
```typescript { .api }
558
// Check credit balance before charging
559
const balance = await stripe.billing.creditBalanceSummary.retrieve({
560
customer: 'cus_123'
561
});
562
563
const usdCredit = balance.balance.monetary.find(b => b.currency === 'usd');
564
if (usdCredit && usdCredit.available_balance.value > 0) {
565
console.log(`Customer has $${usdCredit.available_balance.value / 100} in credits`);
566
}
567
```
568
569
### Alert Configuration
570
```typescript { .api }
571
// Set up graduated alerts for different usage levels
572
const alerts = [
573
{ threshold: 1000, title: 'Usage Warning - 1K API calls' },
574
{ threshold: 5000, title: 'High Usage Alert - 5K API calls' },
575
{ threshold: 10000, title: 'Critical Usage - 10K API calls' }
576
];
577
578
for (const alert of alerts) {
579
await stripe.billing.alerts.create({
580
alert_type: 'usage_threshold',
581
title: alert.title,
582
usage_threshold_config: {
583
gte: alert.threshold,
584
meter: 'mtr_api_requests',
585
recurrence: 'daily'
586
}
587
});
588
}
589
```
590
591
The billing namespace provides enterprise-grade usage metering and credit management capabilities, enabling sophisticated pricing models and proactive billing monitoring for usage-based businesses.