Metered billing using Webhooks with the Invoice API

Watch Video

Metered billing in Chargebee can be used if you need to bill the same customer varying amounts for every billing period based on usage. See the docs  for more details.

Overview 

How does it work?

If metered billing is enabled Chargebee will create an event invoice_created (see Event types ) when one of these 2 conditions occur:

  • Subscription Renewal.
  • Plan changes (upgrade/downgrade or quantity changes) in the subscription.

You will receive generated invoices via webhooks in your webhook handler, and after receiving the invoice, you can use the ID of the invoice resource to add the usage charges to the invoice received.

Note

For the first invoice for a subscription, the invoice will not be moved to pending state but rather it will be collected immediately. For example, the invoice created during signup or during activation (incase of trial) will be collected immediately.

What are Webhooks?

Webhooks are a great way of being notified of changes that occur within your billing system. Once configured, Chargebee will notify your service whenever a event occurs. View the documentation   for further details.

Prerequisites 

To try out the tutorial yourself, you'll need the following:

Setup the Chargebee client library 

You have to download and import  the client library of our choice. Then, configure the client library with your test site and its api key.

For the tutorial, we have configured the site and the credentials in a separate properties file. When the webapp is initialized, the client library gets configured.

For the tutorial, we have configured the site credentials in config/environments/development.rb

We setup the client library in config/initializers/chargebee.rb

For the tutorial, we have configured the site credentials in Config.php

Enable metered billing 

To enable metered billing, login to the admin console, go to Settings > Site Info, enable "Notify for Pending Invoices" and click on "Update Site Info". Once this is done, you are all set.

Listening to events 

Chargebee calls the configured webhook url with the event details sent as json in the request body.
First we need to parse it to obtain the event.

Then we check if the event is of type invoice_created.

Adding usage charges 

We get the details from the invoice received from webhook.

We then add a unmodeled charge to the invoice for the time period via add charge to pending invoice api 

We also add a addon based charge using add addon to pending invoice api 

Once done we invoke the close pending invoice  api.

Note: Securing the webhook url 

The webhook url needs to be secured either using Basic Authentication or via a secret parameter.