--- title: Set up usage-based billing with products and prices subtitle: Charge customers based on their usage of your product or service. route: /billing/subscriptions/usage-based/implementation-guide --- # Set up usage-based billing with products and prices Charge customers based on their usage of your product or service. Usage-based billing enables you to charge customers based on their usage of your product or service. This guide demonstrates how to create a meter, set up pricing and billing, and send meter events to record customer usage using [Products](https://docs.stripe.com/api/products.md) and [Prices](https://docs.stripe.com/api/prices.md). You’ll learn core concepts of a usage-based billing model through a fictional GenAI company called Alpaca AI. Alpaca AI charges their customers 0.04 USD per hundred tokens, and bills them at the end of the month in arrears. Here’s what the lifecycle looks like for a typical [usage-based billing](https://docs.stripe.com/billing/subscriptions/usage-based.md) integration that uses products and prices: ## Create a meter Meters specify how to aggregate meter events over a billing period. Meter events represent all actions that customers take in your system (for example, API requests). Meters attach to prices and form the basis of what’s billed. For the Alpaca AI example, meter events are the number of tokens a customer uses in a query. The meter is the sum of tokens over a month. You can use the Stripe Dashboard or API to [configure a meter](https://docs.stripe.com/billing/subscriptions/usage-based/meters/configure.md). To use the API with the Stripe CLI to create a meter, [get started with the Stripe CLI](https://docs.stripe.com/stripe-cli.md). 1. On the [Meters](https://dashboard.stripe.com/test/meters) page, click **Create meter**. 1. On the **Create meter** page, do the following: - For **Meter name**, enter the name of the meter to display and for organization purposes. For the Alpaca AI example, enter “Alpaca AI tokens.” - For **Event name**, enter the name to display in meter events when reporting usage to Stripe. For the Alpaca AI example, enter “alpaca_ai_tokens.” - Select **Sum** from the **Aggregation method** dropdown to set the aggregation formula. - Click **Create meter**. ```dotnet StripeConfiguration.ApiKey = "<>"; var options = new Stripe.Billing.MeterCreateOptions { DisplayName = "Alpaca AI tokens", EventName = "alpaca_ai_tokens", DefaultAggregation = new Stripe.Billing.MeterDefaultAggregationOptions { Formula = "sum" }, CustomerMapping = new Stripe.Billing.MeterCustomerMappingOptions { EventPayloadKey = "stripe_customer_id", Type = "by_id", }, ValueSettings = new Stripe.Billing.MeterValueSettingsOptions { EventPayloadKey = "value" }, }; var service = new Stripe.Billing.MeterService(); Stripe.Billing.Meter meter = service.Create(options); ``` ```go stripe.Key = "<>" params := &stripe.BillingMeterParams{ DisplayName: stripe.String("Alpaca AI tokens"), EventName: stripe.String("alpaca_ai_tokens"), DefaultAggregation: &stripe.BillingMeterDefaultAggregationParams{ Formula: stripe.String(string(stripe.BillingMeterDefaultAggregationFormulaSum)), }, CustomerMapping: &stripe.BillingMeterCustomerMappingParams{ EventPayloadKey: stripe.String("stripe_customer_id"), Type: stripe.String("by_id"), }, ValueSettings: &stripe.BillingMeterValueSettingsParams{EventPayloadKey: stripe.String("value")}, }; result, err := meter.New(params); ``` ```java Stripe.apiKey = "<>"; MeterCreateParams params = MeterCreateParams.builder() .setDisplayName("Alpaca AI tokens") .setEventName("alpaca_ai_tokens") .setDefaultAggregation( MeterCreateParams.DefaultAggregation.builder() .setFormula(MeterCreateParams.DefaultAggregation.Formula.SUM) .build() ) .setCustomerMapping( MeterCreateParams.CustomerMapping.builder() .setEventPayloadKey("stripe_customer_id") .setType(MeterCreateParams.CustomerMapping.Type.BY_ID) .build() ) .setValueSettings(MeterCreateParams.ValueSettings.builder().setEventPayloadKey("value").build()) .build(); Meter meter = Meter.create(params); ``` ```node const stripe = require('stripe')('<>'); const meter = await stripe.billing.meters.create({ display_name: 'Alpaca AI tokens', event_name: 'alpaca_ai_tokens', default_aggregation: { formula: 'sum', }, customer_mapping: { event_payload_key: 'stripe_customer_id', type: 'by_id', }, value_settings: { event_payload_key: 'value', }, }); ``` ```python import stripe stripe.api_key = "<>" meter = stripe.billing.Meter.create( display_name="Alpaca AI tokens", event_name="alpaca_ai_tokens", default_aggregation={"formula": "sum"}, customer_mapping={"event_payload_key": "stripe_customer_id", "type": "by_id"}, value_settings={"event_payload_key": "value"}, ) ``` ```php $stripe = new \Stripe\StripeClient('<>'); $meter = $stripe->billing->meters->create([ 'display_name' => 'Alpaca AI tokens', 'event_name' => 'alpaca_ai_tokens', 'default_aggregation' => ['formula' => 'sum'], 'customer_mapping' => [ 'event_payload_key' => 'stripe_customer_id', 'type' => 'by_id', ], 'value_settings' => ['event_payload_key' => 'value'], ]); ``` ```ruby Stripe.api_key = '<>' meter = Stripe::Billing::Meter.create({ display_name: 'Alpaca AI tokens', event_name: 'alpaca_ai_tokens', default_aggregation: {formula: 'sum'}, customer_mapping: { event_payload_key: 'stripe_customer_id', type: 'by_id', }, value_settings: {event_payload_key: 'value'}, }) ``` ## Create a pricing model Use the Stripe Dashboard or API to create a [pricing model](https://docs.stripe.com/products-prices/pricing-models.md) that includes your [Products](https://docs.stripe.com/api/products.md) and their pricing options. [Prices](https://docs.stripe.com/api/prices.md) define the unit cost, currency, and billing cycle. For the Alpaca AI example, you create a product with a metered price of 0.04 USD per hundred units, billed at a monthly interval. You use the meter that you created in the previous step. 1. On the [Product catalog](https://dashboard.stripe.com/products?active=true) page, click **Create product**. 1. On the **Add a product** page, do the following: - For **Name**, enter the name of your product. For the Alpaca AI example, enter `Alpaca AI`. - _(Optional)_ For **Description**, add a description that appears at checkout in the [customer portal](https://docs.stripe.com/customer-management.md) and in [quotes](https://docs.stripe.com/quotes.md). - Select **Recurring**. - Under **Billing period**, select **More pricing options**. 1. On the **Add price** page, do the following: - Under **Choose your pricing model**, select **Usage-based** and **Per package**. - Under **Price**, set the **Amount** to `0.04 USD` per `1000` units. - Under **Meter**, select **Alpaca AI tokens** from the dropdown. - Under **Billing period**, select **Monthly**. - Click **Next**. 1. On the **Add a product** page, click **Add product**. You can locate your meter ID on the meter details page. ```dotnet StripeConfiguration.ApiKey = "<>"; var options = new PriceCreateOptions { Currency = "usd", UnitAmount = 4, BillingScheme = "per_unit", TransformQuantity = new PriceTransformQuantityOptions { DivideBy = 1000, Round = "up" }, Recurring = new PriceRecurringOptions { UsageType = "metered", Interval = "month", Meter = "{{METER_ID}}", }, ProductData = new PriceProductDataOptions { Name = "Alpaca AI tokens" }, }; var service = new PriceService(); Price price = service.Create(options); ``` ```go stripe.Key = "<>" params := &stripe.PriceParams{ Currency: stripe.String(string(stripe.CurrencyUSD)), UnitAmount: stripe.Int64(4), BillingScheme: stripe.String(string(stripe.PriceBillingSchemePerUnit)), TransformQuantity: &stripe.PriceTransformQuantityParams{ DivideBy: stripe.Int64(1000), Round: stripe.String(string(stripe.PriceTransformQuantityRoundUp)), }, Recurring: &stripe.PriceRecurringParams{ UsageType: stripe.String(string(stripe.PriceRecurringUsageTypeMetered)), Interval: stripe.String(string(stripe.PriceRecurringIntervalMonth)), Meter: stripe.String("{{METER_ID}}"), }, ProductData: &stripe.PriceProductDataParams{Name: stripe.String("Alpaca AI tokens")}, }; result, err := price.New(params); ``` ```java Stripe.apiKey = "<>"; PriceCreateParams params = PriceCreateParams.builder() .setCurrency("usd") .setUnitAmount(4L) .setBillingScheme(PriceCreateParams.BillingScheme.PER_UNIT) .setTransformQuantity( PriceCreateParams.TransformQuantity.builder() .setDivideBy(1000L) .setRound(PriceCreateParams.TransformQuantity.Round.UP) .build() ) .setRecurring( PriceCreateParams.Recurring.builder() .setUsageType(PriceCreateParams.Recurring.UsageType.METERED) .setInterval(PriceCreateParams.Recurring.Interval.MONTH) .setMeter("{{METER_ID}}") .build() ) .setProductData(PriceCreateParams.ProductData.builder().setName("Alpaca AI tokens").build()) .build(); Price price = Price.create(params); ``` ```node const stripe = require('stripe')('<>'); const price = await stripe.prices.create({ currency: 'usd', unit_amount: 4, billing_scheme: 'per_unit', transform_quantity: { divide_by: 1000, round: 'up', }, recurring: { usage_type: 'metered', interval: 'month', meter: '{{METER_ID}}', }, product_data: { name: 'Alpaca AI tokens', }, }); ``` ```python import stripe stripe.api_key = "<>" price = stripe.Price.create( currency="usd", unit_amount=4, billing_scheme="per_unit", transform_quantity={"divide_by": 1000, "round": "up"}, recurring={"usage_type": "metered", "interval": "month", "meter": "{{METER_ID}}"}, product_data={"name": "Alpaca AI tokens"}, ) ``` ```php $stripe = new \Stripe\StripeClient('<>'); $price = $stripe->prices->create([ 'currency' => 'usd', 'unit_amount' => 4, 'billing_scheme' => 'per_unit', 'transform_quantity' => [ 'divide_by' => 1000, 'round' => 'up', ], 'recurring' => [ 'usage_type' => 'metered', 'interval' => 'month', 'meter' => '{{METER_ID}}', ], 'product_data' => ['name' => 'Alpaca AI tokens'], ]); ``` ```ruby Stripe.api_key = '<>' price = Stripe::Price.create({ currency: 'usd', unit_amount: 4, billing_scheme: 'per_unit', transform_quantity: { divide_by: 1000, round: 'up', }, recurring: { usage_type: 'metered', interval: 'month', meter: '{{METER_ID}}', }, product_data: {name: 'Alpaca AI tokens'}, }) ``` ## Create a customer Next, create a *customer*. 1. On the [Customers](https://dashboard.stripe.com/test/customers) page, click **Add customer**. 1. On the **Create customer** page, do the following: - For **Name**, enter the name of your customer. For the Alpaca AI example, enter `John Doe`. - _(Optional)_ Add an email address and description for your customer. - Click **Add customer**. ```dotnet StripeConfiguration.ApiKey = "<>"; var options = new CustomerCreateOptions { Name = "John Doe" }; var service = new CustomerService(); Customer customer = service.Create(options); ``` ```go stripe.Key = "<>" params := &stripe.CustomerParams{Name: stripe.String("John Doe")}; result, err := customer.New(params); ``` ```java Stripe.apiKey = "<>"; CustomerCreateParams params = CustomerCreateParams.builder().setName("John Doe").build(); Customer customer = Customer.create(params); ``` ```node const stripe = require('stripe')('<>'); const customer = await stripe.customers.create({ name: 'John Doe', }); ``` ```python import stripe stripe.api_key = "<>" customer = stripe.Customer.create(name="John Doe") ``` ```php $stripe = new \Stripe\StripeClient('<>'); $customer = $stripe->customers->create(['name' => 'John Doe']); ``` ```ruby Stripe.api_key = '<>' customer = Stripe::Customer.create({name: 'John Doe'}) ``` ## Create a subscription [Subscriptions](https://docs.stripe.com/api/subscriptions.md) allow you to charge recurring amounts by associating a customer with a specific price. Use the Stripe Dashboard or API to create a subscription that includes your customer, product, and usage-based price. For the Alpaca AI example, you create a subscription for the Alpaca AI product, with a metered price of 0.04 USD per unit, billed monthly to John Doe. You can associate a single metered price with one or more subscriptions. 1. On the [Subscriptions](https://dashboard.stripe.com/test/subscriptions) page, click **Create test subscription**. 1. On the **Create a test subscription** page, do the following: - Under **Customer**, select the name of your customer. For the Alpaca AI example, select **John Doe**. - Under **Product**, select your price. For the Alpaca AI example, select the price under **Alpaca AI**. - _(Optional)_ Modify the subscription details and settings as needed. - Click **Create test subscription**. You can locate your customer ID on the customer details page. To locate your price ID, go to the product details page and click the overflow menu (⋯) under **Pricing**. Select **Copy price ID**. ```dotnet StripeConfiguration.ApiKey = "<>"; var options = new SubscriptionCreateOptions { Customer = "{{CUSTOMER_ID}}", Items = new List { new SubscriptionItemOptions { Price = "{{PRICE_ID}}" }, }, }; var service = new SubscriptionService(); Subscription subscription = service.Create(options); ``` ```go stripe.Key = "<>" params := &stripe.SubscriptionParams{ Customer: stripe.String("{{CUSTOMER_ID}}"), Items: []*stripe.SubscriptionItemsParams{ &stripe.SubscriptionItemsParams{Price: stripe.String("{{PRICE_ID}}")}, }, }; result, err := subscription.New(params); ``` ```java Stripe.apiKey = "<>"; SubscriptionCreateParams params = SubscriptionCreateParams.builder() .setCustomer("{{CUSTOMER_ID}}") .addItem(SubscriptionCreateParams.Item.builder().setPrice("{{PRICE_ID}}").build()) .build(); Subscription subscription = Subscription.create(params); ``` ```node const stripe = require('stripe')('<>'); const subscription = await stripe.subscriptions.create({ customer: '{{CUSTOMER_ID}}', items: [ { price: '{{PRICE_ID}}', }, ], }); ``` ```python import stripe stripe.api_key = "<>" subscription = stripe.Subscription.create( customer="{{CUSTOMER_ID}}", items=[{"price": "{{PRICE_ID}}"}], ) ``` ```php $stripe = new \Stripe\StripeClient('<>'); $subscription = $stripe->subscriptions->create([ 'customer' => '{{CUSTOMER_ID}}', 'items' => [['price' => '{{PRICE_ID}}']], ]); ``` ```ruby Stripe.api_key = '<>' subscription = Stripe::Subscription.create({ customer: '{{CUSTOMER_ID}}', items: [{price: '{{PRICE_ID}}'}], }) ``` ## Send a test meter event Use [Meter Events](https://docs.stripe.com/api/billing/meter-event.md) to [record customer usage](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage.md) for your meter. At the end of the billing period, Stripe bills the reported usage. You can test your usage-based billing by sending a meter event through the Stripe Dashboard or API. When using the API, specify the customer ID and value for the `payload`. After you send meter events, you can view usage details for your meter on the [Meters](https://dashboard.stripe.com/test/meters) page in the Dashboard. 1. On the [Meters](https://dashboard.stripe.com/test/meters) page, select the meter name. For the Alpaca AI example, select **Alpaca AI tokens**. 1. On the meter page, click **Add usage** > **Manually input usage**. 1. On the **Add usage** page, do the following: - Select your customer from the **Customer** dropdown. - For **Value**, enter a sample value. For the Alpaca AI example, enter `3000`. - Click **Submit**. ```dotnet StripeConfiguration.ApiKey = "<>"; var options = new Stripe.Billing.MeterEventCreateOptions { EventName = "alpaca_ai_tokens", Payload = new Dictionary { { "stripe_customer_id", "{{CUSTOMER_ID}}" }, { "value", "25" }, }, }; var service = new Stripe.Billing.MeterEventService(); Stripe.Billing.MeterEvent meterEvent = service.Create(options); ``` ```go stripe.Key = "<>" params := &stripe.BillingMeterEventParams{ EventName: stripe.String("alpaca_ai_tokens"), Payload: map[string]string{"stripe_customer_id": "{{CUSTOMER_ID}}", "value": "25"}, }; result, err := meterevent.New(params); ``` ```java Stripe.apiKey = "<>"; MeterEventCreateParams params = MeterEventCreateParams.builder() .setEventName("alpaca_ai_tokens") .putPayload("stripe_customer_id", "{{CUSTOMER_ID}}") .putPayload("value", "25") .build(); MeterEvent meterEvent = MeterEvent.create(params); ``` ```node const stripe = require('stripe')('<>'); const meterEvent = await stripe.billing.meterEvents.create({ event_name: 'alpaca_ai_tokens', payload: { stripe_customer_id: '{{CUSTOMER_ID}}', value: '25', }, }); ``` ```python import stripe stripe.api_key = "<>" meter_event = stripe.billing.MeterEvent.create( event_name="alpaca_ai_tokens", payload={"stripe_customer_id": "{{CUSTOMER_ID}}", "value": "25"}, ) ``` ```php $stripe = new \Stripe\StripeClient('<>'); $meterEvent = $stripe->billing->meterEvents->create([ 'event_name' => 'alpaca_ai_tokens', 'payload' => [ 'stripe_customer_id' => '{{CUSTOMER_ID}}', 'value' => '25', ], ]); ``` ```ruby Stripe.api_key = '<>' meter_event = Stripe::Billing::MeterEvent.create({ event_name: 'alpaca_ai_tokens', payload: { stripe_customer_id: '{{CUSTOMER_ID}}', value: '25', }, }) ``` ## Create a preview invoice [Create a preview invoice](https://docs.stripe.com/api/invoices/create_preview.md) to see a preview of a customer’s invoice that includes details such as the meter price and usage quantity. 1. On the [Subscriptions](https://dashboard.stripe.com/test/subscriptions) page, select a subscription. For the Alpaca AI example, select the subscription for **John Doe**. 1. On the subscription details page, scroll down to the **Upcoming invoice** section. The preview invoice shows the subscription amount to bill the customer on the specified date. 1. Click **View full invoice** to see complete details for the upcoming invoice, including: - Customer - Billing method - Creation date - Connected subscription - Subscription details (usage quantity and meter price) - Amount due Because Stripe processes meter events asynchronously, upcoming invoices might not immediately reflect recently received meter events. ```dotnet StripeConfiguration.ApiKey = "<>"; var options = new InvoiceCreatePreviewOptions { Subscription = "<>" }; var service = new InvoiceService(); Invoice invoice = service.CreatePreview(options); ``` ```go stripe.Key = "<>" params := &stripe.InvoiceCreatePreviewParams{Subscription: stripe.String("<>")}; result, err := invoice.CreatePreview(params); ``` ```java Stripe.apiKey = "<>"; InvoiceCreatePreviewParams params = InvoiceCreatePreviewParams.builder().setSubscription("<>").build(); Invoice invoice = Invoice.createPreview(params); ``` ```node const stripe = require('stripe')('<>'); const invoice = await stripe.invoices.createPreview({ subscription: '<>', }); ``` ```python import stripe stripe.api_key = "<>" invoice = stripe.Invoice.create_preview(subscription="<>") ``` ```php $stripe = new \Stripe\StripeClient('<>'); $invoice = $stripe->invoices->createPreview(['subscription' => '<>']); ``` ```ruby Stripe.api_key = '<>' invoice = Stripe::Invoice.create_preview({subscription: '<>'}) ``` ## Retrieve usage for a custom time period Use the [Meter Event Summary](https://docs.stripe.com/api/billing/meter-event-summary.md) to retrieve total usage for a custom time period. The meter event summary returns a customer’s aggregated usage for a period, based on the aggregation formula defined by the meter. In the Alpaca AI example, the meter event summary returns the sum of tokens for a specific customer, meter, and time window. Because Stripe processes meter events asynchronously, meter event summaries might not immediately reflect recently received meter events. ```dotnet StripeConfiguration.ApiKey = "<>"; var options = new Stripe.Billing.MeterEventSummaryListOptions { Customer = "{{CUSTOMER_ID}}", StartTime = DateTimeOffset.FromUnixTimeSeconds(1717249380).UtcDateTime, EndTime = DateTimeOffset.FromUnixTimeSeconds(1717249440).UtcDateTime, }; var service = new Stripe.Billing.MeterEventSummaryService(); StripeList meterEventSummaries = service.List( "{{METER_ID}}", options); ``` ```go stripe.Key = "<>" params := &stripe.BillingMeterEventSummaryListParams{ Customer: stripe.String("{{CUSTOMER_ID}}"), StartTime: stripe.Int64(1717249380), EndTime: stripe.Int64(1717249440), ID: stripe.String("{{METER_ID}}"), }; result := metereventsummary.List(params); ``` ```java Stripe.apiKey = "<>"; Meter resource = Meter.retrieve("{{METER_ID}}"); MeterEventSummariesParams params = MeterEventSummariesParams.builder() .setCustomer("{{CUSTOMER_ID}}") .setStartTime(1717249380L) .setEndTime(1717249440L) .build(); MeterEventSummaryCollection meterEventSummaries = resource.eventSummaries(params); ``` ```node const stripe = require('stripe')('<>'); const meterEventSummaries = await stripe.billing.meters.listEventSummaries( '{{METER_ID}}', { customer: '{{CUSTOMER_ID}}', start_time: 1717249380, end_time: 1717249440, } ); ``` ```python import stripe stripe.api_key = "<>" meter_event_summaries = stripe.billing.Meter.list_event_summaries( "{{METER_ID}}", customer="{{CUSTOMER_ID}}", start_time=1717249380, end_time=1717249440, ) ``` ```php $stripe = new \Stripe\StripeClient('<>'); $meterEventSummaries = $stripe->billing->meters->allEventSummaries( '{{METER_ID}}', [ 'customer' => '{{CUSTOMER_ID}}', 'start_time' => 1717249380, 'end_time' => 1717249440, ] ); ``` ```ruby Stripe.api_key = '<>' meter_event_summaries = Stripe::Billing::Meter.list_event_summaries( '{{METER_ID}}', { customer: '{{CUSTOMER_ID}}', start_time: 1717249380, end_time: 1717249440, }, ) ``` ## See Also * [Accept payments with Stripe Checkout](https://docs.stripe.com/payments/checkout.md) * [Set up alerts and thresholds](https://docs.stripe.com/billing/subscriptions/usage-based/monitor.md) * [Set up billing credits](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits/implementation-guide.md)