Authentication overview

Chargebee's API uses authentication mechanisms to verify the identity of an application or user attempting to interact with its services. This process is critical for ensuring that only authorized entities can access and modify sensitive subscription, billing, and customer data. Chargebee's authentication strategy is built around API keys, which are unique identifiers used to grant access to specific functionalities within their platform. The system differentiates between two primary types of API keys: Publishable API Keys and Secret API Keys, each designed for different operational contexts and security requirements. Understanding the distinction and proper usage of these keys is fundamental to building secure and functional integrations with Chargebee.

The authentication process typically involves including the appropriate API key in the header of every API request. When a request is made, Chargebee's servers validate the provided key against its internal records. If the key is valid and has the necessary permissions, the request is processed; otherwise, it is rejected, often with an HTTP 401 Unauthorized or 403 Forbidden status code, depending on the specific error. This mechanism helps protect customer data and maintain the integrity of billing operations. For detailed guidance on API interactions, developers can refer to the official Chargebee API reference documentation.

Supported authentication methods

Chargebee primarily supports API Key authentication for programmatic access to its platform. This method is standard for RESTful APIs due to its simplicity and effectiveness in controlling access. While API keys are the main mechanism, Chargebee also integrates with third-party authentication providers for specific use cases, such as Single Sign-On (SSO) for its web application, though direct API access relies on keys.

API Keys

API keys are unique, alphanumeric strings that identify your application and grant it permission to interact with the Chargebee API. Chargebee provides two types of API keys, each with specific roles:

  • Publishable API Keys: These keys are designed for client-side use, typically in web or mobile applications where the key might be exposed to end-users. They have limited permissions, primarily allowing public-facing operations like initiating a checkout process or retrieving public product information without exposing sensitive backend data. Publishable keys are generally considered less sensitive than secret keys but should still be managed carefully.
  • Secret API Keys: These keys are highly sensitive and must be kept confidential. They are intended for server-side use only, where they can be securely stored and are not exposed to end-users. Secret keys grant full access to your Chargebee account's API, allowing operations such as creating subscriptions, processing payments, managing customers, and retrieving sensitive financial data. Exposure of a secret key could lead to unauthorized access and manipulation of your billing system.

The following table summarizes the primary authentication methods and their characteristics:

Method When to Use Security Level
Publishable API Key Client-side operations (e.g., embedded checkout forms, public data retrieval) Moderate (limited permissions, can be exposed)
Secret API Key Server-side integrations (e.g., creating subscriptions, managing customers, processing refunds) High (full API access, must be kept confidential)

Getting your credentials

To obtain your Chargebee API keys, you need access to your Chargebee account's web interface. The process involves navigating to the API Keys section, where you can generate, manage, and revoke your keys. Here's a general outline of the steps:

  1. Log in to your Chargebee account: Access your Chargebee dashboard with administrative privileges.
  2. Navigate to Settings: In the Chargebee dashboard, locate the 'Settings' menu, typically found in the sidebar or top navigation.
  3. Access Configure Chargebee: Under 'Settings', find and click on 'Configure Chargebee'.
  4. Locate API Keys: Within the 'Configure Chargebee' section, look for 'API Keys' or 'API & Webhooks'.
  5. Generate New Keys: You will find options to generate both 'Publishable API Keys' and 'Secret API Keys'. It is recommended to generate a new Secret API Key for each distinct application or service integrating with Chargebee to facilitate better key management and revocation if necessary.
  6. Copy and Store Keys Securely: Once generated, immediately copy the keys. For Secret API Keys, this is particularly important as they are often displayed only once for security reasons. Store these keys in a secure environment, such as environment variables, a secrets manager, or a secure configuration file, away from version control.

Chargebee allows you to manage multiple sets of API keys, which is beneficial for development, staging, and production environments, or for different applications requiring distinct access levels. You can also revoke compromised or deprecated keys from this interface, enhancing security. For precise instructions and visual guides, refer to the Chargebee API Keys documentation.

Authenticated request example

Authenticating requests to the Chargebee API typically involves including your Secret API Key in the HTTP Authorization header using Basic Authentication. This method encodes your API key (and a dummy password) using Base64 and sends it with each request. The following example demonstrates how to make an authenticated request using Python's requests library to retrieve customer details.

First, ensure you have your Secret API Key and your Chargebee site name. The site name is the subdomain of your Chargebee instance (e.g., your-site-name in your-site-name.chargebee.com).


import requests
from requests.auth import HTTPBasicAuth
import os

# --- Configuration ---
# It's best practice to load sensitive information from environment variables
CHARGEBEE_SITE = os.environ.get('CHARGEBEE_SITE', 'your-site-name') # Replace 'your-site-name' with your actual Chargebee site name
CHARGEBEE_SECRET_KEY = os.environ.get('CHARGEBEE_SECRET_KEY', 'sk_test_xxxxxxxxxxxxxxxxxxxxx') # Replace with your actual Secret API Key
CUSTOMER_ID = 'your_customer_id' # Replace with an actual customer ID from your Chargebee account

# --- API Endpoint ---
API_BASE_URL = f"https://{CHARGEBEE_SITE}.chargebee.com/api/v2"
CUSTOMER_ENDPOINT = f"{API_BASE_URL}/customers/{CUSTOMER_ID}"

# --- Make the Request ---
try:
    response = requests.get(
        CUSTOMER_ENDPOINT,
        auth=HTTPBasicAuth(CHARGEBEE_SECRET_KEY, '') # Basic Auth with API Key and empty password
    )
    response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)

    customer_data = response.json()
    print("Successfully retrieved customer data:")
    print(customer_data)

except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
    print(f"Response body: {response.text}")
except requests.exceptions.ConnectionError as conn_err:
    print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
    print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
    print(f"An unexpected error occurred: {req_err}")

In this example:

  • CHARGEBEE_SITE and CHARGEBEE_SECRET_KEY are loaded from environment variables for security. Replace the placeholder values with your actual site name and Secret API Key.
  • HTTPBasicAuth(CHARGEBEE_SECRET_KEY, '') constructs the Basic Authentication header. The first argument is the username (your API key), and the second is an empty string for the password, as Chargebee's Basic Auth implementation only uses the key.
  • The request is made to the /api/v2/customers/{CUSTOMER_ID} endpoint, which requires a valid Secret API Key for access.
  • Error handling is included to catch common issues like network problems or HTTP errors returned by the API.

This pattern of including the Secret API Key in the Authorization header is consistent across different programming languages and HTTP client libraries. Always ensure your Secret API Keys are never hardcoded directly into your source code, especially in production environments.

Security best practices

Securing your Chargebee integrations is paramount to protecting sensitive customer and financial data. Adhering to security best practices helps prevent unauthorized access and maintain compliance. Chargebee itself maintains PCI DSS Level 1 compliance, SOC 2 Type II, and GDPR, but your integration practices are key to end-to-end security.

API Key Management

  • Never expose Secret API Keys: Secret API Keys should only be used on your backend servers and never embedded in client-side code (JavaScript, mobile apps) or publicly accessible repositories.
  • Use environment variables or secrets management: Store API keys in environment variables (e.g., CHARGEBEE_SECRET_KEY) or a dedicated secrets management service (e.g., AWS Secrets Manager, Google Cloud Secret Manager, Azure Key Vault, HashiCorp Vault) rather than hardcoding them.
  • Rotate keys regularly: Periodically rotate your Secret API Keys. This limits the window of exposure if a key is compromised. Chargebee's dashboard allows you to generate new keys and revoke old ones.
  • Use distinct keys for different environments: Have separate API keys for development, staging, and production environments. This ensures that a compromise in one environment does not affect others.
  • Use distinct keys for different applications: If you have multiple applications integrating with Chargebee, assign a unique Secret API Key to each. This enables granular revocation if one application's key is compromised.

Secure Communication

  • Always use HTTPS: Ensure all communications with the Chargebee API occur over HTTPS. This encrypts data in transit, protecting it from eavesdropping and tampering. Most modern HTTP client libraries enforce HTTPS by default.
  • Validate SSL/TLS certificates: Your application should be configured to validate SSL/TLS certificates presented by Chargebee's API endpoints. This prevents man-in-the-middle attacks.

Least Privilege Principle

  • Grant minimum necessary permissions: When available (e.g., if Chargebee introduces more granular API key permissions in the future, or for internal user roles), configure API keys or user roles with the minimum set of permissions required for their intended function. This reduces the blast radius of a compromised key.
  • Use Publishable Keys for client-side: For operations that must happen client-side (e.g., initiating a checkout flow), use Chargebee's Publishable API Keys, which have inherently limited permissions.

Error Handling and Logging

  • Implement robust error handling: Properly handle API errors, especially authentication failures (e.g., 401 Unauthorized, 403 Forbidden). Avoid exposing raw error messages or sensitive information to end-users.
  • Log authentication attempts: Implement logging for API authentication attempts, especially failures. This can help detect and respond to potential brute-force attacks or unauthorized access attempts.

Compliance

  • Adhere to PCI DSS: If your application handles credit card data directly, ensure your environment and practices are PCI DSS compliant. Chargebee handles much of the PCI burden by acting as a Level 1 service provider, but your integration points still require diligence.
  • Comply with data privacy regulations: Ensure your integration complies with relevant data privacy regulations like GDPR, CCPA, and others, especially regarding how you store and process customer data retrieved from Chargebee.

By consistently applying these security best practices, developers can build robust and secure integrations with the Chargebee platform, safeguarding both their systems and their customers' data.