Meter Events
Meter Events are used to report usage for metered billing. Each event represents a single instance of usage for a specific customer and meter. These events are then processed to deduct from a customer's credit balance. This API allows you to report usage events, retrieve their history, and get aggregated statistics.
Before reporting events, you should define a meter. For more information, please see the Meters API Reference.
The Meter Event Object#
A Meter Event object represents a single recorded usage event. It contains details about the usage, the customer, and its processing status.
Attribute | Type | Description |
|---|---|---|
|
| Unique identifier for the meter event. |
|
| The name of the event, which corresponds to a defined meter. |
|
| An object containing the core details of the event. |
|
| The ID of the customer associated with this usage event. |
|
| The amount of usage to report. |
|
| (Optional) The ID of the subscription this usage is associated with. |
|
| A unique identifier for the event, used for idempotency. Prevents duplicate event submissions. |
|
| Unix timestamp for when the event occurred. |
|
|
|
|
| The processing status of the event. Can be |
|
| (Optional) Unix timestamp for when the event was successfully processed. |
|
| The number of times processing has been attempted for this event. |
|
| (Optional) Unix timestamp for the next scheduled processing attempt. |
|
| The amount of credit consumed by this event after processing. |
|
| The amount of credit that is pending consumption by this event. |
|
| (Optional) A set of key-value pairs that you can attach to the event object. |
|
| How the event was created. Can be |
|
| The creation timestamp for the event record. |
|
| The last update timestamp for the event record. |
Create an Event#
Reports a usage event to a meter. To ensure that events are not double-counted, you must provide a unique identifier for each event.
Parameters
Parameter | Type | Description |
|---|---|---|
|
| The name of the meter you're reporting usage for. |
|
| The details of the usage event. |
|
| The ID of the customer who triggered the event. |
|
| The quantity of usage to report. |
|
| (Optional) The subscription to which this usage should be attributed. |
|
| A unique string to prevent duplicate events. We recommend using a V4 UUID. |
|
| (Optional) A Unix timestamp in seconds representing when the usage occurred. Defaults to the current time if not provided. |
|
| (Optional) Key-value data to store with the event. |
Returns
The newly created Meter Event object.
import payment from '@blocklet/payment-js';
async function reportUsage() {
try {
const meterEvent = await payment.meterEvents.create({
event_name: 'api_calls',
identifier: 'unique-event-id-12345',
timestamp: Math.floor(Date.now() / 1000),
payload: {
customer_id: 'cus_xxxxxxxxxxxxxx',
value: '100',
subscription_id: 'sub_xxxxxxxxxxxxxx'
},
metadata: {
region: 'us-east-1'
}
});
console.log('Meter event created:', meterEvent.id);
} catch (error) {
console.error('Error creating meter event:', error.message);
}
}
reportUsage();Example Response
{
"id": "mevt_xxxxxxxxxxxxxx",
"event_name": "api_calls",
"payload": {
"customer_id": "cus_xxxxxxxxxxxxxx",
"value": "100",
"subscription_id": "sub_xxxxxxxxxxxxxx"
},
"identifier": "unique-event-id-12345",
"timestamp": 1678886400,
"livemode": false,
"status": "pending",
"processed_at": null,
"attempt_count": 0,
"next_attempt": 1678886460,
"credit_consumed": "0",
"credit_pending": "100",
"metadata": {
"region": "us-east-1"
},
"created_via": "api",
"created_at": "2023-03-15T12:00:00.000Z",
"updated_at": "2023-03-15T12:00:00.000Z"
}Retrieve an Event#
Retrieves the details of an existing meter event by its unique ID.
Parameters
Parameter | Type | Description |
|---|---|---|
|
| The unique identifier of the meter event to retrieve. |
Returns
The Meter Event object.
import payment from '@blocklet/payment-js';
async function getMeterEvent(eventId) {
try {
const meterEvent = await payment.meterEvents.retrieve(eventId);
console.log('Retrieved meter event:', meterEvent);
} catch (error) {
console.error('Error retrieving meter event:', error.message);
}
}
getMeterEvent('mevt_xxxxxxxxxxxxxx');Example Response
{
"id": "mevt_xxxxxxxxxxxxxx",
"event_name": "api_calls",
"payload": {
"customer_id": "cus_xxxxxxxxxxxxxx",
"value": "100",
"subscription_id": "sub_xxxxxxxxxxxxxx"
},
"identifier": "unique-event-id-12345",
"timestamp": 1678886400,
"livemode": false,
"status": "completed",
"processed_at": 1678886405,
"attempt_count": 1,
"next_attempt": null,
"credit_consumed": "100",
"credit_pending": "0",
"metadata": {
"region": "us-east-1"
},
"created_via": "api",
"created_at": "2023-03-15T12:00:00.000Z",
"updated_at": "2023-03-15T12:00:05.000Z"
}List Events#
Returns a paginated list of meter events, which can be filtered by various parameters.
Parameters
Parameter | Type | Description |
|---|---|---|
|
| (Optional) Filter events by the meter name. |
|
| (Optional) Filter events by the meter ID. |
|
| (Optional) Filter events for a specific customer. |
|
| (Optional) A Unix timestamp to filter events created on or after this time. |
|
| (Optional) A Unix timestamp to filter events created before this time. |
|
| (Optional) Filter by live mode or test mode. |
|
| (Optional) A search query to filter events. |
|
| (Optional) The page number for pagination, starting from 1. |
|
| (Optional) The number of items per page. Defaults to 20. |
Returns
A paginated object containing a count of total items and a list of Meter Event objects.
import payment from '@blocklet/payment-js';
async function listCustomerEvents(customerId) {
try {
const events = await payment.meterEvents.list({
customer_id: customerId,
pageSize: 5
});
console.log(`Found ${events.count} events for customer.`);
events.list.forEach(event => {
console.log(`- Event ID: ${event.id}, Status: ${event.status}`);
});
} catch (error) {
console.error('Error listing meter events:', error.message);
}
}
listCustomerEvents('cus_xxxxxxxxxxxxxx');Example Response
{
"count": 15,
"list": [
{
"id": "mevt_xxxxxxxxxxxxxx",
"event_name": "api_calls",
"status": "completed",
"value": "100",
"timestamp": 1678886400
},
{
"id": "mevt_yyyyyyyyyyyyyy",
"event_name": "data_storage",
"status": "completed",
"value": "50",
"timestamp": 1678883200
}
]
}Get Statistics#
Retrieves aggregated statistics for a specific meter over a given time range. This is useful for building dashboards and reports.
Parameters
Parameter | Type | Description |
|---|---|---|
|
| The ID of the meter to retrieve statistics for. |
|
| A Unix timestamp for the beginning of the time range. |
|
| A Unix timestamp for the end of the time range. |
|
| (Optional) Filter statistics for a specific customer. |
|
| (Optional) The granularity of the statistics. Can be |
Returns
A paginated object containing a list of MeterEventStats objects. Each object in the list represents a data point for the specified granularity.
MeterEventStats Object
Attribute | Type | Description |
|---|---|---|
|
| The date for the aggregated data point (e.g., '2023-03-15'). |
|
| The Unix timestamp for the start of the period. |
|
| The total number of events in this period. |
|
| The sum of the |
import payment from '@blocklet/payment-js';
async function getMeterStats(meterId) {
try {
const oneMonthAgo = Math.floor(Date.now() / 1000) - 30 * 24 * 60 * 60;
const now = Math.floor(Date.now() / 1000);
const stats = await payment.meterEvents.stats({
meter_id: meterId,
start: oneMonthAgo,
end: now,
granularity: 'day'
});
console.log('Daily stats for the last 30 days:');
stats.list.forEach(stat => {
console.log(`${stat.date}: ${stat.total_value} usage from ${stat.event_count} events`);
});
} catch (error) {
console.error('Error getting meter stats:', error.message);
}
}
getMeterStats('mtr_xxxxxxxxxxxxxx');Example Response
{
"count": 30,
"list": [
{
"date": "2023-03-15",
"timestamp": "1678838400",
"event_count": 120,
"total_value": "12000"
},
{
"date": "2023-03-14",
"timestamp": "1678752000",
"event_count": 110,
"total_value": "11000"
}
]
}Get Pending Amount#
Calculates the total value of pending meter events for a given customer or subscription, grouped by currency.
Parameters
Parameter | Type | Description |
|---|---|---|
|
| (Optional) The ID of the subscription to filter by. |
|
| (Optional) The ID of the customer to filter by. |
|
| (Optional) The currency to calculate the pending amount for. |
Returns
A PendingAmountSummary object.
PendingAmountSummary Object
Attribute | Type | Description |
|---|---|---|
|
| The currency of the pending amount. |
|
| The total value of all pending events. |
|
| The number of pending events. |
import payment from '@blocklet/payment-js';
async function checkPendingAmount(subscriptionId) {
try {
const summary = await payment.meterEvents.pendingAmount({
subscription_id: subscriptionId
});
console.log(`Pending amount for subscription: ${summary.total_pending} ${summary.currency_id}`);
} catch (error) {
console.error('Error fetching pending amount:', error.message);
}
}
checkPendingAmount('sub_xxxxxxxxxxxxxx');Example Response
{
"currency_id": "ucrd_xxxxxxxx",
"total_pending": "500",
"count": 5
}After reporting usage with Meter Events, you can manage how customers pay for this usage through credits. To learn how to issue credits to your customers, see the Credit Grants API Reference.