ChargeBee provides HTTP based API which follows the essence of REST*. The HTTP protocol's rules are followed thereby enabling simple HTTP client tools like "curl" to be used.

The following client libraries provide a "easy to use" wrapper around the raw HTTP based API.

Please do mail us at if you need any other language bindings.

Sample Snippets

The top language bar allows you to see samples in your preferred language.

Want us to generate ready-to-test snippets?

to ChargeBee and open the API docs from there and you'll find ready-to-test sample codes based on your ChargeBee test site's api key and data.
Don't have an account with ChargeBee yet? .

Sample Apps

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.

Installing Python Library

The library can be installed as
pip install --upgrade chargebee
easy_install --upgrade chargebee
To install from source:
python install
Then import as:
import chargebee

Source Code

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.

Library version

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 current version details are:
Version: 1.5.6
Released On: 2015-11-24

ChargeBee uses HTTP BASIC Auth for authenticating the API calls. The user name is your "API key" and the password is empty. The API key could be got from 'Your API Keys' page under integration tab in the web client console.

Note: The API keys are different for your test site and your live site.

Authentication in Python

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


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.

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



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.

Sample Code
result = chargebee.Subscription.create({
    "plan_id" : "basic", 
    "customer" : {
        "email" : "", 
        "first_name" : "John", 
        "last_name" : "Doe", 
        "phone" : "+1-949-999-9999"
    "billing_address" : {
        "first_name" : "John", 
        "last_name" : "Doe", 
        "line1" : "PO Box 9999", 
        "city" : "Walnut", 
        "state" : "California", 
        "zip" : "91789", 
        "country" : "US"
subscription = result.subscription
customer = result.customer
card = result.card
invoice = result.invoice
result = chargebee.Subscription.create({
    "plan_id" : "basic", 
    "customer" : {
        "email" : "", 
        "first_name" : "John", 
        "last_name" : "Doe", 
        "phone" : "+1-949-999-9999"
    "billing_address" : {
        "first_name" : "John", 
        "last_name" : "Doe", 
        "line1" : "PO Box 9999", 
        "city" : "Walnut", 
        "state" : "California", 
        "zip" : "91789", 
        "country" : "US"
subscription = result.subscription
customer = result.customer
card = result.card
invoice = result.invoice

Sample Result [ JSON ]

{ "subscription": { "id": "KyVrKRPHl5UT33q", "plan_id": "basic", "plan_quantity": 1, "status": "in_trial", "trial_start": 1436275944, "trial_end": 1438954344, "created_at": 1436275944, "started_at": 1436275944, "has_scheduled_changes": false, "object": "subscription", "due_invoices_count": 0 }, "customer": { "id": "KyVrKRPHl5UT33q", "first_name": "John", "last_name": "Doe", "email": "", "phone": "+1-949-999-9999", "auto_collection": "on", "created_at": 1436275944, "object": "customer", "billing_address": { "first_name": "John", "last_name": "Doe", "line1": "PO Box 9999", "city": "Walnut", "state_code": "CA", "state": "California", "country": "US", "zip": "91789", "object": "billing_address" }, "card_status": "no_card", "account_credits": 0 } }

Admin Console Details Page

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


  • Accessing the constructed url in a browser will redirect it to the details page.
  • The login page will be shown if the user has not yet logged-in into ChargeBee's admin console.
  • Not all resources will have the corresponding details page. To know if it is supported, please look at the cURL documentation under the retrieve operation for that resource.
  • Do not store the redirected internal id based url as it may change.

HTTP status code is 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.

Sample error response:

Below is the sample error that is returned for 'create subscription' api call when the plan referred in the plan_id parameter is not present. The returned http status code will be 404.

{ "message":"Plan is not present", "type":"invalid_request" "api_error_code":"resource_not_found", "param":"plan_id" }

Http Status Codes

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 bugs on the ChargeBee server side.

Error Attributes

The following attributes are returned as part of the error content. The python library exposes these as attributes in APIError
A descriptive information about the error. This is for developer(/merchant) consumption and should not be used for showing errors to your customers.
An optional attribute which groups errors based on the error handling routine that is required. The types are payment, invalid_request and operation_failed. The client libraries throw a corresponding exception for easy error handling.
A more specific code allowing you to handle the specific errors.
An optional attribute which is filled if the error was due to a specific parameter. The parameter name format that is sent is based on the underlying ChargeBee's REST api format which can be referred in cURL api documentation.
For example, in create subscription for a customer API call if the plan referred in the plan_id parameter is not present in the site, then param value set as plan_id. For 'multivalued' parameters , the index is part of the parameter name. For the same API, if the second addon id is wrongly passed then the param value is set as addons[id][2].
Note: For the same API customer id is part of the url. If the given customer is not present, then resource_not_found error is thrown without the param attribute.

Note: There would be additional deprecated attributes (like error_code) which are present to support older versions of the libraries.

Exception Classes

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.

This is the root exception class for all the api related errors. It contains all the attributes of the error. Error such as authentication failure are thrown as this exception.
Extends: Exception
All payment related errors including payment method detail validation (such as card number validation) and verification.
Extends: APIError
All errors due to invalid request.
Extends: APIError
Thrown if the request parameters were right but the requested operation could not be completed. The reasons might be the api request limit was exceeded or could be due to an issue in ChargeBee side. These should occur very rarely and mostly be of temporary nature.
Extends: APIError

Error handling recommendations

ChargeBee will return the first encountered error when validating the API call. Hence we strongly recommend you to validate the user input on your side before calling ChargeBee's API. Otherwise you will have to show the mistakes one at a time for the user to correct it before proceeding to the next.

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 for the specific param and api_error_code combination to show proper error message to your users.

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.

    # chargebee.Subscription.create code
    # ...
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 for validating it in the client side itself.   

    #elif <other card params> == ex.param:
      # Similarly check for other card parameters entered by the user.
      # ....

      # 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'.
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.
      elif "resource_limit_exhausted" == ex.api_error_code:
        # Inform user that the coupon code has expired.
      elif  "invalid_request" == ex.api_error_code:
        # Inform user that the coupon code is not applicable for his plan(/addons).
        # Inform user to recheck his coupon code.
      # 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.
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.
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.
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.
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.

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.

Returned when the payment collection fails.
HTTP Code: 400, Sample message: Subscription cannot be created as the payment collection failed. Gateway Error: Card declined.
Returned when validation or verification fails for the provided payment method. For example if the payment method is card, this will include all card parameter validation errors and also verification failures from the gateway.
HTTP Code: 400, Sample message: Problem while adding the card. Error message : AVS check failed.
Returned when the request requires payment collection but the 'payment method' details (such as card) is not present for the customer. This error will not occur if auto-collection is disabled for customer.
HTTP Code: 400, Sample message: Card is not present when reactivating the subscription

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.

Returned when any of resource(s) referred in the request is not found.
HTTP Code: 404, Sample message: 82sa2Sqa5 not found
Returned when any limit constraint is violated by the request. For example this error is thrown when the coupon provided has already expired or its maximum redemption count has been reached.
HTTP Code: 400, Sample message: Coupon has expired
Returned when the value does not meet the required specification for the parameter. For example, wrong email format. It is strongly recommended to do the validation at your end before calling ChargeBee's API (other than specific cases like VAT number validation).
HTTP Code: 400, Sample message: invalid email format
Returned when the request provides a duplicate value for an attribute that is specified as unique for that site. For example in 'create subscription api' if you are passing the subscription id then this error will be thrown if a subscription exists in site with the same id.
HTTP Code: 400, Sample message: The value Hy5r4129u is already present.
Returned when the requested operation is not allowed for current state of the resource. This error will occur if the state of the resource has not been checked for the validity of the request. For example this error is returned when we try to schedule subscription changes at 'end of term' for canceled subscriptions.
HTTP Code: 409, Sample message: Only pending invoices can be closed.
Returned when the 'http method', specified in the request, is not allowed for this url. It should not occur if you are using one of the standard client library.
HTTP Code: 405, Sample message: Sorry,the http method GET is not supported for this url.
Returned when the request has incompatible values or does not match the API specification. As it is a generic error, handling this error is recommended only in combination with param attribute.
HTTP Code: 400, Sample message: The plan's billing period and addon's billing period are incompatible.

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.

Returned when the request parameters were right but the operation couldn't be completed due to a bug in ChargeBee side.
HTTP Code: 500, Sample message: Sorry,Something went wrong when trying to process the request.
Returned when temporary occured in Chargebee side. The request can be re-tried, with exponential backoff in case of repeat failures.
HTTP Code: 503, Sample message: Sorry,A temporary error occured when trying to process the request.
Returned when request is blocked for your site. The blocking could be only for a specific set of operation(s) . The reason would be provided as part of the message. You would have to contact support for additional details.
HTTP Code: 403, Sample message: Sorry, The request is blocked
Returned when requests have been blocked temporarily due to request count exceeding acceptable limits.
HTTP Code: 429, Sample message: Sorry, access has been blocked temporarily due to request count exceeding acceptable limits. Please try after some time.

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.

Returned when authentication failed for the request. The possible reasons could be the api key is invalid or authentication header is not present in the request or the header's format is invalid.
HTTP Code: 401, Sample message: Sorry, authentication failed. Invalid API Key.
Returned when the API key does not have sufficient privileges to perform the particular operation.
HTTP Code: 403, Sample message: Sorry, authorization failed. The key does not have the required permissions
Returned when the site is not found.
HTTP Code: 404, Sample message: Sorry, we couldn't find the site acme
Returned when the request is not compatible with the configuration for the site or the configuration is incomplete.
HTTP Code: 400, Sample message: Return url for the hosted page not configured.

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.

  • To skip all actions to be done on the events pass the header chargebee-event-actions with value all-disabled
  • To skip only emails pass the header chargebee-event-email with value all-disabled
  • Similarly to skip only webhooks pass chargebee-event-webhook with value all-disabled
 result = chargebee.Subscription.create_for_customer(cust_id, {"plan_id" : "basic",}, None, 
     {"chargebee-event-email" : "all-disabled"})

Note: Reminder mails (such as card expiry) and other scheduled events cannot be disabled using this option