Note
We are trialing a Discord server for developers building with Chargebee. Limited spots are open on a first-come basis. Join here if interested.
This is the official .NET library for integrating with Chargebee.
- 📘 For a complete reference of available APIs, check out our API Documentation.
- 🧪 To explore and test API capabilities interactively, head over to our API Explorer.
The latest version (v3) of the library supports the following:
- .NET Standard 1.2+
- .NET Core 1.0+
- .NET Framework 4.5+
The versioning scheme of this library is inspired by SemVer and the format is v{MAJOR}.{MINOR}.{PATCH}. For example, v3.0.0 and v2.5.1 are valid library versions.
The following table provides some details for each major version:
| Library major version | Status | Compatible API versions | Branch |
|---|---|---|---|
| v3 | Active | v2 and v1 | master |
| v2 | Inactive | v2 and v1 | chargebee-v2 |
| v1 | Inactive | v1 | chargebee-v1 |
A couple of terms used in the above table are explained below:
- Status: The current development status for the library version. An Active major version is currently being maintained and continues to get backward-compatible changes. Inactive versions no longer receive any updates.
- Branch: The branch in this repository containing the source code for the latest release of the library version. Every version of the library has been tagged. You can check out the source code for any version using its tag.
🔴 Attention: The support for v2 will eventually be discontinued on December 31st 2023 and will no longer receive any further updates. We strongly recommend upgrading to v3 as soon as possible. Note: See the changelog for a history of changes.
You can install any release of an active library version using NuGet—a package manager for Visual Studio—by running the following command in the NuGet Package Manager Console:
$ Install-Package ChargeBee -Version {MAJOR}.{MINOR}.{PATCH}For example, the following commands are valid:
- Install the latest version:
$ Install-Package ChargeBee -Version 3.0.0- Install an earlier version, say v2.5.1:
$ Install-Package ChargeBee -Version 2.5.1Some examples for using the library are listed below.
using ChargeBee.Api;
using ChargeBee.Models;
ApiConfig.Configure("site","api_key");
EntityResult result = Subscription.Create()
.PlanId("basic")
.Request();
Subscription subscription = result.Subscription;
Customer customer = result.Customer;Idempotency keys are passed along with request headers to allow a safe retry of POST requests.
using ChargeBee.Api;
using ChargeBee.Models;
ApiConfig.Configure("site","api_key");
EntityResult result = Customer.Create()
.FirstName("John")
.LastName("Doe")
.Email("john@test.com")
.SetIdempotencyKey("<<UUID>>") // Replace <<UUID>> with a unique string
.Request();
Customer customer = result.Customer;
Console.WriteLine(ApiConfig.SerializeObject(customer));
HttpResponseHeaders httpResponseHeaders = result.ResponseHeaders; // Retrieves response headers
Console.WriteLine(httpResponseHeaders);
string idempotencyReplayedValue = result.IsIdempotencyReplayed(); // Retrieves idempotency replayed header value
Console.WriteLine(idempotencyReplayedValue);isIdempotencyReplayed() method can be accessed to differentiate between original and replayed requests.
ApiConfig.SerializeObject(obj);ApiConfig.DeserializeObject<T>(jsonString);Chargebee's SDK includes built-in retry logic to handle temporary network issues and server-side errors. This feature is disabled by default but can be enabled when needed.
- Automatic retries for specific HTTP status codes: Retries are automatically triggered for status codes
500,502,503, and504. - Exponential backoff: Retry delays increase exponentially to prevent overwhelming the server.
- Rate limit management: If a
429 Too Many Requestsresponse is received with aRetry-Afterheader, the SDK waits for the specified duration before retrying.Note: Exponential backoff and max retries do not apply in this case.
- Customizable retry behavior: Retry logic can be configured using the
retryConfigparameter in the environment configuration.
You can enable and configure the retry logic by passing a retryConfig object when initializing the Chargebee environment:
using ChargeBee.Api;
using ChargeBee.Models;
ApiConfig.Configure("site","api_key");
ChargeBee.Api.RetryConfig retryConfig = new ChargeBee.Api.RetryConfig
{
Enabled = true, // Enable retry logic
MaxRetries = 5, // Maximum number of retries
DelayMs = 300, // Initial delay between retries in milliseconds
RetryOnStatus = [500] // HTTP status codes to retry on
};
ApiConfig.UpdateRetryConfig(retryConfig);
EntityResult result = Customer.Create()
.FirstName("John")
.LastName("Doe")
.Email("john@test.com")
.Reqeust();You can enable and configure the retry logic for rate-limit by passing a retryConfig object when initializing the Chargebee environment:
using ChargeBee.Api;
using ChargeBee.Models;
ApiConfig.Configure("site","api_key");
ChargeBee.Api.RetryConfig retryConfig = new ChargeBee.Api.RetryConfig
{
Enabled = true, // Enable retry logic
MaxRetries = 5, // Maximum number of retries
DelayMs = 300, // Initial delay between retries in milliseconds
RetryOnStatus = [429] // HTTP status codes to retry on
};
ApiConfig.UpdateRetryConfig(retryConfig);
EntityResult result = Customer.Create()
.FirstName("John")
.LastName("Doe")
.Email("john@test.com")
.Reqeust();
Optional add-on. Existing integrations do not need any changes — if you never set a telemetry adapter, API calls behave exactly as before.
Set an ITelemetryAdapter when you want Chargebee API calls traced in your observability stack (Datadog, Splunk, Honeycomb, Jaeger, etc.). OpenTelemetry is not bundled with the Chargebee SDK; install and configure OTel (or your APM SDK) in your application and wire it through the adapter.
The SDK builds standardized span attributes (StartAttributes, EndAttributes) following stable OpenTelemetry HTTP semantic conventions (url.full, http.request.method, http.response.status_code, server.address, error.type) plus Chargebee-specific chargebee.* attributes (see TelemetryAttributeKeys).
Span names follow chargebee.{resource}.{operation}. One span is created per SDK API call; retries reuse the same span. Adapter failures are logged and never affect the underlying API request.
Configure at startup (either form works):
Install OTel packages in your app (not included in the Chargebee SDK):
dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocolusing System.Collections.Generic;
using System.Diagnostics;
using ChargeBee.Api;
using ChargeBee.Models;
using ChargeBee.Telemetry;
using OpenTelemetry;
using OpenTelemetry.Context.Propagation;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
const string ActivitySourceName = "chargebee-dotnet";
using var activitySource = new ActivitySource(ActivitySourceName);
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.ConfigureResource(resource => resource.AddService("my-app"))
.AddSource(ActivitySourceName)
.AddOtlpExporter(options =>
{
options.Endpoint = new Uri("http://localhost:4317"); // your OTLP collector
})
.Build();
// Option 1: pass the adapter when configuring the client
ApiConfig.Configure("site", "api_key", new OtelTelemetryAdapter(activitySource));
// Option 2: configure first, then attach an adapter later
// ApiConfig.Configure("site", "api_key");
// ApiConfig.SetTelemetryAdapter(new OtelTelemetryAdapter(activitySource));
EntityResult result = Customer.List().Limit(1).Request();
sealed class OtelTelemetryAdapter : ITelemetryAdapter
{
private readonly ActivitySource _activitySource;
public OtelTelemetryAdapter(ActivitySource activitySource)
{
_activitySource = activitySource;
}
public object OnRequestStart(RequestTelemetryContext context, Dictionary<string, string> requestHeaders)
{
var activity = _activitySource.StartActivity(context.SpanName, ActivityKind.Client);
if (activity == null)
{
return null!;
}
foreach (var kv in context.StartAttributes)
{
activity.SetTag(kv.Key, kv.Value);
}
// requestHeaders is merged into the outbound HTTP request — inject W3C trace context here
Propagators.DefaultTextMapPropagator.Inject(
new PropagationContext(activity.Context, baggage: default),
requestHeaders,
(carrier, key, value) => carrier[key] = value);
return activity;
}
public void OnRequestEnd(object handle, RequestTelemetryResult result)
{
if (handle is not Activity activity)
{
return;
}
foreach (var kv in result.EndAttributes)
{
activity.SetTag(kv.Key, kv.Value);
}
if (result.Error != null)
{
activity.SetStatus(ActivityStatusCode.Error, result.Error.Message);
}
else
{
activity.SetStatus(ActivityStatusCode.Ok);
}
activity.Dispose();
}
}To pass custom chargebee-* headers (promoted to http.request.header.chargebee-* span attributes), chain .Header(...) on the request:
Customer.List()
.Header("chargebee-business-entity-id", "entity-id")
.Request();You may contribute patches to any of the Active versions of this library. To do so, raise a PR against the respective branch.
If you find something amiss, you are welcome to create an issue.
The API documentation for the .NET library can be found in our API reference.
See the LICENSE.