usage-based-billing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDodo Payments Usage-Based Billing
Dodo Payments 基于使用量的计费
Charge customers for what they actually use—API calls, storage, AI tokens, or any metric you define.
Overview
概述
Usage-based billing is perfect for:
- APIs: Charge per request or operation
- AI Services: Bill per token, generation, or inference
- Infrastructure: Charge for compute, storage, bandwidth
- SaaS: Metered features alongside subscriptions
基于使用量的计费非常适合以下场景:
- API:按请求或操作收费
- AI服务:按令牌、生成或推理次数计费
- 基础设施:按计算、存储、带宽收费
- SaaS:订阅之外的计量功能收费
Core Concepts
核心概念
Events
事件(Events)
Usage actions sent from your application:
json
{
"event_id": "evt_unique_123",
"customer_id": "cus_abc123",
"event_name": "api.call",
"timestamp": "2025-01-21T10:30:00Z",
"metadata": { "endpoint": "/v1/users", "tokens": 150 }
}从你的应用发送的使用行为:
json
{
"event_id": "evt_unique_123",
"customer_id": "cus_abc123",
"event_name": "api.call",
"timestamp": "2025-01-21T10:30:00Z",
"metadata": { "endpoint": "/v1/users", "tokens": 150 }
}Meters
计量器(Meters)
Aggregate events into billable quantities:
| Aggregation | Use Case | Example |
|---|---|---|
| Count | Total events | API calls, image generations |
| Sum | Add values | Tokens used, bytes transferred |
| Max | Highest value | Peak concurrent users |
| Last | Most recent | Current storage used |
将事件聚合为可计费的数量:
| 聚合方式 | 使用场景 | 示例 |
|---|---|---|
| 计数(Count) | 事件总数 | API调用、图片生成次数 |
| 求和(Sum) | 数值累加 | 使用的令牌数、传输的字节数 |
| 最大值(Max) | 最高值 | 并发用户峰值 |
| 最新值(Last) | 最新记录 | 当前存储使用量 |
Products with Usage Pricing
带使用量定价的产品
- Price per unit (e.g., $0.001 per API call)
- Free threshold (e.g., 1,000 free calls)
- Automatic billing each cycle
Billing Example: 2,500 calls - 1,000 free = 1,500 × $0.02 = $30.00
- 按单位定价(例如:每API调用$0.001)
- 免费阈值(例如:1000次免费调用)
- 每个周期自动计费
计费示例:2500次调用 - 1000次免费 = 1500 × $0.02 = $30.00
Quick Start
快速开始
1. Create a Meter
1. 创建计量器
In Dashboard → Meters → Create Meter:
- Name: "API Requests"
- Event Name: (exact match, case-sensitive)
api.call - Aggregation: Count
- Unit: "calls"
在控制台 → 计量器 → 创建计量器:
- 名称:"API请求"
- 事件名称:(精确匹配,区分大小写)
api.call - 聚合方式:计数
- 单位:"calls"
2. Create Usage-Based Product
2. 创建基于使用量的产品
In Dashboard → Products → Create Product:
- Select Usage-Based type
- Connect your meter
- Set pricing:
- Price Per Unit: $0.001
- Free Threshold: 1000
在控制台 → 产品 → 创建产品:
- 选择基于使用量类型
- 关联你的计量器
- 设置定价:
- 单位价格:$0.001
- 免费阈值:1000
3. Send Events
3. 发送事件
typescript
import DodoPayments from 'dodopayments';
const client = new DodoPayments({
bearerToken: process.env.DODO_PAYMENTS_API_KEY,
});
await client.usageEvents.ingest({
events: [{
event_id: `api_${Date.now()}_${Math.random()}`,
customer_id: 'cus_abc123',
event_name: 'api.call',
timestamp: new Date().toISOString(),
metadata: {
endpoint: '/v1/users',
method: 'GET',
}
}]
});typescript
import DodoPayments from 'dodopayments';
const client = new DodoPayments({
bearerToken: process.env.DODO_PAYMENTS_API_KEY,
});
await client.usageEvents.ingest({
events: [{
event_id: `api_${Date.now()}_${Math.random()}`,
customer_id: 'cus_abc123',
event_name: 'api.call',
timestamp: new Date().toISOString(),
metadata: {
endpoint: '/v1/users',
method: 'GET',
}
}]
});Implementation Examples
实现示例
TypeScript/Node.js
TypeScript/Node.js
typescript
import DodoPayments from 'dodopayments';
const client = new DodoPayments({
bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
});
// Track single event
async function trackUsage(
customerId: string,
eventName: string,
metadata: Record<string, string>
) {
await client.usageEvents.ingest({
events: [{
event_id: `${eventName}_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: eventName,
timestamp: new Date().toISOString(),
metadata,
}]
});
}
// Track API call
await trackUsage('cus_abc123', 'api.call', {
endpoint: '/v1/generate',
method: 'POST',
});
// Track token usage (for Sum aggregation)
await trackUsage('cus_abc123', 'token.usage', {
tokens: '1500',
model: 'gpt-4',
});typescript
import DodoPayments from 'dodopayments';
const client = new DodoPayments({
bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
});
// 跟踪单个事件
async function trackUsage(
customerId: string,
eventName: string,
metadata: Record<string, string>
) {
await client.usageEvents.ingest({
events: [{
event_id: `${eventName}_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: eventName,
timestamp: new Date().toISOString(),
metadata,
}]
});
}
// 跟踪API调用
await trackUsage('cus_abc123', 'api.call', {
endpoint: '/v1/generate',
method: 'POST',
});
// 跟踪令牌使用量(用于求和聚合)
await trackUsage('cus_abc123', 'token.usage', {
tokens: '1500',
model: 'gpt-4',
});Batch Event Ingestion
批量事件上报
Send multiple events efficiently (max 1000 per request):
typescript
async function trackBatchUsage(
events: Array<{
customerId: string;
eventName: string;
metadata: Record<string, string>;
timestamp?: string;
}>
) {
const formattedEvents = events.map((e, i) => ({
event_id: `batch_${Date.now()}_${i}_${crypto.randomUUID()}`,
customer_id: e.customerId,
event_name: e.eventName,
timestamp: e.timestamp || new Date().toISOString(),
metadata: e.metadata,
}));
await client.usageEvents.ingest({ events: formattedEvents });
}
// Batch track multiple API calls
await trackBatchUsage([
{ customerId: 'cus_abc', eventName: 'api.call', metadata: { endpoint: '/v1/users' } },
{ customerId: 'cus_abc', eventName: 'api.call', metadata: { endpoint: '/v1/orders' } },
{ customerId: 'cus_xyz', eventName: 'api.call', metadata: { endpoint: '/v1/products' } },
]);高效发送多个事件(每次请求最多1000个):
typescript
async function trackBatchUsage(
events: Array<{
customerId: string;
eventName: string;
metadata: Record<string, string>;
timestamp?: string;
}>
) {
const formattedEvents = events.map((e, i) => ({
event_id: `batch_${Date.now()}_${i}_${crypto.randomUUID()}`,
customer_id: e.customerId,
event_name: e.eventName,
timestamp: e.timestamp || new Date().toISOString(),
metadata: e.metadata,
}));
await client.usageEvents.ingest({ events: formattedEvents });
}
// 批量跟踪多个API调用
await trackBatchUsage([
{ customerId: 'cus_abc', eventName: 'api.call', metadata: { endpoint: '/v1/users' } },
{ customerId: 'cus_abc', eventName: 'api.call', metadata: { endpoint: '/v1/orders' } },
{ customerId: 'cus_xyz', eventName: 'api.call', metadata: { endpoint: '/v1/products' } },
]);Python
Python
python
from dodopayments import DodoPayments
import uuid
from datetime import datetime
client = DodoPayments(bearer_token=os.environ["DODO_PAYMENTS_API_KEY"])
def track_usage(customer_id: str, event_name: str, metadata: dict):
client.usage_events.ingest(events=[{
"event_id": f"{event_name}_{datetime.now().timestamp()}_{uuid.uuid4()}",
"customer_id": customer_id,
"event_name": event_name,
"timestamp": datetime.now().isoformat(),
"metadata": metadata
}])python
from dodopayments import DodoPayments
import uuid
from datetime import datetime
client = DodoPayments(bearer_token=os.environ["DODO_PAYMENTS_API_KEY"])
def track_usage(customer_id: str, event_name: str, metadata: dict):
client.usage_events.ingest(events=[{
"event_id": f"{event_name}_{datetime.now().timestamp()}_{uuid.uuid4()}",
"customer_id": customer_id,
"event_name": event_name,
"timestamp": datetime.now().isoformat(),
"metadata": metadata
}])Track AI token usage
跟踪AI令牌使用量
track_usage("cus_abc123", "ai.tokens", {
"tokens": "2500",
"model": "claude-3",
"operation": "completion"
})
track_usage("cus_abc123", "ai.tokens", {
"tokens": "2500",
"model": "claude-3",
"operation": "completion"
})
Track image generation
跟踪图片生成
track_usage("cus_abc123", "image.generated", {
"size": "1024x1024",
"model": "dall-e-3"
})
undefinedtrack_usage("cus_abc123", "image.generated", {
"size": "1024x1024",
"model": "dall-e-3"
})
undefinedGo
Go
go
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dodopayments/dodopayments-go"
"github.com/google/uuid"
)
func main() {
client := dodopayments.NewClient(
option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")),
)
ctx := context.Background()
_, err := client.UsageEvents.Ingest(ctx, &dodopayments.UsageEventIngestParams{
Events: []dodopayments.UsageEvent{{
EventID: fmt.Sprintf("api_%d_%s", time.Now().Unix(), uuid.New().String()),
CustomerID: "cus_abc123",
EventName: "api.call",
Timestamp: time.Now().Format(time.RFC3339),
Metadata: map[string]string{
"endpoint": "/v1/users",
"method": "GET",
},
}},
})
if err != nil {
panic(err)
}
}go
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dodopayments/dodopayments-go"
"github.com/google/uuid"
)
func main() {
client := dodopayments.NewClient(
option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")),
)
ctx := context.Background()
_, err := client.UsageEvents.Ingest(ctx, &dodopayments.UsageEventIngestParams{
Events: []dodopayments.UsageEvent{{
EventID: fmt.Sprintf("api_%d_%s", time.Now().Unix(), uuid.New().String()),
CustomerID: "cus_abc123",
EventName: "api.call",
Timestamp: time.Now().Format(time.RFC3339),
Metadata: map[string]string{
"endpoint": "/v1/users",
"method": "GET",
},
}},
})
if err != nil {
panic(err)
}
}Meter Configuration
计量器配置
Aggregation Types
聚合类型
Count (API Calls, Requests)
计数(API调用、请求)
Meter: API Requests
Event Name: api.call
Aggregation: Count
Unit: callsMeter: API Requests
Event Name: api.call
Aggregation: Count
Unit: callsSum (Tokens, Bytes)
求和(令牌、字节)
Meter: Token Usage
Event Name: token.usage
Aggregation: Sum
Over Property: tokens
Unit: tokensEvents must include the property in metadata:
typescript
await client.usageEvents.ingest({
events: [{
event_id: 'token_123',
customer_id: 'cus_abc',
event_name: 'token.usage',
metadata: { tokens: '1500' } // This value gets summed
}]
});Meter: Token Usage
Event Name: token.usage
Aggregation: Sum
Over Property: tokens
Unit: tokens事件必须在metadata中包含该属性:
typescript
await client.usageEvents.ingest({
events: [{
event_id: 'token_123',
customer_id: 'cus_abc',
event_name: 'token.usage',
metadata: { tokens: '1500' } // 该值会被求和
}]
});Max (Peak Concurrent Users)
最大值(并发用户峰值)
Meter: Peak Users
Event Name: concurrent.users
Aggregation: Max
Over Property: count
Unit: usersMeter: Peak Users
Event Name: concurrent.users
Aggregation: Max
Over Property: count
Unit: usersLast (Current Storage)
最新值(当前存储量)
Meter: Storage Used
Event Name: storage.snapshot
Aggregation: Last
Over Property: bytes
Unit: GBMeter: Storage Used
Event Name: storage.snapshot
Aggregation: Last
Over Property: bytes
Unit: GBEvent Filtering
事件过滤
Filter which events count toward the meter:
Filter Logic: AND
Conditions:
- Property: tier, Equals: "premium"
- Property: status, Equals: "success"Only events matching ALL conditions are counted.
过滤计入计量器的事件:
过滤逻辑:AND
条件:
- 属性:tier,等于:"premium"
- 属性:status,等于:"success"只有满足所有条件的事件才会被计数。
Common Use Cases
常见使用场景
AI Token Billing
AI令牌计费
typescript
// Meter: AI Tokens (Sum aggregation over "tokens" property)
async function trackAIUsage(
customerId: string,
promptTokens: number,
completionTokens: number,
model: string
) {
const totalTokens = promptTokens + completionTokens;
await client.usageEvents.ingest({
events: [{
event_id: `ai_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: 'ai.tokens',
timestamp: new Date().toISOString(),
metadata: {
tokens: totalTokens.toString(),
prompt_tokens: promptTokens.toString(),
completion_tokens: completionTokens.toString(),
model,
}
}]
});
}
// After AI completion
await trackAIUsage('cus_abc', 500, 1200, 'gpt-4');typescript
// 计量器:AI令牌(对"tokens"属性求和聚合)
async function trackAIUsage(
customerId: string,
promptTokens: number,
completionTokens: number,
model: string
) {
const totalTokens = promptTokens + completionTokens;
await client.usageEvents.ingest({
events: [{
event_id: `ai_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: 'ai.tokens',
timestamp: new Date().toISOString(),
metadata: {
tokens: totalTokens.toString(),
prompt_tokens: promptTokens.toString(),
completion_tokens: completionTokens.toString(),
model,
}
}]
});
}
// AI完成后调用
await trackAIUsage('cus_abc', 500, 1200, 'gpt-4');Image Generation
图片生成计费
typescript
// Meter: Images Generated (Count aggregation)
async function trackImageGeneration(
customerId: string,
imageSize: string,
model: string
) {
await client.usageEvents.ingest({
events: [{
event_id: `img_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: 'image.generated',
timestamp: new Date().toISOString(),
metadata: {
size: imageSize,
model,
}
}]
});
}typescript
// 计量器:图片生成次数(计数聚合)
async function trackImageGeneration(
customerId: string,
imageSize: string,
model: string
) {
await client.usageEvents.ingest({
events: [{
event_id: `img_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: 'image.generated',
timestamp: new Date().toISOString(),
metadata: {
size: imageSize,
model,
}
}]
});
}API Rate Tracking
API调用次数跟踪
typescript
// Middleware for Express/Next.js
async function trackAPIUsage(
req: Request,
customerId: string
) {
await client.usageEvents.ingest({
events: [{
event_id: `api_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: 'api.call',
timestamp: new Date().toISOString(),
metadata: {
endpoint: req.url,
method: req.method,
user_agent: req.headers['user-agent'] || 'unknown',
}
}]
});
}typescript
// Express/Next.js中间件
async function trackAPIUsage(
req: Request,
customerId: string
) {
await client.usageEvents.ingest({
events: [{
event_id: `api_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: 'api.call',
timestamp: new Date().toISOString(),
metadata: {
endpoint: req.url,
method: req.method,
user_agent: req.headers['user-agent'] || 'unknown',
}
}]
});
}Storage Billing
存储计费
typescript
// Meter: Storage (Last aggregation - snapshot of current usage)
async function updateStorageUsage(customerId: string, bytesUsed: number) {
await client.usageEvents.ingest({
events: [{
event_id: `storage_${Date.now()}_${customerId}`,
customer_id: customerId,
event_name: 'storage.snapshot',
timestamp: new Date().toISOString(),
metadata: {
bytes: bytesUsed.toString(),
gb: (bytesUsed / 1024 / 1024 / 1024).toFixed(2),
}
}]
});
}
// Call periodically or after storage changes
await updateStorageUsage('cus_abc', 5368709120); // 5GBtypescript
// 计量器:存储量(最新值聚合 - 当前使用量快照)
async function updateStorageUsage(customerId: string, bytesUsed: number) {
await client.usageEvents.ingest({
events: [{
event_id: `storage_${Date.now()}_${customerId}`,
customer_id: customerId,
event_name: 'storage.snapshot',
timestamp: new Date().toISOString(),
metadata: {
bytes: bytesUsed.toString(),
gb: (bytesUsed / 1024 / 1024 / 1024).toFixed(2),
}
}]
});
}
// 定期调用或存储变更后调用
await updateStorageUsage('cus_abc', 5368709120); // 5GBNext.js Integration
Next.js集成
API Route for Usage Tracking
用于使用量跟踪的API路由
typescript
// app/api/track-usage/route.ts
import { NextRequest, NextResponse } from 'next/server';
import DodoPayments from 'dodopayments';
const client = new DodoPayments({
bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
});
export async function POST(req: NextRequest) {
const { customerId, eventName, metadata } = await req.json();
try {
await client.usageEvents.ingest({
events: [{
event_id: `${eventName}_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: eventName,
timestamp: new Date().toISOString(),
metadata,
}]
});
return NextResponse.json({ success: true });
} catch (error: any) {
return NextResponse.json(
{ error: error.message },
{ status: 500 }
);
}
}typescript
// app/api/track-usage/route.ts
import { NextRequest, NextResponse } from 'next/server';
import DodoPayments from 'dodopayments';
const client = new DodoPayments({
bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
});
export async function POST(req: NextRequest) {
const { customerId, eventName, metadata } = await req.json();
try {
await client.usageEvents.ingest({
events: [{
event_id: `${eventName}_${Date.now()}_${crypto.randomUUID()}`,
customer_id: customerId,
event_name: eventName,
timestamp: new Date().toISOString(),
metadata,
}]
});
return NextResponse.json({ success: true });
} catch (error: any) {
return NextResponse.json(
{ error: error.message },
{ status: 500 }
);
}
}Usage Tracking Hook
使用量跟踪Hook
typescript
// hooks/useUsageTracking.ts
import { useCallback } from 'react';
export function useUsageTracking(customerId: string) {
const trackUsage = useCallback(async (
eventName: string,
metadata: Record<string, string>
) => {
await fetch('/api/track-usage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ customerId, eventName, metadata }),
});
}, [customerId]);
return { trackUsage };
}
// Usage in component
function AIChat() {
const { trackUsage } = useUsageTracking('cus_abc123');
const handleGenerate = async () => {
const result = await generateAIResponse(prompt);
// Track token usage
await trackUsage('ai.tokens', {
tokens: result.totalTokens.toString(),
model: 'gpt-4',
});
};
}typescript
// hooks/useUsageTracking.ts
import { useCallback } from 'react';
export function useUsageTracking(customerId: string) {
const trackUsage = useCallback(async (
eventName: string,
metadata: Record<string, string>
) => {
await fetch('/api/track-usage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ customerId, eventName, metadata }),
});
}, [customerId]);
return { trackUsage };
}
// 在组件中使用
function AIChat() {
const { trackUsage } = useUsageTracking('cus_abc123');
const handleGenerate = async () => {
const result = await generateAIResponse(prompt);
// 跟踪令牌使用量
await trackUsage('ai.tokens', {
tokens: result.totalTokens.toString(),
model: 'gpt-4',
});
};
}Hybrid Billing
混合计费
Combine usage-based with subscriptions:
将基于使用量的计费与订阅相结合:
Subscription + Usage Overage
订阅+使用量超额计费
typescript
// 1. Customer subscribes to plan with included usage
// Product: Pro Plan - $49/month + $0.01/call after 10,000 free
// 2. Track all usage events
await trackUsage('cus_abc', 'api.call', { endpoint: '/v1/generate' });
// 3. Dodo automatically:
// - Applies free threshold (10,000 calls)
// - Charges overage at $0.01/call
// - Combines with subscription feetypescript
// 1. 客户订阅包含一定使用量的套餐
// 产品:专业套餐 - 每月$49 + 超过10000次调用后按$0.01/次收费
// 2. 跟踪所有使用事件
await trackUsage('cus_abc', 'api.call', { endpoint: '/v1/generate' });
// 3. Dodo会自动:
// - 应用免费阈值(10000次调用)
// - 对超额部分按$0.01/次收费
// - 与订阅费用合并计费Multiple Meters per Product
单个产品关联多个计量器
Attach up to 10 meters to a single product:
Product: AI Platform
├── Meter: API Calls ($0.001/call, 1000 free)
├── Meter: Token Usage ($0.01/1000 tokens)
├── Meter: Image Generations ($0.05/image, 10 free)
└── Meter: Storage ($0.10/GB)单个产品最多可关联10个计量器:
产品:AI平台
├── 计量器:API调用($0.001/次,1000次免费)
├── 计量器:令牌使用量($0.01/1000令牌)
├── 计量器:图片生成($0.05/张,10张免费)
└── 计量器:存储($0.10/GB)Best Practices
最佳实践
1. Unique Event IDs
1. 唯一事件ID
Always generate unique IDs for idempotency:
typescript
const eventId = `${eventName}_${Date.now()}_${crypto.randomUUID()}`;始终生成唯一ID以实现幂等性:
typescript
const eventId = `${eventName}_${Date.now()}_${crypto.randomUUID()}`;2. Batch Events
2. 批量事件
For high-volume, batch events (max 1000/request):
typescript
// Queue events and send in batches
const eventQueue: Event[] = [];
function queueEvent(event: Event) {
eventQueue.push(event);
if (eventQueue.length >= 100) {
flushEvents();
}
}
async function flushEvents() {
if (eventQueue.length === 0) return;
const batch = eventQueue.splice(0, 1000);
await client.usageEvents.ingest({ events: batch });
}
// Flush periodically
setInterval(flushEvents, 5000);对于高流量场景,批量发送事件(每次请求最多1000个):
typescript
// 将事件加入队列并批量发送
const eventQueue: Event[] = [];
function queueEvent(event: Event) {
eventQueue.push(event);
if (eventQueue.length >= 100) {
flushEvents();
}
}
async function flushEvents() {
if (eventQueue.length === 0) return;
const batch = eventQueue.splice(0, 1000);
await client.usageEvents.ingest({ events: batch });
}
// 定期批量发送
setInterval(flushEvents, 5000);3. Handle Failures Gracefully
3. 优雅处理失败
Implement retry logic for event ingestion:
typescript
async function trackWithRetry(event: Event, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
await client.usageEvents.ingest({ events: [event] });
return;
} catch (error) {
if (i === retries - 1) throw error;
await sleep(1000 * Math.pow(2, i)); // Exponential backoff
}
}
}为事件上报实现重试逻辑:
typescript
async function trackWithRetry(event: Event, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
await client.usageEvents.ingest({ events: [event] });
return;
} catch (error) {
if (i === retries - 1) throw error;
await sleep(1000 * Math.pow(2, i)); // 指数退避
}
}
}4. Include Relevant Metadata
4. 包含相关元数据
Add context for debugging and filtering:
typescript
metadata: {
endpoint: '/v1/generate',
method: 'POST',
model: 'gpt-4',
user_id: 'internal_user_123',
request_id: requestId,
}添加上下文信息以便调试和过滤:
typescript
metadata: {
endpoint: '/v1/generate',
method: 'POST',
model: 'gpt-4',
user_id: 'internal_user_123',
request_id: requestId,
}5. Monitor in Dashboard
5. 在控制台监控
Check Meters dashboard for:
- Event volume and trends
- Usage per customer
- Aggregated quantities
查看计量器控制台以获取:
- 事件量和趋势
- 客户使用情况
- 聚合后的数量
Pricing Examples
定价示例
API Service
API服务
Meter: API Calls (Count)
Price: $0.001 per call
Free Threshold: 1,000 calls/month
Customer uses 15,000 calls:
(15,000 - 1,000) × $0.001 = $14.00计量器:API调用(计数)
价格:$0.001/次
免费阈值:每月1000次调用
客户使用15000次调用:
(15000 - 1000) × $0.001 = $14.00AI Token Service
AI令牌服务
Meter: Tokens (Sum over "tokens")
Price: $0.00001 per token ($0.01 per 1,000)
Free Threshold: 10,000 tokens
Customer uses 50,000 tokens:
(50,000 - 10,000) × $0.00001 = $0.40计量器:令牌(对"tokens"求和)
价格:$0.00001/令牌($0.01/1000令牌)
免费阈值:10000令牌
客户使用50000令牌:
(50000 - 10000) × $0.00001 = $0.40Image Generation
图片生成服务
Meter: Images (Count)
Price: $0.05 per image
Free Threshold: 10 images
Customer generates 100 images:
(100 - 10) × $0.05 = $4.50计量器:图片(计数)
价格:$0.05/张
免费阈值:10张
客户生成100张图片:
(100 - 10) × $0.05 = $4.50