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 |
---|---|---|
| string | Unique identifier for the meter event. |
| string | The name of the event, which links it to a specific meter. |
| object | An object containing details about the usage, such as |
| string | A unique key provided by you to prevent duplicate event creation. |
| number | Unix timestamp indicating when the usage occurred. |
| string | The processing status of the event. Can be |
| boolean |
|
| boolean |
|
| string | The amount of credit that has been consumed by this event. |
| string | The amount of credit pending consumption for this event. |
| 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 |
---|---|---|
| string | Required. The name of the event, which must correspond to an active meter's |
| object | Required. An object containing the event's core data. See details below. |
| string | Required. A unique identifier for this event to ensure idempotency. The system will reject any new event with a previously used identifier. |
| number | Optional. A Unix timestamp for when the event occurred. If not provided, it defaults to the time of the API call. |
| Record<string, any> | Optional. A set of key-value pairs to store additional information on the object. |
Payload Object Properties
Name | Type | Description |
---|---|---|
| string | Required. The ID of the customer who generated the usage event. |
| string | Required. The amount of usage to report. This should be a positive number representing the quantity of the metered resource consumed. |
| 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 |
---|---|---|
| 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 |
---|---|---|
| string | Optional. Filter events by a specific event name. |
| string | Optional. Filter events associated with a specific meter. |
| string | Optional. Filter events for a specific customer. |
| number | Optional. A Unix timestamp to filter events created on or after this time. |
| number | Optional. A Unix timestamp to filter events created on or before this time. |
| boolean | Optional. Filter by live or test mode. |
| string | Optional. A generic search query string. |
| number | Optional. The page number for pagination, starting at 1. |
| 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 |
---|---|---|
| string | Required. The ID of the meter to retrieve statistics for. |
| number | Required. A Unix timestamp for the beginning of the time range. |
| number | Required. A Unix timestamp for the end of the time range. |
| string | Optional. Filter statistics for a single customer. |
| string | Optional. The time-based granularity of the statistics. Can be |
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 |
---|---|---|
| string | Optional. Scope the calculation to a specific subscription. |
| string | Optional. Scope the calculation to a specific customer. |
| 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).