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

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

id

string

Unique identifier for the meter event.

event_name

string

The name of the event, which corresponds to a defined meter.

payload

object

An object containing the core details of the event.

payload.customer_id

string

The ID of the customer associated with this usage event.

payload.value

string

The amount of usage to report.

payload.subscription_id

string

(Optional) The ID of the subscription this usage is associated with.

identifier

string

A unique identifier for the event, used for idempotency. Prevents duplicate event submissions.

timestamp

number

Unix timestamp for when the event occurred.

livemode

boolean

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

status

string

The processing status of the event. Can be pending, processing, completed, requires_action, requires_capture, or canceled.

processed_at

number

(Optional) Unix timestamp for when the event was successfully processed.

attempt_count

number

The number of times processing has been attempted for this event.

next_attempt

number

(Optional) Unix timestamp for the next scheduled processing attempt.

credit_consumed

string

The amount of credit consumed by this event after processing.

credit_pending

string

The amount of credit that is pending consumption by this event.

metadata

object

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

created_via

string

How the event was created. Can be api, dashboard, webhook, or batch.

created_at

Date

The creation timestamp for the event record.

updated_at

Date

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

event_name

string

The name of the meter you're reporting usage for.

payload

object

The details of the usage event.

payload.customer_id

string

The ID of the customer who triggered the event.

payload.value

string

The quantity of usage to report.

payload.subscription_id

string

(Optional) The subscription to which this usage should be attributed.

identifier

string

A unique string to prevent duplicate events. We recommend using a V4 UUID.

timestamp

number

(Optional) A Unix timestamp in seconds representing when the usage occurred. Defaults to the current time if not provided.

metadata

object

(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

id

string

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

event_name

string

(Optional) Filter events by the meter name.

meter_id

string

(Optional) Filter events by the meter ID.

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 before this time.

livemode

boolean

(Optional) Filter by live mode or test mode.

q

string

(Optional) A search query to filter events.

page

number

(Optional) The page number for pagination, starting from 1.

pageSize

number

(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

meter_id

string

The ID of the meter to retrieve statistics for.

start

number

A Unix timestamp for the beginning of the time range.

end

number

A Unix timestamp for the end of the time range.

customer_id

string

(Optional) Filter statistics for a specific customer.

granularity

string

(Optional) The granularity of the statistics. Can be minute, hour, or day. Defaults to day.

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

date

string

The date for the aggregated data point (e.g., '2023-03-15').

timestamp

string

The Unix timestamp for the start of the period.

event_count

number

The total number of events in this period.

total_value

string

The sum of the value of all events in this period.

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

subscription_id

string

(Optional) The ID of the subscription to filter by.

customer_id

string

(Optional) The ID of the customer to filter by.

currency_id

string

(Optional) The currency to calculate the pending amount for.

Returns

A PendingAmountSummary object.

PendingAmountSummary Object

Attribute

Type

Description

currency_id

string

The currency of the pending amount.

total_pending

string

The total value of all pending events.

count

number

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.