Used to check for browser translation.
用于检测浏览器翻译。
ブラウザの翻訳を検出する
API Reference

Meter Events


A Meter Event represents a single instance of usage for a metered billing model. You report these events to a Meter, which aggregates them to determine how much credit a customer has consumed. This is a core component of implementing Credit-Based Billing.

Each meter event must have a unique identifier to prevent duplicate reporting and ensure idempotency.

The Meter Event Object#

A MeterEvent object contains detailed information about a single usage record.

Attribute

Type

Description

id

string

Unique identifier for the meter event.

event_name

string

The name of the event, which links it to a specific meter.

payload

object

An object containing details about the usage, such as customer_id and value.

identifier

string

A unique key provided by you to prevent duplicate event creation.

timestamp

number

Unix timestamp indicating when the usage occurred.

status

string

The processing status of the event. Can be pending, processed, failed, requires_action, or requires_capture.

livemode

boolean

true if the event was created in live mode, false for test mode.

processed

boolean

true if the event has been successfully processed and credit has been consumed.

credit_consumed

string

The amount of credit that has been consumed by this event.

credit_pending

string

The amount of credit pending consumption for this event.

metadata

object

A set of key-value pairs that you can attach to the event object.

Create a Meter Event#

Reports a usage event to a meter. The system processes this event asynchronously to deduct credits from the customer's subscription.

Parameters

Name

Type

Description

event_name

string

Required. The name of the event, which must correspond to an active meter's event_name.

payload

object

Required. An object containing the event's core data. See details below.

identifier

string

Required. A unique identifier for this event to ensure idempotency. The system will reject any new event with a previously used identifier.

timestamp

number

Optional. A Unix timestamp for when the event occurred. If not provided, it defaults to the time of the API call.

metadata

Record<string, any>

Optional. A set of key-value pairs to store additional information on the object.

Payload Object Properties

Name

Type

Description

customer_id

string

Required. The ID of the customer who generated the usage event.

value

string

Required. The amount of usage to report. This should be a positive number representing the quantity of the metered resource consumed.

subscription_id

string

Optional. The ID of the subscription this usage should be billed against. If provided, the event will consume credit from this specific subscription.

Returns

Returns the newly created MeterEvent object.

Example

import payment from '@blocklet/payment-js';

async function reportApiCallUsage() {
try {
const event = await payment.meterEvents.create({
event_name: 'api_calls',
identifier: 'usage-report-idem-key-12345',
timestamp: Math.floor(Date.now() / 1000),
payload: {
customer_id: 'cust_xxxxxxxxxxxxxx',
value: '100',
subscription_id: 'sub_xxxxxxxxxxxxxx',
},
metadata: {
region: 'us-east-1',
},
});
console.log('Meter event created:', event.id);
} catch (error) {
console.error('Error creating meter event:', error.message);
}
}

reportApiCallUsage();

Example Response

{
"id": "mevt_xxxxxxxxxxxxxx",
"event_name": "api_calls",
"payload": {
"customer_id": "cust_xxxxxxxxxxxxxx",
"currency_id": "usd_xxxxxxxxxxxxxx",
"decimal": 18,
"unit": "USD",
"subscription_id": "sub_xxxxxxxxxxxxxx",
"value": "100000000000000000000"
},
"identifier": "usage-report-idem-key-12345",
"livemode": false,
"processed": false,
"status": "pending",
"attempt_count": 0,
"credit_consumed": "0",
"credit_pending": "100000000000000000000",
"created_via": "api",
"metadata": {
"region": "us-east-1"
},
"timestamp": 1678886400,
"created_at": "2023-03-15T12:00:00.000Z",
"updated_at": "2023-03-15T12:00:00.000Z",
"processing": {
"queued": true,
"message": "Credit consumption will be processed asynchronously"
}
}

Retrieve a Meter Event#

Retrieves the details of an existing meter event by its unique ID.

Parameters

Name

Type

Description

id

string

Required. The unique identifier of the meter event to retrieve.

Returns

Returns the MeterEvent object if found.

Example

import payment from '@blocklet/payment-js';

async function getMeterEvent(eventId) {
try {
const event = await payment.meterEvents.retrieve(eventId);
console.log('Retrieved event:', event.status);
} catch (error) {
console.error(`Error retrieving event ${eventId}:`, error.message);
}
}

getMeterEvent('mevt_xxxxxxxxxxxxxx');

Example Response

{
"id": "mevt_xxxxxxxxxxxxxx",
"event_name": "api_calls",
"payload": {
"customer_id": "cust_xxxxxxxxxxxxxx",
"value": "100000000000000000000"
},
"identifier": "usage-report-idem-key-12345",
"status": "processed",
"livemode": false,
"customer": { },
"subscription": { },
"meter": { }
}

List Meter Events#

Returns a paginated list of meter events. You can filter the list based on various parameters.

Parameters

Name

Type

Description

event_name

string

Optional. Filter events by a specific event name.

meter_id

string

Optional. Filter events associated with a specific meter.

customer_id

string

Optional. Filter events for a specific customer.

start

number

Optional. A Unix timestamp to filter events created on or after this time.

end

number

Optional. A Unix timestamp to filter events created on or before this time.

livemode

boolean

Optional. Filter by live or test mode.

q

string

Optional. A generic search query string.

page

number

Optional. The page number for pagination, starting at 1.

pageSize

number

Optional. The number of objects to return per page. Defaults to 20.

Returns

A paginated object containing a list of MeterEvent objects.

Example

import payment from '@blocklet/payment-js';

async function listCustomerUsageEvents() {
try {
const events = await payment.meterEvents.list({
customer_id: 'cust_xxxxxxxxxxxxxx',
pageSize: 5,
});
console.log(`Found ${events.count} events:`);
events.list.forEach(event => {
console.log(`- Event ID: ${event.id}, Status: ${event.status}`);
});
} catch (error) {
console.error('Error listing meter events:', error.message);
}
}

listCustomerUsageEvents();

Example Response

{
"count": 25,
"list": [
{
"id": "mevt_xxxxxxxxxxxxxx",
"event_name": "api_calls",
"status": "processed"
},
{
"id": "mevt_yyyyyyyyyyyyyy",
"event_name": "api_calls",
"status": "processed"
}
],
"paging": {
"page": 1,
"pageSize": 5
}
}

Retrieve Meter Event Statistics#

Fetches aggregated usage data for a specific meter over a given time period.

Parameters

Name

Type

Description

meter_id

string

Required. The ID of the meter to retrieve statistics for.

start

number

Required. A Unix timestamp for the beginning of the time range.

end

number

Required. A Unix timestamp for the end of the time range.

customer_id

string

Optional. Filter statistics for a single customer.

granularity

string

Optional. The time-based granularity of the statistics. Can be 'minute', 'hour', or 'day'. Defaults to 'day'.

Returns

An object containing a list of MeterEventStats objects, where each object represents an aggregated data point for a specific time interval.

Example

import payment from '@blocklet/payment-js';

async function getDailyUsageStats(meterId) {
try {
const thirtyDaysAgo = Math.floor((Date.now() - 30 * 24 * 60 * 60 * 1000) / 1000);
const now = Math.floor(Date.now() / 1000);

const stats = await payment.meterEvents.stats({
meter_id: meterId,
start: thirtyDaysAgo,
end: now,
granularity: 'day',
});
console.log('Daily usage stats:', stats.list);
} catch (error) {
console.error('Error getting meter stats:', error.message);
}
}

getDailyUsageStats('mtr_xxxxxxxxxxxxxx');

Example Response

{
"count": 30,
"list": [
{
"date": "2023-02-13T00:00:00.000Z",
"timestamp": "2023-02-13T00:00:00.000Z",
"event_count": 150,
"total_value": "15000"
},
{
"date": "2023-02-14T00:00:00.000Z",
"timestamp": "2023-02-14T00:00:00.000Z",
"event_count": 210,
"total_value": "21000"
}
]
}

Retrieve Pending Amount#

Calculates the total value of meter events that have been reported but not yet successfully processed and billed. This is useful for understanding outstanding, unbilled usage for a customer or subscription.

Parameters

Name

Type

Description

subscription_id

string

Optional. Scope the calculation to a specific subscription.

customer_id

string

Optional. Scope the calculation to a specific customer.

currency_id

string

Optional. Filter by a specific currency ID.

Returns

An object where keys are currency IDs and values are strings representing the total pending amount in the smallest unit of that currency.

Example

import payment from '@blocklet/payment-js';

async function checkPendingUsage(customerId) {
try {
const pendingAmounts = await payment.meterEvents.pendingAmount({
customer_id: customerId,
});
console.log('Pending amounts:', pendingAmounts);
} catch (error) {
console.error('Error getting pending amount:', error.message);
}
}

checkPendingUsage('cust_xxxxxxxxxxxxxx');

Example Response

{
"usd_xxxxxxxxxxxxxx": "50000000000000000000"
}

The response indicates a pending amount of 50 units for the currency with ID usd_xxxxxxxxxxxxxx (assuming 18 decimal places).