chargebee/chargebee-php 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

chargebee/chargebee-php

Composer 安装命令:

composer require chargebee/chargebee-php

包简介

ChargeBee API client implementation for PHP

README 文档

README

Packagist Packagist Packagist Packagist

Note

Join Discord

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 PHP 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.

Note: Chargebee now supports two API versions - V1 and V2, of which V2 is the latest release and all future developments will happen in V2. This library is for API version V2. If you’re looking for V1, head to chargebee-v1 branch.

Requirements

PHP 8.1 or later

Installation

Composer

Chargebee is available on Packagist and can be installed using Composer

composer require chargebee/chargebee-php

To use the bindings,

require_once('vendor/autoload.php');

Usage

To create a new subscription:

use Chargebee\ChargebeeClient;

$chargebee = new ChargebeeClient(options: [
    "site" => "{your_site}",
    "apiKey" => "{your_apiKey}",
]);

$result = $chargebee->subscription()->createWithItems("customer_id", [
    "subscription_items" => [
        [
            "item_price_id" => "Montly-Item",
            "quantity" => "3",
        ]
    ]
]);
$subscription = $result->subscription;
$customer = $result->customer;

Create an idempotent request

Idempotency keys are passed along with request headers to allow a safe retry of POST requests.

use Chargebee\ChargebeeClient;

$chargebee = new ChargebeeClient(options: [
    "site" => "{your_site}",
    "apiKey" => "{your_apiKey}",
]);
$responseCustomer = $chargebee->customer()->create([
    "first_name" => "John",
    "last_name" => "Doe",
    "email" => "john@test.com",
    "card" => [
        "first_name" => "Joe",
        "last_name" => "Doe",
        "number" => "4012888888881881",
        "expiry_month" => "10",
        "expiry_year" => "29",
        "cvv" => "231"
        ]
    ],
    [
        "chargebee-idempotency-key" => "<<UUID>>" // Replace <<UUID>> with a unique string
    ]
);
$responseHeaders = $responseCustomer->getResponseHeaders(); // Retrieves response headers
print_r($responseHeaders);
$idempotencyReplayedValue = $responseCustomer->isIdempotencyReplayed(); // Retrieves Idempotency replayed header value
print_r($idempotencyReplayedValue);

isIdempotencyReplayed() method can be accessed to differentiate between original and replayed requests.

Retry Handling

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.

Key features include:

  • Automatic retries for specific HTTP status codes: Retries are automatically triggered for status codes 500, 502, 503, and 504.
  • Exponential backoff: Retry delays increase exponentially to prevent overwhelming the server.
  • Rate limit management: If a 429 Too Many Requests response is received with a Retry-After header, 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 retryConfig parameter in the environment configuration.

Example: Customizing Retry Logic

You can enable and configure the retry logic by passing a retryConfig object when initializing the Chargebee environment:

use Chargebee\ChargebeeClient;

// Retry Configurations
$retryConfig = new RetryConfig();
$retryConfig->setEnabled(true); // Enable retry mechanism
$retryConfig->setMaxRetries(5); // Maximum number of retries
$retryConfig->setDelayMs(1000); // Delay in milliseconds before retrying
$retryConfig->setRetryOn([500, 502, 503, 504]); // Retry on these HTTP status codes

$chargebee = new ChargebeeClient(options: [
    "site" => "{your_site}",
    "apiKey" => "{your_apiKey}",
    "retryConfig" => $retryConfig,
]);

// ... your Chargebee API operations below ...

Example: Rate Limit retry logic

You can enable and configure the retry logic for rate-limit by passing a retryConfig object when initializing the Chargebee environment:

use Chargebee\ChargebeeClient;

// Retry Configurations
$retryConfig = new RetryConfig();
$retryConfig->setEnabled(true); // Enable retry mechanism
$retryConfig->setMaxRetries(5); // Maximum number of retries
$retryConfig->setDelayMs(1000); // Delay in milliseconds before retrying
$retryConfig->setRetryOn([429]); // Retry on 429 HTTP status codes

$chargebee = new ChargebeeClient(options: [
    "site" => "{your_site}",
    "apiKey" => "{your_apiKey}",
    "retryConfig" => $retryConfig,
]);

// ... your Chargebee API operations below ...

Telemetry (OpenTelemetry)

Optional. Pass a telemetryAdapter when you want Chargebee API calls traced in your observability stack (Datadog, Splunk, Honeycomb, Jaeger, etc.). OpenTelemetry is not bundled with chargebee/chargebee-php — install and configure it in your app, implement TelemetryAdapter, and wire it on the client.

The SDK builds standardized span attributes (startAttributes, endAttributes) following the stable OpenTelemetry HTTP semantic conventions (url.full, http.request.method, http.response.status_code, server.address, error.type) plus Chargebee-specific chargebee.* attributes — use them as-is so spans render correctly in your APM and stay consistent across SDKs.

Note: url.full intentionally omits the query string (it carries only scheme, host, and path) to avoid leaking potentially sensitive query parameters into traces. This is a deliberate, cross-SDK PII-safety choice.

Spans are named chargebee.{resource}.{operation} (e.g. chargebee.subscription.create).

When no adapter is configured, the SDK skips all telemetry work — zero overhead for existing integrations.

Trace shape

The SDK emits one CLIENT span per API call, covering the full lifecycle. Retries reuse the same span — onRequestStart runs once before the retry loop and onRequestEnd runs once after the final outcome.

inbound request span
└── chargebee.subscription.create   ← parented to caller, propagates to Chargebee
        └── (Chargebee-side spans)

If you separately enable HTTP auto-instrumentation (e.g. an OpenTelemetry PHP agent on Guzzle), it will create an additional transport-level HTTP span as a sibling of the Chargebee span. For the cleanest trace where chargebee.{resource}.{operation} is the single propagating span, leave HTTP auto-instrumentation off for Chargebee calls.

OpenTelemetry setup

OpenTelemetry is not bundled — install it in your app:

composer require open-telemetry/sdk open-telemetry/exporter-otlp

Configure OpenTelemetry at app startup (tracer provider, exporter, propagator), then pass your adapter:

use Chargebee\ChargebeeClient;
use Chargebee\Telemetry\RequestTelemetryContext;
use Chargebee\Telemetry\RequestTelemetryResult;
use Chargebee\Telemetry\TelemetryAdapter;
use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;
use OpenTelemetry\API\Trace\SpanInterface;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\API\Trace\TracerInterface;

class OtelTelemetryAdapter implements TelemetryAdapter
{
    public function __construct(private readonly TracerInterface $tracer) {}

    public function onRequestStart(RequestTelemetryContext $context, array &$requestHeaders): mixed
    {
        $span = $this->tracer
            ->spanBuilder($context->spanName)
            ->setSpanKind(SpanKind::KIND_CLIENT)
            ->setAttributes($context->startAttributes)
            ->startSpan();

        $scope = $span->activate();
        TraceContextPropagator::getInstance()->inject($requestHeaders);
        $scope->detach();

        return $span;
    }

    public function onRequestEnd(mixed $handle, RequestTelemetryResult $result): void
    {
        if (!$handle instanceof SpanInterface) {
            return;
        }

        $span = $handle;
        $span->setAttributes($result->endAttributes);

        if ($result->error !== null) {
            $span->setStatus(StatusCode::STATUS_ERROR, $result->error->message);
        } else {
            $span->setStatus(StatusCode::STATUS_OK);
        }

        $span->end();
    }
}

$tracer = \OpenTelemetry\API\Globals::tracerProvider()->getTracer('your-app');
$chargebee = new ChargebeeClient([
    'site' => '{your_site}',
    'apiKey' => '{your_apiKey}',
    'telemetryAdapter' => new OtelTelemetryAdapter($tracer),
]);

RequestTelemetryResult also exposes durationMs if you want to record request duration on the span (e.g. $span->setAttribute('chargebee.request.duration_ms', $result->durationMs)).

To add custom span attributes (tenant ID, correlation ID, etc.), set them in your adapter's onRequestStart / onRequestEnd — use your own namespace (e.g. app.tenant_id), not chargebee.*.

Spans are exported by your own OpenTelemetry setup, so they flow to whatever backend you've configured. The Chargebee config above stays the same regardless of backend.

License

See the LICENSE file.

chargebee/chargebee-php 适用场景与选型建议

chargebee/chargebee-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.51M 次下载、GitHub Stars 达 75, 最近一次更新时间为 2013 年 06 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「payments」 「chargebee」 「subscription billing」 「recurring billing」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 chargebee/chargebee-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 chargebee/chargebee-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 chargebee/chargebee-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 8.51M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 77
  • 点击次数: 33
  • 依赖项目数: 12
  • 推荐数: 2

GitHub 信息

  • Stars: 75
  • Watchers: 37
  • Forks: 67
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2013-06-20