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

Credit-Based Billing


Credit-based billing is a flexible model ideal for services where customers pay based on consumption, such as API calls, data storage, or compute time. Instead of a fixed recurring fee, customers purchase or are granted credits, which are then consumed as they use the service. PaymentKit provides a complete toolkit to implement this model.

The core components are:

  • Meters: Define and track specific billable events.
  • Credit Grants: Issue credits to customers, either as a purchase or promotion.
  • Meter Events: Report customer usage against a meter.
  • Credit Transactions: Provide a detailed ledger of all credit movements (grants, consumption, expirations).

This guide will walk you through setting up a complete credit-based billing workflow.

The Billing Workflow#

Here is a high-level overview of how the components work together.


Step 1: Create a Meter#

A Meter acts as a counter for a specific type of usage. You must first define what you want to measure. For example, you can create a meter to track the number of API calls a customer makes.

// Step 1: Create a meter to track usage
const meter = await payment.meters.create({
name: 'API Calls',
event_name: 'api.calls.invoked', // A unique name for the event you will report
aggregation_method: 'sum', // Sums the 'value' from all events
unit: 'calls',
description: 'Tracks the number of API calls made by a customer.',
});

console.log('Meter created:', meter.id);

The event_name is a crucial identifier that links usage reports (Meter Events) back to this specific meter.

Step 2: Grant Credits to a Customer#

Before a customer can consume a metered service, they need a credit balance. You can grant credits to a customer using the creditGrants.create method. Credits can be categorized as paid (purchased by the customer) or promotional (given for free).

// Step 2: Create a credit grant for a customer
const creditGrant = await payment.creditGrants.create({
customer_id: 'cus_xxx', // The ID of the customer receiving credits
amount: '1000',
currency_id: 'pc_xxx', // The ID of the credit currency
category: 'promotional',
name: 'New user bonus credits',
// Credits expire in 30 days
expires_at: Math.floor(Date.now() / 1000) + (30 * 24 * 60 * 60),
});

console.log('Credit grant created:', creditGrant.id);

Step 3: Report Usage Events#

As your customer uses the service, your application must report this activity to PaymentKit. This is done by creating a Meter Event. Each event must have a unique identifier to prevent double-counting.

// Step 3: Report a usage event
const meterEvent = await payment.meterEvents.create({
event_name: 'api.calls.invoked', // Must match the meter's event_name
payload: {
customer_id: 'cus_xxx',
value: '10', // The amount of usage to record. For 'sum' aggregation, this is added to the total.
subscription_id: 'sub_xxx', // Optional: associate usage with a subscription
},
identifier: `unique_event_id_${Date.now()}`, // A unique ID to prevent duplicates
timestamp: Math.floor(Date.now() / 1000),
});

console.log('Meter event reported:', meterEvent.id);

Upon receiving the event, PaymentKit automatically finds the customer's active credit grants and deducts the appropriate amount, creating a consumption transaction in the process.

Step 4: Monitor Balances and Transactions#

You can easily check a customer's remaining credit balance or view their complete transaction history.

Check Credit Balance

Use creditGrants.summary to get a consolidated view of a customer's available credits, grouped by currency.

// Step 4a: Check the customer's credit balance
const creditSummary = await payment.creditGrants.summary({
customer_id: 'cus_xxx',
});

// Example: Log the remaining amount for a specific currency
const currencyId = 'pc_xxx';
if (creditSummary[currencyId]) {
console.log(`Remaining balance: ${creditSummary[currencyId].remainingAmount}`);
}

View Transaction History

Use creditTransactions.list to retrieve a paginated log of all credit activities for a customer, including grants, consumptions, and expirations.

// Step 4b: View the customer's transaction history
const transactions = await payment.creditTransactions.list({
customer_id: 'cus_xxx',
page: 1,
pageSize: 10,
});

console.log(`Found ${transactions.total} transactions:`);
transactions.data.forEach(tx => {
console.log(`- ID: ${tx.id}, Type: ${tx.type}, Amount: ${tx.amount}`);
});

Next Steps#

You now have a foundational understanding of how to implement credit-based billing. For more detailed information on each component, refer to the API reference sections. To learn how to allow customers to purchase credits or set up automatic refills, see the Credit Top-Up guide.

These resources provide the tools you need to build a comprehensive credit-based billing system.