Chargebee provides an HTTP-based API that follows the essence of REST. The HTTP rules followed allow simple HTTP clients like cURL to be used as well. The history of changes made to the API is tracked in the API Changelog.
The following client libraries provide a wrapper around the raw HTTP-based API:
Let us know at support@chargebee.com if you need any other language bindings.The language bar on top allows you to change the code samples in this documentation to your preferred language. The samples provided are ready-to-test as they are generated using your test site's API key and data.
Checkout our collection of sample applications with tutorials on integrating with Chargebee.
Refer to our documentation for a detailed definition & description of all the components in Chargebee.
This documentation is for version 2 of the Chargebee API. The Product Catalog module of Chargebee API allows you to model your products, services, coupons, and discounts in Chargebee. Under APIv2, the module has undergone a major revision and so it has two versions: Product Catalog 1.0 and 2.0. This documentation is for the latter version. When browsing the documentation for APIv2, ensure that you're viewing it for the Product Catalog version of your Chargebee site.
To know the Product Catalog version of your Chargebee site, follow the steps below:
As we support multiple API versions, we request you to:
master
branch has the API v2 code, and chargebee-v1
branch has the API v1 code.With multiple versions of API being supported, the property API Version has been added to Webhooks, which decides the structure of the event content sent to the webhooks.
Find out the version of the API you are using, with the following indicators:
2.x.x
indicates APIv2 while 1.x.x
indicates APIv1./api/v2
for APIv2 and /api/v1
for APIv1.pip install 'chargebee>=2,<3'or
easy_install --upgrade 'chargebee>=2,<3'
The source code for the client library is available as a public repository at github. The code is provided with MIT license. So in case you need any modifications please feel free to do so. If you think it would be useful for other users please do let us know.
Newer versions of client library are released whenever there are new additions to the API. The version
numbering format is major-version.minor-version(s). All
minor releases are backward compatible. Please check the
change notes
for more details.
The latest version details for API V2 are:
Version: 2.15.0
Released On: 2022-04-25
Chargebee uses HTTP Basic authentication for API calls. The username is your API key while the password is empty. You can obtain your API keys from the admin console.
Note: The API keys are different for your test site and your live site.
Use the Environment class to configure your site and your API key. It is a global configuration and can be setup as part of your server initialization
chargebee.configure("{site_api_key}","{site}")
Need to support multiple sites?
In some cases you may need to support multiple sites from the same server. You could pass on both the site name and the api key at each request level.API keys are unique strings used for both authenticating and identifying an application communicating with Chargebee. This section describes the best practices that developers can follow to secure Chargebee API keys.
GET
requests do not generate any events, you can check API key usage for POST
requests by fetching all events with source
set to api
. Among the events returned, filter the API key name found in the event.user
attribute.
<service name>-<key creation timestamp>
(for example: core_app-09-12-2020
).
Chargebee follows the REST model of exposing resources as urls. For example, subscriptions are exposed as
The Python client library provide a corresponding class representation of the resource. For example, subscriptions are represented by
chargebee.Subscription
All operations specific to that resource are exposed as class methods in the corresponding resource class. The methods accepts the input params as hash. You could also pass the environment configuration specific to that request as an additional parameter.
The response is in JSON format. Currently Chargebee does not support any other response format. The Result class wraps the response sent by the server. It has methods that allow you to fetch the specific resource from the result. The ListResult class is used to wrap list responses.
Note: Sometimes, while working with Chargebee APIs, you may see undocumented attributes returned in the response. Such attributes should be ignored.
import chargebee import json chargebee.configure("{site_api_key}","{site}") result = chargebee.Subscription.create_with_items("__test__8asz8Ru9WhHOJO",{ "subscription_items" : [ { "item_price_id" : "day-pass-USD", "unit_price" : 100 }, { "item_price_id" : "basic-USD", "billing_cycles" : 2, "quantity" : 1 }] }) subscription = result.subscription customer = result.customer card = result.card invoice = result.invoice unbilled_charges = result.unbilled_charges
import chargebee import json chargebee.configure("{site_api_key}","{site}") result = chargebee.Subscription.create_with_items("__test__8asz8Ru9WhHOJO",{ "subscription_items" : [ { "item_price_id" : "day-pass-USD", "unit_price" : 100 }, { "item_price_id" : "basic-USD", "billing_cycles" : 2, "quantity" : 1 }] }) subscription = result.subscription customer = result.customer card = result.card invoice = result.invoice unbilled_charges = result.unbilled_charges
Some of the resources have a corresponding details page in the Chargebee's admin console. In some cases you might want to construct the admin console url for easy access from your app (or from exported xls sheets). As the admin console urls are based on internal ids you need to construct the url in the below given format.
Here is an example of a constructed url for a subscription with id 123xyz
Chargebee supports billing in 100+ currencies.
Take a look at the list of supported currencies here.
When multi-decimal pricing is enabled in Chargebee, you can provide
decimal values for prices and quantities. For
prices, the amount is expressed in the major unit of the currency, which is the unit of the currency as represented
by its ISO 4217
code. For example, $1.6782 should be provided as 1.6782
.
The maximum number of decimal places supported can be configured in the admin console. For zero-decimal currencies, which are currencies that do not have minor units (such as the Japanese Yen or JPY), decimal places are not allowed.
price_in_decimal
has been introduced for price
and
amount_in_decimal
has been introduced for amount
in the API.
quantity_in_decimal
for quantity
and tiers[starting_unit_in_decimal]
for
tiers[starting_unit]
have been introduced.
amount
is always rounded off to two decimal places in the major unit of the currency. The major unit of a currency is that represented by its
ISO 4217 code.
The rounding logic used is ROUND_HALF_EVEN
. For example, if the quantity
is 0.0765 and unit_amount
is $10.674, the line item amount
is (0.0765 x $10.674) = $0.816561 and is rounded off to $0.82.
When multi-decimal
pricing is not enabled for your site, or when you provide input via price parameters that do not have the in_decimal
suffix, the unit used for currency depends on the type of currency:
150
.
15
.
With Multi-currency support, you will be able to process transactions in additional currencies apart from your site's Base currency.
Before enabling Multicurrency support, ensure that the currency_code
input parameter is passed to the following methods, to avoid the cannot be blank error:
Multiple Business Entities is currently in early access. Contact eap@chargebee.com to join the Early Adopter Program and enable this feature.
A Chargebee site can be divided into multiple business entities, each with its own configuration and data. By default, a site has only one business entity. Here are some use cases for which you can create multiple:
Creating multiple business entities lets you keep configuration and data for your business units or brands separate so that you can manage their billing and revenue operations independently.
User docs to learn more about business entities and the configuration options available.
If your site has multiple business entities, you can specify the business entity context for an API call by passing a custom HTTP request header.
The table below explains how Chargebee responds to various API calls depending on whether the business entity ID is specified as part of the API call.
Some of the terminology used here defined in the next section.
Any operation that creates a |
|
|
Create a resource other than
|
|
|
Update/delete a resource |
|
|
List resources |
|
|
Retreive a resource |
|
This section defines some useful terms for describing how business entities work.
Any resource is associated with precisely one business entity, called its linked business entity, or simply, the business entity of the resource.
The default business entity of a site is the business entity that customer
resources are linked to by default. A site always has a default business entity, and it is originally set to the first business entity created for the site. You can contact Support to change the default business entity.
The context of an API operation is the data it has access to. An API operation can only read or write data within its context. By default, an API operation has "site context", which means it has access to the entire site's data. However, when a business entity is specified in an API operation, it has "business entity context", which means that the operation only has access to the data linked to the business entity.
Consider the List customers API. When you call the API without specifying a business entity, its context is that of the site and therefore returns customer resources for the entire site. However, when you specify a business entity, the context is that of the business entity alone, and therefore only the customer resources of the selected business entity are returned.
Let's look at the Create checkout for a new subscription API. Say you're calling this API and providing the customer[id]
parameter. When no business entity is specified, the operation has site context and therefore looks up the ID among all the customer resources in the site. However, when a business entity is provided, the operation has business entity context and looks up the ID only among the customers linked to that business entity.
While creating an API resource other than a customer
, you specify a target resource under which it should be created. For example:
invoice
resource for a one-time charge, you must specify either the customer
or the subscription
resource to which it belongs. The customer
or subscription
resource, in this case, is the target resource of the invoice
.subscription
, the target resource of a subscription
resource is always a customer
resource.quote
resource of type
change_subscription
, the target resource is a subscription
resource.Chargebee supports configuring multiple gateway accounts for a gateway type. For example, you can configure multiple Authorize.net accounts to process different currencies.
The default Gateway account to use for each currency can be configured using Smart Routing. However, you can override the selected gateway for each transaction in Chargebee. To do this pass the gateway_account_id
parameter when calling the following APIs:
Passing gateway
, card[gateway]
, payment_method[gateway]
parameters would result in an error in this case since those parameters only resolve the gateway and not the specific account for that gateway.
Chargebee supports multiple payment methods/sources for a customer. So a customer can have a Card and a Paypal Account linked to them, or they can have multiple cards. Moreover, you can mark one of them as Primary and one as Backup payment source.
The purpose of a Backup payment source is that if a charge made via the Primary payment source fails, then the backup payment source will be automatically used for processing the transaction.
Updating a payment source:
An optional parameter, payment_source_id, is available in the following APIs:
If you want to attach a particular payment source to a specific subscription, then pass the parameter in the following APIs:
Pass this parameter in the following APIs to collect the payment using a specific payment source:
Notes:
Chargebee restricts API requests when you exceed the limits entitled for your plan. The limiting mechanism is employed considering two criteria:
When the upper limit is breached on either of the above criteria, an HTTP 429
error response is returned for subsequent requests. As a result, no more requests are served until the limit resets (in approximately a minute).
If you need a temporary increase in API rate limit, you can contact support to avail it. Further, if you breach the limit frequently, we suggest you move to a higher plan (see table below) to accommodate the volume of requests.
Listed below are the API rate limits for each Chargebee plan:
PLAN | REQUESTS PER MINUTE LIMIT | CONCURRENT REQUESTS LIMIT | ||
Live site | Test site | Live site | Test site | |
Launch | 150 | 150 | Up to 150 simultaneous requests, of which GET requests should not exceed 50 and POST requests should not exceed 100. | Up to 100 simultaneous requests, of which the GET and POST requests must not exceed 50 each. |
Grow | 200 | |||
Scale | 300 | |||
Enterprise | 500 |
HTTP status codes are used to indicate success or failure of an API call. The body of the response contains the details of the error in JSON format. The client library wraps the JSON response in an instance of APIError and throws the exception.
Note: Please use latest client library ( greater than 1.3.5 version) to make use of the upgraded error response. It enables simpler error handling. See the change notes for more details.
Given below is a sample error that is returned for the Create a subscription API call when the plan_id
is invalid. The returned HTTP status code is 404
.
{
"message":"Plan is not present",
"type":"invalid_request"
"api_error_code":"resource_not_found",
"param":"item_id"
}
The standard http status codes used are
2XX
The response code in this range implies the API call has succeeded.3XX
This range is not used currently.4XX
response codes indicate failure due to wrong input (i.e, client) side. As the usable list of http codes in the 4xx range is limited we predominantly use the 400
( BAD REQUEST ) error code for client-side errors. 5XX
response codes indicate API request was valid but failed due to issues on the Chargebee server.payment
, invalid_request
and operation_failed
. The client libraries throw a corresponding exception for easy error handling.
customer_id
is a URL path parameter. If that value is invalid, then an error of type
= resource_not_found
is thrown without the param
attribute.
Note: There may be additional deprecated attributes (like error_code
) which are present to support older versions of the libraries.
The client library throws specific exceptions based on the "type" attribute. You could have common error handling routines based on the exception type. For more specific error handling use the "api_error_code" attribute in the exception.
API calls fail at the first error encountered by Chargebee while validating them. To enhance user experience, we recommend that you validate an API call thoroughly to avoid multiple failed attempts from your users, each time for a different error.
There are cases where you have to depend on Chargebee's validation for handling errors like coupon code validation or VAT validations. In such cases, check the specific param
and api_error_code
combination to show a proper error message to your users.
If you receive an HTTP 429 Too Many Requests
error response to an API call, it means that the API requests for your Chargebee site have exceeded acceptable limits. Chargebee may also send a Retry-After
header indicating the time duration to wait before sending a new request. Follow these best practices:
Retry-After
header, wait for the number of seconds indicated before retrying. See Also: API Rate Limits.
Below is a sample pseudo code for handling errors in 'create subscription' api call. Let's assume that you are getting the card details along with coupon code from the user.
try: # chargebee.Subscription.create code # ... pass except chargebee.PaymentError,ex: # First check for card parameters entered by the user. # We recommend you to validate the input at the client side itself to catch simple mistakes. if "card[number]" == ex.param: # Ask your user to recheck the card number. A better way is to use # Stripe's https://github.com/stripe/jquery.payment for validating it in the client side itself. pass #elif <other card params> == ex.param: # Similarly check for other card parameters entered by the user. # .... else: # Verfication or processing failures. # Provide a standard message to your user to recheck his card details or provide a different card. # Like 'Sorry,there was a problem when processing your card, please check the details and try again'. pass except chargebee.InvalidRequestError,ex: # For coupons you could decide to provide specific messages by using # the 'api_error_code' attribute in the ex. if "coupon" == ex.param: if "resource_not_found" == ex.api_error_code: # Inform user to recheck his coupon code. pass elif "resource_limit_exhausted" == ex.api_error_code: # Inform user that the coupon code has expired. pass elif "invalid_request" == ex.api_error_code: # Inform user that the coupon code is not applicable for his plan(/addons). pass else: # Inform user to recheck his coupon code. pass else: # Since you would have validated all other parameters on your side itself, # this could probably be a bug in your code. Provide a generic message to your users. pass except chargebee.OperationFailedError,ex: # Indicates that the request parameters were right but the request couldn't be completed. # The reasons might be "api_request_limit_exceeded" or could be due to an issue in ChargeBee side. # These should occur very rarely and mostly be of temporary nature. # You could ask your user to retry after some time. pass except chargebee.APIError,ex: # Handle the other ChargeBee API errors. Mostly would be setup related # Errors such as authentication failure. # You could ask users contact your support. pass except (httplib.HTTPException, socket.error) as ex: # Handle IO exceptions such as connection timeout, request timeout etc. # You could give a generic message to the customer retry after some time. pass except Exception, ex: # These are unhandled exceptions (Could be due to a bug in your code or very rarely in client library). # You could ask users contact your support. pass
The following are the list of codes grouped based on type.
Note: 'New' codes might get added (though additions are very rare). If you are handling for specific codes also ensure that there is a default block for handling unknown(/new) error codes.
These errors may occur when trying to store the payment method details(such as card, paypal, ACH etc) or when trying to collect a payment. These errors should be handled and appropriate message should be shown to the user.
These errors are thrown as PaymentError.
The following errors are caused due to invalid request. In most cases the errors should occur only during the development phase. These errors are thrown as InvalidRequestError.
These errors are returned when the request was valid but the requested operation could not be completed. These errors should occur very rarely. You generally need not handle them specifically other than showing a generic error message to your users. These errors are thrown as OperationFailedError.
Most of these errors occur due to improper API environment setup in your server or changes to the site's configuration. These errors are thrown as APIError.
Multiple Business Entities is currently in early access. Contact eap@chargebee.com to join the Early Adopter Program and enable this feature.
If your site has multiple business entities, you can pass the chargebee-business-entity-id: <business-entity-id>
custom HTTP header to specify the business entity for which the operation is to be carried out. Here <business-entity-id>
is the id of a business entity. If not provided, the default business entity for the site is assumed.
The default business entity for the site is the same as the first business entity that was created for the site. Contact Chargebee Support to change the default business entity for your site.
As an alternative to passing the customer header, you may specify the business_entity_id
using a query string parameter. See Create a customer endpoint, for example. Select the option based on your use case:
If both the the header and query string are passed together in an API call, their values must be the same or an error is returned.
business_entity_id
business_entity_id
as input:
business_entity_id
business_entity_id
as one of their attributes:
Passing user details like IP address, email address and Device information from your website to Chargebee is always useful. IP address information is routed to the payment gateway (where it will be validated against active fraud detection filters), used for EU tax validation, referral integration and event reports. Email addresses and Device information, even more ubiquitous, are used for identification. Chargebee supports http headers to send user details.
Use the following headers to send user details across:
result = chargebee.Subscription.create_for_customer(cust_id, {"plan_id" : "basic",}, None, {"chargebee-request-origin-ip" : "192.168.1.2", "chargebee-request-origin-user" => "user@example.com", "chargebee-request-origin-device" => "Android" })
Sometimes you would want to disable emails or webhooks for the events that are generated for a particular api call. Typically you would need this when you are migrating customers from your system to Chargebee via api. One option would be to disable all the emails(/webhooks) for all events during the import process. But then you would still want to send emails for new customers who are signing up.
Chargebee supports custom http headers on each api request that allow you to control the actions that are triggered on the events generated by that particular api call.
result = chargebee.Subscription.create_for_customer(cust_id, {"plan_id" : "basic",}, None, {"chargebee-event-email" : "all-disabled"})
Chargebee sends webhook events from specific IP addresses. If you receive webhooks, you may need to configure your integration to ensure that you only receive such notifications from the IP addresses listed below.
Notifications for Updates
Any changes to our IP addresses are notified via the API Changelog.
Alternatively, if you use a Google account, you can turn on notifications for the Google Sheets version of these lists.
Webhooks for Chargebee sites hosted in the US region originate from the following IP addresses:
3.209.65.25
3.215.11.205
3.228.118.137
3.229.12.56
3.230.149.90
3.231.198.174
3.231.48.173
3.233.249.52
18.210.240.138
18.232.249.243
34.195.242.184
34.206.183.55
35.168.199.245
52.203.173.152
52.205.125.34
52.45.227.101
54.158.181.196
54.163.233.122
54.166.107.32
54.84.202.184
View the above list in Google Sheets
Webhooks for Chargebee sites hosted in the EU region originate from the following IP addresses:
18.159.27.9
18.159.5.237
3.126.22.116
3.124.98.200
18.158.188.144
18.197.55.93
18.158.1.51
18.159.186.201
18.159.83.75
3.121.1.124
52.28.49.9
52.58.215.160
View the above list in Google Sheets
Webhooks for Chargebee sites hosted in the AU region originate from the following IP addresses:
13.54.5.219
54.206.234.245
54.253.21.44
13.237.241.199
13.239.143.164
3.105.186.1
View the above list in Google Sheets
Chargebee gives you the option of creating custom fields to track additional information about Customers and their Subscriptions. You can create custom fields for customers, subscriptions, item families, and items. Once the custom fields are created, they can be added to the hosted checkout pages and invoices. They can be accessed through the web interface and API. More on Custom Fields here.
result = chargebee.Customer.create({ first_name : "john", last_name : "Doe", email : "john@test.com", "cf_gender" : "sample", }) customer = result.customer.__str__() print json.loads(customer)["cf_gender"]
Some resources in Chargebee support an attribute called metadata
or meta_data
that can be used to store additional information for the resource. The data can be stored in JSON format. The following resources support this:
Metadata can be passed in both the "create" as well as "update" operations against the resource.
You can use custom fields instead of metadata to overcome the above limitations.
For purposes such as data warehousing, you may need to sync data periodically from Chargebee. We recommend using the list APIs for the various resources you want to sync. (For example, List customers or List subscriptions.) Use the updated_at
filter and the sort_by
parameter set to updated_at
asc
when calling the API. Given below is a more detailed algorithm:
end_time
= sync start time.updated_at
set to before
end_time
.sort_by
set to updated_at
asc
.next_offset
from the previous API call.resource_version
of received resource is greater than (>) resource_version
of same resource cached or stored on your side, update the resource on your side with the received version. If the condition is not true, then ignore the received resource.last_sync_time
= previously stored end_time
minus 5 minutes. (During the previous sync, updates may have happened concurrently while the resources were being fetched. The negative 5 minutes is to ensure that any such resources missed during the last sync, are fetched this time.)end_time
= current time.updated_at
set to after
last_sync_time
.updated_at
set to before
end_time
.sort_by
param set to updated_at
asc
.offset
set to the value of next_offset
from the previous API call.resource_version
of received resource > resource_version
of same resource cached or stored on your side, update the resource on your side with the received version. If the condition is not true, then ignore the received resource.Note: Only the date part of the specified timestamp input will be considered. So in the above example, even though the specified timestamp value evaluates to 2016-02-22 13:25:30 UTC, the resource created on 2016-02-22 will be returned.
Tutorials and use case guides for developers can be found here.