Introducing the Chargebee CLI

Offer prepaid credits that customers spend across your products at different rates

Overview

If your business uses fully prepaid pricing, where your customers buy credits and apply them to their products at different rates, use this guide to set it up in Chargebee Billing. You send usage events; Chargebee converts them into credits based on the credit value defined for each product, and deducts the resulting credits from the shared balance. This is the usage ingestion pipeline.

Throughout this guide, you configure one running example. Acme Inc. sells article generation, image generation, and video generation. All three spend AI Credits.

John Doe subscribes to Growth: $12,000 per year, with 10,000 AI Credits granted each month. One article deducts 1 AI Credit, one image deducts 10, and one video deducts 50. Enterprise is $30,000 per year, with 50,000 AI Credits granted each month, and uses the same credit rates. Unused credits expire at the end of the grant period. This guide does not invoice usage past the grant.

How prepaid credits work when Chargebee converts usage

The illustration below explains how this billing model works:

Before you start

If you don't already have a Chargebee Billing account, click here to sign up.

Confirm your access. You need an admin role to change site configuration and build the Product Catalog.

Advanced Usage-Based Billing is enabled by default for new Chargebee Billing sites. If you are an existing user, enable it before you build the model.

Prepaid Credits is in early access. Contact Chargebee Support to request access before you build the model.

Validate before go-live

Before enabling this on a live site, validate one grant cycle on a test site with Time Machine. Create a Growth subscription, confirm the monthly grant of 10,000 AI Credits, ingest an article event, an image event, and a video event, and confirm the credit balance drops by 1, 10, and 50. Advance to the next grant date and confirm unused credits expired.

When you enter Time Machine, existing subscriptions and customer details on the test site are erased. Export the data first if you need a backup.

When you are ready to go live, copy the configuration and Product Catalog from the test site to the live site with Transfer Configurations. To transfer customer, subscription, or invoices data, you can import them on your live site.

Implementation steps

Follow these steps in order. Each step shows how to do the task in the Chargebee Billing app and with the API where the API accepts the setting.

1. Define the credit unit

A credit unit is the currency customers spend. Create it once. Grants, credit rates, and credit-balance alerts all use this unit.

Usage events are processed asynchronously, so Chargebee cannot stop a product action at the moment the balance hits zero. If a deduction would pass the allowed negative balance, Chargebee still accepts the usage event, but the credit deduction fails and the balance does not change. For this pipeline, set the allowed negative balance to infinite so deductions are not rejected. Leaving Allowed negative balance blank sets the limit to zero. It does not set the limit to infinite.

Using the app
  1. Click Settings > Configure Chargebee > Credit Units.
  2. Select Create a credit unit.
  3. Enter the external name, internal name, and credit unit ID. A site supports up to five credit units.
  4. Click Create.
  5. Confirm the saved unit allows an infinite negative balance. If the app saved a blank Allowed negative balance, the limit is zero. Recreate the unit with the API below.
FieldValue
External nameAI Credits
Internal nameAI Credits
Credit unit IDai_credits
Using the API

Create the credit unit with Create a credit unit. is_unlimited set to true is the uncapped negative balance this pipeline needs. This guide does not attach an overage addon, so usage past the grant is not invoiced. Gate access in your application.

curl  https://{site}.chargebee.com/api/v2/credit_units \
     -u {site_api_key}:\
     -d id="ai_credits" \
     -d name="AI Credits" \
     -d external_name="AI Credits" \
     -d is_unlimited=true

You can update the external name and internal name later. Renaming does not change the name existing subscriptions already show. Archiving a credit unit blocks new grants. Existing subscriptions that use the unit continue to work.

2. Send usage events into Chargebee Billing

Start streaming each product's usage into Chargebee Billing. For Acme, one event is one article, one image, or one video. Chargebee stores any additional properties you send, deduplicates repeated events, and keeps the raw stream queryable.

You can send usage in one of the following ways.

Using the app

CSV bulk upload. Each row must include a deduplication ID, subscription ID, and usage timestamp in milliseconds.

  1. Go to Usages > Usage Events > Add Usage Events.
  2. Select the Quick file upload tab, upload the file, and click Proceed to review.
  3. Review the data, then click Import Events.

You can also add a small number of events manually. Go to Usages > Usage Events > Add Usage Events, select Enter usage events, and click Import Events.

Using the API

Usage events use the ingest host ({site}.ingest.chargebee.com), not the standard Chargebee API host. See Ingest a usage event and Ingest usage events in batch.

Ingest one image

curl  https://{site}.ingest.chargebee.com/api/v2/usage_events \
     -u {site_api_key}:\
     --header 'Content-Type: application/json;charset=UTF-8' \
     --data '{
     "deduplication_id": "image-0001",
     "subscription_id": "{subscription_id}",
     "usage_timestamp": "1737612931000",
     "properties": {
          "image_count": 1
     }
}'

Send an article with article_count set to 1, or a video with video_count set to 1, and a new deduplication_id. Batch ingestion accepts up to 500 events per request.

Using Amazon S3

Upload usage event files from an S3 bucket. Chargebee Billing picks them up and processes them automatically. See Ingesting usage from Amazon S3.

Backdated ingestion limits differ by method and site type. On a live site, the Usage Events API accepts events from the last 12 hours (configurable on request); CSV and S3 uploads accept events from the last 30 days. On a test site, the API window is 12 hours and file uploads accept events from the last year. See Usage-Based Billing limits.

3. Define metered features and set their credit rates

Create the metered features

A metered feature tells Chargebee how to aggregate raw events. Create one feature per product, each with SUM aggregation.

Credit rates apply to metered features with SUM or COUNT aggregation. For this example, create the features before configuring their rates.

Using the app
  1. Go to Usages > Metered Features and click Create Metered Feature.
  2. Create Image generations with Sum on image_count.
  3. Repeat for Article generations on article_count and Video generations on video_count.
FieldImage generationsArticle generationsVideo generations
Aggregation methodSUMSUMSUM
Event propertyimage_countarticle_countvideo_count
Using the API

Use Create a metered feature. Repeat the call for articles and videos, changing the name, unit, and column.

curl  https://{site}.chargebee.com/api/v2/metered_features \
     -u {site_api_key}:\
     -d name="Image generations" \
     -d feature_unit="image" \
     -d description="Number of images generated." \
     -d query="SELECT SUM(image_count) from events" \
     -d "column_definitions[column_name][0]"="image_count" \
     -d "column_definitions[data_type][0]"="NUMBER"

Do not set included usage on these features for subscriptions that should draw credits. Included usage greater than 0 puts the feature in included-usage mode, and Chargebee does not deduct credits for it.

Set credit rates on the metered features

A credit rate tells Chargebee how many credits to deduct for usage on a metered feature. Set it only for the usage ingestion pipeline.

Per unit multiplies the usage quantity by the credits per unit. At 10 AI Credits per image, 50 images deduct 500 AI Credits.

This example uses per-unit rates.

Metered featureCredit rate typeCredits
Article generationsPer unit1 AI Credit
Image generationsPer unit10 AI Credits
Video generationsPer unit50 AI Credits
Using the app
  1. Go to Usages > Metered Features and open Image generations.
  2. In Credit rate, click Set credit rate.
  3. Select the credit unit AI Credits.
  4. Select the credit rate type Per unit.
  5. Enter 10 credits. Click Save.
  6. Repeat for article generations at 1 credit per unit and video generations at 50 credits per unit.

If a cost depends on several attributes, such as model and resolution, use the direct credit ledger or create a separate metered feature for each combination.

Manage changes to credit rates

Each change to a credit rate creates a new version. New subscriptions use the latest version. When you save a new version, choose how existing subscriptions adopt it:

OptionExisting subscriptionsNew subscriptions
Apply to new subscriptionsKeep the credit rate already in effect.Use the new credit rate.
Apply at renewalSubscriptions that use the metered feature's credit rate switch at their next renewal.Use the new credit rate.

A credit rate update does not change a subscription that has a credit rate override for that feature. The same choice applies the first time you set a credit rate on a feature that existing subscriptions already use. Apply at renewal makes those subscriptions start deducting credits for usage that previously did not. Tell affected customers before you save.

4. Define the credit grants for your plans

The plan is the yearly fee. The credit grant on the plan price is the monthly allowance.

4a. Create the plans

Using the app
  1. Click Product Catalog > Plans > Create Plan.
  2. Create Growth and Enterprise in the same product family. Do not mark either plan as metered.
Using the API

Use Create an item. Replace {item_family_id} with your product family ID. Repeat for Enterprise with id set to enterprise and name set to Enterprise.

curl  https://{site}.chargebee.com/api/v2/items \
     -u {site_api_key}:\
     -d id="growth" \
     -d name="Growth" \
     -d type="PLAN" \
     -d item_family_id="{item_family_id}" \
     -d metered=false

4b. Define the plan price points

Using the app
  1. Open the Growth plan. In Pricing, click Set Price for the yearly frequency.
  2. Set the price to 12000, currency USD, and billing frequency Yearly. Click Create.
  3. Repeat for Enterprise at 30000 USD yearly.
Using the API

Use Create an item price. price is in cents.

curl  https://{site}.chargebee.com/api/v2/item_prices \
     -u {site_api_key}:\
     -d id="growth-USD-yearly" \
     -d item_id="growth" \
     -d name="Growth USD yearly" \
     -d pricing_model="FLAT_FEE" \
     -d price=1200000 \
     -d currency_code="USD" \
     -d period_unit="YEAR" \
     -d period=1

Repeat for enterprise-USD-yearly with price set to 3000000.

4c. Configure the credit grant on each price

SettingGrowthEnterprise
Credit unitAI CreditsAI Credits
Grant quantity1000050000
Grant frequencyMonthlyMonthly
RolloverNo rolloverNo rollover
Using the app
  1. Open the Growth yearly item price.
  2. In the Credit Grant section, click Configure Grant.
  3. Select AI Credits, set the grant quantity to 10000, set the grant frequency to Monthly, and select No rollover. Click Save.
  4. Repeat for the Enterprise yearly item price with a grant quantity of 50000.
Using the API

Create an item price and Update an item price do not accept the credit grant. Save the grant with Configure Grant. Chargebee issues it when the customer subscribes.

You cannot change the credit unit on a plan or an active subscription after the grant is saved. Edits to quantity, frequency, or rollover create a new grant version. Existing subscriptions keep the version they already have until the next billing term. Mid-cycle proration of a credit grant is not supported.

To give one subscription a different quantity or rollover, open the subscription, select Manage Credit Grants, and save the override. The credit unit stays the same.

5. Define credit alerts and be notified

A Credits alert triggers when the prepaid credit balance for one credit unit drops to or below the amount you set.

Create the credit-balance alert before customers can exhaust the pool. The alert fires when the AI Credits balance drops to 0. See Usage Alerts and Setting up Alerts. Configure a webhook endpoint and include the alert_status_changed event before you rely on the alert. See Webhook settings.

Create a Credits alert

Using the app
  1. Go to Usages > Alerts and click Create Alert.
  2. Enter the Alert name AI credits exhausted and the Alert description Notify when AI Credits drop to 0.
  3. Under Alert Type, select Credits.
  4. In Set criteria for sending alert, select AI Credits.
  5. Enter 0. The form shows drops to and the unit name after the amount.
  6. Under Apply Alert to, leave All Subscriptions selected. Subscriptions containing specific items is unavailable for Credits.
  7. Under Alert delivery channel, click Manage connected webhooks and select the endpoint that will receive alert_status_changed. Chargebee Billing opens Settings > Configure Chargebee > API Keys and Webhooks on the Webhooks tab.
  8. Click Save Alert.
Using the API
curl  https://{site}.chargebee.com/api/v2/alerts \
     -u {site_api_key}:\
     -d type="credit_balance_dropped" \
     -d name="AI credits exhausted" \
     -d description="Notify when AI Credits drop to 0" \
     -d unit_id="ai_credits" \
     -d "threshold[mode]"="absolute" \
     -d "threshold[value]"=0

See Create an alert. Do not send metered_feature_id or currency_code on this alert type.

Take action when the threshold is reached

When alert_status_changed reports in_alarm, your application rejects the next article, image, or video. Chargebee does not enforce that stop. There is no prebuilt webhook for a hard cutoff. Use the Credits alert for the low-balance notification.

6. Create the customer and subscription

Create the subscription on the Growth yearly plan. Do not attach a metered overage addon. The monthly grant of 10,000 AI Credits is provisioned when the subscription is active.

Using the app
  1. Go to Customers and create a customer record for John Doe if one doesn't already exist.
  2. From the customer, select Create a subscription.
  3. Select the product family and the Growth yearly plan. The subscription shows the credit grant of 10,000 AI Credits per month.
  4. Select Create.
Using the API

Create the customer with Create a customer, then create the subscription with Create a subscription for items.

curl  https://{site}.chargebee.com/api/v2/customers \
     -u {site_api_key}:\
     -d first_name="John" \
     -d last_name="Doe" \
     -d email="jdoe@example.com"
curl  https://{site}.chargebee.com/api/v2/customers/{customer_id}/subscription_for_items \
     -u {site_api_key}:\
     -d "subscription_items[item_price_id][0]"="growth-USD-yearly"

After the subscription exists, the subscription record lists the credit rate for each feature that draws from the grant. To give one customer a different rate, open Credit rate, click Manage, click Override, change the rate, then click Apply and Save Changes. An override must use a credit unit the subscription has a grant for. An override takes precedence over later updates to the metered feature's credit rate.

Changing an override on an active subscription applies to later usage immediately for both per-unit and package rates.

7. Deduct credits by sending usage events

Send the usage events from step 1 for the active subscription. For each event, Chargebee:

  1. Uses the subscription's credit rate override when one exists. Otherwise it uses the metered feature's credit rate.
  2. Applies that rate to the usage quantity.
  3. Deducts the credits from the grant that was valid at the event timestamp, starting with the grant that expires soonest.
  4. Records the deduction in the credit ledger.

One image deducts 10 AI Credits. One article deducts 1. One video deducts 50. Open the subscription and check the credit balance and credit ledger to confirm the deduction.

8. Track usage against your subscriptions

Check the shared credit balance during the term. On Growth, the grant is 10,000 AI Credits each month. Article generation, image generation, and video generation draw from that balance.

Using the app

Open the subscription and view the ledger and credit balance under the Credit balance section.

Using the API

Read the live balance from the ledger. provisioned_balance.usable_balance is the amount available to spend on article generation, image generation, and video generation. provisioned_balance.hold_amount is reserved by authorize operations and is not usable. provisioned_balance.total_balance is usable balance plus held amount. Credit amounts are decimal strings. Keep them as strings when you format or calculate the balance.

Use this balance for the headline total. Grants expire on their own, and the grant list is paginated, so a sum of one page of grant blocks can miss credits.

curl  https://{site}.chargebee.com/api/v2/ledger_account_balances \
     -G \
     -u {site_api_key}:\
     --data-urlencode "subscription_id[is]"="{subscription_id}" \
     --data-urlencode "unit_id[is]"="ai_credits"

See List ledger account balances. List ledger operations when you need the customer's credit history. Grants, usage deductions, rollovers, and expiries appear there as separate operation types.

You can show the remaining balance in your product with the same APIs. See Show prepaid credit balances, grants, and transactions in your customer portal.

Offer a trial period

A trial lets customers try article, image, and video generation before the first paid term. A trial that uses prepaid credits starts immediately and needs no extra credit setup. Chargebee grants plan and addon credits only when the trial ends and the subscription becomes active, so the trial does not use the customer’s first monthly grant. When the trial ends, Chargebee converts the subscription to active and attempts the first payment. See Trial periods.

FAQ

Why might a usage event not deduct credits?

Chargebee accepts and records the usage event even when it does not deduct credits. A deduction does not happen when any of the following is true:

  • The event timestamp falls in a grant period that has expired, and the event arrives after that grant's grace period. The grace period is 12 hours by default. A usage event timestamped August 31 at 11:55 PM that arrives on September 1 at 6:00 AM deducts from the August grant, not the September grant, because it arrives inside that grace period.
  • The deduction would pass the credit unit's allowed negative balance.
  • The metered feature uses an aggregation other than SUM or COUNT.
  • The feature has included usage greater than 0 on the subscription.
  • The feature has no credit rate in the subscription's credit unit.
  • The subscription's credit rate override for the feature is disabled.
  • The subscription has no credit grant to draw from.

A usage event with a negative quantity corrects the usage summary. It does not return credits to the balance.

Chargebee does not reject a usage event when the credit balance runs out. To block the next article, image, or video, gate access in your application.

Summary

This guide showed you how to:

  • Send article, image, and video usage events into Chargebee Billing.
  • Grant 10,000 AI Credits each month on Growth and 50,000 on Enterprise, with no rollover.
  • Set per-unit credit rates of 1, 10, and 50 AI Credits, and let Chargebee deduct those credits from one shared balance.
  • Alert your application when the balance is exhausted, without invoicing usage past the grant.