Send Usage to Chargify

This guide will walk you through how to send usage into Chargify to bill your customers based on usage. When you're finished, you will have an API integration that automatically sends usage into Chargify.

Metered Billing Events-based Billing


Summary - Metered Billing

Chargify Feature
Metered Usage (using metered components)
You Need
Developer experienced with APIs; a web app with Server-side code; the subscription_id is stored in your database
Code
Yes
Difficulty
◉◉

Send usage with metered components

In this example, we'll build an integration that reports usage to Chargify each time a text message is sent. We'll imagine that we are an online service that enables companies to send text messages, and we power those text messages with Twilio. So our integration will be: when a Twilio text message is sent, send usage to Chargify.

 
1. Structure your API call
This is an API call to create usage, using the POST /usages endpoint. You need to know the subscription_id and the metered component_id. This example with use Nodejs, but you'll want to write your API call in your preferred language.

//Nodejs example with Axios Framework
//Copy-paste any code language sample from Chargify API documentation
var axios = require("axios").default;

//Structure the API Call
//Replace SUBDOMAIN, BASE64KEY, and update the memo
var options = {
  method: 'POST',
  url: 'https://SUBDOMAIN.chargify.com/subscriptions/subscription_id/components/component_id/usages.json',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Basic BASE64KEY'
  },
  data: {
    usage: {
      quantity: 1,
      memo: '1 text message'
    }
  }
};

//run the API call and show success or error message
axios.request(options).then(function (response) {
  console.log('success');
}).catch(function (error) {
  console.log(error);
});

 

2. Add the API call to your application code Server-side
Next, you'll need to put the call in the right place inside your code. Since we're sending text messages with Twilio, we need to put the code after the Twilio function.

//Nodejs example with Axios Framework
//Copy-paste any code language sample from Chargify API documentation
var axios = require("axios").default;

//Send a text with Twilio, then report usage to Chargify
client.messages
      .create({
        body: 'Hi Dave, your order is ready for pickup.',
        from: '+15017122661',
        to: '+15558675310'
      })
      .then(message => send_usage(message.sid) );  // on success, we trigger a send_usage function
      .catch(message => console.log('error');  

function send_usage(sid) {
  var options = {
    method: 'POST',
    url: 'https://SUBDOMAIN.chargify.com/subscriptions/subscription_id/components/component_id/usages.json',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Basic BASE64KEY'
    },
    data: {
      usage: {
        quantity: 1,
        memo: '1 text message'
      }
    }
  };

  //run the API call and show success or error message
  axios.request(options).then(function (response) {
    console.log('success, usage sent to Chargify');
  })
.catch(function (error) { console.log("An error occurred:" + error); }); }

 

3. Make the API call dynamic Server-side 
Now that your Chargify API call works in real time, you need to make it dynamic for all subscriptions by replacing a static subscription_id with a dynamic subscription_id. This is typically done by reading the subscription_id from your database, prior to sending the usage.
//Nodejs example with Axios Framework
//Copy-paste any code language sample from Chargify API documentation var axios = require("axios").default;

//Send a text with Twilio, then report usage to Chargify
client.messages .create({ body: 'Hi Dave, your order is ready for pickup.', from: '+15017122661', to: '+15558675310' }) .then(message => send_usage(message.sid) ); // on success, we trigger a send_usage function .catch(message => console.log('error'); function send_usage(sid) {

//read subscription_id from database (abstract, just to illustrate)
SELECT subscription_id FROM users WHERE account_id = 'acct_123456789' LIMIT 1; //based on an account_id you already know

//define subscription_id variable (abstract, just to illustrate)
//var subscription_id = database.users.subscription_id
var options = { method: 'POST', url: 'https://SUBDOMAIN.chargify.com/subscriptions/' + subscription_id + '/components/component_id/usages.json', headers: { 'Content-Type': 'application/json', 'Authorization': 'Basic BASE64KEY' }, data: { usage: { quantity: 1, memo: '1 text message' } } }; //run the API call and show success or error message axios.request(options).then(function (response) { console.log('success, usage sent to Chargify'); })
.catch(function (error) { console.log("An error occurred:" + error); }); }

 

4. Test
Create several subscriptions, each for your real use cases with usage. Test streaming for each subscription, and ensure that after the event occurs in your app, the usage goes to the proper subscription.

 


Summary - Events-based Billing

Chargify Feature
EBB (using Events-based billing components)
You Need
Developer experienced with APIs; a web app with Server-side code
Code
Yes
Difficulty
◉◉

Send usage with EBB

How to send events-based usage to subscriptions.

1. Determine your method 
There are 2 primary methods. With EBB, Real Time is the most common.

Real Time - Best for sending usage after a specific event programmatically occurs in your system. You can add code right after the event occurs. With EBB, this can be for low, medium, and high volume.

Batch - Best for sending usage in batches (eg: every 1 hour, every 1 day). Choose this option if you have an existing cron job that performs a similar task (you can add on to it, or create a new one).

After you've chosen your method, continue to step 2.

2. Configure stream and metric
This should be complete already, based on your Product Catalog setup. If you have not completed this yet, see the guide for Build Your Catalog > Get Started > Configure Events-based Billing.

This step must be completed before continuing to step 3.

3. Write the API call
This step utilizes the events endpoint. Find your specific events API endpoint, by logging into your Chargify Site, go to Events > Streams > click the Stream > click "URL". It will look like this:

getstream.gif

Now you have the API endpoint, such as:
https://events.chargify.com/SUBDOMAIN/events/STREAMHANDLE

and you should also have an example of your real JSON. 
//POST to https://events.chargify.com/SUBDOMAIN/events/STREAMHANDLE
//Notice that you can send your own account_id, assuming you configured ebb to be like this. This means you do not have to store a Chargify-generated ID in your app. As long as your account_id for a user, is the subscription_reference for their Chargify subscription, there is no subscription ID storage required.
//JSON
{ 
  "account_id": "acct_123456" //your own ID, also on the Chargify subscription_reference 
  "clicks": 100,
  "other": "other-thing"
}


Before integrating this into your application, make sure you can get the API call to work, in the coding language you use. Note that there is no API response for this API call (reason: it allows this high volume API endpoint to move faster).

 

4. Add the API call to your application code Server-side
Next, you'll need to put the call in the right place inside your code. Your workflow will look something like this:

Your existing code is in a file
  - event occurs here
  - check if event successful
     - if successful, make Chargify API call


As an abstract code example to illustrate, let's say our online service enables companies to send text messages, and we power those text messages with Twilio. Every time a text is sent, we send usage to Chargify with ebb. 

//Send a text with Twilio, then report usage to Chargify with ebb, nodejs
twilio.messages
      .create({body: 'Hi there', from: '+15017122661', to: '+15558675310'})
      .then(message => 
         var options = {
           method: 'POST',
           url: 'https://events.chargify.com/SUBDOMAIN/events/STREAMHANDLE',
           headers: {
          'Content-Type': 'application/json',
           Authorization: 'Basic validbase64key'
         },
          data: {
            account_id: 'acct_123456',
            body: 'Hi there'
            from: '+15017122661',
            to: '+15558675310',
            count: 1
          }
        };
      );

 

5. Test
Create several subscriptions, each for your real use cases with usage. Test streaming for each subscription, and ensure that after the event occurs in your app, the usage goes to the proper subscription.
Was this article helpful?
0 out of 0 found this helpful